Compare commits

...

22 Commits

Author SHA1 Message Date
Jason Wen 7fde95c2e4 NNLC: keep own PID in torque extension 2026-11-29 01:27:31 -05:00
Jason Wen b6ab2aa2a7 controls: remove sunnypilot accel boost (#2124) 2026-11-29 00:39:10 -05:00
Jason Wen cb72553e68 ci: fix and check big warp frame size (#2123)
* ci: match big warp frame size with stock modeld

* ci: check big warps against stock modeld
2026-11-29 00:34:30 -05:00
nitrobass24 1ee68c19e0 statsd: fix StatLogSP hang at exit (#2118)
* statsd: close comma_statlog's socket before terminating the shared zmq context

StatLogSP and its comma_statlog both connect on zmq.Context.instance().
__del__ ran super().__del__() first, which calls term() on that shared
context while comma_statlog's socket is still open, and term() blocks
until every socket on the context is closed. A process that had sent a
stat hung at exit.

Close comma_statlog's socket first, and terminate the context once.

Co-authored-by: tonesto7 <1835933+tonesto7@users.noreply.github.com>

* cleanup

---------

Co-authored-by: tonesto7 <1835933+tonesto7@users.noreply.github.com>
Co-authored-by: Jason Wen <haibin.wen3@gmail.com>
2026-11-28 23:29:56 -05:00
Jason Wen 4886d4ff5e Sync: commaai/openpilot:master → sunnypilot/sunnypilot:master (#2121) 2026-11-28 22:35:03 -05:00
Jason Wen 106221e913 Merge commit 'bcb9f1f6e1f2bf4f0200b6b10213667a61d8d80a' into sync-20261128
Co-authored-by: discountchubbs <alexgrant990@gmail.com>
2026-11-28 21:31:36 -05:00
Harald Schäfer bcb9f1f6e1 alfred: install branch before release in install job (#39507) 2026-11-28 13:59:32 -08:00
Adeeb Shihadeh cd230febd6 bump ty to 0.0.112 and fix the type errors it finds (#39506)
* fix ty 0.0.112 errors outside the ui

* bump ty to 0.0.112, drop its ignores

* ty: cleaner fixes
2026-11-28 12:57:26 -08:00
Adeeb Shihadeh acedc29bc0 ui: fix the type errors newer ty finds (#39505) 2026-11-28 12:14:17 -08:00
Adeeb Shihadeh afa371c088 athenad: run each connection in its own process for instant network changes (#39500)
* athenad: run each connection in its own process

* athenad: review fixes

* athenad: cleanup and adversarial test fixes

* athenad: sol review fixes
2026-11-28 12:10:16 -08:00
Adeeb Shihadeh be6af3676f raylib typing fixups (#39503) 2026-11-28 11:58:38 -08:00
Jason Wen 55b319248e ci: update prebuilt build (#2117) 2026-11-28 13:26:15 -05:00
Adeeb Shihadeh ef13da2e77 long mpc: add acados solver type stub so it type checks without a build (#39502) 2026-11-28 09:56:42 -08:00
Adeeb Shihadeh 643012f9d4 misc cleanups (#39501) 2026-11-28 09:46:33 -08:00
Armand du Parc Locmaria 7837414753 long mpc: use model predicted lead traj (#39445)
* long mpc: use model predicted lead traj

* no fix for now

* adv test

* aleak residual

* fallback

* clip model accel

* just use model predicted accel

* clip model predicted accel before adding radar residual

* tune

* rename constants

* unused extrapolate

* rm useless checks

* clip model lead like we clip radar lead

* don't need those

* dedupe

* cleanup

* cleanup

* plot on a row

* test adv maneuvers on all follow distances

* cleanup

* simulate aLeadTau

* tune bounds for wrong model

* clip fused to -10, 20 iters

* keep stock acc behavior unchanged

* touch one less file

* cleanup

* codespell

* simplify report

* more cases
2026-11-28 02:02:32 -08:00
Harald Schäfer db01481db1 Test fresh openpilot installs on mici (#39492)
* Test fresh openpilot installs on mici

* Run the installer with the AGNOS app's resource limits

* Keep the clean install in the device app slice

* Exercise a bucket-only LFS object in the mici install test

* Revert "Exercise a bucket-only LFS object in the mici install test"

This reverts commit 1bd772d3afd8523784c8855e8adc61dabe9f2f07.

* Simplify the fresh mici installer test

* Run the mici install test directly from Alfred

* Remove installer test comment
2026-11-27 21:50:56 -08:00
Harald Schäfer e7d349f89f Process replay: remove the cruise jerk RMS check (#39489)
* Process replay: measure jerk over recorded cruise windows

* Process replay: remove the cruise jerk RMS check
2026-11-27 17:30:15 -08:00
Adeeb Shihadeh a7c2a1f1dd bump tinygrad (#39484) 2026-11-27 16:47:43 -08:00
Adeeb Shihadeh 9e9067d5cf model replay: don't cache master's ref (#39487) 2026-11-27 16:35:31 -08:00
Adeeb Shihadeh c86429dfd7 remove device permission workaround, AGNOS does it now (#39485) 2026-11-27 16:01:18 -08:00
Adeeb Shihadeh f37cf702dd prep for mainline kernel (#39481) 2026-11-27 15:25:46 -08:00
Adeeb Shihadeh bfa224d108 ui: forward only raylib's warnings past window setup (#39482) 2026-11-27 15:25:20 -08:00
140 changed files with 1226 additions and 1138 deletions
+56
View File
@@ -0,0 +1,56 @@
name: Compile and check the big warps
description: Compile the chestnut warps for each camera and warm up stock modeld on them, on the amd mock
runs:
using: composite
steps:
- run: ./tools/op.sh setup
shell: bash
- name: Build modeld deps
shell: bash
run: scons -j$(nproc) msgq_repo/msgq openpilot/common
- name: Compile big warp
shell: bash
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32"
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
for res in $(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}')"); do
CAM_W=$(echo $res | cut -d x -f1)
CAM_H=$(echo $res | cut -d x -f2)
STRIDE_INFO=$(python3 -c "
import sys
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
s,y,u,sz = get_nv12_info(int(sys.argv[1]), int(sys.argv[2]))
print(f'{s},{y},{u},{s*(y+u)}')
" $CAM_W $CAM_H)
WARP_PKL="${MODELS_DIR}/big_driving_warp_${res}_tinygrad.pkl"
python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
--warp-to ${MODEL_SIZE} \
--layout yuv420 \
--frames 2 \
--benchmark-runs 0 \
--retargetable \
--output "${WARP_PKL}"
done
- name: Warm up stock modeld on the big warps
shell: bash
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
fail=0
for res in $(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}')"); do
echo "warming up stock modeld on ${res}"
python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" GMMU=0 CHECK_OOB=0 python3 -c "
import sys
from openpilot.selfdrive.modeld.modeld import ModelState
ModelState(*map(int, sys.argv[1].split('x')), chestnut=True).warmup()
" $res || { echo "::error::stock modeld warmup failed on the ${res} big warp"; fail=1; }
done
exit $fail
+1 -31
View File
@@ -166,37 +166,7 @@ jobs:
with:
emu_cache: big-warp
- name: Install the amd mock build dependencies
run: python3 -m pip install -q numpy zstandard
- name: Compile big warp
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32"
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
for res in $(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}')"); do
CAM_W=$(echo $res | cut -d x -f1)
CAM_H=$(echo $res | cut -d x -f2)
STRIDE_INFO=$(python3 -c "
import sys
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
s,y,u,sz = get_nv12_info(int(sys.argv[1]), int(sys.argv[2]))
print(f'{s},{y},{u},{sz}')
" $CAM_W $CAM_H)
WARP_PKL="${MODELS_DIR}/big_driving_warp_${res}_tinygrad.pkl"
python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
--warp-to ${MODEL_SIZE} \
--layout yuv420 \
--frames 2 \
--benchmark-runs 0 \
--retargetable \
--output "${WARP_PKL}"
done
- uses: ./.github/workflows/big-warp
- name: Prepare output
env:
@@ -112,7 +112,7 @@ jobs:
concurrency:
group: build-${{ github.head_ref || github.ref_name }}
cancel-in-progress: false
runs-on: [self-hosted, tici]
runs-on: ubuntu-24.04-arm
if: ${{
(always() && !cancelled() && !failure()) &&
needs.prepare_strategy.result == 'success' &&
@@ -129,55 +129,59 @@ jobs:
repository: ${{ github.event.pull_request.head.repo.fork && github.event.pull_request.head.repo.full_name || github.repository }}
- run: ./lfs.py pull --exclude=''
- name: Set environment variables
- name: Import the AGNOS system image this commit pins
run: |
# Set up common environment
source /etc/profile;
read -r URL HASH HASH_RAW < <(python3 -c "import json; p = next(p for p in json.load(open('openpilot/common/hardware/comma/agnos.json')) if p['name'] == 'system'); print(p['url'], p['hash'], p['hash_raw'])")
curl -fsSL --retry 3 "$URL" | xz -dc -T0 > "$RUNNER_TEMP/system.sparse.img"
echo "$HASH $RUNNER_TEMP/system.sparse.img" | sha256sum -c
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends android-sdk-libsparse-utils
simg2img "$RUNNER_TEMP/system.sparse.img" "$RUNNER_TEMP/system.img" && rm "$RUNNER_TEMP/system.sparse.img"
echo "$HASH_RAW $RUNNER_TEMP/system.img" | sha256sum -c
sudo mkdir -p /mnt/agnos && sudo mount -o loop,ro "$RUNNER_TEMP/system.img" /mnt/agnos
sudo tar -C /mnt/agnos --exclude=./etc/resolv.conf -c . | docker import - agnos # a symlink into /run: docker writes its own
sudo umount /mnt/agnos && rm "$RUNNER_TEMP/system.img"
- name: Build Main Project in AGNOS
run: |
cat > "$RUNNER_TEMP/build.sh" <<'EOF'
set -e
source /etc/profile
set -x
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
mkdir -p "$HOME"
git config --global --add safe.directory '*'
cat /VERSION
clang --version | head -1
cd /src
uv sync
printenv >> $GITHUB_ENV
- name: Setup build environment
run: |
mkdir -p "${BUILD_DIR}/"
sudo find $BUILD_DIR/ -mindepth 1 -delete
echo "Starting build stage..."
echo "BUILD_DIR: ${BUILD_DIR}"
echo "CI_DIR: ${CI_DIR}"
echo "VERSION: ${{ needs.prepare_strategy.outputs.version }}"
echo "UV_PROJECT_ENVIRONMENT: ${UV_PROJECT_ENVIRONMENT}"
echo "VIRTUAL_ENV: ${VIRTUAL_ENV}"
echo "-------"
if [[ "${{ runner.debug }}" == "1" ]]; then
printenv
fi
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- name: Build Main Project
run: |
export PYTHONPATH="$BUILD_DIR:$BUILD_DIR/msgq_repo:$BUILD_DIR/opendbc_repo:$BUILD_DIR/rednose_repo:$BUILD_DIR/teleoprtc_repo:$BUILD_DIR/tinygrad_repo"
./tools/release/release_files.py | xargs -0 cp -pR --parents -t "$BUILD_DIR" --
# outside the checkout, which is wiped each run. /data/scons_cache is the device's, not ours.
SCONS_CACHE="$RUNNER_WORKSPACE/scons_cache"
pip install -q tinymesa==25.2.7.2
# scons passes the warp commands only PATH, TMPDIR and PYTHONPATH, so the mock goes into the command itself
sed -i "s/'DEV=QCOM /'DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes /" "$BUILD_DIR/openpilot/selfdrive/modeld/SConscript"
grep -q "'DEV=MOCK+QCOM " "$BUILD_DIR/openpilot/selfdrive/modeld/SConscript"
# msgq builds the ION vision buffers only when /dev/ion exists; the device has one, the runner does not
touch /dev/ion
SCONS_CACHE=/data/scons_cache
mkdir -p "$SCONS_CACHE"
cd $BUILD_DIR
echo "Building locationd..."
# -j1: parallel rednose generators OOM the device
scons -j1 cache_dir="$SCONS_CACHE" --minimal \
openpilot/selfdrive/locationd
echo "Building rest of sunnypilot"
sudo rm -rf /tmp/* || true
rm -rf /tmp/* || true
mkdir -p "$BUILD_DIR/tmp"
export TMPDIR="$BUILD_DIR/tmp"
SKIP_TINYGRAD_COMPILE=1 /usr/bin/time -v scons -j$(nproc) cache_dir="$SCONS_CACHE" --minimal
SKIP_TINYGRAD_COMPILE=1 scons -j$(nproc) cache_dir="$SCONS_CACHE" --minimal
touch ${BUILD_DIR}/prebuilt
if [[ "${{ runner.debug }}" == "1" ]]; then
ls -la ${BUILD_DIR}
fi
EOF
sudo mkdir -p "$BUILD_DIR" && sudo chown -R "$(id -u):$(id -g)" /data
# AGNOS mounts these at boot (usr/comma/boot.sh); its uv and pip shims remount / read-only and resize /tmp
# /root: scons drops HOME, so tinygrad's compile cache lands in root's home
docker run --rm --privileged -e CI=true -e HOME=/data/media/0/github -e BUILD_DIR \
--tmpfs /tmp:rw,exec,nosuid,nodev,size=150m,nr_inodes=1m,mode=1777 --tmpfs /var:rw,exec,nosuid,nodev,size=128m,mode=755 \
--tmpfs /home:rw,exec,nosuid,nodev,size=100m,mode=755 --tmpfs /root:rw,exec,nosuid,nodev,size=1g,mode=700 \
-v "$GITHUB_WORKSPACE:/src" -v /data:/data -v "$RUNNER_TEMP/build.sh:/build.sh:ro" agnos bash /build.sh
sudo chown -R "$(id -u):$(id -g)" "$BUILD_DIR"
- name: Strip release tree
run: |
@@ -209,12 +213,6 @@ jobs:
path: prebuilt.tar.gz
compression-level: 0
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
prepare_chestnut:
needs: [ prepare_strategy ]
runs-on: ubuntu-24.04
+26
View File
@@ -0,0 +1,26 @@
name: Test big warps with stock modeld
on:
pull_request:
paths:
- 'openpilot/selfdrive/modeld/**'
- 'tinygrad_repo'
- 'openpilot/system/camerad/cameras/nv12_info.py'
- '.github/workflows/big-warp/**'
- '.github/workflows/test-big-warp.yaml'
workflow_dispatch:
jobs:
big-warp:
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Pull big PKL via LFS
run: ./lfs.py pull --exclude=''
- uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: big-warp
- uses: ./.github/workflows/big-warp
+16 -2
View File
@@ -41,7 +41,7 @@ run = "tools/release/check-dirty.sh"
# the UP replays the CAN until the step ends
[[jobs.onroad.steps]]
name = "Onroad tests"
run = "openpilot/tools/replay/can_replay.py --up && ./openpilot/selfdrive/test/test_onroad.py TestOnroad"
run = "openpilot/tools/replay/can_replay.py && ./openpilot/selfdrive/test/test_onroad.py TestOnroad"
timeout-minutes = 1.5
[jobs.hardware]
@@ -63,6 +63,20 @@ run = "./openpilot/system/manager/test/test_manager.py"
name = "Power draw"
run = "./openpilot/selfdrive/test/test_power_draw.py"
[jobs.install]
runs-on = "up-mici"
timeout-minutes = 45
[[jobs.install.steps]]
name = "Install this branch on a fresh mici"
run = 'scripts/test_mici_install.sh "https://installer.comma.ai/${GIT_REPO%/*}/$GIT_BRANCH" "$GIT_COMMIT"'
timeout-minutes = 20
[[jobs.install.steps]]
name = "Install the release on a fresh mici"
run = "scripts/test_mici_install.sh https://openpilot.comma.ai origin/release-mici"
timeout-minutes = 20
[jobs.replay]
runs-on = "up-mici"
timeout-minutes = 35
@@ -145,7 +159,7 @@ mkdir -p /data/pandaextra/certs && printf '%s\n' "$PANDA_RELEASE_KEY" > /data/pa
unset RELEASE_KEY PANDA_RELEASE_KEY
export GIT_SSH_COMMAND="ssh -i /data/gitkey -o StrictHostKeyChecking=accept-new"
git config remote.origin.url git@github.com:commaai/openpilot.git
if [ -n "${UP_REMOTE:-}" ]; then openpilot/tools/replay/can_replay.py --up; fi
if [ -n "${UP_REMOTE:-}" ]; then openpilot/tools/replay/can_replay.py; fi
tools/release/build_release.sh $RELEASE_TESTS
"""
-7
View File
@@ -12,13 +12,6 @@ function agnos_init {
# set success flag for current boot slot
sudo abctl --set_success
# TODO: do this without udev in AGNOS
# udev does this, but sometimes we startup faster
sudo chgrp gpu /dev/adsprpc-smd /dev/ion /dev/kgsl-3d0
sudo chmod 660 /dev/adsprpc-smd /dev/ion /dev/kgsl-3d0
sudo chgrp audio /dev/snd/*C*
sudo chmod 660 /dev/snd/*C*
# Check if AGNOS update is required
if [ "$(< /VERSION)" != "$AGNOS_VERSION" ]; then
AGNOS_PY="$DIR/openpilot/common/hardware/comma/agnos.py"
+1
View File
@@ -3,6 +3,7 @@ from openpilot.common.api.comma_connect import API_HOST as API_HOST, CommaConnec
class Api:
def __init__(self, dongle_id):
self.dongle_id = dongle_id
self.service = CommaConnectApi(dongle_id)
def request(self, method, endpoint, **params):
+3
View File
@@ -137,6 +137,7 @@ class AtClient:
def send_raw(self, data: bytes) -> None:
self._ensure_serial()
assert self._serial is not None
self._serial.reset_input_buffer()
self._serial.write(data)
self._serial.flush()
@@ -156,9 +157,11 @@ class AtClient:
def _send(self, cmd: str) -> None:
if DEBUG:
print(f"SER >> {cmd}", file=sys.stderr)
assert self._serial is not None
self._serial.write((cmd + "\r").encode("ascii"))
def _expect(self) -> list[str]:
assert self._serial is not None
lines: list[str] = []
while True:
raw = self._serial.readline()
+3
View File
@@ -112,6 +112,9 @@ class HardwareBase(ABC):
def get_network_metered(self, network_type) -> bool:
return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet)
def get_voltage(self):
return 0
def get_current_power_draw(self):
return 0
+20 -3
View File
@@ -1,4 +1,5 @@
import configparser
import glob
import json
import os
import socket
@@ -28,9 +29,25 @@ def affine_irq(val, action):
print(f"No IRQs found for '{action}'")
return
# power save takes the big cores offline; their IRQs stay where the kernel moved them until the cores come back
# and the IRQs are affined again
online = Path(f"/sys/devices/system/cpu/cpu{val}/online")
if online.exists() and online.read_text().strip() == "0":
return
for i in irqs:
sudo_write(str(val), f"/proc/irq/{i}/smp_affinity_list")
_hwmon: dict[str, tuple[Path | None, float]] = {}
def hwmon(name: str) -> Path | None:
"""the hwmon device with this name, hwmon numbering depends on probe order. None until its driver has probed, or on
devices without it (the comma four has no INA231): the scan costs ~3 ms, so a miss is only scanned again after 10 s"""
path, scanned = _hwmon.get(name, (None, -10.))
if path is None and time.monotonic() - scanned >= 10.:
path = next((Path(p).parent for p in sorted(glob.glob("/sys/class/hwmon/hwmon*/name")) if Path(p).read_text().strip() == name), None)
_hwmon[name] = (path, time.monotonic())
return path
@lru_cache
def get_device_type():
# lru_cache and cache can cause memory leaks when used in classes
@@ -101,11 +118,11 @@ class HardwareComma(HardwareBase):
return self.get_cmdline()['androidboot.serialno']
def get_voltage(self):
with open("/sys/class/hwmon/hwmon1/in1_input") as f:
with open(f"{hwmon('ina231')}/in1_input") as f:
return int(f.read())
def get_current(self):
with open("/sys/class/hwmon/hwmon1/curr1_input") as f:
with open(f"{hwmon('ina231')}/curr1_input") as f:
return int(f.read())
def set_ir_power(self, percent: int):
@@ -248,7 +265,7 @@ class HardwareComma(HardwareBase):
return self.get_modem_state().get('temperatures', [])
def get_current_power_draw(self):
return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6)
return (self.read_param_file(f"{hwmon('ina231')}/power1_input", int) / 1e6)
def get_som_power_draw(self):
return (self.read_param_file("/sys/class/power_supply/bms/voltage_now", int) * self.read_param_file("/sys/class/power_supply/bms/current_now", int) / 1e12)
@@ -7,10 +7,11 @@ from collections import deque
from openpilot.common.realtime import Ratekeeper
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.hardware.comma.hardware import hwmon
def read_power():
with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/power1_input") as f:
with open(f"{hwmon('ina231')}/power1_input") as f:
return int(f.read()) / 1e6
def sample_power(seconds=5) -> list[float]:
@@ -26,7 +26,7 @@ class TestAmplifier(OpenpilotTestCase):
def _check_for_i2c_errors(self, expected):
dmesg = subprocess.check_output("dmesg", shell=True, encoding='utf8')
i2c_lines = [l for l in dmesg.strip().splitlines() if 'i2c_geni a88000.i2c' in l]
i2c_lines = [l for l in dmesg.strip().splitlines() if 'a88000.i2c' in l]
i2c_str = '\n'.join(i2c_lines)
if not expected:
-1
View File
@@ -149,7 +149,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"Version", {PERSISTENT, STRING}},
// --- sunnypilot params --- //
{"AccelBoostSP", {PERSISTENT | BACKUP, BOOL, "1"}},
{"ApiCache_DriveStats", {PERSISTENT, JSON}},
{"AutoLaneChangeBsmDelay", {PERSISTENT | BACKUP, BOOL, "0"}},
{"AutoLaneChangeTimer", {PERSISTENT | BACKUP, INT, "0"}},
+1 -1
View File
@@ -17,7 +17,7 @@ class Spinner:
return self
def update(self, spinner_text: str):
if self.spinner_proc is not None:
if self.spinner_proc is not None and self.spinner_proc.stdin is not None:
self.spinner_proc.stdin.write(spinner_text.encode('utf8') + b"\n")
try:
self.spinner_proc.stdin.flush()
+2 -1
View File
@@ -49,7 +49,7 @@ class SwaglogRotatingFileHandler(BaseRotatingHandler):
return sorted(log_files, reverse=True)
def shouldRollover(self, record):
size_exceeded = self.max_bytes > 0 and self.stream.tell() >= self.max_bytes
size_exceeded = self.max_bytes > 0 and self.stream is not None and self.stream.tell() >= self.max_bytes
time_exceeded = self.interval > 0 and self.last_rollover + self.interval <= time.monotonic()
return size_exceeded or time_exceeded
@@ -91,6 +91,7 @@ class UnixDomainSocketHandler(logging.Handler):
self.connect()
msg = self.format(record).rstrip('\n')
assert self.sock is not None
try:
self.sock.sendto((chr(record.levelno)+msg).encode('utf8'), Paths.swaglog_ipc())
except OSError:
+2
View File
@@ -4,6 +4,7 @@ import inspect
import os
import subprocess
import unittest
from collections.abc import Callable
from unittest import mock
from openpilot.common.hardware import HARDWARE, COMMA_HARDWARE
@@ -26,6 +27,7 @@ class OpenpilotTestCase(unittest.TestCase):
COMMA_HARDWARE_TEST = False
SHARED_DOWNLOAD_CACHE = False
openpilot_setup_method: Callable[[], None] # a subclass's setup_method, moved here by __init_subclass__
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
@@ -1,19 +0,0 @@
import numpy as np
from scipy.io import wavfile
sr = 48000
max_int16 = 2**15 - 1
def harmonic_beep(freq, duration_seconds):
n_total = int(sr * duration_seconds)
signal = np.sin(2 * np.pi * freq * np.arange(n_total) / sr)
x = np.arange(n_total)
exp_scale = np.exp(-x/5.5e3)
return max_int16 * signal * exp_scale
engage_beep = harmonic_beep(1661.219, 0.5)
wavfile.write("engage.wav", sr, engage_beep.astype(np.int16))
disengage_beep = harmonic_beep(1318.51, 0.5)
wavfile.write("disengage.wav", sr, disengage_beep.astype(np.int16))
+1
View File
@@ -119,6 +119,7 @@ class Car:
# continue onto next fingerprinting step in pandad
self.params.put_bool("FirmwareQueryDone", True, block=True)
else:
assert RI is not None
self.CI, self.CP, self.CP_SP = CI, CI.CP, CI.CP_SP
self.RI = RI
@@ -35,6 +35,9 @@ def run_cruise_simulation(cruise, personality, t_end=20.):
log.LongitudinalPersonality.schema.enumerants, # personality
[5,35])) # speed
class TestCruiseSpeed(OpenpilotTestCase):
personality: str
speed: int
def test_cruise_speed(self):
print(f'Testing {self.speed} m/s')
cruise_speed = float(self.speed)
@@ -46,6 +49,9 @@ class TestCruiseSpeed(OpenpilotTestCase):
# TODO: test pcmCruise and pcmCruiseSpeed
@parameterized_class(('pcm_cruise', 'pcm_cruise_speed'), [(False, True)])
class TestVCruiseHelper(OpenpilotTestCase):
pcm_cruise: bool
pcm_cruise_speed: bool
def setup_method(self):
self.CP = car.CarParams(pcmCruise=self.pcm_cruise)
self.CP_SP = custom.CarParamsSP(pcmCruiseSpeed=self.pcm_cruise_speed)
+2 -1
View File
@@ -18,6 +18,7 @@ from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle, STEER_ANGLE_SATURATION_THRESHOLD
from openpilot.selfdrive.controls.lib.latcontrol_curvature import LatControlCurvature
from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
from openpilot.selfdrive.controls.lib.longcontrol import LongControl
from openpilot.selfdrive.modeld.modeld import LAT_SMOOTH_SECONDS
from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose
@@ -91,7 +92,7 @@ class Controls(ControlsExt):
self.curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll)
# Update Torque Params
if self.CP.lateralTuning.which() == 'torque':
if isinstance(self.LaC, (LatControlTorque, LatControlTorqueV0)):
torque_params = self.sm['lateralTorqueParameters']
if self.sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
self.LaC.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
@@ -82,7 +82,7 @@ lenv["CCFLAGS"].append("-Wno-unused")
if arch != "Darwin":
lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags")
else:
lenv["LINKFLAGS"].append("-Wl,-install_name,@loader_path/libacados_ocp_solver_long.dylib")
lenv["LINKFLAGS"].append(f"-Wl,-install_name,@loader_path/{gen}/libacados_ocp_solver_long.dylib")
lenv["LINKFLAGS"].append(f"-Wl,-rpath,@loader_path/{acados_rel_path}")
lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_long",
build_files,
@@ -96,7 +96,7 @@ libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c')
lenv2 = envCython.Clone()
lenv2["LIBPATH"] += [lib_solver[0].dir.abspath]
lenv2["RPATH"] += [lenv2.Literal('\\$$ORIGIN')]
lenv2["RPATH"] += [lenv2.Literal(f'\\$$ORIGIN/{gen}')]
lenv2.Command(libacados_ocp_solver_c,
[acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd],
f'cython' + \
@@ -104,7 +104,8 @@ lenv2.Command(libacados_ocp_solver_c,
f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \
f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \
f' {acados_ocp_solver_pyx.get_labspath()}')
lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c], LIBS=['acados_ocp_solver_long'])
# outside of gen, next to its committed type stub
lib_cython = lenv2.Program('acados_ocp_solver_pyx.so', [libacados_ocp_solver_c], LIBS=['acados_ocp_solver_long'])
lenv2.Depends(lib_cython, lib_solver)
lenv2.Depends(lib_cython, copied_acados_libs)
lenv2.Depends(libacados_ocp_solver_c, np_version)
@@ -0,0 +1,27 @@
# acados_template's Cython solver, compiled against c_generated_code by the SConscript
from typing import Any
import numpy as np
class AcadosOcpSolverCython:
def __init__(self, model_name: str, nlp_solver_type: str, N: int) -> None: ...
def solve_for_x0(self, x0_bar: np.ndarray) -> np.ndarray: ...
def solve(self) -> int: ...
def reset(self, reset_qp_solver_mem: int = 1) -> int: ...
def custom_update(self, data_: np.ndarray) -> int: ...
def set_new_time_steps(self, new_time_steps: np.ndarray) -> None: ...
def update_qp_solver_cond_N(self, qp_solver_cond_N: int) -> None: ...
def eval_param_sens(self, index: int, stage: int = 0, field: str = "ex") -> None: ...
def get(self, stage: int, field_: str) -> np.ndarray: ...
def print_statistics(self) -> None: ...
def store_iterate(self, filename: str = '', overwrite: bool = False) -> None: ...
def load_iterate(self, filename: str) -> None: ...
def get_stats(self, field_: str) -> Any: ...
def get_cost(self) -> float: ...
def get_residuals(self, recompute: bool = False) -> np.ndarray: ...
def set(self, stage: int, field_: str, value_: Any) -> None: ...
def cost_set(self, stage: int, field_: str, value_: Any) -> None: ...
def constraints_set(self, stage: int, field_: str, value_: Any) -> None: ...
def get_from_qp_in(self, stage: int, field_: str) -> np.ndarray: ...
def options_set(self, field_: str, value_: Any) -> None: ...
def set_params_sparse(self, stage: int, idx_values_: np.ndarray, param_values_: np.ndarray) -> None: ...
@@ -7,13 +7,13 @@ from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX
from openpilot.common.realtime import DT_MDL
from openpilot.common.swaglog import cloudlog
# WARNING: imports outside of constants will not trigger a rebuild
from openpilot.selfdrive.modeld.constants import index_function
from openpilot.selfdrive.modeld.constants import index_function, ModelConstants
from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU
if __name__ == '__main__': # generating code
from acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver
else:
from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython
from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.acados_ocp_solver_pyx import AcadosOcpSolverCython
from casadi import SX, vertcat
@@ -56,6 +56,12 @@ COMFORT_BRAKE = 2.5
STOP_DISTANCE = 6.0
MIN_X_LEAD_FACTOR = 0.5
# model/radar fusion
RADAR_RESIDUAL_DECAY_T = 2.0
RADAR_RESIDUAL_W = np.exp(-T_IDXS / RADAR_RESIDUAL_DECAY_T)
CLIP_MODEL_LEAD_ACCEL = 2.0
LEAD_FALLBACK_RANGE = [2.5, 3.5]
def get_jerk_factor(personality=log.LongitudinalPersonality.standard):
if personality==log.LongitudinalPersonality.relaxed:
return 1.0
@@ -75,8 +81,8 @@ def get_T_FOLLOW(personality=log.LongitudinalPersonality.standard):
else:
raise NotImplementedError("Longitudinal personality not supported")
def get_stopped_equivalence_factor(v_lead):
return (v_lead**2) / (2 * COMFORT_BRAKE)
def get_stopped_equivalence_factor(v_lead, brake=COMFORT_BRAKE):
return (v_lead**2) / (2 * brake)
def get_safe_obstacle_distance(v_ego, t_follow):
return (v_ego**2) / (2 * COMFORT_BRAKE) + t_follow * v_ego + STOP_DISTANCE
@@ -197,7 +203,7 @@ def gen_long_ocp():
# More iterations take too much time and less lead to inaccurate convergence in
# some situations. Ideally we would run just 1 iteration to ensure fixed runtime.
ocp.solver_options.qp_solver_iter_max = 10
ocp.solver_options.qp_solver_iter_max = 20
ocp.solver_options.qp_tol = 1e-3
# set prediction horizon
@@ -274,26 +280,26 @@ class LongitudinalMpc:
self.solver.set(i, 'x', self.x0)
@staticmethod
def extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau):
a_lead_traj = a_lead * np.exp(-a_lead_tau * (T_IDXS**2)/2.)
def integrate_lead(x_lead, v_lead, a_lead_traj):
v_lead_traj = np.clip(v_lead + np.cumsum(T_DIFFS * a_lead_traj), 0.0, 1e8)
x_lead_traj = x_lead + np.cumsum(T_DIFFS * v_lead_traj)
lead_xv = np.column_stack((x_lead_traj, v_lead_traj))
return lead_xv
return np.column_stack((x_lead_traj, v_lead_traj))
def process_lead(self, lead):
def process_lead(self, model_lead, radar_lead):
v_ego = self.x0[1]
if lead is not None and lead.present:
x_lead = lead.dRel
v_lead = lead.vLead
a_lead = lead.aLeadK
a_lead_tau = lead.aLeadTau
if radar_lead is not None and radar_lead.present:
x_lead = radar_lead.dRel
v_lead = radar_lead.vLead
a_lead = radar_lead.aLeadK
a_lead_tau = radar_lead.aLeadTau
model_prob = radar_lead.modelProb
else:
# Fake a fast lead car, so mpc can keep running in the same mode
x_lead = 50.0
v_lead = v_ego + 10.0
a_lead = 0.0
a_lead_tau = _LEAD_ACCEL_TAU
model_prob = 0.0
# MPC will not converge if immediate crash is expected
# Clip lead distance to what is still possible to brake for
@@ -301,14 +307,34 @@ class LongitudinalMpc:
x_lead = np.clip(x_lead, min_x_lead, 1e8)
v_lead = np.clip(v_lead, 0.0, 1e8)
a_lead = np.clip(a_lead, -10., 5.)
lead_xv = self.extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau)
return lead_xv
def update(self, radarstate, personality=log.LongitudinalPersonality.standard):
# radar only lead traj estimate
a_radar = a_lead * np.exp(-a_lead_tau * (T_IDXS**2) / 2.)
radar_xv = self.integrate_lead(x_lead, v_lead, a_radar)
if model_lead is not None and model_prob > 0.5:
a_model = np.interp(T_IDXS, ModelConstants.LEAD_T_IDXS, np.clip(model_lead.a, -10., CLIP_MODEL_LEAD_ACCEL))
a_lead_traj = np.clip(a_model + (a_lead - a_model[0]) * RADAR_RESIDUAL_W, -10., np.maximum(a_radar, CLIP_MODEL_LEAD_ACCEL))
lead_xv = self.integrate_lead(x_lead, v_lead, a_lead_traj)
# smoothly fall back to the more pessimistic radar trajectory when radar requires hard braking
x_obs_radar = radar_xv[:, 0] + get_stopped_equivalence_factor(radar_xv[:, 1], brake=-ACCEL_MIN)
a_req = v_ego**2 / (2. * max(np.min(x_obs_radar) - STOP_DISTANCE, 0.5))
w = np.interp(a_req, LEAD_FALLBACK_RANGE, [0.0, 1.0])
if w > 0.0:
x_obs_fused_comfort = lead_xv[:, 0] + get_stopped_equivalence_factor(lead_xv[:, 1])
x_obs_radar_comfort = radar_xv[:, 0] + get_stopped_equivalence_factor(radar_xv[:, 1])
pessimistic = np.where((x_obs_radar_comfort < x_obs_fused_comfort)[:, None], radar_xv, lead_xv)
lead_xv = (1.0 - w) * lead_xv + w * pessimistic
return lead_xv
return radar_xv
def update(self, modelV2, radarstate, personality=log.LongitudinalPersonality.standard):
t_follow = get_T_FOLLOW(personality)
lead_xv_0 = self.process_lead(radarstate.leadOne)
lead_xv_1 = self.process_lead(radarstate.leadTwo)
lead_xv_0 = self.process_lead(modelV2.leadsV3[0] if modelV2 is not None else None, radarstate.leadOne)
lead_xv_1 = self.process_lead(modelV2.leadsV3[1] if modelV2 is not None else None, radarstate.leadTwo)
# To estimate a safe distance from a moving lead, we calculate how much stopping
# distance that lead needs as a minimum. We can add that to the current distance
@@ -90,9 +90,10 @@ class LongitudinalPlanner(LongitudinalPlannerSP):
self.mpc.set_weights(prev_accel_constraint, personality=personality)
if self.CP.openpilotLongitudinalControl:
self.mpc.set_cur_state(self.v_desired_filter.x, self.output_a_target)
self.mpc.update(sm['modelV2'], sm['radarState'], personality=personality)
else:
self.mpc.set_cur_state(v_ego, sm['carState'].aEgo)
self.mpc.update(sm['radarState'], personality=personality)
self.mpc.update(None, sm['radarState'], personality=personality)
self.v_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.v_solution)
self.a_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.a_solution)
@@ -35,6 +35,9 @@ def run_following_distance_simulation(v_lead, t_end=100.0, personality=0):
log.LongitudinalPersonality.aggressive],
[0,10,35])) # speed
class TestFollowingDistance(OpenpilotTestCase):
personality: int
speed: int
def test_following_distance(self):
v_lead = float(self.speed)
simulation_steady_state = run_following_distance_simulation(v_lead, personality=self.personality)
+11 -6
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, cast
import base64
import ctypes
import gc
@@ -11,10 +12,12 @@ os.environ.setdefault('AM_PERF_LEVEL', 'high')
from tinygrad.device import Buffer, Device
from tinygrad.dtype import DType, dtypes
from tinygrad.engine.jit import CapturedJit
from tinygrad.engine.realize import compile_linear, lower_and_compile
from tinygrad.codegen.compile import lower_and_compile
from tinygrad.tensor import Tensor
from tinygrad.helpers import round_up
from tinygrad.uop.ops import UOp
if TYPE_CHECKING:
from tinygrad.runtime.ops_amd import AMDDevice
import math
import pickle
import threading
@@ -93,7 +96,7 @@ class ChestnutGpuState:
@cached_property
def power_limit(self) -> int:
smu = Device["AMD"].iface.dev_impl.smu
smu = cast("AMDDevice", Device["AMD"]).iface.dev_impl.smu
return smu._send_msg(smu.smu_mod.PPSMC_MSG_GetPptLimit, 0, read_back_arg=True, timeout=100)
def send(self) -> None:
@@ -102,7 +105,7 @@ class ChestnutGpuState:
self.sends += 1
if self.big and "AMD" in Device._opened_devices and self.sends % 100 == 1:
try:
smu = Device["AMD"].iface.dev_impl.smu
smu = cast("AMDDevice", Device["AMD"]).iface.dev_impl.smu
metrics_t = smu.smu_mod.SmuMetricsExternal_t
smu._send_msg(smu.smu_mod.PPSMC_MSG_TransferTableSmu2Dram, smu.smu_mod.TABLE_SMU_METRICS, timeout=100)
metrics_buf = bytearray(smu.adev.vram.view(smu.driver_table_paddr, ctypes.sizeof(metrics_t))[:])
@@ -144,7 +147,8 @@ def input_view(buffer: Buffer, shape: tuple[int, ...], dtype: DType, offset: int
def compile_copy(tensor: Tensor) -> Callable[[], Tensor]:
jit = CapturedJit(tensor, compile_linear(tensor.schedule_linear()), [], [])
fn, externs = Tensor.export(tensor)
jit = CapturedJit(tensor, Tensor.compile(fn), externs, [], [], {})
return lambda: jit([], {})
@@ -174,7 +178,7 @@ class ModelState(ModelStateBase):
self.outputs = {name: Tensor(np.zeros(shape, dtype=dtype), device=device).realize() for name, (shape, dtype, device) in jits['output_specs'].items()}
for name, next_name in self.state_pairs.items():
state = self.input_queues[name]
self.outputs[next_name] = input_view(state._buffer(), state.shape, state.dtype, 0)
self.outputs[next_name] = input_view(state._buffer(), self.input_shapes[name][0], state.dtype, 0)
self.copy_outputs = compile_copy(self.outputs['outputs'].to('CPU'))
self.parser = Parser()
@@ -219,7 +223,7 @@ class ModelState(ModelStateBase):
self.copy_inputs()
self.input_queues['new_img'] = self.run_warp(**self.warp_inputs)
self.run_model(output_buffers=self.outputs, **self.input_queues)
if self.chestnut and (err := Device[self.outputs['outputs'].device].error_state.host.view(fmt='q')[0]):
if self.chestnut and (err := Device[cast(str, self.outputs['outputs'].device)].error_state.host.view(fmt='q')[0]):
raise RuntimeError(f"chestnut failed with {err}")
if after_enqueue is not None:
after_enqueue()
@@ -446,6 +450,7 @@ def main(demo=False):
params.put_bool("ChestnutActive", False)
assert small_model is not None
model = small_model
assert model is not None
if chestnut_state is not None:
chestnut_state.big = False
run_count = 0
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e62c2ae933bd6d3e7a4b3c548a8b6b90ebf9aee7420bb9cbafbd2b2e1e9379bc
size 764592225
oid sha256:8891809d3904cdce68359235bfeea8ac853fae4758e20d08a75ccb02c035ab8d
size 764657206
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1c80960cddf8a463b4a0d9941a684be3acb0938da620f518844419c269173e97
size 462613
oid sha256:03e239d1ab9775c3e329a181199b0f9e5b0e905c0e891c67e86722827308c879
size 463324
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:657dbf7d92b7d8e554dc06fc18038c93318ab373c85af151b184c9ee4d53e1cf
size 462615
oid sha256:1e8b4e7be07b2b3040a33c0abdd9798b55514ee9bae2069c9babdec506cdd360
size 463325
+1 -1
View File
@@ -102,7 +102,7 @@ class RouteEngine:
lang = lang.replace('main_', '')
token = self.mapbox_token
if token is None:
if self.api is not None:
token = self.api.get_token()
params = {
@@ -98,8 +98,16 @@ def route_engine(sm, pm, values):
return RouteEngine(sm, pm, params=params)
class RangeServer(ThreadingHTTPServer):
archive: bytes
etag: str
ignore_range: bool
requests: list[dict[str, str]]
class RangeHandler(BaseHTTPRequestHandler):
def do_GET(self):
assert isinstance(self.server, RangeServer)
self.server.requests.append(dict(self.headers))
if self.headers.get('If-Match', self.server.etag) != self.server.etag:
self.send_error(412)
@@ -108,7 +116,9 @@ class RangeHandler(BaseHTTPRequestHandler):
self.send_response(200)
self.end_headers()
return
offset, end = map(int, re.fullmatch(r'bytes=(\d+)-(\d+)', self.headers['Range']).groups())
m = re.fullmatch(r'bytes=(\d+)-(\d+)', self.headers['Range'])
assert m is not None
offset, end = map(int, m.groups())
data = self.server.archive[offset:end + 1]
self.send_response(206)
self.send_header('Content-Range', f'bytes {offset}-{end}/{len(self.server.archive)}')
@@ -128,7 +138,7 @@ class TileServerCase(unittest.TestCase):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.cache = Path(self.directory.name) / 'navigation' / 'tiles'
self.server = ThreadingHTTPServer(('127.0.0.1', 0), RangeHandler)
self.server = RangeServer(('127.0.0.1', 0), RangeHandler)
self.server.archive = make_archive(leaf=True)
self.server.etag = '"test-version"'
self.server.ignore_range = False
+1 -1
View File
@@ -132,7 +132,7 @@ def main() -> None:
process = subprocess.Popen(["./pandad"], cwd=os.path.join(BASEDIR, "openpilot/selfdrive/pandad"))
process.wait()
# TODO: wrap all panda exceptions in a base panda exception
except (usb1.USBErrorNoDevice, usb1.USBErrorPipe):
except usb1.USBError:
# a panda was disconnected while setting everything up. let's try again
cloudlog.exception("Panda USB exception while setting up")
except PandaProtocolMismatch:
+4 -3
View File
@@ -83,12 +83,13 @@ def processes_context(processes, init_time=0, ignore_stopped=None):
if n < len(processes) - 1:
time.sleep(init_time)
assert all(managed_processes[name].proc.exitcode is None for name in processes)
procs = [managed_processes[name] for name in processes]
assert all(p.proc is not None and p.proc.exitcode is None for p in procs)
try:
yield [managed_processes[name] for name in processes]
yield procs
# assert processes are still started
assert all(managed_processes[name].proc.exitcode is None for name in processes if name not in ignore_stopped)
assert all(p.proc is not None and p.proc.exitcode is None for p in procs if p.name not in ignore_stopped)
finally:
for p in processes:
managed_processes[p].stop()
@@ -8,7 +8,10 @@ from openpilot.common.constants import CV
from openpilot.common.realtime import DT_MDL
from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState
from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner
from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU
from openpilot.selfdrive.controls.radard import KalmanParams, RADAR_TO_CAMERA, Track
from openpilot.selfdrive.modeld.constants import ModelConstants
LEAD_STEPS = (np.asarray(ModelConstants.LEAD_T_IDXS) / DT_MDL).astype(int)
class Maneuver:
@@ -32,8 +35,10 @@ class Maneuver:
# perception
self.lead_relevancy = kwargs.get("lead_relevancy", False)
self.only_lead2 = kwargs.get("only_lead2", False)
only_radar = kwargs.get("only_radar", False)
self.only_radar = kwargs.get("only_radar", False)
prob_lead_values = kwargs.get("prob_lead_values", [1.0] * len(breakpoints))
model_v_lead_values = kwargs.get("model_speed_lead_values", None)
model_breakpoints = kwargs.get("model_breakpoints", breakpoints)
# ego state, to be simulated
n_steps = round(duration / DT_MDL)
@@ -44,29 +49,50 @@ class Maneuver:
self.v_ego[0] = initial_v_ego
# lead state, known in advance
self.v_lead = np.interp(self.t, breakpoints, v_lead_values)
# extend so we can populate fake model predicted traj
lead_t = np.arange(n_steps + LEAD_STEPS[-1] + 1) * DT_MDL
self.v_lead = np.interp(lead_t, breakpoints, v_lead_values)
self.a_lead = np.diff(self.v_lead, prepend=0.0) / DT_MDL
self.x_lead = np.cumsum(np.r_[initial_x_lead, self.v_lead[:-1] * DT_MDL])
self.prob_lead = np.interp(self.t, breakpoints, prob_lead_values)
self.lead_present = np.logical_and(self.lead_relevancy, np.logical_or(only_radar, self.prob_lead > 0.5))
if model_v_lead_values is not None:
self.model_v_lead = np.interp(lead_t, model_breakpoints, model_v_lead_values)
self.model_a_lead = np.diff(self.model_v_lead, prepend=self.model_v_lead[0]) / DT_MDL
self.model_x_lead = np.cumsum(np.r_[initial_x_lead, self.model_v_lead[:-1] * DT_MDL])
else:
self.model_v_lead = self.v_lead
self.model_a_lead = self.a_lead
self.model_x_lead = self.x_lead
self.prob_lead = np.zeros_like(self.t) if self.only_radar else np.interp(self.t, breakpoints, prob_lead_values)
self.lead_present = np.logical_and(self.lead_relevancy, np.logical_or(self.only_radar, self.prob_lead > 0.5))
self.v_cruise = np.interp(self.t, breakpoints, v_cruise_values)
def _make_messages(self, i):
v_ego = float(self.v_ego[i])
v_lead = float(self.v_lead[i])
prob = float(self.prob_lead[i]) if self.lead_relevancy else 0.0
lead = log.RadarState.LeadData(
dRel=max(0., float(self.x_lead[i] - self.x_ego[i])) if self.lead_relevancy else 200.,
vRel=v_lead - v_ego if self.lead_relevancy else 0.,
vLead=v_lead, vLeadK=v_lead, aLeadK=float(self.a_lead[i]), aLeadTau=_LEAD_ACCEL_TAU,
present=bool(self.lead_present[i]), modelProb=prob, radar=True,
)
d_rel = max(0., float(self.x_lead[i] - self.x_ego[i])) if self.lead_relevancy else 200.
v_rel = v_lead - v_ego if self.lead_relevancy else 0.
self.track.update(d_rel, 0.0, v_rel, v_lead)
lead = log.RadarState.LeadData(**(self.track.get_RadarState(prob) | {'present': bool(self.lead_present[i])}))
radar = log.RadarState(leadTwo=lead)
if not self.only_lead2:
radar.leadOne = lead
# Model requests more acceleration so the lead policy must handle slowdowns.
model = log.ModelDataV2()
future = i + LEAD_STEPS
camera_x = self.x_ego[i] - RADAR_TO_CAMERA
future_x = (self.x_lead[i] + (self.model_x_lead[future] - self.model_x_lead[i]) - camera_x).tolist()
future_v = self.model_v_lead[future].tolist()
future_a = self.model_a_lead[future].tolist()
for j, model_lead in enumerate(model.init('leadsV3', len(ModelConstants.LEAD_T_OFFSETS))):
model_lead.prob = 0.0 if self.only_lead2 and j != 1 else prob
model_lead.probTime = ModelConstants.LEAD_T_OFFSETS[j]
model_lead.t = ModelConstants.LEAD_T_IDXS
model_lead.x = future_x
model_lead.v = future_v
model_lead.a = future_a
# Model requests more acceleration so the lead policy must handle slowdowns.
model.action.desiredAcceleration = float(self.a_ego[i] + 0.5)
return {
'radarState': radar,
@@ -97,10 +123,12 @@ class Maneuver:
CP = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC)
CP_SP = CarInterface.get_non_essential_params_sp(CP, CAR.HONDA_CIVIC)
self.planner = LongitudinalPlanner(CP, CP_SP, init_v=self.v_ego[0])
self.track = Track(0, float(self.v_lead[0]), KalmanParams(DT_MDL))
for i in range(len(self.t) - 1):
self._step(i)
d_rel = self.x_lead - self.x_ego
x_lead, v_lead = self.x_lead[:len(self.t)], self.v_lead[:len(self.t)]
d_rel = x_lead - self.x_ego
valid = True
if np.any(d_rel[self.lead_present] < 0.4):
@@ -109,7 +137,7 @@ class Maneuver:
if self.ensure_start and self.lead_relevancy:
not_starting_since = None
not_starting = (self.v_lead > self.v_ego) & (self.a_ego < 1e-3)
not_starting = (v_lead > self.v_ego) & (self.a_ego < 1e-3)
for now, waiting in zip(self.t, not_starting, strict=True):
if not waiting:
not_starting_since = None
@@ -125,5 +153,5 @@ class Maneuver:
valid = False
print('maneuver end', valid)
logs = np.column_stack((self.t, self.x_ego, self.x_lead, self.v_ego, self.v_lead, self.a_ego, d_rel))
logs = np.column_stack((self.t, self.x_ego, x_lead, self.v_ego, v_lead, self.a_ego, d_rel))
return valid, logs
@@ -2,6 +2,7 @@ from openpilot.common.test import OpenpilotTestCase
from openpilot.common.parameterized import parameterized
from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import STOP_DISTANCE
from openpilot.selfdrive.selfdrived.selfdrived import LONGITUDINAL_PERSONALITY_MAP
from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver
@@ -141,9 +142,134 @@ def create_maneuvers(kwargs):
return maneuvers
def create_approach_stopped_adv_maneuvers(kwargs):
return [
Maneuver(
f"approaching stopped lead that doesn't go ({v0:g}m/s from {d0:g}m), "
+ ("radar only" if model_a is None else f"model wrongly predicts +{model_a:g}m/s^2"),
duration=duration,
initial_speed=v0,
lead_relevancy=True,
initial_distance_lead=d0,
speed_lead_values=[0., 0.],
breakpoints=[0., duration],
model_speed_lead_values=None if model_a is None else [0., model_a * (duration + 15.)],
model_breakpoints=[0., duration + 15.],
only_radar=model_a is None,
**kwargs,
)
for v0, d0, duration in ((30., 200., 25.), (15., 70., 20.), (8., 25., 18.))
for model_a in (None, 1., 2., 4.)
]
def create_stopped_adv_maneuvers(kwargs):
return [
Maneuver(
f"stopped behind a lead that doesn't go ({d0:g}m), "
+ ("radar only" if model_a is None else f"model wrongly predicts +{model_a:g}m/s^2"),
duration=20.,
initial_speed=0.,
lead_relevancy=True,
initial_distance_lead=d0,
speed_lead_values=[0., 0.],
breakpoints=[0., 20.],
model_speed_lead_values=None if model_a is None else [0., model_a * 35.],
model_breakpoints=[0., 35.],
only_radar=model_a is None,
**kwargs,
)
for d0 in (STOP_DISTANCE, 4.)
for model_a in (None, 1., 2., 4.)
]
def create_hard_braking_adv_maneuvers(kwargs):
return [
Maneuver(
f"steady following ({v0:g}m/s) then lead brakes hard (-{decel:g}m/s^2), "
+ ("radar only" if model_a is None else f"model wrongly predicts {model_a:+g}m/s^2"),
duration=15. + v0 / decel + 10.,
initial_speed=v0,
cruise_values=[v0, v0, v0],
lead_relevancy=True,
initial_distance_lead=d0,
speed_lead_values=[v0, v0, 0.],
breakpoints=[0., 15., 15. + v0 / decel],
model_speed_lead_values=None if model_a is None else [v0, v0, v0 + model_a * (v0 / decel + 25.)],
model_breakpoints=[0., 15., 15. + v0 / decel + 25.],
only_radar=model_a is None,
**kwargs,
)
for v0, d0 in ((10., 20.), (20., 35.), (30., 50.))
for decel in (2., 3., 3.5)
for model_a in (None, 0., 2.)
]
def create_approach_slower_adv_maneuvers(kwargs):
return [
Maneuver(
f"approaching slower lead ({v0:g}m/s to {v_lead:g}m/s from {d0:g}m), "
+ ("radar only" if model_a is None else f"model wrongly predicts +{model_a:g}m/s^2"),
duration=40.,
initial_speed=v0,
cruise_values=[v0, v0],
lead_relevancy=True,
initial_distance_lead=d0,
speed_lead_values=[v_lead, v_lead],
breakpoints=[0., 40.],
model_speed_lead_values=None if model_a is None else [v_lead, v_lead + model_a * 55.],
model_breakpoints=[0., 55.],
only_radar=model_a is None,
**kwargs,
)
for v0, v_lead, d0 in ((30., 15., 100.), (25., 10., 80.), (20., 10., 60.))
for model_a in (None, 1., 2., 4.)
]
def create_cutin_adv_maneuvers(kwargs):
return [
Maneuver(
f"slower cut-in ({v0:g}m/s to {v_lead:g}m/s at {d0:g}m), "
+ ("radar only" if model_a is None else f"model wrongly predicts +{model_a:g}m/s^2"),
duration=40.,
initial_speed=v0,
cruise_values=[v0, v0],
lead_relevancy=True,
initial_distance_lead=d0,
speed_lead_values=[v_lead, v_lead],
breakpoints=[0., 40.],
model_speed_lead_values=None if model_a is None else [v_lead, v_lead + model_a * 55.],
model_breakpoints=[0., 55.],
only_radar=model_a is None,
**kwargs,
)
for v0, v_lead, d0 in ((10., 5., 12.), (20., 15., 21.), (30., 25., 30.))
for model_a in (None, 1., 2., 4.)
]
def create_adv_maneuvers(kwargs):
return (
create_approach_stopped_adv_maneuvers(kwargs)
+ create_stopped_adv_maneuvers(kwargs)
+ create_hard_braking_adv_maneuvers(kwargs)
+ create_approach_slower_adv_maneuvers(kwargs)
+ create_cutin_adv_maneuvers(kwargs)
)
class TestLongitudinalControl(OpenpilotTestCase):
@parameterized.expand([m for force_decel in (True, False) for m in create_maneuvers({"force_decel": force_decel})],
ids=lambda m: f"{m.title}_force_decel_{m.force_decel}")
def test_maneuver(self, maneuver):
valid, _ = maneuver.evaluate()
assert valid
@parameterized.expand([m for p in LONGITUDINAL_PERSONALITY_MAP for m in create_adv_maneuvers({"personality": p})],
ids=lambda m: f"{m.title}_personality_{LONGITUDINAL_PERSONALITY_MAP[m.personality]}")
def test_adv_maneuver(self, maneuver):
valid, _ = maneuver.evaluate()
assert valid
@@ -10,7 +10,7 @@ import argparse
from openpilot.cereal import messaging, log
from opendbc.car.structs import car
from opendbc.car.fingerprints import MIGRATION
from opendbc.car.toyota.values import EPS_SCALE, ToyotaSafetyFlags
from opendbc.car.toyota.values import CAR as TOYOTA, EPS_SCALE, ToyotaSafetyFlags
from opendbc.car.ford.values import CAR as FORD, FordFlags, FordSafetyFlags
from opendbc.car.hyundai.values import HyundaiSafetyFlags
from opendbc.car.gm.values import GMSafetyFlags
@@ -102,8 +102,7 @@ def migration(inputs: list[str], product: str|None=None):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.inputs = inputs
wrapper.product = product
vars(wrapper).update(inputs=inputs, product=product)
return wrapper
return decorator
@@ -310,8 +309,8 @@ def migrate_carOutput(msgs):
def migrate_pandaStates(msgs):
# TODO: safety param migration should be handled automatically
safety_param_migration = {
"TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | ToyotaSafetyFlags.STOCK_LONGITUDINAL,
"TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | ToyotaSafetyFlags.ALT_BRAKE,
"TOYOTA_PRIUS": EPS_SCALE[TOYOTA.TOYOTA_PRIUS] | ToyotaSafetyFlags.STOCK_LONGITUDINAL,
"TOYOTA_RAV4": EPS_SCALE[TOYOTA.TOYOTA_RAV4] | ToyotaSafetyFlags.ALT_BRAKE,
"KIA_EV6": HyundaiSafetyFlags.EV_GAS | HyundaiSafetyFlags.CANFD_LKA_STEER_MSG,
"CHEVROLET_VOLT": GMSafetyFlags.EV,
"CHEVROLET_BOLT_EUV": GMSafetyFlags.EV | GMSafetyFlags.HW_CAM,
@@ -324,7 +323,7 @@ def migrate_pandaStates(msgs):
assert CP is not None, "carParams message not found"
fingerprint = MIGRATION.get(CP.carFingerprint, CP.carFingerprint)
if fingerprint in safety_param_migration:
safety_param = safety_param_migration[fingerprint].value
safety_param = int(safety_param_migration[fingerprint])
elif len(CP.safetyConfigs):
safety_param = CP.safetyConfigs[0].safetyParam
if CP.safetyConfigs[0].deprecated.safetyParam != 0:
@@ -19,6 +19,7 @@ from openpilot.selfdrive.test.process_replay.process_replay import get_process_c
from openpilot.tools.lib.framereader import FrameReader
from openpilot.tools.lib.logreader import LogReader, save_log
from openpilot.tools.lib.github_utils import GithubUtils
from openpilot.tools.lib.url_file import URLFile
TEST_ROUTE = "98395b7c5b27882e|0000002b--2686b5a2d0"
SEGMENT = 1
@@ -248,7 +249,8 @@ if __name__ == "__main__":
if not update:
log_fn = get_log_fn(TEST_ROUTE)
try:
all_logs = list(LogReader(GITHUB.get_file_url(MODEL_REPLAY_BUCKET, log_fn)))
# master's ref is overwritten at the same URL, so it can't come from the download cache
all_logs = list(LogReader.from_bytes(URLFile(GITHUB.get_file_url(MODEL_REPLAY_BUCKET, log_fn), cache=False).read()))
cmp_log = []
model_start_index = next(i for i, m in enumerate(all_logs) if m.which() in ("modelV2", "drivingModelData", "cameraOdometry"))
cmp_log += all_logs[model_start_index+START_FRAME*3:model_start_index + END_FRAME*3]
@@ -26,6 +26,7 @@ from openpilot.common.timeout import Timeout
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
from openpilot.system.manager.process_config import managed_processes
from openpilot.selfdrive.car.card import convert_to_capnp
from openpilot.system.manager.process import NativeProcess, PythonProcess
from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state, available_streams
from openpilot.selfdrive.test.process_replay.capture import ProcessOutputCapture
from openpilot.tools.lib.logreader import LogIterable
@@ -166,6 +167,7 @@ class ProcessContainer:
return self.cfg.subs
def _clean_env(self):
assert self.environ_config is not None
for k in self.environ_config.keys():
if k in os.environ:
del os.environ[k]
@@ -215,7 +217,8 @@ class ProcessContainer:
def _start_process(self):
if self.capture is not None:
self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher) # ty: ignore[invalid-assignment] # intentional wrapper
assert isinstance(self.process, NativeProcess | PythonProcess)
self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher)
self.process.start()
def start(
@@ -254,6 +257,7 @@ class ProcessContainer:
with self.prefix:
self.process.signal(signal.SIGKILL)
self.process.stop()
assert self.rc is not None
self.rc.close_context()
self.prefix.clean_dirs()
self._clean_env()
@@ -1,33 +0,0 @@
import numpy as np
from openpilot.tools.lib.logreader import LogIterable
def check_jerk_rms(inputs: LogIterable, outputs: LogIterable) -> None:
msgs = [m for m in inputs if m.which() == 'carControl']
msgs += [m for m in outputs if m.which() == 'longitudinalPlan']
active = False
prev = None
jerks = []
for m in sorted(msgs, key=lambda m: m.logMonoTime):
if m.which() == 'carControl':
active = m.carControl.longActive
if not active:
prev = None
continue
plan = m.longitudinalPlan
if not (m.valid and active and plan.longitudinalPlanSource == 'cruise' and not plan.hasLead):
prev = None
continue
if prev is not None:
jerks.append((plan.aTarget - prev.aTarget) / ((plan.modelMonoTime - prev.modelMonoTime) / 1e9))
prev = plan
if jerks:
jerk_rms = np.sqrt(np.mean(np.square(jerks)))
assert jerk_rms < 0.15, f'{jerk_rms=:.5f}'
PROCESS_CHECKS = {
'plannerd': [check_jerk_rms],
}
@@ -14,7 +14,6 @@ from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, f
from openpilot.selfdrive.test.process_replay.diff_report import diff_process, diff_report
from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, PROC_REPLAY_DIR, FAKEDATA, replay_process, \
check_most_messages_valid
from openpilot.selfdrive.test.process_replay.sanity_checks import PROCESS_CHECKS
from openpilot.tools.lib.filereader import FileReader
from openpilot.tools.lib.logreader import LogReader, save_log
from openpilot.tools.lib.url_file import URLFile
@@ -123,8 +122,6 @@ def test_process(cfg, lr, segment, ref_log_msgs, new_log_path, ignore_fields=Non
return f"Expected messages: {expected_msgs}, but got: {seen_msgs}", log_msgs
try:
for check in PROCESS_CHECKS.get(cfg.proc_name, []):
check(lr, log_msgs)
return compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance), log_msgs
except Exception as e:
return str(e), log_msgs
+4 -3
View File
@@ -21,7 +21,7 @@ from openpilot.cereal.services import SERVICE_LIST
from openpilot.common.basedir import BASEDIR
from openpilot.common.timeout import Timeout
from openpilot.common.params import Params
from openpilot.selfdrive.selfdrived.events import EVENTS, ET
from openpilot.selfdrive.selfdrived.events import EVENTS, ET, Alert
from openpilot.selfdrive.test.helpers import set_params_enabled, release_only, processes_context, log_collector
from openpilot.common.hardware import HARDWARE
from openpilot.common.hardware.hw import Paths
@@ -453,8 +453,9 @@ class TestOnroad(OpenpilotTestCase):
@unittest.skipIf(HARDWARE.get_device_type() == "mici", "mici has no startup alert")
def test_startup(self):
startup_alert = self.ts['selfdriveState']['alertText1'][0]
expected = EVENTS[log.OnroadEvent.EventName.startup][ET.PERMANENT].alert_text_1
assert startup_alert == expected, "wrong startup alert"
expected = EVENTS[log.OnroadEvent.EventName.startup][ET.PERMANENT]
assert isinstance(expected, Alert)
assert startup_alert == expected.alert_text_1, "wrong startup alert"
def test_engagable(self):
no_entries = Counter()
+1 -1
View File
@@ -40,7 +40,7 @@ PROCS = [
Proc(['camerad'], 1.0 if MICI else 1.65, atol=0.4, msgs=['narrowRoadCameraState', 'wideRoadCameraState', 'cabinCameraState']),
Proc(['modeld'], 1.5 if MICI else 1.65, atol=0.2, msgs=['modelV2']),
Proc(['dmonitoringmodeld'], 0.65, atol=0.35, msgs=['driverStateV2']),
Proc(['encoderd'], 0.23, msgs=['narrowRoadEncodeData', 'wideRoadEncodeData']),
Proc(['encoderd'], 0.15 if MICI else 0.23, atol=0.07 if MICI else 0.12, msgs=['narrowRoadEncodeData', 'wideRoadEncodeData']),
]
+3 -19
View File
@@ -1,9 +1,6 @@
#!/usr/bin/env python3
import os
import re
import subprocess
import sys
from collections.abc import Iterable
from tqdm import tqdm
from opendbc.car.tests.routes import routes as test_car_models_routes
@@ -18,32 +15,19 @@ SOURCES: list[AzureContainer] = [
DEST = OpenpilotCIContainer
def upload_route(path: str, exclude_patterns: Iterable[str] | None = None) -> None:
if exclude_patterns is None:
exclude_patterns = [r'dcamera\.hevc']
r, n = path.rsplit("--", 1)
r = '/'.join(r.split('/')[-2:]) # strip out anything extra in the path
destpath = f"{r}/{n}"
for file in os.listdir(path):
if any(re.search(pattern, file) for pattern in exclude_patterns):
continue
DEST.upload_file(os.path.join(path, file), f"{destpath}/{file}")
def sync_to_ci_public(route: str) -> bool:
dest_container, dest_key = DEST.get_client_and_key()
key_prefix = route.replace('|', '/')
dongle_id = key_prefix.split('/')[0]
if next(dest_container.list_blob_names(name_starts_with=key_prefix), None) is not None:
if DEST.has_prefix(key_prefix):
return True
dest_key = DEST.sas()
print(f"Uploading {route}")
for source_container in SOURCES:
# assumes az login has been run
print(f"Trying {source_container.ACCOUNT}/{source_container.CONTAINER}")
_, source_key = source_container.get_client_and_key()
source_key = source_container.sas()
cmd = [
"azcopy",
"copy",
+5 -4
View File
@@ -35,9 +35,10 @@ class MainLayout(Widget):
# Initialize layouts
self._home_layout = HomeLayout()
self._home_body_layout = BodyLayout()
self._settings_layout = SettingsLayout()
self._layouts: dict[MainState, Widget] = {
MainState.HOME: self._home_layout,
MainState.SETTINGS: SettingsLayout(),
MainState.SETTINGS: self._settings_layout,
MainState.ONROAD: AugmentedRoadView(),
}
@@ -62,8 +63,8 @@ class MainLayout(Widget):
self._sidebar.set_callbacks(on_settings=self._on_settings_clicked,
on_flag=self._on_bookmark_clicked,
open_settings=lambda: self.open_settings(PanelType.TOGGLES))
self._layouts[MainState.HOME]._setup_widget.set_open_settings_callback(lambda: self.open_settings(PanelType.FIREHOSE))
self._layouts[MainState.SETTINGS].set_callbacks(on_close=self._set_mode_for_state)
self._home_layout._setup_widget.set_open_settings_callback(lambda: self.open_settings(PanelType.FIREHOSE))
self._settings_layout.set_callbacks(on_close=self._set_mode_for_state)
for layout in (self._layouts[MainState.ONROAD], self._home_body_layout):
layout.set_click_callback(self._on_onroad_clicked)
@@ -106,7 +107,7 @@ class MainLayout(Widget):
self._layouts[self._current_mode].show_event()
def open_settings(self, panel_type: PanelType):
self._layouts[MainState.SETTINGS].set_current_panel(panel_type)
self._settings_layout.set_current_panel(panel_type)
self._set_current_layout(MainState.SETTINGS)
self._sidebar.set_visible(False)
@@ -55,7 +55,7 @@ class SoftwareLayout(Widget):
def __init__(self):
super().__init__()
self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off."))
self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off."), action_item=None)
self._version_item = text_item(lambda: tr("Current Version"), ui_state.params.get("UpdaterCurrentDescription") or "")
self._download_btn = button_item(lambda: tr("Download"), lambda: tr("CHECK"), callback=self._on_download_update)
@@ -11,7 +11,7 @@ from openpilot.selfdrive.ui.layouts.settings.initial_cruise_speed import Initial
if gui_app.sunnypilot_ui():
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp as toggle_item
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp as multiple_button_item
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.initial_cruise_speed import initial_cruise_speed_item_sp as ListItem
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.initial_cruise_speed import InitialCruiseSpeedItemSP as ListItem
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.initial_cruise_speed import InitialCruiseSpeedControlSP as InitialCruiseSpeedControl
PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants
@@ -100,7 +100,7 @@ class TogglesLayout(Widget):
icon="speed_limit.png"
)
self._toggles = {}
self._toggles: dict[str, ListItem] = {}
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. " +
+1 -1
View File
@@ -175,7 +175,7 @@ class Sidebar(Widget, SidebarSP):
tint = Colors.BUTTON_PRESSED if (ui_state.started and flag_pressed) else Colors.BUTTON_NORMAL
if icon_opacity < 1.0:
tint = rl.Color(tint[0], tint[1], tint[2], int(255 * icon_opacity))
tint = rl.Color(tint.r, tint.g, tint.b, int(255 * icon_opacity))
rl.draw_texture_ex(button_img, button_pos, 0.0, 1.0, tint)
# Microphone button
@@ -127,6 +127,8 @@ class NetworkIcon(Widget):
class MiciHomeLayout(Widget):
_set_chestnut_visibility: Callable[[], None]
def __init__(self):
super().__init__()
self._on_settings_click: Callable | None = None
@@ -366,7 +366,7 @@ class MiciOffroadAlerts(NavScroller):
time.sleep(REFRESH_INTERVAL)
def _sort_items(self):
self._scroller.items.sort(key=lambda w: -w.alert_data.severity)
self._scroller.items.sort(key=lambda w: -w.alert_data.severity if isinstance(w, AlertItem | NotificationItem) else 0)
def _refresh(self, pending_params: dict) -> int:
"""Refresh alerts from params and return active count."""
@@ -401,7 +401,7 @@ class MiciOffroadAlerts(NavScroller):
if text and not alert_data.visible:
# Bump newly visible alerts to the top, severity sort keeps it at the top of its category
widget = next(w for w in self._scroller.items if w.alert_data is alert_data)
widget = next(w for w in self.alert_items if w.alert_data is alert_data)
self._scroller.items.remove(widget)
self._scroller.items.insert(0, widget)
alert_data.text = text
@@ -99,7 +99,7 @@ class WifiNetworkButton(BigButton):
def _draw_content(self, btn_y: float):
super()._draw_content(btn_y)
# Render lock icon at lower right of wifi icon if secured
if self._draw_lock:
if self._draw_lock and self._txt_icon is not None:
icon_x = self._rect.x + self._rect.width - 30 - self._txt_icon.width
icon_y = btn_y + 30
lock_x = icon_x + self._txt_icon.width - self._lock_txt.width + 7
@@ -19,7 +19,7 @@ def blend_colors(a: rl.Color, b: rl.Color, f: float) -> rl.Color:
def glow_highlight_texture(asset: str, size: int, center: tuple[float, float] = (0.5, 0.5),
radius: tuple[float, float] = (0.5, 0.5)) -> rl.Texture:
image = gui_app._load_image_from_path((ASSETS_DIR / asset).as_posix(), size, size)
image = gui_app._load_image_from_path(str(ASSETS_DIR / asset), size, size)
w, h = image.width, image.height
alpha = np.frombuffer(image.to_bytes(w * h * 4), dtype=np.uint8).reshape(h, w, 4)[..., 3] / 255.0
rl.unload_image(image)
@@ -31,13 +31,11 @@ class BaseCabinCameraDialog(Widget):
self._pm: messaging.PubMaster | None = None
# Load eye icons
self._eye_fill_texture = None
self._eye_orange_texture = None
self._eye_size = 74
self._glasses_texture = None
self._glasses_size = 171
self._load_eye_textures()
self._eye_fill_texture = gui_app.texture("icons_mici/onroad/eye_fill.png", self._eye_size, self._eye_size)
self._eye_orange_texture = gui_app.texture("icons_mici/onroad/eye_orange.png", self._eye_size, self._eye_size)
self._glasses_texture = gui_app.texture("icons_mici/onroad/glasses.png", self._glasses_size, self._glasses_size)
def show_event(self):
super().show_event()
@@ -149,15 +147,6 @@ class BaseCabinCameraDialog(Widget):
alignment_vertical=TextAlignmentVertical.BOTTOM,
color=rl.Color(255, 255, 255, int(255 * 0.9)))
def _load_eye_textures(self):
"""Lazy load eye textures"""
if self._eye_fill_texture is None:
self._eye_fill_texture = gui_app.texture("icons_mici/onroad/eye_fill.png", self._eye_size, self._eye_size)
if self._eye_orange_texture is None:
self._eye_orange_texture = gui_app.texture("icons_mici/onroad/eye_orange.png", self._eye_size, self._eye_size)
if self._glasses_texture is None:
self._glasses_texture = gui_app.texture("icons_mici/onroad/glasses.png", self._glasses_size, self._glasses_size)
def _draw_face_detection(self, rect: rl.Rectangle):
dm_state = ui_state.sm["driverMonitoringState"]
driver_data = self.driver_state_renderer.get_driver_data()
@@ -52,7 +52,7 @@ class NavigationPanel(Widget):
self._unload_texture()
self._texture = rl.load_texture_from_image(rl.Image(None, SIZE, SIZE, 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8))
frame = self._client.recv(timeout_ms=0)
if frame is not None:
if frame is not None and self._texture is not None:
gray = np.frombuffer(frame.data, dtype=np.uint8, count=SIZE * SIZE)
rl.update_texture(self._texture, MAP_COLORS[gray])
# Without a usable map, mapsd publishes black frames with a zero timestamp.
@@ -101,7 +101,7 @@ class NavigationPanel(Widget):
alignment_vertical=TextAlignmentVertical.TOP)
map_rect = rl.Rectangle(x+8, y+61, rect.width-16, rect.height-111)
rl.draw_rectangle_rec(map_rect, rl.BLACK)
if self.map_ready:
if self._texture is not None and self.map_ready:
# A 1:1 crop of the model's frame, centered horizontally with the ego near the bottom.
width, height = min(map_rect.width, SIZE), min(map_rect.height, SIZE)
source = rl.Rectangle((SIZE - width) // 2, min(SIZE - height, max(0, EGO[1] + MARKER_MARGIN - height)), width, height)
@@ -290,7 +290,7 @@ class BigToggle(BigButton):
def __init__(self, text: str, value: str = "", initial_state: bool = False, toggle_callback: Callable | None = None,
*, description: str = "",
description_icon: Union[rl.Texture, None] = None):
super().__init__(text, value, "", description=description, description_icon=description_icon)
super().__init__(text, value, None, description=description, description_icon=description_icon)
self._checked = initial_state
self._toggle_callback = toggle_callback
@@ -81,7 +81,7 @@ class BigConfirmationDialog(BigDialogBase):
def _on_confirm(self):
if self._exit_on_confirm:
self.dismiss(self._confirm_callback)
elif self._confirm_callback:
else:
self._confirm_callback()
def _update_state(self):
+3 -1
View File
@@ -114,7 +114,7 @@ class CameraView(Widget):
if self._switching:
self._handle_switch()
if not self._ensure_connection():
if self.client is None or not self._ensure_connection():
self._draw_placeholder(rect)
return
@@ -165,6 +165,8 @@ class CameraView(Widget):
return FRAME_COLOR
def _ensure_connection(self) -> bool:
if self.client is None:
return False
if not self.client.is_connected():
self.frame = None
self.available_streams.clear()
@@ -63,7 +63,7 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
# Transform matrix (3x3 for car space to screen space)
self._car_space_transform = np.zeros((3, 3), dtype=np.float32)
self._transform_dirty = True
self._clip_region = None
self._clip_region = rl.Rectangle(0, 0, 0, 0)
self._path_gradient = Gradient(
start=(0.0, 1.0), # Bottom of path
@@ -57,12 +57,6 @@ class CruiseLayout(Widget):
description=tr("Use map data to estimate the appropriate speed to drive through turns ahead."),
param="SmartCruiseControlMap")
self.accel_boost_toggle = toggle_item_sp(
title=tr("Acceleration Boost"),
description=tr("Adds a small push on top of sunnypilot's own acceleration, stronger in Aggressive and gentler in Relaxed. " +
"Eases off in curves and when sunnypilot slows or stops. Never goes past your set speed, and lead-car following still comes first."),
param="AccelBoostSP")
self.custom_acc_toggle = toggle_item_sp(
title=tr("Custom ACC Speed Increments"),
description="",
@@ -92,7 +86,6 @@ class CruiseLayout(Widget):
self.icbm_toggle,
self.scc_v_toggle,
self.scc_m_toggle,
self.accel_boost_toggle,
self.custom_acc_toggle,
self.custom_acc_short_increment,
self.custom_acc_long_increment,
@@ -143,8 +136,6 @@ class CruiseLayout(Widget):
self.icbm_toggle.set_description(new_desc)
self.icbm_toggle.show_description(True)
self.accel_boost_toggle.action_item.set_enabled(has_long)
if has_long or has_icbm:
self.custom_acc_toggle.action_item.set_enabled(((has_long and not ui_state.CP.pcmCruise) or has_icbm) and ui_state.is_offroad())
self.scc_v_toggle.action_item.set_enabled(True)
@@ -160,7 +151,6 @@ class CruiseLayout(Widget):
else:
has_icbm = has_long = False
self.icbm_toggle.action_item.set_enabled(False)
self.accel_boost_toggle.action_item.set_enabled(False)
self.icbm_toggle.set_description(tr(ONROAD_ONLY_DESCRIPTION))
show_custom_acc_desc = False
@@ -170,7 +160,7 @@ class CruiseLayout(Widget):
show_custom_acc_desc = True
else:
if has_long or has_icbm:
if has_long and ui_state.CP.pcmCruise:
if has_long and ui_state.CP is not None and ui_state.CP.pcmCruise:
new_custom_acc_desc = tr(ACC_PCMCRUISE_DISABLED_DESCRIPTION)
show_custom_acc_desc = True
else:
@@ -33,6 +33,7 @@ class InitialCruiseSpeedControlSP(OptionControlSP):
return f"{self._options[self.current_value]} " + (tr("km/h") if ui_state.is_metric else tr("mph"))
def initial_cruise_speed_item_sp(**kwargs) -> ListItemSP:
class InitialCruiseSpeedItemSP(ListItemSP):
"""Stock row in the sunnypilot option layout: title on top, control below, like option_item_sp."""
return ListItemSP(inline=False, **kwargs)
def __init__(self, **kwargs):
super().__init__(inline=False, **kwargs)
@@ -158,8 +158,8 @@ class ModelsLayout(Widget):
bundle = self.model_manager.selectedBundle if self.model_manager else None
progresses = [model.artifact.downloadProgress for model in bundle.models if model.artifact.fileName] if bundle else []
if not progresses or bundle.status not in (custom.ModelManagerSP.DownloadStatus.downloading,
custom.ModelManagerSP.DownloadStatus.failed):
if bundle is None or not progresses or bundle.status not in (custom.ModelManagerSP.DownloadStatus.downloading,
custom.ModelManagerSP.DownloadStatus.failed):
self.download_item.action_item.update(name="", segments=self._slot_segments())
return
@@ -261,7 +261,7 @@ class ModelsLayout(Widget):
return {"name": name, "text_color": rl.GRAY, "icon": "icons/circled_slash.png", "icon_color": rl.WHITE}
def _on_model_selected(self, result):
if result != DialogResult.CONFIRM:
if result != DialogResult.CONFIRM or self.model_dialog is None:
self.model_dialog = None
return
selected_ref = self.model_dialog.selection_ref
@@ -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 threading
import time
import raylib_nb as rl
from openpilot.system.ui.lib.multilang import tr
@@ -30,7 +29,6 @@ class NetworkUISP(NetworkUI):
threading.Thread(target=self._wifi_manager._update_networks, daemon=True).start()
self._wifi_manager._request_scan()
self._wifi_manager._last_network_update = time.monotonic()
def _on_networks_updated(self, networks):
if self._scanning:
@@ -59,7 +59,7 @@ class OSMLayout(Widget):
def calculate_size(self):
total_size = 0
directories_to_scan = [MAP_PATH] if MAP_PATH.exists() else []
directories_to_scan = [str(MAP_PATH)] if MAP_PATH.exists() else []
while directories_to_scan:
try:
for entry in os.scandir(directories_to_scan.pop()):
@@ -37,7 +37,7 @@ from openpilot.system.ui.widgets.scroller_tici import Scroller
OP.PANEL_COLOR = rl.Color(10, 10, 10, 255)
ICON_SIZE = 70
OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignment]
PanelType = IntEnum(
"PanelType",
[es.name for es in OP.PanelType] + [
"SUNNYLINK",
@@ -53,6 +53,7 @@ OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignm
],
start=0,
)
OP.PanelType = PanelType # type: ignore[assignment] # ty: ignore[invalid-assignment]
@dataclass
@@ -109,22 +110,22 @@ class SettingsLayoutSP(OP.SettingsLayout):
wifi_manager.set_active(False)
self._panels = {
OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
OP.PanelType.MODELS: PanelInfo(tr_noop("Models"), ModelsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_models.png"),
OP.PanelType.STEERING: PanelInfo(tr_noop("Steering"), SteeringLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_lateral.png"),
OP.PanelType.CRUISE: PanelInfo(tr_noop("Cruise"), CruiseLayout(), icon="icons/speed_limit.png"),
OP.PanelType.VISUALS: PanelInfo(tr_noop("Visuals"), VisualsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_visuals.png"),
OP.PanelType.DISPLAY: PanelInfo(tr_noop("Display"), DisplayLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_display.png"),
OP.PanelType.OSM: PanelInfo(tr_noop("OSM"), OSMLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
# OP.PanelType.NAVIGATION: PanelInfo(tr_noop("Navigation"), NavigationLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
OP.PanelType.TRIPS: PanelInfo(tr_noop("Trips"), TripsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_trips.png"),
OP.PanelType.VEHICLE: PanelInfo(tr_noop("Vehicle"), VehicleLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_vehicle.png"),
OP.PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_firehose.png"),
OP.PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayoutSP(), icon="icons/shell.png"),
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
PanelType.MODELS: PanelInfo(tr_noop("Models"), ModelsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_models.png"),
PanelType.STEERING: PanelInfo(tr_noop("Steering"), SteeringLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_lateral.png"),
PanelType.CRUISE: PanelInfo(tr_noop("Cruise"), CruiseLayout(), icon="icons/speed_limit.png"),
PanelType.VISUALS: PanelInfo(tr_noop("Visuals"), VisualsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_visuals.png"),
PanelType.DISPLAY: PanelInfo(tr_noop("Display"), DisplayLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_display.png"),
PanelType.OSM: PanelInfo(tr_noop("OSM"), OSMLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
# PanelType.NAVIGATION: PanelInfo(tr_noop("Navigation"), NavigationLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
PanelType.TRIPS: PanelInfo(tr_noop("Trips"), TripsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_trips.png"),
PanelType.VEHICLE: PanelInfo(tr_noop("Vehicle"), VehicleLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_vehicle.png"),
PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_firehose.png"),
PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayoutSP(), icon="icons/shell.png"),
}
def _draw_sidebar(self, rect: rl.Rectangle):
@@ -73,7 +73,7 @@ class SoftwareLayoutSP(SoftwareLayout):
]
def _on_branch_selected(result):
if result == DialogResult.CONFIRM and self._branch_dialog is not None:
if result == DialogResult.CONFIRM and isinstance(self._branch_dialog, TreeOptionDialog):
selection = self._branch_dialog.selection_ref
if selection:
ui_state.params.put("UpdaterTargetBranch", selection)
@@ -4,6 +4,7 @@ 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.abc import Callable
from enum import Enum
from openpilot.cereal import messaging, log, custom
@@ -29,6 +30,13 @@ class OnroadTimerStatus(Enum):
class UIStateSP:
CP: "car.CarParams | None"
has_longitudinal_control: bool
chestnut_present: bool
chestnut_active: bool | None
chestnut_loading: bool
is_offroad: Callable[[], bool]
def __init__(self):
self.params = Params()
self.CP_SP: custom.CarParamsSP | None = None
@@ -253,7 +261,7 @@ class DeviceSP:
def __init__(self):
self._blocked_by_screensaver: bool = False
def _set_awake(self, on: bool, _ui_state=None):
def _set_awake(self, on: bool, _ui_state):
self._blocked_by_screensaver = False
if not on and _ui_state.screensaver_enabled:
+1 -2
View File
@@ -74,8 +74,7 @@ def run_replay(variant: LayoutVariant) -> None:
send_fn: Callable | None = None
frame = 0
# Override raylib timing functions to return deterministic values based on frame count instead of real time
rl.get_frame_time = lambda: 1.0 / FPS
rl.get_time = lambda: frame / FPS
vars(rl).update(get_frame_time=lambda: 1.0 / FPS, get_time=lambda: frame / FPS)
# Main loop to replay events and render frames
with tqdm(total=script[-1][0] + 1, desc="Replaying", unit="frame", disable=bool(os.getenv("CI"))) as pbar:
@@ -50,7 +50,7 @@ def patch_submaster(message_chunks):
sm.recv_frame[service] = sm.frame
sm.valid[service] = True
sm.frame += 1
ui_state.sm.update = mock_update # ty: ignore[invalid-assignment] # profiling hook
ui_state.sm.update = mock_update
if __name__ == "__main__":
@@ -117,6 +117,7 @@ def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]:
m = re.match(r'msgstr\[(\d+)]\s+(.*)', stripped)
if m:
assert cur is not None
plural_idx = int(m.group(1))
cur.msgstr_plural[plural_idx] = _parse_quoted(m.group(2))
cur_field = 'msgstr_plural'
@@ -130,6 +131,7 @@ def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]:
continue
if stripped.startswith('"'):
assert cur is not None
val = _parse_quoted(stripped)
if cur_field == 'msgid':
cur.msgid += val
@@ -301,7 +303,7 @@ def init_po(pot_path: str | Path, po_path: str | Path, language: str) -> None:
_, entries = parse_po(pot_path)
plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);')
nplurals = int(re.search(r'nplurals=(\d+)', plural_forms).group(1))
nplurals = int(re.findall(r'nplurals=(\d+)', plural_forms)[0])
for e in entries:
if e.is_plural:
e.msgstr_plural = dict.fromkeys(range(nplurals), '')
@@ -123,7 +123,9 @@ def get_policy_npy_shapes(input_shapes: dict, is_supercombo: bool = False) -> tu
def host_view(tensor: Tensor) -> np.ndarray: # QCOM -> CPU round trip of tfm takes 5ms longer than host memory view
return np.frombuffer(tensor._buffer()._host_mv(), dtype=np.float32).reshape(tensor.shape)
mv = tensor._buffer()._host_mv()
assert mv is not None
return np.frombuffer(mv, dtype=np.float32).reshape(tensor.shape)
def generate_queues_and_npy(input_shapes: dict, frame_skip: int, device: str = Device.DEFAULT,
@@ -217,6 +219,7 @@ def make_run_policy(vision_runner, policy_runners: list, features_slice: slice,
npy_shapes, npy_sizes = get_policy_npy_shapes(input_shapes, is_supercombo=is_supercombo)
def run_policy(warped, img_q, big_img_q, feat_q, desire_q=None, packed_npy_inputs=None, **kwargs):
assert packed_npy_inputs is not None
packed_npy_inputs_dev = packed_npy_inputs.to(Device.DEFAULT)
warped_dev = warped.to(Device.DEFAULT)
Tensor.realize(packed_npy_inputs_dev, warped_dev)
@@ -387,7 +390,7 @@ if __name__ == "__main__":
args = parser.parse_args()
model_w, model_h = args.model_size
output_data = {}
output_data: dict[Any, Any] = {}
is_unified_supercombo = False
if args.model_type == 'supercombo':
@@ -7,6 +7,7 @@ See the LICENSE.md file in the root directory for more details.
"""
import argparse
import dataclasses
import importlib
import inspect
import itertools
import mmap
@@ -14,6 +15,7 @@ import os
import re
import struct
import tempfile
from typing import Any
import numpy as np
from openpilot.sunnypilot.modeld_v2.helpers import ALIGNMENT, Blob, PlainJit, flatten, patch_fetch_fw, write_bundle
@@ -139,11 +141,13 @@ def _elf(image: bytes, rodata: int, entry: int) -> bytes:
def lower_and_compile(linear):
try:
from tinygrad.codegen.compile import lower_and_compile
except ImportError:
from tinygrad.engine.realize import lower_and_compile
return lower_and_compile(linear)
for module in ("tinygrad.codegen.compile", "tinygrad.engine.realize"): # moved to codegen in newer tinygrad
try:
compile_fn = importlib.import_module(module).lower_and_compile
except (ImportError, AttributeError):
continue
return compile_fn(linear)
raise ImportError("tinygrad has no lower_and_compile")
def submit_kernels(jit) -> tuple:
@@ -253,7 +257,7 @@ def main():
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: dict[str, Any] = {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)):
+5 -2
View File
@@ -20,6 +20,7 @@ import mmap
import os
import pickle
import struct
from typing import Any
MAGIC = b"SPTGPLN1"
ALIGNMENT = 256
@@ -334,11 +335,13 @@ class PlainJit(_Jit):
_dtype(spec["dtype"])) for slot, spec in inputs.items()}
input_uops = tuple(stand_ins.get(slot, next(iter(stand_ins.values()), None)) for slot in range(max(stand_ins, default=-1) + 1))
takes_inputs = "input_uops" in inspect.signature(jit.compile_linear).parameters
linear = jit.compile_linear(UOp(Ops.LINEAR, src=tuple(calls)), beam=0, cache=False, **({"input_uops": input_uops} if takes_inputs else {}))
compile_kwargs: dict[str, Any] = {"input_uops": input_uops} if takes_inputs else {}
linear = jit.compile_linear(UOp(Ops.LINEAR, src=tuple(calls)), beam=0, cache=False, **compile_kwargs)
returned = [Tensor(argument(t)).reshape(tuple(t["shape"])) for t in header["returns"]["tensors"]]
ret = {"NoneType": None, "Tensor": returned[0] if returned else None, "tuple": tuple(returned), "list": returned}[header["returns"]["kind"]]
captured = jit.CapturedJit(ret, linear, header["input_names"], []) if takes_inputs else jit.CapturedJit(ret, linear, (), header["input_names"], [], {})
captured_args: tuple[Any, ...] = (ret, linear, header["input_names"], []) if takes_inputs else (ret, linear, (), header["input_names"], [], {})
captured = jit.CapturedJit(*captured_args)
super().__init__(captured, header["input_names"], buffers)
if not verify or not (check := header.get("check")):
@@ -29,6 +29,10 @@ def input_view(buffer: Buffer, shape: tuple[int, ...], dtype: DType, offset: int
class BaseModelAdapter:
frame_copy_size: int
numpy_inputs: dict[str, np.ndarray]
_vision_input_names: list[str]
def __init__(self, jits, cam_w, cam_h, model_device, queue_device, warp_device, chestnut=False):
self.jits = jits
self.DEV = model_device
@@ -185,7 +189,7 @@ class NativeTinygradAdapter(BaseModelAdapter):
self.outputs = {name: Tensor(np.zeros(shape, dtype=dtype), device=device).realize() for name, (shape, dtype, device) in self.jits['output_specs'].items()}
for name, next_name in self.state_pairs.items():
state = self.input_queues[name]
self.outputs[next_name] = input_view(state._buffer(), state.shape, state.dtype, 0)
self.outputs[next_name] = input_view(state._buffer(), self.input_shapes[name][0], state.dtype, 0)
def copy_frames(self, bufs):
for i, key in enumerate(self._vision_input_names):
@@ -19,14 +19,14 @@ from openpilot.sunnypilot.modeld_v2.helpers import Blob, flatten
@contextmanager
def record_kernel_linear():
import tinygrad.engine.jit as jit
import tinygrad.engine.realize as realize
recorded, hcq_compile, compile_linear = [], realize.hcq_compile, jit.compile_linear
import tinygrad.codegen.compile as codegen
recorded, hcq_compile, jit_lower = [], codegen.hcq_compile, jit.jit_lower
def recording_compile_linear(*args, **kwargs):
with mock.patch.object(realize, "hcq_compile", lambda linear, *a, **k: (linear.src and recorded.append(linear), hcq_compile(linear, *a, **k))[1]):
return compile_linear(*args, **kwargs)
def recording_jit_lower(*args, **kwargs):
with mock.patch.object(codegen, "hcq_compile", lambda linear, *a, **k: (linear.src and recorded.append(linear), hcq_compile(linear, *a, **k))[1]):
return jit_lower(*args, **kwargs)
with mock.patch.object(jit, "compile_linear", recording_compile_linear):
with mock.patch.object(jit, "jit_lower", recording_jit_lower):
yield recorded
@@ -51,15 +51,18 @@ def kernel_signature(ast, elf) -> list:
def serialize_jit(jit, kernel_linear, check: dict | None = None) -> tuple[dict, memoryview]:
from tinygrad.device import TinyELF
from tinygrad.uop.ops import Ops
sink = tempfile.TemporaryFile(dir=".")
blob, bases, input_specs = Blob(sink), {}, {}
externs = dict(enumerate(jit.captured._externs, len(jit.captured.expected_input_info)))
def store(array) -> dict:
array = np.ascontiguousarray(array)
return {"data": blob.add(array.tobytes()), "dtype": array.dtype.str, "shape": list(array.shape)}
def describe(uop) -> dict:
uop = externs.get(uop.arg.slot, uop) if uop.op is Ops.EXTERN else uop
if uop.op is Ops.PARAM:
input_specs.setdefault(uop.arg.slot, {"dtype": repr(uop.dtype), "numel": int(uop.max_numel()), "device": uop.device})
return {"input": uop.arg.slot}
@@ -78,8 +81,8 @@ def serialize_jit(jit, kernel_linear, check: dict | None = None) -> tuple[dict,
for call in kernel_linear.src:
ast, arguments = call.src[0], [describe(argument) for argument in call.src[1:]]
if ast.op is Ops.PROGRAM:
elf, info = ast.to_elf(), ast.arg
global_size, local_size = info.launch_dims({})
elf, info = TinyELF.from_program(ast), ast.arg
global_size, local_size = info.launch_dims(call)
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,
"signature": kernel_signature(ast, elf),
@@ -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 unittest
import numpy as np
from openpilot.common.parameterized import parameterized
@@ -188,63 +187,3 @@ class Test4DFeaturesBuffer(OpenpilotTestCase):
shapes, sizes = get_policy_npy_shapes(input_shapes, is_supercombo=True)
assert shapes['prev_feat'] == (1, 512)
assert sizes == [8, 2, 2, 512]
class TestStockCompileModeldEquivalence(OpenpilotTestCase):
@unittest.skip("upstream removed selfdrive/modeld/compile_modeld.py — no stock implementation to compare")
def test_get_policy_npy_shapes_matches_stock(self):
from openpilot.selfdrive.modeld.compile_modeld import get_policy_npy_shapes as stock_get_policy_npy_shapes
from openpilot.sunnypilot.modeld_v2.compile_modeld import get_policy_npy_shapes as sunny_get_policy_npy_shapes
stock_input_shapes = {
'desire_pulse': (1, 25, 8),
'features_buffer': (1, 24, 512), # see below comment
'traffic_convention': (1, 2),
'action_t': (1, 2),
}
stock_shapes, stock_sizes = stock_get_policy_npy_shapes(stock_input_shapes)
sunny_shapes, sunny_sizes = sunny_get_policy_npy_shapes(stock_input_shapes, is_supercombo=True)
assert sunny_shapes == stock_shapes
assert sunny_sizes == stock_sizes
assert sunny_shapes['prev_feat'] == (1, 512)
@unittest.skip("upstream removed selfdrive/modeld/compile_modeld.py — no stock implementation to compare")
def test_make_input_queues_full_stock_equivalence(self):
from openpilot.selfdrive.modeld.compile_modeld import make_input_queues as stock_make_input_queues
from openpilot.sunnypilot.modeld_v2.compile_modeld import make_supercombo_input_queues as sunny_make_supercombo_input_queues
input_shapes = {
'img': (1, 12, 128, 256),
'desire_pulse': (1, 25, 8),
'features_buffer': (1, 24, 32, 512),
'traffic_convention': (1, 2),
'action_t': (1, 2),
}
frame_skip = 4
stock_queues, stock_npy, _frame_views = stock_make_input_queues(input_shapes, frame_skip, device='NPY', frame_copy_size=49152)
sunny_queues, sunny_npy = sunny_make_supercombo_input_queues(input_shapes, frame_skip, device='NPY')
# sunnypilot split pipeline has tfm/big_tfm as queues; packed_npy_inputs size differs (different frame packing)
assert set(stock_queues.keys()) <= set(sunny_queues.keys())
for key in stock_queues:
if key == 'packed_npy_inputs':
continue
assert sunny_queues[key].shape == stock_queues[key].shape, \
f"Queue shape mismatch for {key}: sunny {sunny_queues[key].shape} != stock {stock_queues[key].shape}"
assert set(stock_npy.keys()) <= set(sunny_npy.keys())
for key in stock_npy:
assert sunny_npy[key].shape == stock_npy[key].shape, \
f"Numpy array shape mismatch for {key}: sunny {sunny_npy[key].shape} != stock {stock_npy[key].shape}"
@unittest.skip("upstream removed make_warp_input_queues — warp merged into run_model")
def test_make_warp_queues_stock_equivalence(self):
from openpilot.selfdrive.modeld.compile_modeld import make_warp_input_queues as stock_make_warp_queues
from openpilot.sunnypilot.modeld_v2.compile_modeld import make_warp_queues as sunny_make_warp_queues
stock_vision_shapes = {'img': (1, 12, 128, 256)} # for now?
stock_queues, stock_npy = stock_make_warp_queues(stock_vision_shapes, frame_skip=4, device='NPY')
sunny_queues, sunny_npy = sunny_make_warp_queues(device='NPY')
assert set(sunny_npy.keys()) == set(stock_npy.keys()) == {'tfm', 'big_tfm'}
for key in sunny_npy:
assert sunny_npy[key].shape == stock_npy[key].shape == (3, 3)
@@ -1 +1 @@
ec362fdaecff40a02a2bf3eb23882ca8d28cef26175df194798d5e0a67f813b7
c9700628ee59e67f78fb603afd815b28eb30f4f2c215b67d307f9703593630cf
@@ -13,7 +13,7 @@ ButtonType = car.CarState.ButtonEvent.Type
@parameterized_class(('pcm_cruise', 'pcm_cruise_speed'), [(False, True)])
class TestCustomAccIncrements(TestVCruiseHelper):
def setup_method(self):
TestVCruiseHelper.openpilot_setup_method(self)
super().openpilot_setup_method()
self.params = Params()
self.reset_custom_params()
@@ -1,70 +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.cereal import log
from openpilot.common.params import Params
from openpilot.common.realtime import DT_MDL
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
ACCEL_BOOST_MIN_SPEED = 1.0
ACCEL_BOOST_MAX = (0.4, 0.25, 0.1) # aggressive, standard, relaxed, m/s^2
ACCEL_BOOST_BUILD, ACCEL_BOOST_RELEASE = 0.2, 1.0 # m/s^3
BRAKE_PROB = (0.1, 0.3) # the model's brake press in 4 s: it wants to slow
GAS_PROB = (0.6, 0.8) # predicts a human gas press at this hypothesis at about 23%
CURVE_LAT_ACCEL = (1.5, 2.5)
def get_boost_max(personality=log.LongitudinalPersonality.standard):
if personality == log.LongitudinalPersonality.relaxed:
return ACCEL_BOOST_MAX[2]
elif personality == log.LongitudinalPersonality.standard:
return ACCEL_BOOST_MAX[1]
elif personality == log.LongitudinalPersonality.aggressive:
return ACCEL_BOOST_MAX[0]
else:
raise NotImplementedError("Longitudinal personality not supported")
class AccelBoostSP:
def __init__(self):
self.params = Params()
self.frame = -1
self.enabled = False
self.boost = 0.0
self.total_boost = 0.0
def update_params(self):
self.frame += 1
if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) != 0:
return False
enabled = self.params.get_bool("AccelBoostSP")
if enabled == self.enabled:
return False
self.enabled = enabled
self.boost = self.total_boost = 0.0
return True
def reset(self):
self.boost = self.total_boost = 0.0
def update(self, sm, output_a_target_e2e, curve_offset):
model = sm['modelV2']
brake_probs = model.meta.disengagePredictions.brakePressProbs
gas_probs = model.meta.disengagePredictions.gasPressProbs
if not sm['selfdriveState'].enabled or len(brake_probs) < 2 or len(gas_probs) < 2:
self.boost = self.total_boost = 0.0
return output_a_target_e2e
want = max(float(np.interp(brake_probs[1], BRAKE_PROB, [1.0, 0.0])), float(np.interp(gas_probs[1], GAS_PROB, [0.0, 1.0])))
want = 0.0 if model.action.shouldStop else want
want *= float(np.interp(abs(model.action.desiredCurvature) * sm['carState'].vEgo ** 2, CURVE_LAT_ACCEL, [1.0, 0.0]))
target = want * get_boost_max(sm['selfdriveState'].personality)
self.boost = float(np.clip(target, self.boost - ACCEL_BOOST_RELEASE * DT_MDL, self.boost + ACCEL_BOOST_BUILD * DT_MDL))
speed_scale = np.interp(sm['carState'].vEgo, [ACCEL_BOOST_MIN_SPEED, 2 * ACCEL_BOOST_MIN_SPEED], [0.0, 1.0])
self.total_boost = self.boost * speed_scale * np.interp(output_a_target_e2e, [-0.7, -0.2, 5.0], [0.0, 1.0, 1.0], right=0.0)
return output_a_target_e2e + self.total_boost
@@ -18,7 +18,6 @@ class LatControlTorqueExt(NeuralNetworkLateralControl, LatControlTorqueExtOverri
desired_lateral_accel, actual_lateral_accel, lateral_accel_deadzone, gravity_adjusted_lateral_accel,
desired_curvature, actual_curvature, steer_limited_by_safety, output_torque):
self._ff = ff
self._pid = pid
self._pid_log = pid_log
self._setpoint = setpoint
self._measurement = measurement
@@ -7,6 +7,8 @@ See the LICENSE.md file in the root directory for more details.
import math
import numpy as np
from openpilot.cereal import log
from openpilot.common.pid import PIDController
from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N
from openpilot.selfdrive.modeld.constants import ModelConstants
@@ -61,8 +63,8 @@ class LatControlTorqueExtBase:
self.torque_params = lac_torque.torque_params
self._ff = 0.0
self._pid = PIDController(KP, KI)
self._pid_log = None
self._pid = PIDController(KP, KI, pos_limit=lac_torque.steer_max, neg_limit=-lac_torque.steer_max, rate=1 / lac_torque.dt)
self._pid_log = log.ControlsState.LateralTorqueState.new_message()
self._setpoint = 0.0
self._measurement = 0.0
self._roll_compensation = 0.0
@@ -119,7 +121,7 @@ class LatControlTorqueExtBase:
actual_curvature_rate = -VM.calc_curvature(math.radians(CS.steeringRateDeg), CS.vEgo, 0.0)
self.actual_lateral_jerk = actual_curvature_rate * CS.vEgo ** 2
if self.model_valid:
if self.model_valid and self.model_v2 is not None:
# prepare "look-ahead" desired lateral jerk
lookahead = np.interp(CS.vEgo, self.friction_look_ahead_bp, self.friction_look_ahead_v)
friction_upper_idx = next((i for i, val in enumerate(ModelConstants.T_IDXS) if val > lookahead), 16)
@@ -34,7 +34,7 @@ class LatControlTorqueJerkAware(LatControlTorqueExtBase):
LatControlInputs(self._measurement, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, gravity_adjusted=False
)
self._pid_log.error = float(torque_from_setpoint - torque_from_measurement) # ty: ignore[invalid-assignment]
self._pid_log.error = float(torque_from_setpoint - torque_from_measurement)
self._ff = self.torque_from_lateral_accel_in_torque_space(
LatControlInputs(gravity_adjusted_lateral_accel, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, gravity_adjusted=True
)
@@ -9,9 +9,7 @@ from openpilot.cereal import messaging, custom
from opendbc.car import structs
from openpilot.common.constants import CV
from openpilot.selfdrive.car.cruise import V_CRUISE_MAX
from openpilot.selfdrive.controls.lib.accel_boost import AccelBoost
from openpilot.selfdrive.controls.lib.curve_speed import CurveSpeed
from openpilot.sunnypilot.selfdrive.controls.lib.accel_boost import AccelBoostSP
from openpilot.sunnypilot.selfdrive.controls.lib.e2e_alerts_helper import E2EAlertsHelper
from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.smart_cruise_control import SmartCruiseControl
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_assist import SpeedLimitAssist
@@ -31,6 +29,8 @@ class NoCurveSpeed:
class LongitudinalPlannerSP:
dt: float
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, mpc):
self.events_sp = EventsSP()
self.resolver = SpeedLimitResolver()
@@ -40,7 +40,6 @@ class LongitudinalPlannerSP:
self.generation = int(model_bundle.generation) if (model_bundle := get_active_bundle()) else None
self.source = LongitudinalPlanSource.cruise
self.e2e_alerts_helper = E2EAlertsHelper()
self.accel_boost_sp = AccelBoostSP()
self.openpilot_longitudinal = CP.openpilotLongitudinalControl
self.output_v_target = 0.
@@ -83,8 +82,6 @@ class LongitudinalPlannerSP:
self.curve_speed = NoCurveSpeed() if scc_curves else CurveSpeed(self.dt)
def update(self, sm: messaging.SubMaster) -> None:
if self.accel_boost_sp.update_params():
self.accel_boost = self.accel_boost_sp if self.accel_boost_sp.enabled and self.openpilot_longitudinal else AccelBoost()
self._update_curve_speed()
self.events_sp.clear()
@@ -81,14 +81,14 @@ class NeuralNetworkLateralControl(LatControlTorqueJerkAware):
self.torque_params, gravity_adjusted=False)
torque_from_measurement = self.torque_from_lateral_accel_in_torque_space(LatControlInputs(self._measurement, self._roll_compensation, CS.vEgo, CS.aEgo),
self.torque_params, gravity_adjusted=False)
self._pid_log.error = float(torque_from_setpoint - torque_from_measurement) # ty: ignore[invalid-assignment]
self._pid_log.error = float(torque_from_setpoint - torque_from_measurement)
self._ff = self.torque_from_lateral_accel_in_torque_space(LatControlInputs(self._gravity_adjusted_lateral_accel, self._roll_compensation,
CS.vEgo, CS.aEgo), self.torque_params, gravity_adjusted=True)
self._ff += get_friction_in_torque_space(self._desired_lateral_accel - self._actual_lateral_accel, self._lateral_accel_deadzone,
FRICTION_THRESHOLD, self.torque_params)
def update_neural_network_feedforward(self, CS, params, calibrated_pose) -> None:
if not self._nnlc_enabled:
if not self._nnlc_enabled or self.model is None or self.model_v2 is None:
return
self.update_feedforward_torque_space(CS)
@@ -128,7 +128,7 @@ class NeuralNetworkLateralControl(LatControlTorqueJerkAware):
+ past_rolls + future_rolls
torque_from_setpoint = self.model.evaluate(nnff_setpoint_input)
torque_from_measurement = self.model.evaluate(nnff_measurement_input)
self._pid_log.error = torque_from_setpoint - torque_from_measurement # ty: ignore[invalid-assignment]
self._pid_log.error = torque_from_setpoint - torque_from_measurement
# The "pure" NNLC error response can be too weak for cars whose models were trained
# with a lack of high-magnitude lateral acceleration data, for which the NNLC model
@@ -144,7 +144,7 @@ class NeuralNetworkLateralControl(LatControlTorqueJerkAware):
nnff_error_input = [CS.vEgo, self._setpoint - self._measurement, self.lateral_jerk_setpoint - self.lateral_jerk_measurement, 0.0]
torque_from_error = self.model.evaluate(nnff_error_input)
if sign(self._pid_log.error) == sign(torque_from_error) and abs(self._pid_log.error) < abs(torque_from_error):
self._pid_log.error = self._pid_log.error * (1.0 - error_blend_factor) + torque_from_error * error_blend_factor # ty: ignore[invalid-assignment]
self._pid_log.error = self._pid_log.error * (1.0 - error_blend_factor) + torque_from_error * error_blend_factor
# compute feedforward (same as nn setpoint output)
friction_input = self.update_friction_input(self._setpoint, self._measurement)
@@ -81,12 +81,8 @@ class TestSpeedLimitAssist(OpenpilotTestCase):
def reset_state(self):
self.sla.state = SpeedLimitAssistState.disabled
self.sla.frame = -1
self.sla.last_op_engaged_frame = 0
self.sla.op_engaged = False
self.sla.op_engaged_prev = False
self.sla._speed_limit = 0.
self.sla.speed_limit_prev = 0.
self.sla.last_valid_speed_limit_offsetted = 0.
self.sla._distance = 0.
self.events_sp.clear()
@@ -264,7 +260,6 @@ class TestSpeedLimitAssist(OpenpilotTestCase):
for state in test_states:
self.sla.state = state
self.sla.op_engaged = True
initial_state = state
@@ -1,88 +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.
"""
from types import SimpleNamespace
from openpilot.common.parameterized import parameterized
from openpilot.common.params import Params
from openpilot.common.realtime import DT_MDL
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
from openpilot.sunnypilot.selfdrive.controls.lib.accel_boost import AccelBoostSP, ACCEL_BOOST_MAX
def make_sm(brake_prob=0.05, gas_prob=0.3, lat_accel=0.0, v_ego=30.0, personality=0, enabled=True, should_stop=False):
meta = SimpleNamespace(disengagePredictions=SimpleNamespace(brakePressProbs=[0.0, brake_prob, 0.0, 0.0, 0.0, 0.0],
gasPressProbs=[0.0, gas_prob, 0.0, 0.0, 0.0, 0.0]))
action = SimpleNamespace(shouldStop=should_stop, desiredCurvature=lat_accel / v_ego ** 2)
return {'modelV2': SimpleNamespace(meta=meta, action=action), 'carState': SimpleNamespace(vEgo=v_ego),
'selfdriveState': SimpleNamespace(enabled=enabled, personality=personality)}
def settle(sm, frames=100):
boost = AccelBoostSP()
for _ in range(frames):
boost.update(sm, 0.0, 0.0)
return boost.total_boost
class TestAccelBoostSP(OpenpilotTestCase):
@parameterized.expand([(0,), (1,), (2,)])
def test_personality_max(self, personality):
assert abs(settle(make_sm(personality=personality)) - ACCEL_BOOST_MAX[personality]) < 1e-6
def test_brake_gate_closes(self):
assert settle(make_sm(brake_prob=0.5)) == 0.0
def test_gas_reopens(self):
assert abs(settle(make_sm(brake_prob=0.5, gas_prob=0.9)) - ACCEL_BOOST_MAX[0]) < 1e-6
def test_should_stop(self):
assert settle(make_sm(gas_prob=0.9, should_stop=True)) == 0.0
@parameterized.expand([(1.5, 1.0), (2.0, 0.5), (2.5, 0.0), (-2.0, 0.5)])
def test_curve_fade(self, lat_accel, scale):
assert abs(settle(make_sm(lat_accel=lat_accel)) - scale * ACCEL_BOOST_MAX[0]) < 1e-6
def test_low_speed(self):
assert settle(make_sm(v_ego=0.5)) == 0.0
def test_disabled_resets(self):
boost = AccelBoostSP()
for _ in range(100):
boost.update(make_sm(), 0.0, 0.0)
assert boost.update(make_sm(enabled=False), 0.0, 0.0) == 0.0
assert boost.boost == 0.0 and boost.total_boost == 0.0
def test_reset(self):
boost = AccelBoostSP()
for _ in range(100):
boost.update(make_sm(), 0.0, 0.0)
boost.reset()
assert boost.boost == 0.0 and boost.total_boost == 0.0
def test_build_and_release_rates(self):
boost = AccelBoostSP()
boost.update(make_sm(), 0.0, 0.0)
assert abs(boost.total_boost - 0.01) < 1e-6
for _ in range(100):
boost.update(make_sm(), 0.0, 0.0)
boost.update(make_sm(brake_prob=0.5), 0.0, 0.0)
assert abs(boost.total_boost - (ACCEL_BOOST_MAX[0] - 0.05)) < 1e-6
def test_param_switch(self):
params = Params()
boost = AccelBoostSP()
params.put_bool("AccelBoostSP", True, block=True)
assert boost.update_params() and boost.enabled
for _ in range(100):
boost.update(make_sm(), 0.0, 0.0)
params.put_bool("AccelBoostSP", False, block=True)
for _ in range(int(PARAMS_UPDATE_PERIOD / DT_MDL) - 1):
assert not boost.update_params()
assert boost.update_params() and not boost.enabled
assert boost.boost == 0.0 and boost.total_boost == 0.0
@@ -4,6 +4,7 @@ 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 openpilot.cereal import log, messaging
@@ -59,9 +60,9 @@ def _make_model_v2():
return model
def _run_update(controller, VM):
def _run_update(controller, VM, v_ego=30, desired_curvature=0.5):
CS = car.CarState.new_message()
CS.vEgo = 30
CS.vEgo = v_ego
CS.steeringPressed = False
lp = generate_deviceMotion()
pose = Pose.from_device_motion(lp.deviceMotion)
@@ -69,7 +70,7 @@ def _run_update(controller, VM):
model_v2 = _make_model_v2().modelV2
controller.extension.update_model_v2(model_v2)
controller.extension.update_lateral_lag(0.2)
return controller.update(True, CS, VM, params, False, 0.5, pose, False, 0.2)
return controller.update(True, CS, VM, params, False, desired_curvature, pose, False, 0.2)
class TestLatControlTorqueExt(OpenpilotTestCase):
@@ -107,3 +108,12 @@ class TestLatControlTorqueExt(OpenpilotTestCase):
controller, VM, _ = _make_controller(enhanced=True, nnlc=True)
output_torque, _, pid_log = _run_update(controller, VM)
assert pid_log.active
def test_low_speed_gain_bounded(self):
for kwargs in ({"nnlc": True}, {"enhanced": True}):
controller, VM, _ = _make_controller(**kwargs)
one_degree = -VM.calc_curvature(math.radians(1.0), 2.0, 0.0)
output_torque, _, _ = _run_update(controller, VM, v_ego=2.0, desired_curvature=one_degree)
assert controller.extension._nnlc_enabled or controller.extension._jerk_aware_enabled
assert controller.extension._pid is not controller.pid
assert abs(output_torque) < 0.3, kwargs
@@ -620,19 +620,6 @@
}
]
},
{
"key": "AccelBoostSP",
"widget": "toggle",
"title": "Acceleration Boost",
"description": "Adds a small push on top of sunnypilot's own acceleration, stronger in Aggressive and gentler in Relaxed. Eases off in curves and when sunnypilot slows or stops. Never goes past your set speed, and lead-car following still comes first.",
"enablement": [
{
"type": "capability",
"field": "has_longitudinal_control",
"equals": true
}
]
},
{
"key": "IntelligentCruiseButtonManagement",
"widget": "toggle",
@@ -30,12 +30,6 @@ sections:
label: Relaxed
enablement:
- $ref: '#/macros/longitudinal'
- key: AccelBoostSP
widget: toggle
title: Acceleration Boost
description: "Adds a small push on top of sunnypilot's own acceleration, stronger in Aggressive and gentler in Relaxed. Eases off in curves and when sunnypilot slows or stops. Never goes past your set speed, and lead-car following still comes first."
enablement:
- $ref: '#/macros/longitudinal'
- key: IntelligentCruiseButtonManagement
widget: toggle
title: Intelligent Cruise Button Management (ICBM) (Alpha)
+1 -1
View File
@@ -110,7 +110,7 @@ def stats_main(end_event):
res += f",{k}={str(v)}"
res += " "
if isinstance(value, float):
if not isinstance(value, dict):
value = {'value': value}
for k, v in value.items():
@@ -11,6 +11,7 @@ and additive — they do not replace the broader test_settings_schema.py.
"""
from __future__ import annotations
import importlib
import json
import os
from typing import Any
@@ -157,7 +158,7 @@ class TestValidator(OpenpilotTestCase):
def test_validator_accepts_real_json(self):
"""settings_ui.json validates against settings_ui.schema.json."""
try:
import jsonschema
jsonschema = importlib.import_module("jsonschema")
except ImportError:
self.skipTest("jsonschema not installed")
with open(DEFINITION_PATH) as f:
+8 -1
View File
@@ -51,6 +51,7 @@ class StatLog:
def _send(self, metric: str) -> None:
if os.getpid() != self.pid:
self.connect()
assert self.sock is not None
try:
self.sock.send_string(metric, zmq.NOBLOCK)
@@ -87,6 +88,12 @@ class StatLogSP(StatLog):
self.comma_statlog.connect()
def __del__(self):
# shares zmq.Context.instance() with comma_statlog; term() blocks while any socket on it is open
if self.comma_statlog and self.comma_statlog.sock is not None:
self.comma_statlog.sock.close()
self.comma_statlog.sock = None
if self.comma_statlog.zctx is self.zctx:
self.comma_statlog.zctx = None
super().__del__()
if self.comma_statlog:
self.comma_statlog.__del__()
@@ -119,7 +126,7 @@ def main() -> NoReturn:
res += f",{k}={str(v)}"
res += " "
if isinstance(value, float):
if not isinstance(value, dict):
value = {'value': value}
for k, v in value.items():
+188 -140
View File
@@ -2,15 +2,19 @@
from __future__ import annotations
import base64
import ctypes
import fcntl
import hashlib
import itertools
import json
import math
import multiprocessing
import os
import queue
import random
import re
import select
import signal
import socket
import subprocess
import sys
@@ -18,7 +22,7 @@ import tempfile
import threading
import time
import gzip
from contextlib import suppress
from contextlib import contextmanager, suppress
from dataclasses import asdict, dataclass, replace
from datetime import datetime
from functools import partial, total_ordering
@@ -172,6 +176,7 @@ class AbortTransferException(Exception):
class UploadQueueCache:
lock = threading.Lock()
@staticmethod
def initialize(upload_queue: Queue[UploadItem]) -> None:
@@ -186,16 +191,51 @@ class UploadQueueCache:
@staticmethod
def cache(upload_queue: Queue[UploadItem]) -> None:
try:
queue: list[UploadItem | None] = list(upload_queue.queue)
items = [asdict(i) for i in queue if i is not None and (i.id not in cancelled_uploads)]
Params().put("AthenadUploadQueue", items, block=True)
with UploadQueueCache.lock: # so an older snapshot can't overwrite a newer one
# in-flight uploads too, the session can be killed at any time
items = [{**item, "current": False, "progress": 0} for item in listUploadQueue()]
Params().put("AthenadUploadQueue", items, block=True)
except Exception:
cloudlog.exception("athena.UploadQueueCache.cache.exception")
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
end_event = threading.Event()
def get_route_source() -> str | None:
# local address of the default route. connecting a UDP socket does the route lookup without sending anything
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(("8.8.8.8", 443))
return sock.getsockname()[0]
except OSError:
return None
def die_with_parent() -> None:
if sys.platform == "linux":
ctypes.CDLL(None).prctl(1, signal.SIGKILL) # PR_SET_PDEATHSIG
def fork(target: Callable, *args) -> multiprocessing.process.BaseProcess:
process = multiprocessing.get_context("fork").Process(target=target, args=args, daemon=True)
process.start()
return process
def run_session(ws_uri: str, dongle_id: str, retries: int) -> None:
# each connection gets a fresh process. killing it, like on a network change, drops all of its sockets and threads at once
die_with_parent()
start = time.monotonic()
cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri, retries=retries)
try:
ws = create_connection(ws_uri, cookie="jwt=" + Api(dongle_id).get_token(), enable_multithread=True, timeout=30.0)
except (ConnectionError, TimeoutError, WebSocketException):
sys.exit(1)
except Exception:
cloudlog.exception("athenad.main.exception")
sys.exit(1)
cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri, retries=retries, duration=time.monotonic() - start)
UploadQueueCache.initialize(upload_queue)
end_event = threading.Event()
threads = [
threading.Thread(target=ws_manage, args=(ws, end_event), name='ws_manage'),
threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'),
@@ -212,27 +252,18 @@ def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
]
for thread in threads:
thread.daemon = True
thread.start()
try:
while not end_event.wait(0.1):
if exit_event is not None and exit_event.is_set():
end_event.set()
except (KeyboardInterrupt, SystemExit):
end_event.set()
raise
finally:
for thread in threads:
cloudlog.debug(f"athena.joining {thread.name}")
thread.join()
end_event.wait() # any thread ending the session ends the process
COMMA_PROXY_URI = regex(r'wss://ssh\.comma\.ai(:(443|8443))?/[0-9a-f]{16}')
def jsonrpc_handler(end_event: threading.Event, localProxyHandler = None, proxy_uri_validator = COMMA_PROXY_URI) -> None:
handler = localProxyHandler or partial(startLocalProxy, end_event)
dispatcher.add_method(handler, name="startLocalProxy",
remote_ws_uri=proxy_uri_validator, local_port=one_of(8022, *LOCAL_PORT_WHITELIST))
if localProxyHandler is not None:
dispatcher.add_method(localProxyHandler, name="startLocalProxy",
remote_ws_uri=proxy_uri_validator, local_port=one_of(8022, *LOCAL_PORT_WHITELIST))
while not end_event.is_set():
try:
data = recv_queue.get(timeout=1)
@@ -251,37 +282,37 @@ def jsonrpc_handler(end_event: threading.Event, localProxyHandler = None, proxy_
send_queue_push(json.dumps({"error": str(e)}), SEND_PRIORITY_HIGH)
def finish_upload(tid: int) -> None:
cur_upload_items[tid] = None
UploadQueueCache.cache(upload_queue)
def retry_upload(tid: int, end_event: threading.Event, increase_count: bool = True) -> None:
item = cur_upload_items[tid]
if item is not None and item.retry_count < MAX_RETRY_COUNT:
new_retry_count = item.retry_count + 1 if increase_count else item.retry_count
item = replace(
item,
retry_count=new_retry_count,
progress=0,
current=False
)
upload_queue.put_nowait(item)
UploadQueueCache.cache(upload_queue)
retry = item is not None and item.retry_count < MAX_RETRY_COUNT
with UploadQueueCache.lock: # move it back atomically
if retry:
upload_queue.put_nowait(replace(item, retry_count=item.retry_count + increase_count, progress=0, current=False))
cur_upload_items[tid] = None
UploadQueueCache.cache(upload_queue)
if retry:
end_event.wait(RETRY_DELAY)
def cb(sm, item, tid, end_event: threading.Event, sz: int, cur: int) -> None:
def network_metered() -> bool:
# not deviceState, it lags a network change by up to 10 s. unknown might be a modem that hasn't reported in yet
network_type = HARDWARE.get_network_type()
return network_type == NetworkType.none or HARDWARE.get_network_metered(network_type)
def cb(sm, item, tid, sz: int, cur: int) -> None:
# Abort transfer if connection changed to metered after starting upload
# or if athenad is shutting down to re-connect the websocket
if not item.allow_cellular:
if (time.monotonic() - sm.recv_time['deviceState']) > DEVICE_STATE_UPDATE_INTERVAL:
sm.update(0)
if sm['deviceState'].networkMetered:
if sm['deviceState'].networkMetered and network_metered():
raise AbortTransferException
if end_event.is_set():
raise AbortTransferException
cur_upload_items[tid] = replace(item, progress=cur / sz if sz else 1)
@@ -293,21 +324,27 @@ def upload_handler(end_event: threading.Event) -> None:
cur_upload_items[tid] = None
try:
cur_upload_items[tid] = item = replace(upload_queue.get(timeout=1), current=True)
with upload_queue.not_empty: # wait for work without taking it
upload_queue.not_empty.wait_for(lambda: upload_queue.queue, timeout=1)
with UploadQueueCache.lock: # so a cache snapshot sees the item either queued or in flight
cur_upload_items[tid] = item = replace(upload_queue.get_nowait(), current=True)
if item.id in cancelled_uploads:
cancelled_uploads.remove(item.id)
with UploadQueueCache.lock: # so a cache snapshot never saves it
cur_upload_items[tid] = None
cancelled_uploads.remove(item.id)
continue
# Remove item if too old
age = datetime.now() - datetime.fromtimestamp(item.created_at / 1000)
if age.total_seconds() > MAX_AGE:
cloudlog.event("athena.upload_handler.expired", item=item, error=True)
finish_upload(tid)
continue
# Check if uploading over metered connection is allowed
sm.update(0)
metered = sm['deviceState'].networkMetered
metered = network_metered()
network_type = sm['deviceState'].networkType.raw
if metered and (not item.allow_cellular):
retry_upload(tid, end_event, False)
@@ -322,14 +359,13 @@ def upload_handler(end_event: threading.Event) -> None:
cloudlog.event("athena.upload_handler.upload_start", fn=fn, sz=sz, network_type=network_type, metered=metered, retry_count=item.retry_count)
with _do_upload(item, partial(cb, sm, item, tid, end_event)) as response:
with _do_upload(item, partial(cb, sm, item, tid)) as response:
if response.status_code not in (200, 201, 401, 403, 412):
cloudlog.event("athena.upload_handler.retry", status_code=response.status_code, fn=fn, sz=sz, network_type=network_type, metered=metered)
retry_upload(tid, end_event)
else:
cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type, metered=metered)
UploadQueueCache.cache(upload_queue)
finish_upload(tid)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.SSLError):
cloudlog.event("athena.upload_handler.timeout", fn=fn, sz=sz, network_type=network_type, metered=metered)
retry_upload(tid, end_event)
@@ -341,6 +377,7 @@ def upload_handler(end_event: threading.Event) -> None:
pass
except Exception:
cloudlog.exception("athena.upload_handler.exception")
finish_upload(tid)
def _do_upload(upload_item: UploadItem, callback: Callable | None = None) -> requests.Response:
@@ -425,6 +462,7 @@ def listDataDirectory(prefix='') -> list[str]:
class VideoClips:
"""Clip requests are files in clips/.queue, so they outlive the session process. A worker process encodes them oldest first."""
@dataclass
class Clip:
route: str
@@ -438,10 +476,32 @@ class VideoClips:
def __init__(self):
self.clip_path = os.path.join(Paths.log_root(), "clips")
self.lock = threading.Condition()
self.clips: dict[str, VideoClips.Clip] = {}
self.transcode_proc: tuple[str, subprocess.Popen] | None = None
threading.Thread(target=self._worker, name="video_clip", daemon=True).start()
self.queue_path = os.path.join(self.clip_path, ".queue")
@contextmanager
def _locked(self):
# requests are created and deleted by the session process, finished by the worker process
os.makedirs(self.queue_path, exist_ok=True)
fd = os.open(self.queue_path, os.O_RDONLY) # the directory itself, no request name can collide with it
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
os.close(fd)
def _request_path(self, filename: str) -> str:
return os.path.join(self.queue_path, filename)
def _requests(self) -> list[Clip]:
with suppress(FileNotFoundError):
clips = [clip for name in os.listdir(self.queue_path) if not name.startswith(".") and (clip := self._request(name))]
return sorted(clips, key=lambda clip: clip.requested_at)
return []
def _request(self, filename: str) -> Clip | None:
with suppress(OSError, TypeError, ValueError), open(self._request_path(filename)) as f:
return self.Clip(**json.load(f))
return None
def _encode(self, clip: Clip, inputs: Iterable[str], output_path: str, start_time: float, duration: float) -> None:
inputs = list(inputs)
@@ -460,12 +520,8 @@ class VideoClips:
str(start_time), str(duration), "--bitrate", str(clip.bitrate * 1_000_000),
"--speedup", str(clip.speedup), "--metadata", metadata, "--", *inputs]
with self.lock:
if self.clips.get(clip.filename) is not clip:
return
process = subprocess.Popen(command, stdin=subprocess.PIPE if PC else subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
self.transcode_proc = (clip.filename, process)
process = subprocess.Popen(command, stdin=subprocess.PIPE if PC else subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, preexec_fn=die_with_parent)
try:
if PC:
if process.stdin is None:
@@ -475,7 +531,10 @@ class VideoClips:
escaped_path = path.replace("'", "'\\''")
process.stdin.write(f"file 'file:{escaped_path}'\noption framerate {CAMERA_FPS}\nduration {SEGMENT_LENGTH}\n")
process.stdin.close()
process.wait()
while process.poll() is None:
if self._request(clip.filename) != clip: # deleted or replaced
process.kill() # encoderd ignores SIGTERM
time.sleep(0.5)
if process.returncode != 0:
raise RuntimeError(f"clip encoder exited with code {process.returncode}")
finally:
@@ -483,48 +542,43 @@ class VideoClips:
if process.stdin is not None:
process.stdin.close()
if process.poll() is None:
process.terminate()
process.kill()
process.wait()
with self.lock:
if self.transcode_proc is not None and self.transcode_proc[0] == clip.filename:
self.transcode_proc = None
def _worker(self) -> None:
def worker(self) -> None:
die_with_parent()
with suppress(FileNotFoundError), os.scandir(self.clip_path) as entries:
for entry in entries:
if entry.name.startswith(".") and entry.is_file():
os.unlink(entry.path) # left over from a killed encode, including encoderd's lock that blocks the deleter
while True:
with self.lock:
while not self.clips:
self.lock.wait()
clip = next(iter(self.clips.values()))
temporary_path = ""
if not (queued := self._requests()):
time.sleep(1)
continue
clip = queued[0]
temporary_path = os.path.join(self.clip_path, f".{clip.filename}")
output_path = os.path.join(self.clip_path, clip.filename)
try:
with self.lock:
if self.clips.get(clip.filename) is not clip:
continue
first_segment = math.floor(clip.source_start_time / SEGMENT_LENGTH)
inputs = (
os.path.join(Paths.log_root(), f"{clip.route}--{segment}", clip.camera)
for segment in range(first_segment, math.ceil(clip.source_end_time / SEGMENT_LENGTH))
)
os.makedirs(self.clip_path, exist_ok=True)
temporary_path = os.path.join(self.clip_path, f".{clip.filename}")
output_path = os.path.join(self.clip_path, clip.filename)
self._encode(clip, inputs, temporary_path, clip.source_start_time - first_segment * SEGMENT_LENGTH,
clip.source_end_time - clip.source_start_time)
with self.lock:
if self.clips.get(clip.filename) is clip:
with self._locked():
if self._request(clip.filename) == clip:
os.replace(temporary_path, output_path)
del self.clips[clip.filename]
os.unlink(self._request_path(clip.filename))
except Exception:
with self.lock:
failed = self.clips.get(clip.filename) is clip
if failed:
del self.clips[clip.filename]
if failed:
cloudlog.exception("athena.video_clip.failed")
with self._locked():
if self._request(clip.filename) == clip:
os.unlink(self._request_path(clip.filename))
cloudlog.exception("athena.video_clip.failed")
finally:
with suppress(OSError):
if temporary_path:
os.unlink(temporary_path)
for path in (temporary_path, f"{temporary_path}.lock"): # encoderd leaves its lock when killed
with suppress(OSError):
os.unlink(path)
def _on_disk(self) -> dict[str, dict]:
clips = {}
@@ -587,19 +641,21 @@ class VideoClips:
filename = clip["filename"]
assert camera == os.path.basename(camera) and camera.endswith("camera.hevc"), "invalid camera filename"
assert filename == os.path.basename(filename), "invalid filename"
with self.lock:
self.clips[filename] = self.Clip(route_name, camera, source_start_time, source_end_time, clip["bitrate"], clip["speedup"],
filename, datetime.now().timestamp())
self.lock.notify()
request = self.Clip(route_name, camera, source_start_time, source_end_time, clip["bitrate"], clip["speedup"],
filename, datetime.now().timestamp())
temporary_path = self._request_path(f".{filename}")
with self._locked():
with open(temporary_path, "w") as f:
json.dump(asdict(request), f)
os.replace(temporary_path, self._request_path(filename))
def getClipState(self, route: str | None = None) -> dict:
route_match = re.search(RE.ROUTE_NAME, route or "")
with self.lock:
transcode_filename = self.transcode_proc[0] if self.transcode_proc is not None else None
active_clips = {clip.filename: {**asdict(clip), "status": "encoding" if clip.filename == transcode_filename else "queued"}
for clip in self.clips.values()}
requests = self._requests() # before the disk, so a clip finishing in between isn't missed
clips = self._on_disk()
clips.update(active_clips)
for request in requests:
encoding = os.path.exists(os.path.join(self.clip_path, f".{request.filename}"))
clips[request.filename] = {**asdict(request), "status": "encoding" if encoding else "queued"}
state = {"clips": sorted(clips.values(), key=lambda clip: clip["requested_at"], reverse=True)}
if route_match is not None:
route_name = route_match.group("log_id")
@@ -608,13 +664,10 @@ class VideoClips:
def deleteClip(self, filename: str) -> None:
assert filename == os.path.basename(filename), "invalid filename"
with self.lock:
self.clips.pop(filename, None)
output_path = os.path.join(self.clip_path, filename)
if self.transcode_proc is not None and self.transcode_proc[0] == filename:
self.transcode_proc[1].terminate()
if os.path.exists(output_path):
os.unlink(output_path)
with self._locked():
for path in (self._request_path(filename), os.path.join(self.clip_path, filename)):
with suppress(FileNotFoundError):
os.unlink(path) # the worker stops encoding it
def getClipChunk(self, filename: str, offset: int) -> dict:
assert filename == os.path.basename(filename) and not filename.startswith("."), "invalid filename"
@@ -712,6 +765,7 @@ def cancelUpload(upload_id: str | list[str]) -> dict[str, int | str]:
return {"success": 0, "error": "not found"}
cancelled_uploads.update(cancelled_ids)
UploadQueueCache.cache(upload_queue)
return {"success": 1}
@dispatcher.add_method(latitude=number(-90, 90), longitude=number(-180, 180))
@@ -742,16 +796,17 @@ def setRouteViewed(route: str) -> dict[str, int | str]:
return {"success": 1}
def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]:
@dispatcher.add_method(remote_ws_uri=COMMA_PROXY_URI, local_port=one_of(8022, *LOCAL_PORT_WHITELIST))
def startLocalProxy(remote_ws_uri: str, local_port: int) -> dict[str, int]:
cloudlog.debug("athena.startLocalProxy.starting")
dongle_id = Params().get("DongleId")
identity_token = Api(dongle_id).get_token()
ws = create_connection(remote_ws_uri, cookie="jwt=" + identity_token, redirect_limit=0, enable_multithread=True)
return start_local_proxy_shim(global_end_event, local_port, ws)
return start_local_proxy_shim(None, local_port, ws)
def start_local_proxy_shim(global_end_event: threading.Event, local_port: int, ws: WebSocket) -> dict[str, int]:
def start_local_proxy_shim(global_end_event: threading.Event | None, local_port: int, ws: WebSocket) -> dict[str, int]:
try:
if ws.sock is None:
raise Exception("WebSocket is not connected")
@@ -761,6 +816,7 @@ def start_local_proxy_shim(global_end_event: threading.Event, local_port: int, w
local_port = 22
# Set TOS to keep connection responsive while under load.
assert ws.sock is not None
ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, SSH_TOS)
ssock, csock = socket.socketpair()
@@ -1026,8 +1082,9 @@ def stat_handler(end_event: threading.Event, stats_dir=None, is_sunnylink=False)
time.sleep(0.1)
def ws_proxy_recv(ws: WebSocket, local_sock: socket.socket, ssock: socket.socket, end_event: threading.Event, global_end_event: threading.Event) -> None:
while not (end_event.is_set() or global_end_event.is_set()):
def ws_proxy_recv(ws: WebSocket, local_sock: socket.socket, ssock: socket.socket, end_event: threading.Event,
global_end_event: threading.Event | None = None) -> None:
while not (end_event.is_set() or (global_end_event is not None and global_end_event.is_set())):
try:
sock = ws.sock
if sock is None:
@@ -1145,6 +1202,7 @@ def backoff(retries: int) -> int:
def main(exit_event: threading.Event | None = None):
exit_event = exit_event or threading.Event()
try:
set_core_affinity([0, 1, 2, 3])
except Exception:
@@ -1152,45 +1210,35 @@ def main(exit_event: threading.Event | None = None):
params = Params()
dongle_id = params.get("DongleId")
UploadQueueCache.initialize(upload_queue)
ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id
api = Api(dongle_id)
conn_start = None
# this process only supervises, it has no threads so forking is safe
session = route_source = None
conn_retries = 0
while exit_event is None or not exit_event.is_set():
try:
if conn_start is None:
conn_start = time.monotonic()
clip_worker = fork(video_clips.worker)
try:
while not exit_event.is_set():
if (new_source := get_route_source()) != route_source:
route_source, conn_retries = new_source, 0 # a new network starts over without backoff
cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri, retries=conn_retries)
ws = create_connection(ws_uri,
cookie="jwt=" + api.get_token(),
enable_multithread=True,
timeout=30.0)
cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri, retries=conn_retries,
duration=time.monotonic() - conn_start)
conn_start = None
conn_retries = 0
cur_upload_items.clear()
handle_long_poll(ws, exit_event)
ws.close()
except (KeyboardInterrupt, SystemExit):
break
except (ConnectionError, TimeoutError, WebSocketException):
conn_retries += 1
params.remove("LastAthenaPingTime")
except Exception:
cloudlog.exception("athenad.main.exception")
conn_retries += 1
params.remove("LastAthenaPingTime")
time.sleep(backoff(conn_retries))
session, started = fork(run_session, ws_uri, dongle_id, conn_retries), time.monotonic()
retry_at = math.inf
# back off once the session ends, but reconnect right away when the network changes
while time.monotonic() < retry_at and get_route_source() == route_source and not exit_event.wait(0.1):
if not clip_worker.is_alive():
clip_worker = fork(video_clips.worker)
if retry_at == math.inf and not session.is_alive():
# a connection that ends right away, like the server closing it, still backs off
conn_retries = 0 if session.exitcode == 0 and time.monotonic() - started > 10 else conn_retries + 1
if conn_retries:
params.remove("LastAthenaPingTime")
retry_at = time.monotonic() + backoff(conn_retries)
session.kill()
session.join()
finally:
for process in (session, clip_worker):
if process is not None:
process.kill()
if __name__ == "__main__":
+1 -1
View File
@@ -61,7 +61,7 @@ class Dispatcher(dict[str, Callable[..., Any]]):
def add_method(self, f: Callable[..., Any] | None = None, *, name: str | None = None, **validators: Validator):
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
method = name or fn.__name__
method = name or getattr(fn, '__name__', repr(fn))
sig = inspect.signature(fn)
if set(sig.parameters) != set(validators):
raise TypeError(f"{method}: params {sorted(sig.parameters)} need exactly one validator each, got {sorted(validators)}")
+62 -21
View File
@@ -9,6 +9,7 @@ import threading
import queue
from dataclasses import asdict, replace
from datetime import datetime, timedelta
from unittest import mock
from websocket import ABNF
from websocket._exceptions import WebSocketConnectionClosedException
@@ -60,7 +61,7 @@ def host():
class TestAthenadMethods(OpenpilotTestCase):
def setup_method(self):
athenad.Api = MockApi # ty: ignore[invalid-assignment] # test double
self.enterContext(mock.patch.object(athenad, "Api", MockApi))
self.default_params = {
"DongleId": "0000000000000000",
"GithubSshKeys": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501
@@ -101,14 +102,6 @@ class TestAthenadMethods(OpenpilotTestCase):
f.write(data)
return fn
@staticmethod
def _video_clips(clip):
clips = object.__new__(athenad.VideoClips)
clips.lock = threading.Condition()
clips.clips = {clip.filename: clip}
clips.transcode_proc = None
return clips
# *** test cases ***
@@ -194,7 +187,7 @@ class TestAthenadMethods(OpenpilotTestCase):
def test_video_clip_hardware_encoder(self, mocker):
clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 10, 130, 2, 4, "clip.mp4", 123)
clips = self._video_clips(clip)
clips = athenad.VideoClips()
process = mocker.Mock(stdin=None, returncode=0)
process.poll.return_value = 0
popen = mocker.patch("openpilot.system.athena.athenad.subprocess.Popen", return_value=process)
@@ -208,11 +201,10 @@ class TestAthenadMethods(OpenpilotTestCase):
"--bitrate", "2000000", "--speedup", "4", "--metadata", metadata, "--", "segment0", "segment1",
]
assert popen.call_args.kwargs["stdin"] == athenad.subprocess.DEVNULL
assert clips.transcode_proc is None
def test_video_clip_hardware_encoder_failure(self, mocker):
clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 0, 60, 1, 1, "clip.mp4", 123)
clips = self._video_clips(clip)
clips = athenad.VideoClips()
process = mocker.Mock(stdin=None, returncode=1)
process.poll.return_value = 1
mocker.patch("openpilot.system.athena.athenad.subprocess.Popen", return_value=process)
@@ -220,11 +212,10 @@ class TestAthenadMethods(OpenpilotTestCase):
with self.assertRaisesRegex(RuntimeError, "clip encoder exited with code 1"):
clips._encode(clip, ["segment"], "output.mp4", 0, 60)
assert clips.transcode_proc is None
def test_video_clip_software_fallback(self, mocker):
clip = athenad.VideoClips.Clip("route", "fcamera.hevc", 10, 30, 3, 2, "clip.mp4", 123)
clips = self._video_clips(clip)
clips = athenad.VideoClips()
stdin = mocker.Mock()
process = mocker.Mock(stdin=stdin, returncode=0)
process.poll.return_value = 0
@@ -242,6 +233,57 @@ class TestAthenadMethods(OpenpilotTestCase):
assert "file 'file:segment'\\''0'\n" in writes[1]
assert writes[-1].startswith("file 'file:segment1'")
def test_video_clip_queue(self, mocker):
def encode(self, clip, inputs, output_path, start_time, duration):
with open(output_path, "w") as f:
f.write(clip.filename)
mocker.patch.object(athenad.VideoClips, "_encode", encode)
clips = athenad.VideoClips()
for filename in ("a.mp4", "b.mp4"):
clips.createClip("0000000000000000|2021-03-29--13-32-47", 0, 60, {"camera": "fcamera.hevc", "filename": filename, "bitrate": 1, "speedup": 1})
clips.deleteClip("b.mp4")
assert [clip.filename for clip in clips._requests()] == ["a.mp4"]
# requests survive the process that made them
worker = athenad.fork(clips.worker)
try:
with Timeout(5, "clip not encoded"):
while clips._requests():
time.sleep(0.01)
finally:
worker.kill()
assert sorted(os.listdir(clips.clip_path)) == [".queue", "a.mp4"]
def test_video_clip_replaced_while_encoding(self, mocker):
class Done(BaseException):
pass
clips = athenad.VideoClips()
route = "0000000000000000|2021-03-29--13-32-47"
def encode(self, clip, inputs, output_path, start_time, duration):
if clip.source_end_time == 120:
raise Done # the worker moved on to the replacement
clips.createClip(route, 0, 120, {"camera": "fcamera.hevc", "filename": "a.mp4", "bitrate": 1, "speedup": 1})
with open(output_path, "w") as f:
f.write("stale")
mocker.patch.object(athenad.VideoClips, "_encode", encode)
mocker.patch.object(athenad, "die_with_parent")
mocker.patch.object(athenad.time, "sleep", side_effect=Done) # or the queue went idle
clips.createClip(route, 0, 60, {"camera": "fcamera.hevc", "filename": "a.mp4", "bitrate": 1, "speedup": 1})
with self.assertRaises(Done):
clips.worker()
assert not os.path.exists(os.path.join(clips.clip_path, "a.mp4"))
assert [clip.source_end_time for clip in clips._requests()] == [120]
def test_upload_cb_rechecks_stale_metered(self, mocker):
sm = mocker.MagicMock(recv_time={'deviceState': 0})
sm['deviceState'].networkMetered = True # lags a switch to wifi
item = athenad.UploadItem(path="qlog", url="http://localhost", headers={}, created_at=0, id='0' * 40)
mocker.patch.object(athenad, "network_metered", return_value=False)
athenad.cb(sm, item, 0, 10, 5)
mocker.patch.object(athenad, "network_metered", return_value=True)
with self.assertRaises(athenad.AbortTransferException):
athenad.cb(sm, item, 0, 10, 5)
def test_strip_extension(self):
# any requested log file with an invalid extension won't return as existing
fn = self._create_file('qlog.bz2')
@@ -301,7 +343,7 @@ class TestAthenadMethods(OpenpilotTestCase):
time.sleep(0.1)
# TODO: verify that upload actually succeeded
# TODO: also check that end_event and metered network raises AbortTransferException
# TODO: also check that metered network raises AbortTransferException
assert athenad.upload_queue.qsize() == 0
@parameterized.expand([(500,True), (412,False)], names=("status", "retry"))
@@ -348,9 +390,8 @@ class TestAthenadMethods(OpenpilotTestCase):
item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={},
created_at=int(time.time()*1000), id='0' * 40, allow_cellular=True) # noqa: TID251
athenad.upload_queue.put_nowait(item)
dispatcher["cancelUpload"](item.id)
assert item.id in athenad.cancelled_uploads
assert dispatcher["cancelUpload"](item.id) == {"success": 1}
assert self.params.get("AthenadUploadQueue") == []
self._wait_for_upload()
time.sleep(0.1)
@@ -368,10 +409,12 @@ class TestAthenadMethods(OpenpilotTestCase):
item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=ts, id='', allow_cellular=True)
athenad.upload_queue.put_nowait(item)
athenad.UploadQueueCache.cache(athenad.upload_queue)
self._wait_for_upload()
time.sleep(0.1)
assert athenad.upload_queue.qsize() == 0
assert self.params.get("AthenadUploadQueue") == [] # not restored by the next session
def test_list_upload_queue_empty(self):
items = dispatcher["listUploadQueue"]()
@@ -446,8 +489,6 @@ class TestAthenadMethods(OpenpilotTestCase):
assert asdict(athenad.upload_queue.queue[-1]) == asdict(item1)
def test_start_local_proxy(self, mock_create_connection, mocker):
end_event = threading.Event()
ws_recv = queue.Queue()
ws_send = queue.Queue()
mock_ws = MockWebsocket(ws_recv, ws_send)
@@ -459,7 +500,7 @@ class TestAthenadMethods(OpenpilotTestCase):
socket_thread = threading.Thread(target=echo_socket.run)
socket_thread.start()
athenad.startLocalProxy(end_event, 'ws://localhost:1234', port)
athenad.startLocalProxy('ws://localhost:1234', port)
ws_recv.put_nowait(b'ping')
try:
@@ -56,14 +56,14 @@ class TestAthenadPing(OpenpilotTestCase):
self.athenad.join()
def assertTimeout(self, reconnect_time: float, subtests, mocker) -> None:
# each connection attempt is a forked session process
mock_fork = mocker.patch.object(athenad, "fork", wraps=athenad.fork)
def sessions() -> int:
return sum(call.args[0] is athenad.run_session for call in mock_fork.call_args_list)
self.athenad.start()
mock_create_connection = mocker.patch('openpilot.system.athena.athenad.create_connection',
new_callable=lambda: mocker.MagicMock(wraps=athenad.create_connection))
time.sleep(1)
mock_create_connection.assert_called_once()
mock_create_connection.reset_mock()
assert sessions() == 1
# check normal behavior, server pings on connection
with subtests.test("Wi-Fi: receives ping"), Timeout(70, "no ping received"):
@@ -71,7 +71,7 @@ class TestAthenadPing(OpenpilotTestCase):
time.sleep(0.1)
print("ping received")
mock_create_connection.assert_not_called()
assert sessions() == 1
# websocket should attempt reconnect after short time
with subtests.test("LTE: attempt reconnect"):
@@ -79,7 +79,7 @@ class TestAthenadPing(OpenpilotTestCase):
print("waiting for reconnect attempt")
start_time = time.monotonic()
with Timeout(reconnect_time, "no reconnect attempt"):
while not mock_create_connection.called:
while sessions() == 1:
time.sleep(0.1)
print(f"reconnect attempt after {time.monotonic() - start_time:.2f}s")
+5 -1
View File
@@ -235,6 +235,7 @@ def hardware_thread(end_event, hw_queue) -> None:
in_car = False
engaged_prev = False
pwrsave = False
network_metered_prev: bool | None = None
offroad_cycle_count = 0
params = Params()
@@ -498,7 +499,10 @@ def hardware_thread(end_event, hw_queue) -> None:
except Exception:
cloudlog.exception("failed to save offroad status")
params.put_bool("NetworkMetered", msg.deviceState.networkMetered)
# a param write is a file write and two fsyncs, which keep the storage from going idle. only write on change
if msg.deviceState.networkMetered != network_metered_prev:
params.put_bool("NetworkMetered", msg.deviceState.networkMetered)
network_metered_prev = msg.deviceState.networkMetered
now_ts = time.monotonic()
if off_ts:
@@ -1,6 +1,7 @@
import os
import random
from pathlib import Path
from unittest import mock
from openpilot.common.test import OpenpilotTestCase
@@ -64,10 +65,10 @@ class UploaderTestCase(OpenpilotTestCase):
seg_dir: str
def set_ignore(self):
uploader.Api = MockApiIgnore # ty: ignore[invalid-assignment] # test double
self.enterContext(mock.patch.object(uploader, "Api", MockApiIgnore))
def setup_method(self):
uploader.Api = MockApi # ty: ignore[invalid-assignment] # test double
self.enterContext(mock.patch.object(uploader, "Api", MockApi))
uploader.fake_upload = True
uploader.force_wifi = True
uploader.allow_sleep = False
@@ -1,6 +1,7 @@
from collections import namedtuple
from pathlib import Path
from collections.abc import Sequence
from unittest import mock
import openpilot.system.loggerd.deleter as deleter
from openpilot.system.loggerd.tests.loggerd_tests_common import UploaderTestCase
@@ -21,7 +22,7 @@ class TestDeleter(UploaderTestCase):
self.f_type = "fcamera.hevc"
super().openpilot_setup_method()
self.fake_stats = Stats(f_bavail=0, f_blocks=10, f_frsize=4096)
deleter.os.statvfs = self.fake_statvfs # ty: ignore[invalid-assignment] # test double
self.enterContext(mock.patch.object(deleter.os, "statvfs", self.fake_statvfs))
def test_delete(self):
f_path = self.make_file_with_data(self.seg_dir, self.f_type)
@@ -251,6 +251,7 @@ class TestLoggerd(OpenpilotTestCase):
# next one should increment by one
bl1 = re.match(RE.LOG_ID_V2, bootlog_path.name)
bl2 = re.match(RE.LOG_ID_V2, self._gen_bootlog().name)
assert bl1 is not None and bl2 is not None
assert bl1.group('uid') != bl2.group('uid')
assert int(bl1.group('count')) == 0 and int(bl2.group('count')) == 1
+6 -5
View File
@@ -125,6 +125,8 @@ class ManagerProcess(ABC):
class NativeProcess(ManagerProcess):
launcher: Callable[..., None]
def __init__(self, name, cwd, cmdline, should_run, enabled=True):
self.name = name
self.cwd = cwd
@@ -149,6 +151,8 @@ class NativeProcess(ManagerProcess):
class PythonProcess(ManagerProcess):
launcher: Callable[..., None]
def __init__(self, name, module, should_run, enabled=True):
self.name = name
self.module = module
@@ -173,16 +177,13 @@ class PythonProcess(ManagerProcess):
class DaemonProcess(ManagerProcess):
"""Python process that has to stay running across manager restart.
This is used for athena so you don't lose SSH access when restarting manager."""
def __init__(self, name, module, param_name, enabled=True):
def __init__(self, name, module, param_name, should_run, enabled=True):
self.name = name
self.module = module
self.param_name = param_name
self.enabled = enabled
self.params = None
@staticmethod
def should_run(started, params, CP):
return True
self.should_run = should_run
def start(self) -> None:
if self.params is None:

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