mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-12-02 05:23:43 +08:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a6e313bb9a | |||
| cb95d65923 | |||
| 2bdcb77ed2 | |||
| 5f86bd34dc | |||
| e675689ded | |||
| 4f8d054cf3 | |||
| 1c9fa16a9a | |||
| 0c8e4665a1 | |||
| 59ac80f0d9 | |||
| 87167d7403 | |||
| 8004e0305e | |||
| 3343e9fde8 | |||
| 9b514ae0a7 | |||
| 7d93cd16cd | |||
| cb6b5d6913 | |||
| 3c4f6b5e0e | |||
| 3fb02ca1f6 | |||
| 1f15111e33 | |||
| 368ea8c3d9 | |||
| 202ee8d64e | |||
| 4023e5d616 | |||
| 035f5ce655 | |||
| ec2edb34f7 | |||
| 74f99e04e4 | |||
| 85c794547a | |||
| 9caada9700 | |||
| f733eba7f6 | |||
| 2b203a5237 | |||
| efe7b30b4c | |||
| 74c14722be | |||
| edaf055284 | |||
| 1527c52bf1 | |||
| c78f4c4549 |
@@ -2,6 +2,5 @@ Wen
|
||||
REGIST
|
||||
PullRequest
|
||||
cancelled
|
||||
indeces
|
||||
FOF
|
||||
NoO
|
||||
|
||||
@@ -34,11 +34,6 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: 'qcom'
|
||||
on_device:
|
||||
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
hf_repo:
|
||||
description: 'Hugging Face dataset repository (e.g. sunnypilot/sunnypilot_models_v1)'
|
||||
required: false
|
||||
@@ -112,11 +107,6 @@ on:
|
||||
options:
|
||||
- qcom
|
||||
- chestnut
|
||||
on_device:
|
||||
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
hf_repo:
|
||||
description: 'Hugging Face dataset repository'
|
||||
required: false
|
||||
@@ -140,7 +130,6 @@ jobs:
|
||||
is_20hz: ${{ inputs.is_20hz }}
|
||||
artifact_suffix: ${{ inputs.artifact_suffix }}
|
||||
target_hardware: ${{ inputs.target_hardware }}
|
||||
on_device: ${{ inputs.on_device || false }}
|
||||
secrets: inherit
|
||||
|
||||
publish_model:
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
name: Chestnut mock build parity
|
||||
description: >-
|
||||
Convert one commaai precompiled chestnut model (LS2) on this runner under tinygrad's amd mock, as a hosted chestnut build does, and require the
|
||||
exact bytes the chestnut runner built (the published artifact). Needs setup-amd-mock, numpy and zstandard; tinygrad_repo checked out.
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Key this check by everything its result depends on
|
||||
id: key
|
||||
shell: bash
|
||||
env:
|
||||
SOURCES: ${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**', 'openpilot/sunnypilot/modeld_v2/*.py', '.github/workflows/chestnut-build-parity/action.yml') }}
|
||||
run: echo "key=chestnut-build-parity-$SOURCES-$(sha256sum "$LLVM_PATH" | cut -c1-16)-$(python3 -c 'import platform; print(platform.python_version())')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Passed before with all of it identical?
|
||||
id: passed
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: ~/.chestnut_build_parity.passed
|
||||
key: ${{ steps.key.outputs.key }}
|
||||
|
||||
- name: Rebuild LS2 on the mock and require the chestnut runner's artifact byte for byte
|
||||
if: steps.passed.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
REF: b92fc4828664f8767bce5e92f1630ed319cbe509 # commaai/openpilot: precompiled big_driving_tinygrad.pkl, pins tinygrad ec91b74b5b
|
||||
PKL_OID: b4dead3ee091d66ab002a6b8e716c26f4f79e3c931e4be5f48e017ba92f6e960
|
||||
PKL_SIZE: "767228907"
|
||||
TG_SHA: ec91b74b5b6b0fc924b72d3f27689679ca2438b9
|
||||
WANT: 680a8d629785f2b1d1a2b0e40d0dfbcd0f7291c21e20c51259f1d768a22ec217 # driving_light_speed_2_november_04_2026_tinygrad.pkl, recompiled46
|
||||
run: |
|
||||
set -euo pipefail
|
||||
work="$RUNNER_TEMP/chestnut_parity" && rm -rf "$work" && mkdir -p "$work"
|
||||
href=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" \
|
||||
https://huggingface.co/commaai/openpilot-lfs.git/info/lfs/objects/batch \
|
||||
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$PKL_OID\",\"size\":$PKL_SIZE}]}" | jq -r '.objects[0].actions.download.href')
|
||||
curl -fsSL --retry 3 -o "$work/big_driving_tinygrad.pkl" "$href"
|
||||
echo "$PKL_OID $work/big_driving_tinygrad.pkl" | sha256sum -c -
|
||||
tg="$work/tinygrad" && git init -q "$tg" && git -C "$tg" fetch -q --depth 1 https://github.com/tinygrad/tinygrad "$TG_SHA" && git -C "$tg" checkout -q FETCH_HEAD
|
||||
CHECK_OOB=0 GMMU=0 PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 tinygrad_repo/test/mockgpu/usb_server.py \
|
||||
env DEV=USB+AMD PYTHONPATH="$tg:$GITHUB_WORKSPACE" python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py "$work/big_driving_tinygrad.pkl" "$work/LS2.pkl"
|
||||
got=$(sha256sum "$work/LS2.pkl" | cut -d' ' -f1)
|
||||
if [ "$got" != "$WANT" ]; then
|
||||
echo "::error::the mock's LS2 build ($got) is not the chestnut runner's ($WANT): this runner's LLVM or the mock no longer builds what the chestnut does"
|
||||
exit 1
|
||||
fi
|
||||
echo "LS2 rebuilt on the mock: byte-identical to the chestnut runner's build"
|
||||
touch ~/.chestnut_build_parity.passed
|
||||
|
||||
- name: Remember the pass
|
||||
if: steps.passed.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: ~/.chestnut_build_parity.passed
|
||||
key: ${{ steps.key.outputs.key }}
|
||||
|
||||
- name: Already passed
|
||||
if: steps.passed.outputs.cache-hit == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "LS2 rebuild skipped: it already matched the chestnut runner's build with this exact mock, converter, LLVM and python"
|
||||
@@ -1,60 +0,0 @@
|
||||
name: Set up tinygrad's amd mock
|
||||
description: LLVM 20 and ROCm comgr, as tinygrad_repo/.github/actions/setup-tinygrad installs them for the mock gpu
|
||||
inputs:
|
||||
emu_cache:
|
||||
description: >-
|
||||
Keep tinygrad's cache db (the emulator's compiled kernels and gate results) between runs under this name, e.g. the model's file name.
|
||||
Empty: no cache.
|
||||
default: ''
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install LLVM 20 and ROCm comgr
|
||||
shell: bash
|
||||
run: |
|
||||
. /etc/os-release
|
||||
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
|
||||
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
|
||||
sudo mkdir -p /etc/apt/keyrings
|
||||
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
|
||||
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
|
||||
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
|
||||
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
|
||||
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
|
||||
llvm=$(ls /usr/lib/llvm-20/lib/libLLVM*.so* /usr/lib/*-linux-gnu/libLLVM-20.so* 2>/dev/null | head -1 || true)
|
||||
[ -n "$llvm" ] || { echo "::error::libLLVM 20 not found"; exit 1; }
|
||||
echo "LLVM_PATH=$llvm" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache the chestnut's firmware
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/tinygrad/downloads/fw
|
||||
key: chestnut-fw-${{ hashFiles('tinygrad_repo/tinygrad/runtime/autogen/am/fw.py') }}
|
||||
|
||||
- name: Fetch the chestnut's firmware (gitlab times out now and then; the mock boots from it)
|
||||
shell: bash
|
||||
run: |
|
||||
for i in 1 2 3 4 5; do
|
||||
PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "
|
||||
from tinygrad.helpers import fetch_fw
|
||||
from tinygrad.runtime.autogen.am import fw
|
||||
for n, h in fw.hashes.items():
|
||||
if n.startswith(('psp_14_0_2_', 'smu_14_0_2.', 'sdma_7_0_0.', 'gc_12_0_0_')): fetch_fw('amdgpu', n, h)" && exit 0
|
||||
sleep $((i * 10))
|
||||
done
|
||||
echo "::error::could not fetch the chestnut's firmware from gitlab"; exit 1
|
||||
|
||||
- name: runner cpu
|
||||
if: inputs.emu_cache != ''
|
||||
id: cpu
|
||||
shell: bash
|
||||
run: echo "cpu=$( (grep -m1 '^model name' /proc/cpuinfo; grep -m1 '^flags' /proc/cpuinfo) | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Keep the emulator's compiled kernels between runs
|
||||
if: inputs.emu_cache != ''
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/tinygrad/cache.db
|
||||
key: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-${{ inputs.emu_cache }}
|
||||
restore-keys: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-
|
||||
@@ -35,11 +35,6 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: 'qcom'
|
||||
on_device:
|
||||
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upstream_branch:
|
||||
@@ -64,11 +59,6 @@ on:
|
||||
- qcom
|
||||
- chestnut
|
||||
default: 'qcom'
|
||||
on_device:
|
||||
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
|
||||
run-name: Build model [${{ inputs.custom_name || inputs.upstream_branch }}] from ref [${{ inputs.upstream_branch }}]
|
||||
@@ -121,12 +111,7 @@ jobs:
|
||||
grep -qs "^version https://git-lfs" "$f" || continue
|
||||
OID=$(awk -F'sha256:' '/^oid/{print $2}' "$f"); SIZE=$(awk '/^size/{print $2}' "$f")
|
||||
HREF=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" "$LFS_URL/objects/batch" \
|
||||
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href // empty')
|
||||
if [ -z "$HREF" ]; then
|
||||
HF_PATH=$(curl -fsSL --retry 3 "https://huggingface.co/api/models/commaai/openpilot_driving_models/tree/main?recursive=true" | jq -r --arg oid "$OID" 'map(select(.lfs.oid == $oid))[0].path // empty')
|
||||
[ -n "$HF_PATH" ] || { echo "::error::$f ($OID) is in neither openpilot's LFS nor commaai/openpilot_driving_models"; exit 1; }
|
||||
HREF="https://huggingface.co/commaai/openpilot_driving_models/resolve/main/$HF_PATH"
|
||||
fi
|
||||
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href')
|
||||
aria2c -x 16 -s 16 -k 16M --max-tries=5 --retry-wait=5 --file-allocation=none --summary-interval=30 --allow-overwrite=true \
|
||||
-d "$(dirname "$f")" -o "$(basename "$f")" "$HREF"
|
||||
echo "$OID $f" | sha256sum -c -
|
||||
@@ -134,9 +119,8 @@ jobs:
|
||||
}
|
||||
UPSTREAM_PKL=selfdrive/modeld/models/big_driving_tinygrad.pkl
|
||||
if [ "${{ inputs.target_hardware }}" != "chestnut" ]; then
|
||||
git lfs pull -X "**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl" || true
|
||||
git lfs pull -X "**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl"
|
||||
rm -f selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/dmonitoring_*.onnx selfdrive/modeld/models/big_*.pkl selfdrive/modeld/models/dmonitoring_*.pkl
|
||||
fetch_lfs selfdrive/modeld/models/*.onnx
|
||||
elif compgen -G "selfdrive/modeld/models/big_*.onnx" > /dev/null; then
|
||||
fetch_lfs selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/big_*.pkl
|
||||
find selfdrive/modeld/models -type f \( -name "*.onnx" -o -name "*.pkl" \) ! -name "big_*.onnx" ! -name "big_*.pkl" -delete
|
||||
@@ -169,67 +153,18 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
build_model:
|
||||
runs-on: ${{ inputs.on_device && fromJSON(inputs.target_hardware == 'chestnut' && '["self-hosted","chestnut"]' || '["self-hosted","tici"]') || 'ubuntu-24.04' }}
|
||||
runs-on: [self-hosted, "${{ inputs.target_hardware == 'chestnut' && 'chestnut' || 'tici' }}"]
|
||||
needs: get_model
|
||||
env:
|
||||
MODEL_NAME: ${{ inputs.custom_name || inputs.upstream_branch }} (${{ needs.get_model.outputs.model_date }})
|
||||
REF: ${{ inputs.upstream_branch }}
|
||||
MOCK_BUILD: ${{ !inputs.on_device }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up the hosted mock build
|
||||
if: env.MOCK_BUILD == 'true'
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut'
|
||||
uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: build
|
||||
|
||||
- name: Install the amd mock build dependencies
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut'
|
||||
run: |
|
||||
python3 -m pip install -q numpy zstandard
|
||||
|
||||
- name: Install the qcom mock build dependencies
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut'
|
||||
id: qcom_deps
|
||||
run: |
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2
|
||||
python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2
|
||||
echo "qemu=$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Compiler check passed before with all of it identical?
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut'
|
||||
id: qcom_compiler
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: ~/.qcom_compiler_parity.passed
|
||||
key: qcom-compiler-parity-${{ steps.qcom_deps.outputs.qemu }}-${{ hashFiles('tinygrad_repo/test/device/qcom/compiler_parity.py', 'tinygrad_repo/test/mockgpu/qcom/a630_compiled.pkl.xz', 'tinygrad_repo/tinygrad/runtime/support/compiler_qcom.py') }}
|
||||
|
||||
- name: Check the off-device qcom compiler builds the a630's bytes
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
# every kernel an a630 has compiled must compile to the same bytes here before a model is built here
|
||||
PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/device/qcom/compiler_parity.py" check "$TINYGRAD_PATH/test/mockgpu/qcom/a630_compiled.pkl.xz"
|
||||
touch ~/.qcom_compiler_parity.passed
|
||||
|
||||
- name: Remember the compiler check passed
|
||||
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: ~/.qcom_compiler_parity.passed
|
||||
key: ${{ steps.qcom_compiler.outputs.cache-primary-key }}
|
||||
|
||||
- name: Set environment variables
|
||||
if: env.MOCK_BUILD != 'true'
|
||||
id: set-env
|
||||
run: |
|
||||
# Set up common environment
|
||||
@@ -242,7 +177,6 @@ jobs:
|
||||
printenv >> $GITHUB_ENV
|
||||
|
||||
- name: Setup build environment
|
||||
if: env.MOCK_BUILD != 'true'
|
||||
run: |
|
||||
mkdir -p "${BUILD_DIR}/"
|
||||
sudo find $BUILD_DIR/ -mindepth 1 -delete
|
||||
@@ -264,28 +198,21 @@ jobs:
|
||||
|
||||
- name: Build Model
|
||||
run: |
|
||||
if [ "$MOCK_BUILD" = "true" ]; then
|
||||
TASKSET=""
|
||||
export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock
|
||||
else
|
||||
source /etc/profile
|
||||
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
|
||||
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
TASKSET="taskset -c 7"
|
||||
fi
|
||||
source /etc/profile
|
||||
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
|
||||
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}:${{ github.workspace }}"
|
||||
|
||||
COMPILE_MODELD="${{ github.workspace }}/openpilot/sunnypilot/modeld_v2/compile_modeld.py"
|
||||
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
|
||||
CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')")
|
||||
|
||||
MOCK=$([ "$MOCK_BUILD" = "true" ] && echo MOCK || true)
|
||||
TG_FLAGS_QCOM="DEV=${MOCK:+MOCK+}QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
|
||||
TG_FLAGS_QCOM="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
|
||||
if [ "${{ inputs.target_hardware }}" == "chestnut" ]; then
|
||||
echo "CHESTNUT build"
|
||||
export CHESTNUT=1
|
||||
TG_FLAGS="DEBUG=1 DEV=${MOCK}USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
|
||||
TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
|
||||
OUTPUT_PKL="${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl"
|
||||
else
|
||||
echo "QCOM build"
|
||||
@@ -300,16 +227,14 @@ jobs:
|
||||
echo "Converting commaai's precompiled model with tinygrad $TG_SHA"
|
||||
UPSTREAM_TG="${{ runner.temp }}/upstream_tinygrad"
|
||||
rm -rf "$UPSTREAM_TG" && git init -q "$UPSTREAM_TG" && git -C "$UPSTREAM_TG" fetch -q --depth 1 "$TG_URL" "$TG_SHA" && git -C "$UPSTREAM_TG" checkout -q FETCH_HEAD
|
||||
ON_MOCK=""
|
||||
if [ "$MOCK_BUILD" = "true" ]; then ON_MOCK="env PYTHONPATH=$TINYGRAD_PATH python3 $TINYGRAD_PATH/test/mockgpu/usb_server.py"; fi
|
||||
CONVERTED="${{ runner.temp }}/big_driving_tinygrad_plain.pkl"
|
||||
$ON_MOCK env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" $TASKSET python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
|
||||
env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
|
||||
"${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl" "$CONVERTED"
|
||||
mv "$CONVERTED" "$OUTPUT_PKL"
|
||||
elif NEW_ARCH_ONNX=$(find "${{ env.MODELS_DIR }}" -maxdepth 1 -name "${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}*driving*.onnx" -print -quit) &&
|
||||
[ -n "$NEW_ARCH_ONNX" ] && grep -qa new_img "$NEW_ARCH_ONNX"; then # the new architecture: one ONNX taking the warped frames as new_img
|
||||
echo "Compiling new architecture ONNX: $NEW_ARCH_ONNX"
|
||||
env ${TG_FLAGS} $TASKSET python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
|
||||
env ${TG_FLAGS} taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
|
||||
"$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 1
|
||||
else
|
||||
echo "Detected onnx architecture. Routing to native compile_modeld.py."
|
||||
@@ -359,7 +284,7 @@ jobs:
|
||||
|
||||
if [ -n "$MODEL_TYPE" ]; then
|
||||
echo "Detected: $MODEL_TYPE -> $OUTPUT_PKL"
|
||||
env ${TG_FLAGS} $TASKSET python3 "$COMPILE_MODELD" \
|
||||
env ${TG_FLAGS} taskset -c 7 python3 "$COMPILE_MODELD" \
|
||||
--model-type $MODEL_TYPE \
|
||||
--model-size $MODEL_SIZE \
|
||||
--camera-resolutions $CAMERA_RES \
|
||||
@@ -368,13 +293,6 @@ jobs:
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Replay its check frame on the mock and require the result bit for bit
|
||||
if: env.MOCK_BUILD == 'true'
|
||||
env:
|
||||
DEV: ${{ inputs.target_hardware == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }}
|
||||
PYTHONPATH: ${{ env.TINYGRAD_PATH }}:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "${{ env.MODELS_DIR }}/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl"
|
||||
|
||||
- name: Prepare Output
|
||||
run: |
|
||||
sudo rm -rf ${{ env.OUTPUT_DIR }}
|
||||
@@ -386,7 +304,7 @@ jobs:
|
||||
--include='/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl' \
|
||||
--exclude='*' \
|
||||
--delete-excluded \
|
||||
$([ "$MOCK_BUILD" = "true" ] || echo --chown=comma:comma) \
|
||||
--chown=comma:comma \
|
||||
${{ env.MODELS_DIR }}/ ${{ env.OUTPUT_DIR }}/
|
||||
|
||||
python3 "${{ github.workspace }}/release/ci/model_generator.py" \
|
||||
@@ -415,7 +333,7 @@ jobs:
|
||||
path: ${{ env.OUTPUT_DIR }}/artifact_name.txt
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always() && env.MOCK_BUILD != 'true'
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
|
||||
@@ -28,7 +28,18 @@ jobs:
|
||||
env:
|
||||
DEV: CPU
|
||||
run: tools/op.sh test -v openpilot/sunnypilot/modeld_v2/tests/test_plain_artifact.py
|
||||
- uses: ./.github/workflows/setup-amd-mock
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock, as tinygrad_repo/.github/actions/setup-tinygrad does
|
||||
run: |
|
||||
. /etc/os-release
|
||||
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
|
||||
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
|
||||
sudo mkdir -p /etc/apt/keyrings
|
||||
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
|
||||
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
|
||||
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
|
||||
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
|
||||
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
|
||||
- name: Convert a pickled USB+AMD jit and replay it under tinygrad's amd mock
|
||||
env:
|
||||
DEV: MOCKUSB+AMD
|
||||
@@ -69,8 +80,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
models: ${{ steps.set-matrix.outputs.models }}
|
||||
chestnut: ${{ steps.set-matrix.outputs.chestnut }}
|
||||
qcom: ${{ steps.set-matrix.outputs.qcom }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Fetch and Parse json
|
||||
@@ -82,22 +91,16 @@ jobs:
|
||||
with open("openpilot/sunnypilot/models/fetcher.py", "r") as f:
|
||||
urls = re.findall(r"MODEL_URL(?:_CHESTNUT)?\s*=\s*[\"'"'"']([^\"'"'"']+)[\"'"'"']", f.read())
|
||||
|
||||
artifacts, chestnut, qcom = [], [], []
|
||||
artifacts = []
|
||||
for url in urls:
|
||||
data = json.loads(urllib.request.urlopen(url).read())
|
||||
for bundle in data.get("bundles", []):
|
||||
for model in bundle.get("models", []):
|
||||
if "artifact" in model:
|
||||
artifacts.append(model["artifact"])
|
||||
if "chestnut" in url:
|
||||
chestnut.append(model["artifact"])
|
||||
elif "tinygrad" in model["artifact"]["file_name"]:
|
||||
qcom.append(model["artifact"])
|
||||
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
f.write(f"models={json.dumps(artifacts)}\n")
|
||||
f.write(f"chestnut={json.dumps(chestnut)}\n")
|
||||
f.write(f"qcom={json.dumps(qcom)}\n")
|
||||
'
|
||||
|
||||
test-model:
|
||||
@@ -134,81 +137,3 @@ jobs:
|
||||
export PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo:$GITHUB_WORKSPACE:$PYTHONPATH"
|
||||
python3 -m pip uninstall -y tinygrad || uv pip uninstall -y tinygrad --system || true
|
||||
python3 -m pytest openpilot/sunnypilot/modeld_v2/tests/test_models.py
|
||||
|
||||
chestnut-mock-parity:
|
||||
name: Mock parity ${{ matrix.artifact.file_name }}
|
||||
needs: generate-matrix
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
artifact: ${{ fromJson(needs.generate-matrix.outputs.chestnut) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: ${{ matrix.artifact.file_name }}
|
||||
- run: python3 -m pip install -q numpy
|
||||
- name: Download model
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
|
||||
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
|
||||
shell: bash
|
||||
run: |
|
||||
AUTH=()
|
||||
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
|
||||
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
|
||||
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
|
||||
- name: Replay its check frame on the amd mock and require the chestnut's result bit for bit
|
||||
env:
|
||||
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
|
||||
|
||||
qcom-mock-parity:
|
||||
name: QCOM mock parity ${{ matrix.artifact.file_name }}
|
||||
needs: generate-matrix
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
artifact: ${{ fromJson(needs.generate-matrix.outputs.qcom) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: python3 -m pip install -q numpy tinymesa==25.2.7.2
|
||||
- name: Download model
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
|
||||
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
|
||||
shell: bash
|
||||
run: |
|
||||
AUTH=()
|
||||
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
|
||||
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
|
||||
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
|
||||
- name: Replay its check frame on the qcom mock and require the comma device's result bit for bit
|
||||
env:
|
||||
DEV: MOCK+QCOM
|
||||
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
|
||||
|
||||
chestnut-mock-build-parity:
|
||||
name: Chestnut build on the amd mock = chestnut runner build
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: chestnut-build-parity
|
||||
- run: python3 -m pip install -q numpy zstandard
|
||||
- uses: ./.github/workflows/chestnut-build-parity
|
||||
|
||||
@@ -149,7 +149,6 @@ jobs:
|
||||
|
||||
process_replay:
|
||||
name: process replay
|
||||
if: false #process replay disabled for angle steering until we are ready to merge it
|
||||
runs-on: ${{
|
||||
(github.repository == 'commaai/openpilot') &&
|
||||
((github.event_name != 'pull_request') ||
|
||||
|
||||
Generated
-7
@@ -21,12 +21,5 @@
|
||||
</clean>
|
||||
</configuration>
|
||||
</target>
|
||||
<target id="f2590b2b-9b93-49f9-8510-da3f3724a2ae" name="replay" defaultType="TOOL">
|
||||
<configuration id="d475264f-6f4c-4092-9b4e-6773309f38b7" name="replay" toolchainName="Default">
|
||||
<build type="TOOL">
|
||||
<tool actionId="Tool_External Tools_uv build tools replay" />
|
||||
</build>
|
||||
</configuration>
|
||||
</target>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-7
@@ -20,11 +20,4 @@
|
||||
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
|
||||
</exec>
|
||||
</tool>
|
||||
<tool name="uv build tools replay" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true">
|
||||
<exec>
|
||||
<option name="COMMAND" value="bash" />
|
||||
<option name="PARAMETERS" value="-c "source .venv/bin/activate && scons -u -j$(nproc) tools/replay/"" />
|
||||
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
|
||||
</exec>
|
||||
</tool>
|
||||
</toolSet>
|
||||
@@ -1,5 +1,5 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
|
||||
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="sunnypilot" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
|
||||
<envs>
|
||||
<env name="QT_DBL_CLICK_DIST" value="150" />
|
||||
</envs>
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Debug Route Controls" type="PythonConfigurationType" factoryName="Python">
|
||||
<module name="openpilot-special" />
|
||||
<option name="ENV_FILES" value="" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<envs>
|
||||
<env name="PYTHONUNBUFFERED" value="1" />
|
||||
<env name="FINGERPRINT" value="KIA_EV9" />
|
||||
<env name="SKIP_FW_QUERY" value="1" />
|
||||
</envs>
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/selfdrive/car" />
|
||||
<option name="IS_MODULE_SDK" value="true" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="true" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
|
||||
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/selfdrive/car/card.py" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="SHOW_COMMAND_LINE" value="false" />
|
||||
<option name="EMULATE_TERMINAL" value="true" />
|
||||
<option name="MODULE_MODE" value="false" />
|
||||
<option name="REDIRECT_INPUT" value="false" />
|
||||
<option name="INPUT_FILE" value="" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,7 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Replay for controls + ui" type="Multirun" separateTabs="false" reuseTabsWithFailures="false" startOneByOne="true" markFailedProcess="true" hideSuccessProcess="false" delayTime="0.0">
|
||||
<runConfiguration name="replay for controls" type="Native Application" />
|
||||
<runConfiguration name="Build Debug" type="Custom Build Application" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,7 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="replay for controls" type="CLionNativeAppRunConfigurationType" focusToolWindowBeforeRun="true" PROGRAM_PARAMS=""$Prompt$" --block "sendcan,carState,carParams,carOutput,liveTracks,carParamsSP,carStateSP,bookmarkButton"" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="true" WORKING_DIR="file://$ProjectFileDir$/tools/replay" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="replay" CONFIG_NAME="replay" version="1" RUN_PATH="replay">
|
||||
<method v="2">
|
||||
<option name="CLION.COMPOUND.BUILD" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
+1
-1
@@ -16,7 +16,7 @@ export VECLIB_MAXIMUM_THREADS=1
|
||||
export QCOM_PRIORITY=12
|
||||
|
||||
if [ -z "$AGNOS_VERSION" ]; then
|
||||
export AGNOS_VERSION="19.9-sunnypilot.3"
|
||||
export AGNOS_VERSION="19.9-sunnypilot.2-dae64af"
|
||||
fi
|
||||
|
||||
export STAGING_ROOT="/data/safe_staging"
|
||||
|
||||
+1
-1
Submodule opendbc_repo updated: 365fe9c2ab...b928e4a2c9
@@ -360,7 +360,6 @@ struct OnroadEventSP @0xda96579883444c35 {
|
||||
e2eChime @23;
|
||||
laneChangeRoadEdge @24;
|
||||
bigModelReady @25;
|
||||
stockSteerIntervention @26;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,7 +389,6 @@ struct CarControlSP @0xa5cd762cd951a455 {
|
||||
leadOne @2 :LeadData;
|
||||
leadTwo @3 :LeadData;
|
||||
intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement;
|
||||
pathCurvature @5 :Float32;
|
||||
|
||||
struct Param {
|
||||
key @0 :Text;
|
||||
@@ -455,7 +453,6 @@ struct BackupManagerSP @0xf98d843bfd7004a3 {
|
||||
|
||||
struct CarStateSP @0xb86e6369214c01c8 {
|
||||
speedLimit @0 :Float32;
|
||||
stockSteerIntervention @1 :Bool;
|
||||
}
|
||||
|
||||
struct LiveMapDataSP @0xf416ec09499d9d19 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[
|
||||
{
|
||||
"name": "xbl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"size": 3282256,
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
{
|
||||
"name": "xbl_config",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"size": 98124,
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"name": "abl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"size": 274432,
|
||||
@@ -34,7 +34,7 @@
|
||||
},
|
||||
{
|
||||
"name": "aop",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"size": 184364,
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
{
|
||||
"name": "devcfg",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"size": 40336,
|
||||
@@ -56,28 +56,28 @@
|
||||
},
|
||||
{
|
||||
"name": "boot",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/boot-2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b.img.xz",
|
||||
"hash": "2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b",
|
||||
"hash_raw": "2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/boot-6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b.img.xz",
|
||||
"hash": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
|
||||
"hash_raw": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
|
||||
"size": 47859712,
|
||||
"sparse": false,
|
||||
"full_check": true,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "43739cdc82df6616ecaa1360bfb36e0eaf92f53bdd6fbc033f30e2830e7452a4"
|
||||
"ondevice_hash": "71f49de9dcb8b8181a47695a4390d5a934ac59e92ce398bbfe5767ce01f78e4f"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/system-d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93.img.xz",
|
||||
"hash": "a40883c96fbb0460b7f8d18ccf37e2d94fdd43aaa02cb477526f1008d430217b",
|
||||
"hash_raw": "d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img.xz",
|
||||
"hash": "b959d05e5000ba590b0d47f8394a4024d3d5d348eadb8cc85f4aa7c15f8b7c20",
|
||||
"hash_raw": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
|
||||
"size": 4718592000,
|
||||
"sparse": true,
|
||||
"full_check": false,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "17aec6e1a6570613cf795e2e23f743b946201202633306bdc30b935c805bc3fd",
|
||||
"ondevice_hash": "872ca1b96c0d26d8fdaa74ab019b8c58de36c66afb4fc765681d265d17e80e9d",
|
||||
"alt": {
|
||||
"hash": "d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/system-d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93.img",
|
||||
"hash": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img",
|
||||
"size": 4718592000
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +171,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"CustomAccShortPressIncrement", {PERSISTENT | BACKUP, INT, "1"}},
|
||||
{"DeviceBootMode", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"DevUIInfo", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"DrawRadarTracks", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"EnableCopyparty", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"EnableGithubRunner", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"GreenLightAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
@@ -184,7 +183,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"LastGPSPositionFused", {PERSISTENT, STRING}},
|
||||
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
|
||||
{"MiciRoboticUI", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
|
||||
{"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
@@ -195,7 +193,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}},
|
||||
{"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RadarTracks", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RoadEdgeLaneChangeEnabled", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
@@ -249,7 +246,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"BackupManager_RestoreVersion", {PERSISTENT, STRING}},
|
||||
|
||||
// sunnypilot car specific params
|
||||
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
|
||||
@@ -37,8 +37,6 @@ SP_BRANCH_MIGRATIONS = {
|
||||
("tizi", "release3-staging"): "release-tizi-staging",
|
||||
("mici", "release3"): "release-mici",
|
||||
("mici", "release3-staging"): "release-mici-staging",
|
||||
("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici",
|
||||
("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt"
|
||||
}
|
||||
|
||||
BUILD_METADATA_FILENAME = "build.json"
|
||||
|
||||
@@ -179,8 +179,6 @@ class Car:
|
||||
|
||||
self.is_metric = self.params.get_bool("IsMetric")
|
||||
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
|
||||
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
|
||||
self._applied_radar_tracks = getattr(self.RI, "radar_mode", self.radar_tracks)
|
||||
|
||||
# card is driven by can recv, expected at 100Hz
|
||||
self.rk = Ratekeeper(100, print_delay_threshold=None)
|
||||
@@ -195,8 +193,6 @@ class Car:
|
||||
CS, CS_SP = self.CI.update(can_list)
|
||||
CS_SP = convert_to_capnp(CS_SP)
|
||||
|
||||
self._update_radar_tracks()
|
||||
|
||||
# Update radar tracks from CAN
|
||||
RD: structs.RadarDataT | None = self.RI.update(can_list)
|
||||
|
||||
@@ -223,18 +219,6 @@ class Car:
|
||||
|
||||
return CS, CS_SP, RD
|
||||
|
||||
def _update_radar_tracks(self) -> None:
|
||||
if self.CP.brand != "hyundai" or self.radar_tracks == self._applied_radar_tracks:
|
||||
return
|
||||
|
||||
if self.RI.set_radar_mode(self.radar_tracks):
|
||||
self.CP_SP_capnp = convert_to_capnp(self.CP_SP)
|
||||
cp_sp_bytes = self.CP_SP_capnp.to_bytes()
|
||||
self.params.put("CarParamsSP", cp_sp_bytes)
|
||||
self.params.put("CarParamsSPCache", cp_sp_bytes)
|
||||
self.params.put("CarParamsSPPersistent", cp_sp_bytes)
|
||||
self._applied_radar_tracks = self.radar_tracks
|
||||
|
||||
def state_publish(self, CS: car.CarState, CS_SP: custom.CarStateSP, RD: structs.RadarDataT | None):
|
||||
"""carState and carParams publish loop"""
|
||||
|
||||
@@ -313,7 +297,6 @@ class Car:
|
||||
while not evt.is_set():
|
||||
self.is_metric = self.params.get_bool("IsMetric")
|
||||
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
|
||||
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
|
||||
|
||||
# sunnypilot
|
||||
self.v_cruise_helper.read_custom_set_speed_params()
|
||||
|
||||
@@ -28,8 +28,6 @@ class DesireHelper:
|
||||
self.alc = AutoLaneChangeController(self)
|
||||
self.lane_turn_controller = LaneTurnController(self)
|
||||
self.lane_turn_direction = TurnDirection.none
|
||||
self.turn_frames = 0
|
||||
self.turn_repulse = 98
|
||||
|
||||
@staticmethod
|
||||
def get_lane_change_direction(CS):
|
||||
@@ -97,10 +95,8 @@ class DesireHelper:
|
||||
self.prev_one_blinker = one_blinker and lateral_active
|
||||
|
||||
if self.lane_turn_direction != TurnDirection.none:
|
||||
self.turn_frames += 1
|
||||
self.desire = TURN_DESIRES[self.lane_turn_direction] if self.turn_frames % self.turn_repulse else log.Desire.none
|
||||
self.desire = TURN_DESIRES[self.lane_turn_direction]
|
||||
else:
|
||||
self.turn_frames = 0
|
||||
self.desire = log.Desire.none
|
||||
if self.lane_change_state == LaneChangeState.laneChangeStarting:
|
||||
if self.lane_change_direction == LaneChangeDirection.left:
|
||||
|
||||
@@ -26,8 +26,6 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum
|
||||
|
||||
# stationary qualification parameters
|
||||
V_EGO_STATIONARY = 4. # no stationary object flag below this speed
|
||||
DBC_MOTION_STATIONARY = 1
|
||||
DBC_MOTION_MOVING = 2
|
||||
|
||||
RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame
|
||||
|
||||
@@ -193,14 +191,8 @@ def get_custom_yrel(CP: structs.CarParams, CP_SP: structs.CarParamsSP, lead_dict
|
||||
return lead_dict
|
||||
|
||||
|
||||
def radar_point_eligible_for_fusion(CP: structs.CarParams, CP_SP: structs.CarParamsSP,
|
||||
point: car.RadarData.RadarPoint) -> bool:
|
||||
use_dbc_motion = CP.brand == "hyundai" and CP_SP.flags & HyundaiFlagsSP.RADAR_FULL_RADAR
|
||||
return not use_dbc_motion or point.motionState in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING)
|
||||
|
||||
|
||||
class RadarD:
|
||||
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, delay: float = 0.0):
|
||||
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParams, delay: float = 0.0):
|
||||
self.CP = CP
|
||||
self.CP_SP = CP_SP
|
||||
|
||||
@@ -226,11 +218,7 @@ class RadarD:
|
||||
self.v_ego_hist.append(self.v_ego)
|
||||
self.last_v_ego_frame = sm.recv_frame['carState']
|
||||
|
||||
ar_pts = {
|
||||
pt.trackId: [pt.dRel, pt.yRel, pt.vRel]
|
||||
for pt in rr.points
|
||||
if radar_point_eligible_for_fusion(self.CP, self.CP_SP, pt)
|
||||
}
|
||||
ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points}
|
||||
|
||||
# *** remove missing points from meta data ***
|
||||
for ids in list(self.tracks.keys()):
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:416c99bbd5563b01518be6de91b856986f66ffa03451ea9c451736dcc99896fd
|
||||
size 83976077
|
||||
oid sha256:65a08adc31d5c456219687d99b7bf5e44d61dae2d49ea67850e76105c7248cce
|
||||
size 60918562
|
||||
|
||||
@@ -100,24 +100,7 @@ class TogglesLayout(Widget):
|
||||
icon="speed_limit.png"
|
||||
)
|
||||
|
||||
self._radar_tracks_setting = None
|
||||
self._toggles = {}
|
||||
if gui_app.sunnypilot_ui():
|
||||
self._radar_tracks_setting = multiple_button_item(
|
||||
lambda: tr("Radar Tracks"),
|
||||
"",
|
||||
buttons=[lambda: tr("Off"), lambda: tr("Lead Only"), lambda: tr("Full Radar")],
|
||||
button_width=250,
|
||||
callback=self._set_radar_tracks,
|
||||
selected_index=self._params.get("RadarTracks", return_default=True),
|
||||
)
|
||||
self._toggles["RadarTracks"] = self._radar_tracks_setting
|
||||
self._toggle_defs["DrawRadarTracks"] = (
|
||||
lambda: tr("Draw Radar Tracks"),
|
||||
tr_noop("Show radar tracks on the driving screen. Disabling this does not disable radar processing."),
|
||||
"",
|
||||
False,
|
||||
)
|
||||
self._initial_cruise_speed = ListItem(
|
||||
title=lambda: tr("Initial Max Speed"),
|
||||
description=lambda: tr("Max speed when engaging openpilot. If you are already driving faster, your current speed is used. " +
|
||||
@@ -186,8 +169,6 @@ class TogglesLayout(Widget):
|
||||
# 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))
|
||||
if self._radar_tracks_setting is not None:
|
||||
self._radar_tracks_setting.action_item.set_selected_button(self._params.get("RadarTracks", return_default=True))
|
||||
|
||||
# these toggles need restart, block while engaged
|
||||
for toggle_def in self._toggle_defs:
|
||||
@@ -207,6 +188,3 @@ class TogglesLayout(Widget):
|
||||
|
||||
def _set_longitudinal_personality(self, button_index: int):
|
||||
self._params.put("LongitudinalPersonality", button_index, block=True)
|
||||
|
||||
def _set_radar_tracks(self, button_index: int):
|
||||
self._params.put("RadarTracks", button_index, block=True)
|
||||
|
||||
@@ -14,7 +14,6 @@ from openpilot.system.ui.lib.application import gui_app
|
||||
if gui_app.sunnypilot_ui():
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.home import MiciHomeLayoutSP as MiciHomeLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import RoboticOnroadView
|
||||
|
||||
ONROAD_DELAY = 2.5 # seconds
|
||||
|
||||
@@ -35,35 +34,24 @@ class MiciMainLayout(Scroller):
|
||||
self._alerts_layout = MiciOffroadAlerts()
|
||||
self._settings_layout = SettingsLayout()
|
||||
self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked)
|
||||
self._robotic_onroad_layout = RoboticOnroadView(bookmark_callback=self._on_bookmark_clicked) if gui_app.sunnypilot_ui() else None
|
||||
self._body_onroad_layout = BodyLayout()
|
||||
self._prev_robotic_ui = bool(gui_app.sunnypilot_ui() and ui_state.mici_robotic_ui)
|
||||
|
||||
# Initialize widget rects
|
||||
all_widgets = [self._home_layout, self._alerts_layout, self._settings_layout,
|
||||
self._car_onroad_layout, self._body_onroad_layout]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
all_widgets.append(self._robotic_onroad_layout)
|
||||
for widget in all_widgets:
|
||||
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))
|
||||
|
||||
scroller_widgets = [
|
||||
self._scroller.add_widgets([
|
||||
self._alerts_layout,
|
||||
self._home_layout,
|
||||
self._car_onroad_layout,
|
||||
]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
scroller_widgets.append(self._robotic_onroad_layout)
|
||||
scroller_widgets.append(self._body_onroad_layout)
|
||||
self._scroller.add_widgets(scroller_widgets)
|
||||
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() or
|
||||
(self._robotic_onroad_layout is not None and self._robotic_onroad_layout.is_swiping_left()))
|
||||
)
|
||||
self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left())
|
||||
|
||||
# Set callbacks
|
||||
self._setup_callbacks()
|
||||
@@ -82,11 +70,7 @@ class MiciMainLayout(Scroller):
|
||||
@property
|
||||
def _onroad_layout(self) -> Widget:
|
||||
# For scroll_to
|
||||
if ui_state.is_body:
|
||||
return self._body_onroad_layout
|
||||
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui:
|
||||
return self._robotic_onroad_layout
|
||||
return self._car_onroad_layout
|
||||
return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout
|
||||
|
||||
def _setup_callbacks(self):
|
||||
self._alerts_layout.set_enabled(lambda: self.enabled)
|
||||
@@ -97,10 +81,7 @@ class MiciMainLayout(Scroller):
|
||||
alert_count_callback=self._alerts_layout.active_alerts,
|
||||
alert_icon_callback=self._alerts_layout.highest_severity_icon,
|
||||
)
|
||||
onroad_layouts = [self._car_onroad_layout, self._body_onroad_layout]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
onroad_layouts.append(self._robotic_onroad_layout)
|
||||
for layout in onroad_layouts:
|
||||
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)
|
||||
@@ -114,9 +95,6 @@ class MiciMainLayout(Scroller):
|
||||
super()._update_state()
|
||||
# TODO: Hack to run alert updates while not in view. Add a nav stack tick?
|
||||
self._alerts_layout._update_state()
|
||||
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui != self._prev_robotic_ui:
|
||||
self._prev_robotic_ui = ui_state.mici_robotic_ui
|
||||
self._on_body_changed()
|
||||
|
||||
def _render(self, _):
|
||||
if not self._setup:
|
||||
@@ -175,8 +153,5 @@ class MiciMainLayout(Scroller):
|
||||
self._pm.send(service, msg)
|
||||
|
||||
def _on_body_changed(self):
|
||||
use_robotic = self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui
|
||||
self._car_onroad_layout.set_visible(not ui_state.is_body and not use_robotic)
|
||||
if self._robotic_onroad_layout is not None:
|
||||
self._robotic_onroad_layout.set_visible(not ui_state.is_body and use_robotic)
|
||||
self._car_onroad_layout.set_visible(not ui_state.is_body)
|
||||
self._body_onroad_layout.set_visible(bool(ui_state.is_body))
|
||||
|
||||
@@ -20,9 +20,9 @@ class SettingsLayout(NavScroller):
|
||||
super().__init__()
|
||||
self._params = Params()
|
||||
|
||||
self._toggles_panel = TogglesLayoutMici()
|
||||
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(self._toggles_panel))
|
||||
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))
|
||||
|
||||
@@ -36,19 +36,9 @@ class TogglesLayoutMici(NavScroller):
|
||||
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback,
|
||||
description="Enable to use sunnypilot driver assistance.\n" +
|
||||
"Disable to use your car's stock driver assistance.")
|
||||
radar_tracks = BigMultiParamToggle("radar tracks", "RadarTracks", ["off", "lead only", "full radar"])
|
||||
draw_radar_tracks = BigParamControl("draw radar tracks", "DrawRadarTracks")
|
||||
robotic_ui_toggle = BigParamControl(
|
||||
"robotic companion UI",
|
||||
"MiciRoboticUI",
|
||||
description="Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
|
||||
)
|
||||
self._radar_tracks_toggle = radar_tracks
|
||||
|
||||
|
||||
self._scroller.add_widgets([
|
||||
robotic_ui_toggle,
|
||||
radar_tracks,
|
||||
draw_radar_tracks,
|
||||
self._personality_toggle,
|
||||
self._initial_cruise_speed,
|
||||
is_metric_toggle,
|
||||
@@ -61,8 +51,6 @@ class TogglesLayoutMici(NavScroller):
|
||||
|
||||
# Toggle lists
|
||||
self._refresh_toggles = (
|
||||
("MiciRoboticUI", robotic_ui_toggle),
|
||||
("DrawRadarTracks", draw_radar_tracks),
|
||||
("IsMetric", is_metric_toggle),
|
||||
("IsLdwEnabled", ldw_toggle),
|
||||
("AlwaysOnDM", always_on_dm_toggle),
|
||||
@@ -108,4 +96,3 @@ class TogglesLayoutMici(NavScroller):
|
||||
# Refresh toggles from params to mirror external changes
|
||||
for key, item in self._refresh_toggles:
|
||||
item.set_checked(ui_state.params.get_bool(key))
|
||||
self._radar_tracks_toggle._load_value()
|
||||
|
||||
@@ -15,7 +15,6 @@ from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.model_renderer import LANE_LINE_COLORS_SP, ModelRendererSP
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import draw_radar_lead_connectors, radar_lead_track_colors
|
||||
|
||||
CLIP_MARGIN = 500
|
||||
MIN_DRAW_DISTANCE = 10.0
|
||||
@@ -47,9 +46,6 @@ class ModelPoints:
|
||||
class LeadVehicle:
|
||||
def __init__(self):
|
||||
self.bar = np.empty((0, 2), dtype=np.float32)
|
||||
self.position: tuple[float, float] | None = None
|
||||
self.radar_track_id: int = -1
|
||||
self.radar: bool = False
|
||||
self.d_filter = FirstOrderFilter(0.0, 0.2, 1 / gui_app.target_fps, initialized=False)
|
||||
self.y_filter = FirstOrderFilter(0.0, 0.2, 1 / gui_app.target_fps, initialized=False)
|
||||
self.fade_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps)
|
||||
@@ -130,8 +126,7 @@ class ModelRenderer(Widget, ModelRendererSP):
|
||||
|
||||
# Update model data when needed
|
||||
model_updated = sm.updated['modelV2']
|
||||
transform_updated = self._transform_dirty
|
||||
if model_updated or sm.updated['radarState'] or transform_updated:
|
||||
if model_updated or sm.updated['radarState'] or self._transform_dirty:
|
||||
if model_updated:
|
||||
self._update_raw_points(model)
|
||||
|
||||
@@ -148,33 +143,8 @@ class ModelRenderer(Widget, ModelRendererSP):
|
||||
self._draw_path()
|
||||
self.blendful.draw(self._rect)
|
||||
|
||||
radar_matched_positions = {}
|
||||
radar_highlighted_tracks = {}
|
||||
if ui_state.draw_radar_tracks and sm.valid['radarTracks'] and sm.recv_frame['radarTracks'] >= ui_state.started_frame:
|
||||
if (sm.updated['radarTracks'] or sm.updated['extrinsicsCalibration'] or transform_updated or
|
||||
not self.radar_tracks.projection_initialized):
|
||||
self.radar_tracks.update_radar_tracks(
|
||||
sm['radarTracks'], self._map_to_screen, self._path_offset_z,
|
||||
)
|
||||
radar_highlighted_tracks = radar_lead_track_colors(radar_state) if render_lead_indicator else {}
|
||||
radar_matched_positions = self.radar_tracks.draw_cached_radar_tracks(
|
||||
screen_offset=(self._rect.x, self._rect.y),
|
||||
highlighted_tracks=radar_highlighted_tracks,
|
||||
)
|
||||
else:
|
||||
self.radar_tracks.clear_projection()
|
||||
|
||||
if render_lead_indicator:
|
||||
self._update_leads(sm)
|
||||
plan = sm['longitudinalPlan']
|
||||
if plan.longitudinalPlanSource != log.LongitudinalPlan.LongitudinalPlanSource.e2e:
|
||||
for lead_vehicle, lead in zip(self._lead_vehicles, (radar_state.leadOne, radar_state.leadTwo), strict=True):
|
||||
lead_vehicle.radar_track_id = int(lead.radarTrackId)
|
||||
lead_vehicle.radar = lead.radar
|
||||
draw_radar_lead_connectors(
|
||||
self._lead_vehicles, radar_matched_positions, radar_highlighted_tracks,
|
||||
screen_offset=(self._rect.x, self._rect.y),
|
||||
)
|
||||
self._draw_lead_indicator()
|
||||
else:
|
||||
self._lead_vehicles = [LeadVehicle(), LeadVehicle()]
|
||||
@@ -218,7 +188,6 @@ class ModelRenderer(Widget, ModelRendererSP):
|
||||
lead.fade_filter.update(opacity if visible else 0.0)
|
||||
if visible:
|
||||
lead.bar = self._get_lead_bar(lane, lead.d_filter.update(d_rel), lead.y_filter.update(y_rel))
|
||||
lead.position = tuple(lead.bar.mean(axis=0))
|
||||
|
||||
def _get_lead_bar(self, lane, d_rel, y_rel):
|
||||
# bar on the road behind the lead, following the lane
|
||||
@@ -372,21 +341,6 @@ class ModelRenderer(Widget, ModelRendererSP):
|
||||
for lead in self._lead_vehicles:
|
||||
draw_polygon(self._rect, lead.bar + offset, rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
|
||||
|
||||
def _map_to_screen(self, in_x, in_y, in_z):
|
||||
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 + self._rect.x <= clip.x + clip.width and clip.y <= y + self._rect.y <= clip.y + clip.height):
|
||||
return None
|
||||
|
||||
return (x, y)
|
||||
|
||||
@staticmethod
|
||||
def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int:
|
||||
"""Get the index corresponding to the given path height"""
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
"""Tests for MICI Robotic Companion onroad UI mood engine and telemetry helpers."""
|
||||
import random
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
EyeGlyph,
|
||||
MouthGlyph,
|
||||
PALETTE,
|
||||
RoboticMood,
|
||||
RoboticMoodEngine,
|
||||
STANDSTILL_POUT_DELAY,
|
||||
STANDSTILL_SLEEPY_DELAY,
|
||||
display_speed_and_set_speed,
|
||||
)
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
|
||||
|
||||
class TestRoboticMoodEngine(OpenpilotTestCase):
|
||||
def _engine(self) -> RoboticMoodEngine:
|
||||
return RoboticMoodEngine(rng=random.Random(42))
|
||||
|
||||
def test_engaged_happy_then_speed_then_cruising(self):
|
||||
engine = self._engine()
|
||||
# Initially disengaged
|
||||
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
|
||||
target = engine.update(snap, now=10.0)
|
||||
assert engine.mood == RoboticMood.IDLE_CURIOUS
|
||||
assert target.color == PALETTE["disengaged"]
|
||||
|
||||
# Engage triggers HAPPY_ENGAGE crescent eyes
|
||||
snap_eng = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
|
||||
target = engine.update(snap_eng, now=11.0)
|
||||
assert engine.mood == RoboticMood.HAPPY_ENGAGE
|
||||
assert target.glyph == EyeGlyph.CRESCENT
|
||||
assert target.color == PALETTE["engaged"]
|
||||
|
||||
# After happy hold, briefly shows speed confirmation
|
||||
engine.update(snap_eng, now=12.2)
|
||||
assert engine.mood == RoboticMood.SPEED_DISPLAY
|
||||
assert engine.showing_speed is True
|
||||
|
||||
# After speed confirm expires, settles into CRUISING_HAPPY
|
||||
target = engine.update(snap_eng, now=15.0)
|
||||
assert engine.mood == RoboticMood.CRUISING_HAPPY
|
||||
assert engine.showing_speed is False
|
||||
assert target.color == PALETTE["engaged"]
|
||||
|
||||
def test_critical_alert_overrides_all_moods(self):
|
||||
engine = self._engine()
|
||||
engine.trigger_love(now=10.0)
|
||||
engine.trigger_speed_peek(now=10.0)
|
||||
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, alert=alert)
|
||||
|
||||
target = engine.update(snap, now=10.1)
|
||||
assert engine.mood == RoboticMood.CRITICAL
|
||||
assert target.glyph == EyeGlyph.LASER_ALERT
|
||||
assert target.color == PALETTE["critical"]
|
||||
assert engine.showing_speed is False
|
||||
|
||||
def test_distracted_driver_monitoring(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, dm_alert_level=1)
|
||||
target = engine.update(snap, now=20.0)
|
||||
assert engine.mood == RoboticMood.DISTRACTED
|
||||
assert target.color == PALETTE["prompt"]
|
||||
assert target.mouth == MouthGlyph.FROWN
|
||||
|
||||
def test_hard_decel_triggers_star_eyes(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, a_ego=-3.8)
|
||||
target = engine.update(snap, now=30.0)
|
||||
assert engine.mood == RoboticMood.STARTLED_STARS
|
||||
assert target.glyph == EyeGlyph.STAR
|
||||
assert target.mouth == MouthGlyph.SURPRISED
|
||||
|
||||
def test_lane_change_and_blind_spot(self):
|
||||
engine = self._engine()
|
||||
snap_lc = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, pre_lane_change_left=True)
|
||||
target = engine.update(snap_lc, now=40.0)
|
||||
assert engine.mood == RoboticMood.LANE_CHANGE
|
||||
assert target.glyph == EyeGlyph.ARROW_LEFT
|
||||
assert target.gaze_x < 0
|
||||
|
||||
snap_bsm = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, right_blinker=True, right_blindspot=True)
|
||||
target = engine.update(snap_bsm, now=41.0)
|
||||
assert engine.mood == RoboticMood.BLIND_SPOT
|
||||
assert target.gaze_x > 0
|
||||
assert target.blind_spot_side == 1
|
||||
|
||||
def test_standstill_pout_and_sleepy_progression(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
|
||||
engine.update(snap, now=100.0)
|
||||
# Past happy engage & speed confirm, still before pout
|
||||
engine.update(snap, now=105.0)
|
||||
assert engine.mood == RoboticMood.CRUISING_HAPPY
|
||||
|
||||
# Past pout threshold
|
||||
target = engine.update(snap, now=100.0 + STANDSTILL_POUT_DELAY + 1.0)
|
||||
assert engine.mood == RoboticMood.POUT_STANDSTILL
|
||||
assert target.mouth == MouthGlyph.FROWN
|
||||
|
||||
# Past sleepy threshold
|
||||
target = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 1.0)
|
||||
assert engine.mood == RoboticMood.SLEEPY
|
||||
assert target.top_lid >= 0.5
|
||||
|
||||
def test_set_speed_change_triggers_speed_display(self):
|
||||
engine = self._engine()
|
||||
snap1 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
|
||||
engine.update(snap1, now=10.0)
|
||||
engine.update(snap1, now=15.0)
|
||||
assert engine.showing_speed is False
|
||||
|
||||
snap2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=110.0)
|
||||
engine.update(snap2, now=16.0)
|
||||
assert engine.mood == RoboticMood.SPEED_DISPLAY
|
||||
assert engine.showing_speed is True
|
||||
assert engine.speed_reason == "set_speed"
|
||||
|
||||
def test_mads_lat_only_warm_peach_palette(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=18.0)
|
||||
engine.update(snap, now=10.0)
|
||||
target = engine.update(snap, now=15.0)
|
||||
assert target.color == PALETTE["lat_only"]
|
||||
|
||||
def test_display_speed_conversion(self):
|
||||
snap_mph = DrivingSnapshot(v_ego=26.8224, set_speed_kph=100.0, is_metric=False)
|
||||
cur, set_s = display_speed_and_set_speed(snap_mph)
|
||||
assert cur == 60
|
||||
assert set_s == 62
|
||||
|
||||
snap_kph = DrivingSnapshot(v_ego=27.7778, set_speed_kph=100.0, is_metric=True)
|
||||
cur, set_s = display_speed_and_set_speed(snap_kph)
|
||||
assert cur == 100
|
||||
assert set_s == 100
|
||||
|
||||
def test_sharp_accel_turn_signal_sharp_turn_and_continuous_motion(self):
|
||||
engine = self._engine()
|
||||
# Sharp acceleration triggers BOOST_ACCEL with speed lines
|
||||
snap_boost = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, a_ego=2.8)
|
||||
engine.update(snap_boost, now=10.0)
|
||||
target = engine.update(snap_boost, now=14.0)
|
||||
# Trigger fresh boost after engage hold expires
|
||||
snap_boost2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, a_ego=2.9)
|
||||
target = engine.update(snap_boost2, now=15.0)
|
||||
assert engine.mood == RoboticMood.BOOST_ACCEL
|
||||
assert target.glyph == EyeGlyph.SPARKLE_BOOST
|
||||
assert target.show_speed_lines is True
|
||||
|
||||
# Turn indicator triggers TURN_SIGNAL with blinker side
|
||||
snap_turn = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0, left_blinker=True)
|
||||
target = engine.update(snap_turn, now=20.0)
|
||||
assert engine.mood == RoboticMood.TURN_SIGNAL
|
||||
assert target.blinker_side == -1
|
||||
|
||||
# Sharp turn triggers SHARP_TURN with centrifugal tilt
|
||||
snap_sharp = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=12.0, steering_angle_deg=55.0)
|
||||
target = engine.update(snap_sharp, now=25.0)
|
||||
assert engine.mood == RoboticMood.SHARP_TURN
|
||||
assert abs(target.tilt_y) >= 10.0
|
||||
|
||||
# Bookmark wink triggers love with wink_right=True
|
||||
engine.trigger_love(now=30.0, wink=True)
|
||||
target = engine.update(DrivingSnapshot(started=True, engaged=False), now=30.2)
|
||||
assert engine.mood == RoboticMood.BOOKMARK_LOVE
|
||||
assert target.wink_right is True
|
||||
assert target.show_hearts is True
|
||||
|
||||
# Continuous motion check: idle bounce_y & gaze_x are never frozen across frames
|
||||
snap_idle = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=0.0)
|
||||
t1 = engine.update(snap_idle, now=40.0)
|
||||
t2 = engine.update(snap_idle, now=40.5)
|
||||
assert (t1.bounce_y != t2.bounce_y) or (t1.gaze_x != t2.gaze_x)
|
||||
|
||||
def test_music_analyzer_rejects_road_noise_and_speech_detects_music(self):
|
||||
import numpy as np
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import (
|
||||
DEFAULT_SAMPLE_RATE,
|
||||
MusicAnalyzer,
|
||||
MusicState,
|
||||
)
|
||||
|
||||
sr = DEFAULT_SAMPLE_RATE
|
||||
chunk_len = 800 # 50 ms @ 16 kHz
|
||||
rng = np.random.default_rng(7)
|
||||
|
||||
# 1. Broadband cabin road/wind noise -> MUST be rejected
|
||||
road_analyzer = MusicAnalyzer(sr)
|
||||
for _ in range(90): # 4.5 s
|
||||
noise = rng.normal(0.0, 0.08, size=chunk_len).astype(np.float32)
|
||||
state = road_analyzer.process_samples(noise)
|
||||
assert state.is_music is False, f"Road noise falsely triggered music (conf={state.confidence:.2f})"
|
||||
|
||||
# 2. Simulated human talking (irregular vocal-band bursts with speech pauses) -> MUST be rejected
|
||||
speech_analyzer = MusicAnalyzer(sr)
|
||||
t_total = np.arange(90 * chunk_len, dtype=np.float32) / sr
|
||||
# Speech formants (550Hz + 1200Hz) modulated by irregular syllables & pauses
|
||||
vocal = 0.09 * np.sin(2 * np.pi * 550 * t_total) + 0.06 * np.sin(2 * np.pi * 1250 * t_total)
|
||||
for idx in range(90):
|
||||
# Irregular talk/pause pattern (approx 45% active)
|
||||
speaking = (idx % 11) in (0, 1, 2, 5, 6)
|
||||
seg = vocal[idx * chunk_len:(idx + 1) * chunk_len] * (1.0 if speaking else 0.02)
|
||||
seg = seg + rng.normal(0.0, 0.01, size=chunk_len).astype(np.float32)
|
||||
state = speech_analyzer.process_samples(seg)
|
||||
assert state.is_music is False, f"Talking falsely triggered music (conf={state.confidence:.2f})"
|
||||
|
||||
# 3. Simulated rhythmic harmonic music (120 BPM kick + chords + hi-hat) -> MUST be detected
|
||||
music_analyzer = MusicAnalyzer(sr)
|
||||
beat_period = 0.5 # 120 BPM
|
||||
for idx in range(100): # 5.0 s
|
||||
t = (idx * chunk_len + np.arange(chunk_len, dtype=np.float32)) / sr
|
||||
beat_t = t % beat_period
|
||||
kick = 0.22 * np.exp(-beat_t * 18.0) * np.sin(2 * np.pi * 95.0 * t)
|
||||
chord = (
|
||||
0.09 * np.sin(2 * np.pi * 261.6 * t)
|
||||
+ 0.07 * np.sin(2 * np.pi * 329.6 * t)
|
||||
+ 0.07 * np.sin(2 * np.pi * 392.0 * t)
|
||||
)
|
||||
hihat_t = (t + 0.25) % beat_period
|
||||
hihat = 0.08 * np.exp(-hihat_t * 35.0) * np.sin(2 * np.pi * 5200.0 * t)
|
||||
mix = (kick + chord + hihat).astype(np.float32)
|
||||
state = music_analyzer.process_samples(mix)
|
||||
assert state.is_music is True, f"Music was not detected (conf={state.confidence:.2f})"
|
||||
assert max(state.bands) > 0.2
|
||||
|
||||
# 4. Mood engine enters MUSIC_GROOVE when cruising/idling, overridden immediately by alerts
|
||||
engine = self._engine()
|
||||
music_on = MusicState(is_music=True, confidence=0.85, beat_pulse=0.7, groove_phase=1.2, bpm=120.0, energy=0.7)
|
||||
snap_cruise = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on)
|
||||
engine.update(snap_cruise, now=10.0)
|
||||
engine.update(snap_cruise, now=15.0)
|
||||
assert engine.mood == RoboticMood.MUSIC_GROOVE
|
||||
|
||||
# Alert overrides MUSIC_GROOVE immediately
|
||||
snap_alert = DrivingSnapshot(
|
||||
started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on,
|
||||
alert=Alert("Pay Attention", "Eyes on road", status=AlertStatus.userPrompt),
|
||||
)
|
||||
engine.update(snap_alert, now=15.5)
|
||||
assert engine.mood == RoboticMood.USER_PROMPT
|
||||
|
||||
def test_centrifugal_turn_squish_and_pitch_response(self):
|
||||
engine = self._engine()
|
||||
# Gentle left turn (yaw_rate > 0 -> pushed right: squish_force > 0)
|
||||
snap_mild = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=15.0, yaw_rate=0.10, pitch_rad=0.05)
|
||||
engine.update(snap_mild, now=10.0)
|
||||
t_mild = engine.update(snap_mild, now=15.0)
|
||||
assert t_mild.squish_force > 0.15
|
||||
assert t_mild.pitch_offset_y > 0.0
|
||||
|
||||
# Fast left turn (high lateral G -> strongly squished right + surprised mouth)
|
||||
snap_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=0.18, pitch_rate=-0.2)
|
||||
t_fast = engine.update(snap_fast, now=16.0)
|
||||
assert engine.mood == RoboticMood.SHARP_TURN
|
||||
assert t_fast.squish_force > t_mild.squish_force
|
||||
assert t_fast.squish_force > 0.65
|
||||
assert t_fast.mouth == MouthGlyph.SURPRISED
|
||||
|
||||
# Fast right turn (yaw_rate < 0 -> pushed left: squish_force < 0)
|
||||
snap_right = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, yaw_rate=-0.18)
|
||||
t_right = engine.update(snap_right, now=17.0)
|
||||
assert t_right.squish_force < -0.65
|
||||
@@ -103,7 +103,7 @@ class AugmentedRoadView(CameraView, AugmentedRoadViewSP):
|
||||
# Draw colored border based on driving state
|
||||
self._draw_border(rect)
|
||||
|
||||
def _handle_mouse_press(self, mouse_pos):
|
||||
def _handle_mouse_press(self, _):
|
||||
if self._click_callback is not None:
|
||||
self._click_callback()
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.model_renderer import ChevronMetrics, ModelRendererSP
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import draw_radar_lead_connectors, radar_lead_track_colors
|
||||
|
||||
CLIP_MARGIN = 500
|
||||
MIN_DRAW_DISTANCE = 10.0
|
||||
@@ -36,9 +35,6 @@ class LeadVehicle:
|
||||
glow: list[tuple[float, float]] = field(default_factory=list)
|
||||
chevron: list[tuple[float, float]] = field(default_factory=list)
|
||||
fill_alpha: int = 0
|
||||
position: tuple[float, float] | None = None
|
||||
radar_track_id: int = -1
|
||||
radar: bool = False
|
||||
|
||||
|
||||
class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
|
||||
@@ -111,8 +107,7 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
|
||||
|
||||
# Update model data when needed
|
||||
model_updated = sm.updated['modelV2']
|
||||
transform_updated = self._transform_dirty
|
||||
if model_updated or sm.updated['radarState'] or transform_updated:
|
||||
if model_updated or sm.updated['radarState'] or self._transform_dirty:
|
||||
if model_updated:
|
||||
self._update_raw_points(model)
|
||||
|
||||
@@ -130,21 +125,6 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
|
||||
self._draw_path()
|
||||
self.blendful.draw(self._rect)
|
||||
|
||||
if ui_state.draw_radar_tracks and sm.valid['radarTracks'] and sm.recv_frame['radarTracks'] >= ui_state.started_frame:
|
||||
if (sm.updated['radarTracks'] or sm.updated['liveCalibration'] or transform_updated or
|
||||
not self.radar_tracks.projection_initialized):
|
||||
self.radar_tracks.update_radar_tracks(
|
||||
sm['radarTracks'], self._map_to_screen, self._path_offset_z,
|
||||
)
|
||||
highlighted_tracks = radar_lead_track_colors(radar_state) if render_lead_indicator else {}
|
||||
matched_positions = self.radar_tracks.draw_cached_radar_tracks(
|
||||
highlighted_tracks=highlighted_tracks,
|
||||
)
|
||||
if render_lead_indicator:
|
||||
draw_radar_lead_connectors(self._lead_vehicles, matched_positions, highlighted_tracks)
|
||||
else:
|
||||
self.radar_tracks.clear_projection()
|
||||
|
||||
if render_lead_indicator and radar_state:
|
||||
self._draw_lead_indicator()
|
||||
self.chevron_metrics.draw_lead_status(sm, radar_state, self._rect, self._lead_vehicles)
|
||||
@@ -177,11 +157,7 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
|
||||
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 + self._camera_offset, z + self._path_offset_z)
|
||||
if point:
|
||||
lead_vehicle = self._update_lead_vehicle(d_rel, v_rel, point, self._rect)
|
||||
lead_vehicle.position = lead_vehicle.chevron[1]
|
||||
lead_vehicle.radar_track_id = int(lead_data.radarTrackId)
|
||||
lead_vehicle.radar = lead_data.radar
|
||||
self._lead_vehicles[i] = lead_vehicle
|
||||
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"""
|
||||
|
||||
@@ -15,7 +15,6 @@ from openpilot.system import micd
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
|
||||
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
|
||||
|
||||
SAMPLE_RATE = 48000
|
||||
SAMPLE_BUFFER = 4096 # (approx 100ms)
|
||||
@@ -74,7 +73,6 @@ def check_selfdrive_timeout_alert(sm):
|
||||
class Soundd(QuietMode):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.robotic_sound_pack = RoboticSoundPack(self.params, SAMPLE_RATE)
|
||||
|
||||
self.load_sounds()
|
||||
|
||||
@@ -105,22 +103,13 @@ class Soundd(QuietMode):
|
||||
length = wavefile.getnframes()
|
||||
self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2)
|
||||
|
||||
self.robotic_sound_pack.load()
|
||||
|
||||
def load_param(self) -> None:
|
||||
prev_frame = self._frame
|
||||
super().load_param()
|
||||
if self._frame != prev_frame and self._frame % 50 == 0:
|
||||
if self.robotic_sound_pack.refresh_param():
|
||||
self.current_sound_frame = 0
|
||||
|
||||
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.should_play_sound(self.current_alert):
|
||||
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
|
||||
sound_data = self.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds)
|
||||
num_loops = sound_list[self.current_alert][1]
|
||||
sound_data = self.loaded_sounds[self.current_alert]
|
||||
written_frames = 0
|
||||
|
||||
current_sound_frame = self.current_sound_frame % len(sound_data)
|
||||
@@ -147,17 +136,9 @@ class Soundd(QuietMode):
|
||||
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.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds))
|
||||
)
|
||||
current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert])
|
||||
# let looping sounds finish the current loop instead of cutting off mid tone
|
||||
if (
|
||||
new_alert == AudibleAlert.none
|
||||
and self.current_alert != AudibleAlert.none
|
||||
and self.current_alert not in REACTIVE_CHIRP_IDS
|
||||
and sound_list[self.current_alert][1] is None
|
||||
):
|
||||
if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None:
|
||||
if current_alert_played_once:
|
||||
self.pending_stop = True
|
||||
else:
|
||||
@@ -183,12 +164,6 @@ class Soundd(QuietMode):
|
||||
self.update_alert(AudibleAlert.none)
|
||||
self.selfdrive_timeout_alert = False
|
||||
|
||||
# Trigger playful one-shot robotic chirps only when idle (never preempting safety alerts)
|
||||
if self.robotic_sound_pack.enabled and self.current_alert == AudibleAlert.none:
|
||||
chirp = self.robotic_sound_pack.detect_reactive_chirp(sm)
|
||||
if chirp is not None:
|
||||
self.update_alert(chirp)
|
||||
|
||||
def calculate_volume(self, weighted_db):
|
||||
volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME
|
||||
return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1))
|
||||
@@ -205,7 +180,7 @@ class Soundd(QuietMode):
|
||||
import sounddevice as sd
|
||||
micd.patch_sounddevice(sd)
|
||||
|
||||
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure', 'carState', 'controlsState', 'userBookmark', 'bookmarkButton'])
|
||||
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure'])
|
||||
|
||||
with self.get_stream(sd) as stream:
|
||||
rk = Ratekeeper(20)
|
||||
|
||||
@@ -7,7 +7,7 @@ See the LICENSE.md file in the root directory for more details.
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp
|
||||
from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR
|
||||
|
||||
|
||||
@@ -16,9 +16,16 @@ class HyundaiSettings(BrandSettings):
|
||||
super().__init__()
|
||||
self.alpha_long_available = False
|
||||
|
||||
self.longitudinal_tuning_item = toggle_item_sp(tr("Custom Longitudinal Tuning"), "", param="HyundaiLongitudinalTuning")
|
||||
tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")]
|
||||
self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts,
|
||||
button_width=300, callback=self._on_tuning_selected,
|
||||
param="HyundaiLongitudinalTuning", inline=False)
|
||||
self.items = [self.longitudinal_tuning_item]
|
||||
|
||||
@staticmethod
|
||||
def _on_tuning_selected(index):
|
||||
ui_state.params.put("HyundaiLongitudinalTuning", index)
|
||||
|
||||
def update_settings(self):
|
||||
self.alpha_long_available = False
|
||||
bundle = ui_state.params.get("CarPlatformBundle")
|
||||
@@ -28,14 +35,25 @@ class HyundaiSettings(BrandSettings):
|
||||
elif ui_state.CP is not None:
|
||||
self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable
|
||||
|
||||
tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0")
|
||||
long_enabled = ui_state.has_longitudinal_control
|
||||
desc = tr("Accelerates and brakes the way your car's own cruise control does.")
|
||||
if not ui_state.is_offroad():
|
||||
desc = tr("This feature is unavailable while the car is onroad.")
|
||||
elif not long_enabled:
|
||||
desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
|
||||
|
||||
self.longitudinal_tuning_item.action_item.set_enabled(ui_state.is_offroad() and long_enabled)
|
||||
self.longitudinal_tuning_item.set_description(desc)
|
||||
long_tuning_descs = [
|
||||
tr("Your vehicle will use the Default longitudinal tuning."),
|
||||
tr("Your vehicle will use the Dynamic longitudinal tuning."),
|
||||
tr("Your vehicle will use the Predictive longitudinal tuning."),
|
||||
]
|
||||
long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0]
|
||||
|
||||
longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled
|
||||
if longitudinal_tuning_disabled:
|
||||
if not ui_state.is_offroad():
|
||||
long_tuning_desc = tr("This feature is unavailable while the car is onroad.")
|
||||
elif not long_enabled:
|
||||
long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
|
||||
|
||||
self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled)
|
||||
self.longitudinal_tuning_item.set_description(long_tuning_desc)
|
||||
self.longitudinal_tuning_item.show_description(True)
|
||||
self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param)
|
||||
self.longitudinal_tuning_item.set_visible(self.alpha_long_available)
|
||||
|
||||
@@ -7,7 +7,6 @@ See the LICENSE.md file in the root directory for more details.
|
||||
import pyray as rl
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.blendful import BlendfulRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import RadarTracks
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath
|
||||
|
||||
LANE_LINE_COLORS_SP = {
|
||||
@@ -19,5 +18,4 @@ LANE_LINE_COLORS_SP = {
|
||||
class ModelRendererSP:
|
||||
def __init__(self):
|
||||
self.rainbow_path = RainbowPath()
|
||||
self.radar_tracks = RadarTracks()
|
||||
self.blendful = BlendfulRenderer(rect_relative=True)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.robotic_view import RoboticOnroadView
|
||||
|
||||
__all__ = ["RoboticOnroadView"]
|
||||
@@ -1,137 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert, AlertRenderer
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import FontWeight, TextAlignment, gui_app
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
|
||||
|
||||
class RoboticAlertOverlay:
|
||||
"""Harmonized alert overlay that keeps robotic expressions visible while preserving safety readability."""
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._alert_source = AlertRenderer()
|
||||
self._prev_alert: Alert | None = None
|
||||
self._alpha_filter = FirstOrderFilter(0.0, 0.06, dt)
|
||||
|
||||
self._text1_label = UnifiedLabel(
|
||||
text="",
|
||||
font_size=44,
|
||||
font_weight=FontWeight.DISPLAY,
|
||||
alignment=TextAlignment.CENTER,
|
||||
line_height=0.9,
|
||||
)
|
||||
self._text2_label = UnifiedLabel(
|
||||
text="",
|
||||
font_size=26,
|
||||
font_weight=FontWeight.MEDIUM,
|
||||
alignment=TextAlignment.CENTER,
|
||||
line_height=0.95,
|
||||
)
|
||||
|
||||
def get_alert(self) -> Alert | None:
|
||||
alert = self._alert_source.get_alert(ui_state.sm)
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.onroad_brightness_handle_alerts(ui_state, alert)
|
||||
return alert
|
||||
|
||||
def render(self, rect: rl.Rectangle, alert: Alert | None) -> float:
|
||||
"""Render alert overlay and return current alpha (0..1) so caller can shift face if needed."""
|
||||
alpha = self._alpha_filter.update(1.0 if alert is not None else 0.0)
|
||||
if alert is not None:
|
||||
self._prev_alert = alert
|
||||
elif alpha > 0.02 and self._prev_alert is not None:
|
||||
alert = self._prev_alert
|
||||
else:
|
||||
self._prev_alert = None
|
||||
return 0.0
|
||||
|
||||
is_critical = alert.status == AlertStatus.critical
|
||||
is_prompt = alert.status == AlertStatus.userPrompt
|
||||
|
||||
if is_critical:
|
||||
pulse = 0.65 + 0.35 * (0.5 + 0.5 * math.sin(rl.get_time() * 14.0))
|
||||
# Pulsing red edge frame + bottom dark backing so red eyes + takeover text are unmistakable
|
||||
border_col = rl.Color(255, 25, 35, int(230 * pulse * alpha))
|
||||
rl.draw_rectangle_rounded_lines_ex(
|
||||
rl.Rectangle(rect.x + 3, rect.y + 3, rect.width - 6, rect.height - 6),
|
||||
0.16,
|
||||
12,
|
||||
10.0,
|
||||
border_col,
|
||||
)
|
||||
band_h = 98
|
||||
rl.draw_rectangle_gradient_v(
|
||||
int(rect.x),
|
||||
int(rect.y + rect.height - band_h - 18),
|
||||
int(rect.width),
|
||||
band_h + 18,
|
||||
rl.Color(180, 0, 15, 0),
|
||||
rl.Color(210, 0, 20, int(230 * alpha)),
|
||||
)
|
||||
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 4, band_h, alpha, big=True)
|
||||
elif is_prompt:
|
||||
band_h = 84
|
||||
rl.draw_rectangle_gradient_v(
|
||||
int(rect.x),
|
||||
int(rect.y + rect.height - band_h - 14),
|
||||
int(rect.width),
|
||||
band_h + 14,
|
||||
rl.Color(220, 95, 0, 0),
|
||||
rl.Color(235, 105, 0, int(215 * alpha)),
|
||||
)
|
||||
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 6, band_h, alpha, big=False)
|
||||
else:
|
||||
# Soft / normal alert: compact bottom pill leaving the expressive eyes unobstructed
|
||||
band_h = 66
|
||||
pill = rl.Rectangle(rect.x + 24, rect.y + rect.height - band_h - 8, rect.width - 48, band_h)
|
||||
rl.draw_rectangle_rounded(pill, 0.38, 12, rl.Color(24, 28, 34, int(215 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill, 0.38, 12, 2.0, rl.Color(255, 255, 255, int(45 * alpha)))
|
||||
self._draw_banner_text(rect, alert, pill.y + 6, band_h - 8, alpha, big=False)
|
||||
|
||||
return alpha
|
||||
|
||||
def _draw_banner_text(
|
||||
self,
|
||||
rect: rl.Rectangle,
|
||||
alert: Alert,
|
||||
top_y: float,
|
||||
band_h: float,
|
||||
alpha: float,
|
||||
big: bool,
|
||||
) -> None:
|
||||
text1 = alert.text1.lower()
|
||||
text2 = alert.text2.lower()
|
||||
|
||||
if big:
|
||||
font1 = 42 if len(text1) <= 18 else 34
|
||||
else:
|
||||
font1 = 34 if len(text1) <= 22 else 28
|
||||
|
||||
margin_x = 34
|
||||
w = rect.width - margin_x * 2
|
||||
|
||||
self._text1_label.set_text(text1)
|
||||
self._text1_label.set_font_size(font1)
|
||||
self._text1_label.set_text_color(rl.Color(255, 255, 255, int(245 * alpha)))
|
||||
self._text1_label.render(rl.Rectangle(rect.x + margin_x, top_y, w, band_h))
|
||||
|
||||
if text2:
|
||||
font2 = 24 if len(text2) <= 28 else 20
|
||||
self._text2_label.set_text(text2)
|
||||
self._text2_label.set_font_size(font2)
|
||||
self._text2_label.set_text_color(rl.Color(255, 255, 255, int(195 * alpha)))
|
||||
self._text2_label.render(rl.Rectangle(rect.x + margin_x, top_y + font1 + 2, w, max(24.0, band_h - font1)))
|
||||
@@ -1,712 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import groove_prism_color
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
EventName = log.OnroadEvent.EventName
|
||||
|
||||
SET_SPEED_NA = 255
|
||||
KM_TO_MILE = 0.621371
|
||||
|
||||
# Thresholds & hold durations (seconds)
|
||||
HARD_DECEL_THRESHOLD = -3.0 # m/s^2 triggers startled star eyes
|
||||
SHARP_ACCEL_THRESHOLD = 2.2 # m/s^2 triggers excited boost eyes
|
||||
STANDSTILL_POUT_DELAY = 8.0 # seconds at standstill before pouting
|
||||
STANDSTILL_SLEEPY_DELAY = 35.0 # seconds at standstill before sleepy
|
||||
CURVE_STEER_THRESHOLD = 15.0 # degrees steering angle for curve tracking
|
||||
SHARP_TURN_THRESHOLD = 45.0 # degrees steering angle for intense centrifugal lean
|
||||
SET_SPEED_SHOW_DURATION = 3.0 # seconds to show speed arc on set-speed change
|
||||
ENGAGE_HAPPY_DURATION = 0.9 # seconds of joyful crescent eyes on engage
|
||||
ENGAGE_SPEED_CONFIRM = 2.0 # seconds of speed readout right after happy engage
|
||||
STARTLED_HOLD_DURATION = 1.5 # seconds to hold star-shock expression
|
||||
BOOST_HOLD_DURATION = 1.2 # seconds to hold sharp-accel boost expression
|
||||
LOVE_HOLD_DURATION = 1.6 # seconds to hold heart/pet expression
|
||||
MANUAL_SPEED_PEEK_DURATION = 4.0 # seconds for swipe-up speed peek
|
||||
|
||||
|
||||
class RoboticMood(Enum):
|
||||
CRITICAL = "critical"
|
||||
DISTRACTED = "distracted"
|
||||
USER_PROMPT = "user_prompt"
|
||||
STARTLED_STARS = "startled_stars"
|
||||
LANE_CHANGE = "lane_change"
|
||||
BLIND_SPOT = "blind_spot"
|
||||
BOOKMARK_LOVE = "bookmark_love"
|
||||
HAPPY_ENGAGE = "happy_engage"
|
||||
BOOST_ACCEL = "boost_accel"
|
||||
TURN_SIGNAL = "turn_signal"
|
||||
SPEED_DISPLAY = "speed_display"
|
||||
POUT_STANDSTILL = "pout_standstill"
|
||||
SLEEPY = "sleepy"
|
||||
SHARP_TURN = "sharp_turn"
|
||||
CURVE_FOCUS = "curve_focus"
|
||||
MUSIC_GROOVE = "music_groove"
|
||||
CRUISING_HAPPY = "cruising_happy"
|
||||
IDLE_CURIOUS = "idle_curious"
|
||||
|
||||
|
||||
class IdleAction(Enum):
|
||||
"""Playful autonomous micro-behaviors during normal cruising & idle driving."""
|
||||
NONE = "none"
|
||||
HAPPY_SQUINT = "happy_squint"
|
||||
CURIOUS_LOOK = "curious_look"
|
||||
CHEEKY_WINK = "cheeky_wink"
|
||||
GROOVE_BOB = "groove_bob"
|
||||
|
||||
|
||||
class EyeGlyph(Enum):
|
||||
ROUND_RECT = "round_rect"
|
||||
STAR = "star"
|
||||
HEART = "heart"
|
||||
CRESCENT = "crescent"
|
||||
ARROW_LEFT = "arrow_left"
|
||||
ARROW_RIGHT = "arrow_right"
|
||||
LASER_ALERT = "laser_alert"
|
||||
SPARKLE_BOOST = "sparkle_boost"
|
||||
|
||||
|
||||
class MouthGlyph(Enum):
|
||||
NONE = "none"
|
||||
SMILE = "smile"
|
||||
BIG_GRIN = "big_grin"
|
||||
FROWN = "frown"
|
||||
SURPRISED = "surprised"
|
||||
|
||||
|
||||
# Dynamic status & mood palette (RGB tuples)
|
||||
PALETTE = {
|
||||
"engaged": (64, 240, 226), # EMO vibrant cyan-emerald
|
||||
"lat_only": (255, 212, 178), # Reference-video warm peach
|
||||
"long_only": (92, 198, 255), # Sky cyan
|
||||
"disengaged": (218, 232, 248), # Soft ice white
|
||||
"override": (255, 196, 68), # Warm amber
|
||||
"boost": (76, 178, 255), # Electric boost blue
|
||||
"prompt": (255, 125, 20), # Vivid orange
|
||||
"critical": (255, 38, 48), # Alert red
|
||||
"love": (255, 112, 168), # Rose pink
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class EyeTarget:
|
||||
width: float = 104.0
|
||||
height: float = 112.0
|
||||
roundness: float = 0.62 # Bubbly chunky squircle
|
||||
top_lid: float = 0.0 # 0..1 fraction covered from top
|
||||
bottom_lid: float = 0.0 # 0..1 fraction covered from bottom
|
||||
top_slant: float = 0.0 # degrees (+ = angry/inward, - = sad/outward)
|
||||
gaze_x: float = 0.0 # px shift (-42..+42)
|
||||
gaze_y: float = 0.0 # px shift (-22..+22)
|
||||
bounce_y: float = 0.0 # vertical expressiveness offset
|
||||
tilt_y: float = 0.0 # vertical asymmetry between left & right eye (playful head tilt)
|
||||
scale_x: float = 1.0 # squash-and-stretch horizontal multiplier
|
||||
scale_y: float = 1.0 # squash-and-stretch vertical multiplier
|
||||
wink_right: bool = False # cute asymmetric wink on bookmark or cheeky idle wink
|
||||
squish_force: float = 0.0 # -1..+1 centrifugal push (-1 left wall, +1 right wall)
|
||||
pitch_offset_y: float = 0.0 # px vertical bob from pitch / pitch-rate (bumps, hills, dive)
|
||||
glyph: EyeGlyph = EyeGlyph.ROUND_RECT
|
||||
mouth: MouthGlyph = MouthGlyph.NONE
|
||||
color: tuple[int, int, int] = PALETTE["engaged"]
|
||||
pulse_speed: float = 0.0 # Hz for alert pulsing
|
||||
blind_spot_side: int = 0 # -1 left, +1 right, 0 none
|
||||
blinker_side: int = 0 # -1 left, +1 right, 0 none
|
||||
show_speed_lines: bool = False
|
||||
show_zzz: bool = False
|
||||
show_hearts: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class DrivingSnapshot:
|
||||
"""Pure-data snapshot of driving signals for deterministic mood evaluation & testing."""
|
||||
started: bool = True
|
||||
engaged: bool = False
|
||||
status: UIStatus = UIStatus.DISENGAGED
|
||||
v_ego: float = 0.0 # m/s
|
||||
a_ego: float = 0.0 # m/s^2
|
||||
standstill: bool = False
|
||||
steering_angle_deg: float = 0.0
|
||||
yaw_rate: float = 0.0 # rad/s (+ = turning left -> centrifugal push right)
|
||||
pitch_rad: float = 0.0 # rad (+ = nose up / hill climb)
|
||||
pitch_rate: float = 0.0 # rad/s (bumps, crests, braking dive)
|
||||
curvature: float = 0.0 # rad/m fallback for centrifugal accel
|
||||
set_speed_kph: float = SET_SPEED_NA
|
||||
is_metric: bool = False
|
||||
left_blinker: bool = False
|
||||
right_blinker: bool = False
|
||||
left_blindspot: bool = False
|
||||
right_blindspot: bool = False
|
||||
pre_lane_change_left: bool = False
|
||||
pre_lane_change_right: bool = False
|
||||
lane_change: bool = False
|
||||
lane_change_blocked: bool = False
|
||||
dm_alert_level: int = 0 # 0=none, 1=warn, 2=critical
|
||||
alert: Alert | None = None
|
||||
music: MusicState | None = None
|
||||
|
||||
|
||||
class RoboticMoodEngine:
|
||||
"""Priority-based EMO-inspired mood & lively autonomous personality state machine."""
|
||||
|
||||
def __init__(self, rng: random.Random | None = None):
|
||||
self._rng = rng or random.Random()
|
||||
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
|
||||
self.idle_action: IdleAction = IdleAction.NONE
|
||||
self.showing_speed: bool = False
|
||||
self.speed_reason: str = "" # "set_speed", "engage", "peek"
|
||||
self.cruising_smoothly: bool = False
|
||||
|
||||
self._prev_engaged: bool = False
|
||||
self._prev_set_speed: float = SET_SPEED_NA
|
||||
self._standstill_since: float | None = None
|
||||
self._last_lane_dir: int = 0 # -1 left, +1 right
|
||||
|
||||
# Hold / effect timers (monotonic timestamps)
|
||||
self._startled_until: float = 0.0
|
||||
self._boost_until: float = 0.0
|
||||
self._love_until: float = 0.0
|
||||
self._love_wink: bool = False
|
||||
self._happy_engage_until: float = 0.0
|
||||
self._speed_display_until: float = 0.0
|
||||
|
||||
# Blink, gaze, and playful idle personality schedulers
|
||||
now = time.monotonic()
|
||||
self._next_blink_at: float = now + self._rng.uniform(1.8, 3.6)
|
||||
self._blink_end_at: float = 0.0
|
||||
self._blink_rebound_until: float = 0.0
|
||||
self._double_blink_pending: bool = False
|
||||
|
||||
self._next_glance_at: float = now + self._rng.uniform(1.2, 2.6)
|
||||
self._idle_gaze_x: float = 0.0
|
||||
self._idle_gaze_y: float = 0.0
|
||||
self._idle_tilt_y: float = 0.0
|
||||
|
||||
self._next_idle_action_at: float = now + self._rng.uniform(2.2, 3.8)
|
||||
self._idle_action_until: float = 0.0
|
||||
self._idle_action_dir: float = 1.0
|
||||
|
||||
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._love_until = t + LOVE_HOLD_DURATION
|
||||
self._love_wink = wink
|
||||
|
||||
def trigger_speed_peek(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._speed_display_until = max(self._speed_display_until, t + MANUAL_SPEED_PEEK_DURATION)
|
||||
self.speed_reason = "peek"
|
||||
|
||||
def trigger_startled(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
|
||||
|
||||
def trigger_boost(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
|
||||
|
||||
def _status_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
|
||||
if snap.status == UIStatus.ENGAGED:
|
||||
return PALETTE["engaged"]
|
||||
if snap.status == UIStatus.LAT_ONLY:
|
||||
return PALETTE["lat_only"]
|
||||
if snap.status == UIStatus.LONG_ONLY:
|
||||
return PALETTE["long_only"]
|
||||
if snap.status == UIStatus.OVERRIDE:
|
||||
return PALETTE["override"]
|
||||
return PALETTE["disengaged"]
|
||||
|
||||
def _update_blink_and_personality(self, now: float, sleepy: bool) -> tuple[float, float, float]:
|
||||
"""Returns (blink_closure, squash_x, stretch_y) and advances idle glances & micro-actions."""
|
||||
blink_closure = 0.0
|
||||
squash_x = 1.0
|
||||
stretch_y = 1.0
|
||||
|
||||
if now < self._blink_end_at:
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.16
|
||||
stretch_y = 0.86
|
||||
elif now < self._blink_rebound_until:
|
||||
# Juicy bubbly pop-open after blink
|
||||
squash_x = 0.93
|
||||
stretch_y = 1.10
|
||||
elif now >= self._next_blink_at:
|
||||
blink_dur = 0.22 if sleepy else 0.11
|
||||
self._blink_end_at = now + blink_dur
|
||||
self._blink_rebound_until = self._blink_end_at + 0.12
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.16
|
||||
stretch_y = 0.86
|
||||
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.30:
|
||||
self._double_blink_pending = True
|
||||
self._next_blink_at = self._blink_end_at + 0.13
|
||||
else:
|
||||
self._double_blink_pending = False
|
||||
lo, hi = (1.6, 3.0) if sleepy else (2.2, 4.4)
|
||||
self._next_blink_at = self._blink_end_at + self._rng.uniform(lo, hi)
|
||||
|
||||
if now >= self._next_glance_at:
|
||||
roll = self._rng.random()
|
||||
if roll < 0.28:
|
||||
self._idle_gaze_x = 0.0
|
||||
self._idle_gaze_y = 0.0
|
||||
self._idle_tilt_y = 0.0
|
||||
else:
|
||||
self._idle_gaze_x = self._rng.uniform(-34.0, 34.0)
|
||||
self._idle_gaze_y = self._rng.uniform(-12.0, 10.0)
|
||||
self._idle_tilt_y = self._rng.uniform(-9.0, 9.0)
|
||||
self._next_glance_at = now + self._rng.uniform(1.3, 2.8)
|
||||
|
||||
# Playful autonomous micro-behaviors during normal cruising/idle
|
||||
if now >= self._idle_action_until:
|
||||
self.idle_action = IdleAction.NONE
|
||||
if not sleepy and now >= self._next_idle_action_at:
|
||||
choice = self._rng.choice([
|
||||
IdleAction.HAPPY_SQUINT,
|
||||
IdleAction.CURIOUS_LOOK,
|
||||
IdleAction.CHEEKY_WINK,
|
||||
IdleAction.GROOVE_BOB,
|
||||
])
|
||||
self.idle_action = choice
|
||||
self._idle_action_dir = -1.0 if self._rng.random() < 0.5 else 1.0
|
||||
dur = {
|
||||
IdleAction.HAPPY_SQUINT: 0.80,
|
||||
IdleAction.CURIOUS_LOOK: 1.50,
|
||||
IdleAction.CHEEKY_WINK: 0.55,
|
||||
IdleAction.GROOVE_BOB: 1.80,
|
||||
}[choice]
|
||||
self._idle_action_until = now + dur
|
||||
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(2.0, 3.8)
|
||||
|
||||
return blink_closure, squash_x, stretch_y
|
||||
|
||||
def update(self, snap: DrivingSnapshot, now: float | None = None) -> EyeTarget:
|
||||
t = time.monotonic() if now is None else now
|
||||
|
||||
# Track standstill duration
|
||||
if snap.standstill or not snap.started:
|
||||
if self._standstill_since is None:
|
||||
self._standstill_since = t
|
||||
else:
|
||||
self._standstill_since = None
|
||||
standstill_dur = (t - self._standstill_since) if self._standstill_since is not None else 0.0
|
||||
|
||||
# Track engagement rising edge
|
||||
if snap.engaged and not self._prev_engaged:
|
||||
self._happy_engage_until = t + ENGAGE_HAPPY_DURATION
|
||||
self._speed_display_until = max(
|
||||
self._speed_display_until,
|
||||
t + ENGAGE_HAPPY_DURATION + ENGAGE_SPEED_CONFIRM,
|
||||
)
|
||||
self.speed_reason = "engage"
|
||||
self._prev_engaged = snap.engaged
|
||||
|
||||
# Track set-speed change while cruise is set
|
||||
cruise_set = 0 < snap.set_speed_kph < SET_SPEED_NA
|
||||
if cruise_set and snap.set_speed_kph != self._prev_set_speed and self._prev_set_speed != SET_SPEED_NA:
|
||||
self._speed_display_until = max(self._speed_display_until, t + SET_SPEED_SHOW_DURATION)
|
||||
self.speed_reason = "set_speed"
|
||||
self._prev_set_speed = snap.set_speed_kph
|
||||
|
||||
# Track startling events & sharp acceleration
|
||||
if snap.a_ego < HARD_DECEL_THRESHOLD or snap.lane_change_blocked:
|
||||
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
|
||||
elif snap.a_ego > SHARP_ACCEL_THRESHOLD and not snap.standstill:
|
||||
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
|
||||
|
||||
# Track lane change direction
|
||||
if snap.pre_lane_change_left:
|
||||
self._last_lane_dir = -1
|
||||
elif snap.pre_lane_change_right:
|
||||
self._last_lane_dir = 1
|
||||
elif not snap.lane_change:
|
||||
self._last_lane_dir = 0
|
||||
|
||||
blinker_side = -1 if snap.left_blinker else (1 if snap.right_blinker else 0)
|
||||
|
||||
bsm_side = 0
|
||||
if snap.left_blindspot and (snap.left_blinker or snap.pre_lane_change_left):
|
||||
bsm_side = -1
|
||||
elif snap.right_blindspot and (snap.right_blinker or snap.pre_lane_change_right):
|
||||
bsm_side = 1
|
||||
elif snap.left_blindspot and not snap.standstill:
|
||||
bsm_side = -1
|
||||
elif snap.right_blindspot and not snap.standstill:
|
||||
bsm_side = 1
|
||||
|
||||
self.cruising_smoothly = snap.engaged and not snap.standstill and abs(snap.a_ego) < 0.8
|
||||
|
||||
# Evaluate mood priority
|
||||
alert = snap.alert
|
||||
alert_status = alert.status if alert is not None else -1
|
||||
alert_type = alert.alert_type if alert is not None else ""
|
||||
is_dm_alert = snap.dm_alert_level >= 1 or "Distracted" in alert_type or "Unresponsive" in alert_type
|
||||
|
||||
self.showing_speed = False
|
||||
|
||||
# Compute physical centrifugal force (-1 = pushed left, +1 = pushed right) & pitch bob
|
||||
# Positive yaw_rate (turning left) pushes the bot toward the right wall (+1)
|
||||
effective_yaw = snap.yaw_rate
|
||||
if abs(effective_yaw) < 1e-4 and abs(snap.curvature) > 1e-5:
|
||||
effective_yaw = snap.v_ego * snap.curvature
|
||||
lat_accel = snap.v_ego * effective_yaw # m/s^2
|
||||
# Blend true lateral G with direct gyro yaw-rate so even tight low-speed turns feel lively
|
||||
centrifugal_raw = (lat_accel / 4.2) + (effective_yaw / 1.4) * 0.35
|
||||
if abs(centrifugal_raw) < 0.05 and abs(snap.steering_angle_deg) > CURVE_STEER_THRESHOLD and not snap.standstill:
|
||||
# Fallback for desktop previews/simulators without IMU data
|
||||
centrifugal_raw = max(-1.0, min(1.0, (snap.steering_angle_deg / 90.0) * max(0.35, snap.v_ego / 20.0)))
|
||||
squish_force = max(-1.0, min(1.0, centrifugal_raw)) if not snap.standstill else 0.0
|
||||
if abs(squish_force) < 0.08:
|
||||
squish_force = 0.0
|
||||
pitch_offset_y = max(-22.0, min(22.0, snap.pitch_rad * 55.0 + snap.pitch_rate * 20.0))
|
||||
|
||||
if alert is not None and alert_status == AlertStatus.critical:
|
||||
self.mood = RoboticMood.CRITICAL
|
||||
elif is_dm_alert:
|
||||
self.mood = RoboticMood.DISTRACTED
|
||||
elif alert is not None and alert_status == AlertStatus.userPrompt:
|
||||
self.mood = RoboticMood.USER_PROMPT
|
||||
elif t < self._startled_until:
|
||||
self.mood = RoboticMood.STARTLED_STARS
|
||||
elif snap.pre_lane_change_left or snap.pre_lane_change_right or snap.lane_change:
|
||||
self.mood = RoboticMood.LANE_CHANGE
|
||||
elif bsm_side != 0 and blinker_side != 0:
|
||||
self.mood = RoboticMood.BLIND_SPOT
|
||||
elif t < self._love_until:
|
||||
self.mood = RoboticMood.BOOKMARK_LOVE
|
||||
elif t < self._happy_engage_until:
|
||||
self.mood = RoboticMood.HAPPY_ENGAGE
|
||||
elif t < self._speed_display_until and snap.started:
|
||||
self.mood = RoboticMood.SPEED_DISPLAY
|
||||
self.showing_speed = True
|
||||
elif t < self._boost_until:
|
||||
self.mood = RoboticMood.BOOST_ACCEL
|
||||
elif blinker_side != 0:
|
||||
self.mood = RoboticMood.TURN_SIGNAL
|
||||
elif (abs(squish_force) >= 0.42 or abs(snap.steering_angle_deg) >= SHARP_TURN_THRESHOLD) and not snap.standstill:
|
||||
self.mood = RoboticMood.SHARP_TURN
|
||||
elif (abs(squish_force) >= 0.18 or abs(snap.steering_angle_deg) > CURVE_STEER_THRESHOLD) and not snap.standstill:
|
||||
self.mood = RoboticMood.CURVE_FOCUS
|
||||
elif snap.started and snap.music is not None and snap.music.is_music and alert is None:
|
||||
self.mood = RoboticMood.MUSIC_GROOVE
|
||||
elif not snap.started or standstill_dur >= STANDSTILL_SLEEPY_DELAY:
|
||||
self.mood = RoboticMood.SLEEPY
|
||||
elif standstill_dur >= STANDSTILL_POUT_DELAY:
|
||||
self.mood = RoboticMood.POUT_STANDSTILL
|
||||
elif snap.engaged:
|
||||
self.mood = RoboticMood.CRUISING_HAPPY
|
||||
else:
|
||||
self.mood = RoboticMood.IDLE_CURIOUS
|
||||
|
||||
base_color = self._status_color(snap)
|
||||
blink, squash_x, stretch_y = self._update_blink_and_personality(t, sleepy=(self.mood == RoboticMood.SLEEPY))
|
||||
|
||||
# Lively, clearly visible breathing & energetic bounce so the face is always bubbling with life
|
||||
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
|
||||
breathe_y = math.sin(t * 2.8 * energy) * 6.5 + math.sin(t * 1.3) * 2.5
|
||||
breathe_scale = 1.0 + 0.035 * math.sin(t * 2.8 * energy - 0.35)
|
||||
micro_drift_x = math.sin(t * 1.1) * 6.0
|
||||
|
||||
# Steering-coupled gaze (clamped to [-40, +40])
|
||||
steer_gaze = max(-40.0, min(40.0, -snap.steering_angle_deg * 0.78))
|
||||
|
||||
target = EyeTarget(
|
||||
color=base_color,
|
||||
bounce_y=breathe_y,
|
||||
scale_x=squash_x * breathe_scale,
|
||||
scale_y=stretch_y * (2.0 - breathe_scale),
|
||||
squish_force=squish_force,
|
||||
pitch_offset_y=pitch_offset_y,
|
||||
blind_spot_side=bsm_side,
|
||||
blinker_side=blinker_side,
|
||||
)
|
||||
|
||||
if self.mood == RoboticMood.CRITICAL:
|
||||
target.glyph = EyeGlyph.LASER_ALERT
|
||||
target.color = PALETTE["critical"]
|
||||
target.width = 114.0
|
||||
target.height = 84.0
|
||||
target.roundness = 0.42
|
||||
target.top_lid = 0.28
|
||||
target.top_slant = 18.0
|
||||
target.pulse_speed = 5.5
|
||||
target.bounce_y = math.sin(t * 28.0) * 3.5
|
||||
|
||||
elif self.mood == RoboticMood.DISTRACTED:
|
||||
target.color = PALETTE["prompt"]
|
||||
target.width = 108.0
|
||||
target.height = 96.0
|
||||
target.roundness = 0.48
|
||||
target.top_lid = 0.32
|
||||
target.top_slant = 12.0
|
||||
target.gaze_x = math.sin(t * 5.2) * 18.0
|
||||
target.mouth = MouthGlyph.FROWN
|
||||
target.pulse_speed = 2.5
|
||||
|
||||
elif self.mood == RoboticMood.USER_PROMPT:
|
||||
target.color = PALETTE["prompt"]
|
||||
target.width = 108.0
|
||||
target.height = 120.0
|
||||
target.top_lid = 0.06
|
||||
target.top_slant = -6.0
|
||||
target.gaze_x = micro_drift_x
|
||||
target.pulse_speed = 1.8
|
||||
|
||||
elif self.mood == RoboticMood.STARTLED_STARS:
|
||||
target.glyph = EyeGlyph.STAR
|
||||
target.color = PALETTE["override"]
|
||||
target.width = 114.0
|
||||
target.height = 114.0
|
||||
target.mouth = MouthGlyph.SURPRISED
|
||||
target.bounce_y = math.sin(t * 26.0) * 6.0
|
||||
target.scale_x = 1.0 + 0.08 * math.sin(t * 22.0)
|
||||
target.scale_y = 1.0 - 0.08 * math.sin(t * 22.0)
|
||||
|
||||
elif self.mood == RoboticMood.LANE_CHANGE:
|
||||
direction = -1 if snap.pre_lane_change_left else (1 if snap.pre_lane_change_right else self._last_lane_dir or 1)
|
||||
target.glyph = EyeGlyph.ARROW_LEFT if direction < 0 else EyeGlyph.ARROW_RIGHT
|
||||
target.gaze_x = direction * 32.0 + math.sin(t * 6.5) * 5.0
|
||||
target.height = 106.0
|
||||
target.top_lid = 0.10
|
||||
target.tilt_y = direction * 7.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.BLIND_SPOT:
|
||||
target.color = PALETTE["override"]
|
||||
target.gaze_x = bsm_side * 38.0
|
||||
target.height = 102.0
|
||||
target.top_lid = 0.22
|
||||
target.top_slant = 9.0
|
||||
target.pulse_speed = 3.2
|
||||
|
||||
elif self.mood == RoboticMood.BOOKMARK_LOVE:
|
||||
target.glyph = EyeGlyph.HEART
|
||||
target.color = PALETTE["love"]
|
||||
target.width = 114.0
|
||||
target.height = 114.0
|
||||
target.wink_right = self._love_wink
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 10.5)) * 15.0
|
||||
target.show_hearts = True
|
||||
|
||||
elif self.mood == RoboticMood.HAPPY_ENGAGE:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
target.color = PALETTE["engaged"]
|
||||
target.width = 116.0
|
||||
target.height = 100.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 9.5)) * 16.0
|
||||
|
||||
elif self.mood == RoboticMood.BOOST_ACCEL:
|
||||
target.glyph = EyeGlyph.SPARKLE_BOOST
|
||||
target.color = PALETTE["boost"]
|
||||
target.width = 116.0
|
||||
target.height = 120.0
|
||||
target.gaze_y = -7.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = math.sin(t * 18.0) * 5.0
|
||||
target.show_speed_lines = True
|
||||
|
||||
elif self.mood == RoboticMood.TURN_SIGNAL:
|
||||
beat = 0.5 + 0.5 * math.sin(t * 8.4)
|
||||
target.gaze_x = blinker_side * (22.0 + 14.0 * beat)
|
||||
target.tilt_y = blinker_side * 8.0
|
||||
target.width = 106.0
|
||||
target.height = 108.0
|
||||
target.top_lid = 0.08
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.POUT_STANDSTILL:
|
||||
target.width = 98.0
|
||||
target.height = 84.0
|
||||
target.roundness = 0.34
|
||||
target.top_lid = 0.26 + 0.05 * math.sin(t * 1.8)
|
||||
target.gaze_x = self._idle_gaze_x * 0.75 + micro_drift_x
|
||||
target.gaze_y = 6.0
|
||||
target.tilt_y = self._idle_tilt_y * 0.7
|
||||
target.mouth = MouthGlyph.FROWN
|
||||
|
||||
elif self.mood == RoboticMood.SLEEPY:
|
||||
target.width = 104.0
|
||||
target.height = 76.0
|
||||
target.roundness = 0.45
|
||||
target.top_lid = 0.58 + 0.09 * math.sin(t * 1.5)
|
||||
target.bottom_lid = 0.14
|
||||
target.gaze_y = 8.0
|
||||
target.gaze_x = math.sin(t * 0.7) * 8.0
|
||||
target.bounce_y = math.sin(t * 1.5) * 6.0
|
||||
target.show_zzz = True
|
||||
|
||||
elif self.mood == RoboticMood.SHARP_TURN:
|
||||
intensity = max(abs(squish_force), min(1.0, abs(snap.steering_angle_deg) / 85.0))
|
||||
push_dir = 1.0 if squish_force > 0 else (-1.0 if squish_force < 0 else (1.0 if snap.steering_angle_deg > 0 else -1.0))
|
||||
target.squish_force = push_dir * intensity
|
||||
target.width = 108.0
|
||||
target.height = 104.0
|
||||
target.top_lid = 0.10 + 0.14 * intensity
|
||||
target.top_slant = 5.0 + 7.0 * intensity
|
||||
target.gaze_x = push_dir * 12.0 # squish renderer handles primary wall slide
|
||||
target.gaze_y = -3.0
|
||||
target.tilt_y = push_dir * (8.0 + 8.0 * intensity)
|
||||
target.mouth = MouthGlyph.SURPRISED if intensity >= 0.62 else MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.CURVE_FOCUS:
|
||||
intensity = max(abs(squish_force), min(0.5, abs(snap.steering_angle_deg) / 70.0))
|
||||
push_dir = 1.0 if squish_force > 0 else (-1.0 if squish_force < 0 else (1.0 if snap.steering_angle_deg > 0 else -1.0))
|
||||
target.squish_force = push_dir * intensity
|
||||
target.width = 106.0
|
||||
target.height = 106.0
|
||||
target.top_lid = 0.08
|
||||
target.gaze_x = push_dir * 8.0
|
||||
target.gaze_y = -2.0
|
||||
target.tilt_y = push_dir * (5.0 + 6.0 * intensity)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.MUSIC_GROOVE:
|
||||
m = snap.music or MusicState()
|
||||
sway = math.sin(m.groove_phase)
|
||||
beat = m.beat_pulse
|
||||
target.color = groove_prism_color(t)
|
||||
target.width = 108.0
|
||||
target.height = 112.0
|
||||
target.gaze_x = sway * 22.0
|
||||
target.gaze_y = -6.0 - beat * 6.0
|
||||
target.tilt_y = sway * 12.0
|
||||
target.bounce_y = -14.0 * beat - abs(sway) * 6.0 - 8.0
|
||||
target.scale_x = 1.0 + 0.11 * beat
|
||||
target.scale_y = 1.0 - 0.08 * beat
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
if beat > 0.58:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
|
||||
elif self.mood == RoboticMood.CRUISING_HAPPY:
|
||||
target.width = 106.0
|
||||
target.height = 114.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
target.gaze_x = steer_gaze * 0.35 + self._idle_gaze_x * 0.65 + micro_drift_x
|
||||
target.gaze_y = self._idle_gaze_y * 0.65
|
||||
target.tilt_y = self._idle_tilt_y * 0.75 + math.sin(t * 1.6) * 3.0
|
||||
self._apply_idle_action(target, t)
|
||||
|
||||
else: # IDLE_CURIOUS or SPEED_DISPLAY fallback
|
||||
target.width = 104.0
|
||||
target.height = 110.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
target.gaze_x = self._idle_gaze_x + micro_drift_x
|
||||
target.gaze_y = self._idle_gaze_y
|
||||
target.tilt_y = self._idle_tilt_y + math.sin(t * 1.4) * 3.0
|
||||
self._apply_idle_action(target, t)
|
||||
|
||||
# Apply natural blink closure to standard rounded-rect eyes
|
||||
if target.glyph == EyeGlyph.ROUND_RECT and not target.wink_right and blink > 0.0:
|
||||
target.top_lid = max(target.top_lid, 0.52 * blink)
|
||||
target.bottom_lid = max(target.bottom_lid, 0.48 * blink)
|
||||
|
||||
return target
|
||||
|
||||
def _apply_idle_action(self, target: EyeTarget, t: float) -> None:
|
||||
"""Layer bubbly autonomous micro-behaviors onto normal cruising/idle states."""
|
||||
if self.idle_action == IdleAction.HAPPY_SQUINT:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 9.0)) * 12.0
|
||||
elif self.idle_action == IdleAction.CURIOUS_LOOK:
|
||||
target.gaze_x = self._idle_action_dir * 34.0
|
||||
target.gaze_y = -6.0
|
||||
target.tilt_y = self._idle_action_dir * 10.0
|
||||
target.height = 118.0
|
||||
elif self.idle_action == IdleAction.CHEEKY_WINK:
|
||||
target.wink_right = True
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.tilt_y = 6.0
|
||||
target.bounce_y = -8.0
|
||||
elif self.idle_action == IdleAction.GROOVE_BOB:
|
||||
target.bounce_y = math.sin(t * 7.2) * 11.0
|
||||
target.tilt_y = math.sin(t * 3.6) * 8.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
|
||||
|
||||
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
|
||||
"""Build a DrivingSnapshot safely from ui_state.sm."""
|
||||
sm = ui_state.sm
|
||||
cs = sm["carState"]
|
||||
controls = sm["controlsState"]
|
||||
dm = sm["driverMonitoringState"]
|
||||
events = sm["onroadEvents"]
|
||||
|
||||
v_cruise_cluster = cs.vCruiseCluster
|
||||
set_speed_kph = controls.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
|
||||
|
||||
pre_left = any(e.name == EventName.preLaneChangeLeft for e in events)
|
||||
pre_right = any(e.name == EventName.preLaneChangeRight for e in events)
|
||||
lane_change = any(e.name == EventName.laneChange for e in events)
|
||||
lane_blocked = any(e.name == EventName.laneChangeBlocked for e in events)
|
||||
|
||||
v_ego_cluster = cs.vEgoCluster
|
||||
v_ego = v_ego_cluster if v_ego_cluster != 0.0 else cs.vEgo
|
||||
|
||||
# Extract pitch, pitch rate, and yaw rate from modelV2 orientation + gyroscope (104 Hz)
|
||||
yaw_rate = 0.0
|
||||
pitch_rad = 0.0
|
||||
pitch_rate = 0.0
|
||||
if sm.valid.get("modelV2"):
|
||||
mv2 = sm["modelV2"]
|
||||
if len(mv2.orientation.y) > 0:
|
||||
pitch_rad = float(mv2.orientation.y[0])
|
||||
if len(mv2.orientationRate.y) > 0 and len(mv2.orientationRate.z) > 0:
|
||||
pitch_rate = float(mv2.orientationRate.y[0])
|
||||
yaw_rate = float(mv2.orientationRate.z[0])
|
||||
if sm.valid.get("gyroscope"):
|
||||
gv = sm["gyroscope"].gyro.v
|
||||
if len(gv) >= 3:
|
||||
# Blend crisp high-rate gyro directly with model orientation rate
|
||||
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
|
||||
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
|
||||
|
||||
return DrivingSnapshot(
|
||||
started=ui_state.started,
|
||||
engaged=ui_state.engaged,
|
||||
status=ui_state.status,
|
||||
v_ego=max(0.0, float(v_ego)),
|
||||
a_ego=float(cs.aEgo),
|
||||
standstill=bool(cs.standstill),
|
||||
steering_angle_deg=float(cs.steeringAngleDeg),
|
||||
yaw_rate=yaw_rate,
|
||||
pitch_rad=pitch_rad,
|
||||
pitch_rate=pitch_rate,
|
||||
curvature=float(controls.curvature) if sm.valid.get("controlsState") else 0.0,
|
||||
set_speed_kph=float(set_speed_kph),
|
||||
is_metric=bool(ui_state.is_metric),
|
||||
left_blinker=bool(cs.leftBlinker),
|
||||
right_blinker=bool(cs.rightBlinker),
|
||||
left_blindspot=bool(cs.leftBlindspot),
|
||||
right_blindspot=bool(cs.rightBlindspot),
|
||||
pre_lane_change_left=pre_left,
|
||||
pre_lane_change_right=pre_right,
|
||||
lane_change=lane_change,
|
||||
lane_change_blocked=lane_blocked,
|
||||
dm_alert_level=int(dm.alertLevel.raw) if sm.valid["driverMonitoringState"] else 0,
|
||||
alert=alert,
|
||||
)
|
||||
|
||||
|
||||
def display_speed_and_set_speed(snap: DrivingSnapshot) -> tuple[int, int | None]:
|
||||
"""Convert current speed and cruise set speed to display units (mph or km/h)."""
|
||||
speed_conv = CV.MS_TO_KPH if snap.is_metric else CV.MS_TO_MPH
|
||||
cur_speed = round(max(0.0, snap.v_ego * speed_conv))
|
||||
if 0 < snap.set_speed_kph < SET_SPEED_NA:
|
||||
set_val = snap.set_speed_kph if snap.is_metric else snap.set_speed_kph * KM_TO_MILE
|
||||
return cur_speed, round(set_val)
|
||||
return cur_speed, None
|
||||
@@ -1,388 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
EyeGlyph,
|
||||
EyeTarget,
|
||||
MouthGlyph,
|
||||
)
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
|
||||
|
||||
class ProceduralFaceRenderer:
|
||||
"""60 FPS bubbly EMO-inspired procedural vector face renderer for 536x240 MICI OLED."""
|
||||
|
||||
EYE_SPACING = 166.0 # distance between left and right eye centers
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
# Bubbly spring-overshoot filters for juicy EMO-style squash-and-stretch motion
|
||||
self._w = BounceFilter(104.0, 0.065, dt, bounce=4.2)
|
||||
self._h = BounceFilter(112.0, 0.065, dt, bounce=4.2)
|
||||
self._gaze_x = BounceFilter(0.0, 0.075, dt, bounce=3.4)
|
||||
self._gaze_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
|
||||
self._bounce_y = BounceFilter(0.0, 0.055, dt, bounce=4.4)
|
||||
self._tilt_y = BounceFilter(0.0, 0.075, dt, bounce=3.2)
|
||||
self._scale_x = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._scale_y = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._squish = BounceFilter(0.0, 0.075, dt, bounce=3.6)
|
||||
self._pitch_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
|
||||
|
||||
# Crisp first-order filters for eyelids, roundness, and smooth color blending
|
||||
self._roundness = FirstOrderFilter(0.62, 0.08, dt)
|
||||
self._top_lid = FirstOrderFilter(0.0, 0.032, dt)
|
||||
self._bottom_lid = FirstOrderFilter(0.0, 0.032, dt)
|
||||
self._top_slant = FirstOrderFilter(0.0, 0.065, dt)
|
||||
self._r = FirstOrderFilter(218.0, 0.14, dt)
|
||||
self._g = FirstOrderFilter(232.0, 0.14, dt)
|
||||
self._b = FirstOrderFilter(248.0, 0.14, dt)
|
||||
self._bsm_alpha = FirstOrderFilter(0.0, 0.07, dt)
|
||||
self._blinker_alpha = FirstOrderFilter(0.0, 0.06, dt)
|
||||
|
||||
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
|
||||
|
||||
def render(self, rect: rl.Rectangle, target: EyeTarget, alpha: float = 1.0, y_shift: float = 0.0) -> None:
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
|
||||
# Update bubbly & smooth filters
|
||||
w = max(24.0, self._w.update(target.width) * self._scale_x.update(target.scale_x))
|
||||
h = max(20.0, self._h.update(target.height) * self._scale_y.update(target.scale_y))
|
||||
roundness = max(0.15, min(0.85, self._roundness.update(target.roundness)))
|
||||
top_lid = max(0.0, min(0.95, self._top_lid.update(target.top_lid)))
|
||||
bottom_lid = max(0.0, min(0.95, self._bottom_lid.update(target.bottom_lid)))
|
||||
top_slant = self._top_slant.update(target.top_slant)
|
||||
gaze_x = self._gaze_x.update(target.gaze_x)
|
||||
gaze_y = self._gaze_y.update(target.gaze_y)
|
||||
bounce_y = self._bounce_y.update(target.bounce_y)
|
||||
tilt_y = self._tilt_y.update(target.tilt_y)
|
||||
squish = max(-1.0, min(1.0, self._squish.update(target.squish_force)))
|
||||
pitch_y = self._pitch_y.update(target.pitch_offset_y)
|
||||
squish_abs = abs(squish)
|
||||
|
||||
r = max(0, min(255, int(self._r.update(target.color[0]))))
|
||||
g = max(0, min(255, int(self._g.update(target.color[1]))))
|
||||
b = max(0, min(255, int(self._b.update(target.color[2]))))
|
||||
|
||||
# Optional alert brightness pulse
|
||||
pulse = 1.0
|
||||
if target.pulse_speed > 0.0:
|
||||
pulse = 0.72 + 0.28 * (0.5 + 0.5 * math.sin(t * target.pulse_speed * math.tau))
|
||||
|
||||
eff_alpha = max(0.0, min(1.0, alpha * pulse))
|
||||
core_color = rl.Color(r, g, b, int(255 * eff_alpha))
|
||||
|
||||
# Subtle wall-cushion glow when centrifugal force squishes the bot strongly to one side
|
||||
if squish_abs > 0.35:
|
||||
wall_a = (squish_abs - 0.35) / 0.65
|
||||
self._draw_wall_squish_glow(rect, 1 if squish > 0 else -1, core_color, wall_a * eff_alpha)
|
||||
|
||||
# Ambient edge accents (blind spot glow, blinker chevrons, boost speed lines)
|
||||
bsm_a = self._bsm_alpha.update(1.0 if target.blind_spot_side != 0 else 0.0)
|
||||
if bsm_a > 0.02 and target.blind_spot_side != 0:
|
||||
self._draw_bsm_edge_glow(rect, target.blind_spot_side, bsm_a * alpha)
|
||||
|
||||
blinker_a = self._blinker_alpha.update(1.0 if target.blinker_side != 0 else 0.0)
|
||||
if blinker_a > 0.02 and target.blinker_side != 0:
|
||||
self._draw_blinker_indicator(rect, target.blinker_side, blinker_a * alpha, t)
|
||||
|
||||
if target.show_speed_lines:
|
||||
self._draw_speed_lines(rect, core_color, eff_alpha, t)
|
||||
|
||||
# Slide the whole face toward the opposite side of the turn under centrifugal force
|
||||
centrifugal_shift_x = squish * 76.0
|
||||
cx = rect.x + rect.width / 2.0 + gaze_x + centrifugal_shift_x
|
||||
cy = rect.y + rect.height / 2.0 - 8.0 + gaze_y + bounce_y + pitch_y + y_shift
|
||||
|
||||
# Compress spacing between eyes as the bot gets smooshed against the side wall
|
||||
spacing = self.EYE_SPACING * (1.0 - 0.24 * squish_abs)
|
||||
left_cx = cx - spacing / 2.0
|
||||
right_cx = cx + spacing / 2.0
|
||||
left_cy = cy - tilt_y
|
||||
right_cy = cy + tilt_y
|
||||
|
||||
# Asymmetric centrifugal wall-squish: outer pressed eye squishes narrower & taller!
|
||||
left_w_mult = (1.0 - 0.36 * max(0.0, -squish)) * (1.0 - 0.14 * max(0.0, squish))
|
||||
left_h_mult = (1.0 + 0.16 * max(0.0, -squish)) * (1.0 - 0.05 * max(0.0, squish))
|
||||
right_w_mult = (1.0 - 0.36 * max(0.0, squish)) * (1.0 - 0.14 * max(0.0, -squish))
|
||||
right_h_mult = (1.0 + 0.16 * max(0.0, squish)) * (1.0 - 0.05 * max(0.0, -squish))
|
||||
|
||||
# Subtle 3D perspective scaling when glancing left/right
|
||||
left_scale = 1.0 - max(0.0, gaze_x / 210.0)
|
||||
right_scale = 1.0 + min(0.0, gaze_x / 210.0)
|
||||
|
||||
eye_configs = (
|
||||
(left_cx, left_cy, w * left_scale * left_w_mult, h * left_scale * left_h_mult),
|
||||
(right_cx, right_cy, w * right_scale * right_w_mult, h * right_scale * right_h_mult),
|
||||
)
|
||||
for side_idx, (ecx, ecy, ew, eh) in enumerate(eye_configs):
|
||||
slant = top_slant if side_idx == 0 else -top_slant
|
||||
glyph = EyeGlyph.CRESCENT if (side_idx == 1 and target.wink_right) else target.glyph
|
||||
self._draw_eye(ecx, ecy, ew, eh, roundness, top_lid, bottom_lid, slant, glyph, core_color, eff_alpha, gaze_x, gaze_y, t)
|
||||
|
||||
if target.mouth != MouthGlyph.NONE:
|
||||
self._draw_mouth(cx, cy + h * 0.72, target.mouth, core_color)
|
||||
|
||||
if target.show_zzz:
|
||||
self._draw_floating_zzz(right_cx + w * 0.58, right_cy - h * 0.35, core_color, eff_alpha, t)
|
||||
|
||||
if target.show_hearts:
|
||||
self._draw_floating_mini_hearts(cx, cy - h * 0.58, core_color, eff_alpha, t)
|
||||
|
||||
def _draw_wall_squish_glow(self, rect: rl.Rectangle, side: int, color: rl.Color, alpha: float) -> None:
|
||||
glow_w = 46
|
||||
edge = rl.Color(color.r, color.g, color.b, int(95 * alpha))
|
||||
clear = rl.Color(color.r, color.g, color.b, 0)
|
||||
if side < 0:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), edge, clear)
|
||||
else:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, edge)
|
||||
|
||||
def _draw_bsm_edge_glow(self, rect: rl.Rectangle, side: int, alpha: float) -> None:
|
||||
glow_w = 56
|
||||
amber = rl.Color(255, 160, 30, int(145 * alpha))
|
||||
clear = rl.Color(255, 160, 30, 0)
|
||||
if side < 0:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), amber, clear)
|
||||
else:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, amber)
|
||||
|
||||
def _draw_blinker_indicator(self, rect: rl.Rectangle, side: int, alpha: float, t: float) -> None:
|
||||
"""Crisp pulsing directional chevron on the left/right edge for turn signals."""
|
||||
pulse = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(t * 8.4))
|
||||
col = rl.Color(85, 240, 140, int(235 * pulse * alpha))
|
||||
glow = rl.Color(85, 240, 140, int(65 * pulse * alpha))
|
||||
cy = rect.y + rect.height / 2.0
|
||||
sign = 1.0 if side > 0 else -1.0
|
||||
base_x = (rect.x + rect.width - 34.0) if side > 0 else (rect.x + 34.0)
|
||||
|
||||
for idx in range(2):
|
||||
ox = base_x - sign * idx * 14.0
|
||||
p_top = rl.Vector2(ox - sign * 10.0, cy - 18.0)
|
||||
p_tip = rl.Vector2(ox + sign * 8.0, cy)
|
||||
p_bot = rl.Vector2(ox - sign * 10.0, cy + 18.0)
|
||||
rl.draw_line_ex(p_top, p_tip, 9.0, glow)
|
||||
rl.draw_line_ex(p_tip, p_bot, 9.0, glow)
|
||||
rl.draw_line_ex(p_top, p_tip, 4.5, col)
|
||||
rl.draw_line_ex(p_tip, p_bot, 4.5, col)
|
||||
|
||||
def _draw_speed_lines(self, rect: rl.Rectangle, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Energetic animated speed streaks on the screen edges during sharp acceleration."""
|
||||
for i in range(4):
|
||||
phase = (t * 4.5 + i * 0.25) % 1.0
|
||||
y = rect.y + 68.0 + i * 44.0
|
||||
line_len = 26.0 + 22.0 * math.sin(phase * math.pi)
|
||||
a = int(170 * math.sin(phase * math.pi) * alpha)
|
||||
col = rl.Color(color.r, color.g, color.b, a)
|
||||
# Left & right symmetrical streaks
|
||||
lx = rect.x + 12.0 + (1.0 - phase) * 28.0
|
||||
rx = rect.x + rect.width - 12.0 - (1.0 - phase) * 28.0
|
||||
rl.draw_line_ex(rl.Vector2(lx, y), rl.Vector2(lx + line_len, y), 3.5, col)
|
||||
rl.draw_line_ex(rl.Vector2(rx - line_len, y), rl.Vector2(rx, y), 3.5, col)
|
||||
|
||||
def _draw_floating_zzz(self, x: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Softly drifting Zzz bubbles so sleepy/standstill state is continuously animated."""
|
||||
for idx, ch in enumerate(("z", "Z")):
|
||||
phase = (t * 0.55 + idx * 0.5) % 1.0
|
||||
zx = x + phase * 18.0 + math.sin(phase * math.tau) * 4.0
|
||||
zy = y - phase * 34.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
size = 20 + idx * 8
|
||||
col = rl.Color(color.r, color.g, color.b, int(190 * fade * alpha))
|
||||
rl.draw_text_ex(self._font_semi_bold, ch, rl.Vector2(zx, zy), size, 0, col)
|
||||
|
||||
def _draw_floating_mini_hearts(self, cx: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Floating mini-hearts above the face during pet/bookmark reactions."""
|
||||
for idx, dx in enumerate((-62.0, 0.0, 62.0)):
|
||||
phase = (t * 1.4 + idx * 0.33) % 1.0
|
||||
hx = cx + dx + math.sin(phase * math.tau) * 6.0
|
||||
hy = y - phase * 26.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
col = rl.Color(color.r, color.g, color.b, int(210 * fade * alpha))
|
||||
self._draw_heart_eye(hx, hy, 8.5, col, fade * alpha, with_glow=False)
|
||||
|
||||
def _draw_eye(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
w: float,
|
||||
h: float,
|
||||
roundness: float,
|
||||
top_lid: float,
|
||||
bottom_lid: float,
|
||||
slant_deg: float,
|
||||
glyph: EyeGlyph,
|
||||
color: rl.Color,
|
||||
alpha: float,
|
||||
gaze_x: float,
|
||||
gaze_y: float,
|
||||
t: float,
|
||||
) -> None:
|
||||
if glyph == EyeGlyph.STAR:
|
||||
self._draw_star_eye(cx, cy, min(w, h) * 0.48, color, alpha, t)
|
||||
return
|
||||
if glyph == EyeGlyph.HEART:
|
||||
self._draw_heart_eye(cx, cy, min(w, h) * 0.48, color, alpha, with_glow=True)
|
||||
return
|
||||
if glyph == EyeGlyph.CRESCENT:
|
||||
self._draw_crescent_eye(cx, cy, w, h, color, alpha)
|
||||
return
|
||||
|
||||
# Silky radial OLED bloom (zero banding, consistent with star & heart eyes)
|
||||
visible_frac = max(0.25, 1.0 - top_lid - bottom_lid)
|
||||
bloom_r = max(w, h) * 0.78 * (0.65 + 0.35 * visible_frac)
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy),
|
||||
bloom_r,
|
||||
rl.Color(color.r, color.g, color.b, int(92 * visible_frac * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
|
||||
# Crisp eye core
|
||||
core_rec = rl.Rectangle(cx - w / 2.0, cy - h / 2.0, w, h)
|
||||
rl.draw_rectangle_rounded(core_rec, min(0.85, roundness), 24, color)
|
||||
|
||||
# Glossy dual specular catchlights (centered-dynamic so eyes never appear stuck staring at top-left)
|
||||
glint_dx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.8
|
||||
glint_dy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.4
|
||||
hi_col = rl.Color(255, 255, 255, int(105 * alpha))
|
||||
rl.draw_rectangle_rounded(
|
||||
rl.Rectangle(cx - w * 0.14 + glint_dx, cy - h * 0.30 + glint_dy, w * 0.28, h * 0.16),
|
||||
0.90,
|
||||
12,
|
||||
hi_col,
|
||||
)
|
||||
rl.draw_circle(
|
||||
int(cx + w * 0.18 + glint_dx * 0.6),
|
||||
int(cy + h * 0.22 + glint_dy * 0.6),
|
||||
max(3.5, min(w, h) * 0.055),
|
||||
rl.Color(255, 255, 255, int(75 * alpha)),
|
||||
)
|
||||
|
||||
# Sparkle glint inside eyes during sharp acceleration boost
|
||||
if glyph == EyeGlyph.SPARKLE_BOOST:
|
||||
self._draw_boost_sparkle(cx, cy, min(w, h) * 0.22, alpha, t)
|
||||
|
||||
# Directional chevron glint inside eye during lane changes
|
||||
if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT):
|
||||
self._draw_chevron_glint(cx, cy, w * 0.24, glyph == EyeGlyph.ARROW_RIGHT, alpha)
|
||||
|
||||
# Laser-alert inner bright core bar
|
||||
if glyph == EyeGlyph.LASER_ALERT:
|
||||
inner_col = rl.Color(255, 235, 235, int(215 * alpha))
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(cx - w * 0.36, cy - 5, w * 0.72, 10), 0.85, 10, inner_col)
|
||||
|
||||
# Eyelid masks (pure black polygons over the OLED canvas, tall enough to cleanly clip outer halo)
|
||||
if top_lid > 0.01 or abs(slant_deg) > 0.5:
|
||||
lid_h = max(42.0, h * (top_lid + 0.55))
|
||||
lid_w = w + 80.0
|
||||
lid_cy = (cy - h / 2.0) + h * top_lid - lid_h / 2.0 - 4.0
|
||||
rl.draw_rectangle_pro(
|
||||
rl.Rectangle(cx, lid_cy, lid_w, lid_h),
|
||||
rl.Vector2(lid_w / 2.0, lid_h / 2.0),
|
||||
slant_deg,
|
||||
rl.BLACK,
|
||||
)
|
||||
|
||||
if bottom_lid > 0.01:
|
||||
lid_h = max(36.0, h * (bottom_lid + 0.45))
|
||||
lid_w = w + 80.0
|
||||
lid_cy = (cy + h / 2.0) - h * bottom_lid + lid_h / 2.0 + 4.0
|
||||
rl.draw_rectangle_pro(
|
||||
rl.Rectangle(cx, lid_cy, lid_w, lid_h),
|
||||
rl.Vector2(lid_w / 2.0, lid_h / 2.0),
|
||||
0.0,
|
||||
rl.BLACK,
|
||||
)
|
||||
|
||||
def _draw_boost_sparkle(self, cx: float, cy: float, size: float, alpha: float, t: float) -> None:
|
||||
"""4-point pulsing star sparkle inside eyes during sharp acceleration."""
|
||||
s = size * (0.85 + 0.25 * math.sin(t * 14.0))
|
||||
col = rl.Color(255, 255, 255, int(210 * alpha))
|
||||
rl.draw_line_ex(rl.Vector2(cx - s, cy), rl.Vector2(cx + s, cy), 4.0, col)
|
||||
rl.draw_line_ex(rl.Vector2(cx, cy - s), rl.Vector2(cx, cy + s), 4.0, col)
|
||||
|
||||
def _draw_chevron_glint(self, cx: float, cy: float, size: float, right: bool, alpha: float) -> None:
|
||||
sign = 1.0 if right else -1.0
|
||||
col = rl.Color(0, 0, 0, int(135 * alpha))
|
||||
p_top = rl.Vector2(cx - sign * size * 0.35, cy - size * 0.75)
|
||||
p_tip = rl.Vector2(cx + sign * size * 0.55, cy)
|
||||
p_bot = rl.Vector2(cx - sign * size * 0.35, cy + size * 0.75)
|
||||
rl.draw_line_ex(p_top, p_tip, 7.0, col)
|
||||
rl.draw_line_ex(p_tip, p_bot, 7.0, col)
|
||||
|
||||
def _draw_star_eye(self, cx: float, cy: float, outer_r: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
inner_r = outer_r * 0.44
|
||||
spin = math.sin(t * 7.0) * 0.14 # playful wobble
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(10):
|
||||
angle = -math.pi / 2.0 + spin + i * (math.pi / 5.0)
|
||||
rad = outer_r if i % 2 == 0 else inner_r
|
||||
pts.append(rl.Vector2(cx + math.cos(angle) * rad, cy + math.sin(angle) * rad))
|
||||
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy), outer_r * 1.25,
|
||||
rl.Color(color.r, color.g, color.b, int(90 * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
center = rl.Vector2(cx, cy)
|
||||
for i in range(10):
|
||||
p1 = pts[i]
|
||||
p2 = pts[(i + 1) % 10]
|
||||
rl.draw_triangle(center, p2, p1, color)
|
||||
|
||||
def _draw_heart_eye(self, cx: float, cy: float, radius: float, color: rl.Color, alpha: float, with_glow: bool = True) -> None:
|
||||
"""Seamless, perfectly symmetrical 48-point parametric smooth heart curve."""
|
||||
if with_glow:
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy), radius * 1.4,
|
||||
rl.Color(color.r, color.g, color.b, int(92 * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
|
||||
# Classic smooth parametric heart:
|
||||
# x(t) = 16 sin^3(t), y(t) = -(13 cos(t) - 5 cos(2t) - 2 cos(3t) - cos(4t))
|
||||
# Normalized so half-width ~= radius; centered vertically around cy
|
||||
scale = radius / 16.0
|
||||
n_pts = 48
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(n_pts):
|
||||
ang = (i / n_pts) * math.tau
|
||||
s = math.sin(ang)
|
||||
hx = 16.0 * (s * s * s)
|
||||
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
|
||||
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
|
||||
|
||||
center = rl.Vector2(cx, cy + radius * 0.05)
|
||||
for i in range(n_pts):
|
||||
p1 = pts[i]
|
||||
p2 = pts[(i + 1) % n_pts]
|
||||
# Parametric curve runs clockwise in screen coords (y-down), so (center, p2, p1) is CCW
|
||||
rl.draw_triangle(center, p2, p1, color)
|
||||
|
||||
def _draw_crescent_eye(self, cx: float, cy: float, w: float, h: float, color: rl.Color, alpha: float) -> None:
|
||||
radius = min(w, h) * 0.50
|
||||
arc_cy = cy + radius * 0.35
|
||||
glow_col = rl.Color(color.r, color.g, color.b, int(55 * alpha))
|
||||
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 22.0, radius + 8.0, 200.0, 340.0, 28, glow_col)
|
||||
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 14.0, radius, 202.0, 338.0, 28, color)
|
||||
|
||||
def _draw_mouth(self, cx: float, cy: float, mouth: MouthGlyph, color: rl.Color) -> None:
|
||||
if mouth == MouthGlyph.SMILE:
|
||||
rl.draw_ring(rl.Vector2(cx, cy - 10.0), 17.0, 23.0, 25.0, 155.0, 20, color)
|
||||
elif mouth == MouthGlyph.BIG_GRIN:
|
||||
rl.draw_ring(rl.Vector2(cx, cy - 12.0), 19.0, 26.0, 18.0, 162.0, 24, color)
|
||||
elif mouth == MouthGlyph.FROWN:
|
||||
rl.draw_ring(rl.Vector2(cx, cy + 16.0), 17.0, 23.0, 205.0, 335.0, 20, color)
|
||||
elif mouth == MouthGlyph.SURPRISED:
|
||||
rl.draw_ring(rl.Vector2(cx, cy + 2.0), 9.0, 15.0, 0.0, 360.0, 24, color)
|
||||
@@ -1,249 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
DEFAULT_SAMPLE_RATE = 16000
|
||||
FRAME_RATE = 20.0 # micd publishes 800 samples @ 16kHz = 50ms (20 Hz)
|
||||
FFT_SIZE = 1024 # ~64ms analysis window
|
||||
NUM_BANDS = 12
|
||||
HISTORY_FRAMES = 50 # 2.5 seconds of flux/energy history @ 20 Hz
|
||||
|
||||
# Tempo autocorrelation lag bounds @ 20 Hz: 7..17 frames -> 70..171 BPM
|
||||
MIN_TEMPO_LAG = 7
|
||||
MAX_TEMPO_LAG = 17
|
||||
|
||||
# Hysteresis thresholds for stable music detection (rejects road noise & talking)
|
||||
ENTER_MUSIC_CONF = 0.58
|
||||
EXIT_MUSIC_CONF = 0.36
|
||||
MIN_ACTIVE_RMS = 0.012
|
||||
|
||||
|
||||
@dataclass
|
||||
class MusicState:
|
||||
is_music: bool = False
|
||||
confidence: float = 0.0
|
||||
beat_pulse: float = 0.0 # 0..1 sharp onset with smooth decay
|
||||
groove_phase: float = 0.0 # radians advancing at estimated tempo
|
||||
bpm: float = 116.0
|
||||
energy: float = 0.0 # 0..1 normalized musical loudness
|
||||
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
|
||||
|
||||
|
||||
class MusicAnalyzer:
|
||||
"""Low-CPU pure-NumPy cabin music detector, beat tracker, and 12-band equalizer analyzer.
|
||||
|
||||
Distinguishes ambient music from car road/wind noise and human speech by combining:
|
||||
1. Adaptive cabin noise-floor gating
|
||||
2. Spectral tonality (1 - spectral flatness) to reject broadband road/wind noise
|
||||
3. Musical bandwidth balance (bass + treble presence) to reject narrowband talking
|
||||
4. Rhythmic tempo periodicity (spectral flux autocorrelation at 70-171 BPM)
|
||||
5. Temporal energy continuity (speech has frequent inter-word silences)
|
||||
"""
|
||||
|
||||
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE):
|
||||
self._sample_rate = sample_rate
|
||||
self._window = np.hanning(FFT_SIZE).astype(np.float32)
|
||||
self._ring = np.zeros(FFT_SIZE, dtype=np.float32)
|
||||
self._prev_mag: np.ndarray | None = None
|
||||
|
||||
self._noise_floor: float = 0.008
|
||||
self._confidence: float = 0.0
|
||||
self._is_music: bool = False
|
||||
self._beat_pulse: float = 0.0
|
||||
self._groove_phase: float = 0.0
|
||||
self._bpm: float = 116.0
|
||||
self._energy: float = 0.0
|
||||
self._bands = np.zeros(NUM_BANDS, dtype=np.float32)
|
||||
|
||||
self._flux_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
|
||||
self._active_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
|
||||
self._bass_flux_hist: deque[float] = deque(maxlen=20)
|
||||
|
||||
self._build_frequency_masks(sample_rate)
|
||||
|
||||
def _build_frequency_masks(self, sr: int) -> None:
|
||||
self._sample_rate = sr
|
||||
freqs = np.fft.rfftfreq(FFT_SIZE, d=1.0 / sr)
|
||||
self._freqs = freqs
|
||||
self._bass_mask = (freqs >= 55.0) & (freqs < 230.0)
|
||||
self._speech_mask = (freqs >= 300.0) & (freqs < 2400.0)
|
||||
self._treble_mask = (freqs >= 2800.0) & (freqs < min(7600.0, sr * 0.48))
|
||||
self._tonal_mask = (freqs >= 100.0) & (freqs < 4000.0)
|
||||
|
||||
# 12 log-spaced equalizer bands (60 Hz .. 7200 Hz)
|
||||
edges = np.geomspace(60.0, min(7200.0, sr * 0.47), NUM_BANDS + 1)
|
||||
self._band_slices: list[tuple[int, int]] = []
|
||||
for i in range(NUM_BANDS):
|
||||
lo = int(np.searchsorted(freqs, edges[i]))
|
||||
hi = max(lo + 1, int(np.searchsorted(freqs, edges[i + 1])))
|
||||
self._band_slices.append((lo, min(hi, len(freqs))))
|
||||
|
||||
@property
|
||||
def state(self) -> MusicState:
|
||||
return MusicState(
|
||||
is_music=self._is_music,
|
||||
confidence=self._confidence,
|
||||
beat_pulse=self._beat_pulse,
|
||||
groove_phase=self._groove_phase,
|
||||
bpm=self._bpm,
|
||||
energy=self._energy,
|
||||
bands=tuple(float(b) for b in self._bands),
|
||||
)
|
||||
|
||||
def step_visual_decay(self, dt: float) -> MusicState:
|
||||
"""Advance smooth 60 FPS groove phase and beat decay between 20 Hz audio chunks."""
|
||||
if self._is_music:
|
||||
rad_per_sec = (self._bpm / 60.0) * math.pi # half-note sway cycle
|
||||
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % (math.tau * 4.0)
|
||||
decay = math.exp(-dt * 7.5)
|
||||
self._beat_pulse *= decay
|
||||
if not self._is_music:
|
||||
self._bands *= math.exp(-dt * 6.0)
|
||||
return self.state
|
||||
|
||||
def process_audio_bytes(self, data: bytes, sample_rate: int = DEFAULT_SAMPLE_RATE) -> MusicState:
|
||||
"""Process a rawAudioData int16 PCM byte buffer from micd."""
|
||||
if not data:
|
||||
return self.state
|
||||
if sample_rate > 0 and sample_rate != self._sample_rate:
|
||||
self._build_frequency_masks(sample_rate)
|
||||
samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
return self.process_samples(samples)
|
||||
|
||||
def process_samples(self, samples: np.ndarray) -> MusicState:
|
||||
"""Analyze a normalized float32 [-1, 1] mono audio chunk (~50 ms)."""
|
||||
n = len(samples)
|
||||
if n == 0:
|
||||
return self.state
|
||||
|
||||
# Update rolling FFT window
|
||||
if n >= FFT_SIZE:
|
||||
self._ring[:] = samples[-FFT_SIZE:]
|
||||
else:
|
||||
self._ring[:-n] = self._ring[n:]
|
||||
self._ring[-n:] = samples
|
||||
|
||||
rms = float(np.sqrt(np.mean(self._ring * self._ring)))
|
||||
|
||||
# Slow adaptive cabin noise floor (tracks down quickly, tracks up very slowly)
|
||||
if rms < self._noise_floor:
|
||||
self._noise_floor = 0.85 * self._noise_floor + 0.15 * rms
|
||||
else:
|
||||
self._noise_floor = 0.996 * self._noise_floor + 0.004 * rms
|
||||
self._noise_floor = max(0.003, min(0.08, self._noise_floor))
|
||||
|
||||
# Gate very quiet / pure-floor frames
|
||||
above_floor = rms > max(MIN_ACTIVE_RMS, self._noise_floor * 1.45)
|
||||
self._active_hist.append(1.0 if above_floor else 0.0)
|
||||
|
||||
# FFT magnitude spectrum
|
||||
spec = np.abs(np.fft.rfft(self._ring * self._window)) / (FFT_SIZE * 0.5)
|
||||
power = spec * spec + 1e-12
|
||||
|
||||
# 1. Spectral tonality (1 - flatness): music is tonal/harmonic; road noise is flat
|
||||
tonal_p = power[self._tonal_mask]
|
||||
geo_mean = float(np.exp(np.mean(np.log(tonal_p))))
|
||||
arith_mean = float(np.mean(tonal_p))
|
||||
flatness = geo_mean / max(arith_mean, 1e-12)
|
||||
tonality_score = float(np.clip((0.52 - flatness) / 0.36, 0.0, 1.0))
|
||||
|
||||
# 2. Musical bandwidth balance: speech is concentrated in 300-2400Hz with weak bass+treble
|
||||
total_p = float(np.sum(power[1:])) + 1e-12
|
||||
bass_ratio = float(np.sum(power[self._bass_mask])) / total_p
|
||||
speech_ratio = float(np.sum(power[self._speech_mask])) / total_p
|
||||
treble_ratio = float(np.sum(power[self._treble_mask])) / total_p
|
||||
non_speech_ratio = bass_ratio + treble_ratio
|
||||
# Penalize narrowband vocal-only energy (speech_ratio > 0.78 and low bass+treble)
|
||||
bandwidth_score = float(np.clip(non_speech_ratio / 0.34, 0.0, 1.0))
|
||||
if speech_ratio > 0.80 and bass_ratio < 0.12:
|
||||
bandwidth_score *= 0.25
|
||||
|
||||
# 3. Spectral flux & bass onset flux
|
||||
if self._prev_mag is None:
|
||||
flux = 0.0
|
||||
bass_flux = 0.0
|
||||
else:
|
||||
diff = np.maximum(0.0, spec - self._prev_mag)
|
||||
flux = float(np.sum(diff))
|
||||
bass_flux = float(np.sum(diff[self._bass_mask]))
|
||||
self._prev_mag = spec
|
||||
|
||||
self._flux_hist.append(flux)
|
||||
self._bass_flux_hist.append(bass_flux)
|
||||
|
||||
# 4. Tempo periodicity via normalized autocorrelation of spectral flux (70-171 BPM)
|
||||
rhythm_score = 0.0
|
||||
if len(self._flux_hist) >= MAX_TEMPO_LAG + 12:
|
||||
arr = np.array(self._flux_hist, dtype=np.float32)
|
||||
arr_centered = arr - np.mean(arr)
|
||||
denom = float(np.dot(arr_centered, arr_centered))
|
||||
if denom > 1e-9:
|
||||
best_corr = 0.0
|
||||
best_lag = 10
|
||||
for lag in range(MIN_TEMPO_LAG, MAX_TEMPO_LAG + 1):
|
||||
c = float(np.dot(arr_centered[:-lag], arr_centered[lag:])) / denom
|
||||
if c > best_corr:
|
||||
best_corr = c
|
||||
best_lag = lag
|
||||
rhythm_score = float(np.clip((best_corr - 0.14) / 0.32, 0.0, 1.0))
|
||||
if best_corr > 0.22:
|
||||
est_bpm = (60.0 * FRAME_RATE) / best_lag
|
||||
# Smooth BPM estimate
|
||||
self._bpm = 0.90 * self._bpm + 0.10 * float(np.clip(est_bpm, 75.0, 170.0))
|
||||
|
||||
# 5. Temporal continuity (music fills frames steadily; talking has frequent pauses)
|
||||
continuity = float(np.mean(self._active_hist)) if self._active_hist else 0.0
|
||||
continuity_score = float(np.clip((continuity - 0.45) / 0.45, 0.0, 1.0))
|
||||
|
||||
# Combined music frame score
|
||||
if not above_floor:
|
||||
frame_score = 0.0
|
||||
else:
|
||||
frame_score = (
|
||||
0.30 * tonality_score
|
||||
+ 0.25 * bandwidth_score
|
||||
+ 0.30 * rhythm_score
|
||||
+ 0.15 * continuity_score
|
||||
)
|
||||
# Require both harmonic tonality AND either rhythmic lock or rich musical bandwidth
|
||||
if tonality_score < 0.22 or (rhythm_score < 0.15 and bandwidth_score < 0.45):
|
||||
frame_score *= 0.35
|
||||
|
||||
# Smooth confidence with hysteresis (~1.4s attack, ~2.0s release @ 20 Hz)
|
||||
alpha = 0.055 if frame_score > self._confidence else 0.035
|
||||
self._confidence = (1.0 - alpha) * self._confidence + alpha * frame_score
|
||||
|
||||
if not self._is_music and self._confidence >= ENTER_MUSIC_CONF:
|
||||
self._is_music = True
|
||||
elif self._is_music and self._confidence <= EXIT_MUSIC_CONF:
|
||||
self._is_music = False
|
||||
|
||||
# Beat onset pulse (bass + overall flux spike above rolling mean)
|
||||
if self._is_music and len(self._bass_flux_hist) >= 6:
|
||||
bf_mean = float(np.mean(self._bass_flux_hist))
|
||||
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
|
||||
if bass_flux > bf_mean + 0.95 * bf_std and bass_flux > 0.015:
|
||||
strength = float(np.clip((bass_flux - bf_mean) / (2.2 * bf_std), 0.45, 1.0))
|
||||
self._beat_pulse = max(self._beat_pulse, strength)
|
||||
|
||||
# Normalized energy & 12-band equalizer bars (log-compressed for lush visuals)
|
||||
self._energy = float(np.clip((rms - self._noise_floor) / max(0.10, self._noise_floor * 4.5), 0.0, 1.0))
|
||||
for i, (lo, hi) in enumerate(self._band_slices):
|
||||
band_mag = float(np.sqrt(np.mean(power[lo:hi])))
|
||||
# Log scale into 0..1 with slight treble tilt for lively equalizer shape
|
||||
tilt = 1.0 + 0.16 * i
|
||||
norm = float(np.clip(math.log1p(band_mag * 150.0 * tilt) / 2.0, 0.0, 1.0))
|
||||
if norm > self._bands[i]:
|
||||
self._bands[i] = 0.45 * self._bands[i] + 0.55 * norm
|
||||
else:
|
||||
self._bands[i] = 0.78 * self._bands[i] + 0.22 * norm
|
||||
|
||||
return self.state
|
||||
@@ -1,127 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState, NUM_BANDS
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
|
||||
|
||||
def groove_prism_color(t: float) -> tuple[int, int, int]:
|
||||
"""Smoothly cycle vibrant OLED-friendly cyan -> aqua -> orchid -> mint hues while grooving."""
|
||||
# Smooth cosine palette keeping high brightness and pleasant saturation
|
||||
r = int(125 + 95 * math.sin(t * 0.9 + 2.2))
|
||||
g = int(195 + 55 * math.sin(t * 0.9 + 0.4))
|
||||
b = int(215 + 40 * math.sin(t * 0.9 + 4.1))
|
||||
return (max(50, min(255, r)), max(90, min(255, g)), max(140, min(255, b)))
|
||||
|
||||
|
||||
class MusicVisualizerRenderer:
|
||||
"""Smooth 60 FPS OLED equalizer bars, bass pulse aura, and floating musical notes."""
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._alpha = FirstOrderFilter(0.0, 0.16, dt)
|
||||
self._bar_filters = [FirstOrderFilter(0.0, 0.06, dt) for _ in range(NUM_BANDS)]
|
||||
|
||||
def render_background(self, rect: rl.Rectangle, music: MusicState, active: bool) -> float:
|
||||
"""Render smooth ambient bass aura & bottom pill equalizer bars; returns current visualizer alpha."""
|
||||
alpha = self._alpha.update(1.0 if active else 0.0)
|
||||
if alpha < 0.01:
|
||||
return 0.0
|
||||
|
||||
t = rl.get_time()
|
||||
cr, cg, cb = groove_prism_color(t)
|
||||
|
||||
# 1. Soft beat-reactive ambient bass aura along bottom center
|
||||
aura_r = 140.0 + 75.0 * music.beat_pulse + 35.0 * music.energy
|
||||
aura_alpha = int((42 + 52 * music.beat_pulse) * alpha)
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(rect.x + rect.width / 2.0, rect.y + rect.height + 10.0),
|
||||
aura_r,
|
||||
rl.Color(cr, cg, cb, aura_alpha),
|
||||
rl.Color(cr, cg, cb, 0),
|
||||
)
|
||||
|
||||
# 2. Smooth 12-band symmetric pill equalizer along the bottom edge
|
||||
bar_count = NUM_BANDS
|
||||
total_w = rect.width - 76.0
|
||||
gap = 10.0
|
||||
bar_w = (total_w - gap * (bar_count - 1)) / bar_count
|
||||
start_x = rect.x + (rect.width - total_w) / 2.0
|
||||
base_y = rect.y + rect.height - 8.0
|
||||
max_bar_h = 44.0
|
||||
|
||||
for i in range(bar_count):
|
||||
raw_level = music.bands[i] if i < len(music.bands) else 0.0
|
||||
# Keep a smooth living wave + subtle beat lift on bass/mid bars
|
||||
wave = 0.14 + 0.10 * math.sin(t * 5.0 + i * 0.65)
|
||||
beat_lift = music.beat_pulse * (0.28 if i < 6 else 0.16)
|
||||
level = self._bar_filters[i].update(min(1.0, max(wave, raw_level + beat_lift)))
|
||||
bar_h = max(8.0, level * max_bar_h)
|
||||
|
||||
bx = start_x + i * (bar_w + gap)
|
||||
by = base_y - bar_h
|
||||
|
||||
# Subtle color gradient across the spectrum (cyan -> violet -> pink)
|
||||
frac = i / max(1, bar_count - 1)
|
||||
br = int(min(255, cr * (1.0 - frac * 0.25) + 255 * frac * 0.25))
|
||||
bg = int(min(255, cg * (1.0 - frac * 0.30) + 120 * frac * 0.30))
|
||||
bb = int(min(255, cb * 0.85 + 255 * 0.15))
|
||||
|
||||
# Soft glow cap on taller bars
|
||||
if level > 0.35:
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(bx + bar_w / 2.0, by + 4.0),
|
||||
bar_w * 1.15,
|
||||
rl.Color(br, bg, bb, int(75 * level * alpha)),
|
||||
rl.Color(br, bg, bb, 0),
|
||||
)
|
||||
|
||||
bar_col = rl.Color(br, bg, bb, int((155 + 90 * level) * alpha))
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(bx, by, bar_w, bar_h), 0.9, 10, bar_col)
|
||||
|
||||
return alpha
|
||||
|
||||
def render_foreground_notes(self, rect: rl.Rectangle, music: MusicState, alpha: float) -> None:
|
||||
"""Draw cute floating vector musical notes on the left and right edges while grooving."""
|
||||
if alpha < 0.05:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
cr, cg, cb = groove_prism_color(t + 1.2)
|
||||
note_specs = (
|
||||
(rect.x + 48.0, 0.0, 1.0),
|
||||
(rect.x + rect.width - 48.0, 0.5, -1.0),
|
||||
(rect.x + 82.0, 0.28, 0.8),
|
||||
(rect.x + rect.width - 82.0, 0.76, -0.8),
|
||||
)
|
||||
|
||||
for base_x, phase_off, sway_dir in note_specs:
|
||||
phase = (t * 0.65 + phase_off) % 1.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
nx = base_x + math.sin(phase * math.tau) * 10.0 * sway_dir
|
||||
ny = rect.y + 150.0 - phase * 98.0
|
||||
scale = 0.85 + 0.25 * music.beat_pulse
|
||||
col = rl.Color(cr, cg, cb, int(215 * fade * alpha))
|
||||
self._draw_eighth_note(nx, ny, 7.5 * scale, col)
|
||||
|
||||
def _draw_eighth_note(self, cx: float, cy: float, r: float, color: rl.Color) -> None:
|
||||
"""Crisp vector eighth-note glyph (♪) — zero font dependency."""
|
||||
rl.draw_circle(int(cx), int(cy), r * 0.72, color)
|
||||
stem_x = cx + r * 0.58
|
||||
stem_top = cy - r * 2.5
|
||||
rl.draw_line_ex(rl.Vector2(stem_x, cy), rl.Vector2(stem_x, stem_top), 2.8, color)
|
||||
# Curved flag
|
||||
rl.draw_line_ex(
|
||||
rl.Vector2(stem_x, stem_top),
|
||||
rl.Vector2(stem_x + r * 1.15, stem_top + r * 0.95),
|
||||
2.8,
|
||||
color,
|
||||
)
|
||||
@@ -1,214 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import BookmarkIcon
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.alert_overlay import RoboticAlertOverlay
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
RoboticMood,
|
||||
RoboticMoodEngine,
|
||||
snapshot_from_ui_state,
|
||||
)
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.face_renderer import ProceduralFaceRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicAnalyzer, MusicState
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import MusicVisualizerRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.speed_arc_renderer import SpeedArcRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state
|
||||
from openpilot.system.ui.lib.application import (
|
||||
FontWeight,
|
||||
MouseEvent,
|
||||
MousePos,
|
||||
TextAlignment,
|
||||
TextAlignmentVertical,
|
||||
gui_app,
|
||||
)
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
VERTICAL_SWIPE_THRESHOLD = 45.0 # px
|
||||
|
||||
|
||||
class RoboticOnroadView(Widget):
|
||||
"""Full-screen EMO-inspired Robotic Companion onroad view for MICI (536x240 @ 60 FPS)."""
|
||||
|
||||
def __init__(self, bookmark_callback=None):
|
||||
super().__init__()
|
||||
self._bookmark_callback = bookmark_callback
|
||||
|
||||
self._mood_engine = RoboticMoodEngine()
|
||||
self._face_renderer = ProceduralFaceRenderer()
|
||||
self._speed_renderer = SpeedArcRenderer()
|
||||
self._alert_overlay = RoboticAlertOverlay()
|
||||
self._music_analyzer = MusicAnalyzer()
|
||||
self._music_visualizer = MusicVisualizerRenderer()
|
||||
|
||||
self._bookmark_icon = BookmarkIcon(self._on_bookmark_triggered)
|
||||
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._speed_blend = FirstOrderFilter(0.0, 0.08, dt)
|
||||
|
||||
# Vertical swipe tracking (up = speed peek, down = pet robot)
|
||||
self._touch_start_y: float = 0.0
|
||||
self._touch_start_x: float = 0.0
|
||||
self._vertical_swipe_handled: bool = False
|
||||
|
||||
self._offroad_label = UnifiedLabel(
|
||||
"start the car to\nuse sunnypilot",
|
||||
54,
|
||||
FontWeight.DISPLAY,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
|
||||
alignment=TextAlignment.CENTER,
|
||||
alignment_vertical=TextAlignmentVertical.MIDDLE,
|
||||
)
|
||||
|
||||
def _on_bookmark_triggered(self) -> None:
|
||||
self._mood_engine.trigger_love(wink=True)
|
||||
if self._bookmark_callback is not None:
|
||||
self._bookmark_callback()
|
||||
|
||||
def is_swiping_left(self) -> bool:
|
||||
"""Match AugmentedRoadView API so MiciMainLayout disables horizontal scroller during bookmark swipe."""
|
||||
return self._bookmark_icon.is_swiping_left()
|
||||
|
||||
def _update_state(self) -> None:
|
||||
super()._update_state()
|
||||
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 sunnypilot")
|
||||
|
||||
def _handle_mouse_event(self, mouse_event: MouseEvent) -> None:
|
||||
if ui_state.started:
|
||||
if mouse_event.left_pressed:
|
||||
self._touch_start_x = mouse_event.pos.x
|
||||
self._touch_start_y = mouse_event.pos.y
|
||||
self._vertical_swipe_handled = False
|
||||
elif mouse_event.left_down and not self._vertical_swipe_handled:
|
||||
dx = abs(mouse_event.pos.x - self._touch_start_x)
|
||||
dy = mouse_event.pos.y - self._touch_start_y
|
||||
if abs(dy) > VERTICAL_SWIPE_THRESHOLD and abs(dy) > dx * 1.4:
|
||||
self._vertical_swipe_handled = True
|
||||
if dy < 0:
|
||||
self._mood_engine.trigger_speed_peek()
|
||||
else:
|
||||
self._mood_engine.trigger_love()
|
||||
|
||||
self._bookmark_icon._handle_mouse_event(mouse_event)
|
||||
super()._handle_mouse_event(mouse_event)
|
||||
|
||||
def _handle_mouse_release(self, mouse_pos: MousePos) -> None:
|
||||
if self._vertical_swipe_handled:
|
||||
self._vertical_swipe_handled = False
|
||||
return
|
||||
if not self._bookmark_icon.interacting():
|
||||
super()._handle_mouse_release(mouse_pos)
|
||||
|
||||
def _render(self, _) -> None:
|
||||
rl.draw_rectangle_rec(self.rect, rl.BLACK)
|
||||
|
||||
if not ui_state.started:
|
||||
# Keep subtle animated sleepy eyes behind the offroad message so the screen is never static
|
||||
sleepy_snap = DrivingSnapshot(started=False, standstill=True)
|
||||
eye_target = self._mood_engine.update(sleepy_snap)
|
||||
self._face_renderer.render(self.rect, eye_target, alpha=0.28, y_shift=16.0)
|
||||
self._offroad_label.render(self._rect)
|
||||
return
|
||||
|
||||
alert = self._alert_overlay.get_alert()
|
||||
if ui_state.sm.updated["rawAudioData"] and alert is None:
|
||||
raw_audio = ui_state.sm["rawAudioData"]
|
||||
self._music_analyzer.process_audio_bytes(raw_audio.data, int(raw_audio.sampleRate))
|
||||
music_state = self._music_analyzer.step_visual_decay(1.0 / max(gui_app.target_fps, 1))
|
||||
|
||||
snap = snapshot_from_ui_state(ui_state, alert)
|
||||
snap.music = music_state
|
||||
self._render_from_snapshot(snap, alert)
|
||||
|
||||
self._bookmark_icon.render(self.rect)
|
||||
|
||||
def _render_from_snapshot(self, snap: DrivingSnapshot, alert) -> None:
|
||||
eye_target = self._mood_engine.update(snap)
|
||||
speed_alpha = self._speed_blend.update(1.0 if self._mood_engine.showing_speed else 0.0)
|
||||
face_alpha = 1.0 - speed_alpha
|
||||
|
||||
# Shift eyes slightly upward when a bottom alert banner or music equalizer is visible
|
||||
grooving = self._mood_engine.mood == RoboticMood.MUSIC_GROOVE and alert is None
|
||||
alert_shift = -26.0 if alert is not None else (-14.0 if grooving else 0.0)
|
||||
music_state = snap.music or MusicState()
|
||||
|
||||
viz_alpha = 0.0
|
||||
if face_alpha > 0.01:
|
||||
viz_alpha = self._music_visualizer.render_background(self.rect, music_state, active=grooving)
|
||||
self._face_renderer.render(self.rect, eye_target, alpha=face_alpha, y_shift=alert_shift)
|
||||
if viz_alpha > 0.05:
|
||||
self._music_visualizer.render_foreground_notes(self.rect, music_state, alpha=viz_alpha * face_alpha)
|
||||
if alert is None:
|
||||
self._speed_renderer.render_corner_badge(self.rect, snap, alpha=face_alpha)
|
||||
|
||||
if speed_alpha > 0.01:
|
||||
self._speed_renderer.render_speed_mode(
|
||||
self.rect,
|
||||
snap,
|
||||
alpha=speed_alpha,
|
||||
cruising_smoothly=self._mood_engine.cruising_smoothly,
|
||||
reason=self._mood_engine.speed_reason,
|
||||
)
|
||||
|
||||
self._alert_overlay.render(self.rect, alert)
|
||||
|
||||
def show_event(self) -> None:
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME)
|
||||
|
||||
def hide_event(self) -> None:
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
|
||||
gui_app.init_window("MICI Robotic Companion Preview")
|
||||
view = RoboticOnroadView()
|
||||
view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
|
||||
|
||||
print("Keys: [1] Engaged [2] MADS [3] Disengaged [4] Speed Peek [5] Stars [6] Love [7] Prompt [8] Critical [9] Pout [Left/Right] Steer")
|
||||
for _ in gui_app.render():
|
||||
if rl.is_key_pressed(rl.KeyboardKey.KEY_ONE):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_TWO):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=20.0, set_speed_kph=90.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_THREE):
|
||||
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FOUR):
|
||||
view._mood_engine.trigger_speed_peek()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FIVE):
|
||||
view._mood_engine.trigger_startled()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SIX):
|
||||
view._mood_engine.trigger_love()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SEVEN):
|
||||
snap.alert = Alert("Pay Attention", "Eyes on road", status=log.SelfdriveState.AlertStatus.userPrompt)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_EIGHT):
|
||||
snap.alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=log.SelfdriveState.AlertStatus.critical)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_NINE):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
|
||||
elif rl.is_key_down(rl.KeyboardKey.KEY_LEFT):
|
||||
snap.steering_angle_deg = 30.0
|
||||
elif rl.is_key_down(rl.KeyboardKey.KEY_RIGHT):
|
||||
snap.steering_angle_deg = -30.0
|
||||
else:
|
||||
snap.steering_angle_deg = 0.0
|
||||
|
||||
rl.draw_rectangle_rec(view.rect, rl.BLACK)
|
||||
view._render_from_snapshot(snap, snap.alert)
|
||||
@@ -1,218 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.common.filter_simple import BounceFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
PALETTE,
|
||||
display_speed_and_set_speed,
|
||||
)
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
|
||||
|
||||
class SpeedArcRenderer:
|
||||
"""Reference-video-inspired color-coded speed + curved arc gauge and subtle Set-Speed badge."""
|
||||
|
||||
SPEED_FONT_SIZE = 114
|
||||
UNIT_FONT_SIZE = 24
|
||||
BADGE_SPEED_FONT_SIZE = 32
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY)
|
||||
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
|
||||
self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM)
|
||||
self._arc_progress = BounceFilter(0.0, 0.11, dt, bounce=2.4)
|
||||
|
||||
def _speed_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
|
||||
if snap.status == UIStatus.OVERRIDE or snap.a_ego > 1.8:
|
||||
return (255, 205, 65) # Warm yellow/amber
|
||||
if snap.status == UIStatus.ENGAGED:
|
||||
return (85, 238, 150) # Vibrant green
|
||||
if snap.status == UIStatus.LAT_ONLY:
|
||||
return PALETTE["lat_only"]
|
||||
return (240, 245, 255) # Crisp white
|
||||
|
||||
def render_speed_mode(
|
||||
self,
|
||||
rect: rl.Rectangle,
|
||||
snap: DrivingSnapshot,
|
||||
alpha: float,
|
||||
cruising_smoothly: bool,
|
||||
reason: str,
|
||||
) -> None:
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
cur_speed, set_speed = display_speed_and_set_speed(snap)
|
||||
sr, sg, sb = self._speed_color(snap)
|
||||
speed_color = rl.Color(sr, sg, sb, int(255 * alpha))
|
||||
sub_color = rl.Color(255, 255, 255, int(195 * alpha))
|
||||
|
||||
cx = rect.x + rect.width / 2.0
|
||||
# Subtle breathing float so speed mode is alive and never frozen
|
||||
float_y = math.sin(t * 2.2) * 2.0
|
||||
|
||||
# Top accent above speed: MAX set-speed pill or gently pulsing heart
|
||||
if reason == "set_speed" and set_speed is not None:
|
||||
pill_text = f"{tr('MAX')} {set_speed}"
|
||||
pill_sz = measure_text_cached(self._font_semi_bold, pill_text, 26)
|
||||
pill_w = pill_sz.x + 28
|
||||
pill_h = 34
|
||||
pill_rect = rl.Rectangle(cx - pill_w / 2.0, rect.y + 14 + float_y * 0.5, pill_w, pill_h)
|
||||
rl.draw_rectangle_rounded(pill_rect, 0.5, 14, rl.Color(sr, sg, sb, int(48 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill_rect, 0.5, 14, 2.0, rl.Color(sr, sg, sb, int(180 * alpha)))
|
||||
rl.draw_text_ex(
|
||||
self._font_semi_bold,
|
||||
pill_text,
|
||||
rl.Vector2(cx - pill_sz.x / 2.0, pill_rect.y + (pill_h - pill_sz.y) / 2.0),
|
||||
26,
|
||||
0,
|
||||
speed_color,
|
||||
)
|
||||
elif cruising_smoothly:
|
||||
heart_r = 10.0 * (1.0 + 0.10 * math.sin(t * 4.5))
|
||||
self._draw_tiny_heart(cx, rect.y + 30 + float_y * 0.5, heart_r, rl.Color(255, 118, 168, int(240 * alpha)))
|
||||
elif set_speed is not None:
|
||||
max_lbl = f"{tr('MAX')} {set_speed}"
|
||||
lbl_sz = measure_text_cached(self._font_medium, max_lbl, self.UNIT_FONT_SIZE)
|
||||
rl.draw_text_ex(
|
||||
self._font_medium,
|
||||
max_lbl,
|
||||
rl.Vector2(cx - lbl_sz.x / 2.0, rect.y + 18 + float_y * 0.5),
|
||||
self.UNIT_FONT_SIZE,
|
||||
0,
|
||||
sub_color,
|
||||
)
|
||||
|
||||
# Big centered speed number
|
||||
speed_text = str(cur_speed)
|
||||
speed_sz = measure_text_cached(self._font_display, speed_text, self.SPEED_FONT_SIZE)
|
||||
speed_y = rect.y + rect.height / 2.0 - speed_sz.y / 2.0 - 8.0 + float_y
|
||||
rl.draw_text_ex(
|
||||
self._font_display,
|
||||
speed_text,
|
||||
rl.Vector2(cx - speed_sz.x / 2.0, speed_y),
|
||||
self.SPEED_FONT_SIZE,
|
||||
0,
|
||||
speed_color,
|
||||
)
|
||||
|
||||
# Unit beside speed (small & subtle)
|
||||
unit_text = tr("km/h") if snap.is_metric else tr("mph")
|
||||
rl.draw_text_ex(
|
||||
self._font_medium,
|
||||
unit_text,
|
||||
rl.Vector2(cx + speed_sz.x / 2.0 + 10.0, speed_y + speed_sz.y - 34.0),
|
||||
self.UNIT_FONT_SIZE,
|
||||
0,
|
||||
rl.Color(255, 255, 255, int(150 * alpha)),
|
||||
)
|
||||
|
||||
# Curved arc speedometer gauge underneath (matches reference video)
|
||||
max_ref = float(set_speed) if (set_speed is not None and set_speed > 0) else (130.0 if snap.is_metric else 85.0)
|
||||
raw_frac = max(0.0, min(1.0, cur_speed / max_ref))
|
||||
frac = max(0.0, min(1.0, self._arc_progress.update(raw_frac)))
|
||||
|
||||
arc_center = rl.Vector2(cx, rect.y + rect.height + 74.0)
|
||||
inner_r = 104.0
|
||||
outer_r = 114.0
|
||||
mid_r = (inner_r + outer_r) / 2.0
|
||||
cap_r = (outer_r - inner_r) / 2.0
|
||||
start_deg = 228.0
|
||||
end_deg = 312.0
|
||||
span_deg = end_deg - start_deg
|
||||
|
||||
# Track background arc with rounded caps
|
||||
track_col = rl.Color(255, 255, 255, int(45 * alpha))
|
||||
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, end_deg, 32, track_col)
|
||||
for deg in (start_deg, end_deg):
|
||||
rad = math.radians(deg)
|
||||
rl.draw_circle(int(arc_center.x + math.cos(rad) * mid_r), int(arc_center.y + math.sin(rad) * mid_r), cap_r, track_col)
|
||||
|
||||
# Active glowing arc + bright animated tip pip
|
||||
if frac > 0.01:
|
||||
active_end = start_deg + span_deg * frac
|
||||
glow_pulse = 0.78 + 0.22 * math.sin(t * 3.5)
|
||||
rl.draw_ring(
|
||||
arc_center,
|
||||
inner_r - 4.0,
|
||||
outer_r + 4.0,
|
||||
start_deg,
|
||||
active_end,
|
||||
32,
|
||||
rl.Color(sr, sg, sb, int(65 * glow_pulse * alpha)),
|
||||
)
|
||||
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, active_end, 32, speed_color)
|
||||
|
||||
# Rounded start cap & bright glowing tip pip
|
||||
s_rad = math.radians(start_deg)
|
||||
e_rad = math.radians(active_end)
|
||||
rl.draw_circle(int(arc_center.x + math.cos(s_rad) * mid_r), int(arc_center.y + math.sin(s_rad) * mid_r), cap_r, speed_color)
|
||||
tip_x = arc_center.x + math.cos(e_rad) * mid_r
|
||||
tip_y = arc_center.y + math.sin(e_rad) * mid_r
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(tip_x, tip_y),
|
||||
14.0,
|
||||
rl.Color(255, 255, 255, int(140 * glow_pulse * alpha)),
|
||||
rl.Color(sr, sg, sb, 0),
|
||||
)
|
||||
rl.draw_circle(int(tip_x), int(tip_y), cap_r + 1.5, rl.Color(255, 255, 255, int(235 * alpha)))
|
||||
|
||||
def render_corner_badge(self, rect: rl.Rectangle, snap: DrivingSnapshot, alpha: float) -> None:
|
||||
"""Subtle top-left Set-Speed / engagement pill visible during normal hero-face mode."""
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
_, set_speed = display_speed_and_set_speed(snap)
|
||||
sr, sg, sb = self._speed_color(snap)
|
||||
dot_pulse = 0.72 + 0.28 * math.sin(t * 3.0)
|
||||
|
||||
x = rect.x + 16.0
|
||||
y = rect.y + 12.0
|
||||
|
||||
if set_speed is not None:
|
||||
text = str(set_speed)
|
||||
sz = measure_text_cached(self._font_semi_bold, text, self.BADGE_SPEED_FONT_SIZE)
|
||||
pill_w = sz.x + 48.0
|
||||
pill_h = 38.0
|
||||
pill_rec = rl.Rectangle(x, y, pill_w, pill_h)
|
||||
rl.draw_rectangle_rounded(pill_rec, 0.5, 14, rl.Color(255, 255, 255, int(22 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill_rec, 0.5, 14, 1.5, rl.Color(255, 255, 255, int(35 * alpha)))
|
||||
rl.draw_circle(int(x + 16), int(y + pill_h / 2.0), 5.0, rl.Color(sr, sg, sb, int(235 * dot_pulse * alpha)))
|
||||
rl.draw_text_ex(
|
||||
self._font_semi_bold,
|
||||
text,
|
||||
rl.Vector2(x + 28.0, y + (pill_h - sz.y) / 2.0),
|
||||
self.BADGE_SPEED_FONT_SIZE,
|
||||
0,
|
||||
rl.Color(255, 255, 255, int(210 * alpha)),
|
||||
)
|
||||
else:
|
||||
rl.draw_circle(int(x + 10), int(y + 12), 5.5, rl.Color(sr, sg, sb, int(200 * dot_pulse * alpha)))
|
||||
|
||||
def _draw_tiny_heart(self, cx: float, cy: float, radius: float, color: rl.Color) -> None:
|
||||
scale = radius / 16.0
|
||||
n_pts = 32
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(n_pts):
|
||||
ang = (i / n_pts) * math.tau
|
||||
s = math.sin(ang)
|
||||
hx = 16.0 * (s * s * s)
|
||||
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
|
||||
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
|
||||
center = rl.Vector2(cx, cy + radius * 0.05)
|
||||
for i in range(n_pts):
|
||||
rl.draw_triangle(center, pts[(i + 1) % n_pts], pts[i], color)
|
||||
@@ -8,7 +8,6 @@ from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.blendful import BlendfulRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.chevron_metrics import ChevronMetrics
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import RadarTracks
|
||||
from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath
|
||||
from openpilot.selfdrive.ui.sunnypilot.ui_state import UIStateSP
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
@@ -18,7 +17,6 @@ class ModelRendererSP:
|
||||
def __init__(self):
|
||||
self.rainbow_path = RainbowPath()
|
||||
self.chevron_metrics = ChevronMetrics()
|
||||
self.radar_tracks = RadarTracks()
|
||||
self.blendful = BlendfulRenderer(readout=False)
|
||||
self._width_filter = FirstOrderFilter(0.9, 0.1, 1 / gui_app.target_fps)
|
||||
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
import pyray as rl
|
||||
from opendbc.car.hyundai.radar_interface import RADAR_235_248, RADAR_3A5_3C4
|
||||
|
||||
NEUTRAL_COLOR = (255, 255, 255)
|
||||
DBC_MOVING_COLOR = (190, 125, 255)
|
||||
DBC_UNKNOWN_COLOR = (154, 168, 184)
|
||||
DBC_MOTION_STATIONARY = 1
|
||||
DBC_MOTION_MOVING = 2
|
||||
LEAD_TRACK_COLORS = (
|
||||
rl.Color(255, 215, 0, 255),
|
||||
rl.Color(255, 140, 0, 220),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProjectedRadarTrack:
|
||||
x: float
|
||||
y: float
|
||||
radius: float
|
||||
color: object
|
||||
source_index: int
|
||||
camera_object: bool
|
||||
track_id: int
|
||||
|
||||
|
||||
def is_preferred_radar_source(source) -> bool:
|
||||
return source.startAddress == RADAR_3A5_3C4.start_addr and source.endAddress == RADAR_3A5_3C4.end_addr
|
||||
|
||||
|
||||
def radar_source_sort_key(source) -> tuple[bool, int, int, int]:
|
||||
return (
|
||||
not is_preferred_radar_source(source),
|
||||
int(source.startAddress),
|
||||
int(source.endAddress),
|
||||
int(source.bus),
|
||||
)
|
||||
|
||||
|
||||
def sorted_radar_sources(live_tracks):
|
||||
return sorted(live_tracks.trackSources, key=radar_source_sort_key)
|
||||
|
||||
|
||||
def radar_track_source_index(track, sources) -> int:
|
||||
address = int(track.sourceAddress)
|
||||
bus = int(track.sourceBus)
|
||||
if address != 0:
|
||||
return next((
|
||||
index for index, source in enumerate(sources)
|
||||
if source.startAddress <= address <= source.endAddress and source.bus == bus
|
||||
), 0)
|
||||
return 0
|
||||
|
||||
|
||||
def is_camera_object_source(source) -> bool:
|
||||
return source.startAddress == RADAR_235_248.start_addr and source.endAddress == RADAR_235_248.end_addr
|
||||
|
||||
|
||||
def radar_track_source(track, sources):
|
||||
address = int(track.sourceAddress)
|
||||
bus = int(track.sourceBus)
|
||||
if address == 0:
|
||||
return None
|
||||
return next((
|
||||
source for source in sources
|
||||
if source.startAddress <= address <= source.endAddress and source.bus == bus
|
||||
), None)
|
||||
|
||||
|
||||
|
||||
def draw_radar_source_marker(center: rl.Vector2, radius: float, color: rl.Color, source_index: int,
|
||||
camera_object: bool = False) -> None:
|
||||
if camera_object:
|
||||
rl.draw_poly(center, 3, radius, -90.0, color)
|
||||
return
|
||||
if source_index <= 0:
|
||||
rl.draw_circle(int(center.x), int(center.y), radius, color)
|
||||
return
|
||||
sides = (4, 3, 5, 6)[(source_index - 1) % 4]
|
||||
rotation = 45.0 if sides == 4 else -90.0
|
||||
rl.draw_poly(center, sides, radius, rotation, color)
|
||||
|
||||
|
||||
def radar_track_display(motion_state: int) -> tuple[rl.Color, bool]:
|
||||
"""Color tracks exclusively from the radar's DBC motion classification."""
|
||||
if motion_state == DBC_MOTION_STATIONARY:
|
||||
return rl.Color(*NEUTRAL_COLOR, 255), True
|
||||
if motion_state == DBC_MOTION_MOVING:
|
||||
return rl.Color(*DBC_MOVING_COLOR, 255), False
|
||||
return rl.Color(*DBC_UNKNOWN_COLOR, 255), False
|
||||
|
||||
|
||||
def radar_lead_track_colors(radar_state) -> dict[int, rl.Color]:
|
||||
highlighted_tracks = {}
|
||||
if radar_state is None:
|
||||
return highlighted_tracks
|
||||
|
||||
for lead, color in zip((radar_state.leadOne, radar_state.leadTwo), LEAD_TRACK_COLORS, strict=True):
|
||||
if lead.present and lead.radar and lead.radarTrackId >= 0:
|
||||
highlighted_tracks.setdefault(int(lead.radarTrackId), color)
|
||||
return highlighted_tracks
|
||||
|
||||
|
||||
def draw_radar_lead_connectors(lead_vehicles, matched_positions, highlighted_tracks, screen_offset=(0, 0)) -> None:
|
||||
for lead in lead_vehicles:
|
||||
if not lead.radar or lead.position is None or lead.radar_track_id not in matched_positions:
|
||||
continue
|
||||
|
||||
radar_position = matched_positions[lead.radar_track_id]
|
||||
lead_position = (lead.position[0] + screen_offset[0], lead.position[1] + screen_offset[1])
|
||||
if math.dist(lead_position, radar_position) < 4:
|
||||
continue
|
||||
|
||||
rl.draw_line_ex(
|
||||
rl.Vector2(*lead_position), rl.Vector2(*radar_position), 2,
|
||||
highlighted_tracks[lead.radar_track_id],
|
||||
)
|
||||
|
||||
|
||||
class RadarTracks:
|
||||
def __init__(self):
|
||||
self._projected_tracks: tuple[ProjectedRadarTrack, ...] = ()
|
||||
self._projection_initialized = False
|
||||
|
||||
@property
|
||||
def projection_initialized(self) -> bool:
|
||||
return self._projection_initialized
|
||||
|
||||
def clear_projection(self) -> None:
|
||||
self._projected_tracks = ()
|
||||
self._projection_initialized = False
|
||||
|
||||
def update_radar_tracks(self, live_tracks, map_to_screen, path_offset_z, track_size=7) -> None:
|
||||
projected_tracks = []
|
||||
sources = sorted_radar_sources(live_tracks)
|
||||
|
||||
for track in live_tracks.points:
|
||||
d_rel, y_rel, v_rel = track.dRel, track.yRel, track.vRel
|
||||
if not (math.isfinite(d_rel) and math.isfinite(y_rel) and math.isfinite(v_rel)):
|
||||
continue
|
||||
|
||||
motion_state = int(track.motionState)
|
||||
if motion_state not in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING):
|
||||
continue
|
||||
|
||||
pt = map_to_screen(d_rel, -y_rel, path_offset_z)
|
||||
if pt is None:
|
||||
continue
|
||||
|
||||
color, stationary = radar_track_display(motion_state)
|
||||
radius = max(1, track_size - 5) if stationary else track_size
|
||||
source = radar_track_source(track, sources)
|
||||
projected_tracks.append(ProjectedRadarTrack(
|
||||
x=pt[0],
|
||||
y=pt[1],
|
||||
radius=radius,
|
||||
color=color,
|
||||
source_index=radar_track_source_index(track, sources),
|
||||
camera_object=source is not None and is_camera_object_source(source),
|
||||
track_id=int(track.trackId),
|
||||
))
|
||||
|
||||
self._projected_tracks = tuple(projected_tracks)
|
||||
self._projection_initialized = True
|
||||
|
||||
def draw_cached_radar_tracks(self, screen_offset=(0, 0), highlighted_tracks=None):
|
||||
highlighted_tracks = highlighted_tracks or {}
|
||||
highlighted_positions = {}
|
||||
|
||||
for track in self._projected_tracks:
|
||||
x, y = track.x + screen_offset[0], track.y + screen_offset[1]
|
||||
highlight_color = highlighted_tracks.get(track.track_id)
|
||||
if highlight_color is not None:
|
||||
center = rl.Vector2(int(x), int(y))
|
||||
rl.draw_ring(center, track.radius + 2, track.radius + 5, 0, 360, 24, highlight_color)
|
||||
highlighted_positions[track.track_id] = (x, y)
|
||||
draw_radar_source_marker(
|
||||
rl.Vector2(x, y), track.radius, track.color, track.source_index, track.camera_object,
|
||||
)
|
||||
|
||||
return highlighted_positions
|
||||
|
||||
def draw_radar_tracks(self, live_tracks, map_to_screen, path_offset_z, track_size=7, screen_offset=(0, 0), v_ego=0.0,
|
||||
highlighted_tracks=None):
|
||||
self.update_radar_tracks(live_tracks, map_to_screen, path_offset_z, track_size)
|
||||
return self.draw_cached_radar_tracks(screen_offset, highlighted_tracks)
|
||||
@@ -36,8 +36,7 @@ class UIStateSP:
|
||||
self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch")
|
||||
self.sm_services_ext = [
|
||||
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
|
||||
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP",
|
||||
"gyroscope",
|
||||
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP"
|
||||
]
|
||||
|
||||
self.sunnylink_state = SunnylinkState()
|
||||
@@ -52,9 +51,7 @@ class UIStateSP:
|
||||
self.chevron_metrics = None
|
||||
self.custom_interactive_timeout: int = 0
|
||||
self.developer_ui = None
|
||||
self.draw_radar_tracks: bool = self.params.get_bool("DrawRadarTracks")
|
||||
self.hide_v_ego_ui: bool = False
|
||||
self.mici_robotic_ui: bool = self.params.get_bool("MiciRoboticUI")
|
||||
self.onroad_brightness: int = 0
|
||||
self.onroad_brightness_timer: int = 0
|
||||
self.onroad_brightness_timer_param: int = 0
|
||||
@@ -178,9 +175,7 @@ class UIStateSP:
|
||||
self.chevron_metrics = self.params.get("ChevronInfo")
|
||||
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
|
||||
self.developer_ui = self.params.get("DevUIInfo")
|
||||
self.draw_radar_tracks = self.params.get_bool("DrawRadarTracks")
|
||||
self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI")
|
||||
self.mici_robotic_ui = self.params.get_bool("MiciRoboticUI")
|
||||
self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True)))
|
||||
self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True)
|
||||
self.rainbow_path = self.params.get_bool("RainbowMode")
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import wave
|
||||
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.cereal.messaging import SubMaster, PubMaster
|
||||
from openpilot.selfdrive.ui.soundd import SAMPLE_RATE, SELFDRIVE_STATE_TIMEOUT, Soundd, check_selfdrive_timeout_alert
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import ROBOTIC_SOUND_FILES, ROBOTIC_SOUNDS_DIR, RoboticSoundPack
|
||||
from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
|
||||
@@ -59,86 +56,4 @@ class TestSoundd(OpenpilotTestCase):
|
||||
|
||||
assert check_selfdrive_timeout_alert(sm)
|
||||
|
||||
def test_robotic_sound_pack_wav_formats(self):
|
||||
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
|
||||
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
|
||||
assert os.path.exists(path), f"Missing robotic sound for {alert_id}: {path}"
|
||||
with wave.open(path, "r") as wf:
|
||||
assert wf.getnchannels() == 1, f"{filename} must be mono"
|
||||
assert wf.getsampwidth() == 2, f"{filename} must be 16-bit PCM"
|
||||
assert wf.getframerate() == SAMPLE_RATE, f"{filename} must be {SAMPLE_RATE} Hz"
|
||||
assert wf.getnframes() > 0, f"{filename} must not be empty"
|
||||
|
||||
def test_robotic_sound_pack_switching_and_quiet_mode(self):
|
||||
class _FakeParams:
|
||||
def __init__(self):
|
||||
self.vals = {"MiciRoboticUI": False, "QuietMode": False}
|
||||
|
||||
def get_bool(self, key: str) -> bool:
|
||||
return self.vals.get(key, False)
|
||||
|
||||
fake_params = _FakeParams()
|
||||
pack = RoboticSoundPack(fake_params, SAMPLE_RATE)
|
||||
pack.load()
|
||||
assert set(ROBOTIC_SOUND_FILES).issubset(pack.sounds)
|
||||
|
||||
soundd = Soundd.__new__(Soundd)
|
||||
soundd.params = fake_params
|
||||
soundd.enabled = False
|
||||
soundd._frame = 0
|
||||
soundd.robotic_sound_pack = pack
|
||||
soundd.load_sounds()
|
||||
soundd.current_alert = AudibleAlert.engage
|
||||
soundd.current_volume = 1.0
|
||||
soundd.current_sound_frame = 0
|
||||
soundd.pending_stop = False
|
||||
|
||||
# Default buffer used when MiciRoboticUI is False
|
||||
buf_default = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
|
||||
assert buf_default is soundd.loaded_sounds[AudibleAlert.engage]
|
||||
|
||||
# Switching MiciRoboticUI to True swaps buffer to robotic sound
|
||||
fake_params.vals["MiciRoboticUI"] = True
|
||||
assert pack.refresh_param() is True
|
||||
buf_robotic = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
|
||||
assert buf_robotic is pack.sounds[AudibleAlert.engage]
|
||||
assert buf_robotic is not buf_default
|
||||
|
||||
# QuietMode still suppresses non-critical robotic engage chirp
|
||||
soundd.enabled = True
|
||||
assert not soundd.should_play_sound(AudibleAlert.engage)
|
||||
assert soundd.should_play_sound(AudibleAlert.warningImmediate)
|
||||
|
||||
def test_robotic_sound_pack_lfs_fallback_and_reactive_chirps(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import (
|
||||
CHIRP_BOOST,
|
||||
CHIRP_SPEED_UP,
|
||||
CHIRP_STARTLED,
|
||||
REACTIVE_CHIRP_IDS,
|
||||
)
|
||||
|
||||
class _FakeParams:
|
||||
def get_bool(self, key: str) -> bool:
|
||||
return key == "MiciRoboticUI"
|
||||
|
||||
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
|
||||
pack.load()
|
||||
for cid in REACTIVE_CHIRP_IDS:
|
||||
assert cid in pack.sounds and len(pack.sounds[cid]) > 0
|
||||
|
||||
class _FakeSM:
|
||||
def __init__(self, v_cruise=100.0, a_ego=0.0):
|
||||
self.updated = {"carState": True, "userBookmark": False, "bookmarkButton": False}
|
||||
self.valid = {"controlsState": False}
|
||||
self._cs = SimpleNamespace(vCruiseCluster=v_cruise, leftBlinker=False, rightBlinker=False, standstill=False, aEgo=a_ego)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self._cs
|
||||
|
||||
assert pack.detect_reactive_chirp(_FakeSM(100.0, 0.0), now=10.0) is None # first sample seeds prev_set_speed
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, 0.0), now=11.0) == CHIRP_SPEED_UP
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, -3.5), now=12.0) == CHIRP_STARTLED
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, 2.6), now=13.0) == CHIRP_BOOST
|
||||
|
||||
# TODO: add test with micd for checking that soundd actually outputs sounds
|
||||
|
||||
@@ -77,7 +77,6 @@ class UIState(UIStateSP):
|
||||
"vehicleParameters",
|
||||
"testJoystick",
|
||||
"rawAudioData",
|
||||
"radarTracks",
|
||||
] + self.sm_services_ext
|
||||
)
|
||||
|
||||
|
||||
@@ -8,10 +8,10 @@ import numpy as np
|
||||
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.realtime import DT_MDL
|
||||
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
|
||||
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants
|
||||
|
||||
LANE_WIDTH_DEFAULT = 3.6 # m
|
||||
LANE_WIDTH_CLIP = (2.4, 4.5) # m
|
||||
LANE_WIDTH_CLIP = (2.8, 4.5) # m
|
||||
LOOKAHEAD_TIME = 1.5 # s
|
||||
MIN_LOOKAHEAD = 10.0 # m
|
||||
MIN_SPEED = 5.0 # m/s
|
||||
@@ -19,11 +19,6 @@ LINE_STD = (0.2, 0.6)
|
||||
POINT_STD = 0.1
|
||||
YIELD = (0.2, 0.45)
|
||||
X_IDXS = np.array(ModelConstants.X_IDXS)
|
||||
JUMP = 0.5
|
||||
JUMP_TAU = 0.5
|
||||
JUMP_ACCEPT = 3.0
|
||||
WIDEN = 0.4
|
||||
YAW_RATE = Plan.ORIENTATION_RATE.start + 2 # matched .991 correlation to actual car
|
||||
|
||||
|
||||
class Blendful:
|
||||
@@ -41,8 +36,7 @@ class Blendful:
|
||||
self.l_prob = 0.0
|
||||
self.r_prob = 0.0
|
||||
self.model_curvature = 0.0
|
||||
self.ref = None
|
||||
self.jumped = np.zeros(2)
|
||||
self.smooth = 0.0 # smooths the correction target below .53 lat accel
|
||||
self.curvature = 0.0
|
||||
|
||||
def update(self, model_output: dict[str, np.ndarray], v_ego: float, active: bool, model_curvature: float, enabled: bool = True) -> float:
|
||||
@@ -58,8 +52,8 @@ class Blendful:
|
||||
self.usual_offset.initialized = False
|
||||
self.lane_width.initialized = False
|
||||
self.going_around = False
|
||||
self.ref = None
|
||||
target = 0.0 if fading else self._target(model_output, v_ego, model_curvature)
|
||||
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 0.0]))
|
||||
build = 0.5 / max(v_ego, 1.0) ** 2 * DT_MDL # jerk over 1 second
|
||||
release = (0.5 if fading else 2.0) / max(v_ego, 1.0) ** 2 * DT_MDL # lets go fast, but past zero it builds like any other pull
|
||||
k = self.curvature
|
||||
@@ -69,10 +63,6 @@ class Blendful:
|
||||
def _target(self, model_output: dict[str, np.ndarray], v_ego: float, model_curvature: float) -> float:
|
||||
lookahead = max(v_ego * LOOKAHEAD_TIME, MIN_LOOKAHEAD)
|
||||
lines = model_output['lane_lines'][0, :, :, 0]
|
||||
plan = model_output['plan'][0]
|
||||
self._jumps(lines[1:3], v_ego, plan[0, YAW_RATE] if plan.shape[-1] > YAW_RATE else model_curvature * v_ego,
|
||||
np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [JUMP_TAU, 0.0]), lookahead)
|
||||
held = bool(np.any((self.jumped > 0) & (self.jumped < JUMP_ACCEPT)))
|
||||
stds = model_output['lane_lines_stds'][0, :, :, 0]
|
||||
|
||||
lone_weight = np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 1.0]) # 0.5 on straights, 1.0 in curves
|
||||
@@ -93,8 +83,6 @@ class Blendful:
|
||||
lane_trust = min(l_prob, r_prob)
|
||||
else:
|
||||
lane_trust = l_prob + r_prob - l_prob * r_prob
|
||||
if held or (l_prob * r_prob > 0.5 and np.interp(lookahead, X_IDXS, lines[2] - lines[1]) > self.lane_width.x + WIDEN):
|
||||
lane_trust = 0.0
|
||||
if lone_weight > 0.5 and lane_trust < self.line_trust:
|
||||
lane_trust = self.line_trust + (lane_trust - self.line_trust) * DT_MDL / (lone_weight - 0.5 + DT_MDL)
|
||||
self.line_trust = lane_trust
|
||||
@@ -108,7 +96,7 @@ class Blendful:
|
||||
win = (X_IDXS >= 0.5 * lookahead) & (X_IDXS <= 1.5 * lookahead)
|
||||
x = X_IDXS[win]
|
||||
half_width = self.lane_width.x / 2
|
||||
if l_prob * r_prob > 0.5 and not held:
|
||||
if l_prob * r_prob > 0.5:
|
||||
width = np.interp(lookahead, X_IDXS, lines[2]) - np.interp(lookahead, X_IDXS, lines[1])
|
||||
self.lane_width.update(float(np.clip(width, *LANE_WIDTH_CLIP)))
|
||||
half_width = np.clip(lines[2, win] - lines[1, win], *LANE_WIDTH_CLIP) / 2
|
||||
@@ -155,14 +143,3 @@ class Blendful:
|
||||
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (1.5 + DT_MDL)
|
||||
self.dk = dk
|
||||
return float(self.trust * dk)
|
||||
|
||||
def _jumps(self, raw: np.ndarray, v_ego: float, yaw_rate: float, tau: float, lookahead: float) -> None:
|
||||
if self.ref is None:
|
||||
self.ref, self.jumped = raw.copy(), np.zeros(2)
|
||||
return
|
||||
ref = np.array([np.interp(X_IDXS + v_ego * DT_MDL, X_IDXS, line) for line in self.ref]) - yaw_rate * DT_MDL * X_IDXS
|
||||
off = np.abs([np.interp(lookahead, X_IDXS, d) for d in raw - ref]) > JUMP
|
||||
self.jumped = np.where(off & ~off[::-1], self.jumped + DT_MDL, 0.0)
|
||||
self.ref = ref + (raw - ref) * DT_MDL / (DT_MDL + tau)
|
||||
accept = (self.jumped >= JUMP_ACCEPT) | off.all()
|
||||
self.ref[accept] = raw[accept]
|
||||
|
||||
@@ -371,7 +371,7 @@ def _compile_warp_resolution_worker(cam_w, cam_h, model_w, model_h, benchmark_ru
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if ('USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT')) and not os.getenv('DEV', '').startswith('MOCK'):
|
||||
if 'USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT'):
|
||||
from openpilot.system.hardware.chestnut.flash import link_up
|
||||
for _ in range(10):
|
||||
if link_up():
|
||||
|
||||
@@ -17,7 +17,6 @@ def main():
|
||||
parser.add_argument("--frame", required=True, help="width,height,stride,y_height,uv_height,buffer_size")
|
||||
parser.add_argument("--warp-to", required=True, help="model input WxH")
|
||||
parser.add_argument("--output", required=True)
|
||||
parser.add_argument("--light", action="store_true")
|
||||
parser.add_argument("--split-frames", action="store_true", help="one input per camera (frame, big_frame), bound to the camera buffers by pointer")
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -25,20 +24,18 @@ def main():
|
||||
from tinygrad import Device, Tensor, TinyJit
|
||||
frame = parse_frame(args.frame)
|
||||
warp = make_frame_prepare(frame, *parse_size(args.warp_to))
|
||||
n = 1 if args.light else 2
|
||||
cams = list(range(n))
|
||||
rng = np.random.default_rng(42)
|
||||
frames = rng.integers(0, 256, (2, frame.size), dtype=np.uint8)
|
||||
m_inv = Tensor((rng.standard_normal((n, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize()
|
||||
m_inv = Tensor((rng.standard_normal((2, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize()
|
||||
if args.split_frames:
|
||||
names = [("frame", "big_frame")[c] for c in cams]
|
||||
run = TinyJit(lambda M_inv, **f: Tensor.stack(*(warp(f[nm], M_inv[i]) for i, nm in enumerate(names))), prune=True)
|
||||
inputs = {nm: Tensor(frames[c], device=Device.DEFAULT).realize() for nm, c in zip(names, cams, strict=True)} | {"M_inv": m_inv}
|
||||
specs = {nm: ((frame.size,), "|u1", Device.DEFAULT) for nm in names} | {"M_inv": ((n, 3, 3), "<f4", Device.DEFAULT)} # noqa: C420
|
||||
run = TinyJit(lambda frame, big_frame, M_inv: Tensor.stack(warp(frame, M_inv[0]), warp(big_frame, M_inv[1])), prune=True)
|
||||
inputs = {"frame": Tensor(frames[0], device=Device.DEFAULT).realize(), "big_frame": Tensor(frames[1], device=Device.DEFAULT).realize(), "M_inv": m_inv}
|
||||
specs = {"frame": ((frame.size,), "|u1", Device.DEFAULT), "big_frame": ((frame.size,), "|u1", Device.DEFAULT),
|
||||
"M_inv": ((2, 3, 3), "<f4", Device.DEFAULT)}
|
||||
else:
|
||||
run = TinyJit(lambda input_frame, M_inv: Tensor.stack(*(warp(input_frame[c], M_inv[i]) for i, c in enumerate(cams))), prune=True)
|
||||
run = TinyJit(lambda input_frame, M_inv: Tensor.stack(*(warp(input_frame[i], M_inv[i]) for i in range(2))), prune=True)
|
||||
inputs = {"input_frame": Tensor(frames, device=Device.DEFAULT).realize(), "M_inv": m_inv}
|
||||
specs = {"input_frame": ((2, frame.size), "|u1", Device.DEFAULT), "M_inv": ((n, 3, 3), "<f4", Device.DEFAULT)}
|
||||
specs = {"input_frame": ((2, frame.size), "|u1", Device.DEFAULT), "M_inv": ((2, 3, 3), "<f4", Device.DEFAULT)}
|
||||
with record_kernel_linear() as recorded:
|
||||
run(**inputs)
|
||||
run(**inputs)
|
||||
|
||||
@@ -10,7 +10,6 @@ import dataclasses
|
||||
import inspect
|
||||
import itertools
|
||||
import mmap
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import tempfile
|
||||
@@ -195,8 +194,7 @@ def convert(jit, kwargs: dict, frame: dict, target) -> tuple[dict, memoryview]:
|
||||
base, at, nbytes = _address(argument_words[slot])
|
||||
args.append({"buffer": buffers.setdefault(base, len(buffers)), "offset": at, "nbytes": nbytes or base.max_numel() * base.dtype.itemsize, "dtype": u8})
|
||||
outs, ins = kernel[6]
|
||||
device_target = dataclasses.asdict(dataclasses.replace(target, interface=target.interface.removeprefix("MOCK")))
|
||||
calls.append({"kind": "program", "name": re.sub(r"\x1b\[[0-9;]*m", "", kernel[1]), "lib": programs[image_alloc], "target": device_target,
|
||||
calls.append({"kind": "program", "name": re.sub(r"\x1b\[[0-9;]*m", "", kernel[1]), "lib": programs[image_alloc], "target": dataclasses.asdict(target),
|
||||
"signature": [[f"data{i}", i, u8, [a.get("nbytes", 1)]] for i, a in enumerate(args)], "global_size": grid, "local_size": local,
|
||||
"globals": list(range(len(args))), "outs": list(outs), "ins": list(ins), "args": args})
|
||||
needs_init |= {args[i]["buffer"] for i in ins if "buffer" in args[i] and args[i]["buffer"] not in written}
|
||||
@@ -237,16 +235,14 @@ def main():
|
||||
frame, _ = capture_frame(artifact["run"], kwargs, "output_buffers")
|
||||
part = convert(artifact["run"], kwargs, frame, Device[Device.DEFAULT].renderer.target)
|
||||
|
||||
if not os.getenv("MOCKUSB_SOCKET"):
|
||||
plain = PlainJit(*part)
|
||||
replay = {path[0]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 1}
|
||||
replay["output_buffers"] = {path[1]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 2}
|
||||
flatten(plain(**replay))
|
||||
for index, (got, expected) in enumerate(zip([t.numpy() for t in replay["output_buffers"].values()], frame["outputs"], strict=True)):
|
||||
assert np.array_equal(got, expected), f"output {index} of the plain artifact differs from the pickle"
|
||||
plain = PlainJit(*part) # replays the frame, within tolerance
|
||||
replay = {path[0]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 1}
|
||||
replay["output_buffers"] = {path[1]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 2}
|
||||
flatten(plain(**replay))
|
||||
for index, (got, expected) in enumerate(zip([t.numpy() for t in replay["output_buffers"].values()], frame["outputs"], strict=True)):
|
||||
assert np.array_equal(got, expected), f"output {index} of the plain artifact differs from the pickle"
|
||||
write_bundle(args.output, {"run": part}, {key: artifact[key] for key in ("metadata", "input_specs", "output_specs")})
|
||||
checked = "left to mock_parity" if os.getenv("MOCKUSB_SOCKET") else "bit-exact with the pickle"
|
||||
print(f"converted {len(part[0]['calls'])} kernels, {checked}: {args.output}")
|
||||
print(f"converted {len(part[0]['calls'])} kernels, bit-exact with the pickle: {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -12,6 +12,8 @@ from functools import partial
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.sunnypilot.modeld_v2.helpers import _dtype, read_parts
|
||||
|
||||
SPLIT_FRAMES = ("big_frame", "frame")
|
||||
|
||||
|
||||
def pack_layout(shapes: dict[str, tuple], frame_size: int) -> tuple[dict[str, int], int]:
|
||||
offsets, offset = {}, 0
|
||||
@@ -19,13 +21,6 @@ def pack_layout(shapes: dict[str, tuple], frame_size: int) -> tuple[dict[str, in
|
||||
offsets[name], offset = offset, offset + -(-math.prod(shape) * 4 // 128) * 128
|
||||
return offsets | {"frames": offset}, offset + 2 * frame_size
|
||||
|
||||
EXTRA_WARPS = {"light_img": "light_tfm"}
|
||||
SPLIT_FRAMES = ("big_frame", "frame")
|
||||
|
||||
def host_shapes(input_shapes: dict[str, tuple], states) -> dict[str, tuple]:
|
||||
shapes = {name: shape for name, shape in input_shapes.items() if name not in states and name != "new_img" and name not in EXTRA_WARPS}
|
||||
return shapes | {tfm: (1, 3, 3) for img, tfm in EXTRA_WARPS.items() if img in input_shapes}
|
||||
|
||||
|
||||
class _Blobs: # the model's and the warp's blobs as one address space, for a part whose ranges span both files
|
||||
def __init__(self, *blobs):
|
||||
@@ -37,46 +32,31 @@ class _Blobs: # the model's and the warp's blobs as one address space, for a pa
|
||||
|
||||
|
||||
def fused_with_warp(cam_w: int, cam_h: int, chestnut: bool): # load_model's extend: a native model runs upload, warp and model as one submit
|
||||
models, big = f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models", 'big_' if chestnut else ''
|
||||
return partial(frame_part, f"{models}/{big}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl",
|
||||
light_warp_path=f"{models}/{big}driving_lightwarp_{cam_w}x{cam_h}_tinygrad.pkl")
|
||||
return partial(frame_part, f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models/{'big_' if chestnut else ''}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl")
|
||||
|
||||
|
||||
def frame_part(warp_path: str, parts: dict, extras: dict, light_warp_path: str | None = None) -> dict:
|
||||
def frame_part(warp_path: str, parts: dict, extras: dict) -> dict:
|
||||
if "input_specs" not in extras: # a legacy model warps in its own parts
|
||||
return {}
|
||||
(model, model_blob), (warp, warp_blob) = parts["run"], read_parts(warp_path)[0]["run"]
|
||||
states = sorted(name for name in extras["input_specs"] if f"next_{name}" in extras["metadata"]["output_shapes"])
|
||||
host = host_shapes({name: shape for name, (shape, _, _) in extras["input_specs"].items()}, states)
|
||||
paths = {"light_img": light_warp_path}
|
||||
extra = [(img, tfm, *read_parts(paths[img])[0]["run"]) for img, tfm in EXTRA_WARPS.items() if img in extras["input_specs"]]
|
||||
split = any(s["name"] in SPLIT_FRAMES for s in warp["inputs"])
|
||||
assert all(any(s["name"] in SPLIT_FRAMES for s in part["inputs"]) == split for _, _, part, _ in extra), "camera and extra warps must share a frame layout"
|
||||
offsets, packed = pack_layout(host, 0 if split else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2)
|
||||
shift = len(model_blob)
|
||||
buf_base, blob_base = [len(model["buffers"]) + len(warp["buffers"])], [len(model_blob) + len(warp_blob)]
|
||||
for _, _, part, blob in extra:
|
||||
buf_base.append(buf_base[-1] + len(part["buffers"])); blob_base.append(blob_base[-1] + len(blob))
|
||||
upload, u8 = buf_base[-1], repr(_dtype("dtypes.uint8"))
|
||||
extra_at = {img: (part, buf_base[i], blob_base[i], tfm) for i, (img, tfm, part, _) in enumerate(extra)}
|
||||
host = {name: shape for name, (shape, _, _) in extras["input_specs"].items() if name not in states and name != "new_img"}
|
||||
frame_specs = {s["name"]: s for s in warp["inputs"] if s["name"] in SPLIT_FRAMES}
|
||||
offsets, packed = pack_layout(host, 0 if frame_specs else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2)
|
||||
shift, upload, u8 = len(model_blob), len(model["buffers"]) + len(warp["buffers"]), repr(_dtype("dtypes.uint8"))
|
||||
|
||||
def view(name: str, nbytes: int, dtype: str) -> dict:
|
||||
return {"buffer": upload, "offset": offsets[name], "nbytes": nbytes, "dtype": dtype}
|
||||
outputs = sorted(s["slot"] for s in model["inputs"] if s["name"] is None)
|
||||
frame_specs = {s["name"]: s for _, _, part, _ in [(None, None, warp, None), *extra] for s in part["inputs"] if s["name"] in SPLIT_FRAMES}
|
||||
names = sorted(["host", *states, *frame_specs])
|
||||
slots = {s["slot"]: names.index(s["name"]) for s in model["inputs"] if s["name"] in states} | \
|
||||
{slot: len(names) + i for i, slot in enumerate(outputs)}
|
||||
def warped(part: dict, base: int) -> dict:
|
||||
returned = part["returns"]["tensors"][0]
|
||||
return {k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + base}
|
||||
returned = warp["returns"]["tensors"][0]
|
||||
model_inputs = {s["slot"]: {"input": slots[s["slot"]]} if s["slot"] in slots else
|
||||
warped(warp, len(model["buffers"])) if s["name"] == "new_img" else
|
||||
warped(extra_at[s["name"]][0], extra_at[s["name"]][1]) if s["name"] in extra_at else
|
||||
{k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + len(model["buffers"])} if s["name"] == "new_img" else
|
||||
view(s["name"], s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in model["inputs"]}
|
||||
def warp_inputs(part: dict, tfm: str) -> dict:
|
||||
return {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else
|
||||
view("frames" if s["name"] == "input_frame" else tfm, s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in part["inputs"]}
|
||||
warp_inputs = {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else
|
||||
view("frames" if s["name"] == "input_frame" else "tfm", s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in warp["inputs"]}
|
||||
|
||||
def remap(calls: list, inputs: dict, buffers: int, lib: int) -> list:
|
||||
return [call | ({"lib": [call["lib"][0] + lib, call["lib"][1] + lib]} if "lib" in call else {}) |
|
||||
@@ -85,11 +65,8 @@ def frame_part(warp_path: str, parts: dict, extras: dict, light_warp_path: str |
|
||||
"inputs": [{"slot": names.index("host"), "name": "host", "dtype": u8, "numel": packed, "device": "NPY"}] +
|
||||
[s | {"slot": slots[s["slot"]]} for s in model["inputs"] if s["slot"] in slots] +
|
||||
[s | {"slot": names.index(name)} for name, s in frame_specs.items()],
|
||||
"buffers": model["buffers"] + [b | ({"init": [b["init"][0] + d, b["init"][1] + d]} if "init" in b else {})
|
||||
for part, d in ((warp, shift), *((p, bb) for p, _, bb, _ in extra_at.values())) for b in part["buffers"]] +
|
||||
"buffers": model["buffers"] + [b | ({"init": [b["init"][0] + shift, b["init"][1] + shift]} if "init" in b else {}) for b in warp["buffers"]] +
|
||||
[{"nbytes": packed, "device": model["inputs"][0]["device"], "dtype": u8}],
|
||||
"calls": [{"kind": "copy", "args": [{"buffer": upload, "offset": 0, "nbytes": packed, "dtype": u8}, {"input": names.index("host")}]}] +
|
||||
remap(warp["calls"], warp_inputs(warp, "tfm"), len(model["buffers"]), shift) +
|
||||
[c for p, b0, bb, tfm in extra_at.values() for c in remap(p["calls"], warp_inputs(p, tfm), b0, bb)] +
|
||||
remap(model["calls"], model_inputs, 0, 0)}
|
||||
return {"run": (header, _Blobs(model_blob, warp_blob, *(blob for *_, blob in extra)))}
|
||||
remap(warp["calls"], warp_inputs, len(model["buffers"]), shift) + remap(model["calls"], model_inputs, 0, 0)}
|
||||
return {"run": (header, _Blobs(model_blob, warp_blob))} # replaces the model's run: one set of buffers, no separate warp
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame
|
||||
from openpilot.common.transformations.orientation import rot_from_euler
|
||||
|
||||
LIGHT_INPUT_SIZE = (512, 256)
|
||||
light_intrinsics = np.array([
|
||||
[1000.0, 0.0, 256.0],
|
||||
[0.0, 1000.0, 200.0],
|
||||
[0.0, 0.0, 1.0]])
|
||||
calib_from_light = np.linalg.inv((light_intrinsics @ get_view_frame_from_calib_frame(0, 0, 0, 0))[:, :3])
|
||||
|
||||
|
||||
def get_light_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray) -> np.ndarray:
|
||||
camera_from_calib = intrinsics @ view_frame_from_device_frame @ rot_from_euler(device_from_calib_euler)
|
||||
return (camera_from_calib @ calib_from_light).astype(np.float32)
|
||||
@@ -1,153 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
os.environ.setdefault("DEV", "MOCKUSB+AMD")
|
||||
QCOM = "QCOM" in os.environ["DEV"]
|
||||
ON_MOCK = os.environ["DEV"].startswith("MOCK")
|
||||
ARCH, HARDWARE = ("a630", "comma 3x/4 (a630)") if QCOM else ("gfx1200", "chestnut")
|
||||
os.environ.setdefault("CHECK_OOB", "0")
|
||||
os.environ.setdefault("GMMU", "0")
|
||||
if sys.platform == "darwin" and os.environ["DEV"].startswith("MOCKUSB"): # the mock's VRAM is a memfd, which macOS lacks: an unlinked file is the same
|
||||
from tinygrad.runtime.autogen import libc
|
||||
|
||||
def _memfd_create(name, flags):
|
||||
fd, path = tempfile.mkstemp()
|
||||
os.unlink(path)
|
||||
return fd
|
||||
libc.memfd_create = _memfd_create
|
||||
|
||||
import numpy as np
|
||||
|
||||
from openpilot.sunnypilot.modeld_v2.helpers import ALIGNMENT, MAGIC, PlainJit, _device, read_parts
|
||||
|
||||
|
||||
class ParityError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _emulator():
|
||||
try:
|
||||
if QCOM:
|
||||
from test.mockgpu.qcom import emu
|
||||
else:
|
||||
from test.mockgpu.amd import emu
|
||||
except ImportError as e:
|
||||
raise ParityError(f"tinygrad's {'qcom' if QCOM else 'amd'} mock is not importable: put tinygrad_repo on PYTHONPATH") from e
|
||||
if not hasattr(emu, "hw_unverified"):
|
||||
raise ParityError(f"this tinygrad's emulator has no {ARCH} rounding model, its check frames would not match a {HARDWARE}")
|
||||
return emu
|
||||
|
||||
|
||||
def unverified(header: dict, blob: memoryview) -> dict[str, int]:
|
||||
emu, out = _emulator(), {}
|
||||
for call in header["calls"]:
|
||||
if call["kind"] != "program":
|
||||
continue
|
||||
if (arch := call["target"].get("arch", "")).split(",")[0] != ARCH: # IMAGE builds append ",IMAGE_PITCH_ALIGNMENT=64"
|
||||
out[f"arch={arch}"] = out.get(f"arch={arch}", 0) + 1
|
||||
continue
|
||||
for sig, n in emu.hw_unverified(bytes(blob[slice(*call["lib"])])).items():
|
||||
out[sig] = out.get(sig, 0) + n
|
||||
return out
|
||||
|
||||
|
||||
def _array(blob: memoryview, stored: dict) -> np.ndarray:
|
||||
return np.frombuffer(blob[slice(*stored["data"])], dtype=np.dtype(stored["dtype"])).reshape(stored["shape"]).copy()
|
||||
|
||||
|
||||
def replay(header: dict, blob: memoryview, shared: dict) -> list[np.ndarray]:
|
||||
from tinygrad import Tensor
|
||||
check = header["check"]
|
||||
jit = PlainJit(header, blob, None, verify=False, shared=shared)
|
||||
kwargs: dict = {}
|
||||
for path, stored, device in check["inputs"]:
|
||||
tensor = Tensor(_array(blob, stored), device=_device(device, None)).realize()
|
||||
kwargs[path[0]] = tensor if len(path) == 1 else {**kwargs.get(path[0], {}), path[1]: tensor}
|
||||
result = jit(**kwargs)
|
||||
outputs = kwargs[check["output_container"]].values() if check["output_container"] else result
|
||||
return [t.numpy() for t in (outputs if isinstance(outputs, (list, tuple)) or check["output_container"] else [outputs])]
|
||||
|
||||
|
||||
def _parts_with_offsets(path: str) -> tuple[dict, dict]:
|
||||
parts, _ = read_parts(path)
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(len(MAGIC) + 8)
|
||||
start = len(MAGIC) + 8 + struct.unpack_from("<Q", head, len(MAGIC))[0]
|
||||
f.seek(len(MAGIC) + 8)
|
||||
entries = json.loads(f.read(start - len(MAGIC) - 8))["parts"]
|
||||
base = start + -start % ALIGNMENT
|
||||
offsets = {tuple(e["key"]) if isinstance(e["key"], list) else e["key"]: base + e["blob"][0] for e in entries}
|
||||
return parts, offsets
|
||||
|
||||
|
||||
def _gate(parts: dict) -> None:
|
||||
missing: dict[str, int] = {}
|
||||
for header, blob in parts.values():
|
||||
if "check" not in header:
|
||||
raise ParityError("artifact has no check frame")
|
||||
for sig, n in unverified(header, blob).items():
|
||||
missing[sig] = missing.get(sig, 0) + n
|
||||
if missing:
|
||||
raise ParityError(f"kernels use instructions the emulator is not verified against a {HARDWARE} for: " +
|
||||
", ".join(f"{s} ({n}x)" for s, n in sorted(missing.items(), key=lambda kv: -kv[1])))
|
||||
|
||||
|
||||
def check(path: str) -> None:
|
||||
parts, _ = read_parts(path)
|
||||
if ON_MOCK:
|
||||
_gate(parts)
|
||||
shared: dict = {}
|
||||
for key, (header, blob) in parts.items():
|
||||
got = replay(header, blob, shared)
|
||||
for i, (g, stored) in enumerate(zip(got, header["check"]["outputs"], strict=True)):
|
||||
want = _array(blob, stored)
|
||||
if g.shape != want.shape or not np.array_equal(g.view(np.uint8), want.view(np.uint8)):
|
||||
n = int(np.count_nonzero(g != want)) if g.shape == want.shape else -1
|
||||
where = "mock" if ON_MOCK else "device"
|
||||
raise ParityError(f"part {key} output {i}: the {where}'s check frame differs from the stored one in {n} of {want.size} values")
|
||||
|
||||
|
||||
def record(path: str, out: str) -> None:
|
||||
parts, offsets = _parts_with_offsets(path)
|
||||
_gate(parts)
|
||||
shared, writes = {}, []
|
||||
for key, (header, blob) in parts.items():
|
||||
for g, stored in zip(replay(header, blob, shared), header["check"]["outputs"], strict=True):
|
||||
want = np.dtype(stored["dtype"])
|
||||
if tuple(g.shape) != tuple(stored["shape"]) or g.dtype != want:
|
||||
raise ParityError(f"part {key}: replayed output {g.dtype}{g.shape} does not fit the stored {want}{tuple(stored['shape'])}")
|
||||
writes.append((offsets[key] + stored["data"][0], np.ascontiguousarray(g).tobytes()))
|
||||
shutil.copyfile(path, out)
|
||||
with open(out, "r+b") as f:
|
||||
for offset, data in writes:
|
||||
f.seek(offset)
|
||||
f.write(data)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) < 2 or argv[0] not in ("check", "record") or (argv[0] == "record" and len(argv) != 3):
|
||||
print("usage: mock_parity check ARTIFACT... | record ARTIFACT OUT", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
if argv[0] == "record":
|
||||
st = time.perf_counter()
|
||||
record(argv[1], argv[2])
|
||||
print(f"{argv[2]}: check frame recorded on the mock in {time.perf_counter() - st:.0f}s")
|
||||
return 0
|
||||
for path in argv[1:]:
|
||||
st = time.perf_counter()
|
||||
check(path)
|
||||
print(f"{os.path.basename(path)}: bit-identical to its {HARDWARE} check frame on the {'mock' if ON_MOCK else 'device'} ({time.perf_counter() - st:.0f}s)")
|
||||
return 0
|
||||
except ParityError as e:
|
||||
print(f"PARITY FAIL: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -11,7 +11,7 @@ import pickle
|
||||
import numpy as np
|
||||
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.sunnypilot.modeld_v2.frame_fusion import host_shapes, pack_layout, SPLIT_FRAMES
|
||||
from openpilot.sunnypilot.modeld_v2.frame_fusion import pack_layout, SPLIT_FRAMES
|
||||
from openpilot.sunnypilot.modeld_v2.helpers import load_model
|
||||
from openpilot.sunnypilot.modeld_v2.compile_modeld import (POLICY_INPUTS, derive_frame_skip,
|
||||
make_split_input_queues, make_supercombo_input_queues)
|
||||
@@ -174,7 +174,7 @@ class NativeTinygradAdapter(BaseModelAdapter):
|
||||
|
||||
self.input_queues = {name: Tensor(np.zeros(shape, dtype=dtype), device=self.model_device).realize()
|
||||
for name, (shape, dtype) in self.input_shapes.items() if name in self.state_pairs}
|
||||
shapes = host_shapes({name: shape for name, (shape, _) in self.input_shapes.items()}, self.state_pairs)
|
||||
shapes = {name: shape for name, (shape, _) in self.input_shapes.items() if name not in self.state_pairs and name != 'new_img'}
|
||||
offsets, packed = pack_layout(shapes, 0 if self.split else self.warp_frame_size)
|
||||
self.packed_input = np.zeros(packed, dtype=np.uint8)
|
||||
self.host = Tensor(self.packed_input, device='NPY')
|
||||
|
||||
@@ -11,7 +11,6 @@ from functools import partial
|
||||
import gc
|
||||
import os
|
||||
os.environ['GMMU'] = '0'
|
||||
os.environ['QCOM_PRIORITY'] = '1'
|
||||
from tinygrad.device import Device
|
||||
import numpy as np
|
||||
import threading
|
||||
@@ -45,7 +44,6 @@ from openpilot.sunnypilot.modeld_v2.blendful import Blendful
|
||||
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
|
||||
from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants
|
||||
from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper
|
||||
from openpilot.sunnypilot.modeld_v2.light_frame import get_light_warp_matrix
|
||||
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
|
||||
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
|
||||
from openpilot.sunnypilot.modeld_v2.helpers import load_model
|
||||
@@ -173,7 +171,7 @@ class ModelState(ModelStateBase):
|
||||
np.where(inputs[desire_key] - self.prev_desire > .99, inputs[desire_key], 0)
|
||||
self.prev_desire[:] = inputs[desire_key]
|
||||
|
||||
for key in ('traffic_convention', 'lateral_control_params', 'action_t', 'speed_limit'):
|
||||
for key in ('traffic_convention', 'lateral_control_params', 'action_t'):
|
||||
if key in self.numpy_inputs and key in inputs:
|
||||
self.numpy_inputs[key][:] = inputs[key]
|
||||
|
||||
@@ -181,8 +179,6 @@ class ModelState(ModelStateBase):
|
||||
for i, key in enumerate(self._vision_input_names):
|
||||
if key in transforms:
|
||||
self.numpy_inputs['tfm'][i] = transforms[key].reshape(3, 3)
|
||||
if 'light_tfm' in self.numpy_inputs and 'light' in transforms:
|
||||
self.numpy_inputs['light_tfm'][0] = transforms['light'].reshape(3, 3)
|
||||
else:
|
||||
self.numpy_inputs['tfm'][:, :] = transforms[self._road_key].reshape(3, 3)
|
||||
self.numpy_inputs['big_tfm'][:, :] = transforms[self._wide_key].reshape(3, 3)
|
||||
@@ -342,7 +338,7 @@ def main(demo=False):
|
||||
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutGpuState"] if CHESTNUT else [])
|
||||
pm = PubMaster(pub_socks)
|
||||
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState",
|
||||
"carControl", "controlsState", "lateralDelay", "longitudinalPlanSP"])
|
||||
"carControl", "controlsState", "lateralDelay"])
|
||||
|
||||
publish_state = PublishState()
|
||||
chestnut_state = ChestnutGpuState(pm, model.chestnut) if CHESTNUT else None
|
||||
@@ -355,7 +351,6 @@ def main(demo=False):
|
||||
|
||||
model_transform_main = np.zeros((3, 3), dtype=np.float32)
|
||||
model_transform_extra = np.zeros((3, 3), dtype=np.float32)
|
||||
model_transform_light = np.zeros((3, 3), dtype=np.float32)
|
||||
live_calib_seen = False
|
||||
buf_main, buf_extra = None, None
|
||||
meta_main = FrameMeta()
|
||||
@@ -374,9 +369,6 @@ def main(demo=False):
|
||||
prev_action = log.ModelDataV2.Action()
|
||||
|
||||
DH = DesireHelper()
|
||||
desire_frames = [q.shape[0] for m in (model, small_model) if m is not None for name, q in m.adapter.input_queues.items() if 'desire' in name]
|
||||
if desire_frames:
|
||||
DH.turn_repulse = min(desire_frames) - 2
|
||||
meta_constants = load_meta_constants()
|
||||
RELC = RoadEdgeLaneChangeController()
|
||||
blendful = Blendful()
|
||||
@@ -433,7 +425,6 @@ def main(demo=False):
|
||||
model_transform_main = get_warp_matrix(device_from_calib_euler, main_intrinsics, False).astype(np.float32)
|
||||
model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.wide_road.intrinsics, True).astype(np.float32)
|
||||
model_transform_main, model_transform_extra = camera_offset_helper.update(model_transform_main, model_transform_extra, sm, main_wide_camera)
|
||||
model_transform_light = get_light_warp_matrix(device_from_calib_euler, main_intrinsics)
|
||||
live_calib_seen = True
|
||||
|
||||
traffic_convention = np.zeros(2)
|
||||
@@ -455,7 +446,6 @@ def main(demo=False):
|
||||
|
||||
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}
|
||||
transforms['light'] = model_transform_light
|
||||
|
||||
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)
|
||||
@@ -473,10 +463,6 @@ def main(demo=False):
|
||||
if 'action_t' in model.numpy_inputs:
|
||||
inputs['action_t'] = np.array([lat_action_t, long_action_t], dtype=np.float32)
|
||||
|
||||
if 'speed_limit' in model.numpy_inputs:
|
||||
resolver = sm['longitudinalPlanSP'].speedLimit.resolver
|
||||
inputs['speed_limit'] = np.array([resolver.speedLimitFinal if resolver.speedLimitValid else 0.0], dtype=np.float32)
|
||||
|
||||
mt1 = time.perf_counter()
|
||||
try:
|
||||
send_chestnut = (chestnut_state is not None and
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:1baac6f02902df5689e9e275633c122a9955b7c57de2681e0137e1724c1f32dd
|
||||
size 3463278
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:0478837491c584b2212e31a91c494a908b8fb048205700f05a02a13ee7fc9b90
|
||||
size 7690094
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:580fadf61ded34b4b19f0ba1f5e4b61c0ea489ca34a0952ccf2878593e3f68c4
|
||||
size 1851239
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:44700f3533abb3e65232c8aca46b48384a59218545ed6bb505c5d4762204359b
|
||||
size 3964263
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:1f5dd8855de07d0e8b9ed836934e1dcbe77aa27c3b5c77eee1f21888f974ba8b
|
||||
oid sha256:d776c72125156b5dd3eb59768409401e28c8a52a3a619cd3b9f02c10a156fda6
|
||||
size 3699072
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:226d40112a292077b7eca26b97273c56ab3a84feee8ddf9b6d02d46c2a7b8403
|
||||
oid sha256:a3f13ed12e087817a86afd48b2496c66c4f61a1925065b676b2945e81fabaacd
|
||||
size 7924864
|
||||
|
||||
@@ -80,8 +80,7 @@ def serialize_jit(jit, kernel_linear, check: dict | None = None) -> tuple[dict,
|
||||
if ast.op is Ops.PROGRAM:
|
||||
elf, info = ast.to_elf(), ast.arg
|
||||
global_size, local_size = info.launch_dims({})
|
||||
device_target = dataclasses.asdict(dataclasses.replace(elf.target, interface=elf.target.interface.removeprefix("MOCK")))
|
||||
calls.append({"kind": "program", "name": elf.name, "lib": blob.add(bytes(elf.lib)), "target": device_target,
|
||||
calls.append({"kind": "program", "name": elf.name, "lib": blob.add(bytes(elf.lib)), "target": dataclasses.asdict(elf.target),
|
||||
"signature": kernel_signature(ast, elf),
|
||||
"global_size": [int(x) for x in global_size], "local_size": [int(x) for x in local_size],
|
||||
"globals": list(info.globals), "outs": list(info.outs), "ins": list(info.ins), "args": arguments})
|
||||
|
||||
@@ -17,4 +17,4 @@ class TestRegistryModels(unittest.TestCase):
|
||||
self.skipTest("MODEL_BASE_NAME env var not set, skipping integration test.")
|
||||
bundle = load_model(os.path.join(os.environ.get("MODEL_DIR", "/tmp/models"), base_name), {"QCOM": "CPU", "AMD": "CPU"}, verify=False, cache=False)
|
||||
jits = [value for value in bundle.values() if isinstance(value, PlainJit)]
|
||||
assert "metadata" in bundle and jits and all(len(jit.captured._linear.src) > 0 for jit in jits)
|
||||
assert "metadata" in bundle and jits and all(len(jit.captured.linear.src) > 0 for jit in jits)
|
||||
|
||||
@@ -112,7 +112,7 @@ class ModelCache:
|
||||
|
||||
class ModelFetcher:
|
||||
"""Handles fetching and caching of model data from remote source"""
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v26.json"
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v25.json"
|
||||
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v28.json"
|
||||
|
||||
MODEL_SOURCES = {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:bd28c1e0a0dc15f5a1abc97cea2817f437880ed9e04fd7fc2ab1fb1b6a694ab0
|
||||
size 65812
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:e641bf54c1dd190ec903f12b06c761865b5bcfe918f015c4f8b781364a52817d
|
||||
size 33164
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4d94997ee61f7ba0f3afece1db5b0c9c16f32512832380fc0ac13c384d360efd
|
||||
size 56152
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:9c85ee1bdbede640c484da13c5a25bd40f7c165df5d2ed9b1db3edf15712aae7
|
||||
size 115522
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4b9cd0c5d6f06f53dd8781afe685a52ea52de717eabb3865a642b3464c851ac8
|
||||
size 31244
|
||||
@@ -1,219 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate EMO-inspired robotic chirps and vocoded voice alert WAVs (48 kHz, mono, 16-bit PCM).
|
||||
|
||||
Run this script whenever tweaking the robotic sound pack:
|
||||
python3 openpilot/sunnypilot/selfdrive/assets/sounds/robotic/generate_robotic_sounds.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
|
||||
import numpy as np
|
||||
|
||||
SAMPLE_RATE = 48000
|
||||
MAX_INT16 = 32767
|
||||
OUT_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def write_wav(path: Path, samples: np.ndarray) -> None:
|
||||
clipped = np.clip(samples, -1.0, 1.0)
|
||||
pcm = (clipped * MAX_INT16).astype(np.int16)
|
||||
with wave.open(str(path), "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(SAMPLE_RATE)
|
||||
wf.writeframes(pcm.tobytes())
|
||||
|
||||
|
||||
def adsr(n: int, attack: float = 0.015, release: float = 0.04) -> np.ndarray:
|
||||
env = np.ones(n, dtype=np.float32)
|
||||
a_n = min(n // 2, int(attack * SAMPLE_RATE))
|
||||
r_n = min(n // 2, int(release * SAMPLE_RATE))
|
||||
if a_n > 0:
|
||||
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
|
||||
if r_n > 0:
|
||||
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
|
||||
return env
|
||||
|
||||
|
||||
def emo_chirp(f_start: float, f_end: float, duration: float, vibrato_hz: float = 0.0, vibrato_depth: float = 0.0, gain: float = 0.65) -> np.ndarray:
|
||||
"""Synthesize an expressive EMO-like harmonic chirp with smooth pitch glide."""
|
||||
n = int(SAMPLE_RATE * duration)
|
||||
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
|
||||
# Smooth cubic-ish frequency glide
|
||||
progress = t / max(duration, 1e-6)
|
||||
s_curve = progress * progress * (3.0 - 2.0 * progress)
|
||||
freq = f_start + (f_end - f_start) * s_curve
|
||||
if vibrato_hz > 0.0:
|
||||
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
|
||||
phase = 2.0 * np.pi * np.cumsum(freq) / SAMPLE_RATE
|
||||
|
||||
# Warm robotic timbre: fundamental + soft 2nd & 3rd harmonics
|
||||
sig = (
|
||||
0.72 * np.sin(phase)
|
||||
+ 0.22 * np.sin(2.0 * phase + 0.3)
|
||||
+ 0.08 * np.sin(3.0 * phase)
|
||||
)
|
||||
env = adsr(n, attack=min(0.015, duration * 0.2), release=min(0.055, duration * 0.35))
|
||||
return (sig * env * gain).astype(np.float32)
|
||||
|
||||
|
||||
def silence(duration: float) -> np.ndarray:
|
||||
return np.zeros(int(SAMPLE_RATE * duration), dtype=np.float32)
|
||||
|
||||
|
||||
def robotize_voice(samples: np.ndarray, carrier_hz: float = 165.0) -> np.ndarray:
|
||||
"""Apply a clean EMO-style robotic vocoder / comb-resonance effect while keeping speech crisp."""
|
||||
n = len(samples)
|
||||
if n == 0:
|
||||
return samples
|
||||
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
|
||||
|
||||
# Normalize speech input
|
||||
peak = float(np.max(np.abs(samples)))
|
||||
if peak > 1e-5:
|
||||
samples = samples / peak
|
||||
|
||||
# Short metallic comb resonance (~5.5 ms delay) for unmistakable robot character
|
||||
delay = int(0.0055 * SAMPLE_RATE)
|
||||
comb = samples.copy()
|
||||
if delay < n:
|
||||
comb[delay:] += 0.42 * samples[:-delay]
|
||||
|
||||
# Gentle ring modulation blended with intelligible dry+comb voice
|
||||
carrier = 0.65 * np.sin(2.0 * np.pi * carrier_hz * t) + 0.35 * np.sin(2.0 * np.pi * carrier_hz * 2.0 * t)
|
||||
ring = comb * carrier
|
||||
blended = 0.62 * comb + 0.38 * ring
|
||||
|
||||
# Soft saturation & normalization
|
||||
blended = np.tanh(blended * 1.45)
|
||||
peak = float(np.max(np.abs(blended)))
|
||||
if peak > 1e-5:
|
||||
blended = blended / peak * 0.94
|
||||
return blended.astype(np.float32)
|
||||
|
||||
|
||||
def synthesize_robotic_phrase(text: str, rate: int = 205, carrier_hz: float = 175.0) -> np.ndarray | None:
|
||||
"""Render a short spoken phrase via macOS `say` + `ffmpeg`/`afconvert`, then robotize it."""
|
||||
say_bin = shutil.which("say")
|
||||
ffmpeg_bin = shutil.which("ffmpeg")
|
||||
if not say_bin or not ffmpeg_bin:
|
||||
return None
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
aiff_path = Path(tmpdir) / "speech.aiff"
|
||||
wav_path = Path(tmpdir) / "speech.wav"
|
||||
# Use a crisp clear voice ("Samantha" or system default) pitched up slightly via ffmpeg asetrate
|
||||
cmd_say = [say_bin, "-r", str(rate), "-o", str(aiff_path), text]
|
||||
subprocess.run(cmd_say, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
# Convert to 48kHz mono 16-bit WAV, slight pitch-up (+12%) for cute EMO-like robot timbre, trim silence
|
||||
cmd_ff = [
|
||||
ffmpeg_bin, "-y", "-i", str(aiff_path),
|
||||
"-af", "silenceremove=start_periods=1:start_threshold=-40dB:stop_periods=1:stop_threshold=-40dB,asetrate=22050*1.12,aresample=48000",
|
||||
"-ac", "1", "-ar", str(SAMPLE_RATE), "-sample_fmt", "s16",
|
||||
str(wav_path),
|
||||
]
|
||||
subprocess.run(cmd_ff, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
with wave.open(str(wav_path), "rb") as wf:
|
||||
raw = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0
|
||||
return robotize_voice(raw, carrier_hz=carrier_hz)
|
||||
|
||||
|
||||
def build_all_sounds() -> None:
|
||||
# 1. EMO-style expressive chirps & vocalizations (punchy & bubbly loudness matching stock WAVs)
|
||||
engage = np.concatenate([
|
||||
emo_chirp(660, 1020, 0.11, gain=0.88),
|
||||
silence(0.025),
|
||||
emo_chirp(1020, 1580, 0.19, vibrato_hz=24, vibrato_depth=28, gain=0.94),
|
||||
])
|
||||
write_wav(OUT_DIR / "engage.wav", engage)
|
||||
|
||||
disengage = np.concatenate([
|
||||
emo_chirp(1080, 740, 0.13, gain=0.86),
|
||||
silence(0.025),
|
||||
emo_chirp(700, 440, 0.19, gain=0.84),
|
||||
])
|
||||
write_wav(OUT_DIR / "disengage.wav", disengage)
|
||||
|
||||
refuse = np.concatenate([
|
||||
emo_chirp(480, 340, 0.12, vibrato_hz=32, vibrato_depth=28, gain=0.88),
|
||||
silence(0.04),
|
||||
emo_chirp(390, 270, 0.16, vibrato_hz=32, vibrato_depth=28, gain=0.88),
|
||||
])
|
||||
write_wav(OUT_DIR / "refuse.wav", refuse)
|
||||
|
||||
pre_alert = emo_chirp(860, 1480, 0.22, vibrato_hz=26, vibrato_depth=22, gain=0.88)
|
||||
write_wav(OUT_DIR / "pre_alert.wav", pre_alert)
|
||||
|
||||
prompt_low = emo_chirp(620, 500, 0.19, gain=0.84)
|
||||
write_wav(OUT_DIR / "prompt_single_low.wav", prompt_low)
|
||||
|
||||
prompt_high = emo_chirp(1080, 1420, 0.17, gain=0.88)
|
||||
write_wav(OUT_DIR / "prompt_single_high.wav", prompt_high)
|
||||
|
||||
# 2. Hybrid chirp + vocoded robotic spoken phrases for warnings & critical alerts
|
||||
def hybrid(intro: np.ndarray, phrase: str, fallback: np.ndarray, tail_pause: float = 0.0, carrier_hz: float = 175.0) -> np.ndarray:
|
||||
voice = synthesize_robotic_phrase(phrase, carrier_hz=carrier_hz)
|
||||
body = voice if voice is not None else fallback
|
||||
parts = [intro, silence(0.04), body]
|
||||
if tail_pause > 0.0:
|
||||
parts.append(silence(tail_pause))
|
||||
return np.concatenate(parts)
|
||||
|
||||
warning = hybrid(
|
||||
emo_chirp(820, 1120, 0.12, gain=0.65),
|
||||
"Heads up",
|
||||
emo_chirp(1120, 880, 0.22, gain=0.65),
|
||||
carrier_hz=185.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "warning.wav", warning)
|
||||
|
||||
warning_repeat = hybrid(
|
||||
emo_chirp(860, 1180, 0.12, gain=0.68),
|
||||
"Attention",
|
||||
emo_chirp(1180, 900, 0.22, gain=0.68),
|
||||
tail_pause=0.35,
|
||||
carrier_hz=185.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "warning_repeat.wav", warning_repeat)
|
||||
|
||||
dm_warning = hybrid(
|
||||
np.concatenate([emo_chirp(740, 1080, 0.10, gain=0.68), silence(0.03), emo_chirp(880, 1240, 0.10, gain=0.68)]),
|
||||
"Eyes on road",
|
||||
emo_chirp(1050, 780, 0.25, gain=0.68),
|
||||
tail_pause=0.35,
|
||||
carrier_hz=190.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "dm_warning.wav", dm_warning)
|
||||
|
||||
critical = hybrid(
|
||||
np.concatenate([emo_chirp(1320, 1520, 0.11, gain=0.80), silence(0.03), emo_chirp(1520, 1320, 0.11, gain=0.80)]),
|
||||
"Take control",
|
||||
emo_chirp(1480, 1100, 0.26, gain=0.80),
|
||||
tail_pause=0.28,
|
||||
carrier_hz=160.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "critical.wav", critical)
|
||||
|
||||
dm_critical = hybrid(
|
||||
np.concatenate([
|
||||
emo_chirp(1450, 1720, 0.09, gain=0.85),
|
||||
silence(0.025),
|
||||
emo_chirp(1450, 1720, 0.09, gain=0.85),
|
||||
]),
|
||||
"Take control now",
|
||||
emo_chirp(1680, 1200, 0.28, gain=0.85),
|
||||
tail_pause=0.22,
|
||||
carrier_hz=150.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "dm_critical.wav", dm_critical)
|
||||
|
||||
print(f"Generated 11 robotic WAV files in {OUT_DIR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_all_sounds()
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:19b08e539bdce2cefbcee335f513c24b6bc87792468c93a6cb22fe7aa8a9db90
|
||||
size 21164
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:fadc2782ae6a2459e4151fe0ad2d23ff2d061b74b53817391c8d9109ee00d321
|
||||
size 16364
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:9c58699ac691974880a9b49083a3f44ed95f1996aebfb85057e6b6bd012da2a2
|
||||
size 18284
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2a88e78d6fb30fd6b9093fa7dad87d9c754c97afaf53b0006882f2be60329a01
|
||||
size 30764
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:ed26262d283e696b73452e63486b656c777a4fe24914090e07e8f95f7a5c2461
|
||||
size 42098
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2e172036401b6c5d81ce922b6e5ed9e1bc39320646f8b7aa1df223f9e392fe90
|
||||
size 52158
|
||||
@@ -5,7 +5,6 @@ This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.cereal import log, custom
|
||||
from opendbc.car import structs
|
||||
|
||||
@@ -24,15 +23,10 @@ class CarSpecificEventsSP:
|
||||
self.CP_SP = CP_SP
|
||||
|
||||
self.low_speed_alert = False
|
||||
self.sm = messaging.SubMaster(['carStateSP'])
|
||||
|
||||
def update(self, CS: structs.CarState, events: Events):
|
||||
events_sp = EventsSP()
|
||||
|
||||
self.sm.update(0)
|
||||
if self.sm['carStateSP'].stockSteerIntervention:
|
||||
events_sp.add(EventNameSP.stockSteerIntervention)
|
||||
|
||||
if self.CP.brand == 'chrysler':
|
||||
if self.CP.carFingerprint in RAM_DT:
|
||||
# remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic
|
||||
|
||||
@@ -11,7 +11,6 @@ from opendbc.car.interfaces import CarInterfaceBase
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import PIDD_VERSION
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability
|
||||
|
||||
from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP
|
||||
@@ -56,18 +55,10 @@ def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_S
|
||||
CP_SP.pcmCruiseSpeed = False
|
||||
|
||||
|
||||
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool,
|
||||
params: Params | None = None) -> None:
|
||||
if params is None:
|
||||
params = Params()
|
||||
|
||||
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None:
|
||||
if nnlc_enabled or enforce_torque:
|
||||
CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning)
|
||||
|
||||
if enforce_torque and not nnlc_enabled and CP.steerControlType == structs.CarParams.SteerControlType.torque \
|
||||
and params.get("TorqueControlTune") == PIDD_VERSION:
|
||||
CP.lateralTuning.init('pid')
|
||||
|
||||
|
||||
def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params | None = None) -> None:
|
||||
if params is None:
|
||||
@@ -101,7 +92,7 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
|
||||
enforce_torque = _enforce_torque_lateral_control(CI.CP, params)
|
||||
nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params)
|
||||
_initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params)
|
||||
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled, params)
|
||||
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled)
|
||||
_cleanup_unsupported_params(CI.CP, CI.CP_SP)
|
||||
|
||||
try:
|
||||
@@ -114,8 +105,6 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
|
||||
def initialize_params(params) -> list[dict[str, Any]]:
|
||||
keys: list = []
|
||||
|
||||
keys.append("RadarTracks")
|
||||
|
||||
# hyundai
|
||||
keys.extend([
|
||||
"HyundaiLongitudinalTuning",
|
||||
|
||||
@@ -6,8 +6,6 @@ See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.cereal import log, custom
|
||||
|
||||
@@ -19,22 +17,6 @@ from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
|
||||
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, pidd_selected
|
||||
|
||||
|
||||
PATH_CURVATURE_LOOKAHEAD_SLICE = slice(2, 11) # ~0.04s to ~1.0s lookahead in T_IDXS
|
||||
PATH_CURVATURE_MIN_SPEED = 1.0 # m/s
|
||||
|
||||
|
||||
def path_curvature_ahead(model_v2) -> float:
|
||||
vx = model_v2.velocity.x
|
||||
oz = model_v2.orientationRate.z
|
||||
if len(vx) < 11 or len(oz) < 11 or vx[0] < PATH_CURVATURE_MIN_SPEED:
|
||||
return 0.0
|
||||
|
||||
vx_arr = np.maximum(np.asarray(vx, dtype=np.float64)[PATH_CURVATURE_LOOKAHEAD_SLICE], PATH_CURVATURE_MIN_SPEED)
|
||||
oz_arr = np.asarray(oz, dtype=np.float64)[PATH_CURVATURE_LOOKAHEAD_SLICE]
|
||||
return float(np.mean(oz_arr / vx_arr))
|
||||
|
||||
|
||||
class ControlsExt(ModelStateBase):
|
||||
@@ -48,15 +30,11 @@ class ControlsExt(ModelStateBase):
|
||||
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
|
||||
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
|
||||
cloudlog.info("controlsd_ext got CarParamsSP")
|
||||
self.pidd: LatControlPidd | None = None
|
||||
|
||||
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
|
||||
self.pm_services_ext = ['carControlSP']
|
||||
|
||||
def initialize_lateral_control(self, lac, CI, dt):
|
||||
if pidd_selected(self.CP):
|
||||
self.pidd = LatControlPidd(self.CP, self.CP_SP, CI, dt)
|
||||
return self.pidd
|
||||
enforce_torque_control = self.params.get_bool("EnforceTorqueControl")
|
||||
torque_versions = self.params.get("TorqueControlTune")
|
||||
if not enforce_torque_control:
|
||||
@@ -126,8 +104,6 @@ class ControlsExt(ModelStateBase):
|
||||
CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton
|
||||
CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget
|
||||
|
||||
CC_SP.pathCurvature = path_curvature_ahead(sm['modelV2'])
|
||||
|
||||
return CC_SP
|
||||
|
||||
@staticmethod
|
||||
@@ -138,13 +114,6 @@ class ControlsExt(ModelStateBase):
|
||||
|
||||
pm.send('carControlSP', cc_sp_send)
|
||||
|
||||
def update_pidd_torque_params(self, sm: messaging.SubMaster) -> None:
|
||||
torque_params = sm['lateralTorqueParameters']
|
||||
if self.pidd is not None and sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
|
||||
self.pidd.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
|
||||
torque_params.frictionCoefficientFiltered)
|
||||
|
||||
def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None:
|
||||
self.update_pidd_torque_params(sm)
|
||||
CC_SP = self.state_control_ext(sm)
|
||||
self.publish_ext(CC_SP, sm, pm)
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"pidd": {
|
||||
"version": "2.0"
|
||||
},
|
||||
"v1.0": {
|
||||
"version": "1.0"
|
||||
},
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from collections import deque
|
||||
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.pid import PIDController
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
|
||||
# gains are in lateral acceleration, scaled to torque per degree by each car's vehicle model and latAccelFactor
|
||||
PIDD_VERSION = 2.0
|
||||
INTERP_SPEEDS = [1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 30.0]
|
||||
KP_INTERP = [250.0, 120.0, 65.0, 30.0, 11.5, 5.5, 3.5, 2.0, 0.8]
|
||||
TD_INTERP = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15, 0.2]
|
||||
HIGH_SPEED_BP = [25.0, 29.0]
|
||||
TURN_RATE_BP = [5.0, 20.0]
|
||||
TURN_LAT_ACCEL_BP = [0.18, 0.53]
|
||||
DESIRED_ANGLE_BUFFER_SECONDS = 1.0
|
||||
LIVE_LAT_ACCEL_FACTOR_RANGE = [1.0, 2.0]
|
||||
LIVE_FRICTION_RANGE = [0.5, 2.0]
|
||||
SWING_CAP_FRICTION = 1.3
|
||||
|
||||
|
||||
def pidd_selected(CP):
|
||||
return CP.steerControlType == 'torque' and CP.lateralTuning.which() == 'pid' and len(CP.lateralTuning.pid.kpBP) == 0 and \
|
||||
CP.carFingerprint in get_torque_params()
|
||||
|
||||
|
||||
def filter_rc(hz):
|
||||
return 1 / (2 * math.pi * hz)
|
||||
|
||||
|
||||
def lat_accel_per_deg(VM, v_ego):
|
||||
return VM.calc_curvature(math.radians(1.0), v_ego, 0.0) * v_ego**2
|
||||
|
||||
|
||||
class LatControlPidd(LatControl):
|
||||
def __init__(self, CP, CP_SP, CI, dt):
|
||||
super().__init__(CP, CP_SP, CI, dt)
|
||||
|
||||
torque_params = get_torque_params()[CP.carFingerprint]
|
||||
self.VM = VehicleModel(CP)
|
||||
self.pid = PIDController(0.0, 0.0, 0.0, pos_limit=self.steer_max, neg_limit=-self.steer_max)
|
||||
self.offline_lat_accel_factor, self.offline_friction = float(torque_params['LAT_ACCEL_FACTOR']), float(torque_params['FRICTION'])
|
||||
self.lat_accel_factor = self.friction = None
|
||||
self.update_torque_parameters(self.offline_lat_accel_factor, 0.0, self.offline_friction)
|
||||
|
||||
self.error_filter = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.request_filter = FirstOrderFilter(0.0, filter_rc(3.0), dt, initialized=False)
|
||||
self.error_rate_filter = FirstOrderFilter(0.0, 0.0354, dt)
|
||||
self.wheel_angle_filter = FirstOrderFilter(0.0, filter_rc(10.0), dt, initialized=False)
|
||||
self.wheel_rate_filter = FirstOrderFilter(0.0, 0.005, dt)
|
||||
self.request_rate_ref = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.break_rate = FirstOrderFilter(0.0, filter_rc(0.5), dt)
|
||||
self.break_rate2 = FirstOrderFilter(0.0, filter_rc(0.5), dt)
|
||||
self.break_error = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.command_slow = FirstOrderFilter(0.0, filter_rc(0.5), dt, initialized=False)
|
||||
self.last_error = 0.0
|
||||
self.wheel_angle_held = None
|
||||
self.swing = 0.0
|
||||
|
||||
buffer_len = int(DESIRED_ANGLE_BUFFER_SECONDS / dt)
|
||||
self.desired_angle_buffer = deque([0.0] * buffer_len, maxlen=buffer_len)
|
||||
self.delay_frames = int(np.clip(CP.steerActuatorDelay / dt + 1, 1, buffer_len))
|
||||
self.rate_span_frames = max(1, int(0.1 / dt))
|
||||
|
||||
def update_torque_parameters(self, latAccelFactor, latAccelOffset, friction):
|
||||
# a learned factor below the offline one would raise every gain
|
||||
latAccelFactor = float(np.clip(latAccelFactor, *(r * self.offline_lat_accel_factor for r in LIVE_LAT_ACCEL_FACTOR_RANGE)))
|
||||
friction = float(np.clip(friction, *(r * self.offline_friction for r in LIVE_FRICTION_RANGE)))
|
||||
if (latAccelFactor, friction) == (self.lat_accel_factor, self.friction):
|
||||
return
|
||||
self.lat_accel_factor, self.friction = latAccelFactor, friction
|
||||
self.kp = [kp * lat_accel_per_deg(self.VM, v) / latAccelFactor for kp, v in zip(KP_INTERP, INTERP_SPEEDS, strict=True)]
|
||||
self.pid._k_p = (INTERP_SPEEDS, self.kp)
|
||||
self.pid._k_i = (INTERP_SPEEDS, [kp / 6.0 for kp in self.kp])
|
||||
self.pid._k_d = (INTERP_SPEEDS, [kp * td for kp, td in zip(self.kp, TD_INTERP, strict=True)])
|
||||
|
||||
def reset(self):
|
||||
super().reset()
|
||||
self.pid.reset()
|
||||
self.swing = self.last_error = 0.0
|
||||
self.command_slow.initialized = False
|
||||
for f in (self.error_filter, self.error_rate_filter, self.wheel_rate_filter, self.request_rate_ref, self.break_error, self.break_rate, self.break_rate2):
|
||||
f.x = 0.0
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay):
|
||||
pid_log = log.ControlsState.LateralPIDState.new_message()
|
||||
pid_log.steeringAngleDeg = float(CS.steeringAngleDeg)
|
||||
pid_log.steeringRateDeg = float(CS.steeringRateDeg)
|
||||
|
||||
high_speed = float(np.interp(CS.vEgo, HIGH_SPEED_BP, [0.0, 1.0]))
|
||||
angle_steers_des_no_offset = self.request_filter.update(math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)))
|
||||
angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg
|
||||
|
||||
self.desired_angle_buffer.append(angle_steers_des)
|
||||
expected_angle = self.desired_angle_buffer[-self.delay_frames]
|
||||
request_rate = (self.desired_angle_buffer[-1] - self.desired_angle_buffer[-1 - self.rate_span_frames]) / (self.rate_span_frames * self.dt)
|
||||
request_rate_ref = self.request_rate_ref.update(request_rate)
|
||||
break_rate = self.break_rate2.update(self.break_rate.update(request_rate))
|
||||
# a 1 Hz error filter lags enough for P to pump a 2 Hz wheel swing, so it opens up only while the request turns the wheel
|
||||
error_filter_hz = float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [1.0, 3.0]))
|
||||
self.error_filter.update_alpha(filter_rc(float(np.interp(CS.vEgo, HIGH_SPEED_BP, [error_filter_hz, 1.0]))))
|
||||
error = self.error_filter.update(expected_angle - CS.steeringAngleDeg)
|
||||
# at highway speed, ignore the angle sensor toggling one count
|
||||
held = self.wheel_angle_held if self.wheel_angle_held is not None else CS.steeringAngleDeg
|
||||
wheel_backlash = 0.08 * high_speed
|
||||
self.wheel_angle_held = held = CS.steeringAngleDeg - float(np.clip(CS.steeringAngleDeg - held, -wheel_backlash, wheel_backlash))
|
||||
wheel_angle_last = self.wheel_angle_filter.x if self.wheel_angle_filter.initialized else held
|
||||
wheel_rate = self.wheel_rate_filter.update((self.wheel_angle_filter.update(held) - wheel_angle_last) / self.dt)
|
||||
|
||||
wheel_swing = 0.0 if CS.steeringPressed else min(abs(wheel_rate - request_rate_ref), 60.0)
|
||||
self.swing = max(wheel_swing, self.swing * (1.0 - self.dt))
|
||||
|
||||
pid_log.steeringAngleDesiredDeg = float(angle_steers_des)
|
||||
pid_log.angleError = float(error)
|
||||
|
||||
if not active:
|
||||
output_torque = 0.0
|
||||
pid_log.active = False
|
||||
self.reset()
|
||||
else:
|
||||
error_rate = self.error_rate_filter.update((error - self.last_error) / self.dt)
|
||||
self.last_error = error
|
||||
error_rate += high_speed * (-wheel_rate - error_rate)
|
||||
ff = angle_steers_des_no_offset * lat_accel_per_deg(VM, CS.vEgo) / self.lat_accel_factor
|
||||
ff += 0.4 * params.roll * ACCELERATION_DUE_TO_GRAVITY / self.lat_accel_factor
|
||||
|
||||
# break rack friction as soon as the request moves, before the error builds up
|
||||
error_deadzone = error - float(np.clip(error, -0.3, 0.3))
|
||||
turn_lat_accel = abs(desired_curvature) * max(CS.vEgo, 8.0) ** 2
|
||||
friction_scale = float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.6, 1.0]))
|
||||
friction = self.friction * (friction_scale + high_speed * (0.1 - friction_scale))
|
||||
friction_rate_gain = 0.75 - 0.25 * high_speed
|
||||
ff += friction * float(np.tanh((error_deadzone + friction_rate_gain * request_rate) * 0.1887))
|
||||
kp = float(np.interp(CS.vEgo, INTERP_SPEEDS, self.kp))
|
||||
# damp the wheel toward the request's rate; the rack rings near 2 Hz without it
|
||||
wheel_damp = 0.0 if CS.steeringPressed else (1.0 - high_speed) * kp * 0.05 * (wheel_rate - request_rate_ref)
|
||||
ff -= wheel_damp
|
||||
# half P on a straight, flat road; the cut goes through the feedforward so the integrator still holds a crown
|
||||
kp_load = max(float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0])),
|
||||
float(np.interp(abs(params.roll) * ACCELERATION_DUE_TO_GRAVITY, [0.35, 0.7], [0.0, 1.0])))
|
||||
kp_scale = 0.5 + 0.5 * kp_load
|
||||
ff -= (1.0 - float(np.interp(CS.vEgo, [12.0, 18.0], [kp_scale, 1.0]))) * kp * error
|
||||
ff += high_speed * 0.325 * self.friction * float(np.tanh((self.break_error.update(error) + 0.35 * break_rate) / 0.5))
|
||||
|
||||
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
|
||||
error_rate_clean = error_rate - float(np.clip(error_rate, -0.3, 0.3))
|
||||
output_torque = self.pid.update(error, error_rate=error_rate_clean, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
|
||||
|
||||
# a swing the request isn't asking for: pass only the command's slow part
|
||||
command = output_torque + wheel_damp
|
||||
self.command_slow.update(command)
|
||||
if CS.steeringPressed:
|
||||
self.command_slow.x = command
|
||||
swing_gate = float(np.interp(self.swing, [16.0, 30.0], [0.0, 1.0])) * float(np.interp(CS.vEgo, [3.0, 5.0, 10.0, 14.0], [0.0, 1.0, 1.0, 0.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [0.0, 1.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(abs(error), [3.0, 6.0], [0.0, 1.0]))
|
||||
if not (CS.steeringPressed or CS.leftBlinker or CS.rightBlinker):
|
||||
cap = SWING_CAP_FRICTION * self.friction
|
||||
output_torque += swing_gate * float(np.clip(self.command_slow.x - command, -cap, cap))
|
||||
output_torque = float(np.clip(output_torque, -self.steer_max, self.steer_max))
|
||||
|
||||
pid_log.active = True
|
||||
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_torque, angle_steers_des, pid_log
|
||||
@@ -1,127 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.honda.values import CAR as HONDA
|
||||
from opendbc.car.hyundai.values import CAR as HYUNDAI
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.nissan.values import CAR as NISSAN
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.mock.generators import generate_deviceMotion
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import DT_CTRL
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.selfdrive.car.helpers import convert_to_capnp
|
||||
from openpilot.selfdrive.locationd.helpers import Pose
|
||||
from openpilot.selfdrive.locationd.torqued import TorqueEstimator
|
||||
from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces
|
||||
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, PIDD_VERSION
|
||||
|
||||
|
||||
def setup_car(car_name):
|
||||
CarInterface = interfaces[car_name]
|
||||
CP = CarInterface.get_non_essential_params(car_name)
|
||||
CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name)
|
||||
CI = CarInterface(CP, CP_SP)
|
||||
sunnypilot_interfaces.setup_interfaces(CI)
|
||||
return CI
|
||||
|
||||
|
||||
def make_controller(CI):
|
||||
return LatControlPidd(CI.CP.as_reader(), convert_to_capnp(CI.CP_SP).as_reader(), CI, DT_CTRL)
|
||||
|
||||
|
||||
def drive(controller, CS, VM, angles, curvature=0.0):
|
||||
params = log.VehicleParameters.new_message()
|
||||
pose = Pose.from_device_motion(generate_deviceMotion().deviceMotion)
|
||||
return [controller.update(True, CS, VM, params, False, curvature, pose, False, 0.2)[0] for CS.steeringAngleDeg in angles]
|
||||
|
||||
|
||||
class TestPidd(OpenpilotTestCase):
|
||||
def setup_method(self):
|
||||
self.params = Params()
|
||||
self.params.put_bool("EnforceTorqueControl", True, block=True)
|
||||
self.params.put("TorqueControlTune", PIDD_VERSION, block=True)
|
||||
|
||||
def test_selected_on_any_torque_car(self):
|
||||
for car_name in (HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.KIA_NIRO_EV):
|
||||
assert setup_car(car_name).CP.lateralTuning.which() == 'pid'
|
||||
|
||||
def test_needs_enforce_torque(self):
|
||||
self.params.remove("EnforceTorqueControl")
|
||||
assert setup_car(HYUNDAI.KIA_NIRO_EV).CP.lateralTuning.which() == 'torque'
|
||||
|
||||
def test_not_on_angle_cars(self):
|
||||
CI = setup_car(NISSAN.NISSAN_LEAF)
|
||||
assert CI.CP.steerControlType == car.CarParams.SteerControlType.angle
|
||||
assert not self.params.get_bool("EnforceTorqueControl")
|
||||
|
||||
def test_controlsd_builds_it(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
|
||||
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
|
||||
|
||||
def test_selection_follows_car_params(self):
|
||||
# params changing after card picked pidd must not leave controlsd with a pid that has no gains
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
self.params.remove("EnforceTorqueControl")
|
||||
self.params.put("TorqueControlTune", 1.0, block=True)
|
||||
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
|
||||
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
|
||||
|
||||
def test_damps_wheel_swing(self):
|
||||
CI = setup_car(HONDA.HONDA_CIVIC)
|
||||
VM = VehicleModel(CI.CP)
|
||||
corr = {}
|
||||
for pressed in (False, True):
|
||||
controller = make_controller(CI)
|
||||
CS = car.CarState.new_message(vEgo=8.0, steeringPressed=pressed)
|
||||
angles = [2.0 * math.sin(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(300)]
|
||||
out = drive(controller, CS, VM, angles)[100:]
|
||||
rate = [math.cos(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(100, 300)]
|
||||
corr[pressed] = float(np.corrcoef(out, rate)[0, 1])
|
||||
assert corr[False] < corr[True] - 0.3
|
||||
|
||||
def test_output_within_steer_max(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
controller = make_controller(CI)
|
||||
controller.pid.update = lambda *args, **kwargs: controller.steer_max
|
||||
CS = car.CarState.new_message(vEgo=8.0)
|
||||
out = drive(controller, CS, VehicleModel(CI.CP), [2.0 * math.sin(2 * math.pi * 2.5 * i * DT_CTRL) for i in range(500)])
|
||||
assert max(abs(x) for x in out) <= controller.steer_max
|
||||
|
||||
def test_reset_clears_swing_gate(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
controller = make_controller(CI)
|
||||
drive(controller, car.CarState.new_message(vEgo=8.0), VehicleModel(CI.CP), [30.0] * 200, curvature=-0.02)
|
||||
controller.reset()
|
||||
assert not controller.command_slow.initialized
|
||||
|
||||
def test_live_torque_params_rescale_gains(self):
|
||||
controller = make_controller(setup_car(HYUNDAI.KIA_NIRO_EV))
|
||||
kp = list(controller.kp)
|
||||
controller.update_torque_parameters(2 * controller.lat_accel_factor, 0.0, controller.friction)
|
||||
assert np.allclose(controller.kp, [k / 2 for k in kp])
|
||||
assert np.allclose(controller.pid._k_p[1], controller.kp)
|
||||
controller.update_torque_parameters(0.5 * controller.offline_lat_accel_factor, 0.0, 0.0)
|
||||
assert np.allclose(controller.kp, kp)
|
||||
|
||||
def test_torqued_learns_under_pidd(self):
|
||||
estimator = TorqueEstimator(setup_car(HYUNDAI.KIA_NIRO_EV).CP.as_reader())
|
||||
offline = get_torque_params()[HYUNDAI.KIA_NIRO_EV]
|
||||
assert estimator.offline_latAccelFactor == pytest.approx(offline['LAT_ACCEL_FACTOR'])
|
||||
assert estimator.offline_friction == pytest.approx(offline['FRICTION'])
|
||||
assert estimator.max_lataccel_factor > estimator.min_lataccel_factor
|
||||
@@ -6,13 +6,11 @@ See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.structs import car
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import DT_MDL
|
||||
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import pidd_selected
|
||||
|
||||
RELAXED_MIN_BUCKET_POINTS = np.array([1, 200, 300, 500, 500, 300, 200, 1])
|
||||
|
||||
@@ -39,11 +37,6 @@ class TorqueEstimatorExt:
|
||||
def initialize_custom_params(self, decimated=False):
|
||||
self.update_use_params()
|
||||
|
||||
if pidd_selected(self.CP):
|
||||
torque_params = get_torque_params()[self.CP.carFingerprint]
|
||||
self.offline_latAccelFactor = float(torque_params['LAT_ACCEL_FACTOR'])
|
||||
self.offline_friction = float(torque_params['FRICTION'])
|
||||
|
||||
if self.enforce_torque_control_toggle:
|
||||
if self._params.get_bool("LiveTorqueParamsRelaxedToggle"):
|
||||
self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS / (10 if decimated else 1)
|
||||
|
||||
@@ -249,14 +249,6 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
|
||||
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
|
||||
},
|
||||
|
||||
EventNameSP.stockSteerIntervention: {
|
||||
ET.PERMANENT: Alert(
|
||||
"TAKE CONTROL",
|
||||
"Stock Emergency Assist: Risk of Collision",
|
||||
AlertStatus.critical, AlertSize.mid,
|
||||
Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.none, 2.),
|
||||
},
|
||||
|
||||
EventNameSP.bigModelReady: {
|
||||
ET.PERMANENT: Alert(
|
||||
"Big Model Ready",
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import wave
|
||||
|
||||
import numpy as np
|
||||
|
||||
from openpilot.cereal import custom, log
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
|
||||
|
||||
ROBOTIC_SOUNDS_DIR = os.path.join(BASEDIR, "openpilot/sunnypilot/selfdrive/assets/sounds/robotic")
|
||||
|
||||
ROBOTIC_SOUND_FILES: dict[int, str] = {
|
||||
AudibleAlert.engage: "engage.wav",
|
||||
AudibleAlert.disengage: "disengage.wav",
|
||||
AudibleAlert.refuse: "refuse.wav",
|
||||
AudibleAlert.prompt: "warning.wav",
|
||||
AudibleAlert.promptRepeat: "warning_repeat.wav",
|
||||
AudibleAlert.promptDistracted: "dm_warning.wav",
|
||||
AudibleAlert.preAlert: "pre_alert.wav",
|
||||
AudibleAlert.warningSoft: "critical.wav",
|
||||
AudibleAlert.warningImmediate: "dm_critical.wav",
|
||||
AudibleAlertSP.promptSingleLow: "prompt_single_low.wav",
|
||||
AudibleAlertSP.promptSingleHigh: "prompt_single_high.wav",
|
||||
}
|
||||
|
||||
# Custom reactive robotic chirp IDs (non-overlapping with AudibleAlert / AudibleAlertSP enums)
|
||||
CHIRP_SPEED_UP = 1001
|
||||
CHIRP_SPEED_DOWN = 1002
|
||||
CHIRP_STARTLED = 1003
|
||||
CHIRP_BOOST = 1004
|
||||
CHIRP_BOOKMARK = 1005
|
||||
CHIRP_BLINKER = 1006
|
||||
|
||||
REACTIVE_CHIRP_IDS = {
|
||||
CHIRP_SPEED_UP,
|
||||
CHIRP_SPEED_DOWN,
|
||||
CHIRP_STARTLED,
|
||||
CHIRP_BOOST,
|
||||
CHIRP_BOOKMARK,
|
||||
CHIRP_BLINKER,
|
||||
}
|
||||
|
||||
SET_SPEED_NA = 255
|
||||
CHIRP_COOLDOWN = 0.6 # minimum seconds between reactive chirps
|
||||
|
||||
|
||||
def _adsr(n: int, sr: int, attack: float = 0.012, release: float = 0.035) -> np.ndarray:
|
||||
env = np.ones(n, dtype=np.float32)
|
||||
a_n = min(n // 2, int(attack * sr))
|
||||
r_n = min(n // 2, int(release * sr))
|
||||
if a_n > 0:
|
||||
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
|
||||
if r_n > 0:
|
||||
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
|
||||
return env
|
||||
|
||||
|
||||
def synth_emo_chirp(
|
||||
f_start: float,
|
||||
f_end: float,
|
||||
duration: float,
|
||||
sr: int = 48000,
|
||||
vibrato_hz: float = 0.0,
|
||||
vibrato_depth: float = 0.0,
|
||||
gain: float = 0.85,
|
||||
) -> np.ndarray:
|
||||
"""Synthesize a bright, bubbly EMO-style harmonic chirp in pure NumPy."""
|
||||
n = max(1, int(sr * duration))
|
||||
t = np.arange(n, dtype=np.float32) / sr
|
||||
p = t / max(duration, 1e-6)
|
||||
s_curve = p * p * (3.0 - 2.0 * p)
|
||||
freq = f_start + (f_end - f_start) * s_curve
|
||||
if vibrato_hz > 0.0:
|
||||
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
|
||||
phase = 2.0 * np.pi * np.cumsum(freq) / sr
|
||||
sig = (
|
||||
0.66 * np.sin(phase)
|
||||
+ 0.24 * np.sin(2.0 * phase + 0.35)
|
||||
+ 0.10 * np.sin(3.0 * phase)
|
||||
)
|
||||
env = _adsr(n, sr, attack=min(0.012, duration * 0.2), release=min(0.045, duration * 0.35))
|
||||
return np.clip(sig * env * gain, -0.98, 0.98).astype(np.float32)
|
||||
|
||||
|
||||
def _sil(duration: float, sr: int = 48000) -> np.ndarray:
|
||||
return np.zeros(int(sr * duration), dtype=np.float32)
|
||||
|
||||
|
||||
def build_procedural_sounds(sr: int = 48000) -> dict[int, np.ndarray]:
|
||||
"""Build bubbly EMO chirps in pure NumPy (used for reactive chirps and guaranteed WAV fallback)."""
|
||||
return {
|
||||
# Core alert fallbacks (in case WAV LFS files are unavailable on device)
|
||||
AudibleAlert.engage: np.concatenate([
|
||||
synth_emo_chirp(660, 1020, 0.10, sr, gain=0.86),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(1020, 1580, 0.18, sr, vibrato_hz=24, vibrato_depth=28, gain=0.90),
|
||||
]),
|
||||
AudibleAlert.disengage: np.concatenate([
|
||||
synth_emo_chirp(1080, 740, 0.12, sr, gain=0.82),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(700, 440, 0.18, sr, gain=0.80),
|
||||
]),
|
||||
AudibleAlert.refuse: np.concatenate([
|
||||
synth_emo_chirp(480, 340, 0.11, sr, vibrato_hz=32, vibrato_depth=28, gain=0.85),
|
||||
_sil(0.04, sr),
|
||||
synth_emo_chirp(390, 270, 0.15, sr, vibrato_hz=32, vibrato_depth=28, gain=0.85),
|
||||
]),
|
||||
AudibleAlert.preAlert: synth_emo_chirp(860, 1480, 0.20, sr, vibrato_hz=26, vibrato_depth=22, gain=0.84),
|
||||
AudibleAlertSP.promptSingleLow: synth_emo_chirp(620, 500, 0.18, sr, gain=0.80),
|
||||
AudibleAlertSP.promptSingleHigh: synth_emo_chirp(1080, 1420, 0.16, sr, gain=0.84),
|
||||
AudibleAlert.prompt: np.concatenate([
|
||||
synth_emo_chirp(920, 1340, 0.11, sr, gain=0.88),
|
||||
_sil(0.03, sr),
|
||||
synth_emo_chirp(1340, 1040, 0.16, sr, gain=0.86),
|
||||
]),
|
||||
AudibleAlert.promptRepeat: np.concatenate([
|
||||
synth_emo_chirp(960, 1380, 0.11, sr, gain=0.88),
|
||||
_sil(0.03, sr),
|
||||
synth_emo_chirp(1380, 1060, 0.15, sr, gain=0.86),
|
||||
_sil(0.28, sr),
|
||||
]),
|
||||
AudibleAlert.promptDistracted: np.concatenate([
|
||||
synth_emo_chirp(840, 1280, 0.09, sr, gain=0.90),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(980, 1480, 0.12, sr, vibrato_hz=22, vibrato_depth=20, gain=0.90),
|
||||
_sil(0.30, sr),
|
||||
]),
|
||||
AudibleAlert.warningSoft: np.concatenate([
|
||||
synth_emo_chirp(1380, 1680, 0.10, sr, gain=0.94),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(1680, 1260, 0.14, sr, gain=0.94),
|
||||
_sil(0.22, sr),
|
||||
]),
|
||||
AudibleAlert.warningImmediate: np.concatenate([
|
||||
synth_emo_chirp(1520, 1880, 0.09, sr, gain=0.96),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1520, 1880, 0.09, sr, gain=0.96),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1880, 1400, 0.12, sr, gain=0.96),
|
||||
_sil(0.18, sr),
|
||||
]),
|
||||
# Reactive chirps for driving & user interactions
|
||||
CHIRP_SPEED_UP: np.concatenate([
|
||||
synth_emo_chirp(880, 1180, 0.075, sr, gain=0.72),
|
||||
_sil(0.015, sr),
|
||||
synth_emo_chirp(1180, 1520, 0.09, sr, gain=0.75),
|
||||
]),
|
||||
CHIRP_SPEED_DOWN: np.concatenate([
|
||||
synth_emo_chirp(1220, 940, 0.075, sr, gain=0.70),
|
||||
_sil(0.015, sr),
|
||||
synth_emo_chirp(940, 680, 0.09, sr, gain=0.70),
|
||||
]),
|
||||
CHIRP_STARTLED: np.concatenate([
|
||||
synth_emo_chirp(720, 1680, 0.11, sr, vibrato_hz=38, vibrato_depth=45, gain=0.82),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1480, 980, 0.10, sr, gain=0.78),
|
||||
]),
|
||||
CHIRP_BOOST: np.concatenate([
|
||||
synth_emo_chirp(640, 1040, 0.07, sr, gain=0.76),
|
||||
_sil(0.015, sr),
|
||||
synth_emo_chirp(1040, 1640, 0.13, sr, vibrato_hz=28, vibrato_depth=35, gain=0.80),
|
||||
]),
|
||||
CHIRP_BOOKMARK: np.concatenate([
|
||||
synth_emo_chirp(980, 1380, 0.07, sr, gain=0.78),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1240, 1720, 0.10, sr, vibrato_hz=24, vibrato_depth=25, gain=0.82),
|
||||
]),
|
||||
CHIRP_BLINKER: synth_emo_chirp(920, 1180, 0.065, sr, gain=0.55),
|
||||
}
|
||||
|
||||
|
||||
class RoboticSoundPack:
|
||||
"""Manages pre-loaded robotic voice/chirp buffers and reactive driving chirps for Soundd."""
|
||||
|
||||
def __init__(self, params, sample_rate: int = 48000):
|
||||
self._params = params
|
||||
self._sample_rate = sample_rate
|
||||
self.enabled: bool = self._params.get_bool("MiciRoboticUI")
|
||||
self.sounds: dict[int, np.ndarray] = {}
|
||||
|
||||
# Edge-detection state for reactive chirps
|
||||
self._prev_set_speed: float = SET_SPEED_NA
|
||||
self._prev_blinker: bool = False
|
||||
self._last_chirp_time: float = 0.0
|
||||
|
||||
def load(self) -> None:
|
||||
# Start with guaranteed pure-NumPy procedural chirps so soundd never fails if LFS WAVs are missing
|
||||
self.sounds = build_procedural_sounds(self._sample_rate)
|
||||
|
||||
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
|
||||
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
|
||||
if not os.path.exists(path):
|
||||
cloudlog.warning(f"Robotic sound file missing, using procedural fallback: {path}")
|
||||
continue
|
||||
try:
|
||||
with wave.open(path, "r") as wavefile:
|
||||
if (
|
||||
wavefile.getnchannels() != 1
|
||||
or wavefile.getsampwidth() != 2
|
||||
or wavefile.getframerate() != self._sample_rate
|
||||
):
|
||||
cloudlog.warning(f"Robotic sound format mismatch, using procedural fallback: {path}")
|
||||
continue
|
||||
length = wavefile.getnframes()
|
||||
if length > 0:
|
||||
self.sounds[alert_id] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16 / 2)
|
||||
except Exception as e:
|
||||
cloudlog.warning(f"Failed to load robotic WAV (possible Git LFS pointer), using procedural fallback: {path} ({e})")
|
||||
|
||||
def refresh_param(self) -> bool:
|
||||
"""Refresh MiciRoboticUI param; returns True if the enabled state changed."""
|
||||
new_val = self._params.get_bool("MiciRoboticUI")
|
||||
changed = new_val != self.enabled
|
||||
self.enabled = new_val
|
||||
return changed
|
||||
|
||||
def get_buffer(self, alert_id: int, default_sounds: dict[int, np.ndarray]) -> np.ndarray:
|
||||
if self.enabled and alert_id in self.sounds:
|
||||
return self.sounds[alert_id]
|
||||
return default_sounds[alert_id]
|
||||
|
||||
def detect_reactive_chirp(self, sm, now: float | None = None) -> int | None:
|
||||
"""Detect driving/user events that should emit a cute one-shot robotic chirp."""
|
||||
if not self.enabled:
|
||||
return None
|
||||
|
||||
t = time.monotonic() if now is None else now
|
||||
if t - self._last_chirp_time < CHIRP_COOLDOWN:
|
||||
return None
|
||||
|
||||
chirp: int | None = None
|
||||
|
||||
if sm.updated.get("userBookmark") or sm.updated.get("bookmarkButton"):
|
||||
chirp = CHIRP_BOOKMARK
|
||||
elif sm.updated.get("carState"):
|
||||
cs = sm["carState"]
|
||||
v_cruise = cs.vCruiseCluster
|
||||
if v_cruise == 0.0 and sm.valid.get("controlsState"):
|
||||
v_cruise = sm["controlsState"].deprecated.vCruise
|
||||
|
||||
cruise_set = 0 < v_cruise < SET_SPEED_NA
|
||||
if cruise_set and self._prev_set_speed != SET_SPEED_NA and v_cruise != self._prev_set_speed:
|
||||
chirp = CHIRP_SPEED_UP if v_cruise > self._prev_set_speed else CHIRP_SPEED_DOWN
|
||||
self._prev_set_speed = v_cruise
|
||||
|
||||
blinker = bool(cs.leftBlinker or cs.rightBlinker)
|
||||
if chirp is None and blinker and not self._prev_blinker:
|
||||
chirp = CHIRP_BLINKER
|
||||
self._prev_blinker = blinker
|
||||
|
||||
if chirp is None and not cs.standstill:
|
||||
if cs.aEgo < -3.0:
|
||||
chirp = CHIRP_STARTLED
|
||||
elif cs.aEgo > 2.2:
|
||||
chirp = CHIRP_BOOST
|
||||
|
||||
if chirp is not None:
|
||||
self._last_chirp_time = t
|
||||
return chirp
|
||||
@@ -44,7 +44,6 @@ CAPABILITY_FIELDS = (
|
||||
"device_type",
|
||||
"subaru_has_sng",
|
||||
"hyundai_alpha_long_available",
|
||||
"hyundai_radar_tracks_available",
|
||||
"toyota_tss2",
|
||||
"custom_model_active",
|
||||
)
|
||||
@@ -69,7 +68,6 @@ CAPABILITY_LABELS: dict[str, str] = {
|
||||
"device_type": "Device type",
|
||||
"subaru_has_sng": "Subaru Stop-and-Go available",
|
||||
"hyundai_alpha_long_available": "Hyundai Alpha Longitudinal available",
|
||||
"hyundai_radar_tracks_available": "Hyundai radar tracks available",
|
||||
"toyota_tss2": "Toyota TSS2 platform",
|
||||
"custom_model_active": "Non-Default model selected",
|
||||
}
|
||||
@@ -90,7 +88,6 @@ CAR_CAPABILITY_FIELDS = (
|
||||
"has_stop_and_go",
|
||||
"subaru_has_sng",
|
||||
"hyundai_alpha_long_available",
|
||||
"hyundai_radar_tracks_available",
|
||||
"toyota_tss2",
|
||||
)
|
||||
|
||||
@@ -125,7 +122,6 @@ def _resolve_brand_capabilities(caps: dict, bundle_platform: str, CP) -> None:
|
||||
cloudlog.exception(f"capabilities: unknown hyundai platform {bundle_platform!r}")
|
||||
elif CP is not None:
|
||||
caps["hyundai_alpha_long_available"] = bool(CP.alphaLongitudinalAvailable)
|
||||
caps["hyundai_radar_tracks_available"] = not CP.radarUnavailable
|
||||
|
||||
elif brand == "subaru":
|
||||
if bundle_platform:
|
||||
|
||||
@@ -484,10 +484,6 @@
|
||||
"value": "",
|
||||
"label": "Default"
|
||||
},
|
||||
{
|
||||
"value": 2.0,
|
||||
"label": "pidd"
|
||||
},
|
||||
{
|
||||
"value": 1.0,
|
||||
"label": "v1.0"
|
||||
@@ -1553,19 +1549,6 @@
|
||||
"widget": "toggle",
|
||||
"title": "Tesla Rainbow Mode",
|
||||
"description": "Display a rainbow effect on the path the model wants to take. It does not affect driving in any way."
|
||||
},
|
||||
{
|
||||
"key": "MiciRoboticUI",
|
||||
"widget": "toggle",
|
||||
"title": "Robotic Companion UI",
|
||||
"description": "Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
"field": "device_type",
|
||||
"equals": "mici"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2216,9 +2199,22 @@
|
||||
"items": [
|
||||
{
|
||||
"key": "HyundaiLongitudinalTuning",
|
||||
"widget": "toggle",
|
||||
"widget": "multiple_button",
|
||||
"title": "Custom Longitudinal Tuning",
|
||||
"description": "Accelerates and brakes the way your car's own cruise control does.",
|
||||
"options": [
|
||||
{
|
||||
"value": 0,
|
||||
"label": "Off"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"label": "Dynamic"
|
||||
},
|
||||
{
|
||||
"value": 2,
|
||||
"label": "Predictive"
|
||||
}
|
||||
],
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
@@ -2236,37 +2232,6 @@
|
||||
"equals": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "RadarTracks",
|
||||
"widget": "multiple_button",
|
||||
"title": "Radar Tracks",
|
||||
"options": [
|
||||
{
|
||||
"value": 0,
|
||||
"label": "Off"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"label": "Lead Only"
|
||||
},
|
||||
{
|
||||
"value": 2,
|
||||
"label": "Full Radar"
|
||||
}
|
||||
],
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
"field": "hyundai_radar_tracks_available",
|
||||
"equals": true
|
||||
}
|
||||
],
|
||||
"enablement": [
|
||||
{
|
||||
"type": "offroad_only"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -31,10 +31,6 @@ macros:
|
||||
- type: not
|
||||
condition: {type: capability, field: device_type, equals: mici}
|
||||
|
||||
# Show only on MICI hardware.
|
||||
mici_only:
|
||||
- {type: capability, field: device_type, equals: mici}
|
||||
|
||||
# Mirrors selfdrive/ui/sunnypilot/layouts/.../mads_settings.py:_mads_limited_settings()
|
||||
# Rivian + Tesla-without-vehicle-bus get the limited MADS UI (3-toggle subset).
|
||||
# On those platforms these toggles are disabled — full MADS settings are
|
||||
|
||||
@@ -225,8 +225,6 @@ sections:
|
||||
options:
|
||||
- value: ''
|
||||
label: Default
|
||||
- value: 2.0
|
||||
label: pidd
|
||||
- value: 1.0
|
||||
label: v1.0
|
||||
- value: 0.0
|
||||
|
||||
@@ -11,9 +11,15 @@ sections:
|
||||
description: ''
|
||||
items:
|
||||
- key: HyundaiLongitudinalTuning
|
||||
widget: toggle
|
||||
widget: multiple_button
|
||||
title: Custom Longitudinal Tuning
|
||||
description: Accelerates and brakes the way your car's own cruise control does.
|
||||
options:
|
||||
- value: 0
|
||||
label: 'Off'
|
||||
- value: 1
|
||||
label: Dynamic
|
||||
- value: 2
|
||||
label: Predictive
|
||||
visibility:
|
||||
- type: capability
|
||||
field: hyundai_alpha_long_available
|
||||
@@ -21,22 +27,6 @@ sections:
|
||||
enablement:
|
||||
- $ref: '#/macros/offroad'
|
||||
- $ref: '#/macros/longitudinal'
|
||||
- key: RadarTracks
|
||||
widget: multiple_button
|
||||
title: Radar Tracks
|
||||
options:
|
||||
- value: 0
|
||||
label: 'Off'
|
||||
- value: 1
|
||||
label: Lead Only
|
||||
- value: 2
|
||||
label: Full Radar
|
||||
visibility:
|
||||
- type: capability
|
||||
field: hyundai_radar_tracks_available
|
||||
equals: true
|
||||
enablement:
|
||||
- $ref: '#/macros/offroad'
|
||||
- id: subaru
|
||||
title: Subaru Settings
|
||||
description: ''
|
||||
|
||||
@@ -111,9 +111,3 @@ sections:
|
||||
widget: toggle
|
||||
title: Tesla Rainbow Mode
|
||||
description: Display a rainbow effect on the path the model wants to take. It does not affect driving in any way.
|
||||
- key: MiciRoboticUI
|
||||
widget: toggle
|
||||
title: Robotic Companion UI
|
||||
description: Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.
|
||||
visibility:
|
||||
- $ref: '#/macros/mici_only'
|
||||
|
||||
@@ -126,7 +126,7 @@ class Rpc:
|
||||
def _status(self, grants: list[dict]) -> dict:
|
||||
return {"version": get_version(), "agnos": HARDWARE.get_os_version(), "dongle_id": self._params.get("DongleId"),
|
||||
"onroad": not self._params.get_bool("IsOffroad"), "engaged": self._params.get_bool("IsEngaged"),
|
||||
"network": _wifi_status(), "phones": len(grants), "capabilities": ["ssh"]}
|
||||
"network": _wifi_status(), "phones": len(grants)}
|
||||
|
||||
def _known(self) -> set[str]:
|
||||
return {key.decode() for key in self._params.all_keys()}
|
||||
@@ -146,6 +146,7 @@ class Rpc:
|
||||
keys = args.get("keys")
|
||||
if not isinstance(keys, list) or len(keys) > MAX_PARAM_KEYS or not all(isinstance(k, str) for k in keys):
|
||||
raise _refused("keys must be a list of at most 32 names")
|
||||
self._check_keys(keys)
|
||||
known = self._known()
|
||||
values = {}
|
||||
for key in keys:
|
||||
|
||||
@@ -13,12 +13,11 @@ from dataclasses import dataclass
|
||||
from openpilot.sunnypilot.system import connect_phone
|
||||
from openpilot.sunnypilot.system.ble import cpace, grants, link, noise
|
||||
from openpilot.sunnypilot.system.ble.rpc import Rpc
|
||||
from openpilot.sunnypilot.system.ble.stream import Streams
|
||||
|
||||
PROTO = 1
|
||||
CONNECT_START, CONNECT_WINDOW, PAKE_A, PAKE_B, CONFIRM_A, CONFIRM_B = 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
|
||||
RESUME_1, RESUME_2, ERROR = 0x10, 0x11, 0x7F
|
||||
DECISION, DEVICE_KEYS, PHONE_KEYS, GRANT_RESULT, RPC, STREAM = 0x30, 0x31, 0x32, 0x33, 0x40, 0x50
|
||||
DECISION, DEVICE_KEYS, PHONE_KEYS, GRANT_RESULT, RPC = 0x30, 0x31, 0x32, 0x33, 0x40
|
||||
ERR_NO_WINDOW, ERR_BUSY, ERR_VERSION, ERR_WRONG_CODE, ERR_WINDOW_CLOSED, ERR_TIMEOUT, ERR_UNKNOWN_PHONE = 1, 2, 3, 4, 5, 6, 8
|
||||
ALLOW, DENY, NO_ANSWER = 1, 2, 3
|
||||
GRANT_ADDED, GRANT_REFUSED = 1, 2 # 3 reserved
|
||||
@@ -61,8 +60,7 @@ class _Link:
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, params, window, *, wifi: Callable | None = None, wall: Callable[[], float] = time.time, # noqa: TID251 unix time: the app shows added and last_seen
|
||||
stream_host: str = "127.0.0.1"):
|
||||
def __init__(self, params, window, *, wifi: Callable | None = None, wall: Callable[[], float] = time.time): # noqa: TID251 unix time: the app shows added and last_seen
|
||||
self._params = params
|
||||
self._window = window
|
||||
self._wall = wall
|
||||
@@ -70,7 +68,6 @@ class Engine:
|
||||
self._fail_nonce = b""
|
||||
self._fails = 0
|
||||
self._rpc = Rpc(params, wifi)
|
||||
self._streams = Streams(target_host=stream_host)
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int, now: float) -> list[Action]:
|
||||
lk = self._links.get(device)
|
||||
@@ -118,15 +115,8 @@ class Engine:
|
||||
lk = self._links.get(device)
|
||||
if lk is not None and lk.phase == "session":
|
||||
acts += self._record(lk, RPC, _json(response))
|
||||
acts += self._stream_actions(self._streams.tick(now))
|
||||
return acts
|
||||
|
||||
def stream_selector_entries(self) -> list[tuple[int, int]]:
|
||||
return self._streams.selector_entries()
|
||||
|
||||
def on_stream_ready(self, fd: int, readable: bool, writable: bool) -> list[Action]:
|
||||
return self._stream_actions(self._streams.on_socket_ready(fd, readable, writable))
|
||||
|
||||
def prompt(self, now: float) -> dict | None:
|
||||
lk = next((o for o in self._links.values() if o.phase == "decide"), None)
|
||||
if lk is None:
|
||||
@@ -171,8 +161,6 @@ class Engine:
|
||||
return self._phone_keys(lk, body, now)
|
||||
if lk.phase == "session" and typ == RPC:
|
||||
return self._rpc_request(lk, body, now)
|
||||
if lk.phase == "session" and typ == STREAM:
|
||||
return self._stream_actions(self._streams.handle(lk.device, body, now))
|
||||
return self._drop(lk)
|
||||
typ, body = msg[0], msg[1:]
|
||||
if lk.phase == "new" and typ == CONNECT_START:
|
||||
@@ -324,16 +312,7 @@ class Engine:
|
||||
def _error(self, lk: _Link, code: int) -> list[Action]:
|
||||
return self._plain(lk, ERROR, bytes([code])) + self._drop(lk)
|
||||
|
||||
def _stream_actions(self, events: list[tuple[str, bytes]]) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
for device, payload in events:
|
||||
lk = self._links.get(device)
|
||||
if lk is not None and lk.phase == "session":
|
||||
acts += self._record(lk, STREAM, payload)
|
||||
return acts
|
||||
|
||||
def _drop(self, lk: _Link) -> list[Action]:
|
||||
self._streams.close_device(lk.device)
|
||||
if self._links.get(lk.device) is lk:
|
||||
del self._links[lk.device]
|
||||
if lk.phase in HELD:
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import errno
|
||||
import select
|
||||
import selectors
|
||||
import socket
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
STREAM_OPEN = 0x01
|
||||
STREAM_OPEN_OK = 0x02
|
||||
STREAM_DATA = 0x03
|
||||
STREAM_WINDOW = 0x04
|
||||
STREAM_CLOSE = 0x05
|
||||
STREAM_ERROR = 0x06
|
||||
|
||||
ERR_REFUSED = 1
|
||||
ERR_UNSUPPORTED_PORT = 2
|
||||
ERR_LIMIT = 3
|
||||
ERR_PROTOCOL = 4
|
||||
|
||||
INITIAL_WINDOW = 8_192
|
||||
WINDOW_UPDATE_THRESHOLD = 2_048
|
||||
MAX_DATA_CHUNK = 1_024
|
||||
MAX_STREAMS_PER_DEVICE = 8
|
||||
OPEN_TIMEOUT = 5.0
|
||||
ALLOWED_PORTS = (22,)
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _TcpStream:
|
||||
device: str
|
||||
stream_id: int
|
||||
sock: socket.socket
|
||||
opened_at: float
|
||||
peer_window: int
|
||||
local_window: int = INITIAL_WINDOW
|
||||
consumed_since_ack: int = 0
|
||||
connecting: bool = True
|
||||
eof_from_phone: bool = False
|
||||
tx_queue: deque[bytes] = field(default_factory=deque)
|
||||
|
||||
@property
|
||||
def fd(self) -> int:
|
||||
return self.sock.fileno()
|
||||
|
||||
@property
|
||||
def want_write(self) -> bool:
|
||||
return self.connecting or bool(self.tx_queue)
|
||||
|
||||
|
||||
class Streams:
|
||||
def __init__(self, target_host: str = "127.0.0.1"):
|
||||
self._target_host = target_host
|
||||
self._streams: dict[tuple[str, int], _TcpStream] = {}
|
||||
self._by_fd: dict[int, _TcpStream] = {}
|
||||
|
||||
def has_streams(self) -> bool:
|
||||
return bool(self._streams)
|
||||
|
||||
def selector_entries(self) -> list[tuple[int, int]]:
|
||||
entries: list[tuple[int, int]] = []
|
||||
for st in self._streams.values():
|
||||
events = selectors.EVENT_READ
|
||||
if st.want_write:
|
||||
events |= selectors.EVENT_WRITE
|
||||
entries.append((st.fd, events))
|
||||
return entries
|
||||
|
||||
def handle(self, device: str, body: bytes, now: float) -> list[tuple[str, bytes]]:
|
||||
if len(body) < 3:
|
||||
return []
|
||||
stream_id = int.from_bytes(body[0:2], "big")
|
||||
kind = body[2]
|
||||
payload = body[3:]
|
||||
if stream_id == 0:
|
||||
return []
|
||||
|
||||
key = (device, stream_id)
|
||||
if kind == STREAM_OPEN:
|
||||
return self._open(device, stream_id, payload, now)
|
||||
|
||||
st = self._streams.get(key)
|
||||
if st is None:
|
||||
return []
|
||||
|
||||
if kind == STREAM_DATA:
|
||||
if not payload or st.eof_from_phone:
|
||||
return []
|
||||
if len(payload) > st.local_window:
|
||||
self._close_stream(st)
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "window exceeded"))]
|
||||
st.local_window -= len(payload)
|
||||
st.tx_queue.append(payload)
|
||||
return self._flush_tx(st)
|
||||
|
||||
if kind == STREAM_WINDOW:
|
||||
if len(payload) != 4:
|
||||
return []
|
||||
credit = int.from_bytes(payload, "big")
|
||||
st.peer_window += credit
|
||||
return self._drain_rx(st)
|
||||
|
||||
if kind == STREAM_CLOSE:
|
||||
st.eof_from_phone = True
|
||||
if not st.tx_queue and not st.connecting:
|
||||
self._close_stream(st)
|
||||
return []
|
||||
|
||||
return []
|
||||
|
||||
def on_socket_ready(self, fd: int, readable: bool, writable: bool) -> list[tuple[str, bytes]]:
|
||||
st = self._by_fd.get(fd)
|
||||
if st is None:
|
||||
return []
|
||||
out: list[tuple[str, bytes]] = []
|
||||
if st.connecting and writable:
|
||||
err = st.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
||||
if err != 0:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
return [(device, _err(sid, ERR_REFUSED, f"connect failed ({err})"))]
|
||||
st.connecting = False
|
||||
out.append((st.device, _open_ok(st.stream_id, st.local_window)))
|
||||
if st.tx_queue:
|
||||
out += self._flush_tx(st)
|
||||
elif st.eof_from_phone:
|
||||
self._close_stream(st)
|
||||
return out
|
||||
|
||||
if (st.device, st.stream_id) not in self._streams:
|
||||
return out
|
||||
|
||||
if writable and st.tx_queue:
|
||||
out += self._flush_tx(st)
|
||||
|
||||
if (st.device, st.stream_id) not in self._streams:
|
||||
return out
|
||||
|
||||
if readable and not st.connecting:
|
||||
out += self._drain_rx(st)
|
||||
return out
|
||||
|
||||
def tick(self, now: float) -> list[tuple[str, bytes]]:
|
||||
out: list[tuple[str, bytes]] = []
|
||||
for st in list(self._streams.values()):
|
||||
if st.connecting and now - st.opened_at >= OPEN_TIMEOUT:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _err(sid, ERR_REFUSED, "connect timed out")))
|
||||
return out
|
||||
|
||||
def close_device(self, device: str):
|
||||
for st in [s for s in self._streams.values() if s.device == device]:
|
||||
self._close_stream(st)
|
||||
|
||||
def _open(self, device: str, stream_id: int, payload: bytes, now: float) -> list[tuple[str, bytes]]:
|
||||
if len(payload) != 6:
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "bad open"))]
|
||||
port = int.from_bytes(payload[0:2], "big")
|
||||
peer_window = int.from_bytes(payload[2:6], "big")
|
||||
if port not in ALLOWED_PORTS:
|
||||
return [(device, _err(stream_id, ERR_UNSUPPORTED_PORT, f"port {port} not allowed"))]
|
||||
if (device, stream_id) in self._streams:
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "duplicate stream id"))]
|
||||
if sum(1 for d, _ in self._streams if d == device) >= MAX_STREAMS_PER_DEVICE:
|
||||
return [(device, _err(stream_id, ERR_LIMIT, "too many open streams"))]
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.setblocking(False)
|
||||
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
try:
|
||||
err = sock.connect_ex((self._target_host, port))
|
||||
except OSError as e:
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, str(e)))]
|
||||
if err not in (0, errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, f"connect failed ({err})"))]
|
||||
|
||||
if err != 0:
|
||||
_, writable, _ = select.select([], [sock], [], 0.05)
|
||||
if writable:
|
||||
so_err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
||||
if so_err != 0:
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, f"connect failed ({so_err})"))]
|
||||
err = 0
|
||||
|
||||
st = _TcpStream(
|
||||
device=device,
|
||||
stream_id=stream_id,
|
||||
sock=sock,
|
||||
opened_at=now,
|
||||
peer_window=peer_window,
|
||||
connecting=(err != 0),
|
||||
)
|
||||
self._streams[(device, stream_id)] = st
|
||||
self._by_fd[st.fd] = st
|
||||
if not st.connecting:
|
||||
return [(device, _open_ok(stream_id, st.local_window))]
|
||||
return []
|
||||
|
||||
def _flush_tx(self, st: _TcpStream) -> list[tuple[str, bytes]]:
|
||||
if st.connecting:
|
||||
return []
|
||||
written_total = 0
|
||||
while st.tx_queue:
|
||||
chunk = st.tx_queue[0]
|
||||
try:
|
||||
sent = st.sock.send(chunk)
|
||||
except BlockingIOError:
|
||||
break
|
||||
except OSError:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
return [(device, _close(sid, 1))]
|
||||
if sent == 0:
|
||||
break
|
||||
written_total += sent
|
||||
if sent < len(chunk):
|
||||
st.tx_queue[0] = chunk[sent:]
|
||||
break
|
||||
st.tx_queue.popleft()
|
||||
|
||||
out: list[tuple[str, bytes]] = []
|
||||
if written_total > 0:
|
||||
st.consumed_since_ack += written_total
|
||||
st.local_window += written_total
|
||||
if st.consumed_since_ack >= WINDOW_UPDATE_THRESHOLD:
|
||||
ack = st.consumed_since_ack
|
||||
st.consumed_since_ack = 0
|
||||
out.append((st.device, _window(st.stream_id, ack)))
|
||||
|
||||
if st.eof_from_phone and not st.tx_queue:
|
||||
self._close_stream(st)
|
||||
return out
|
||||
|
||||
def _drain_rx(self, st: _TcpStream) -> list[tuple[str, bytes]]:
|
||||
out: list[tuple[str, bytes]] = []
|
||||
while st.peer_window > 0:
|
||||
to_read = min(MAX_DATA_CHUNK, st.peer_window)
|
||||
try:
|
||||
data = st.sock.recv(to_read)
|
||||
except BlockingIOError:
|
||||
break
|
||||
except OSError:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _close(sid, 1)))
|
||||
return out
|
||||
if not data:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _close(sid, 0)))
|
||||
return out
|
||||
st.peer_window -= len(data)
|
||||
out.append((st.device, _data(st.stream_id, data)))
|
||||
return out
|
||||
|
||||
def _close_stream(self, st: _TcpStream):
|
||||
self._streams.pop((st.device, st.stream_id), None)
|
||||
self._by_fd.pop(st.fd, None)
|
||||
try:
|
||||
st.sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_ok(stream_id: int, window: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_OPEN_OK]) + window.to_bytes(4, "big")
|
||||
|
||||
|
||||
def _data(stream_id: int, payload: bytes) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_DATA]) + payload
|
||||
|
||||
|
||||
def _window(stream_id: int, credit: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_WINDOW]) + credit.to_bytes(4, "big")
|
||||
|
||||
|
||||
def _close(stream_id: int, reason: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_CLOSE, reason & 0xFF])
|
||||
|
||||
|
||||
def _err(stream_id: int, code: int, message: str) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_ERROR, code & 0xFF]) + message.encode()
|
||||
@@ -4,7 +4,6 @@ Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import selectors
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
@@ -67,17 +66,11 @@ def _prop(ifaces: dict, iface: str, name: str, default=None):
|
||||
|
||||
class BluetoothManager:
|
||||
def __init__(self, on_write: Callable[[str, bytes, int], None], on_disconnect: Callable[[str], None] | None = None,
|
||||
on_tick: Callable[[], None] | None = None,
|
||||
stream_fds: Callable[[], list[tuple[int, int]]] | None = None,
|
||||
on_stream_ready: Callable[[int, bool, bool], None] | None = None,
|
||||
has_active_session: Callable[[], bool] | None = None):
|
||||
# all callbacks run on the run() thread
|
||||
on_tick: Callable[[], None] | None = None):
|
||||
# all three run on the run() thread
|
||||
self._on_write = on_write # device path, value, mtu
|
||||
self._on_disconnect = on_disconnect # device path
|
||||
self._on_tick = on_tick
|
||||
self._stream_fds = stream_fds
|
||||
self._on_stream_ready = on_stream_ready
|
||||
self._has_active_session = has_active_session
|
||||
self._params = Params()
|
||||
self._conn = None
|
||||
self._enabled = False
|
||||
@@ -85,7 +78,6 @@ class BluetoothManager:
|
||||
self._adapter: str | None = None # the adapter this manager has changed; ready implies it is set
|
||||
self._ready = False
|
||||
self._connected: frozenset[str] = frozenset()
|
||||
self._stale_connected_since: float | None = None
|
||||
self._failed_step: str | None = None
|
||||
self._last_reconcile = 0.0
|
||||
self._last_tick = 0.0
|
||||
@@ -110,7 +102,6 @@ class BluetoothManager:
|
||||
(GATT_CHARACTERISTIC_IFACE, {"Value": ("ay", data)}, [])))
|
||||
|
||||
def disconnect(self, device: str):
|
||||
cloudlog.warning(f"bluetooth: disconnecting {device}")
|
||||
self._send(new_method_call(DBusAddress(device, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
|
||||
def stop(self):
|
||||
@@ -124,7 +115,10 @@ class BluetoothManager:
|
||||
self._last_reconcile = time.monotonic()
|
||||
self._reconcile()
|
||||
self._tick()
|
||||
self._wait_and_dispatch()
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
self._teardown()
|
||||
@@ -134,51 +128,6 @@ class BluetoothManager:
|
||||
conn.close()
|
||||
self._set_connected(frozenset())
|
||||
|
||||
def _wait_and_dispatch(self):
|
||||
# Drain any already-buffered D-Bus messages without blocking.
|
||||
while not self._exit:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=0))
|
||||
except TimeoutError:
|
||||
break
|
||||
if self._exit:
|
||||
return
|
||||
|
||||
entries = self._stream_fds() if self._stream_fds is not None else []
|
||||
if not entries:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
pass
|
||||
return
|
||||
|
||||
dbus_fd = self._conn.sock.fileno()
|
||||
sel = selectors.DefaultSelector()
|
||||
try:
|
||||
sel.register(dbus_fd, selectors.EVENT_READ, data="dbus")
|
||||
for fd, events in entries:
|
||||
try:
|
||||
sel.register(fd, events, data="stream")
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
ready = sel.select(timeout=RECONCILE_PERIOD)
|
||||
for key, mask in ready:
|
||||
if key.data == "dbus":
|
||||
while not self._exit:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=0))
|
||||
except TimeoutError:
|
||||
break
|
||||
else:
|
||||
self._callback(
|
||||
self._on_stream_ready,
|
||||
key.fd,
|
||||
bool(mask & selectors.EVENT_READ),
|
||||
bool(mask & selectors.EVENT_WRITE),
|
||||
)
|
||||
finally:
|
||||
sel.close()
|
||||
|
||||
def _send(self, msg: Message) -> bool:
|
||||
conn = self._conn
|
||||
if conn is None:
|
||||
@@ -241,25 +190,11 @@ class BluetoothManager:
|
||||
self._set_connected(frozenset(path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Connected")))
|
||||
adapter = next((path for path, ifaces in objects.items() if GATT_MANAGER_IFACE in ifaces and ADVERTISING_MANAGER_IFACE in ifaces), None)
|
||||
|
||||
if self._connected and self._has_active_session is not None and not self._has_active_session():
|
||||
now = time.monotonic()
|
||||
if self._stale_connected_since is None:
|
||||
self._stale_connected_since = now
|
||||
elif now - self._stale_connected_since >= 15.0:
|
||||
cloudlog.warning(f"bluetooth: disconnecting stale idle devices {sorted(self._connected)}")
|
||||
for path in self._connected:
|
||||
self._call(new_method_call(DBusAddress(path, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
self._stale_connected_since = None
|
||||
self._set_connected(frozenset())
|
||||
else:
|
||||
self._stale_connected_since = None
|
||||
|
||||
if self._ready and adapter == self._adapter:
|
||||
ifaces = objects[adapter]
|
||||
# a restarted bluetoothd keeps the adapter powered but has no advertisement;
|
||||
# while a phone is connected, single-role controllers may pause advertising without losing the app.
|
||||
# a restarted bluetoothd keeps the adapter powered but has no advertisement
|
||||
if (_prop(ifaces, ADAPTER_IFACE, "Powered") and not _prop(ifaces, ADAPTER_IFACE, "Pairable", True) and
|
||||
(self._connected or _prop(ifaces, ADVERTISING_MANAGER_IFACE, "ActiveInstances", 0) >= 1)):
|
||||
_prop(ifaces, ADVERTISING_MANAGER_IFACE, "ActiveInstances", 0) >= 1):
|
||||
return
|
||||
cloudlog.warning(f"bluetooth: lost {adapter}, setting up again")
|
||||
|
||||
@@ -270,10 +205,6 @@ class BluetoothManager:
|
||||
|
||||
def _setup(self, adapter: str, objects: dict):
|
||||
self._unregister(adapter)
|
||||
for path, ifaces in objects.items():
|
||||
if _prop(ifaces, DEVICE_IFACE, "Connected"):
|
||||
cloudlog.warning(f"bluetooth: disconnecting leftover {path} before setup")
|
||||
self._call(new_method_call(DBusAddress(path, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
adapter_address = DBusAddress(adapter, BLUEZ, ADAPTER_IFACE)
|
||||
props = Properties(adapter_address)
|
||||
paired = [path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Paired")]
|
||||
@@ -339,7 +270,6 @@ class BluetoothManager:
|
||||
# BlueZ has already acked the write and discards this reply, so the only refusal is a disconnect.
|
||||
# A long write arrives joined at offset 0, so the length is checked as well.
|
||||
if options.get("offset", ("q", 0))[1] != 0 or len(value) > mtu - 3:
|
||||
cloudlog.warning(f"bluetooth: bad WriteValue offset={options.get('offset')} len={len(value)} mtu={mtu} from {device}")
|
||||
self.disconnect(device)
|
||||
else:
|
||||
self._callback(self._on_write, device, bytes(value), mtu)
|
||||
@@ -368,19 +298,9 @@ class Daemon:
|
||||
self._retry_at: float | None = None
|
||||
|
||||
def new_manager(self) -> BluetoothManager:
|
||||
self.bt = BluetoothManager(
|
||||
self.on_write,
|
||||
self._engine.on_disconnect,
|
||||
self.tick,
|
||||
stream_fds=self._engine.stream_selector_entries,
|
||||
on_stream_ready=self.on_stream_ready,
|
||||
has_active_session=lambda: self._engine.connected() > 0,
|
||||
)
|
||||
self.bt = BluetoothManager(self.on_write, self._engine.on_disconnect, self.tick)
|
||||
return self.bt
|
||||
|
||||
def on_stream_ready(self, fd: int, readable: bool, writable: bool):
|
||||
self._act(self._engine.on_stream_ready(fd, readable, writable))
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int):
|
||||
self._act(self._engine.on_write(device, value, mtu, time.monotonic()))
|
||||
|
||||
|
||||
@@ -568,7 +568,7 @@ class TestRpcOverSession(OpenpilotTestCase):
|
||||
def test_params_refusals_are_all_or_nothing(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
for keys in (["BluetoothAllowed"], ["BluetoothEnabled"], ["SunnylinkLocalBleGrants"], ["AdbEnabled"]):
|
||||
assert "result" in phone.rpc("params.get", 0.0, {"keys": keys})
|
||||
assert phone.rpc("params.get", 0.0, {"keys": keys})["error"]["code"] == -32001
|
||||
refused = phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "y", "BluetoothAllowed": False}})
|
||||
assert refused["error"]["code"] == -32001
|
||||
assert h.params.data.get("CarParamsSP") is None
|
||||
@@ -624,64 +624,3 @@ class TestRpcOverSession(OpenpilotTestCase):
|
||||
assert phone.connected and json.loads(phone.pop_record(s.RPC))["error"]["code"] == -32601
|
||||
h.send(phone, phone.records.seal(bytes([s.RPC]) + b" " * 17000), 0.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_stream_rejects_disallowed_port(self, mocker):
|
||||
from openpilot.sunnypilot.system.ble import stream as st
|
||||
h, phone = self.session(mocker)
|
||||
open_req = (1).to_bytes(2, "big") + bytes([st.STREAM_OPEN]) + (80).to_bytes(2, "big") + (16384).to_bytes(4, "big")
|
||||
h.send_record(phone, s.STREAM, open_req, 0.0)
|
||||
reply = phone.pop_record(s.STREAM)
|
||||
assert int.from_bytes(reply[0:2], "big") == 1
|
||||
assert reply[2] == st.STREAM_ERROR
|
||||
assert reply[3] == st.ERR_UNSUPPORTED_PORT
|
||||
|
||||
def test_stream_proxies_tcp_echo(self, mocker):
|
||||
import selectors
|
||||
import socket
|
||||
from openpilot.sunnypilot.system.ble import stream as st
|
||||
|
||||
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
srv.bind(("127.0.0.1", 0))
|
||||
srv.listen(1)
|
||||
port = srv.getsockname()[1]
|
||||
try:
|
||||
mocker.patch.object(st, "ALLOWED_PORTS", (port,))
|
||||
h, phone = self.session(mocker)
|
||||
phone.mtu = 247
|
||||
open_req = (7).to_bytes(2, "big") + bytes([st.STREAM_OPEN]) + port.to_bytes(2, "big") + (16384).to_bytes(4, "big")
|
||||
h.send_record(phone, s.STREAM, open_req, 0.0)
|
||||
|
||||
conn, _ = srv.accept()
|
||||
try:
|
||||
# Pump until OPEN_OK arrives
|
||||
for _ in range(10):
|
||||
for fd, events in h.engine.stream_selector_entries():
|
||||
h._deliver(h.engine.on_stream_ready(fd, bool(events & selectors.EVENT_READ), bool(events & selectors.EVENT_WRITE)))
|
||||
if phone.inbox:
|
||||
break
|
||||
ok = phone.pop_record(s.STREAM)
|
||||
assert ok[0:3] == (7).to_bytes(2, "big") + bytes([st.STREAM_OPEN_OK])
|
||||
|
||||
# Phone -> TCP server
|
||||
data_req = (7).to_bytes(2, "big") + bytes([st.STREAM_DATA]) + b"SSH-2.0-test\r\n"
|
||||
h.send_record(phone, s.STREAM, data_req, 0.0)
|
||||
assert conn.recv(64) == b"SSH-2.0-test\r\n"
|
||||
|
||||
# TCP server -> Phone
|
||||
conn.sendall(b"SSH-2.0-OpenSSH\r\n")
|
||||
for _ in range(10):
|
||||
for fd, events in h.engine.stream_selector_entries():
|
||||
h._deliver(h.engine.on_stream_ready(fd, bool(events & selectors.EVENT_READ), bool(events & selectors.EVENT_WRITE)))
|
||||
if phone.inbox:
|
||||
break
|
||||
echoed = phone.pop_record(s.STREAM)
|
||||
assert echoed[0:3] == (7).to_bytes(2, "big") + bytes([st.STREAM_DATA])
|
||||
assert echoed[3:] == b"SSH-2.0-OpenSSH\r\n"
|
||||
|
||||
# Disconnect cleans up stream
|
||||
h.engine.on_disconnect(phone.device)
|
||||
assert h.engine.stream_selector_entries() == []
|
||||
finally:
|
||||
conn.close()
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
+1
-1
Submodule tinygrad_repo updated: 301a0d1ded...92b742f711
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user