mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-11-30 03:24:03 +08:00
Compare commits
231 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6c049a8dab | |||
| 64bce9668c | |||
| b6ab2aa2a7 | |||
| cb72553e68 | |||
| 1ee68c19e0 | |||
| 4886d4ff5e | |||
| 106221e913 | |||
| bcb9f1f6e1 | |||
| cd230febd6 | |||
| acedc29bc0 | |||
| afa371c088 | |||
| be6af3676f | |||
| 55b319248e | |||
| ef13da2e77 | |||
| 643012f9d4 | |||
| 7837414753 | |||
| d110c5cf57 | |||
| 6b3ac12762 | |||
| db01481db1 | |||
| 7f074bfa74 | |||
| 37a44c332d | |||
| efad504537 | |||
| 5ba10b090d | |||
| 24aba1d40f | |||
| e7d349f89f | |||
| a7c2a1f1dd | |||
| 9e9067d5cf | |||
| c86429dfd7 | |||
| f37cf702dd | |||
| bfa224d108 | |||
| c65119ce14 | |||
| 8ca7fef60d | |||
| 40aa55877c | |||
| d474328f6d | |||
| 81d479c4d2 | |||
| c162fdcc02 | |||
| e5f93ab0aa | |||
| 14bd9ef0c2 | |||
| ce4670cad4 | |||
| 9a3ab49474 | |||
| 6732fcc52a | |||
| bd02b7a6bc | |||
| fc05bc918a | |||
| 4840886df5 | |||
| 1d23066201 | |||
| 158555d9cc | |||
| 4813903daa | |||
| 6a5f37e0b4 | |||
| 07805ce214 | |||
| c410198c80 | |||
| 05c5c54f61 | |||
| e170f08049 | |||
| d8c58a323f | |||
| a5f4c3ac8a | |||
| 20acdd07c5 | |||
| 88d47a473d | |||
| 6daa874b34 | |||
| abada6315d | |||
| af90646a4a | |||
| 44a0304a54 | |||
| 4bd73298e9 | |||
| d0800d005e | |||
| ff300ecf78 | |||
| 45e522ba1a | |||
| fc5ef6ea8e | |||
| ea0223f136 | |||
| 3cbec83b36 | |||
| c0b91ba701 | |||
| f9c3aad99b | |||
| 79a255fee6 | |||
| 7fa414d659 | |||
| 929691cf67 | |||
| cd1355f0de | |||
| 03fd773f29 | |||
| d739e474a3 | |||
| 4973478a5d | |||
| 7bc336de77 | |||
| 1b09aabb6b | |||
| b1a662033f | |||
| abb9f48517 | |||
| b3ab22efe1 | |||
| 65d0961bf7 | |||
| 21f7747d35 | |||
| 9ada6b94ad | |||
| 7607bcdc68 | |||
| 29a57f9642 | |||
| d509d65712 | |||
| ef37231287 | |||
| 5eaad83ae0 | |||
| b642020a31 | |||
| ed616a1640 | |||
| 18868f3bdc | |||
| f14f4ca608 | |||
| ff5a4e5673 | |||
| 24e3379aaf | |||
| 54d95afe2d | |||
| 20536fb45d | |||
| 41de784bd3 | |||
| 083ee84e45 | |||
| c5c95d6729 | |||
| e44967322c | |||
| 4e79724ac1 | |||
| a70872f8f2 | |||
| edde587a77 | |||
| b50b804f8a | |||
| 700c43579d | |||
| ccbd8c01a7 | |||
| cec317fd39 | |||
| 77536e6e1f | |||
| 5be93bfa19 | |||
| 60085d1b40 | |||
| c80dad77da | |||
| 64596de55e | |||
| 7fd9c84746 | |||
| 8b025ff1c6 | |||
| 057e21249f | |||
| ef9a8d4a6c | |||
| 38e24dfc89 | |||
| 45d6ab3cc0 | |||
| 7b7bc80d5d | |||
| 011b357814 | |||
| 7d5647bdde | |||
| 0375b3679f | |||
| 03bd6c170c | |||
| 169d71c11f | |||
| f76de843f4 | |||
| 2897eb2fd3 | |||
| cdc79b3d0d | |||
| 479baf9191 | |||
| 87eee9c220 | |||
| 018b69f1fa | |||
| 5ea8c4c733 | |||
| 440c6684a4 | |||
| 7680fa617a | |||
| 7e5662a4db | |||
| 49ac522fea | |||
| d2200f170e | |||
| 99e869d377 | |||
| c089b82d95 | |||
| 05c1611019 | |||
| 090d1c825f | |||
| 1c0851f490 | |||
| 945de35418 | |||
| 903260a25c | |||
| 7786e59279 | |||
| f5dfddb72a | |||
| ac17dbac0f | |||
| 011256612c | |||
| 0a745f9f33 | |||
| b9fa0a1aef | |||
| ce4a019af3 | |||
| 3fbd4ea0bf | |||
| 20895c40e5 | |||
| 1e96c7ea8b | |||
| 59edbba300 | |||
| 073e2a6168 | |||
| e04c08d367 | |||
| 2c8be4825a | |||
| d5e08fc3d0 | |||
| 89e7e0a4c4 | |||
| 2ddefe2e16 | |||
| 4b20c34e51 | |||
| b92fc48286 | |||
| 493ae5ad0e | |||
| ab1a112ce4 | |||
| b181224142 | |||
| af6622c310 | |||
| 070de2aefc | |||
| 43d648094c | |||
| 4c7439c598 | |||
| 9a12b5c42f | |||
| 6537be2552 | |||
| 98dbeb1811 | |||
| e60f535fa9 | |||
| 00ab7b32e0 | |||
| 12c9157d84 | |||
| b614827c61 | |||
| 20d34be6a4 | |||
| 31a0ee6b94 | |||
| 9464d2ef68 | |||
| ad4c9cdf18 | |||
| 0c40995cd7 | |||
| c8ff7f7815 | |||
| 56f702dbf5 | |||
| 086a8a5023 | |||
| 54ce79f01e | |||
| 96ca6759e2 | |||
| 8d5d764dce | |||
| 904bb691f5 | |||
| 958b5cbde0 | |||
| c651a3465b | |||
| f1b344b781 | |||
| 5384c06b3d | |||
| 4d5d6c47ae | |||
| eaadb5a75d | |||
| 880b40e192 | |||
| afedebcfd4 | |||
| 0152aab4a4 | |||
| 8ba9f4baee | |||
| 371e4ef888 | |||
| e376168818 | |||
| a802a4b041 | |||
| ef03ef80f9 | |||
| ef317505db | |||
| 14652aacb2 | |||
| 335ea25754 | |||
| be1e3c7908 | |||
| a0ac948b3f | |||
| fa8babd944 | |||
| 9fba666fd4 | |||
| f2f9d5d420 | |||
| 730c7c663a | |||
| ff47f484e6 | |||
| 6f68efea69 | |||
| 8d10a9deb6 | |||
| 079cd47296 | |||
| 34d4241e19 | |||
| 815a90f606 | |||
| d486c143aa | |||
| 06ed8252da | |||
| 9c6887c611 | |||
| ef4b6cc788 | |||
| 1ace967a7e | |||
| b7b4bb22b2 | |||
| 2ab952d5eb | |||
| 6b592ae2cc | |||
| 53498bbbdc | |||
| b1e88c2357 | |||
| d0198e0203 | |||
| 8eed21e499 | |||
| 6d7d4872e8 |
@@ -11,6 +11,7 @@ openpilot/sunnypilot/modeld_v2/models/*.pkl filter=lfs diff=lfs merge=lfs -text
|
||||
*.ttf filter=lfs diff=lfs merge=lfs -text
|
||||
*.otf filter=lfs diff=lfs merge=lfs -text
|
||||
*.wav filter=lfs diff=lfs merge=lfs -text
|
||||
*.npz filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
openpilot/selfdrive/car/tests/test_models_segs.txt filter=lfs diff=lfs merge=lfs -text
|
||||
openpilot/common/hardware/comma/updater filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
ci:
|
||||
- changed-files:
|
||||
- any-glob-to-all-files: "{.github/**,**/test_*,**/test/**,Jenkinsfile}"
|
||||
- any-glob-to-all-files: "{.github/**,**/test_*,**/test/**}"
|
||||
|
||||
chore:
|
||||
- changed-files:
|
||||
|
||||
@@ -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
|
||||
@@ -77,9 +77,8 @@ jobs:
|
||||
build_small_model:
|
||||
needs: resolve
|
||||
if: ${{ inputs.target == 'small' }}
|
||||
runs-on: [self-hosted, tici]
|
||||
runs-on: ubuntu-24.04-arm
|
||||
env:
|
||||
MODELS_DIR: openpilot/selfdrive/modeld/models
|
||||
COMPILER: tinygrad_repo/examples/openpilot
|
||||
SMALL_ONNX: openpilot/selfdrive/modeld/models/driving_supercombo.onnx
|
||||
SMALL_PKL: openpilot/selfdrive/modeld/models/driving_tinygrad.pkl
|
||||
@@ -89,39 +88,30 @@ jobs:
|
||||
submodules: recursive
|
||||
|
||||
- name: Pull small ONNX via LFS
|
||||
run: git lfs pull -I "${{ env.SMALL_ONNX }}"
|
||||
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
source /etc/profile
|
||||
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
|
||||
uv sync --frozen
|
||||
printenv >> $GITHUB_ENV
|
||||
|
||||
- name: Disable powersave
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
|
||||
- name: Set up the qcom mock
|
||||
uses: ./.github/workflows/setup-qcom-mock
|
||||
with:
|
||||
hf_token: ${{ secrets.HF_TOKEN }}
|
||||
|
||||
- name: Compile small model from ONNX
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
env ${TG_FLAGS} python3 ${{ github.workspace }}/${{ env.COMPILER }}/compile_onnx.py \
|
||||
${{ github.workspace }}/${{ env.SMALL_ONNX }} \
|
||||
${{ github.workspace }}/${{ env.SMALL_PKL }} \
|
||||
--out-of-band --benchmark-runs 1
|
||||
--out-of-band --benchmark-runs 0
|
||||
|
||||
- name: Prepare output
|
||||
env:
|
||||
MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }}
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH=${{ github.workspace }}
|
||||
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
|
||||
OUTPUT_DIR="${{ github.workspace }}/small_output"
|
||||
@@ -153,19 +143,11 @@ jobs:
|
||||
name: artifact-name-${{ needs.resolve.outputs.safe_model_name }}
|
||||
path: ${{ github.workspace }}/small_output/artifact_name.txt
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
|
||||
build_big_model:
|
||||
needs: resolve
|
||||
if: ${{ inputs.target == 'big' }}
|
||||
runs-on: [self-hosted, chestnut]
|
||||
runs-on: ubuntu-24.04
|
||||
env:
|
||||
MODELS_DIR: openpilot/selfdrive/modeld/models
|
||||
COMPILER: tinygrad_repo/examples/openpilot
|
||||
BIG_PKL: openpilot/selfdrive/modeld/models/big_driving_tinygrad.pkl
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -173,72 +155,23 @@ jobs:
|
||||
submodules: recursive
|
||||
|
||||
- name: Pull big PKL via LFS
|
||||
run: git lfs pull -I "${{ env.BIG_PKL }}"
|
||||
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
source /etc/profile
|
||||
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
|
||||
uv sync --frozen
|
||||
printenv >> $GITHUB_ENV
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Disable powersave
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock
|
||||
uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: big-warp
|
||||
|
||||
- name: Wait for chestnut PCIe link
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
python3 -c "
|
||||
import time
|
||||
from openpilot.system.hardware.chestnut.flash import link_up
|
||||
for i in range(10):
|
||||
if link_up():
|
||||
print(f'PCIe link up after {i+1} attempt(s)')
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError('Chestnut PCIe link not ready after 10 attempts')
|
||||
"
|
||||
|
||||
- name: Compile big warp
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${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 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"
|
||||
env ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
|
||||
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
|
||||
--warp-to ${MODEL_SIZE} \
|
||||
--layout yuv420 \
|
||||
--frames 2 \
|
||||
--output "${WARP_PKL}"
|
||||
done
|
||||
- uses: ./.github/workflows/big-warp
|
||||
|
||||
- name: Prepare output
|
||||
env:
|
||||
MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }}
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH=${{ github.workspace }}
|
||||
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
|
||||
OUTPUT_DIR="${{ github.workspace }}/big_output"
|
||||
@@ -272,12 +205,6 @@ jobs:
|
||||
name: artifact-name-${{ needs.resolve.outputs.safe_model_name }}
|
||||
path: ${{ github.workspace }}/big_output/artifact_name.txt
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
|
||||
upload_defaults:
|
||||
needs: [ resolve, build_small_model, build_big_model, build_dm_model ]
|
||||
if: |
|
||||
@@ -296,7 +223,7 @@ jobs:
|
||||
|
||||
- name: Pull LFS for resolved ONNX files
|
||||
if: ${{ needs.resolve.outputs.onnx_path != '' }}
|
||||
run: git lfs pull -I "${{ needs.resolve.outputs.onnx_path }}"
|
||||
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
|
||||
|
||||
- name: Install huggingface_hub
|
||||
run: pip install --upgrade "huggingface_hub>=0.22.0"
|
||||
@@ -405,7 +332,7 @@ jobs:
|
||||
build_dm_model:
|
||||
needs: resolve
|
||||
if: ${{ inputs.target == 'dm' }}
|
||||
runs-on: [self-hosted, tici]
|
||||
runs-on: ubuntu-24.04-arm
|
||||
env:
|
||||
DM_ONNX: openpilot/selfdrive/modeld/models/dmonitoring_model.onnx
|
||||
DM_PKL: openpilot/selfdrive/modeld/models/dmonitoring_model_tinygrad.pkl
|
||||
@@ -415,42 +342,34 @@ jobs:
|
||||
submodules: recursive
|
||||
|
||||
- name: Pull DM ONNX via LFS
|
||||
run: git lfs pull -I "${{ env.DM_ONNX }}"
|
||||
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
source /etc/profile
|
||||
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
|
||||
uv sync --frozen
|
||||
printenv >> $GITHUB_ENV
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Disable powersave
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
|
||||
- name: Set up the qcom mock
|
||||
uses: ./.github/workflows/setup-qcom-mock
|
||||
with:
|
||||
hf_token: ${{ secrets.HF_TOKEN }}
|
||||
|
||||
- name: Compile DM model
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
|
||||
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
|
||||
taskset -c 7 env ${TG_FLAGS} python3 \
|
||||
env ${TG_FLAGS} python3 \
|
||||
${{ github.workspace }}/tinygrad_repo/examples/openpilot/compile_onnx.py \
|
||||
${{ github.workspace }}/${{ env.DM_ONNX }} \
|
||||
${{ github.workspace }}/${{ env.DM_PKL }} \
|
||||
--out-of-band --benchmark-runs 1
|
||||
--out-of-band --benchmark-runs 0
|
||||
|
||||
- name: Compile DM warp
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
|
||||
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
|
||||
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
|
||||
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
|
||||
DM_SIZE=$(python3 -c "from openpilot.common.transformations.model import DM_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
|
||||
@@ -465,12 +384,13 @@ jobs:
|
||||
print(f'{s},{y},{u},{sz}')
|
||||
" $CAM_W $CAM_H)
|
||||
WARP_PKL="${MODELS_DIR}/dm_warp_${res}_tinygrad.pkl"
|
||||
taskset -c 7 env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
|
||||
env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
|
||||
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
|
||||
--warp-to ${DM_SIZE} \
|
||||
--layout luma \
|
||||
--border-fill 16 \
|
||||
--transform-device NPY \
|
||||
--benchmark-runs 0 \
|
||||
--output "${WARP_PKL}"
|
||||
done
|
||||
|
||||
@@ -485,9 +405,3 @@ jobs:
|
||||
with:
|
||||
name: dm-model-${{ github.run_number }}
|
||||
path: dm_output/
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
|
||||
@@ -11,6 +11,11 @@ on:
|
||||
description: 'Custom name for the model (no date, only name)'
|
||||
required: false
|
||||
type: string
|
||||
from_sunnypilot:
|
||||
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
recompiled_dir:
|
||||
description: 'Existing recompiled directory number (e.g. 1 for recompiled1)'
|
||||
required: true
|
||||
@@ -62,6 +67,11 @@ on:
|
||||
description: 'Custom name for the model (no date, only name)'
|
||||
required: false
|
||||
type: string
|
||||
from_sunnypilot:
|
||||
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
is_20hz:
|
||||
description: 'Is this a 20Hz model'
|
||||
required: false
|
||||
@@ -85,7 +95,7 @@ on:
|
||||
- Release Models
|
||||
- 2026 World Models
|
||||
- 2026 Deep RL Models
|
||||
- Custom Merge Models
|
||||
- Custom sunnypilot Models
|
||||
- Other
|
||||
custom_model_folder:
|
||||
description: 'Custom model folder name (if "Other" selected)'
|
||||
@@ -127,6 +137,7 @@ jobs:
|
||||
with:
|
||||
upstream_branch: ${{ inputs.upstream_branch }}
|
||||
custom_name: ${{ inputs.custom_name || inputs.upstream_branch }}
|
||||
from_sunnypilot: ${{ inputs.from_sunnypilot || false }}
|
||||
is_20hz: ${{ inputs.is_20hz }}
|
||||
artifact_suffix: ${{ inputs.artifact_suffix }}
|
||||
target_hardware: ${{ inputs.target_hardware }}
|
||||
|
||||
@@ -3,58 +3,87 @@ name: Compile warp for sunnypilot modeld
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
WARP_DIR: openpilot/sunnypilot/modeld_v2/models
|
||||
|
||||
jobs:
|
||||
compile_warps:
|
||||
runs-on: [self-hosted, chestnut]
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- target: qcom
|
||||
runs-on: ubuntu-24.04-arm
|
||||
prefix: driving_warp
|
||||
flags: DEV=MOCK+QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1
|
||||
args: --split-frames
|
||||
- target: chestnut
|
||||
runs-on: ubuntu-24.04
|
||||
prefix: big_driving_warp
|
||||
flags: DEV=MOCKUSB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32
|
||||
args: ''
|
||||
runs-on: ${{ matrix.runs-on }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
source /etc/profile
|
||||
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
|
||||
uv sync --frozen
|
||||
printenv >> $GITHUB_ENV
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Disable powersave
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
|
||||
- name: Set up the qcom mock
|
||||
if: matrix.target == 'qcom'
|
||||
uses: ./.github/workflows/setup-qcom-mock
|
||||
with:
|
||||
hf_token: ${{ secrets.HF_TOKEN }}
|
||||
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock
|
||||
if: matrix.target == 'chestnut'
|
||||
uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: warp
|
||||
|
||||
- name: Install the amd mock build dependencies
|
||||
if: matrix.target == 'chestnut'
|
||||
run: python3 -m pip install -q numpy zstandard
|
||||
|
||||
- name: Compile Warp Kernels
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
mkdir -p openpilot/sunnypilot/modeld_v2/models/
|
||||
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
|
||||
mkdir -p "$WARP_DIR"
|
||||
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
|
||||
CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')")
|
||||
echo "Model size: $MODEL_SIZE"
|
||||
echo "Camera resolutions: $CAMERA_RES"
|
||||
|
||||
for res in $CAMERA_RES; do
|
||||
FRAME_PARAM=$(python3 -c "from openpilot.system.camerad.cameras.nv12_info import get_nv12_info; w, h = map(int, '${res}'.split('x')); stride, y_h, uv_h, _ = get_nv12_info(w, h); print(f'{w},{h},{stride},{y_h},{uv_h},{stride * (y_h + uv_h)}')")
|
||||
|
||||
WARP_PKL="openpilot/sunnypilot/modeld_v2/models/driving_warp_${res}_tinygrad.pkl"
|
||||
echo "Compiling $WARP_PKL on QCOM"
|
||||
taskset -c 7 env DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
|
||||
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --split-frames --output "${WARP_PKL}"
|
||||
|
||||
BIG_WARP_PKL="openpilot/sunnypilot/modeld_v2/models/big_driving_warp_${res}_tinygrad.pkl"
|
||||
echo "Compiling $BIG_WARP_PKL on AMD"
|
||||
taskset -c 7 env DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
|
||||
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --output "${BIG_WARP_PKL}"
|
||||
WARP_PKL="$WARP_DIR/${{ matrix.prefix }}_${res}_tinygrad.pkl"
|
||||
echo "Compiling $WARP_PKL"
|
||||
env ${{ matrix.flags }} python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
|
||||
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} ${{ matrix.args }} --output "${WARP_PKL}"
|
||||
done
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
- name: Replay their check frames on the mock and require the result bit for bit
|
||||
env:
|
||||
DEV: ${{ matrix.target == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }}
|
||||
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$WARP_DIR"/${{ matrix.prefix }}_*_tinygrad.pkl
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: warps-${{ matrix.target }}
|
||||
path: ${{ env.WARP_DIR }}/${{ matrix.prefix }}_*_tinygrad.pkl
|
||||
if-no-files-found: error
|
||||
|
||||
create_pr:
|
||||
needs: compile_warps
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: warps-*
|
||||
path: ${{ env.WARP_DIR }}
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
&& fromJSON('["namespace-profile-amd64-8x16"]')
|
||||
|| fromJSON('["ubuntu-24.04"]') }}
|
||||
steps:
|
||||
- uses: commaai/timeout@v1
|
||||
#- uses: commaai/timeout@v1 # TODO: figure out how to re-enable this. uv download is super slow right now...
|
||||
- uses: actions/checkout@v7
|
||||
- run: ./tools/op.sh setup
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
name: Sync comma's LFS
|
||||
|
||||
# Mirrors the LFS objects of upstream's tip from comma's HF bucket into sunnypilot's,
|
||||
# so lfs.py clients (devices, CI) find every object in one bucket.
|
||||
env:
|
||||
LFS_URL: 'https://huggingface.co/sunnypilot/sunnypilot-lfs.git/info/lfs'
|
||||
LFS_PUSH_URL: 'https://huggingface.co/sunnypilot/sunnypilot-lfs.git/info/lfs'
|
||||
UPSTREAM_BUCKET: 'commaai/openpilot-lfs'
|
||||
SUNNYPILOT_BUCKET: 'sunnypilot/sunnypilot-lfs'
|
||||
|
||||
on:
|
||||
schedule:
|
||||
@@ -25,137 +27,57 @@ jobs:
|
||||
# Skip if PR is in draft mode
|
||||
if: (github.event_name != 'pull_request' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false)) && !github.event.pull_request.head.repo.fork
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
- name: Checkout upstream
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'commaai/openpilot'
|
||||
ref: ${{ inputs.upstream_branch }}
|
||||
|
||||
- name: LFS Fetch
|
||||
run: |
|
||||
git lfs fetch || echo "::warning::some objects are missing on commaai/openpilot-lfs; mirroring the rest"
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
git config --global user.name 'GitHub Action'
|
||||
git config --global user.email 'action@github.com'
|
||||
|
||||
- name: Setup hf
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: |
|
||||
git config --global credential.helper store
|
||||
echo "https://user:${HF_TOKEN}@huggingface.co" > ~/.git-credentials
|
||||
|
||||
- name: Ensure branch
|
||||
run: |
|
||||
if git symbolic-ref -q HEAD >/dev/null; then
|
||||
echo "Already on a branch, proceeding with push"
|
||||
else
|
||||
echo "Detached HEAD state detected, creating temporary branch"
|
||||
git checkout -b temp_branch
|
||||
fi
|
||||
|
||||
- name: Update LFS Config
|
||||
run: |
|
||||
echo '[lfs]' > .lfsconfig
|
||||
echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig
|
||||
echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig
|
||||
echo ' locksverify = false' >> .lfsconfig
|
||||
|
||||
- name: Configure LFS transfer settings
|
||||
run: |
|
||||
git config lfs.activitytimeout 300
|
||||
git config lfs.transfer.maxretries 5
|
||||
git config lfs.concurrenttransfers 4
|
||||
git config lfs.allowincompletepush true
|
||||
|
||||
- name: Push LFS
|
||||
id: sync-and-commit
|
||||
run: |
|
||||
git lfs ls-files -l
|
||||
for attempt in 1 2 3; do
|
||||
echo "Push attempt $attempt..."
|
||||
git lfs push --all origin && exit 0
|
||||
echo "Attempt $attempt failed, retrying in 30s..."
|
||||
sleep 30
|
||||
done
|
||||
echo "All push attempts failed"
|
||||
exit 1
|
||||
|
||||
- name: Checkout sunnypilot
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'sunnypilot/sunnypilot'
|
||||
path: sunnypilot
|
||||
fetch-depth: 0
|
||||
filter: blob:limit=1k
|
||||
lfs: false
|
||||
|
||||
- name: Reference objects on sunnypilot-lfs
|
||||
- name: Install hf-xet
|
||||
run: |
|
||||
python3 -m venv "$RUNNER_TEMP/lfs-venv"
|
||||
"$RUNNER_TEMP/lfs-venv/bin/pip" install -q hf-xet==1.7.0
|
||||
echo "$RUNNER_TEMP/lfs-venv/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Fetch from comma's bucket
|
||||
run: OPENPILOT_LFS_BUCKET="$UPSTREAM_BUCKET" ./lfs.py pull --exclude=''
|
||||
|
||||
- name: Upload to sunnypilot's bucket
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
GIT_LFS_SKIP_SMUDGE=1 git clone --quiet https://huggingface.co/sunnypilot/sunnypilot-lfs hf-lfs
|
||||
mkdir -p hf-lfs/all
|
||||
cat > scan_pointers.py <<'EOF'
|
||||
import re, subprocess, sys, threading
|
||||
repo = sys.argv[1]
|
||||
chk = subprocess.run(["git", "-C", repo, "cat-file", "--batch-all-objects",
|
||||
"--batch-check=%(objectname) %(objecttype) %(objectsize)"],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
small = [f[0] for f in (l.split() for l in chk.splitlines()) if f[1] == "blob" and int(f[2]) < 1024]
|
||||
p = subprocess.Popen(["git", "-C", repo, "cat-file", "--batch=%(objectsize)"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||
def feed():
|
||||
for sha in small:
|
||||
p.stdin.write(sha.encode() + b"\n")
|
||||
p.stdin.close()
|
||||
threading.Thread(target=feed, daemon=True).start()
|
||||
rx = re.compile(rb"^version https://git-lfs\.github\.com/spec/v1\noid sha256:([0-9a-f]{64})\nsize ([0-9]+)\n")
|
||||
seen = {}
|
||||
for _ in small:
|
||||
n = int(p.stdout.readline()); body = p.stdout.read(n); p.stdout.read(1)
|
||||
m = rx.match(body)
|
||||
if m:
|
||||
seen.setdefault(m.group(1).decode(), m.group(2).decode())
|
||||
for oid, size in sorted(seen.items()):
|
||||
print(oid, size)
|
||||
EOF
|
||||
for repo in . sunnypilot; do
|
||||
python3 scan_pointers.py "$repo"
|
||||
done | sort -u | while read -r oid size; do
|
||||
[ -e "hf-lfs/all/$oid" ] && continue
|
||||
printf 'version https://git-lfs.github.com/spec/v1\noid sha256:%s\nsize %s\n' "$oid" "$size" > "hf-lfs/all/$oid"
|
||||
echo "$oid"
|
||||
done > new_oids.txt
|
||||
echo "new pointer files: $(wc -l < new_oids.txt)"
|
||||
OPENPILOT_LFS_BUCKET="$SUNNYPILOT_BUCKET" python3 -c "
|
||||
import lfs
|
||||
objects = list(lfs.pointers_for_index())
|
||||
lfs.upload(objects)
|
||||
print(f'{len(objects)} objects present in {lfs.BUCKET}')
|
||||
"
|
||||
|
||||
dropped=0
|
||||
while mapfile -t -n 100 chunk && ((${#chunk[@]})); do
|
||||
body=$(for oid in "${chunk[@]}"; do
|
||||
size=$(awk '/^size /{print $2}' "hf-lfs/all/$oid")
|
||||
printf '{"oid":"%s","size":%s}\n' "$oid" "$size"
|
||||
done | jq -s '{operation:"download",transfers:["basic"],objects:.}')
|
||||
for attempt in 1 2 3 4 5; do
|
||||
resp=$(curl -sS -u "user:${HF_TOKEN}" -w '\n%{http_code}' \
|
||||
-H 'Accept: application/vnd.git-lfs+json' -H 'Content-Type: application/vnd.git-lfs+json' \
|
||||
--data "$body" "${LFS_URL}/objects/batch") && [ "$(tail -n1 <<<"$resp")" = 200 ] && break
|
||||
echo "batch check attempt $attempt failed ($(tail -n1 <<<"$resp")), retrying in 60s"; sleep 60
|
||||
done
|
||||
[ "$(tail -n1 <<<"$resp")" = 200 ] || { echo "batch check failed"; exit 1; }
|
||||
for oid in $(sed '$d' <<<"$resp" | jq -r '.objects[] | select(.error) | .oid'); do
|
||||
rm -f "hf-lfs/all/$oid"; dropped=$((dropped+1))
|
||||
done
|
||||
done < new_oids.txt
|
||||
echo "dropped (not on HF): $dropped"
|
||||
mirror-git-lfs:
|
||||
# Clients still on git-lfs (devices on an older updater) fetch from the .lfsconfig model repo, which lfs.py never uploads to
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
lfs: false
|
||||
|
||||
cd hf-lfs
|
||||
git add -A all
|
||||
if git diff --cached --quiet; then
|
||||
echo "nothing new to reference"
|
||||
exit 0
|
||||
fi
|
||||
git commit -q -m "Reference $(git diff --cached --name-only | wc -l | tr -d ' ') new LFS objects"
|
||||
git push origin HEAD:main
|
||||
- name: Fetch what the model repo lacks from sunnypilot's bucket
|
||||
run: |
|
||||
python3 -c "
|
||||
import lfs
|
||||
objects = dict(lfs.pointers_for_index().keys())
|
||||
missing = sorted(objects.keys() - lfs.endpoint_objects(objects).keys())
|
||||
lfs.parallel(lfs.download_one, [(oid, objects[oid]) for oid in missing])
|
||||
for oid in missing:
|
||||
print(oid)
|
||||
" > missing.txt
|
||||
echo "$(wc -l < missing.txt) objects missing from the model repo"
|
||||
|
||||
- name: Upload to the model repo
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: |
|
||||
git config --global credential.https://huggingface.co.helper '!f() { echo username=hf; echo "password=$HF_TOKEN"; }; f'
|
||||
xargs -r git lfs push --object-id origin < missing.txt
|
||||
|
||||
@@ -36,5 +36,5 @@ jobs:
|
||||
run: BRANCH=__nightly tools/release/build_stripped.sh
|
||||
- name: Push chestnut nightly
|
||||
run: |
|
||||
git lfs pull --exclude=''
|
||||
./lfs.py pull --exclude=''
|
||||
INCLUDE_BIG_MODEL=1 BRANCH=__nightly-chestnut tools/release/build_stripped.sh
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Set up tinygrad's amd mock
|
||||
description: LLVM 20 and ROCm comgr, as tinygrad_repo/.github/actions/setup-tinygrad installs them for the mock gpu
|
||||
inputs:
|
||||
emu_cache:
|
||||
description: >-
|
||||
Keep tinygrad's cache db (the emulator's compiled kernels and gate results) between runs under this name, e.g. the model's file name.
|
||||
Empty: no cache.
|
||||
default: ''
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install LLVM 20 and ROCm comgr
|
||||
shell: bash
|
||||
run: |
|
||||
. /etc/os-release
|
||||
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
|
||||
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
|
||||
sudo mkdir -p /etc/apt/keyrings
|
||||
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
|
||||
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
|
||||
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
|
||||
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
|
||||
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
|
||||
llvm=$(ls /usr/lib/llvm-20/lib/libLLVM*.so* /usr/lib/*-linux-gnu/libLLVM-20.so* 2>/dev/null | head -1 || true)
|
||||
[ -n "$llvm" ] || { echo "::error::libLLVM 20 not found"; exit 1; }
|
||||
echo "LLVM_PATH=$llvm" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache the chestnut's firmware
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/tinygrad/downloads/fw
|
||||
key: chestnut-fw-${{ hashFiles('tinygrad_repo/tinygrad/runtime/autogen/am/fw.py') }}
|
||||
|
||||
- name: Fetch the chestnut's firmware (gitlab times out now and then; the mock boots from it)
|
||||
shell: bash
|
||||
run: |
|
||||
for i in 1 2 3 4 5; do
|
||||
PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "
|
||||
from tinygrad.helpers import fetch_fw
|
||||
from tinygrad.runtime.autogen.am import fw
|
||||
for n, h in fw.hashes.items():
|
||||
if n.startswith(('psp_14_0_2_', 'smu_14_0_2.', 'sdma_7_0_0.', 'gc_12_0_0_')): fetch_fw('amdgpu', n, h)" && exit 0
|
||||
sleep $((i * 10))
|
||||
done
|
||||
echo "::error::could not fetch the chestnut's firmware from gitlab"; exit 1
|
||||
|
||||
- name: runner cpu
|
||||
if: inputs.emu_cache != ''
|
||||
id: cpu
|
||||
shell: bash
|
||||
run: echo "cpu=$( (grep -m1 '^model name' /proc/cpuinfo; grep -m1 '^flags' /proc/cpuinfo) | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Keep the emulator's compiled kernels between runs
|
||||
if: inputs.emu_cache != ''
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/tinygrad/cache.db
|
||||
key: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-${{ inputs.emu_cache }}
|
||||
restore-keys: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-
|
||||
@@ -0,0 +1,62 @@
|
||||
name: Set up tinygrad's qcom mock
|
||||
description: The a630 compiler, checked against what an a630 compiled, and the kernels earlier builds compiled
|
||||
inputs:
|
||||
hf_token:
|
||||
description: Records a passed compiler check on HF so the next build skips it
|
||||
default: ''
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install the qcom mock build dependencies
|
||||
id: deps
|
||||
shell: bash
|
||||
run: |
|
||||
python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2
|
||||
if [ "$RUNNER_ARCH" = ARM64 ]; then # the qcomcl rootfs's compiler loads in this python, no qemu
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends aria2
|
||||
FS=$(PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "from tinygrad.helpers import fetch; print(fetch('https://git.tinygrad.win/tinygrad/images/releases/download/v2/qcomcl.tar.gz', extract=True))")
|
||||
echo "LLVM_QCOM_PATH=$FS/usr/lib/libllvm-qcom.so" >> "$GITHUB_ENV"
|
||||
echo "compiler=native-$(sha256sum "$FS/usr/lib/libllvm-qcom.so" | cut -c1-16)" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2
|
||||
echo "compiler=qemu-$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Compiler check passed before with all of it identical?
|
||||
id: compiler
|
||||
shell: bash
|
||||
env:
|
||||
KEY: qcom-compiler-parity-${{ steps.deps.outputs.compiler }}-${{ hashFiles('tinygrad_repo/test/device/qcom/compiler_parity.py', 'tinygrad_repo/test/mockgpu/qcom/a630_compiled.pkl.xz', 'tinygrad_repo/tinygrad/runtime/support/compiler_qcom.py') }}
|
||||
run: |
|
||||
MARKER="ci/qcom-compiler-parity/$(printf '%s' "$KEY" | tr -c 'A-Za-z0-9._-' '_').txt"
|
||||
CODE=$(curl -s -o /dev/null -w '%{http_code}' -I -L "https://huggingface.co/datasets/sunnypilot/sunnypilot_models_v1/resolve/main/$MARKER")
|
||||
echo "$MARKER: HTTP $CODE"
|
||||
{ echo "key=$KEY"; echo "marker=$MARKER"; echo "passed=$([ "$CODE" = 200 ] && echo true || echo false)"; } >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Check the off-device qcom compiler builds the a630's bytes
|
||||
if: steps.compiler.outputs.passed != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
# every kernel an a630 has compiled must compile to the same bytes here before a model is built here
|
||||
TG="$GITHUB_WORKSPACE/tinygrad_repo"
|
||||
PYTHONPATH="$TG" python3 "$TG/test/device/qcom/compiler_parity.py" check "$TG/test/mockgpu/qcom/a630_compiled.pkl.xz"
|
||||
|
||||
- name: Remember the compiler check passed
|
||||
if: steps.compiler.outputs.passed != 'true' && inputs.hf_token != ''
|
||||
shell: bash
|
||||
env:
|
||||
HF_TOKEN: ${{ inputs.hf_token }}
|
||||
KEY: ${{ steps.compiler.outputs.key }}
|
||||
MARKER: ${{ steps.compiler.outputs.marker }}
|
||||
run: |
|
||||
python3 -m pip install -q --upgrade "huggingface_hub>=0.34"
|
||||
printf '%s\n%s\n' "$KEY" "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" > "$RUNNER_TEMP/marker.txt"
|
||||
hf upload --repo-type dataset sunnypilot/sunnypilot_models_v1 "$RUNNER_TEMP/marker.txt" "$MARKER" \
|
||||
--commit-message "qcom compiler parity passed: $KEY" || echo "::warning::could not record the pass, the next build checks again"
|
||||
|
||||
- name: Kernels compiled by earlier builds
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/tinygrad/cache.db
|
||||
key: qcom-kernels-${{ steps.compiler.outputs.key }}-${{ github.run_id }}
|
||||
restore-keys: qcom-kernels-${{ steps.compiler.outputs.key }}-
|
||||
@@ -1,9 +1,7 @@
|
||||
name: Build Model from Upstream
|
||||
|
||||
env:
|
||||
BUILD_DIR: "/data/openpilot"
|
||||
OUTPUT_DIR: ${{ github.workspace }}/output
|
||||
SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache
|
||||
UPSTREAM_REPO: "commaai/openpilot"
|
||||
TINYGRAD_PATH: ${{ github.workspace }}/tinygrad_repo
|
||||
MODELS_DIR: ${{ github.workspace }}/openpilot/selfdrive/modeld/models
|
||||
@@ -20,6 +18,11 @@ on:
|
||||
description: 'Custom name for the model (no date, only name)'
|
||||
required: false
|
||||
type: string
|
||||
from_sunnypilot:
|
||||
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
is_20hz:
|
||||
description: 'Is this a 20Hz model'
|
||||
required: false
|
||||
@@ -46,6 +49,11 @@ on:
|
||||
description: 'Custom name for the model (no date, only name)'
|
||||
required: false
|
||||
type: string
|
||||
from_sunnypilot:
|
||||
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
is_20hz:
|
||||
description: 'Is this a 20Hz model'
|
||||
required: false
|
||||
@@ -74,6 +82,7 @@ jobs:
|
||||
# Note: To allow dynamic models from both openpilot and sunnypilot (merges/mashups), we try commaai as default,
|
||||
# and fallback to sunnypilot if the ref checkout fails.
|
||||
- name: Checkout commaai/openpilot
|
||||
if: ${{ !inputs.from_sunnypilot }}
|
||||
id: checkout_upstream
|
||||
continue-on-error: true
|
||||
uses: actions/checkout@v4
|
||||
@@ -85,7 +94,7 @@ jobs:
|
||||
path: openpilot
|
||||
|
||||
- name: Fallback to sunnypilot/sunnypilot
|
||||
if: steps.checkout_upstream.outcome == 'failure'
|
||||
if: inputs.from_sunnypilot || steps.checkout_upstream.outcome == 'failure'
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: sunnypilot/sunnypilot
|
||||
@@ -110,8 +119,17 @@ jobs:
|
||||
for f in "$@"; do
|
||||
grep -qs "^version https://git-lfs" "$f" || continue
|
||||
OID=$(awk -F'sha256:' '/^oid/{print $2}' "$f"); SIZE=$(awk '/^size/{print $2}' "$f")
|
||||
HREF=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" "$LFS_URL/objects/batch" \
|
||||
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href')
|
||||
HREF=""
|
||||
for B in sunnypilot/sunnypilot-lfs commaai/openpilot-lfs; do # lfs.py's buckets (commaai/openpilot#39206)
|
||||
if curl -fsSL --retry 3 -r 0-0 -o /dev/null "https://huggingface.co/buckets/$B/resolve/sha256/$OID"; then HREF="https://huggingface.co/buckets/$B/resolve/sha256/$OID"; break; fi
|
||||
done
|
||||
[ -n "$HREF" ] || HREF=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" "$LFS_URL/objects/batch" \
|
||||
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href // empty')
|
||||
if [ -z "$HREF" ]; then # not in openpilot's LFS: comma also publishes models to openpilot_driving_models
|
||||
HF_PATH=$(curl -fsSL --retry 3 "https://huggingface.co/api/models/commaai/openpilot_driving_models/tree/main?recursive=true" | jq -r --arg oid "$OID" 'map(select(.lfs.oid == $oid))[0].path // empty')
|
||||
[ -n "$HF_PATH" ] || { echo "::error::$f ($OID) is in neither openpilot's LFS nor commaai/openpilot_driving_models"; exit 1; }
|
||||
HREF="https://huggingface.co/commaai/openpilot_driving_models/resolve/main/$HF_PATH"
|
||||
fi
|
||||
aria2c -x 16 -s 16 -k 16M --max-tries=5 --retry-wait=5 --file-allocation=none --summary-interval=30 --allow-overwrite=true \
|
||||
-d "$(dirname "$f")" -o "$(basename "$f")" "$HREF"
|
||||
echo "$OID $f" | sha256sum -c -
|
||||
@@ -119,8 +137,11 @@ jobs:
|
||||
}
|
||||
UPSTREAM_PKL=selfdrive/modeld/models/big_driving_tinygrad.pkl
|
||||
if [ "${{ inputs.target_hardware }}" != "chestnut" ]; then
|
||||
git lfs pull -X "**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl"
|
||||
LFS_EXCLUDE="**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl"
|
||||
TOP=$(git rev-parse --show-toplevel)
|
||||
if [ -f "$TOP/lfs.py" ]; then (cd "$TOP" && ./lfs.py pull --exclude="$LFS_EXCLUDE"); else git lfs pull -X "$LFS_EXCLUDE"; fi || true
|
||||
rm -f selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/dmonitoring_*.onnx selfdrive/modeld/models/big_*.pkl selfdrive/modeld/models/dmonitoring_*.pkl
|
||||
fetch_lfs selfdrive/modeld/models/*.onnx
|
||||
elif compgen -G "selfdrive/modeld/models/big_*.onnx" > /dev/null; then
|
||||
fetch_lfs selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/big_*.pkl
|
||||
find selfdrive/modeld/models -type f \( -name "*.onnx" -o -name "*.pkl" \) ! -name "big_*.onnx" ! -name "big_*.pkl" -delete
|
||||
@@ -153,7 +174,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
build_model:
|
||||
runs-on: [self-hosted, "${{ inputs.target_hardware == 'chestnut' && 'chestnut' || 'tici' }}"]
|
||||
runs-on: ${{ inputs.target_hardware == 'chestnut' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
|
||||
needs: get_model
|
||||
env:
|
||||
MODEL_NAME: ${{ inputs.custom_name || inputs.upstream_branch }} (${{ needs.get_model.outputs.model_date }})
|
||||
@@ -164,31 +185,25 @@ jobs:
|
||||
fetch-depth: 1
|
||||
submodules: recursive
|
||||
|
||||
- name: Set environment variables
|
||||
id: set-env
|
||||
run: |
|
||||
# Set up common environment
|
||||
source /etc/profile;
|
||||
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
|
||||
uv sync --frozen
|
||||
printenv >> $GITHUB_ENV
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- 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: ${{ steps.set-env.outputs.version }}"
|
||||
echo "UV_PROJECT_ENVIRONMENT: ${UV_PROJECT_ENVIRONMENT}"
|
||||
echo "VIRTUAL_ENV: ${VIRTUAL_ENV}"
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
|
||||
rm -rf ${{ env.MODELS_DIR }}/*.onnx*
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock
|
||||
if: inputs.target_hardware == 'chestnut'
|
||||
uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: build
|
||||
|
||||
- name: Install the amd mock build dependencies
|
||||
if: inputs.target_hardware == 'chestnut'
|
||||
run: python3 -m pip install -q numpy zstandard
|
||||
|
||||
- name: Set up the qcom mock
|
||||
if: inputs.target_hardware != 'chestnut'
|
||||
uses: ./.github/workflows/setup-qcom-mock
|
||||
with:
|
||||
hf_token: ${{ secrets.HF_TOKEN }}
|
||||
|
||||
- name: Download model artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
@@ -198,21 +213,18 @@ jobs:
|
||||
|
||||
- name: Build Model
|
||||
run: |
|
||||
source /etc/profile
|
||||
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
|
||||
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock
|
||||
export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}:${{ github.workspace }}"
|
||||
|
||||
COMPILE_MODELD="${{ github.workspace }}/openpilot/sunnypilot/modeld_v2/compile_modeld.py"
|
||||
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
|
||||
CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')")
|
||||
|
||||
TG_FLAGS_QCOM="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
|
||||
TG_FLAGS_QCOM="DEV=MOCK+QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
|
||||
if [ "${{ inputs.target_hardware }}" == "chestnut" ]; then
|
||||
echo "CHESTNUT build"
|
||||
export CHESTNUT=1
|
||||
TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
|
||||
TG_FLAGS="DEBUG=1 DEV=MOCKUSB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
|
||||
OUTPUT_PKL="${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl"
|
||||
else
|
||||
echo "QCOM build"
|
||||
@@ -228,14 +240,14 @@ jobs:
|
||||
UPSTREAM_TG="${{ runner.temp }}/upstream_tinygrad"
|
||||
rm -rf "$UPSTREAM_TG" && git init -q "$UPSTREAM_TG" && git -C "$UPSTREAM_TG" fetch -q --depth 1 "$TG_URL" "$TG_SHA" && git -C "$UPSTREAM_TG" checkout -q FETCH_HEAD
|
||||
CONVERTED="${{ runner.temp }}/big_driving_tinygrad_plain.pkl"
|
||||
env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
|
||||
env PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/mockgpu/usb_server.py" env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
|
||||
"${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl" "$CONVERTED"
|
||||
mv "$CONVERTED" "$OUTPUT_PKL"
|
||||
elif NEW_ARCH_ONNX=$(find "${{ env.MODELS_DIR }}" -maxdepth 1 -name "${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}*driving*.onnx" -print -quit) &&
|
||||
[ -n "$NEW_ARCH_ONNX" ] && grep -qa new_img "$NEW_ARCH_ONNX"; then # the new architecture: one ONNX taking the warped frames as new_img
|
||||
echo "Compiling new architecture ONNX: $NEW_ARCH_ONNX"
|
||||
env ${TG_FLAGS} taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
|
||||
"$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 1
|
||||
env ${TG_FLAGS} python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
|
||||
"$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 0
|
||||
else
|
||||
echo "Detected onnx architecture. Routing to native compile_modeld.py."
|
||||
# Detect model type and build compile args
|
||||
@@ -284,7 +296,7 @@ jobs:
|
||||
|
||||
if [ -n "$MODEL_TYPE" ]; then
|
||||
echo "Detected: $MODEL_TYPE -> $OUTPUT_PKL"
|
||||
env ${TG_FLAGS} taskset -c 7 python3 "$COMPILE_MODELD" \
|
||||
env ${TG_FLAGS} python3 "$COMPILE_MODELD" \
|
||||
--model-type $MODEL_TYPE \
|
||||
--model-size $MODEL_SIZE \
|
||||
--camera-resolutions $CAMERA_RES \
|
||||
@@ -293,6 +305,12 @@ jobs:
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Replay its check frame on the mock and require the result bit for bit
|
||||
env:
|
||||
DEV: ${{ inputs.target_hardware == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }}
|
||||
PYTHONPATH: ${{ env.TINYGRAD_PATH }}:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "${{ env.MODELS_DIR }}/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl"
|
||||
|
||||
- name: Prepare Output
|
||||
run: |
|
||||
sudo rm -rf ${{ env.OUTPUT_DIR }}
|
||||
@@ -304,7 +322,6 @@ jobs:
|
||||
--include='/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl' \
|
||||
--exclude='*' \
|
||||
--delete-excluded \
|
||||
--chown=comma:comma \
|
||||
${{ env.MODELS_DIR }}/ ${{ env.OUTPUT_DIR }}/
|
||||
|
||||
python3 "${{ github.workspace }}/release/ci/model_generator.py" \
|
||||
@@ -331,9 +348,3 @@ jobs:
|
||||
with:
|
||||
name: artifact-name-${{ inputs.custom_name || inputs.upstream_branch }}
|
||||
path: ${{ env.OUTPUT_DIR }}/artifact_name.txt
|
||||
|
||||
- name: Re-enable powersave
|
||||
if: always()
|
||||
run: |
|
||||
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
|
||||
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
|
||||
|
||||
@@ -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' &&
|
||||
@@ -127,57 +127,61 @@ jobs:
|
||||
submodules: recursive
|
||||
ref: ${{ env.SOURCE_BRANCH }}
|
||||
repository: ${{ github.event.pull_request.head.repo.fork && github.event.pull_request.head.repo.full_name || github.repository }}
|
||||
- run: git lfs pull
|
||||
- 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 openpilot/sunnypilot/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: |
|
||||
@@ -190,7 +194,7 @@ jobs:
|
||||
find . -name '__pycache__' -type d -exec rm -rf {} +
|
||||
find . -name 'SConstruct' -delete
|
||||
find . -name 'SConscript' -delete
|
||||
rm -rf .sconsign.dblite Jenkinsfile tools/release/ release/
|
||||
rm -rf .sconsign.dblite tools/release/ release/
|
||||
rm -f openpilot/selfdrive/modeld/models/*.onnx*
|
||||
rm -f openpilot/sunnypilot/modeld*/models/*.onnx*
|
||||
find openpilot/third_party/ -name '*x86*' -exec rm -r {} +
|
||||
@@ -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
|
||||
@@ -599,7 +597,8 @@ jobs:
|
||||
CHESTNUT_BRANCH="${{ needs.prepare_strategy.outputs.new_branch }}-chestnut"
|
||||
cp .lfsconfig "${{ env.OUTPUT_DIR }}/"
|
||||
echo 'openpilot/selfdrive/modeld/models/big_*_tinygrad.pkl filter=lfs diff=lfs merge=lfs -text' > "${{ env.OUTPUT_DIR }}/.gitattributes"
|
||||
git lfs install
|
||||
python3 -m venv "$RUNNER_TEMP/lfs-venv" && "$RUNNER_TEMP/lfs-venv/bin/pip" install -q hf-xet==1.7.0
|
||||
export PATH="$RUNNER_TEMP/lfs-venv/bin:$PATH" # publish.sh runs lfs.py install; its pre-push uploads to the HF bucket
|
||||
git config --global credential.helper store
|
||||
echo "https://user:${HF_TOKEN}@huggingface.co" > ~/.git-credentials
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ name: Build dev
|
||||
env:
|
||||
DEFAULT_SOURCE_BRANCH: "master"
|
||||
DEFAULT_TARGET_BRANCH: "master-dev"
|
||||
LFS_URL: 'https://gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git/info/lfs'
|
||||
LFS_PUSH_URL: 'ssh://git@gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git'
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -66,15 +64,6 @@ jobs:
|
||||
git config --global user.name 'github-actions[bot]'
|
||||
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
|
||||
- name: Set up SSH
|
||||
uses: webfactory/ssh-agent@v0.9.0
|
||||
with:
|
||||
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
|
||||
- name: Add GitLab public keys
|
||||
run: |
|
||||
ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
@@ -167,13 +156,6 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Update LFS Config
|
||||
run: |
|
||||
echo '[lfs]' > .lfsconfig
|
||||
echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig
|
||||
echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig
|
||||
echo ' locksverify = false' >> .lfsconfig
|
||||
|
||||
- name: Restore workflows from source
|
||||
run: |
|
||||
TARGET_BRANCH="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}"
|
||||
|
||||
@@ -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
|
||||
@@ -28,18 +28,7 @@ jobs:
|
||||
env:
|
||||
DEV: CPU
|
||||
run: tools/op.sh test -v openpilot/sunnypilot/modeld_v2/tests/test_plain_artifact.py
|
||||
- name: Install LLVM 20 and ROCm comgr for the amd mock, as tinygrad_repo/.github/actions/setup-tinygrad does
|
||||
run: |
|
||||
. /etc/os-release
|
||||
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
|
||||
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
|
||||
sudo mkdir -p /etc/apt/keyrings
|
||||
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
|
||||
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
|
||||
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
|
||||
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
|
||||
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
|
||||
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
|
||||
- uses: ./.github/workflows/setup-amd-mock
|
||||
- name: Convert a pickled USB+AMD jit and replay it under tinygrad's amd mock
|
||||
env:
|
||||
DEV: MOCKUSB+AMD
|
||||
@@ -79,7 +68,8 @@ jobs:
|
||||
generate-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
models: ${{ steps.set-matrix.outputs.models }}
|
||||
chestnut: ${{ steps.set-matrix.outputs.chestnut }}
|
||||
qcom: ${{ steps.set-matrix.outputs.qcom }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Fetch and Parse json
|
||||
@@ -91,49 +81,83 @@ jobs:
|
||||
with open("openpilot/sunnypilot/models/fetcher.py", "r") as f:
|
||||
urls = re.findall(r"MODEL_URL(?:_CHESTNUT)?\s*=\s*[\"'"'"']([^\"'"'"']+)[\"'"'"']", f.read())
|
||||
|
||||
artifacts = []
|
||||
chestnut, qcom = [], []
|
||||
for url in urls:
|
||||
data = json.loads(urllib.request.urlopen(url).read())
|
||||
for bundle in data.get("bundles", []):
|
||||
for model in bundle.get("models", []):
|
||||
if "artifact" in model:
|
||||
artifacts.append(model["artifact"])
|
||||
if "chestnut" in url:
|
||||
chestnut.append(model["artifact"])
|
||||
elif "tinygrad" in model["artifact"]["file_name"]:
|
||||
qcom.append(model["artifact"])
|
||||
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
f.write(f"models={json.dumps(artifacts)}\n")
|
||||
f.write(f"chestnut={json.dumps(chestnut)}\n")
|
||||
f.write(f"qcom={json.dumps(qcom)}\n")
|
||||
'
|
||||
|
||||
test-model:
|
||||
name: Test ${{ matrix.artifact.file_name }}
|
||||
chestnut-mock-parity:
|
||||
name: Mock parity ${{ matrix.artifact.file_name }}
|
||||
needs: generate-matrix
|
||||
runs-on: ubuntu-latest
|
||||
container: ghcr.io/commaai/openpilot-base:latest
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
artifact: ${{ fromJson(needs.generate-matrix.outputs.models) }}
|
||||
artifact: ${{ fromJson(needs.generate-matrix.outputs.chestnut) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- uses: ./.github/workflows/setup-amd-mock
|
||||
with:
|
||||
emu_cache: ${{ matrix.artifact.file_name }}
|
||||
- run: python3 -m pip install -q numpy
|
||||
- name: Download model
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
|
||||
MODEL_FILE: ${{ matrix.artifact.file_name }}
|
||||
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p /tmp/models
|
||||
AUTH=()
|
||||
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
|
||||
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "/tmp/models/$MODEL_FILE" "$MODEL_URL"
|
||||
|
||||
- name: Run Model Compatibility Test
|
||||
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
|
||||
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
|
||||
- name: Replay its check frame on the amd mock and require the chestnut's result bit for bit
|
||||
env:
|
||||
MODEL_BASE_NAME: ${{ matrix.artifact.file_name }}
|
||||
MODEL_DIR: "/tmp/models"
|
||||
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
|
||||
|
||||
qcom-mock-parity:
|
||||
name: QCOM mock parity ${{ matrix.artifact.file_name }}
|
||||
needs: generate-matrix
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
artifact: ${{ fromJson(needs.generate-matrix.outputs.qcom) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: python3 -m pip install -q numpy tinymesa==25.2.7.2
|
||||
- name: Download model
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
|
||||
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
|
||||
shell: bash
|
||||
run: |
|
||||
export PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo:$GITHUB_WORKSPACE:$PYTHONPATH"
|
||||
python3 -m pip uninstall -y tinygrad || uv pip uninstall -y tinygrad --system || true
|
||||
python3 -m pytest openpilot/sunnypilot/modeld_v2/tests/test_models.py
|
||||
AUTH=()
|
||||
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
|
||||
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
|
||||
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
|
||||
- name: Replay its check frame on the qcom mock and require the comma device's result bit for bit
|
||||
env:
|
||||
DEV: MOCK+QCOM
|
||||
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
|
||||
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
|
||||
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
with:
|
||||
timeout_minutes: 2
|
||||
max_attempts: 3
|
||||
command: git lfs pull
|
||||
command: ./lfs.py pull
|
||||
- name: Build devel
|
||||
timeout-minutes: 3
|
||||
run: TARGET_DIR=$STRIPPED_DIR tools/release/build_stripped.sh
|
||||
@@ -102,7 +102,7 @@ jobs:
|
||||
key: scons-${{ runner.os }}-${{ github.job }}-${{ github.sha }}
|
||||
restore-keys: scons-${{ runner.os }}-${{ github.job }}-
|
||||
- name: Building openpilot
|
||||
run: scons
|
||||
run: tools/op.sh build
|
||||
|
||||
static_analysis:
|
||||
name: static analysis
|
||||
@@ -140,7 +140,7 @@ jobs:
|
||||
key: scons-${{ runner.os }}-${{ github.job }}-${{ github.sha }}
|
||||
restore-keys: scons-${{ runner.os }}-${{ github.job }}-
|
||||
- name: Build openpilot
|
||||
run: scons
|
||||
run: tools/op.sh build
|
||||
- name: Run unit tests
|
||||
timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 999 }}
|
||||
env:
|
||||
|
||||
@@ -62,7 +62,6 @@ docs/_site/
|
||||
openpilot/selfdrive/pandad/pandad
|
||||
openpilot/cereal/services.h
|
||||
openpilot/cereal/gen
|
||||
openpilot/cereal/messaging/bridge
|
||||
openpilot/selfdrive/ui/translations/tmp
|
||||
openpilot/selfdrive/car/tests/cars_dump
|
||||
openpilot/system/camerad/camerad
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
[lfs]
|
||||
url = https://gitlab.com/commaai/openpilot-lfs.git/info/lfs
|
||||
pushurl = ssh://git@gitlab.com/commaai/openpilot-lfs.git
|
||||
locksverify = false
|
||||
Vendored
-320
@@ -1,320 +0,0 @@
|
||||
def retryWithDelay(int maxRetries, int delay, Closure body) {
|
||||
for (int i = 0; i < maxRetries; i++) {
|
||||
try {
|
||||
return body()
|
||||
} catch (Exception e) {
|
||||
sleep(delay)
|
||||
}
|
||||
}
|
||||
throw Exception("Failed after ${maxRetries} retries")
|
||||
}
|
||||
|
||||
def device(String ip, String step_label, String cmd) {
|
||||
withCredentials([file(credentialsId: 'id_rsa', variable: 'key_file')]) {
|
||||
def ssh_cmd = """
|
||||
ssh -o ControlMaster=no -o ControlPath=none -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=12 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec setpriv --pdeathsig HUP /usr/bin/bash <<'END'
|
||||
|
||||
set -e
|
||||
|
||||
export TERM=xterm-256color
|
||||
|
||||
trap 'kill 0' HUP # stop this process group on SSH disconnect
|
||||
|
||||
export CI=1
|
||||
export PYTHONWARNINGS=error
|
||||
export PYTHONFAULTHANDLER=1
|
||||
export COMMA_CACHE=/data/tmp/comma_download_cache
|
||||
#export LOGPRINT=debug # this has gotten too spammy...
|
||||
export TEST_DIR=${env.TEST_DIR}
|
||||
export SOURCE_DIR=${env.SOURCE_DIR}
|
||||
export GIT_BRANCH=${env.GIT_BRANCH}
|
||||
export GIT_COMMIT=${env.GIT_COMMIT}
|
||||
export CI_ARTIFACTS_TOKEN=${env.CI_ARTIFACTS_TOKEN}
|
||||
export GITHUB_COMMENTS_TOKEN=${env.GITHUB_COMMENTS_TOKEN}
|
||||
export AZURE_TOKEN='${env.AZURE_TOKEN}'
|
||||
# only use 1 thread since most require real hardware that can't be shared
|
||||
export PYTEST_ADDOPTS="-n0 -s"
|
||||
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -i /data/gitkey"
|
||||
|
||||
source ~/.bash_profile
|
||||
if [ -f /AGNOS ]; then
|
||||
source /etc/profile
|
||||
|
||||
rm -rf /tmp/tmp*
|
||||
rm -rf ~/.commacache
|
||||
rm -rf /dev/shm/*
|
||||
rm -rf /dev/tmp/tmp*
|
||||
|
||||
if ! systemctl is-active --quiet systemd-resolved; then
|
||||
echo "restarting resolved"
|
||||
sudo systemctl start systemd-resolved
|
||||
sleep 3
|
||||
fi
|
||||
|
||||
# restart aux USB
|
||||
if [ -e /sys/bus/usb/drivers/hub/3-0:1.0 ]; then
|
||||
echo "restarting aux usb"
|
||||
echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/unbind
|
||||
sleep 0.5
|
||||
echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/bind
|
||||
fi
|
||||
fi
|
||||
if [ -f /data/openpilot/launch_env.sh ]; then
|
||||
source /data/openpilot/launch_env.sh
|
||||
fi
|
||||
|
||||
export LD_LIBRARY_PATH="\$(python -c 'import ffmpeg; print(ffmpeg.LIB_DIR)'):/usr/local/lib:\${LD_LIBRARY_PATH:-}"
|
||||
|
||||
ln -snf ${env.TEST_DIR} /data/pythonpath
|
||||
|
||||
cd ${env.TEST_DIR} || true
|
||||
time ( ${cmd} ) &
|
||||
wait \$!
|
||||
END"""
|
||||
|
||||
sh script: ssh_cmd, label: step_label
|
||||
}
|
||||
}
|
||||
|
||||
def deviceStage(String stageName, String deviceType, List extra_env, def steps) {
|
||||
stage(stageName) {
|
||||
if (currentBuild.result != null) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isReplay()) {
|
||||
error("REPLAYING TESTS IS NOT ALLOWED. FIX THEM INSTEAD.")
|
||||
}
|
||||
|
||||
def extra = extra_env.collect { "export ${it}" }.join('\n');
|
||||
def branch = env.BRANCH_NAME ?: 'master';
|
||||
def gitDiff = sh returnStdout: true, script: 'curl -s -H "Authorization: Bearer ${GITHUB_COMMENTS_TOKEN}" https://api.github.com/repos/commaai/openpilot/compare/master...${GIT_BRANCH} | jq .files[].filename || echo "/"', label: 'Getting changes'
|
||||
|
||||
lock(resource: "", label: deviceType, inversePrecedence: true, variable: 'device_ip', quantity: 1, resourceSelectStrategy: 'random') {
|
||||
docker.image('ghcr.io/commaai/alpine-ssh').inside('--user=root') {
|
||||
timeout(time: 35, unit: 'MINUTES') {
|
||||
retry (3) {
|
||||
def date = sh(script: 'date', returnStdout: true).trim();
|
||||
device(device_ip, "set time", "date -s '" + date + "'")
|
||||
device(device_ip, "git checkout", extra + "\n" + readFile("openpilot/selfdrive/test/setup_device_ci.sh"))
|
||||
}
|
||||
steps.each { item ->
|
||||
def name = item[0]
|
||||
def cmd = item[1]
|
||||
|
||||
def args = item[2]
|
||||
def diffPaths = args.diffPaths ?: []
|
||||
def cmdTimeout = args.timeout ?: 9999
|
||||
|
||||
if (branch != "master" && !branch.contains("__jenkins_loop_") && diffPaths && !hasPathChanged(gitDiff, diffPaths)) {
|
||||
println "Skipping ${name}: no changes in ${diffPaths}."
|
||||
return
|
||||
} else {
|
||||
timeout(time: cmdTimeout, unit: 'SECONDS') {
|
||||
device(device_ip, name, cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def hasPathChanged(String gitDiff, List<String> paths) {
|
||||
for (path in paths) {
|
||||
if (gitDiff.contains(path)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
def isReplay() {
|
||||
def replayClass = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause"
|
||||
return currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClass) }
|
||||
}
|
||||
|
||||
def setupCredentials() {
|
||||
withCredentials([
|
||||
string(credentialsId: 'azure_token', variable: 'AZURE_TOKEN'),
|
||||
]) {
|
||||
env.AZURE_TOKEN = "${AZURE_TOKEN}"
|
||||
}
|
||||
|
||||
withCredentials([
|
||||
string(credentialsId: 'ci_artifacts_pat', variable: 'CI_ARTIFACTS_TOKEN'),
|
||||
]) {
|
||||
env.CI_ARTIFACTS_TOKEN = "${CI_ARTIFACTS_TOKEN}"
|
||||
}
|
||||
|
||||
withCredentials([
|
||||
string(credentialsId: 'post_comments_github_pat', variable: 'GITHUB_COMMENTS_TOKEN'),
|
||||
]) {
|
||||
env.GITHUB_COMMENTS_TOKEN = "${GITHUB_COMMENTS_TOKEN}"
|
||||
}
|
||||
}
|
||||
|
||||
def step(String name, String cmd, Map args = [:]) {
|
||||
return [name, cmd, args]
|
||||
}
|
||||
|
||||
def chestnutStage(String name = "chestnut") {
|
||||
deviceStage(name, "mici-chestnut-ci", ["UNSAFE=1", "CHESTNUT=1"], [
|
||||
step("build", "./openpilot/selfdrive/test/chestnut.sh"),
|
||||
step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py --chestnut"),
|
||||
step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py TestChestnutOnroad", [timeout: 120]),
|
||||
])
|
||||
}
|
||||
|
||||
node {
|
||||
env.CI = "1"
|
||||
env.PYTHONWARNINGS = "error"
|
||||
env.TEST_DIR = "/data/openpilot"
|
||||
env.SOURCE_DIR = "/data/openpilot_source/"
|
||||
setupCredentials()
|
||||
|
||||
env.GIT_BRANCH = checkout(scm).GIT_BRANCH
|
||||
env.GIT_COMMIT = checkout(scm).GIT_COMMIT
|
||||
|
||||
if (env.JOB_BASE_NAME == 'chestnut-stresstest') {
|
||||
sh 'git fetch --no-tags origin nightly-chestnut'
|
||||
env.GIT_COMMIT = sh(script: 'git show FETCH_HEAD:git_src_commit', returnStdout: true).trim()
|
||||
if (!(env.GIT_COMMIT ==~ /[0-9a-f]{40}/)) {
|
||||
error("invalid nightly-chestnut source commit")
|
||||
}
|
||||
def results = []
|
||||
try {
|
||||
timeout(time: 12, unit: 'HOURS') {
|
||||
for (int run = 1; run <= 100; run++) {
|
||||
results << "run ${run}: INCOMPLETE"
|
||||
try {
|
||||
chestnutStage("chestnut ${run}/100")
|
||||
results[run - 1] = "run ${run}: PASS"
|
||||
} catch (hudson.AbortException e) {
|
||||
results[run - 1] = "run ${run}: FAIL"
|
||||
echo e.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
writeFile file: 'chestnut_stress_report.txt', text: "commit: ${env.GIT_COMMIT}\ncompleted: ${results.count { !it.endsWith('INCOMPLETE') }}/100\n" + results.join('\n') + '\n'
|
||||
archiveArtifacts artifacts: 'chestnut_stress_report.txt'
|
||||
}
|
||||
if (results.any { !it.endsWith('PASS') }) {
|
||||
error("chestnut stress test failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
def excludeBranches = ['__nightly', '__nightly-chestnut', 'devel', 'devel-staging',
|
||||
'release-tizi', 'release-tizi-staging', 'release-mici', 'release-mici-staging', 'testing-closet*', 'hotfix-*']
|
||||
def excludeRegex = excludeBranches.join('|').replaceAll('\\*', '.*')
|
||||
|
||||
if (env.BRANCH_NAME != 'master' && !env.BRANCH_NAME.contains('__jenkins_loop_')) {
|
||||
properties([
|
||||
disableConcurrentBuilds(abortPrevious: true)
|
||||
])
|
||||
}
|
||||
|
||||
try {
|
||||
if (env.BRANCH_NAME == 'devel-staging') {
|
||||
deviceStage("build release-tizi-staging", "tizi-needs-can", [], [
|
||||
step("build release-tizi-staging", "RELEASE_BRANCH=release-tizi-staging,release-mici-staging $SOURCE_DIR/tools/release/build_release.sh"),
|
||||
])
|
||||
}
|
||||
|
||||
if (env.BRANCH_NAME == '__nightly') {
|
||||
parallel (
|
||||
'nightly': {
|
||||
deviceStage("build nightly", "tizi-needs-can", [], [
|
||||
step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/tools/release/build_release.sh"),
|
||||
])
|
||||
},
|
||||
'nightly-dev': {
|
||||
deviceStage("build nightly-dev", "tizi-needs-can", [], [
|
||||
step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/tools/release/build_release.sh"),
|
||||
])
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (env.BRANCH_NAME == '__nightly-chestnut') {
|
||||
parallel (
|
||||
'nightly-chestnut': {
|
||||
deviceStage("build nightly-chestnut", "mici-chestnut-ci", ["CHESTNUT=1"], [
|
||||
step("build nightly-chestnut", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 RELEASE_BRANCH=nightly-chestnut $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"),
|
||||
])
|
||||
},
|
||||
'nightly-chestnut-dev': {
|
||||
deviceStage("build nightly-chestnut-dev", "mici-chestnut-ci", ["CHESTNUT=1"], [
|
||||
step("build nightly-chestnut-dev", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-chestnut-dev $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"),
|
||||
])
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (!env.BRANCH_NAME.matches(excludeRegex)) {
|
||||
parallel (
|
||||
'onroad tests': {
|
||||
deviceStage("onroad", "tizi-needs-can", ["UNSAFE=1"], [
|
||||
step("build openpilot", "cd openpilot/system/manager && ./build.py"),
|
||||
step("check dirty", "tools/release/check-dirty.sh"),
|
||||
step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py", [timeout: 60]),
|
||||
])
|
||||
},
|
||||
'HW + Unit Tests': {
|
||||
deviceStage("tizi-hardware", "tizi-common", ["UNSAFE=1"], [
|
||||
step("build", "cd openpilot/system/manager && ./build.py"),
|
||||
step("test power draw", "./openpilot/selfdrive/test/test_power_draw.py"),
|
||||
step("test encoder", "./openpilot/system/loggerd/tests/test_encoder.py", [diffPaths: ["openpilot/system/loggerd/"]]),
|
||||
step("test manager", "./openpilot/system/manager/test/test_manager.py"),
|
||||
])
|
||||
},
|
||||
'camerad OX03C10': {
|
||||
deviceStage("OX03C10", "tizi-ox03c10", ["UNSAFE=1"], [
|
||||
step("build", "cd openpilot/system/manager && ./build.py"),
|
||||
step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"),
|
||||
step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]),
|
||||
])
|
||||
},
|
||||
'camerad OS04C10': {
|
||||
deviceStage("OS04C10", "tici-os04c10", ["UNSAFE=1"], [
|
||||
step("build", "cd openpilot/system/manager && ./build.py"),
|
||||
step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"),
|
||||
step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]),
|
||||
])
|
||||
},
|
||||
'sensord': {
|
||||
deviceStage("LSM + MMC", "tizi-lsmc", ["UNSAFE=1"], [
|
||||
step("build", "cd openpilot/system/manager && ./build.py"),
|
||||
step("test sensord", "./openpilot/system/sensord/tests/test_sensord.py"),
|
||||
])
|
||||
},
|
||||
'replay': {
|
||||
deviceStage("model-replay", "tizi-replay", ["UNSAFE=1"], [
|
||||
step("build", "cd openpilot/system/manager && ./build.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]),
|
||||
step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]),
|
||||
])
|
||||
},
|
||||
'tizi': {
|
||||
deviceStage("tizi", "tizi", ["UNSAFE=1"], [
|
||||
step("build openpilot", "cd openpilot/system/manager && ./build.py"),
|
||||
step("test pandad loopback", "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"),
|
||||
step("test pandad spi", "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py"),
|
||||
step("test amp", "./openpilot/common/hardware/comma/tests/test_amplifier.py"),
|
||||
])
|
||||
},
|
||||
'chestnut': {
|
||||
chestnutStage()
|
||||
},
|
||||
|
||||
)
|
||||
}
|
||||
} catch (Exception e) {
|
||||
currentBuild.result = 'FAILED'
|
||||
throw e
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -6,7 +6,11 @@ Version 0.11.3 (2026-XX-XX)
|
||||
* slowing down for curves
|
||||
* adjusting speed based on surrounding traffic
|
||||
* This behavior was previously available with openpilot's "Experimental mode", but is now out of beta and always enabled
|
||||
* With openpilot deciding which speed to drive, the car's cruise speed is treated as a maximum speed openpilot will not exceed
|
||||
* With openpilot deciding the speed to drive, the set speed is treated as a maximum speed openpilot will not exceed
|
||||
* Driving personalities retuned to be more distinct
|
||||
* Always-on sleep detection
|
||||
* Improved comma four UI
|
||||
* Romanian translation thanks to adriantabirta!
|
||||
|
||||
Version 0.11.2 (2026-10-14)
|
||||
=======================
|
||||
|
||||
+34
-37
@@ -6,6 +6,8 @@ import platform
|
||||
import shlex
|
||||
import importlib
|
||||
import numpy as np
|
||||
import nanobind
|
||||
import eigen
|
||||
|
||||
import SCons.Errors
|
||||
from SCons.Defaults import _stripixes
|
||||
@@ -55,24 +57,11 @@ assert arch in [
|
||||
"Darwin", # macOS arm64 (x86 not supported)
|
||||
]
|
||||
|
||||
pkg_names = ['acados', 'capnproto', 'eigen', 'ffmpeg', 'json11', 'ncurses', 'zeromq', 'zstd']
|
||||
pkg_names = ['acados', 'capnproto', 'ffmpeg', 'json11', 'ncurses', 'zstd']
|
||||
pkgs = [importlib.import_module(name) for name in pkg_names]
|
||||
acados = pkgs[pkg_names.index('acados')]
|
||||
ffmpeg = pkgs[pkg_names.index('ffmpeg')]
|
||||
# Shared package ships .so/.dylib; older device venvs still have static .a only.
|
||||
# Keep static link deps (x264/z/va/drm) when the installed package is static so
|
||||
# COMMA_HARDWARE CI works without upgrading the device venv yet.
|
||||
# TODO: drop the static fallback once device venvs have comma-deps-ffmpeg>=7.1.0.post94
|
||||
_ffmpeg_lib_names = os.listdir(ffmpeg.LIB_DIR) if os.path.isdir(ffmpeg.LIB_DIR) else []
|
||||
ffmpeg_shared = any(
|
||||
n.startswith('libavcodec.so') or (n.startswith('libavcodec') and n.endswith('.dylib'))
|
||||
for n in _ffmpeg_lib_names
|
||||
)
|
||||
ffmpeg_libs = ['avformat', 'avcodec', 'swresample', 'avutil']
|
||||
if not ffmpeg_shared:
|
||||
ffmpeg_libs += ['x264', 'z']
|
||||
if arch != "Darwin":
|
||||
ffmpeg_libs += ['va', 'va-drm', 'drm']
|
||||
acados_include_dirs = [
|
||||
acados.INCLUDE_DIR,
|
||||
os.path.join(acados.INCLUDE_DIR, "blasfeo", "include"),
|
||||
@@ -160,12 +149,11 @@ env = Environment(
|
||||
"#rednose_repo/rednose/helpers",
|
||||
[x.LIB_DIR for x in pkgs],
|
||||
],
|
||||
RPATH=[ffmpeg.LIB_DIR] if ffmpeg_shared else [],
|
||||
CYTHONCFILESUFFIX=".cpp",
|
||||
RPATH=[ffmpeg.LIB_DIR],
|
||||
COMPILATIONDB_USE_ABSPATH=True,
|
||||
REDNOSE_ROOT="#rednose_repo",
|
||||
tools=["default", "cython", "compilation_db", "rednose_filter"],
|
||||
toolpath=["#msgq_repo/site_scons/site_tools", "#rednose_repo/site_scons/site_tools"],
|
||||
tools=["default", "compilation_db", "rednose_filter"],
|
||||
toolpath=["#rednose_repo/site_scons/site_tools"],
|
||||
)
|
||||
# SCons' Darwin linker tool doesn't define the variables used to expand RPATH.
|
||||
if arch == "Darwin":
|
||||
@@ -231,6 +219,20 @@ else:
|
||||
np_version = SCons.Script.Value(np.__version__)
|
||||
Export('envCython', 'np_version')
|
||||
|
||||
# ********** nanobind build environment **********
|
||||
envNanobind = env.Clone(LIBS=[])
|
||||
nanobind_dir = os.path.dirname(nanobind.__file__)
|
||||
envNanobind.Append(CPPPATH=[sysconfig.get_paths()['include'], nanobind.include_dir(), os.path.join(nanobind_dir, "ext", "robin_map", "include"),
|
||||
os.path.join(eigen.INCLUDE_DIR, "eigen3")],
|
||||
CCFLAGS=["-fvisibility=hidden"])
|
||||
envNanobind["CCFLAGS"] = [f for f in envNanobind["CCFLAGS"] if not f.startswith("-Wshadow")]
|
||||
envNanobind["NANOBIND_SOURCE"] = os.path.join(nanobind_dir, "src", "nb_combined.cpp")
|
||||
if arch == "Darwin":
|
||||
envNanobind["LINKFLAGS"] = env["LINKFLAGS"] + ["-bundle", "-undefined", "dynamic_lookup"]
|
||||
else:
|
||||
envNanobind["LINKFLAGS"] = ["-pthread", "-shared"]
|
||||
Export('envNanobind')
|
||||
|
||||
Export('env', 'arch', 'acados', 'release', 'ffmpeg_libs')
|
||||
|
||||
# Setup cache dir
|
||||
@@ -254,14 +256,11 @@ def prune_cache_dir(target=None, source=None, env=None):
|
||||
# Build common module
|
||||
SConscript(['openpilot/common/SConscript'])
|
||||
Import('_common')
|
||||
common = [_common, 'json11', 'zmq']
|
||||
common = [_common, 'json11']
|
||||
Export('common')
|
||||
|
||||
# Build messaging (cereal + msgq + socketmaster + their dependencies)
|
||||
# Enable swaglog include in submodules
|
||||
env_swaglog = env.Clone()
|
||||
env_swaglog['CXXFLAGS'].append('-DSWAGLOG="\\"common/swaglog.h\\""')
|
||||
SConscript(['msgq_repo/SConscript'], exports={'env': env_swaglog})
|
||||
SConscript(['msgq_repo/SConscript'])
|
||||
|
||||
SConscript(['openpilot/cereal/SConscript'])
|
||||
|
||||
@@ -293,8 +292,6 @@ SConscript([
|
||||
'openpilot/selfdrive/ui/SConscript',
|
||||
])
|
||||
|
||||
SConscript(['openpilot/sunnypilot/SConscript'])
|
||||
|
||||
# Build desktop-only tools
|
||||
if GetOption('extras') and arch != "comma_arm64":
|
||||
SConscript([
|
||||
@@ -307,7 +304,7 @@ if GetOption('extras') and arch != "comma_arm64":
|
||||
env.CompilationDatabase('compile_commands.json')
|
||||
|
||||
# progress output
|
||||
def count_scons_nodes(nodes):
|
||||
def get_scons_nodes(nodes):
|
||||
seen = set()
|
||||
stack = list(nodes)
|
||||
|
||||
@@ -316,26 +313,26 @@ def count_scons_nodes(nodes):
|
||||
if node in seen:
|
||||
continue
|
||||
seen.add(node)
|
||||
executor = node.get_executor()
|
||||
if executor is not None:
|
||||
stack += executor.get_all_prerequisites() + executor.get_all_children()
|
||||
# Only scan directories; generated sources are not ready yet.
|
||||
stack += (node.prerequisites or []) + node.children(scan=isinstance(node, SCons.Node.FS.Dir))
|
||||
|
||||
return len(seen)
|
||||
return seen
|
||||
|
||||
progress_interval = 5
|
||||
progress_count = 0
|
||||
progress_total = max(1, count_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry)))
|
||||
progress_nodes = get_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry))
|
||||
progress_total = max(1, len(progress_nodes))
|
||||
|
||||
def progress_function(node):
|
||||
global progress_count
|
||||
if progress_count >= progress_total:
|
||||
if node not in progress_nodes:
|
||||
return
|
||||
progress_count = min(progress_count + progress_interval, progress_total)
|
||||
progress = round(100. * progress_count / progress_total, 1)
|
||||
progress_nodes.remove(node)
|
||||
if len(progress_nodes) % progress_interval:
|
||||
return
|
||||
progress = round(100. * (1 - len(progress_nodes) / progress_total), 1)
|
||||
sys.stderr.write("\rBuilding: %5.1f%%" % progress if sys.stderr.isatty() else "progress: %.1f\n" % progress)
|
||||
if progress == 100. and sys.stderr.isatty():
|
||||
sys.stderr.write("\n")
|
||||
sys.stderr.flush()
|
||||
|
||||
Progress(progress_function, interval=progress_interval)
|
||||
Progress(progress_function)
|
||||
AddPostAction(BUILD_TARGETS or [Dir('.')], prune_cache_dir)
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
# a UP's DUT starts each job with an empty /data: these come back from master's last good job, as it left them
|
||||
cache = ["/data/scons_cache"]
|
||||
|
||||
[env]
|
||||
PYTHONPATH = "/data/ci/tree/openpilot" # the tree
|
||||
TERM = "xterm-256color"
|
||||
PYTHONWARNINGS = "error"
|
||||
PYTHONFAULTHANDLER = "1"
|
||||
COMMA_CACHE = "/data/tmp/comma_download_cache"
|
||||
# as launch_env.sh sets for openpilot on a device
|
||||
OMP_NUM_THREADS = "1"
|
||||
MKL_NUM_THREADS = "1"
|
||||
NUMEXPR_NUM_THREADS = "1"
|
||||
OPENBLAS_NUM_THREADS = "1"
|
||||
VECLIB_MAXIMUM_THREADS = "1"
|
||||
|
||||
# with the submodule package symlinks launch_chffrplus.sh makes
|
||||
[steps.build]
|
||||
name = "Build openpilot"
|
||||
run = """
|
||||
for p in msgq_repo/msgq opendbc_repo/opendbc rednose_repo/rednose teleoprtc_repo/teleoprtc tinygrad_repo/tinygrad; do ln -sfn "$p" "${p#*/}"; done
|
||||
tools/op.sh build
|
||||
"""
|
||||
|
||||
[steps.flash-chestnut]
|
||||
name = "Flash Chestnut"
|
||||
run = "sudo python3 openpilot/system/hardware/chestnut/flash.py"
|
||||
|
||||
# jobs run on comma fours, and on a comma 3x only where it differs, like its camera sensor
|
||||
[jobs.onroad]
|
||||
runs-on = "up-can"
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.onroad.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.onroad.steps]]
|
||||
name = "Check dirty"
|
||||
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 && ./openpilot/selfdrive/test/test_onroad.py TestOnroad"
|
||||
timeout-minutes = 1.5
|
||||
|
||||
[jobs.hardware]
|
||||
runs-on = "up-mici"
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.hardware.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.hardware.steps]]
|
||||
name = "Encoder"
|
||||
run = "./openpilot/system/loggerd/tests/test_encoder.py"
|
||||
|
||||
[[jobs.hardware.steps]]
|
||||
name = "Manager"
|
||||
run = "./openpilot/system/manager/test/test_manager.py"
|
||||
|
||||
[[jobs.hardware.steps]]
|
||||
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
|
||||
|
||||
[[jobs.replay.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.replay.steps]]
|
||||
name = "Model replay"
|
||||
run = "openpilot/selfdrive/test/process_replay/model_replay.py"
|
||||
|
||||
[jobs.pandad]
|
||||
runs-on = "up-mici"
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.pandad.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.pandad.steps]]
|
||||
name = "Pandad"
|
||||
run = "./openpilot/selfdrive/pandad/tests/test_pandad.py"
|
||||
|
||||
[[jobs.pandad.steps]]
|
||||
name = "Pandad loopback"
|
||||
run = "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"
|
||||
|
||||
[[jobs.pandad.steps]]
|
||||
name = "Pandad SPI"
|
||||
run = "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py"
|
||||
|
||||
[jobs.camerad]
|
||||
runs-on = "up-mici" # TODO: re-enable up-tres
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.camerad.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.camerad.steps]]
|
||||
name = "Camerad"
|
||||
run = "./openpilot/system/camerad/test/test_camerad.py"
|
||||
timeout-minutes = 1.5
|
||||
|
||||
[jobs.sensord]
|
||||
runs-on = "up-mici"
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.sensord.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.sensord.steps]]
|
||||
name = "Sensord"
|
||||
run = "./openpilot/system/sensord/tests/test_sensord.py"
|
||||
|
||||
# a comma four with a Chestnut on its aux port, which runs the big model
|
||||
[jobs.chestnut]
|
||||
runs-on = "chestnut"
|
||||
timeout-minutes = 35
|
||||
|
||||
[[jobs.chestnut.steps]]
|
||||
uses = "build"
|
||||
|
||||
[[jobs.chestnut.steps]]
|
||||
uses = "flash-chestnut"
|
||||
|
||||
[[jobs.chestnut.steps]]
|
||||
name = "Model replay"
|
||||
run = "openpilot/selfdrive/test/process_replay/model_replay.py --chestnut"
|
||||
|
||||
[[jobs.chestnut.steps]]
|
||||
name = "Onroad tests"
|
||||
run = "./openpilot/selfdrive/test/test_onroad.py TestChestnutOnroad"
|
||||
timeout-minutes = 2
|
||||
|
||||
[steps.release]
|
||||
name = "Build and test the release"
|
||||
run = """
|
||||
trap 'rm -rf /data/gitkey /data/pandaextra' EXIT
|
||||
printf '%s\n' "$RELEASE_KEY" > /data/gitkey && chmod 600 /data/gitkey
|
||||
mkdir -p /data/pandaextra/certs && printf '%s\n' "$PANDA_RELEASE_KEY" > /data/pandaextra/certs/release
|
||||
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; fi
|
||||
tools/release/build_release.sh $RELEASE_TESTS
|
||||
"""
|
||||
|
||||
[jobs.nightly]
|
||||
runs-on = "up-can"
|
||||
timeout-minutes = 90
|
||||
push = ["nightly"]
|
||||
env = { RELEASE_TESTS = "TestOnroad" }
|
||||
steps = [{ uses = "build" }, { uses = "release" }]
|
||||
|
||||
[jobs.nightly-dev]
|
||||
runs-on = "up-can"
|
||||
timeout-minutes = 90
|
||||
push = ["nightly-dev"]
|
||||
env = { RELEASE_TESTS = "TestOnroad", PANDA_DEBUG_BUILD = "1" }
|
||||
steps = [{ uses = "build" }, { uses = "release" }]
|
||||
|
||||
[jobs.release-staging]
|
||||
runs-on = "up-can"
|
||||
timeout-minutes = 90
|
||||
push = ["release-tizi-staging", "release-mici-staging"]
|
||||
env = { RELEASE_TESTS = "TestOnroad" }
|
||||
steps = [{ uses = "build" }, { uses = "release" }]
|
||||
|
||||
[jobs.nightly-chestnut]
|
||||
runs-on = "chestnut"
|
||||
timeout-minutes = 150
|
||||
push = ["nightly-chestnut"]
|
||||
env = { RELEASE_TESTS = "TestChestnutOnroad TestChestnutDrive", INCLUDE_BIG_MODEL = "1", SCONSFLAGS = "-j4" }
|
||||
steps = [{ uses = "build" }, { uses = "flash-chestnut" }, { uses = "release" }]
|
||||
|
||||
[jobs.nightly-chestnut-dev]
|
||||
runs-on = "chestnut"
|
||||
timeout-minutes = 90
|
||||
push = ["nightly-chestnut-dev"]
|
||||
env = { RELEASE_TESTS = "TestChestnutOnroad", INCLUDE_BIG_MODEL = "1", SCONSFLAGS = "-j4", PANDA_DEBUG_BUILD = "1" }
|
||||
steps = [{ uses = "build" }, { uses = "flash-chestnut" }, { uses = "release" }]
|
||||
+2
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
A supported vehicle is one that just works when you install a comma device. All supported cars provide a better experience than any stock system. Supported vehicles reference the US market unless otherwise specified.
|
||||
|
||||
# 358 Supported Cars
|
||||
# 359 Supported Cars
|
||||
|
||||
|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|<a href="##"><img width=2000></a>Hardware Needed<br> |Video|Setup Video|
|
||||
|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
@@ -161,6 +161,7 @@ A supported vehicle is one that just works when you install a comma device. All
|
||||
|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|19 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai L connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2021">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson 2022|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2022">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson 2023-24|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2023-24">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson (without HDA II) 2025-26|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson (without HDA II) 2025-26">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai L connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Diesel 2019">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson Hybrid 2022-24|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Hybrid 2022-24">Buy Here</a></sub></details>|||
|
||||
|Hyundai|Tucson Hybrid (without HDA II) 2025-26|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[](##)|[](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Hybrid (without HDA II) 2025-26">Buy Here</a></sub></details>|||
|
||||
|
||||
+26
-1
@@ -5,6 +5,8 @@ openpilot ALC and openpilot LDW do not automatically drive the vehicle or reduce
|
||||
|
||||
While changing lanes, openpilot is not capable of looking next to you or checking your blind spot. Only nudge the wheel to initiate a lane change after you have confirmed it's safe to do so.
|
||||
|
||||
Unexpected steering may occur. openpilot ALC may not steer to avoid stopped or slow-moving vehicles, cross traffic, construction barriers or cones, motorcycles, children, pedestrians, animals, or other objects on the road.
|
||||
|
||||
Many factors can impact the performance of openpilot ALC and openpilot LDW, causing them to be unable to function as intended. These include, but are not limited to:
|
||||
|
||||
* Poor visibility (heavy rain, snow, fog, etc.) or weather conditions that may interfere with sensor operation.
|
||||
@@ -13,6 +15,14 @@ Many factors can impact the performance of openpilot ALC and openpilot LDW, caus
|
||||
* The device is mounted incorrectly.
|
||||
* When in sharp curves, like on-off ramps, intersections etc...; openpilot is designed to be limited in the amount of steering torque it can produce.
|
||||
* In the presence of restricted lanes or construction zones.
|
||||
* When the lane markings are unclear, worn, missing, or they cross each other.
|
||||
* Tar marks, shadows, road cracks, temporary or construction lane markings, or other road imperfections.
|
||||
* When lanes merge or split.
|
||||
* When entering a highway on-ramp or exiting an off-ramp.
|
||||
* On roads with intersections or roundabouts.
|
||||
* On slippery roads.
|
||||
* When towing a trailer.
|
||||
* When entering or exiting a tunnel.
|
||||
* When driving on highly banked roads or in presence of strong cross-wind.
|
||||
* Extremely hot or cold temperatures.
|
||||
* Bright light (due to oncoming headlights, direct sunlight, etc.).
|
||||
@@ -24,6 +34,8 @@ The list above does not represent an exhaustive list of situations that may inte
|
||||
|
||||
openpilot ACC and openpilot FCW are not systems that allow careless or inattentive driving. It is still necessary for the driver to pay close attention to the vehicle’s surroundings and to be ready to re-take control of the gas and the brake at all times.
|
||||
|
||||
openpilot ACC may not stop your vehicle in time to avoid a collision with a vehicle that quickly stops in front of you. openpilot ACC may occasionally cause your vehicle to brake when not required or when you are not expecting it.
|
||||
|
||||
Many factors can impact the performance of openpilot ACC and openpilot FCW, causing them to be unable to function as intended. These include, but are not limited to:
|
||||
|
||||
* Poor visibility (heavy rain, snow, fog, etc.) or weather conditions that may interfere with sensor operation.
|
||||
@@ -35,9 +47,20 @@ Many factors can impact the performance of openpilot ACC and openpilot FCW, caus
|
||||
* In presence of traffic signs or stop lights, which are not detected by openpilot at this time.
|
||||
* When the posted speed limit is below the user selected set speed. openpilot does not detect speed limits at this time.
|
||||
* In presence of vehicles in the same lane that are not moving.
|
||||
* When a vehicle you are following moves out of your driving path and a stationary or slow-moving vehicle or object is in front of you.
|
||||
* Narrow vehicles, such as bicycles or motorcycles.
|
||||
* Vehicles or objects only partially in the driving lane.
|
||||
* On curves, openpilot ACC may not detect a vehicle in the same lane, and may accelerate to the set speed.
|
||||
* Cross traffic.
|
||||
* Oncoming vehicles.
|
||||
* Animals or objects in the road.
|
||||
* Rare objects such as trailers, ramps, cargo, open doors, etc. protruding from vehicles.
|
||||
* When abrupt braking maneuvers are required. openpilot is designed to be limited in the amount of deceleration and acceleration that it can produce.
|
||||
* When surrounding vehicles perform close cut-ins from neighbor lanes.
|
||||
* Driving on hills, narrow, or winding roads.
|
||||
* On slippery roads.
|
||||
* When towing a trailer.
|
||||
* When entering or exiting a tunnel.
|
||||
* Extremely hot or cold temperatures.
|
||||
* Bright light (due to oncoming headlights, direct sunlight, etc.).
|
||||
* Interference from other equipment that generates radar waves.
|
||||
@@ -46,7 +69,9 @@ The list above does not represent an exhaustive list of situations that may inte
|
||||
|
||||
## Limitations of openpilot DM
|
||||
|
||||
openpilot DM should not be considered an exact measurement of the alertness of the driver.
|
||||
openpilot DM displays a series of escalating warnings. Disregard of these warnings may result in openpilot being unavailable for a period of time.
|
||||
|
||||
openpilot DM should not be considered an exact measurement of the alertness of the driver. openpilot DM cannot always detect if the driver is tired or inattentive.
|
||||
|
||||
Many factors can impact the performance of openpilot DM, causing it to be unable to function as intended. These include, but are not limited to:
|
||||
|
||||
|
||||
@@ -4,6 +4,12 @@ openpilot is an Adaptive Cruise Control (ACC) and Automated Lane Centering (ALC)
|
||||
Like other ACC and ALC systems, openpilot is a failsafe passive system and it requires the
|
||||
driver to be alert and to pay attention at all times.
|
||||
|
||||
openpilot is not an autonomous driving system. It is not a collision avoidance system or a
|
||||
substitute for safe and attentive driving. The driver is always responsible for the safe
|
||||
operation of the vehicle and must be ready to take control at any time. The driver can override
|
||||
openpilot at any time by braking, accelerating, or steering the vehicle. openpilot may
|
||||
disengage without warning. Read the [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md) carefully before using openpilot.
|
||||
|
||||
To assist the driver in maintaining alertness, openpilot includes a driver monitoring feature
|
||||
that alerts when it detects driver distraction.
|
||||
|
||||
|
||||
@@ -12,11 +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
|
||||
|
||||
# Check if AGNOS update is required
|
||||
if [ "$(< /VERSION)" != "$AGNOS_VERSION" ]; then
|
||||
AGNOS_PY="$DIR/openpilot/common/hardware/comma/agnos.py"
|
||||
|
||||
+1
-10
@@ -6,17 +6,8 @@ export NUMEXPR_NUM_THREADS=1
|
||||
export OPENBLAS_NUM_THREADS=1
|
||||
export VECLIB_MAXIMUM_THREADS=1
|
||||
|
||||
# models get lower priority than ui
|
||||
# - ui is ~5ms
|
||||
# - modeld is 20ms
|
||||
# - DM is 10ms
|
||||
# in order to run ui at 60fps (16.67ms), we need to allow
|
||||
# it to preempt the model workloads. we have enough
|
||||
# headroom for this until ui is moved to the CPU.
|
||||
export QCOM_PRIORITY=12
|
||||
|
||||
if [ -z "$AGNOS_VERSION" ]; then
|
||||
export AGNOS_VERSION="19.9"
|
||||
export AGNOS_VERSION="20.6"
|
||||
fi
|
||||
|
||||
export STAGING_ROOT="/data/safe_staging"
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A small Git LFS client backed by a Hugging Face bucket."""
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import fcntl
|
||||
import fnmatch
|
||||
import functools
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
POINTER_VERSION = "https://git-lfs.github.com/spec/v1"
|
||||
POINTER_RE = re.compile(rb"\Aversion " + POINTER_VERSION.encode() + rb"\noid sha256:([0-9a-f]{64})\nsize ([0-9]+)\n\Z")
|
||||
BUCKET = os.environ.get("OPENPILOT_LFS_BUCKET", "sunnypilot/sunnypilot-lfs")
|
||||
ZERO = "0" * 40
|
||||
RANGES = 8
|
||||
RANGE_MIN = 16 << 20
|
||||
TRUE_VALUES = ("1", "ON", "YES", "TRUE")
|
||||
|
||||
|
||||
def git(*args, stdin=None, check=True):
|
||||
return subprocess.run(["git", *args], input=stdin, capture_output=True, check=check).stdout
|
||||
|
||||
|
||||
ROOT, GIT_DIR = map(Path, git("rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir").decode().splitlines())
|
||||
STORE = GIT_DIR / "lfs" / "objects"
|
||||
|
||||
|
||||
# TODO: Remove this helper and its call once migration from stock Git LFS is no longer supported.
|
||||
def remove_git_lfs_hooks(directory):
|
||||
for name in ("pre-push", "post-checkout", "post-commit", "post-merge"):
|
||||
path = directory / name
|
||||
if not path.is_file() or path.is_symlink() or path.stat().st_size > 1024:
|
||||
continue
|
||||
lines = [line.strip() for line in path.read_text(errors="replace").splitlines() if line.strip()]
|
||||
commands = {f'git lfs {name} "$@"'}
|
||||
if name == "pre-push":
|
||||
commands.update(('git lfs push --stdin $*', 'git lfs push --stdin "$@"'))
|
||||
if lines and re.fullmatch(r'exec "?[^"]*/git-lfs"? pre-push "\$@"', lines[-1]): # hooks from tools/op.sh (#38775, #39114)
|
||||
commands.add(lines[-1])
|
||||
has_lfs_guard = len(lines) == 3 and lines[1].startswith("command -v git-lfs ")
|
||||
if lines[:1] == ["#!/bin/sh"] and lines[-1] in commands and (len(lines) == 2 or has_lfs_guard):
|
||||
path.unlink()
|
||||
|
||||
|
||||
def write_executable(path, data):
|
||||
# replace atomically so git never runs a partly written script
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}-", delete=False) as tmp:
|
||||
tmp.write(data)
|
||||
os.chmod(tmp.name, 0o755)
|
||||
os.replace(tmp.name, path)
|
||||
|
||||
|
||||
def install():
|
||||
script = GIT_DIR / "lfs.py"
|
||||
hook = Path(git("rev-parse", "--path-format=absolute", "--git-path", "hooks/pre-push").decode().strip())
|
||||
remove_git_lfs_hooks(hook.parent)
|
||||
remove_git_lfs_hooks(hook.parent / "post-commit.d") # where `op post-commit` moves an existing post-commit hook
|
||||
hook_script = '#!/bin/sh\nexec "$(git rev-parse --git-common-dir)/lfs.py" pre-push "$@"\n'
|
||||
custom_hook = hook.is_file() and hook.read_text(errors="replace") != hook_script
|
||||
if Path(__file__).resolve() != script:
|
||||
write_executable(script, Path(__file__).read_bytes())
|
||||
script.chmod(0o755)
|
||||
if custom_hook:
|
||||
# keep it so pulls and updates still work; pushes won't upload LFS objects until the hook runs lfs.py
|
||||
print(f"lfs.py: keeping custom hook {hook}; add this line to it to upload LFS objects on push: {hook_script.splitlines()[-1]}", file=sys.stderr)
|
||||
else:
|
||||
hook.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_executable(hook, hook_script.encode())
|
||||
# TODO: Remove legacy worktree filter cleanup once migration from stock Git LFS is no longer supported.
|
||||
git("config", "--worktree", "--remove-section", "filter.lfs", check=False)
|
||||
git("config", "--local", "filter.lfs.process", '"$(git rev-parse --git-common-dir)/lfs.py" filter-process')
|
||||
# a client that can't run fails git rather than committing raw files; failed downloads still leave the pointer
|
||||
git("config", "--local", "filter.lfs.required", "true")
|
||||
|
||||
|
||||
def object_path(oid):
|
||||
return STORE / oid[:2] / oid[2:4] / oid
|
||||
|
||||
|
||||
def pointer(oid, size):
|
||||
return f"version {POINTER_VERSION}\noid sha256:{oid}\nsize {size}\n".encode()
|
||||
|
||||
|
||||
def parse_pointer(data):
|
||||
match = POINTER_RE.match(data)
|
||||
return (match[1].decode(), int(match[2])) if match else None
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def object_lock(oid):
|
||||
path = GIT_DIR / "lfs" / "locks" / (oid + ".lock")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a+b") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def valid(path, size):
|
||||
return path.is_file() and path.stat().st_size == size
|
||||
|
||||
|
||||
def hash_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def store(chunks):
|
||||
STORE.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="incoming-", dir=STORE) as directory:
|
||||
tmp = Path(directory) / "object"
|
||||
digest, size = hashlib.sha256(), 0
|
||||
with tmp.open("xb") as out:
|
||||
for chunk in chunks:
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
if size == 0:
|
||||
return b""
|
||||
if size <= 1024:
|
||||
data = tmp.read_bytes()
|
||||
if parse_pointer(data):
|
||||
return data
|
||||
oid = digest.hexdigest()
|
||||
dst = object_path(oid)
|
||||
with object_lock(oid):
|
||||
if not valid(dst, size):
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(tmp, dst)
|
||||
else:
|
||||
dst.touch()
|
||||
return pointer(oid, size)
|
||||
|
||||
|
||||
def transfer_workers():
|
||||
return int(git("config", "--get", "--default", "16", "lfs.concurrenttransfers"))
|
||||
|
||||
|
||||
def parallel(function, arguments, workers=None):
|
||||
if workers is None:
|
||||
workers = transfer_workers()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(function, *args) for args in arguments]
|
||||
return [future.result() for future in futures]
|
||||
|
||||
|
||||
def hf_request(url, **kwargs):
|
||||
request = urllib.request.Request(url, **kwargs)
|
||||
if os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN", "").upper() not in TRUE_VALUES:
|
||||
hf_home = Path(os.environ.get("HF_HOME", Path(os.environ.get("XDG_CACHE_HOME", "~/.cache")) / "huggingface")).expanduser()
|
||||
token_path = Path(os.environ.get("HF_TOKEN_PATH", hf_home / "token")).expanduser()
|
||||
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
||||
if not token and token_path.is_file():
|
||||
token = token_path.read_text().strip()
|
||||
if token:
|
||||
request.add_unredirected_header("Authorization", f"Bearer {token.strip()}")
|
||||
return request
|
||||
|
||||
|
||||
def object_info(objects):
|
||||
keys = [f"sha256/{oid}" for oid in objects]
|
||||
found = {}
|
||||
for start in range(0, len(keys), 1000):
|
||||
request = hf_request(f"https://huggingface.co/api/buckets/{BUCKET}/paths-info",
|
||||
data=json.dumps({"paths": keys[start:start + 1000]}).encode(), headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
found.update((item["path"], item["size"]) for item in json.load(response))
|
||||
return found
|
||||
|
||||
|
||||
def download_http(oid, size, path, span=None, url=None, headers=None):
|
||||
ranges = min(RANGES, max(1, (size + RANGE_MIN - 1) // RANGE_MIN))
|
||||
if span is None and ranges > 1:
|
||||
# each range writes its own slice of one preallocated file
|
||||
with path.open("wb") as out:
|
||||
out.truncate(size)
|
||||
parallel(download_http, [(oid, size, path, (i * size // ranges, (i + 1) * size // ranges - 1), url, headers) for i in range(ranges)], ranges)
|
||||
return
|
||||
|
||||
if url is None:
|
||||
request = hf_request(f"https://huggingface.co/buckets/{BUCKET}/resolve/sha256/{oid}")
|
||||
else:
|
||||
request = urllib.request.Request(url, headers=headers or {})
|
||||
if span is not None:
|
||||
request.add_header("Range", f"bytes={span[0]}-{span[1]}")
|
||||
expected_size = size if span is None else span[1] - span[0] + 1
|
||||
for attempt in range(4):
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response, path.open("wb" if span is None else "r+b") as out:
|
||||
if span is not None and (response.status != 206 or response.headers.get("Content-Range") != f"bytes {span[0]}-{span[1]}/{size}"):
|
||||
raise RuntimeError(f"invalid range response for {oid}")
|
||||
out.seek(0 if span is None else span[0])
|
||||
written = 0
|
||||
while chunk := response.read(1024 * 1024):
|
||||
out.write(chunk)
|
||||
written += len(chunk)
|
||||
if written != expected_size:
|
||||
raise http.client.HTTPException(f"incomplete download for {oid}")
|
||||
return
|
||||
except (urllib.error.URLError, http.client.HTTPException, TimeoutError, ConnectionError) as error:
|
||||
retryable = not isinstance(error, urllib.error.HTTPError) or error.code in (408, 429) or 500 <= error.code < 600
|
||||
if not retryable or attempt == 3:
|
||||
raise
|
||||
time.sleep(2 ** attempt)
|
||||
|
||||
|
||||
@functools.cache
|
||||
def lfs_config(key):
|
||||
# like stock git-lfs: git config first, then .lfsconfig
|
||||
value = git("config", "--get", f"lfs.{key}", check=False).decode().strip()
|
||||
return value or git("config", "-f", str(ROOT / ".lfsconfig"), "--get", f"lfs.{key}", check=False).decode().strip()
|
||||
|
||||
|
||||
def endpoint_objects(objects):
|
||||
"""oid -> (href, headers) for the objects the git-lfs server at lfs.url has. A fork's own objects aren't in the bucket."""
|
||||
found = {}
|
||||
items = list(objects.items())
|
||||
for start in range(0, len(items), 100):
|
||||
body = {"operation": "download", "transfers": ["basic"], "objects": [{"oid": oid, "size": size} for oid, size in items[start:start + 100]]}
|
||||
request = urllib.request.Request(lfs_config("url").rstrip("/") + "/objects/batch", data=json.dumps(body).encode(),
|
||||
headers={"Accept": "application/vnd.git-lfs+json", "Content-Type": "application/vnd.git-lfs+json"})
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
for item in json.load(response)["objects"]:
|
||||
if download := item.get("actions", {}).get("download"):
|
||||
found[item["oid"]] = (download["href"], download.get("header", {}))
|
||||
return found
|
||||
|
||||
|
||||
def download_one(oid, size):
|
||||
dst = object_path(oid)
|
||||
with object_lock(oid):
|
||||
if valid(dst, size):
|
||||
dst.touch()
|
||||
return dst
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix=f"{oid}-", dir=dst.parent) as directory:
|
||||
tmp = Path(directory) / "object"
|
||||
try:
|
||||
download_http(oid, size, tmp)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 404 or not lfs_config("url") or oid not in (found := endpoint_objects({oid: size})):
|
||||
raise
|
||||
download_http(oid, size, tmp, url=found[oid][0], headers=found[oid][1])
|
||||
if tmp.stat().st_size != size or hash_file(tmp) != oid:
|
||||
raise RuntimeError(f"sha256 mismatch for {oid}")
|
||||
os.replace(tmp, dst)
|
||||
return dst
|
||||
|
||||
|
||||
def excluded(name, patterns):
|
||||
for pattern in filter(None, patterns.split(",")):
|
||||
pattern = pattern.strip().lstrip("/").rstrip("/")
|
||||
paths = [name, *(str(p) for p in Path(name).parents)]
|
||||
if "/" not in pattern:
|
||||
paths.extend(Path(name).parts)
|
||||
if pattern and any(fnmatch.fnmatchcase(path, pattern) for path in paths):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def smudge(data, name, exclude, pool=None):
|
||||
if os.environ.get("GIT_LFS_SKIP_SMUDGE", "").upper() in TRUE_VALUES or excluded(name, exclude):
|
||||
return data
|
||||
parsed = parse_pointer(data)
|
||||
if not parsed:
|
||||
return data
|
||||
oid, size = parsed
|
||||
if pool is not None and not valid(object_path(oid), size):
|
||||
return pool.submit(download_one, oid, size)
|
||||
return download_one(oid, size)
|
||||
|
||||
|
||||
def read_packets(stream):
|
||||
while True:
|
||||
header = stream.read(4)
|
||||
if len(header) != 4:
|
||||
raise EOFError
|
||||
length = int(header, 16)
|
||||
if length == 0:
|
||||
return
|
||||
if length < 4:
|
||||
raise RuntimeError("unsupported pkt-line control packet")
|
||||
yield stream.read(length - 4)
|
||||
|
||||
|
||||
def write_packets(source):
|
||||
if isinstance(source, bytes):
|
||||
source = (source,)
|
||||
for chunk in source:
|
||||
for start in range(0, len(chunk), 65512):
|
||||
packet = chunk[start : start + 65512]
|
||||
sys.stdout.buffer.write(f"{len(packet) + 4:04x}".encode() + packet)
|
||||
sys.stdout.buffer.write(b"0000")
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
|
||||
def filter_process():
|
||||
exclude = lfs_config("fetchexclude")
|
||||
list(read_packets(sys.stdin.buffer))
|
||||
write_packets((b"git-filter-server\n", b"version=2\n"))
|
||||
capabilities = {line.rstrip(b"\n") for line in read_packets(sys.stdin.buffer)}
|
||||
write_packets(capability + b"\n" for capability in (b"capability=clean", b"capability=smudge", b"capability=delay")
|
||||
if capability in capabilities)
|
||||
pending, ready, pointers = {}, {}, {}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=transfer_workers()) as pool:
|
||||
while True:
|
||||
try:
|
||||
fields = dict(line.rstrip(b"\n").split(b"=", 1) for line in read_packets(sys.stdin.buffer))
|
||||
except EOFError:
|
||||
return
|
||||
if fields[b"command"] == b"list_available_blobs":
|
||||
if pending:
|
||||
concurrent.futures.wait(pending.values(), return_when=concurrent.futures.FIRST_COMPLETED)
|
||||
available = [name for name, future in pending.items() if future.done()]
|
||||
for name in available:
|
||||
ready[name] = pending.pop(name)
|
||||
write_packets(b"pathname=" + name + b"\n" for name in available)
|
||||
write_packets(b"status=success\n")
|
||||
continue
|
||||
content = read_packets(sys.stdin.buffer)
|
||||
name = fields[b"pathname"]
|
||||
if fields[b"command"] == b"clean":
|
||||
result = store(content)
|
||||
else:
|
||||
data = b"".join(content)
|
||||
if name in ready: # git sends no content when it asks again for a delayed blob
|
||||
data = pointers.pop(name)
|
||||
try:
|
||||
result = ready.pop(name).result() if name in ready else smudge(data, os.fsdecode(name), exclude,
|
||||
pool if fields.get(b"can-delay") == b"1" else None)
|
||||
except Exception as error:
|
||||
print(f"lfs.py: {os.fsdecode(name)}: {error}; leaving the pointer, run ./lfs.py pull to retry", file=sys.stderr)
|
||||
result = data
|
||||
if isinstance(result, concurrent.futures.Future):
|
||||
pending[name] = result
|
||||
pointers[name] = data
|
||||
write_packets(b"status=delayed\n")
|
||||
continue
|
||||
write_packets(b"status=success\n")
|
||||
if isinstance(result, Path):
|
||||
with result.open("rb") as source_stream:
|
||||
write_packets(iter(lambda: source_stream.read(65512), b""))
|
||||
else:
|
||||
write_packets(result)
|
||||
write_packets(())
|
||||
|
||||
|
||||
def cat_small(oids):
|
||||
checked = git("cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)", stdin=("\n".join(oids) + "\n").encode()).decode().splitlines()
|
||||
small = [line.split()[0] for line in checked if len(line.split()) == 3 and line.split()[1] == "blob" and int(line.split()[2]) <= 1024]
|
||||
stream = io.BytesIO(git("cat-file", "--batch", stdin=("\n".join(small) + "\n").encode()))
|
||||
for oid in small:
|
||||
size = int(stream.readline().split()[2])
|
||||
yield oid, stream.read(size)
|
||||
stream.read(1)
|
||||
|
||||
|
||||
def pointers_for_index():
|
||||
paths = {}
|
||||
for entry in filter(None, git("-C", str(ROOT), "ls-files", "--stage", "-z").split(b"\0")):
|
||||
metadata, path = entry.split(b"\t", 1)
|
||||
mode, oid, stage = metadata.split()
|
||||
if stage == b"0" and mode in (b"100644", b"100755"):
|
||||
paths.setdefault(oid.decode(), []).append(path.decode(errors="surrogateescape"))
|
||||
found = {}
|
||||
for oid, data in cat_small(paths):
|
||||
if parsed := parse_pointer(data):
|
||||
found.setdefault(parsed, []).extend(paths[oid])
|
||||
return found
|
||||
|
||||
|
||||
def prune():
|
||||
heads, blobs = [], set()
|
||||
for directory in [GIT_DIR, *(GIT_DIR / "worktrees").glob("*")]:
|
||||
args = ("-C", str(ROOT), "--git-dir", str(directory))
|
||||
if head := git(*args, "rev-parse", "--verify", "--quiet", "HEAD", check=False).decode().strip():
|
||||
heads.append(head)
|
||||
entries = git(*args, "ls-files", "--stage", "-z")
|
||||
blobs.update(entry.split(b"\t", 1)[0].split()[1].decode() for entry in entries.split(b"\0") if entry)
|
||||
stashes = git("reflog", "show", "--format=%H %P", "refs/stash", check=False).decode().split()
|
||||
for ref in set(heads + stashes):
|
||||
entries = git("ls-tree", "-r", "-z", ref)
|
||||
blobs.update(entry.split(b"\t", 1)[0].split()[2].decode() for entry in entries.split(b"\0") if entry)
|
||||
remote = git("config", "--get", "--default", "origin", "lfs.pruneremotetocheck").decode().strip()
|
||||
blobs.update(git("rev-list", "--objects", "--no-object-names", *heads, *stashes, "--all", "--not",
|
||||
f"--remotes={remote}").decode().splitlines())
|
||||
retained = {parsed[0] for _oid, data in cat_small(blobs) if (parsed := parse_pointer(data))}
|
||||
cutoff = time.time() - 7 * 24 * 60 * 60 # noqa: TID251
|
||||
removed, freed = 0, 0
|
||||
for path in STORE.glob("??/??/*"):
|
||||
if path.name in retained or not re.fullmatch(r"[0-9a-f]{64}", path.name):
|
||||
continue
|
||||
with object_lock(path.name):
|
||||
if path.is_file() and path.stat().st_mtime < cutoff:
|
||||
freed += path.stat().st_size
|
||||
path.unlink()
|
||||
removed += 1
|
||||
print(f"Pruned {removed} objects ({freed / 1024**2:.1f} MiB)")
|
||||
|
||||
|
||||
def pull(exclude=None):
|
||||
install()
|
||||
found = pointers_for_index()
|
||||
if exclude is None:
|
||||
exclude = lfs_config("fetchexclude")
|
||||
if exclude:
|
||||
found = {obj: kept for obj, paths in found.items() if (kept := [path for path in paths if not excluded(path, exclude)])}
|
||||
parallel(download_one, found)
|
||||
materialized = []
|
||||
for (oid, size), paths in found.items():
|
||||
for name in paths:
|
||||
relative = Path(name)
|
||||
if any((ROOT / part).is_symlink() for part in (relative, *relative.parents)):
|
||||
continue
|
||||
path = ROOT / relative
|
||||
try:
|
||||
if path.stat().st_size > 1024 or parse_pointer(path.read_bytes()) != (oid, size):
|
||||
continue
|
||||
except (FileNotFoundError, IsADirectoryError):
|
||||
continue
|
||||
with tempfile.TemporaryDirectory(prefix=path.name + "-", dir=path.parent) as directory:
|
||||
tmp = shutil.copyfile(object_path(oid), Path(directory) / "object")
|
||||
shutil.copymode(path, tmp)
|
||||
Path(tmp).replace(path)
|
||||
materialized.append(name)
|
||||
if materialized:
|
||||
# Clear pointer stat data without changing staged blob IDs or modes.
|
||||
entries = git("--literal-pathspecs", "-C", str(ROOT), "ls-files", "--stage", "-z", "--", *materialized)
|
||||
git("update-index", "-z", "--index-info", stdin=entries)
|
||||
git("update-index", "-q", "--refresh", check=False)
|
||||
|
||||
|
||||
def bucket_request(path, data=None):
|
||||
headers = {"Content-Type": "application/x-ndjson"} if data is not None else {}
|
||||
request = hf_request(f"https://huggingface.co/api/buckets/{BUCKET}/{path}", data=data, headers=headers)
|
||||
for attempt in range(4):
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.read(), response.headers
|
||||
except (urllib.error.URLError, http.client.HTTPException, TimeoutError, ConnectionError) as error:
|
||||
retryable = not isinstance(error, urllib.error.HTTPError) or error.code in (408, 429) or 500 <= error.code < 600
|
||||
if not retryable or attempt == 3:
|
||||
raise
|
||||
time.sleep(2 ** attempt)
|
||||
|
||||
|
||||
def upload_xet(objects, upload_files):
|
||||
def connection():
|
||||
_, headers = bucket_request("xet-write-token")
|
||||
return headers["X-Xet-Cas-Url"], (headers["X-Xet-Access-Token"], int(headers["X-Xet-Token-Expiration"]))
|
||||
|
||||
oids = list(objects)
|
||||
for start in range(0, len(oids), 100):
|
||||
batch = oids[start:start + 100]
|
||||
paths = [object_path(oid) for oid in batch]
|
||||
endpoint, token = connection()
|
||||
infos = upload_files([str(path) for path in paths], endpoint, token, lambda: connection()[1], None, "bucket", skip_sha256=True)
|
||||
payload = b"".join(json.dumps({"type": "addFile", "path": f"sha256/{oid}", "xetHash": info.hash,
|
||||
"mtime": int(path.stat().st_mtime * 1000)}).encode() + b"\n"
|
||||
for oid, path, info in zip(batch, paths, infos, strict=True))
|
||||
bucket_request("batch", payload)
|
||||
|
||||
|
||||
def upload(objects):
|
||||
objects = dict(objects)
|
||||
if not objects:
|
||||
return
|
||||
existing = object_info(objects)
|
||||
pending = {}
|
||||
for oid, size in objects.items():
|
||||
key = f"sha256/{oid}"
|
||||
if key in existing:
|
||||
if existing[key] != size:
|
||||
raise RuntimeError(f"invalid bucket object {oid}: size {existing[key]}, expected {size}")
|
||||
continue
|
||||
pending[oid] = size
|
||||
if not pending:
|
||||
return
|
||||
try:
|
||||
from hf_xet import upload_files
|
||||
except ImportError:
|
||||
raise RuntimeError("Missing hf-xet: run 'uv sync' and activate .venv.") from None
|
||||
for oid, size in pending.items():
|
||||
path = object_path(oid)
|
||||
if not valid(path, size):
|
||||
raise RuntimeError(f"missing local LFS object {oid}")
|
||||
if hash_file(path) != oid:
|
||||
raise RuntimeError(f"local sha256 mismatch for {oid}")
|
||||
upload_xet(pending, upload_files)
|
||||
uploaded = object_info(pending)
|
||||
for oid, size in pending.items():
|
||||
if uploaded.get(f"sha256/{oid}") != size:
|
||||
raise RuntimeError(f"uploaded object {oid} is missing or has the wrong size")
|
||||
|
||||
|
||||
def pre_push(remote):
|
||||
if os.environ.get("GIT_LFS_SKIP_PUSH", "").upper() in TRUE_VALUES:
|
||||
return
|
||||
input_data = sys.stdin.buffer.read()
|
||||
updates = (line.decode().split() for line in input_data.splitlines())
|
||||
local_oids = [local_oid for _local_ref, local_oid, _remote_ref, _remote_oid in updates if local_oid != ZERO]
|
||||
if not local_oids:
|
||||
return
|
||||
output = git("rev-list", "--objects", "--no-object-names", *local_oids, "--not", f"--remotes={remote}")
|
||||
object_ids = output.decode().splitlines()
|
||||
objects = [parsed for _oid, data in cat_small(object_ids) if (parsed := parse_pointer(data))]
|
||||
try:
|
||||
upload(objects)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code not in (401, 403):
|
||||
raise
|
||||
if lfs_config("url"):
|
||||
# without write access to the bucket, a fork's objects only need to be on its own LFS server
|
||||
in_bucket = object_info(dict(objects)) # upload() asked this too, but doesn't return it
|
||||
pending = {oid: size for oid, size in objects if f"sha256/{oid}" not in in_bucket}
|
||||
if missing := sorted(pending.keys() - endpoint_objects(pending).keys()):
|
||||
sys.exit(f"lfs.py: {len(missing)} LFS objects are in neither {BUCKET} nor {lfs_config('url')}, push them first: " +
|
||||
f"git lfs push --object-id {remote} {' '.join(missing)}")
|
||||
return
|
||||
sys.exit(f"lfs.py: uploading LFS objects to {BUCKET} needs a Hugging Face token with write access (hf auth login, or set HF_TOKEN)")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("command", choices=("filter-process", "pull", "pre-push", "install", "ls-files", "prune"))
|
||||
parser.add_argument("remote", nargs="?", default="origin")
|
||||
parser.add_argument("url", nargs="?")
|
||||
parser.add_argument("--exclude", help="comma-separated path globs to leave as pointers; overrides lfs.fetchexclude")
|
||||
args = parser.parse_args()
|
||||
if args.command == "filter-process":
|
||||
filter_process()
|
||||
elif args.command == "pull":
|
||||
pull(args.exclude)
|
||||
elif args.command == "pre-push":
|
||||
pre_push(args.remote)
|
||||
elif args.command == "install":
|
||||
install()
|
||||
elif args.command == "prune":
|
||||
prune()
|
||||
elif args.command == "ls-files":
|
||||
for (oid, _size), paths in pointers_for_index().items():
|
||||
for path in paths:
|
||||
print(f"{oid} {path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1
-1
Submodule msgq_repo updated: e7396e76da...5ae2281f6f
+1
-1
Submodule opendbc_repo updated: 2f514586b2...07fb3ab9bc
@@ -15,7 +15,6 @@ cereal = env.Library('cereal', [f'gen/cpp/{s}.c++' for s in all_output])
|
||||
|
||||
# Build messaging
|
||||
services_h = env.Command(['services.h'], ['services.py'], 'python3 ' + cereal_dir.path + '/services.py > $TARGET')
|
||||
env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc', 'messaging/bridge_zmq.cc'], LIBS=[msgq, common, 'pthread'])
|
||||
|
||||
socketmaster = env.Library('socketmaster', ['messaging/socketmaster.cc'])
|
||||
|
||||
|
||||
@@ -483,7 +483,16 @@ struct ModelDataV2SP @0xa1680744031fdb2d {
|
||||
}
|
||||
}
|
||||
|
||||
struct CustomReserved10 @0xcb9fd56c7057593a {
|
||||
struct GpsLocationSP @0xcb9fd56c7057593a {
|
||||
latitude @0 :Float64;
|
||||
longitude @1 :Float64;
|
||||
speed @2 :Float32;
|
||||
bearingDeg @3 :Float32;
|
||||
horizontalAccuracy @4 :Float32; # m
|
||||
bearingAccuracyDeg @5 :Float32;
|
||||
hasFix @6 :Bool;
|
||||
gpsOK @7 :Bool; # a raw fix arrived in the last 2 s
|
||||
fused @8 :Bool; # false while passing the raw fix through
|
||||
}
|
||||
|
||||
struct CustomReserved11 @0xc2243c65e0340384 {
|
||||
|
||||
+23
-17
@@ -100,6 +100,7 @@ struct OnroadEvent @0xc4fa6047f024e718 {
|
||||
startupNoControl @62;
|
||||
startupNoSecOcKey @63;
|
||||
startupMaster @64;
|
||||
startupCruiseCanceled @105;
|
||||
fcw @65;
|
||||
steerSaturated @66;
|
||||
belowEngageSpeed @67;
|
||||
@@ -120,10 +121,7 @@ struct OnroadEvent @0xc4fa6047f024e718 {
|
||||
steerTimeLimit @83;
|
||||
vehicleSensorsInvalid @84;
|
||||
locationdTemporaryError @85;
|
||||
locationdPermanentError @86;
|
||||
paramsdTemporaryError @87;
|
||||
paramsdPermanentError @88;
|
||||
actuatorsApiUnavailable @89;
|
||||
espActive @90;
|
||||
personalityChanged @91;
|
||||
aeb @92;
|
||||
@@ -139,6 +137,9 @@ struct OnroadEvent @0xc4fa6047f024e718 {
|
||||
usbErrorDEPRECATED @78;
|
||||
audioFeedbackDEPRECATED @97;
|
||||
bigModelReadyDEPRECATED @101;
|
||||
locationdPermanentErrorDEPRECATED @86;
|
||||
paramsdPermanentErrorDEPRECATED @88;
|
||||
actuatorsApiUnavailableDEPRECATED @89;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,25 +591,29 @@ struct PandaState @0xa7649e2575e4591e {
|
||||
interruptRateGmlanDEPRECATED @6;
|
||||
interruptRateInterrupts @7;
|
||||
interruptRateSpiDma @8;
|
||||
interruptRateSpiCs @9;
|
||||
interruptRateUart1 @10;
|
||||
interruptRateUart2 @11;
|
||||
interruptRateUart3 @12;
|
||||
interruptRateUart5 @13;
|
||||
interruptRateUartDma @14;
|
||||
selfTestCpu @9;
|
||||
selfTestRam @10;
|
||||
selfTestFlash @11;
|
||||
ecc @12;
|
||||
outputReadback @13;
|
||||
dma @14;
|
||||
interruptRateUsb @15;
|
||||
interruptRateTim1 @16;
|
||||
interruptRateTim3 @17;
|
||||
clock @16;
|
||||
interruptMissing @17;
|
||||
registerDivergent @18;
|
||||
interruptRateKlineInit @19;
|
||||
interruptRateClockSource @20;
|
||||
interruptRateTick @21;
|
||||
interruptRateExti @22;
|
||||
interruptRateSpi @23;
|
||||
interruptRateUart7 @24;
|
||||
adc @24;
|
||||
sirenMalfunction @25;
|
||||
heartbeatLoopWatchdog @26;
|
||||
# Update max fault type in boardd when adding faults
|
||||
interruptRateSoundDma @27;
|
||||
mpu @28;
|
||||
timer @29;
|
||||
safetyRedundancy @30;
|
||||
# Update max fault type in pandad when adding faults
|
||||
}
|
||||
|
||||
enum PandaType @0x8a58adf93e5b3751 {
|
||||
@@ -832,7 +837,8 @@ struct SelfdriveState {
|
||||
refuse @3;
|
||||
|
||||
warningSoft @4;
|
||||
warningImmediate @5;
|
||||
warningImmediateSystem @5;
|
||||
warningImmediateUser @11;
|
||||
|
||||
prompt @6;
|
||||
promptRepeat @7;
|
||||
@@ -1240,7 +1246,6 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
|
||||
shouldStop @37: Bool;
|
||||
allowThrottle @38: Bool;
|
||||
allowBrake @39: Bool;
|
||||
accelBoost @40 :Float32;
|
||||
|
||||
|
||||
solverExecutionTime @35 :Float32;
|
||||
@@ -1282,6 +1287,7 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
|
||||
gpsTrajectory @12 :Deprecated.GpsTrajectory;
|
||||
gpsPlannerActive @19 :Bool;
|
||||
personality @36 :LongitudinalPersonality;
|
||||
accelBoost @40 :Float32;
|
||||
}
|
||||
}
|
||||
struct UiPlan {
|
||||
@@ -2648,7 +2654,7 @@ struct Event {
|
||||
carStateSP @114 :Custom.CarStateSP;
|
||||
liveMapDataSP @115 :Custom.LiveMapDataSP;
|
||||
modelDataV2SP @116 :Custom.ModelDataV2SP;
|
||||
customReserved10 @136 :Custom.CustomReserved10;
|
||||
gpsLocationSP @136 :Custom.GpsLocationSP;
|
||||
customReserved11 @137 :Custom.CustomReserved11;
|
||||
customReserved12 @138 :Custom.CustomReserved12;
|
||||
customReserved13 @139 :Custom.CustomReserved13;
|
||||
@@ -2701,7 +2707,7 @@ struct Event {
|
||||
lateralPlanDEPRECATED @64 :LateralPlan;
|
||||
navModelDEPRECATED @104 :Deprecated.NavModelData;
|
||||
uiPlanDEPRECATED @106 :UiPlan;
|
||||
liveLocationKalman @72 :LiveLocationKalman;
|
||||
liveLocationKalmanDEPRECATED @72 :LiveLocationKalman;
|
||||
liveTracksDEPRECATED @16 :List(Deprecated.LiveTracksDEPRECATED);
|
||||
onroadEventsDEPRECATED @68: List(Car.OnroadEventDEPRECATED);
|
||||
gyroscope2DEPRECATED @100 :SensorEventData;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# must be built with scons
|
||||
from msgq import fake_event_handle, drain_sock_raw, MultiplePublishersError, IpcError, \
|
||||
Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \
|
||||
Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \
|
||||
set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event
|
||||
import msgq
|
||||
import os
|
||||
@@ -15,7 +15,6 @@ from openpilot.common.utils import MovingAverage
|
||||
|
||||
__all__ = (
|
||||
"NO_TRAVERSAL_LIMIT",
|
||||
"Context",
|
||||
"FrequencyTracker",
|
||||
"IpcError",
|
||||
"MultiplePublishersError",
|
||||
@@ -37,7 +36,6 @@ __all__ = (
|
||||
"recv_one_or_none",
|
||||
"recv_one_retry",
|
||||
"recv_sock",
|
||||
"reset_context",
|
||||
"set_fake_prefix",
|
||||
"sub_sock",
|
||||
"toggle_fake_events",
|
||||
@@ -53,18 +51,14 @@ def pub_sock(endpoint: str) -> PubSocket:
|
||||
return msgq.pub_sock(endpoint, segment_size)
|
||||
|
||||
|
||||
def sub_sock(endpoint: str, poller: Poller | None = None, addr: str = "127.0.0.1",
|
||||
def sub_sock(endpoint: str, poller: Poller | None = None,
|
||||
conflate: bool = False, timeout: int | None = None) -> SubSocket:
|
||||
service = SERVICE_LIST.get(endpoint)
|
||||
segment_size = service.queue_size if service else 0
|
||||
return msgq.sub_sock(endpoint, poller=poller, addr=addr, conflate=conflate,
|
||||
return msgq.sub_sock(endpoint, poller=poller, conflate=conflate,
|
||||
timeout=timeout, segment_size=segment_size)
|
||||
|
||||
|
||||
def reset_context():
|
||||
msgq.context = Context()
|
||||
|
||||
|
||||
def log_from_bytes(dat: bytes, struct: capnp.lib.capnp._StructModule = log.Event) -> capnp.lib.capnp._DynamicStructReader:
|
||||
with struct.from_bytes(dat, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as msg:
|
||||
return msg
|
||||
@@ -181,7 +175,7 @@ class FrequencyTracker:
|
||||
class SubMaster:
|
||||
def __init__(self, services: list[str], poll: str | None = None,
|
||||
ignore_alive: list[str] | None = None, ignore_avg_freq: list[str] | None = None,
|
||||
ignore_valid: list[str] | None = None, addr: str = "127.0.0.1", frequency: float | None = None):
|
||||
ignore_valid: list[str] | None = None, frequency: float | None = None):
|
||||
self.frame = -1
|
||||
self.services = services
|
||||
self.seen = dict.fromkeys(services, False)
|
||||
@@ -216,7 +210,7 @@ class SubMaster:
|
||||
|
||||
for s in services:
|
||||
p = self.poller if s not in self.non_polled_services else None
|
||||
self.sock[s] = sub_sock(s, poller=p, addr=addr, conflate=True)
|
||||
self.sock[s] = sub_sock(s, poller=p, conflate=True)
|
||||
|
||||
try:
|
||||
data = new_message(s)
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
#include <cassert>
|
||||
|
||||
#include "openpilot/cereal/messaging/msgq_to_zmq.h"
|
||||
#include "openpilot/cereal/services.h"
|
||||
#include "common/util.h"
|
||||
|
||||
ExitHandler do_exit;
|
||||
|
||||
static std::vector<std::string> get_services(const std::string &whitelist_str, bool zmq_to_msgq) {
|
||||
std::vector<std::string> service_list;
|
||||
for (const auto& it : services) {
|
||||
std::string name = it.second.name;
|
||||
bool in_whitelist = whitelist_str.find(name) != std::string::npos;
|
||||
if (zmq_to_msgq && !in_whitelist) {
|
||||
continue;
|
||||
}
|
||||
service_list.push_back(name);
|
||||
}
|
||||
return service_list;
|
||||
}
|
||||
|
||||
void msgq_to_zmq(const std::vector<std::string> &endpoints, const std::string &ip) {
|
||||
MsgqToZmq bridge;
|
||||
bridge.run(endpoints, ip);
|
||||
}
|
||||
|
||||
void zmq_to_msgq(const std::vector<std::string> &endpoints, const std::string &ip) {
|
||||
auto poller = std::make_unique<BridgeZmqPoller>();
|
||||
auto pub_context = std::make_unique<Context>();
|
||||
auto sub_context = std::make_unique<BridgeZmqContext>();
|
||||
std::map<BridgeZmqSubSocket *, PubSocket *> sub2pub;
|
||||
|
||||
for (auto endpoint : endpoints) {
|
||||
auto pub_sock = new PubSocket();
|
||||
auto sub_sock = new BridgeZmqSubSocket();
|
||||
size_t queue_size = services.at(endpoint).queue_size;
|
||||
pub_sock->connect(pub_context.get(), endpoint, true, queue_size);
|
||||
sub_sock->connect(sub_context.get(), endpoint, ip, false);
|
||||
|
||||
poller->registerSocket(sub_sock);
|
||||
sub2pub[sub_sock] = pub_sock;
|
||||
}
|
||||
|
||||
while (!do_exit) {
|
||||
for (auto sub_sock : poller->poll(100)) {
|
||||
std::unique_ptr<Message> msg(sub_sock->receive(true));
|
||||
if (msg) {
|
||||
sub2pub[sub_sock]->sendMessage(msg.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up allocated sockets
|
||||
for (auto &[sub_sock, pub_sock] : sub2pub) {
|
||||
delete sub_sock;
|
||||
delete pub_sock;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
bool is_zmq_to_msgq = argc > 2;
|
||||
std::string ip = is_zmq_to_msgq ? argv[1] : "127.0.0.1";
|
||||
std::string whitelist_str = is_zmq_to_msgq ? std::string(argv[2]) : "";
|
||||
std::vector<std::string> endpoints = get_services(whitelist_str, is_zmq_to_msgq);
|
||||
|
||||
if (is_zmq_to_msgq) {
|
||||
zmq_to_msgq(endpoints, ip);
|
||||
} else {
|
||||
msgq_to_zmq(endpoints, ip);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
#include "openpilot/cereal/messaging/bridge_zmq.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <unistd.h>
|
||||
|
||||
static size_t fnv1a_hash(const std::string &str) {
|
||||
const size_t fnv_prime = 0x100000001b3;
|
||||
size_t hash_value = 0xcbf29ce484222325;
|
||||
for (char c : str) {
|
||||
hash_value ^= (unsigned char)c;
|
||||
hash_value *= fnv_prime;
|
||||
}
|
||||
return hash_value;
|
||||
}
|
||||
|
||||
// FIXME: This is a hack to get the port number from the socket name, might have collisions.
|
||||
static int get_port(std::string endpoint) {
|
||||
size_t hash_value = fnv1a_hash(endpoint);
|
||||
int start_port = 8023;
|
||||
int max_port = 65535;
|
||||
return start_port + (hash_value % (max_port - start_port));
|
||||
}
|
||||
|
||||
BridgeZmqContext::BridgeZmqContext() {
|
||||
context = zmq_ctx_new();
|
||||
}
|
||||
|
||||
BridgeZmqContext::~BridgeZmqContext() {
|
||||
if (context != nullptr) {
|
||||
zmq_ctx_term(context);
|
||||
}
|
||||
}
|
||||
|
||||
void BridgeZmqMessage::init(size_t sz) {
|
||||
size = sz;
|
||||
data = new char[size];
|
||||
}
|
||||
|
||||
void BridgeZmqMessage::init(char *d, size_t sz) {
|
||||
size = sz;
|
||||
data = new char[size];
|
||||
memcpy(data, d, size);
|
||||
}
|
||||
|
||||
void BridgeZmqMessage::close() {
|
||||
if (size > 0) {
|
||||
delete[] data;
|
||||
}
|
||||
data = nullptr;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
BridgeZmqMessage::~BridgeZmqMessage() {
|
||||
close();
|
||||
}
|
||||
|
||||
int BridgeZmqSubSocket::connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate, bool check_endpoint) {
|
||||
sock = zmq_socket(context->getRawContext(), ZMQ_SUB);
|
||||
if (sock == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0);
|
||||
|
||||
if (conflate) {
|
||||
int arg = 1;
|
||||
zmq_setsockopt(sock, ZMQ_CONFLATE, &arg, sizeof(int));
|
||||
}
|
||||
|
||||
int reconnect_ivl = 500;
|
||||
zmq_setsockopt(sock, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl, sizeof(reconnect_ivl));
|
||||
|
||||
full_endpoint = "tcp://" + address + ":";
|
||||
if (check_endpoint) {
|
||||
full_endpoint += std::to_string(get_port(endpoint));
|
||||
} else {
|
||||
full_endpoint += endpoint;
|
||||
}
|
||||
|
||||
return zmq_connect(sock, full_endpoint.c_str());
|
||||
}
|
||||
|
||||
void BridgeZmqSubSocket::setTimeout(int timeout) {
|
||||
zmq_setsockopt(sock, ZMQ_RCVTIMEO, &timeout, sizeof(int));
|
||||
}
|
||||
|
||||
Message *BridgeZmqSubSocket::receive(bool non_blocking) {
|
||||
zmq_msg_t msg;
|
||||
assert(zmq_msg_init(&msg) == 0);
|
||||
|
||||
int flags = non_blocking ? ZMQ_DONTWAIT : 0;
|
||||
int rc = zmq_msg_recv(&msg, sock, flags);
|
||||
|
||||
Message *ret = nullptr;
|
||||
if (rc >= 0) {
|
||||
ret = new BridgeZmqMessage;
|
||||
ret->init((char *)zmq_msg_data(&msg), zmq_msg_size(&msg));
|
||||
}
|
||||
|
||||
zmq_msg_close(&msg);
|
||||
return ret;
|
||||
}
|
||||
|
||||
BridgeZmqSubSocket::~BridgeZmqSubSocket() {
|
||||
if (sock != nullptr) {
|
||||
zmq_close(sock);
|
||||
}
|
||||
}
|
||||
|
||||
int BridgeZmqPubSocket::connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint) {
|
||||
sock = zmq_socket(context->getRawContext(), ZMQ_PUB);
|
||||
if (sock == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
full_endpoint = "tcp://*:";
|
||||
if (check_endpoint) {
|
||||
full_endpoint += std::to_string(get_port(endpoint));
|
||||
} else {
|
||||
full_endpoint += endpoint;
|
||||
}
|
||||
|
||||
// ZMQ pub sockets cannot be shared between processes, so we need to ensure pid stays the same.
|
||||
pid = getpid();
|
||||
|
||||
return zmq_bind(sock, full_endpoint.c_str());
|
||||
}
|
||||
|
||||
int BridgeZmqPubSocket::sendMessage(Message *message) {
|
||||
assert(pid == getpid());
|
||||
return zmq_send(sock, message->getData(), message->getSize(), ZMQ_DONTWAIT);
|
||||
}
|
||||
|
||||
int BridgeZmqPubSocket::send(char *data, size_t size) {
|
||||
assert(pid == getpid());
|
||||
return zmq_send(sock, data, size, ZMQ_DONTWAIT);
|
||||
}
|
||||
|
||||
BridgeZmqPubSocket::~BridgeZmqPubSocket() {
|
||||
if (sock != nullptr) {
|
||||
zmq_close(sock);
|
||||
}
|
||||
}
|
||||
|
||||
void BridgeZmqPoller::registerSocket(BridgeZmqSubSocket *socket) {
|
||||
assert(num_polls + 1 < (sizeof(polls) / sizeof(polls[0])));
|
||||
polls[num_polls].socket = socket->getRawSocket();
|
||||
polls[num_polls].events = ZMQ_POLLIN;
|
||||
|
||||
sockets.push_back(socket);
|
||||
num_polls++;
|
||||
}
|
||||
|
||||
std::vector<BridgeZmqSubSocket *> BridgeZmqPoller::poll(int timeout) {
|
||||
std::vector<BridgeZmqSubSocket *> ret;
|
||||
|
||||
int rc = zmq_poll(polls, num_polls, timeout);
|
||||
if (rc < 0) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < num_polls; i++) {
|
||||
if (polls[i].revents) {
|
||||
ret.push_back(sockets[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <zmq.h>
|
||||
|
||||
#include "msgq/ipc.h"
|
||||
|
||||
class BridgeZmqContext {
|
||||
public:
|
||||
BridgeZmqContext();
|
||||
void *getRawContext() { return context; }
|
||||
~BridgeZmqContext();
|
||||
|
||||
private:
|
||||
void *context = nullptr;
|
||||
};
|
||||
|
||||
class BridgeZmqMessage : public Message {
|
||||
public:
|
||||
void init(size_t size);
|
||||
void init(char *data, size_t size);
|
||||
void close();
|
||||
size_t getSize() { return size; }
|
||||
char *getData() { return data; }
|
||||
~BridgeZmqMessage();
|
||||
|
||||
private:
|
||||
char *data = nullptr;
|
||||
size_t size = 0;
|
||||
};
|
||||
|
||||
class BridgeZmqSubSocket {
|
||||
public:
|
||||
int connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate = false, bool check_endpoint = true);
|
||||
void setTimeout(int timeout);
|
||||
Message *receive(bool non_blocking = false);
|
||||
void *getRawSocket() { return sock; }
|
||||
~BridgeZmqSubSocket();
|
||||
|
||||
private:
|
||||
void *sock = nullptr;
|
||||
std::string full_endpoint;
|
||||
};
|
||||
|
||||
class BridgeZmqPubSocket {
|
||||
public:
|
||||
int connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint = true);
|
||||
int sendMessage(Message *message);
|
||||
int send(char *data, size_t size);
|
||||
void *getRawSocket() { return sock; }
|
||||
~BridgeZmqPubSocket();
|
||||
|
||||
private:
|
||||
void *sock = nullptr;
|
||||
std::string full_endpoint;
|
||||
int pid = -1;
|
||||
};
|
||||
|
||||
class BridgeZmqPoller {
|
||||
public:
|
||||
void registerSocket(BridgeZmqSubSocket *socket);
|
||||
std::vector<BridgeZmqSubSocket *> poll(int timeout);
|
||||
|
||||
private:
|
||||
static constexpr size_t MAX_BRIDGE_ZMQ_POLLERS = 128;
|
||||
std::vector<BridgeZmqSubSocket *> sockets;
|
||||
zmq_pollitem_t polls[MAX_BRIDGE_ZMQ_POLLERS] = {};
|
||||
size_t num_polls = 0;
|
||||
};
|
||||
@@ -15,7 +15,7 @@
|
||||
class SubMaster {
|
||||
public:
|
||||
SubMaster(const std::vector<const char *> &service_list, const std::vector<const char *> &poll = {},
|
||||
const char *address = nullptr, const std::vector<const char *> &ignore_alive = {});
|
||||
const std::vector<const char *> &ignore_alive = {});
|
||||
void update(int timeout = 1000);
|
||||
void update_msgs(uint64_t current_time, const std::vector<std::pair<std::string, cereal::Event::Reader>> &messages);
|
||||
inline bool allAlive(const std::vector<const char *> &service_list = {}) { return all_(service_list, false, true); }
|
||||
@@ -77,6 +77,7 @@ public:
|
||||
PubMaster(const std::vector<const char *> &service_list);
|
||||
inline int send(const char *name, capnp::byte *data, size_t size) { return sockets_.at(name)->send((char *)data, size); }
|
||||
int send(const char *name, MessageBuilder &msg);
|
||||
inline bool all_readers_updated(const char *name) { return sockets_.at(name)->all_readers_updated(); }
|
||||
~PubMaster();
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
#include "openpilot/cereal/messaging/msgq_to_zmq.h"
|
||||
|
||||
#include <cassert>
|
||||
|
||||
#include "openpilot/cereal/services.h"
|
||||
#include "common/util.h"
|
||||
|
||||
extern ExitHandler do_exit;
|
||||
|
||||
// Max messages to process per socket per poll
|
||||
constexpr int MAX_MESSAGES_PER_SOCKET = 50;
|
||||
|
||||
static std::string recv_zmq_msg(void *sock) {
|
||||
zmq_msg_t msg;
|
||||
zmq_msg_init(&msg);
|
||||
std::string ret;
|
||||
if (zmq_msg_recv(&msg, sock, 0) > 0) {
|
||||
ret.assign((char *)zmq_msg_data(&msg), zmq_msg_size(&msg));
|
||||
}
|
||||
zmq_msg_close(&msg);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void MsgqToZmq::run(const std::vector<std::string> &endpoints, const std::string &ip) {
|
||||
zmq_context = std::make_unique<BridgeZmqContext>();
|
||||
msgq_context = std::make_unique<Context>();
|
||||
|
||||
// Create ZMQPubSockets for each endpoint
|
||||
for (const auto &endpoint : endpoints) {
|
||||
auto &socket_pair = socket_pairs.emplace_back();
|
||||
socket_pair.endpoint = endpoint;
|
||||
socket_pair.pub_sock = std::make_unique<BridgeZmqPubSocket>();
|
||||
int ret = socket_pair.pub_sock->connect(zmq_context.get(), endpoint);
|
||||
if (ret != 0) {
|
||||
printf("Failed to create ZMQ publisher for [%s]: %s\n", endpoint.c_str(), zmq_strerror(zmq_errno()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Start ZMQ monitoring thread to monitor socket events
|
||||
std::thread thread(&MsgqToZmq::zmqMonitorThread, this);
|
||||
|
||||
// Main loop for processing messages
|
||||
while (!do_exit) {
|
||||
{
|
||||
std::unique_lock lk(mutex);
|
||||
cv.wait(lk, [this]() { return do_exit || !sub2pub.empty(); });
|
||||
if (do_exit) break;
|
||||
|
||||
for (auto sub_sock : msgq_poller->poll(100)) {
|
||||
// Process messages for each socket
|
||||
BridgeZmqPubSocket *pub_sock = sub2pub.at(sub_sock);
|
||||
for (int i = 0; i < MAX_MESSAGES_PER_SOCKET; ++i) {
|
||||
auto msg = std::unique_ptr<Message>(sub_sock->receive(true));
|
||||
if (!msg) break;
|
||||
|
||||
while (pub_sock->sendMessage(msg.get()) == -1) {
|
||||
if (errno != EINTR) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
util::sleep_for(1); // Give zmqMonitorThread a chance to acquire the mutex
|
||||
}
|
||||
|
||||
thread.join();
|
||||
}
|
||||
|
||||
void MsgqToZmq::zmqMonitorThread() {
|
||||
std::vector<zmq_pollitem_t> pollitems;
|
||||
|
||||
// Set up ZMQ monitor for each pub socket
|
||||
for (int i = 0; i < socket_pairs.size(); ++i) {
|
||||
std::string addr = "inproc://op-bridge-monitor-" + std::to_string(i);
|
||||
zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED);
|
||||
|
||||
void *monitor_socket = zmq_socket(zmq_context->getRawContext(), ZMQ_PAIR);
|
||||
zmq_connect(monitor_socket, addr.c_str());
|
||||
pollitems.emplace_back(zmq_pollitem_t{.socket = monitor_socket, .events = ZMQ_POLLIN});
|
||||
}
|
||||
|
||||
while (!do_exit) {
|
||||
int ret = zmq_poll(pollitems.data(), pollitems.size(), 1000);
|
||||
if (ret < 0) {
|
||||
if (errno == EINTR) {
|
||||
// Due to frequent EINTR signals from msgq, introduce a brief delay (200 ms)
|
||||
// to reduce CPU usage during retry attempts.
|
||||
util::sleep_for(200);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int i = 0; i < pollitems.size(); ++i) {
|
||||
if (pollitems[i].revents & ZMQ_POLLIN) {
|
||||
// First frame in message contains event number and value
|
||||
std::string frame = recv_zmq_msg(pollitems[i].socket);
|
||||
if (frame.empty()) continue;
|
||||
|
||||
uint16_t event_type = *(uint16_t *)(frame.data());
|
||||
|
||||
// Second frame in message contains event address
|
||||
frame = recv_zmq_msg(pollitems[i].socket);
|
||||
if (frame.empty()) continue;
|
||||
|
||||
std::unique_lock lk(mutex);
|
||||
auto &pair = socket_pairs[i];
|
||||
if (event_type & ZMQ_EVENT_ACCEPTED) {
|
||||
printf("socket [%s] connected\n", pair.endpoint.c_str());
|
||||
if (++pair.connected_clients == 1) {
|
||||
// Create new MSGQ subscriber socket and map to ZMQ publisher
|
||||
pair.sub_sock = std::make_unique<MSGQSubSocket>();
|
||||
size_t queue_size = services.at(pair.endpoint).queue_size;
|
||||
pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1", false, true, queue_size);
|
||||
sub2pub[pair.sub_sock.get()] = pair.pub_sock.get();
|
||||
registerSockets();
|
||||
}
|
||||
} else if (event_type & ZMQ_EVENT_DISCONNECTED) {
|
||||
printf("socket [%s] disconnected\n", pair.endpoint.c_str());
|
||||
if (pair.connected_clients == 0 || --pair.connected_clients == 0) {
|
||||
// Remove MSGQ subscriber socket from mapping and reset it
|
||||
sub2pub.erase(pair.sub_sock.get());
|
||||
pair.sub_sock.reset(nullptr);
|
||||
registerSockets();
|
||||
}
|
||||
}
|
||||
cv.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up monitor sockets
|
||||
for (int i = 0; i < pollitems.size(); ++i) {
|
||||
zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), nullptr, 0);
|
||||
zmq_close(pollitems[i].socket);
|
||||
}
|
||||
cv.notify_one();
|
||||
}
|
||||
|
||||
void MsgqToZmq::registerSockets() {
|
||||
msgq_poller = std::make_unique<MSGQPoller>();
|
||||
for (const auto &socket_pair : socket_pairs) {
|
||||
if (socket_pair.sub_sock) {
|
||||
msgq_poller->registerSocket(socket_pair.sub_sock.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "msgq/impl_msgq.h"
|
||||
#include "openpilot/cereal/messaging/bridge_zmq.h"
|
||||
|
||||
class MsgqToZmq {
|
||||
public:
|
||||
MsgqToZmq() {}
|
||||
void run(const std::vector<std::string> &endpoints, const std::string &ip);
|
||||
|
||||
protected:
|
||||
void registerSockets();
|
||||
void zmqMonitorThread();
|
||||
|
||||
struct SocketPair {
|
||||
std::string endpoint;
|
||||
std::unique_ptr<BridgeZmqPubSocket> pub_sock;
|
||||
std::unique_ptr<MSGQSubSocket> sub_sock;
|
||||
int connected_clients = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<Context> msgq_context;
|
||||
std::unique_ptr<BridgeZmqContext> zmq_context;
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
std::unique_ptr<MSGQPoller> msgq_poller;
|
||||
std::map<SubSocket *, BridgeZmqPubSocket *> sub2pub;
|
||||
std::vector<SocketPair> socket_pairs;
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
#include "openpilot/cereal/services.h"
|
||||
#include "openpilot/cereal/messaging/messaging.h"
|
||||
@@ -15,21 +14,6 @@ static inline bool inList(const std::vector<const char *> &list, const char *val
|
||||
return false;
|
||||
}
|
||||
|
||||
class MessageContext {
|
||||
public:
|
||||
MessageContext() : ctx_(nullptr) {}
|
||||
~MessageContext() { delete ctx_; }
|
||||
inline Context *context() {
|
||||
std::call_once(init_flag, [=]() { ctx_ = Context::create(); });
|
||||
return ctx_;
|
||||
}
|
||||
private:
|
||||
Context *ctx_;
|
||||
std::once_flag init_flag;
|
||||
};
|
||||
|
||||
MessageContext message_context;
|
||||
|
||||
struct SubMaster::SubMessage {
|
||||
std::string name;
|
||||
SubSocket *socket = nullptr;
|
||||
@@ -44,13 +28,13 @@ struct SubMaster::SubMessage {
|
||||
};
|
||||
|
||||
SubMaster::SubMaster(const std::vector<const char *> &service_list, const std::vector<const char *> &poll,
|
||||
const char *address, const std::vector<const char *> &ignore_alive) {
|
||||
poller_ = Poller::create();
|
||||
const std::vector<const char *> &ignore_alive) {
|
||||
poller_ = new Poller();
|
||||
for (auto name : service_list) {
|
||||
assert(services.count(std::string(name)) > 0);
|
||||
|
||||
service serv = services.at(std::string(name));
|
||||
SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true, true, serv.queue_size);
|
||||
SubSocket *socket = SubSocket::create(name, true, serv.queue_size);
|
||||
assert(socket != 0);
|
||||
bool is_polled = inList(poll, name) || poll.empty();
|
||||
if (is_polled) poller_->registerSocket(socket);
|
||||
@@ -188,7 +172,7 @@ PubMaster::PubMaster(const std::vector<const char *> &service_list) {
|
||||
for (auto name : service_list) {
|
||||
assert(services.count(name) > 0);
|
||||
service serv = services.at(std::string(name));
|
||||
PubSocket *socket = PubSocket::create(message_context.context(), name, true, serv.queue_size);
|
||||
PubSocket *socket = PubSocket::create(name, serv.queue_size);
|
||||
assert(socket);
|
||||
sockets_[name] = socket;
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ _services: dict[str, tuple] = {
|
||||
"carStateSP": (True, 100., 10),
|
||||
"liveMapDataSP": (True, 1., 1),
|
||||
"modelDataV2SP": (True, 20., 10, QueueSize.BIG),
|
||||
"liveLocationKalman": (True, 20.),
|
||||
"gpsLocationSP": (True, 20., 20),
|
||||
|
||||
# debug
|
||||
"uiDebug": (True, 0., 1),
|
||||
|
||||
@@ -11,9 +11,9 @@ common_libs = [
|
||||
_common = env.Library('common', common_libs, LIBS="json11")
|
||||
Export('_common')
|
||||
|
||||
params_python = env.SharedLibrary('params_c', 'params_c.cc', LIBS=[_common, 'zmq', 'json11'])
|
||||
params_python = env.SharedLibrary('params_c', 'params_c.cc', LIBS=[_common, 'json11'])
|
||||
common_python = [params_python]
|
||||
Export('common_python')
|
||||
|
||||
if GetOption('extras'):
|
||||
env.Program('tests/test_swaglog', 'tests/test_swaglog.cc', LIBS=[_common, 'json11', 'zmq', 'pthread'])
|
||||
env.Program('tests/test_swaglog', 'tests/test_swaglog.cc', LIBS=[_common, 'json11', 'pthread'])
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -13,7 +13,7 @@ import capnp
|
||||
T = TypeVar("T")
|
||||
|
||||
_EDGE_SLOTS = 16
|
||||
_MINIMAL_EXAMPLES = 10
|
||||
_MINIMAL_EXAMPLES = 1
|
||||
_INTEGER_RANGES = {
|
||||
"int8": (-2**7, 2**7 - 1),
|
||||
"int16": (-2**15, 2**15 - 1),
|
||||
@@ -42,8 +42,8 @@ class Fuzzy:
|
||||
draw_index = self._draw_index
|
||||
self._draw_index += 1
|
||||
|
||||
# Preserve the cheap minimal prefix Hypothesis produced, then interleave
|
||||
# systematic boundaries and random values at every draw site.
|
||||
# Start with one minimal example, then interleave systematic
|
||||
# boundaries and random values at every draw site.
|
||||
if self.example_index < _MINIMAL_EXAMPLES:
|
||||
return edges[0]
|
||||
search_example = self.example_index - _MINIMAL_EXAMPLES
|
||||
|
||||
@@ -13,7 +13,6 @@ public:
|
||||
static std::string get_name() { return ""; }
|
||||
static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; }
|
||||
|
||||
static std::string get_serial() { return "cccccc"; }
|
||||
|
||||
static std::map<std::string, std::string> get_init_logs(bool route_log = false) {
|
||||
return {};
|
||||
|
||||
@@ -69,9 +69,6 @@ class HardwareBase(ABC):
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
def booted(self) -> bool:
|
||||
return True
|
||||
|
||||
def reboot(self, reason=None):
|
||||
print("REBOOT!")
|
||||
|
||||
@@ -115,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
|
||||
|
||||
|
||||
@@ -56,29 +56,29 @@
|
||||
},
|
||||
{
|
||||
"name": "boot",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/boot-b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615.img.xz",
|
||||
"hash": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
|
||||
"hash_raw": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
|
||||
"size": 46962688,
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/boot-2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a.img.xz",
|
||||
"hash": "2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a",
|
||||
"hash_raw": "2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a",
|
||||
"size": 46897152,
|
||||
"sparse": false,
|
||||
"full_check": true,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "3ef4769bb1cc73bfc31f96f073b46af42dcc0bad4ab2dde32d11929745d0cd28"
|
||||
"ondevice_hash": "3519123cc1ec417e56ed2bdd449094e6e6e38ecb610ea4452dd44d5bdce5604c"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img.xz",
|
||||
"hash": "9aebca09b9d142718e71efbfe44b723010eec6e70067c043c63186067291739d",
|
||||
"hash_raw": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
|
||||
"size": 4718592000,
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e.img.xz",
|
||||
"hash": "6042848e01cd245df7570fc96cff28c831b4d3713e4321ee38735cb4e4591593",
|
||||
"hash_raw": "ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e",
|
||||
"size": 2147483648,
|
||||
"sparse": true,
|
||||
"full_check": false,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "270b76c5c5568828e3883390b83ea445425a104dd42119d68f06093ce6b6fcef",
|
||||
"ondevice_hash": "b2fc71b9071ddb0664a7e3a837df8d57ee36a2befabd8f044eb8be8d73ee66b7",
|
||||
"alt": {
|
||||
"hash": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img",
|
||||
"size": 4718592000
|
||||
"hash": "ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e.img",
|
||||
"size": 2147483648
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -1,7 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <algorithm> // for std::clamp
|
||||
@@ -29,24 +28,6 @@ public:
|
||||
return it->second;
|
||||
}
|
||||
|
||||
static std::string get_serial() {
|
||||
static std::string serial("");
|
||||
if (serial.empty()) {
|
||||
std::ifstream stream("/proc/cmdline");
|
||||
std::string cmdline;
|
||||
std::getline(stream, cmdline);
|
||||
|
||||
auto start = cmdline.find("serialno=");
|
||||
if (start == std::string::npos) {
|
||||
serial = "cccccc";
|
||||
} else {
|
||||
auto end = cmdline.find(" ", start + 9);
|
||||
serial = cmdline.substr(start + 9, end - start - 9);
|
||||
}
|
||||
}
|
||||
return serial;
|
||||
}
|
||||
|
||||
static void set_ir_power(int percent) {
|
||||
auto device = get_device_type();
|
||||
if (device == cereal::InitData::DeviceType::TIZI) {
|
||||
|
||||
@@ -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)
|
||||
@@ -356,12 +373,9 @@ class HardwareComma(HardwareBase):
|
||||
|
||||
# *** IRQ config ***
|
||||
|
||||
# mask off big cluster from default affinity
|
||||
sudo_write("f", "/proc/irq/default_smp_affinity")
|
||||
|
||||
# move these off the default core
|
||||
affine_irq(1, "msm_vidc") # encoders
|
||||
affine_irq(1, "i2c_geni") # sensors
|
||||
# move these off the default core, and off the cores AGNOS keeps for everything but openpilot
|
||||
affine_irq(2, "msm_vidc") # encoders
|
||||
affine_irq(2, "i2c_geni") # sensors
|
||||
|
||||
# *** GPU config ***
|
||||
# https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216
|
||||
@@ -418,13 +432,6 @@ class HardwareComma(HardwareBase):
|
||||
time.sleep(0.01)
|
||||
gpio_set(GPIO.STM_BOOT0, False)
|
||||
|
||||
def booted(self):
|
||||
# this normally boots within 8s, but on rare occasions takes 30+s
|
||||
encoder_state = sudo_read("/sys/kernel/debug/msm_vidc/core0/info")
|
||||
if "Core state: 0" in encoder_state and (time.monotonic() < 60*2):
|
||||
return False
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
t = HardwareComma()
|
||||
t.initialize_hardware()
|
||||
|
||||
@@ -1,632 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import string
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import termios
|
||||
import time
|
||||
|
||||
from contextlib import contextmanager
|
||||
from ipaddress import IPv4Address, AddressValueError
|
||||
|
||||
from enum import Enum
|
||||
|
||||
from openpilot.common.esim.base import WEBBING_ICCID_PREFIX
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s.%(msecs)03d %(levelname)-7s modem: %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
|
||||
AT_PORT = "/dev/modem_at0"
|
||||
PPP_PORT = "/dev/modem_at1"
|
||||
STATE_PATH = "/dev/shm/modem"
|
||||
AT_LOCK = "/dev/shm/modem.lock" # shared with LPA
|
||||
AT_INIT = [
|
||||
"ATE0", # disable command echo
|
||||
"ATV1", # verbose result codes (CONNECT/BUSY/NO CARRIER, not numeric)
|
||||
"AT+CMEE=1", # numeric +CME ERROR codes on failures (per 3GPP 27.007)
|
||||
"ATX4", # extended result codes: busy + dial tone detection, line speed in CONNECT
|
||||
"AT&C1", # DCD pin follows carrier state (V.250 default)
|
||||
"AT+CREG=2", # registration URCs include location info
|
||||
"AT+CGREG=2", # GPRS registration URCs include location info
|
||||
]
|
||||
CREG = {0: "not_registered", 1: "home", 2: "searching", 3: "denied", 4: "unknown", 5: "roaming"}
|
||||
# 3GPP TS 27.007 +COPS <AcT> -> network type
|
||||
NETWORK_TYPE = {0: "gsm", 1: "gsm", 3: "gsm", 8: "gsm",
|
||||
2: "utran", 4: "utran", 5: "utran", 6: "utran",
|
||||
7: "lte", 9: "lte", 10: "lte",
|
||||
11: "nr", 12: "nr", 13: "nr"}
|
||||
|
||||
DIAL_CID = 1
|
||||
|
||||
PPPD_CMD = [
|
||||
"sudo", "pppd", PPP_PORT, "460800", "noauth", "nodetach", "noipdefault", "usepeerdns",
|
||||
"nodefaultroute", "connect",
|
||||
"/usr/sbin/chat -v ABORT 'NO CARRIER' ABORT 'NO DIALTONE' ABORT 'BUSY' " +
|
||||
f"ABORT 'NO ANSWER' ABORT 'ERROR' TIMEOUT 5 '' AT OK ATD*99***{DIAL_CID}# CONNECT ''",
|
||||
"lcp-echo-interval", "30", "lcp-echo-failure", "4", "mtu", "1500", "mru", "1500",
|
||||
"novj", "novjccomp", "ipcp-accept-local", "ipcp-accept-remote", "nomagic",
|
||||
"user", '""', "password", '""',
|
||||
]
|
||||
INITIAL_STATE: dict[str, object] = {
|
||||
"seconds_since_boot": 0,
|
||||
"state": "INITIALIZING",
|
||||
"connected": False, "ip_address": "",
|
||||
"iccid": "", "mcc_mnc": "", "imei": "", "modem_version": "",
|
||||
"signal_strength": 0, "signal_quality": 0,
|
||||
"network_type": "unknown", "operator": "", "band": "", "channel": 0,
|
||||
"registration": "unknown", "temperatures": [], "extra": "",
|
||||
"tx_bytes": 0, "rx_bytes": 0,
|
||||
}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _serial_port(port: str, baudrate: int):
|
||||
fd = os.open(port, os.O_RDWR | os.O_NOCTTY)
|
||||
try:
|
||||
attrs = termios.tcgetattr(fd)
|
||||
attrs[0] = 0
|
||||
attrs[1] = 0
|
||||
attrs[2] = termios.CLOCAL | termios.CREAD | termios.CS8
|
||||
attrs[3] = 0
|
||||
attrs[4] = attrs[5] = getattr(termios, f"B{baudrate}")
|
||||
attrs[6][termios.VMIN] = 0
|
||||
attrs[6][termios.VTIME] = 0
|
||||
termios.tcsetattr(fd, termios.TCSANOW, attrs)
|
||||
yield fd
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _read_line(fd: int, timeout: float) -> bytes:
|
||||
data = bytearray()
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
readable, _, _ = select.select([fd], [], [], max(0.0, deadline - time.monotonic()))
|
||||
if not readable:
|
||||
return bytes(data)
|
||||
byte = os.read(fd, 1)
|
||||
if not byte:
|
||||
return bytes(data)
|
||||
data.extend(byte)
|
||||
if byte == b"\n":
|
||||
return bytes(data)
|
||||
|
||||
|
||||
class State(Enum):
|
||||
INITIALIZING = "INITIALIZING"
|
||||
SEARCHING = "SEARCHING"
|
||||
CONNECTING = "CONNECTING"
|
||||
CONNECTED = "CONNECTED"
|
||||
DISCONNECTING = "DISCONNECTING"
|
||||
|
||||
|
||||
STATE_WAIT = 1.0 # seconds to wait after each state handler returns
|
||||
|
||||
|
||||
class PPPSession:
|
||||
"""Owns pppd lifecycle, fail tracking, and PPP routing."""
|
||||
MAX_FAILS = 3
|
||||
|
||||
def __init__(self):
|
||||
self._proc: subprocess.Popen | None = None
|
||||
self._fails = 0
|
||||
self._peer = ""
|
||||
|
||||
def start(self):
|
||||
self._proc = subprocess.Popen(PPPD_CMD, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self._peer = ""
|
||||
logging.info(f"PPP dialing CID {DIAL_CID}")
|
||||
|
||||
def kill(self):
|
||||
subprocess.run(["sudo", "killall", "-9", "pppd"], capture_output=True)
|
||||
self._peer = ""
|
||||
|
||||
@staticmethod
|
||||
def reset_data_port():
|
||||
"""Drop DTR on PPP_PORT so the modem terminates any stuck PPP session."""
|
||||
try:
|
||||
with _serial_port(PPP_PORT, 460800) as fd:
|
||||
dtr = struct.pack("I", termios.TIOCM_DTR)
|
||||
fcntl.ioctl(fd, termios.TIOCMBIC, dtr)
|
||||
time.sleep(0.2)
|
||||
fcntl.ioctl(fd, termios.TIOCMBIS, dtr)
|
||||
except Exception as e:
|
||||
logging.warning(f"data port reset failed: {e}")
|
||||
|
||||
def has_exited(self) -> bool:
|
||||
return self._proc is not None and self._proc.poll() is not None
|
||||
|
||||
def reset_fail_counter(self):
|
||||
self._fails = 0
|
||||
|
||||
def record_fail(self) -> bool:
|
||||
"""Bump fail counter; return True if at the give-up limit."""
|
||||
self._fails += 1
|
||||
return self._fails >= self.MAX_FAILS
|
||||
|
||||
@property
|
||||
def fails(self) -> int:
|
||||
return self._fails
|
||||
|
||||
def maybe_install_routes(self, ip: str, peer: str) -> bool:
|
||||
"""Install routes if peer changed; kill the session on failure so the state machine reconnects."""
|
||||
if not peer or peer == self._peer:
|
||||
return False
|
||||
try:
|
||||
IPv4Address(ip)
|
||||
IPv4Address(peer)
|
||||
except AddressValueError:
|
||||
logging.warning(f"refusing route install with non-IPv4 ip={ip!r} peer={peer!r}")
|
||||
self.kill()
|
||||
return False
|
||||
self.cleanup_routes()
|
||||
cmds = [
|
||||
["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "metric", "1000"],
|
||||
["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "table", "1000"],
|
||||
["sudo", "ip", "rule", "add", "from", ip, "table", "1000"],
|
||||
]
|
||||
for cmd in cmds:
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
logging.warning(f"route install failed ({' '.join(cmd[1:])}): {r.stderr.strip()}")
|
||||
self.cleanup_routes()
|
||||
self.kill()
|
||||
return False
|
||||
logging.info(f"route set up for {ip} via {peer}")
|
||||
self._peer = peer
|
||||
return True
|
||||
|
||||
def maybe_install_dns(self, dns_servers: list[str]) -> bool:
|
||||
"""Register DNS servers with systemd-resolved; kill the session on failure to force a retry."""
|
||||
if not dns_servers:
|
||||
return False
|
||||
for cmd in (["sudo", "resolvectl", "dns", "ppp0", *dns_servers],
|
||||
["sudo", "resolvectl", "default-route", "ppp0", "yes"]):
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
logging.warning(f"resolvectl failed ({' '.join(cmd[1:])}): {r.stderr.strip()}")
|
||||
self.kill()
|
||||
return False
|
||||
logging.info(f"resolvectl: ppp0 DNS = {dns_servers}")
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def cleanup_routes():
|
||||
subprocess.run(["sudo", "ip", "route", "del", "default", "dev", "ppp0"], capture_output=True)
|
||||
subprocess.run(["sudo", "ip", "route", "flush", "table", "1000"], capture_output=True)
|
||||
# rules don't have a flush; delete until none remain
|
||||
while subprocess.run(["sudo", "ip", "rule", "del", "table", "1000"], capture_output=True).returncode == 0:
|
||||
pass
|
||||
subprocess.run(["sudo", "resolvectl", "revert", "ppp0"], capture_output=True)
|
||||
|
||||
|
||||
class Modem:
|
||||
def __init__(self):
|
||||
self._ppp = PPPSession()
|
||||
self._sim_change = False
|
||||
self._apn = "" # blank = network-provided via PCO
|
||||
self._roaming_allowed = True
|
||||
self.running = True
|
||||
self.S = INITIAL_STATE.copy()
|
||||
|
||||
@staticmethod
|
||||
def _read_param(key):
|
||||
try:
|
||||
with open(f"/data/params/d/{key}") as f:
|
||||
return f.read().strip()
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _parse_reg(v: str) -> str:
|
||||
try:
|
||||
return CREG.get(int(v.split(",")[1].strip('"')), "unknown")
|
||||
except (ValueError, IndexError):
|
||||
return "unknown"
|
||||
|
||||
@staticmethod
|
||||
def _has_modem_manager() -> bool:
|
||||
return os.path.isfile("/lib/systemd/system/ModemManager.service")
|
||||
|
||||
def _is_roaming_allowed(self) -> bool:
|
||||
if self.S["iccid"].startswith(WEBBING_ICCID_PREFIX):
|
||||
return True
|
||||
return self._read_param("GsmRoaming") == "1"
|
||||
|
||||
def _publish_state(self, **kwargs):
|
||||
self.S.update(kwargs)
|
||||
self.S["seconds_since_boot"] = time.monotonic()
|
||||
with tempfile.NamedTemporaryFile(mode="w", dir="/dev/shm", delete=False) as f:
|
||||
json.dump(self.S, f, indent=2)
|
||||
os.chmod(f.name, 0o644)
|
||||
os.replace(f.name, STATE_PATH)
|
||||
|
||||
def _at(self, cmd):
|
||||
"""Send AT command, return response lines. [] on error or if LPA holds port."""
|
||||
fd = os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
os.close(fd)
|
||||
return []
|
||||
try:
|
||||
with _serial_port(AT_PORT, 9600) as serial_fd:
|
||||
termios.tcflush(serial_fd, termios.TCIFLUSH)
|
||||
command = (cmd + "\r").encode()
|
||||
while command:
|
||||
command = command[os.write(serial_fd, command):]
|
||||
lines = []
|
||||
while True:
|
||||
raw = _read_line(serial_fd, 5)
|
||||
if not raw:
|
||||
raise TimeoutError("AT timeout")
|
||||
line = raw.decode(errors="ignore").strip()
|
||||
if not line:
|
||||
continue
|
||||
if line == "OK":
|
||||
break
|
||||
if line == "ERROR" or line.startswith("+CME ERROR"):
|
||||
raise RuntimeError(line)
|
||||
lines.append(line)
|
||||
return lines
|
||||
except (RuntimeError, TimeoutError, OSError) as e:
|
||||
logging.info(f"AT {cmd} failed: {e}")
|
||||
return []
|
||||
finally:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
|
||||
def _atv(self, cmd, pfx):
|
||||
for line in self._at(cmd):
|
||||
if pfx in line and ":" in line:
|
||||
return line.split(":", 1)[1].strip()
|
||||
return None
|
||||
|
||||
def _init_at_channel(self) -> bool:
|
||||
"""Run AT_INIT and confirm ATE0 took effect. Returns False if echo is still on."""
|
||||
for c in AT_INIT:
|
||||
self._at(c)
|
||||
r = self._at("AT+CGMI")
|
||||
return bool(r) and not r[0].startswith("AT")
|
||||
|
||||
def _configure_modem(self, modem_version: str):
|
||||
if not modem_version.startswith("EG25"):
|
||||
return
|
||||
cmds = [
|
||||
# clear initial EPS bearer APN (some carriers reject the default)
|
||||
'AT+CGDCONT=0,"IP",""',
|
||||
|
||||
# SIM hot swap
|
||||
'AT+QSIMDET=1,0',
|
||||
'AT+QSIMSTAT=1',
|
||||
|
||||
# configure modem as data-centric
|
||||
'AT+QNVW=5280,0,"0102000000000000"',
|
||||
'AT+QNVFW="/nv/item_files/ims/IMS_enable",00',
|
||||
'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01',
|
||||
]
|
||||
for c in cmds:
|
||||
self._at(c)
|
||||
|
||||
def _do_initializing(self):
|
||||
if not os.path.exists(AT_PORT):
|
||||
return State.INITIALIZING
|
||||
logging.info("port found, initializing")
|
||||
self._ppp.kill()
|
||||
self._ppp.cleanup_routes()
|
||||
|
||||
if not self._init_at_channel():
|
||||
logging.warning("AT echo still on, retrying")
|
||||
return State.INITIALIZING
|
||||
|
||||
identity = self._read_identity()
|
||||
if not identity["iccid"] or not identity["imei"]:
|
||||
logging.warning(f"identity read incomplete: {identity}, retrying")
|
||||
return State.INITIALIZING
|
||||
|
||||
self._configure_modem(identity["modem_version"])
|
||||
|
||||
self.S.update(identity)
|
||||
self._apn = self._read_param("GsmApn")
|
||||
self._roaming_allowed = self._is_roaming_allowed()
|
||||
# blank APN lets the carrier supply one via PCO
|
||||
self._at(f'AT+CGDCONT={DIAL_CID},"IP","{self._apn}"')
|
||||
logging.info(f"APN '{self._apn or '(network-provided)'}' written to CID {DIAL_CID}, roaming={'on' if self._roaming_allowed else 'off'}")
|
||||
|
||||
self._sim_change = False # clear since we just re-read identity with the new SIM
|
||||
self._publish_state(**identity)
|
||||
return State.SEARCHING
|
||||
|
||||
def _read_identity(self):
|
||||
def first_line(cmd):
|
||||
r = self._at(cmd)
|
||||
return r[0].strip() if r else ""
|
||||
|
||||
imei = first_line("AT+CGSN")
|
||||
if not (imei.isdigit() and 14 <= len(imei) <= 17): # 3GPP TS 23.003
|
||||
imei = ""
|
||||
|
||||
iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F")
|
||||
if not all(c in string.hexdigits for c in iccid):
|
||||
iccid = ""
|
||||
|
||||
imsi = first_line("AT+CIMI")
|
||||
mcc_mnc = imsi[:6] if imsi.isdigit() and len(imsi) >= 6 else ""
|
||||
|
||||
modem_version = first_line("AT+GMR")
|
||||
|
||||
logging.info(f"imei={imei} iccid={iccid} mcc_mnc={mcc_mnc} ver={modem_version}")
|
||||
return {"imei": imei, "iccid": iccid, "mcc_mnc": mcc_mnc, "modem_version": modem_version}
|
||||
|
||||
def _do_searching(self):
|
||||
new_roaming = self._is_roaming_allowed()
|
||||
if new_roaming != self._roaming_allowed:
|
||||
logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}")
|
||||
self._roaming_allowed = new_roaming
|
||||
|
||||
v = self._atv("AT+CREG?", "+CREG:")
|
||||
if not v:
|
||||
return self._searching_idle()
|
||||
|
||||
reg = self._parse_reg(v)
|
||||
greg = self._parse_reg(self._atv("AT+CGREG?", "+CGREG:") or "")
|
||||
logging.debug(f"creg={reg} cgreg={greg} roaming_allowed={self._roaming_allowed}")
|
||||
|
||||
if reg == "roaming" and not self._roaming_allowed:
|
||||
self._publish_state(registration=reg)
|
||||
return State.SEARCHING
|
||||
|
||||
if reg in ("home", "roaming") and greg in ("home", "roaming"):
|
||||
self._publish_state(registration=reg)
|
||||
return State.CONNECTING
|
||||
|
||||
if reg != self.S.get("registration"):
|
||||
self._publish_state(registration=reg)
|
||||
return self._searching_idle()
|
||||
|
||||
def _searching_idle(self):
|
||||
if self._sim_change or not os.path.exists(AT_PORT):
|
||||
logging.info(f"-> reconnecting (sim_change={self._sim_change} port={os.path.exists(AT_PORT)})")
|
||||
return State.DISCONNECTING
|
||||
return State.SEARCHING
|
||||
|
||||
def _do_connecting(self):
|
||||
logging.info("starting pppd")
|
||||
self._ppp.reset_fail_counter()
|
||||
self._sim_change = False
|
||||
self._ppp.start()
|
||||
return State.CONNECTED
|
||||
|
||||
def _handle_pppd_exit(self):
|
||||
if self._sim_change or not os.path.exists(AT_PORT):
|
||||
return State.DISCONNECTING
|
||||
give_up = self._ppp.record_fail()
|
||||
if give_up:
|
||||
logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, reconnecting")
|
||||
return State.DISCONNECTING
|
||||
logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, retrying")
|
||||
self._ppp.reset_data_port()
|
||||
if not os.path.exists(AT_PORT):
|
||||
return State.DISCONNECTING
|
||||
self._ppp.start()
|
||||
return State.CONNECTED
|
||||
|
||||
def _params_changed(self) -> bool:
|
||||
new_apn = self._read_param("GsmApn")
|
||||
if new_apn != self._apn:
|
||||
logging.info(f"GsmApn changed: '{self._apn}' -> '{new_apn}'")
|
||||
return True
|
||||
new_roaming = self._is_roaming_allowed()
|
||||
if new_roaming != self._roaming_allowed:
|
||||
logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}")
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_iccid(self, state):
|
||||
if state in (State.INITIALIZING, State.DISCONNECTING) or not self.S["iccid"]:
|
||||
return
|
||||
iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F")
|
||||
if iccid and iccid != self.S["iccid"]:
|
||||
logging.warning(f"iccid changed: {self.S['iccid']} -> {iccid}")
|
||||
self._sim_change = True
|
||||
|
||||
def _do_connected(self):
|
||||
if self._ppp.has_exited():
|
||||
return self._handle_pppd_exit()
|
||||
|
||||
if self._sim_change or not os.path.exists(AT_PORT) or self._params_changed():
|
||||
return State.DISCONNECTING
|
||||
|
||||
self._poll()
|
||||
return State.CONNECTED
|
||||
|
||||
def _do_disconnecting(self):
|
||||
logging.warning("reconnecting")
|
||||
self._publish_state(**INITIAL_STATE)
|
||||
self._ppp.kill()
|
||||
self._ppp.cleanup_routes()
|
||||
self._ppp.reset_data_port()
|
||||
self._sim_change = False
|
||||
return State.INITIALIZING
|
||||
|
||||
def _poll_signal(self) -> dict:
|
||||
v = self._atv("AT+CSQ", "+CSQ:")
|
||||
if not v:
|
||||
return {}
|
||||
try:
|
||||
rssi = int(v.split(",")[0])
|
||||
if rssi == 99:
|
||||
return {}
|
||||
return {"signal_strength": rssi, "signal_quality": min(100, int(rssi / 31 * 100))}
|
||||
except (ValueError, IndexError):
|
||||
return {}
|
||||
|
||||
def _poll_operator(self) -> dict:
|
||||
v = self._atv("AT+COPS?", "+COPS:")
|
||||
if not v:
|
||||
return {}
|
||||
p = v.split(",")
|
||||
out: dict = {}
|
||||
try:
|
||||
if len(p) >= 3:
|
||||
out["operator"] = p[2].strip('"')
|
||||
if len(p) >= 4:
|
||||
out["network_type"] = NETWORK_TYPE.get(int(p[3]), "unknown")
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return out
|
||||
|
||||
def _poll_band(self) -> dict:
|
||||
v = self._atv("AT+QNWINFO", "+QNWINFO:")
|
||||
if not v:
|
||||
return {}
|
||||
info = v.replace('"', '').split(",")
|
||||
try:
|
||||
if len(info) >= 4:
|
||||
return {"band": info[2], "channel": int(info[3])}
|
||||
except ValueError:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def _poll_extra(self) -> dict:
|
||||
v = self._atv('AT+QENG="servingcell"', "+QENG:")
|
||||
return {"extra": v.replace('"', '')} if v else {}
|
||||
|
||||
def _poll_temps(self) -> dict:
|
||||
v = self._atv("AT+QTEMP", "+QTEMP:")
|
||||
if not v:
|
||||
return {}
|
||||
try:
|
||||
return {"temperatures": [t for t in (int(x) for x in v.split(",") if x.strip()) if t != 255]}
|
||||
except (ValueError, IndexError):
|
||||
return {}
|
||||
|
||||
def _poll_iface(self) -> dict:
|
||||
try:
|
||||
r = subprocess.run(["ip", "-4", "addr", "show", "ppp0"], capture_output=True, text=True, timeout=2)
|
||||
ip, peer = "", ""
|
||||
for line in r.stdout.splitlines():
|
||||
# `inet 10.x.x.x peer 10.64.64.64/32 ...`
|
||||
parts = line.strip().split()
|
||||
if "inet" in parts:
|
||||
i = parts.index("inet")
|
||||
ip = parts[i + 1].split("/")[0]
|
||||
if "peer" in parts:
|
||||
peer = parts[parts.index("peer") + 1].split("/")[0]
|
||||
break
|
||||
if ip:
|
||||
if self._ppp.maybe_install_routes(ip, peer):
|
||||
self._ppp.maybe_install_dns(self._read_cellular_dns())
|
||||
return {"ip_address": ip, "connected": True}
|
||||
if self.S["connected"]:
|
||||
return {"connected": False, "ip_address": ""}
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def _read_cellular_dns(self) -> list[str]:
|
||||
v = self._atv(f"AT+CGCONTRDP={DIAL_CID}", "+CGCONTRDP:")
|
||||
if not v:
|
||||
return []
|
||||
# +CGCONTRDP: <cid>,<bearer_id>,<apn>,<local_addr>,<gw_addr>,<dns_prim>,<dns_sec>,...
|
||||
fields = [f.strip().strip('"') for f in v.split(",")]
|
||||
dns_servers = []
|
||||
for d in fields[5:7]:
|
||||
try:
|
||||
dns_servers.append(str(IPv4Address(d)))
|
||||
except (AddressValueError, ValueError):
|
||||
pass
|
||||
if not dns_servers:
|
||||
dns_servers = [
|
||||
"8.8.8.8", # Google
|
||||
"1.1.1.1", # Cloudflare
|
||||
]
|
||||
logging.warning(f"no cellular DNS servers reported by modem: {v!r}; using fallback {dns_servers}")
|
||||
return dns_servers
|
||||
|
||||
def _poll_byte_counters(self) -> dict:
|
||||
try:
|
||||
with open("/sys/class/net/ppp0/statistics/tx_bytes") as f:
|
||||
tx = int(f.read().strip())
|
||||
with open("/sys/class/net/ppp0/statistics/rx_bytes") as f:
|
||||
rx = int(f.read().strip())
|
||||
except Exception:
|
||||
return {}
|
||||
return {"tx_bytes": tx, "rx_bytes": rx}
|
||||
|
||||
def _poll(self):
|
||||
s: dict = {}
|
||||
for fn in (self._poll_signal, self._poll_operator, self._poll_band,
|
||||
self._poll_extra, self._poll_temps, self._poll_iface,
|
||||
self._poll_byte_counters):
|
||||
s.update(fn())
|
||||
if s:
|
||||
self._publish_state(**s)
|
||||
|
||||
def run(self):
|
||||
logging.info("starting")
|
||||
self._publish_state(state=State.INITIALIZING.value)
|
||||
if self._has_modem_manager():
|
||||
subprocess.run(["sudo", "systemctl", "mask", "--runtime", "ModemManager"], capture_output=True)
|
||||
subprocess.run(["sudo", "systemctl", "stop", "ModemManager"], capture_output=True)
|
||||
self._ppp.kill()
|
||||
|
||||
state = State.INITIALIZING
|
||||
|
||||
handlers = {
|
||||
State.INITIALIZING: self._do_initializing,
|
||||
State.SEARCHING: self._do_searching,
|
||||
State.CONNECTING: self._do_connecting,
|
||||
State.CONNECTED: self._do_connected,
|
||||
State.DISCONNECTING: self._do_disconnecting,
|
||||
}
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
self._check_iccid(state)
|
||||
prev = state
|
||||
state = handlers[state]()
|
||||
if state != prev:
|
||||
self._publish_state(state=state.value)
|
||||
logging.info(f"{prev.value} -> {state.value}")
|
||||
except Exception:
|
||||
logging.exception(f"error in {state.value}")
|
||||
state = State.DISCONNECTING
|
||||
time.sleep(STATE_WAIT)
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
self._ppp.kill()
|
||||
self._ppp.cleanup_routes()
|
||||
try:
|
||||
os.remove(STATE_PATH)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
if self._has_modem_manager():
|
||||
subprocess.run(["sudo", "systemctl", "unmask", "--runtime", "ModemManager"], capture_output=True)
|
||||
subprocess.run(["sudo", "systemctl", "start", "ModemManager"], capture_output=True)
|
||||
|
||||
|
||||
def main():
|
||||
m = Modem()
|
||||
|
||||
def _sig(*_):
|
||||
m.running = False
|
||||
|
||||
signal.signal(signal.SIGINT, _sig)
|
||||
signal.signal(signal.SIGTERM, _sig)
|
||||
m.run()
|
||||
m.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:f92c0a9b41613e063b6a1cd086729f5555d9df6482249e171ed1e276272cad7d
|
||||
size 24709520
|
||||
oid sha256:86d8e83be5e2c7a1e9a443a8bc0ddc706ea6c40a822f86aaf35fc09641082487
|
||||
size 41289720
|
||||
|
||||
@@ -33,12 +33,8 @@ namespace Path {
|
||||
return util::getenv("PARAMS_ROOT", Hardware::PC() ? (Path::comma_home() + "/params") : "/data/params");
|
||||
}
|
||||
|
||||
inline std::string rsa_file() {
|
||||
return Hardware::PC() ? Path::comma_home() + "/persist/comma/id_rsa" : "/persist/comma/id_rsa";
|
||||
}
|
||||
|
||||
inline std::string swaglog_ipc() {
|
||||
return "ipc:///tmp/logmessage" + Path::openpilot_prefix();
|
||||
return "/tmp/logmessage" + Path::openpilot_prefix();
|
||||
}
|
||||
|
||||
inline std::string download_cache_root() {
|
||||
@@ -48,14 +44,6 @@ namespace Path {
|
||||
return "/tmp/comma_download_cache" + Path::openpilot_prefix() + "/";
|
||||
}
|
||||
|
||||
inline std::string shm_path() {
|
||||
#ifdef __APPLE__
|
||||
return"/tmp";
|
||||
#else
|
||||
return "/dev/shm";
|
||||
#endif
|
||||
}
|
||||
|
||||
inline std::string model_root() {
|
||||
return Hardware::PC() ? Path::comma_home() + "/media/0/models" : "/data/media/0/models";
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class Paths:
|
||||
|
||||
@staticmethod
|
||||
def swaglog_ipc() -> str:
|
||||
return "ipc:///tmp/logmessage" + os.environ.get("OPENPILOT_PREFIX", "")
|
||||
return "/tmp/logmessage" + os.environ.get("OPENPILOT_PREFIX", "")
|
||||
|
||||
@staticmethod
|
||||
def download_cache_root() -> str:
|
||||
|
||||
@@ -7,6 +7,7 @@ CHESTNUT_ROM_USB_IDS = ((0x174C, 0x2464), (0x174C, 0x2463))
|
||||
CHESTNUT_USB_PRODUCT = f"custom {CHESTNUT_FW_VERSION}-CLEAN"
|
||||
USB_DEVICES_PATH = Path("/sys/bus/usb/devices")
|
||||
TYPEC_CC_ORIENTATION_PATH = Path("/sys/class/power_supply/usb/typec_cc_orientation")
|
||||
UDC_PATH = Path("/sys/class/udc")
|
||||
PRIMARY_USB_CONTROLLER = "a600000.ssusb"
|
||||
|
||||
|
||||
@@ -40,6 +41,15 @@ def cable_connected() -> bool:
|
||||
return read_int(TYPEC_CC_ORIENTATION_PATH) != 0
|
||||
|
||||
|
||||
def usb_host_connected() -> bool:
|
||||
"""Whether a USB host, e.g. a PC with adb or the UP in CI, is on the USB-C port, also while it has suspended this device.
|
||||
A chestnut is a USB device, so then it isn't on that port."""
|
||||
try:
|
||||
return any(read(p) not in (None, "not attached") for p in UDC_PATH.glob("*/state"))
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def usb_devices() -> list[Path]:
|
||||
try:
|
||||
devices = (d for d in USB_DEVICES_PATH.glob("*") if (d / "idVendor").exists())
|
||||
|
||||
@@ -3,7 +3,6 @@ import os
|
||||
import sys
|
||||
import copy
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import socket
|
||||
import logging
|
||||
@@ -13,7 +12,6 @@ from threading import local
|
||||
from collections import OrderedDict
|
||||
from contextlib import contextmanager
|
||||
|
||||
LOG_TIMESTAMPS = "LOG_TIMESTAMPS" in os.environ
|
||||
|
||||
def json_handler(obj):
|
||||
if isinstance(obj, np.bool_):
|
||||
@@ -169,14 +167,6 @@ class SwagLogger(logging.Logger):
|
||||
else:
|
||||
self.info(evt)
|
||||
|
||||
def timestamp(self, event_name):
|
||||
if LOG_TIMESTAMPS:
|
||||
t = time.monotonic()
|
||||
tstp = NiceOrderedDict()
|
||||
tstp['timestamp'] = NiceOrderedDict()
|
||||
tstp['timestamp']["event"] = event_name
|
||||
tstp['timestamp']["time"] = t*1e9
|
||||
self.debug(tstp)
|
||||
|
||||
def findCaller(self, stack_info=False, stacklevel=1):
|
||||
"""
|
||||
|
||||
@@ -9,7 +9,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"AccessToken", {CLEAR_ON_MANAGER_START | DONT_LOG, STRING}},
|
||||
{"AdbEnabled", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"AlwaysOnDM", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"ApiCache_Device", {PERSISTENT, STRING}},
|
||||
{"AlwaysOnDMLock", {PERSISTENT, BOOL}},
|
||||
{"ApiCache_FirehoseStats", {PERSISTENT, JSON}},
|
||||
{"AssistNowToken", {PERSISTENT, STRING}},
|
||||
{"AthenadPid", {PERSISTENT, INT}},
|
||||
@@ -25,7 +25,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"CarParamsPersistent", {PERSISTENT, BYTES}},
|
||||
{"CarParamsPrevRoute", {PERSISTENT, BYTES}},
|
||||
{"CompletedTrainingVersion", {PERSISTENT, STRING, "0"}},
|
||||
{"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
|
||||
{"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
{"CurrentBootlog", {PERSISTENT, STRING}},
|
||||
{"CurrentRoute", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, STRING}},
|
||||
{"DisableDriverCameraIR", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
|
||||
@@ -40,7 +40,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"DriverTooDistracted", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL}},
|
||||
{"DriverLockoutCount", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, INT, "0"}},
|
||||
{"AlphaLongitudinalEnabled", {PERSISTENT | DEVELOPMENT_ONLY | BACKUP, BOOL}},
|
||||
{"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
|
||||
{"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
{"ForcePowerDown", {PERSISTENT, BOOL}},
|
||||
{"GitBranch", {PERSISTENT, STRING}},
|
||||
{"GitCommit", {PERSISTENT, STRING}},
|
||||
@@ -87,8 +87,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"LongitudinalManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
{"LongitudinalPersonality", {PERSISTENT | BACKUP, INT, std::to_string(static_cast<int>(cereal::LongitudinalPersonality::STANDARD))}},
|
||||
{"NetworkMetered", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
|
||||
{"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
|
||||
{"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
{"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
{"Offroad_CarUnrecognized", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
|
||||
{"Offroad_ChestnutBranch", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
{"Offroad_ChestnutNotDetected", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
|
||||
@@ -100,7 +100,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"Offroad_ConnectivityNeeded", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
{"Offroad_ConnectivityNeededPrompt", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
{"Offroad_ExcessiveActuation", {PERSISTENT, JSON}},
|
||||
{"Offroad_NoFirmware", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
|
||||
{"Offroad_Recalibration", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
|
||||
{"Offroad_TemperatureTooHigh", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
{"Offroad_UnregisteredHardware", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
@@ -114,6 +113,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"RecordFront", {PERSISTENT | BACKUP, BOOL}},
|
||||
{"RecordFrontLock", {PERSISTENT, BOOL}}, // for the internal fleet
|
||||
{"SecOCKey", {PERSISTENT | DONT_LOG | BACKUP, STRING}},
|
||||
{"Notifications", {PERSISTENT, JSON}},
|
||||
{"ShowDebugInfo", {PERSISTENT, BOOL}},
|
||||
{"RouteCount", {PERSISTENT, INT, "0"}},
|
||||
{"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
|
||||
@@ -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"}},
|
||||
@@ -178,7 +177,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"InteractivityTimeout", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"IsDevelopmentBranch", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"IsReleaseSpBranch", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"LastGPSPositionLLK", {PERSISTENT, STRING}},
|
||||
{"LastGPSPositionFused", {PERSISTENT, STRING}},
|
||||
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
|
||||
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
|
||||
|
||||
@@ -4,7 +4,7 @@ import functools
|
||||
import itertools
|
||||
|
||||
import numpy as np
|
||||
import pyray as rl
|
||||
import raylib_nb as rl
|
||||
|
||||
|
||||
# (ec codewords per block, block count) for levels L, M, Q, H, versions 1-40
|
||||
@@ -237,12 +237,8 @@ def make_texture(data: str, inverted: bool = False) -> rl.Texture:
|
||||
gray = ((modules == inverted) * 255).astype(np.uint8)
|
||||
img_array = np.dstack((gray, gray, gray, np.full_like(gray, 255)))
|
||||
|
||||
rl_image = rl.Image()
|
||||
rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data)
|
||||
rl_image.width = img_array.shape[1]
|
||||
rl_image.height = img_array.shape[0]
|
||||
rl_image.mipmaps = 1
|
||||
rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
|
||||
rl_image = rl.Image(img_array, img_array.shape[1], img_array.shape[0], 1,
|
||||
rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)
|
||||
return rl.load_texture_from_image(rl_image)
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -29,11 +29,12 @@ class Spinner:
|
||||
|
||||
def close(self):
|
||||
if self.spinner_proc is not None:
|
||||
self.spinner_proc.kill()
|
||||
self.spinner_proc.terminate() # lets it restore the display
|
||||
try:
|
||||
self.spinner_proc.communicate(timeout=2.)
|
||||
except subprocess.TimeoutExpired:
|
||||
print("WARNING: failed to kill spinner")
|
||||
self.spinner_proc.kill()
|
||||
print("WARNING: failed to stop spinner")
|
||||
self.spinner_proc = None
|
||||
|
||||
def __del__(self):
|
||||
|
||||
+16
-58
@@ -5,12 +5,13 @@
|
||||
#include "common/swaglog.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include <zmq.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
#include "json11/json11.hpp"
|
||||
#include "common/version.h"
|
||||
#include "common/hardware/hw.h"
|
||||
@@ -20,13 +21,11 @@
|
||||
class SwaglogState {
|
||||
public:
|
||||
SwaglogState() {
|
||||
zctx = zmq_ctx_new();
|
||||
sock = zmq_socket(zctx, ZMQ_PUSH);
|
||||
|
||||
// Timeout on shutdown for messages to be received by the logging process
|
||||
int timeout = 100;
|
||||
zmq_setsockopt(sock, ZMQ_LINGER, &timeout, sizeof(timeout));
|
||||
zmq_connect(sock, Path::swaglog_ipc().c_str());
|
||||
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
|
||||
int sndbuf = SWAGLOG_MAX_SIZE;
|
||||
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
|
||||
addr.sun_family = AF_UNIX;
|
||||
strncpy(addr.sun_path, Path::swaglog_ipc().c_str(), sizeof(addr.sun_path) - 1);
|
||||
|
||||
// workaround for https://github.com/dropbox/json11/issues/38
|
||||
setlocale(LC_NUMERIC, "C");
|
||||
@@ -64,8 +63,7 @@ public:
|
||||
}
|
||||
|
||||
~SwaglogState() {
|
||||
zmq_close(sock);
|
||||
zmq_ctx_destroy(zctx);
|
||||
close(sock);
|
||||
}
|
||||
|
||||
void log(int levelnum, const char* filename, int lineno, const char* func, const char* msg, const std::string& log_s) {
|
||||
@@ -73,21 +71,18 @@ public:
|
||||
if (levelnum >= print_level) {
|
||||
printf("%s: %s\n", filename, msg);
|
||||
}
|
||||
zmq_send(sock, log_s.data(), log_s.length(), ZMQ_NOBLOCK);
|
||||
// drop if logmessaged is busy, not running, or the message is too big
|
||||
sendto(sock, log_s.data(), log_s.length(), MSG_DONTWAIT, (struct sockaddr*)&addr, sizeof(addr));
|
||||
}
|
||||
|
||||
std::mutex lock;
|
||||
void* zctx = nullptr;
|
||||
void* sock = nullptr;
|
||||
int sock = -1;
|
||||
struct sockaddr_un addr = {};
|
||||
int print_level;
|
||||
json11::Json::object ctx_j;
|
||||
};
|
||||
|
||||
bool LOG_TIMESTAMPS = getenv("LOG_TIMESTAMPS");
|
||||
uint32_t NO_FRAME_ID = std::numeric_limits<uint32_t>::max();
|
||||
|
||||
static void cloudlog_common(int levelnum, const char* filename, int lineno, const char* func,
|
||||
char* msg_buf, const json11::Json::object &msg_j={}) {
|
||||
static void cloudlog_common(int levelnum, const char* filename, int lineno, const char* func, char* msg_buf) {
|
||||
static SwaglogState s;
|
||||
|
||||
json11::Json::object log_j = json11::Json::object {
|
||||
@@ -96,13 +91,9 @@ static void cloudlog_common(int levelnum, const char* filename, int lineno, cons
|
||||
{"filename", filename},
|
||||
{"lineno", lineno},
|
||||
{"funcname", func},
|
||||
{"created", seconds_since_epoch()}
|
||||
{"created", seconds_since_epoch()},
|
||||
{"msg", msg_buf},
|
||||
};
|
||||
if (msg_j.empty()) {
|
||||
log_j["msg"] = msg_buf;
|
||||
} else {
|
||||
log_j["msg"] = msg_j;
|
||||
}
|
||||
|
||||
std::string log_s;
|
||||
log_s += (char)levelnum;
|
||||
@@ -122,36 +113,3 @@ void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func
|
||||
if (ret <= 0 || !msg_buf) return;
|
||||
cloudlog_common(levelnum, filename, lineno, func, msg_buf);
|
||||
}
|
||||
|
||||
void cloudlog_t_common(int levelnum, const char* filename, int lineno, const char* func,
|
||||
uint32_t frame_id, const char* fmt, va_list args) {
|
||||
if (!LOG_TIMESTAMPS) return;
|
||||
char* msg_buf = nullptr;
|
||||
int ret = vasprintf(&msg_buf, fmt, args);
|
||||
if (ret <= 0 || !msg_buf) return;
|
||||
json11::Json::object tspt_j = json11::Json::object{
|
||||
{"event", msg_buf},
|
||||
{"time", std::to_string(nanos_since_boot())}
|
||||
};
|
||||
if (frame_id < NO_FRAME_ID) {
|
||||
tspt_j["frame_id"] = std::to_string(frame_id);
|
||||
}
|
||||
tspt_j = json11::Json::object{{"timestamp", tspt_j}};
|
||||
cloudlog_common(levelnum, filename, lineno, func, msg_buf, tspt_j);
|
||||
}
|
||||
|
||||
|
||||
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
|
||||
const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
cloudlog_t_common(levelnum, filename, lineno, func, NO_FRAME_ID, fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
|
||||
uint32_t frame_id, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
cloudlog_t_common(levelnum, filename, lineno, func, frame_id, fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#define CLOUDLOG_ERROR 40
|
||||
#define CLOUDLOG_CRITICAL 50
|
||||
|
||||
#define SWAGLOG_MAX_SIZE (4*1024*1024)
|
||||
|
||||
#ifdef __GNUC__
|
||||
#define SWAG_LOG_CHECK_FMT(a, b) __attribute__ ((format (printf, a, b)))
|
||||
@@ -18,20 +19,12 @@
|
||||
void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func,
|
||||
const char* fmt, ...) SWAG_LOG_CHECK_FMT(5, 6);
|
||||
|
||||
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
|
||||
const char* fmt, ...) SWAG_LOG_CHECK_FMT(5, 6);
|
||||
|
||||
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
|
||||
uint32_t frame_id, const char* fmt, ...) SWAG_LOG_CHECK_FMT(6, 7);
|
||||
|
||||
|
||||
#define cloudlog(lvl, fmt, ...) cloudlog_e(lvl, __FILE__, __LINE__, \
|
||||
__func__, \
|
||||
fmt, ## __VA_ARGS__)
|
||||
|
||||
#define cloudlog_t(lvl, ...) cloudlog_te(lvl, __FILE__, __LINE__, \
|
||||
__func__, \
|
||||
__VA_ARGS__)
|
||||
|
||||
|
||||
#define cloudlog_rl(burst, millis, lvl, fmt, ...) \
|
||||
@@ -64,13 +57,9 @@ void cloudlog_te(int levelnum, const char* filename, int lineno, const char* fun
|
||||
}
|
||||
|
||||
|
||||
#define LOGT(...) cloudlog_t(CLOUDLOG_DEBUG, __VA_ARGS__)
|
||||
#define LOGD(fmt, ...) cloudlog(CLOUDLOG_DEBUG, fmt, ## __VA_ARGS__)
|
||||
#define LOG(fmt, ...) cloudlog(CLOUDLOG_INFO, fmt, ## __VA_ARGS__)
|
||||
#define LOGW(fmt, ...) cloudlog(CLOUDLOG_WARNING, fmt, ## __VA_ARGS__)
|
||||
#define LOGE(fmt, ...) cloudlog(CLOUDLOG_ERROR, fmt, ## __VA_ARGS__)
|
||||
|
||||
#define LOGD_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_DEBUG, fmt, ## __VA_ARGS__)
|
||||
#define LOG_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_INFO, fmt, ## __VA_ARGS__)
|
||||
#define LOGW_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_WARNING, fmt, ## __VA_ARGS__)
|
||||
#define LOGE_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_ERROR, fmt, ## __VA_ARGS__)
|
||||
|
||||
+13
-19
@@ -1,16 +1,16 @@
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from logging.handlers import BaseRotatingHandler
|
||||
|
||||
import zmq
|
||||
|
||||
from openpilot.common.logging_extra import SwagLogger, SwagFormatter, SwagLogFileFormatter
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
|
||||
|
||||
SWAGLOG_MAX_SIZE = 4*1024*1024
|
||||
|
||||
def get_file_handler():
|
||||
Path(Paths.swaglog_root()).mkdir(parents=True, exist_ok=True)
|
||||
base_filename = os.path.join(Paths.swaglog_root(), "swaglog")
|
||||
@@ -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
|
||||
|
||||
@@ -69,8 +69,6 @@ class UnixDomainSocketHandler(logging.Handler):
|
||||
logging.Handler.__init__(self)
|
||||
self.setFormatter(formatter)
|
||||
self.pid = None
|
||||
|
||||
self.zctx = None
|
||||
self.sock = None
|
||||
|
||||
def __del__(self):
|
||||
@@ -79,29 +77,25 @@ class UnixDomainSocketHandler(logging.Handler):
|
||||
def close(self):
|
||||
if self.sock is not None:
|
||||
self.sock.close()
|
||||
if self.zctx is not None:
|
||||
self.zctx.term()
|
||||
self.sock = None
|
||||
|
||||
def connect(self):
|
||||
self.zctx = zmq.Context()
|
||||
self.sock = self.zctx.socket(zmq.PUSH)
|
||||
self.sock.setsockopt(zmq.LINGER, 10)
|
||||
self.sock.connect(Paths.swaglog_ipc())
|
||||
self.close()
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SWAGLOG_MAX_SIZE)
|
||||
self.sock.setblocking(False)
|
||||
self.pid = os.getpid()
|
||||
|
||||
def emit(self, record):
|
||||
if os.getpid() != self.pid:
|
||||
# TODO suppresses warning about forking proc with zmq socket, fix root cause
|
||||
warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*<zmq.*>")
|
||||
self.connect()
|
||||
|
||||
msg = self.format(record).rstrip('\n')
|
||||
# print("SEND".format(repr(msg)))
|
||||
assert self.sock is not None
|
||||
try:
|
||||
s = chr(record.levelno)+msg
|
||||
self.sock.send(s.encode('utf8'), zmq.NOBLOCK)
|
||||
except zmq.error.Again:
|
||||
# drop :/
|
||||
self.sock.sendto((chr(record.levelno)+msg).encode('utf8'), Paths.swaglog_ipc())
|
||||
except OSError:
|
||||
# logmessaged is busy, not running, or the message is too big. drop :/
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -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,7 +1,11 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include <zmq.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "common/hardware/hw.h"
|
||||
#include "common/swaglog.h"
|
||||
@@ -10,27 +14,25 @@
|
||||
|
||||
#include "sunnypilot/common/version.h"
|
||||
|
||||
std::string daemon_name = "testy";
|
||||
std::string dongle_id = "test_dongle_id";
|
||||
int LINE_NO = 0;
|
||||
|
||||
void test_swaglog() {
|
||||
setenv("MANAGER_DAEMON", "swaglog_test", 1);
|
||||
setenv("DONGLE_ID", "test_dongle_id", 1);
|
||||
setenv("CLEAN", "1", 1);
|
||||
|
||||
void *context = zmq_ctx_new();
|
||||
CHECK(context != nullptr);
|
||||
void *socket = zmq_socket(context, ZMQ_PULL);
|
||||
CHECK(socket != nullptr);
|
||||
int timeout = 5000;
|
||||
CHECK(zmq_setsockopt(socket, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)) == 0);
|
||||
CHECK(zmq_bind(socket, Path::swaglog_ipc().c_str()) == 0);
|
||||
const std::string path = Path::swaglog_ipc();
|
||||
unlink(path.c_str());
|
||||
int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
|
||||
CHECK(sock >= 0);
|
||||
struct timeval timeout = {.tv_sec = 5, .tv_usec = 0};
|
||||
CHECK(setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0);
|
||||
struct sockaddr_un addr = {.sun_family = AF_UNIX};
|
||||
strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
|
||||
CHECK(bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == 0);
|
||||
|
||||
LOGD("native-cpp-log");
|
||||
|
||||
char buffer[4096] = {};
|
||||
const int size = zmq_recv(socket, buffer, sizeof(buffer), 0);
|
||||
const int size = recv(sock, buffer, sizeof(buffer), 0);
|
||||
CHECK(size > 1);
|
||||
CHECK(buffer[0] == CLOUDLOG_DEBUG);
|
||||
std::string error;
|
||||
@@ -43,58 +45,10 @@ void test_swaglog() {
|
||||
CHECK(message["ctx"]["daemon"].string_value() == "swaglog_test");
|
||||
CHECK(message["ctx"]["dongle_id"].string_value() == "test_dongle_id");
|
||||
CHECK(message["ctx"]["dirty"].bool_value() == false);
|
||||
CHECK(message["ctx"]["version"].string_value() == SUNNYPILOT_VERSION);
|
||||
|
||||
CHECK(zmq_close(socket) == 0);
|
||||
CHECK(zmq_ctx_destroy(context) == 0);
|
||||
}
|
||||
|
||||
void recv_log(int thread_cnt, int thread_msg_cnt) {
|
||||
void *zctx = zmq_ctx_new();
|
||||
void *sock = zmq_socket(zctx, ZMQ_PULL);
|
||||
zmq_bind(sock, Path::swaglog_ipc().c_str());
|
||||
std::vector<int> thread_msgs(thread_cnt);
|
||||
int total_count = 0;
|
||||
|
||||
for (auto start = std::chrono::steady_clock::now(), now = start;
|
||||
now < start + std::chrono::seconds{1} && total_count < (thread_cnt * thread_msg_cnt);
|
||||
now = std::chrono::steady_clock::now()) {
|
||||
char buf[4096] = {};
|
||||
if (zmq_recv(sock, buf, sizeof(buf), ZMQ_DONTWAIT) <= 0) {
|
||||
if (errno == EAGAIN || errno == EINTR || errno == EFSM) continue;
|
||||
break;
|
||||
}
|
||||
|
||||
CHECK(buf[0] == CLOUDLOG_DEBUG);
|
||||
std::string err;
|
||||
auto msg = json11::Json::parse(buf + 1, err);
|
||||
CHECK(!msg.is_null());
|
||||
|
||||
CHECK(msg["levelnum"].int_value() == CLOUDLOG_DEBUG);
|
||||
CHECK(msg["filename"].string_value().find("test_swaglog.cc") != std::string::npos);
|
||||
CHECK(msg["funcname"].string_value() == "log_thread");
|
||||
CHECK(msg["lineno"].int_value() == LINE_NO);
|
||||
|
||||
auto ctx = msg["ctx"];
|
||||
|
||||
CHECK(ctx["daemon"].string_value() == daemon_name);
|
||||
CHECK(ctx["dongle_id"].string_value() == dongle_id);
|
||||
CHECK(ctx["dirty"].bool_value() == true);
|
||||
|
||||
CHECK(ctx["version"].string_value() == SUNNYPILOT_VERSION);
|
||||
|
||||
std::string device = Hardware::get_name();
|
||||
CHECK(ctx["device"].string_value() == device);
|
||||
|
||||
int thread_id = atoi(msg["msg"].string_value().c_str());
|
||||
CHECK((thread_id >= 0 && thread_id < thread_cnt));
|
||||
thread_msgs[thread_id]++;
|
||||
total_count++;
|
||||
}
|
||||
for (int i = 0; i < thread_cnt; ++i) {
|
||||
CHECK(thread_msgs[i] == thread_msg_cnt);
|
||||
}
|
||||
zmq_close(sock);
|
||||
zmq_ctx_destroy(zctx);
|
||||
CHECK(close(sock) == 0);
|
||||
CHECK(unlink(path.c_str()) == 0);
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
@@ -36,16 +36,3 @@ static inline double seconds_since_epoch() {
|
||||
clock_gettime(CLOCK_REALTIME, &t);
|
||||
return (double)t.tv_sec + t.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
// you probably should use nanos_since_boot instead
|
||||
static inline uint64_t nanos_monotonic() {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return t.tv_sec * 1000000000ULL + t.tv_nsec;
|
||||
}
|
||||
|
||||
static inline uint64_t nanos_monotonic_raw() {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC_RAW, &t);
|
||||
return t.tv_sec * 1000000000ULL + t.tv_nsec;
|
||||
}
|
||||
|
||||
@@ -235,12 +235,6 @@ std::string hexdump(const uint8_t* in, const size_t size) {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
int random_int(int min, int max) {
|
||||
std::random_device dev;
|
||||
std::mt19937 rng(dev());
|
||||
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
|
||||
return dist(rng);
|
||||
}
|
||||
|
||||
std::string random_string(std::string::size_type length) {
|
||||
const std::string chrs = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
@@ -78,7 +78,6 @@ bool ends_with(const std::string &s, const std::string &suffix);
|
||||
std::string strip(const std::string &str);
|
||||
|
||||
// ***** random helpers *****
|
||||
int random_int(int min, int max);
|
||||
std::string random_string(std::string::size_type length);
|
||||
|
||||
// **** file helpers *****
|
||||
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
# Builds emoji.npz from Noto Color Emoji's 72px PNGs and region flags: uv run --with pillow build_emoji.py
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
NOTO_EMOJI = "https://github.com/googlefonts/noto-emoji.git"
|
||||
COMMIT = "99701e07d3d1fe1bdbcdb14964547f0fd592966f"
|
||||
OUT = Path(__file__).parent / "emoji.npz"
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp)
|
||||
git = ["git", "-C", tmp]
|
||||
subprocess.run(["git", "init", "-q", tmp], check=True)
|
||||
subprocess.run([*git, "sparse-checkout", "set", "2D/png/72", "third_party/region-flags/png"], check=True)
|
||||
subprocess.run([*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", NOTO_EMOJI, COMMIT], check=True)
|
||||
subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True)
|
||||
|
||||
arrays: dict[str, np.ndarray] = {}
|
||||
for f in sorted((src / "2D/png/72").glob("emoji_u*.png")):
|
||||
key = f.stem.removeprefix("emoji_u")
|
||||
codepoints = [int(c, 16) for c in key.split("_")]
|
||||
# digits, # and * are always text, and only the default skin tone ships
|
||||
if len(codepoints) == 1 and codepoints[0] < 0x2000 and codepoints[0] not in (0xA9, 0xAE):
|
||||
continue
|
||||
if any(0x1F3FB <= c <= 0x1F3FF for c in codepoints):
|
||||
continue
|
||||
arrays[key] = np.asarray(Image.open(f).convert("RGBA"))
|
||||
|
||||
# flags are pairs of regional indicators, one per letter of the country code
|
||||
for f in sorted((src / "third_party/region-flags/png").glob("??.png")):
|
||||
img = Image.open(f).convert("RGBA")
|
||||
img = img.resize((72, max(1, round(72 * img.height / img.width))), Image.Resampling.LANCZOS)
|
||||
arrays["_".join(f"{0x1F1E6 + ord(c) - ord('A'):x}" for c in f.stem)] = np.asarray(img)
|
||||
|
||||
# same layout as np.savez_compressed, which np.load reads one array at a time
|
||||
with zipfile.ZipFile(OUT, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
for key, array in arrays.items():
|
||||
with z.open(f"{key}.npy", "w") as f:
|
||||
np.lib.format.write_array(f, array)
|
||||
print(f"{len(arrays)} emoji, {OUT.stat().st_size / 1e6:.1f} MB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:af9b3abfec97714f2a79e066703a841c63d975596e21253f325db15da0ec4963
|
||||
size 4325737
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:254b7f753b70c964847b686f0f71af751f2f49beea6ede4aeb333fe06062a257
|
||||
size 2289
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:57c7ba72642b0350ee764c924586fa66ff94915be4aba1813797e67eb4b74376
|
||||
size 33215
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:71dc069bd3dc5b11ba8e1b52eb3a1025ee0ad8c82834f94b4b2269ec0d401920
|
||||
size 237
|
||||
oid sha256:11cb414145582a5738c038b09c61b6bbd60a7b3255c96664f4f69adda41b8252
|
||||
size 312
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:73a6fe02cf19105c0051a6664a424c1bf2ede364c6cf3791f235c86ffa203f39
|
||||
size 10348
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4f500f118dca3eedbd86fc6cc943ad8be67fe5d4f7b474d5b452cd757ad805c3
|
||||
size 282
|
||||
oid sha256:fb3c2ea747e4aa7a1ad23df2776589886b1f89acb12dcd701469176607f9f82c
|
||||
size 338
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:8a49996f0ce069a048abe94ba9424de655dcff53745676ab35e045204af88a3c
|
||||
size 12103
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:8542374779f1908dc52c8a126bc041efea4c4d605afdd34e3bf8e520a7e78bf2
|
||||
size 320
|
||||
oid sha256:aa4ccc0d4d7f52a55772675f42bd53071a750d5dcefef2f9d4c8266b4959f2c5
|
||||
size 371
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:21e656b387c1a7e8de54d3e1b1c246f442cffe3c5e0924273d6d6d897c00b568
|
||||
size 13868
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:53b616fcfaaa05d6d5ac405b3a5da70525ddf65fc70ed01cdcf8e13420936bd2
|
||||
size 2460
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:aeee7f049879caff52320fab5f286cf3fd6a52c820cd8e150ff242e53a14176f
|
||||
size 14774
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:0b59ddada9c9e0e7972ead27396ebe6c10fd2352687b18ff6b476f61f74d80bf
|
||||
size 46106
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:46d08a8a08b42d466ff45d8ad6d2578e345dcbb1c06c126ad361873d9d35eaec
|
||||
size 12877
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:42ea275e5fe0a8a0e2fddb5a4a8487806fb22850115ea3646ee8f213d5fd6bb6
|
||||
size 37202
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:cfbf38672a893fd1d8fadf942354d2511e2436814a9af0e5c188cbb427fc6c70
|
||||
size 12281
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a7102850bcfb075a285041cecb546559374a905403ab3b9814fa6097d2d822dd
|
||||
size 34680
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:001cb8227eaaff5367055395d9b3ccd5822f9a47276091832d8ad28b074d77c9
|
||||
size 914
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4c3d9082b295f9e5ddef93f8d4e9cb961ea2374c7affd26394bbccb26e7137b2
|
||||
size 11023
|
||||
@@ -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))
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:02b6789e9c05eff8b02bd74a48cf2175d73720c85e91f4caf87d62fe8334acc8
|
||||
size 1963310
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a13b28f8b94e06d28f7d0f9177f50057f8b053714a11814896eef0864c5b3f0a
|
||||
size 1592395
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:35a9280706245e5c1cf875cba1a10b5b550d3c119197e2e9ec98a165ecca6b25
|
||||
size 587
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:359f691e052eb2f3ec08dca9d5c2fbedf7360a9286307c5f09b63e7c8e8888b2
|
||||
size 1123
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:6bee3a5a909e8c1f1d14a2148e54a4b7356b334a86c5a3273d5793b152b5646c
|
||||
size 776
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:cf2c9030349d352654d27d2bdc598cb63b9acf9c33d37cfcd1906216514d357e
|
||||
size 4554
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2dfd423a1caefda3a86904d4738e5bcf535e81430b49a596bd76b0d7adcd6d06
|
||||
size 2704
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:bfd580559fd4c0aaea2e974d83bb71f8766cfeb2928a5028e1a0d577bfe792eb
|
||||
size 2990
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:abdd965ba3474ac9f5d9d74b2806195cf33addc2ebded13f13050817736b13f3
|
||||
size 3401
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user