mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-11-30 05:33:45 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7fde95c2e4 |
@@ -2,6 +2,5 @@ Wen
|
||||
REGIST
|
||||
PullRequest
|
||||
cancelled
|
||||
indeces
|
||||
FOF
|
||||
NoO
|
||||
|
||||
@@ -194,7 +194,7 @@ jobs:
|
||||
find . -name '__pycache__' -type d -exec rm -rf {} +
|
||||
find . -name 'SConstruct' -delete
|
||||
find . -name 'SConscript' -delete
|
||||
rm -rf .sconsign.dblite tools/release/ release/
|
||||
rm -rf .sconsign.dblite Jenkinsfile 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 {} +
|
||||
|
||||
@@ -3,6 +3,8 @@ 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:
|
||||
@@ -64,6 +66,15 @@ 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:
|
||||
@@ -156,6 +167,13 @@ 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 }}"
|
||||
|
||||
@@ -149,7 +149,6 @@ jobs:
|
||||
|
||||
process_replay:
|
||||
name: process replay
|
||||
if: false #process replay disabled for angle steering until we are ready to merge it
|
||||
runs-on: ${{
|
||||
(github.repository == 'commaai/openpilot') &&
|
||||
((github.event_name != 'pull_request') ||
|
||||
|
||||
Generated
-7
@@ -21,12 +21,5 @@
|
||||
</clean>
|
||||
</configuration>
|
||||
</target>
|
||||
<target id="f2590b2b-9b93-49f9-8510-da3f3724a2ae" name="replay" defaultType="TOOL">
|
||||
<configuration id="d475264f-6f4c-4092-9b4e-6773309f38b7" name="replay" toolchainName="Default">
|
||||
<build type="TOOL">
|
||||
<tool actionId="Tool_External Tools_uv build tools replay" />
|
||||
</build>
|
||||
</configuration>
|
||||
</target>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-7
@@ -20,11 +20,4 @@
|
||||
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
|
||||
</exec>
|
||||
</tool>
|
||||
<tool name="uv build tools replay" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true">
|
||||
<exec>
|
||||
<option name="COMMAND" value="bash" />
|
||||
<option name="PARAMETERS" value="-c "source .venv/bin/activate && scons -u -j$(nproc) tools/replay/"" />
|
||||
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
|
||||
</exec>
|
||||
</tool>
|
||||
</toolSet>
|
||||
@@ -0,0 +1,4 @@
|
||||
[lfs]
|
||||
url = https://gitlab.com/commaai/openpilot-lfs.git/info/lfs
|
||||
pushurl = ssh://git@gitlab.com/commaai/openpilot-lfs.git
|
||||
locksverify = false
|
||||
@@ -1,5 +1,5 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
|
||||
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="sunnypilot" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
|
||||
<envs>
|
||||
<env name="QT_DBL_CLICK_DIST" value="150" />
|
||||
</envs>
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Debug Route Controls" type="PythonConfigurationType" factoryName="Python">
|
||||
<module name="openpilot-special" />
|
||||
<option name="ENV_FILES" value="" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<envs>
|
||||
<env name="PYTHONUNBUFFERED" value="1" />
|
||||
<env name="FINGERPRINT" value="KIA_EV9" />
|
||||
<env name="SKIP_FW_QUERY" value="1" />
|
||||
</envs>
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/selfdrive/car" />
|
||||
<option name="IS_MODULE_SDK" value="true" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="true" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
|
||||
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/selfdrive/car/card.py" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="SHOW_COMMAND_LINE" value="false" />
|
||||
<option name="EMULATE_TERMINAL" value="true" />
|
||||
<option name="MODULE_MODE" value="false" />
|
||||
<option name="REDIRECT_INPUT" value="false" />
|
||||
<option name="INPUT_FILE" value="" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,7 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Replay for controls + ui" type="Multirun" separateTabs="false" reuseTabsWithFailures="false" startOneByOne="true" markFailedProcess="true" hideSuccessProcess="false" delayTime="0.0">
|
||||
<runConfiguration name="replay for controls" type="Native Application" />
|
||||
<runConfiguration name="Build Debug" type="Custom Build Application" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,7 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="replay for controls" type="CLionNativeAppRunConfigurationType" focusToolWindowBeforeRun="true" PROGRAM_PARAMS=""$Prompt$" --block "sendcan,carState,carParams,carOutput,liveTracks,carParamsSP,carStateSP,bookmarkButton"" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="true" WORKING_DIR="file://$ProjectFileDir$/tools/replay" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="replay" CONFIG_NAME="replay" version="1" RUN_PATH="replay">
|
||||
<method v="2">
|
||||
<option name="CLION.COMPOUND.BUILD" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
+1
-1
@@ -7,7 +7,7 @@ export OPENBLAS_NUM_THREADS=1
|
||||
export VECLIB_MAXIMUM_THREADS=1
|
||||
|
||||
if [ -z "$AGNOS_VERSION" ]; then
|
||||
export AGNOS_VERSION="20.6-994bc1b"
|
||||
export AGNOS_VERSION="20.6"
|
||||
fi
|
||||
|
||||
export STAGING_ROOT="/data/safe_staging"
|
||||
|
||||
+1
-1
Submodule opendbc_repo updated: 2c67cf7429...07fb3ab9bc
@@ -360,7 +360,6 @@ struct OnroadEventSP @0xda96579883444c35 {
|
||||
e2eChime @23;
|
||||
laneChangeRoadEdge @24;
|
||||
bigModelReady @25;
|
||||
stockSteerIntervention @26;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,7 +389,6 @@ struct CarControlSP @0xa5cd762cd951a455 {
|
||||
leadOne @2 :LeadData;
|
||||
leadTwo @3 :LeadData;
|
||||
intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement;
|
||||
pathCurvature @5 :Float32;
|
||||
|
||||
struct Param {
|
||||
key @0 :Text;
|
||||
@@ -455,7 +453,6 @@ struct BackupManagerSP @0xf98d843bfd7004a3 {
|
||||
|
||||
struct CarStateSP @0xb86e6369214c01c8 {
|
||||
speedLimit @0 :Float32;
|
||||
stockSteerIntervention @1 :Bool;
|
||||
}
|
||||
|
||||
struct LiveMapDataSP @0xf416ec09499d9d19 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[
|
||||
{
|
||||
"name": "xbl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"size": 3282256,
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
{
|
||||
"name": "xbl_config",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"size": 98124,
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"name": "abl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"size": 274432,
|
||||
@@ -34,7 +34,7 @@
|
||||
},
|
||||
{
|
||||
"name": "aop",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"size": 184364,
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
{
|
||||
"name": "devcfg",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"size": 40336,
|
||||
@@ -56,28 +56,28 @@
|
||||
},
|
||||
{
|
||||
"name": "boot",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4.img.xz",
|
||||
"hash": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
|
||||
"hash_raw": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
|
||||
"size": 47855616,
|
||||
"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": "f456444afa8d821c5e482240af5bcfb717d8c840d16dd98100941e5f665eefa1"
|
||||
"ondevice_hash": "3519123cc1ec417e56ed2bdd449094e6e6e38ecb610ea4452dd44d5bdce5604c"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img.xz",
|
||||
"hash": "bd3c6cc917f8fdd74c1248324fa1518b091a8e810d1466c5e8fea9cf1e23f6d0",
|
||||
"hash_raw": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
|
||||
"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": "71814ad7b2ab4344790f660d463a1dc12142a8cf6a31dfabf4c43bd8545f152d",
|
||||
"ondevice_hash": "b2fc71b9071ddb0664a7e3a837df8d57ee36a2befabd8f044eb8be8d73ee66b7",
|
||||
"alt": {
|
||||
"hash": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img",
|
||||
"hash": "ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e.img",
|
||||
"size": 2147483648
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[
|
||||
{
|
||||
"name": "gpt_main_0",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_0-8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_0-8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd.img.xz",
|
||||
"hash": "8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd",
|
||||
"hash_raw": "8928a31fd9ee20f8703649f89833eba9b55e84b6415e67799c777b163c95a0bd",
|
||||
"size": 24576,
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
{
|
||||
"name": "gpt_main_1",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_1-fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_1-fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6.img.xz",
|
||||
"hash": "fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6",
|
||||
"hash_raw": "fe8ef7653db588d7420a625920ca06927dfcb0ed8aff3e3a1c74a52a24398ba6",
|
||||
"size": 24576,
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
{
|
||||
"name": "gpt_main_2",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_2-5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_2-5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21.img.xz",
|
||||
"hash": "5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21",
|
||||
"hash_raw": "5ccfc7240c8cbfa2f1a018a2e376cf274a6baf858c9bfe71951d8e28cab53c21",
|
||||
"size": 24576,
|
||||
@@ -49,7 +49,7 @@
|
||||
},
|
||||
{
|
||||
"name": "gpt_main_3",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_3-c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_3-c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159.img.xz",
|
||||
"hash": "c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159",
|
||||
"hash_raw": "c707979fa21e89519328f4f30c2b21c9c453401ca8303f914c1873d410a95159",
|
||||
"size": 24576,
|
||||
@@ -65,7 +65,7 @@
|
||||
},
|
||||
{
|
||||
"name": "gpt_main_4",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_4-e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_4-e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e.img.xz",
|
||||
"hash": "e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e",
|
||||
"hash_raw": "e9405dcd785dbe79412184e1894a9c51ab7deb33bb612166c4c42a3d2bf42a0e",
|
||||
"size": 24576,
|
||||
@@ -81,7 +81,7 @@
|
||||
},
|
||||
{
|
||||
"name": "gpt_main_5",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/gpt_main_5-21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/gpt_main_5-21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3.img.xz",
|
||||
"hash": "21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3",
|
||||
"hash_raw": "21ae965f05b2fa8d02e04f1eb74718f9779864f6eacdeb859757d6435e8ccce3",
|
||||
"size": 24576,
|
||||
@@ -97,7 +97,7 @@
|
||||
},
|
||||
{
|
||||
"name": "persist",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/persist-d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/persist-d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786.img.xz",
|
||||
"hash": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786",
|
||||
"hash_raw": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786",
|
||||
"size": 4096,
|
||||
@@ -108,7 +108,7 @@
|
||||
},
|
||||
{
|
||||
"name": "systemrw",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/systemrw-8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/systemrw-8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e.img.xz",
|
||||
"hash": "8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e",
|
||||
"hash_raw": "8ce150ca38ef64a0885fc2fe816e5b63bae8adb4df5d809c5b318e6996366c7e",
|
||||
"size": 16777216,
|
||||
@@ -119,7 +119,7 @@
|
||||
},
|
||||
{
|
||||
"name": "cache",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/cache-ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/cache-ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4.img.xz",
|
||||
"hash": "ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4",
|
||||
"hash_raw": "ebfbaaa2f96dc4e5fea4f126364e5bf5b3b44c12cbc753b62fdd8baab82f70b4",
|
||||
"size": 134217728,
|
||||
@@ -130,7 +130,7 @@
|
||||
},
|
||||
{
|
||||
"name": "xbl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"size": 3282256,
|
||||
@@ -141,7 +141,7 @@
|
||||
},
|
||||
{
|
||||
"name": "xbl_config",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"size": 98124,
|
||||
@@ -152,18 +152,18 @@
|
||||
},
|
||||
{
|
||||
"name": "abl",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/abl-b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c.img.xz",
|
||||
"hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c",
|
||||
"hash_raw": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c",
|
||||
"size": 274432,
|
||||
"sparse": false,
|
||||
"full_check": true,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35"
|
||||
"ondevice_hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c"
|
||||
},
|
||||
{
|
||||
"name": "aop",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"size": 184364,
|
||||
@@ -174,7 +174,7 @@
|
||||
},
|
||||
{
|
||||
"name": "bluetooth",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/bluetooth-9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/bluetooth-9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533.img.xz",
|
||||
"hash": "9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533",
|
||||
"hash_raw": "9bb766d2d2ce0cc4491664b3010fe1ef62f8ffc1e362d55f78e48c4141f75533",
|
||||
"size": 1048576,
|
||||
@@ -185,7 +185,7 @@
|
||||
},
|
||||
{
|
||||
"name": "cmnlib64",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/cmnlib64-1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/cmnlib64-1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3.img.xz",
|
||||
"hash": "1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3",
|
||||
"hash_raw": "1a876bd151bb9635f18719c4a17f953079de6e11d3eaec800968fc75669e0dc3",
|
||||
"size": 524288,
|
||||
@@ -196,7 +196,7 @@
|
||||
},
|
||||
{
|
||||
"name": "cmnlib",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/cmnlib-63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/cmnlib-63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82.img.xz",
|
||||
"hash": "63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82",
|
||||
"hash_raw": "63df823e8a5fae01d66cb2b8c20f0d2ddb5c5f2425e5d0992a64676273ba1c82",
|
||||
"size": 524288,
|
||||
@@ -207,7 +207,7 @@
|
||||
},
|
||||
{
|
||||
"name": "devcfg",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"size": 40336,
|
||||
@@ -218,7 +218,7 @@
|
||||
},
|
||||
{
|
||||
"name": "devinfo",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/devinfo-143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/devinfo-143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3.img.xz",
|
||||
"hash": "143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3",
|
||||
"hash_raw": "143869c499a7e878fbeab756e9c53074195770cc41d6d0d10e45c043141389a3",
|
||||
"size": 4096,
|
||||
@@ -229,7 +229,7 @@
|
||||
},
|
||||
{
|
||||
"name": "dsp",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/dsp-4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/dsp-4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248.img.xz",
|
||||
"hash": "4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248",
|
||||
"hash_raw": "4b15fbd2f45581f1553f33f01649e450b24aa19d5deff2ac7dcb16a534d9c248",
|
||||
"size": 33554432,
|
||||
@@ -240,7 +240,7 @@
|
||||
},
|
||||
{
|
||||
"name": "hyp",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/hyp-ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/hyp-ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927.img.xz",
|
||||
"hash": "ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927",
|
||||
"hash_raw": "ff5ece6a4e3d2b4d898c77ffe193fc8bbc8acebe78263996ecf52373d8088927",
|
||||
"size": 524288,
|
||||
@@ -251,7 +251,7 @@
|
||||
},
|
||||
{
|
||||
"name": "keymaster",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/keymaster-5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/keymaster-5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04.img.xz",
|
||||
"hash": "5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04",
|
||||
"hash_raw": "5c968c76f29b9a4d66fbe57e639bac6b7a2c83b1758e25abbaf5d276b8a6af04",
|
||||
"size": 524288,
|
||||
@@ -262,7 +262,7 @@
|
||||
},
|
||||
{
|
||||
"name": "limits",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/limits-94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/limits-94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1.img.xz",
|
||||
"hash": "94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1",
|
||||
"hash_raw": "94951a0f7aa55fb6cb975535ce4ebbfe6d695f04cb5424677b01c10dfa2e94e1",
|
||||
"size": 4096,
|
||||
@@ -273,7 +273,7 @@
|
||||
},
|
||||
{
|
||||
"name": "logfs",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/logfs-b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/logfs-b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220.img.xz",
|
||||
"hash": "b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220",
|
||||
"hash_raw": "b8b5ac87f3d954404fc7ecbdd9ee3b5b0cf5691e5006e6ec55db4c899ff61220",
|
||||
"size": 8388608,
|
||||
@@ -284,7 +284,7 @@
|
||||
},
|
||||
{
|
||||
"name": "modem",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/modem-a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/modem-a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994.img.xz",
|
||||
"hash": "a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994",
|
||||
"hash_raw": "a3d014f0896d77a2df7e5a80a70f43a51a047b9d03cfc675b6f0e31a6ecc4994",
|
||||
"size": 125829120,
|
||||
@@ -295,7 +295,7 @@
|
||||
},
|
||||
{
|
||||
"name": "qupfw",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/qupfw-64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/qupfw-64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a.img.xz",
|
||||
"hash": "64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a",
|
||||
"hash_raw": "64cc7c29d5d69b04267452b8b4ddba9f4809e68f476fc162ca283f58537afe4a",
|
||||
"size": 65536,
|
||||
@@ -306,7 +306,7 @@
|
||||
},
|
||||
{
|
||||
"name": "splash",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/splash-5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/splash-5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08.img.xz",
|
||||
"hash": "5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08",
|
||||
"hash_raw": "5c61260048f22ede6e6343fabb27f6ff73f9271f4751a01aaf7abf097afc1f08",
|
||||
"size": 34226176,
|
||||
@@ -317,7 +317,7 @@
|
||||
},
|
||||
{
|
||||
"name": "storsec",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/storsec-4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/storsec-4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce.img.xz",
|
||||
"hash": "4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce",
|
||||
"hash_raw": "4494d86f68b125fbf2c004c824b1c6dbe71e61a65d2a1cc7db13c553edcb3fce",
|
||||
"size": 131072,
|
||||
@@ -328,7 +328,7 @@
|
||||
},
|
||||
{
|
||||
"name": "tz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/tz-e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16.img.xz",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/tz-e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16.img.xz",
|
||||
"hash": "e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16",
|
||||
"hash_raw": "e9443bf187641661bfa6c96702b9ab0156e72fb7482500f8799ba9ee2503cb16",
|
||||
"size": 2097152,
|
||||
@@ -339,29 +339,51 @@
|
||||
},
|
||||
{
|
||||
"name": "boot",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4.img.xz",
|
||||
"hash": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
|
||||
"hash_raw": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
|
||||
"size": 47855616,
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/boot-5463317ca7a231f2ddd55a667a8c2b0d6692982359773ca875a99a0e6fd67fb4.img.xz",
|
||||
"hash": "5463317ca7a231f2ddd55a667a8c2b0d6692982359773ca875a99a0e6fd67fb4",
|
||||
"hash_raw": "5463317ca7a231f2ddd55a667a8c2b0d6692982359773ca875a99a0e6fd67fb4",
|
||||
"size": 46897152,
|
||||
"sparse": false,
|
||||
"full_check": true,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "f456444afa8d821c5e482240af5bcfb717d8c840d16dd98100941e5f665eefa1"
|
||||
"ondevice_hash": "daefa6f897bdcc277e50dbf562fd63e57d50d9fc7a599f2d171208a490e725d9"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img.xz",
|
||||
"hash": "bd3c6cc917f8fdd74c1248324fa1518b091a8e810d1466c5e8fea9cf1e23f6d0",
|
||||
"hash_raw": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
|
||||
"size": 2147483648,
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-2e1ca22762e66898aae384fcc21f488cb015c020b6b588862a64fc8128f0ad1d.img.xz",
|
||||
"hash": "14ab660bb955604ab6c482b3f59e5239e2c40c54e798201afcaed43d5cb0dcfd",
|
||||
"hash_raw": "2e1ca22762e66898aae384fcc21f488cb015c020b6b588862a64fc8128f0ad1d",
|
||||
"size": 4718592000,
|
||||
"sparse": true,
|
||||
"full_check": false,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "71814ad7b2ab4344790f660d463a1dc12142a8cf6a31dfabf4c43bd8545f152d",
|
||||
"ondevice_hash": "18666ca3b529304f5e7a8fc2e3c9dce715b55941e3965a7af43c613f8e18cfce",
|
||||
"alt": {
|
||||
"hash": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img",
|
||||
"size": 2147483648
|
||||
"hash": "2e1ca22762e66898aae384fcc21f488cb015c020b6b588862a64fc8128f0ad1d",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-2e1ca22762e66898aae384fcc21f488cb015c020b6b588862a64fc8128f0ad1d.img",
|
||||
"size": 4718592000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "userdata_90",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/userdata_90-871adca25cb254ad1704ce427f3faaae1027f74aff43a3e150188c8a1c3d3cb8.img.xz",
|
||||
"hash": "e4f59e5dcf4758759da9284479163e420febf1c118bf33c83b402e80e241608d",
|
||||
"hash_raw": "871adca25cb254ad1704ce427f3faaae1027f74aff43a3e150188c8a1c3d3cb8",
|
||||
"size": 96636764160,
|
||||
"sparse": true,
|
||||
"full_check": true,
|
||||
"has_ab": false,
|
||||
"ondevice_hash": "17b4ec7449e62c52be5df551542684b953e5c7ffc95103008043602f79ae7112"
|
||||
},
|
||||
{
|
||||
"name": "userdata_89",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/userdata_89-9d84bd64ef237a32675f936594c16932f8acbb52cf2dd82373a0e718cd32dfcf.img.xz",
|
||||
"hash": "652e61ecb5b12250dbfeb9f12fd74af16b867b5ea9bf8a08b5731ffd63a76317",
|
||||
"hash_raw": "9d84bd64ef237a32675f936594c16932f8acbb52cf2dd82373a0e718cd32dfcf",
|
||||
"size": 95563022336,
|
||||
"sparse": true,
|
||||
"full_check": true,
|
||||
"has_ab": false,
|
||||
"ondevice_hash": "acad63821bb48823c871910b1a363ab924d2635a7574cc5045e877c438d3012f"
|
||||
}
|
||||
]
|
||||
@@ -155,8 +155,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"BlinkerLateralReengageDelay", {PERSISTENT | BACKUP, INT, "0"}}, // seconds
|
||||
{"BlinkerMinLateralControlSpeed", {PERSISTENT | BACKUP, INT, "20"}}, // MPH or km/h
|
||||
{"BlinkerPauseLateralControl", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"BluetoothAllowed", {PERSISTENT, BOOL, "1"}},
|
||||
{"BluetoothEnabled", {CLEAR_ON_MANAGER_START, BOOL, "0"}},
|
||||
{"Brightness", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"CarList", {PERSISTENT, JSON}},
|
||||
{"CarParamsSP", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}},
|
||||
@@ -182,7 +180,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"LastGPSPositionFused", {PERSISTENT, STRING}},
|
||||
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
|
||||
{"MiciRoboticUI", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
|
||||
{"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
@@ -193,7 +190,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}},
|
||||
{"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RadarTracks", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RoadEdgeLaneChangeEnabled", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
@@ -235,11 +231,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"SunnylinkDongleId", {PERSISTENT, STRING}},
|
||||
{"SunnylinkdPid", {PERSISTENT, INT}},
|
||||
{"SunnylinkEnabled", {PERSISTENT, BOOL, "1"}},
|
||||
{"SunnylinkLocalConnectPhoneRequest", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalConnectPhoneWindow", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalBleGrants", {PERSISTENT | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalBleKey", {PERSISTENT | DONT_LOG, BYTES}},
|
||||
{"SunnylinkLocalBluetoothStatus", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkTempFault", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL, "0"}},
|
||||
|
||||
// Backup Manager params
|
||||
@@ -247,7 +238,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"BackupManager_RestoreVersion", {PERSISTENT, STRING}},
|
||||
|
||||
// sunnypilot car specific params
|
||||
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
{"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
|
||||
@@ -37,8 +37,6 @@ SP_BRANCH_MIGRATIONS = {
|
||||
("tizi", "release3-staging"): "release-tizi-staging",
|
||||
("mici", "release3"): "release-mici",
|
||||
("mici", "release3-staging"): "release-mici-staging",
|
||||
("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici",
|
||||
("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt"
|
||||
}
|
||||
|
||||
BUILD_METADATA_FILENAME = "build.json"
|
||||
|
||||
@@ -180,8 +180,6 @@ class Car:
|
||||
|
||||
self.is_metric = self.params.get_bool("IsMetric")
|
||||
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
|
||||
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
|
||||
self._applied_radar_tracks = getattr(self.RI, "radar_mode", self.radar_tracks)
|
||||
|
||||
# card is driven by can recv, expected at 100Hz
|
||||
self.rk = Ratekeeper(100, print_delay_threshold=None)
|
||||
@@ -196,8 +194,6 @@ class Car:
|
||||
CS, CS_SP = self.CI.update(can_list)
|
||||
CS_SP = convert_to_capnp(CS_SP)
|
||||
|
||||
self._update_radar_tracks()
|
||||
|
||||
# Update radar tracks from CAN
|
||||
RD: structs.RadarDataT | None = self.RI.update(can_list)
|
||||
|
||||
@@ -224,18 +220,6 @@ class Car:
|
||||
|
||||
return CS, CS_SP, RD
|
||||
|
||||
def _update_radar_tracks(self) -> None:
|
||||
if self.CP.brand != "hyundai" or self.radar_tracks == self._applied_radar_tracks:
|
||||
return
|
||||
|
||||
if self.RI.set_radar_mode(self.radar_tracks):
|
||||
self.CP_SP_capnp = convert_to_capnp(self.CP_SP)
|
||||
cp_sp_bytes = self.CP_SP_capnp.to_bytes()
|
||||
self.params.put("CarParamsSP", cp_sp_bytes)
|
||||
self.params.put("CarParamsSPCache", cp_sp_bytes)
|
||||
self.params.put("CarParamsSPPersistent", cp_sp_bytes)
|
||||
self._applied_radar_tracks = self.radar_tracks
|
||||
|
||||
def state_publish(self, CS: car.CarState, CS_SP: custom.CarStateSP, RD: structs.RadarDataT | None):
|
||||
"""carState and carParams publish loop"""
|
||||
|
||||
@@ -315,7 +299,6 @@ class Car:
|
||||
while not evt.is_set():
|
||||
self.is_metric = self.params.get_bool("IsMetric")
|
||||
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
|
||||
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
|
||||
|
||||
# sunnypilot
|
||||
self.v_cruise_helper.read_custom_set_speed_params()
|
||||
|
||||
@@ -26,8 +26,6 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum
|
||||
|
||||
# stationary qualification parameters
|
||||
V_EGO_STATIONARY = 4. # no stationary object flag below this speed
|
||||
DBC_MOTION_STATIONARY = 1
|
||||
DBC_MOTION_MOVING = 2
|
||||
|
||||
RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame
|
||||
|
||||
@@ -193,14 +191,8 @@ def get_custom_yrel(CP: structs.CarParams, CP_SP: structs.CarParamsSP, lead_dict
|
||||
return lead_dict
|
||||
|
||||
|
||||
def radar_point_eligible_for_fusion(CP: structs.CarParams, CP_SP: structs.CarParamsSP,
|
||||
point: car.RadarData.RadarPoint) -> bool:
|
||||
use_dbc_motion = CP.brand == "hyundai" and CP_SP.flags & HyundaiFlagsSP.RADAR_FULL_RADAR
|
||||
return not use_dbc_motion or point.motionState in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING)
|
||||
|
||||
|
||||
class RadarD:
|
||||
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, delay: float = 0.0):
|
||||
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParams, delay: float = 0.0):
|
||||
self.CP = CP
|
||||
self.CP_SP = CP_SP
|
||||
|
||||
@@ -226,11 +218,7 @@ class RadarD:
|
||||
self.v_ego_hist.append(self.v_ego)
|
||||
self.last_v_ego_frame = sm.recv_frame['carState']
|
||||
|
||||
ar_pts = {
|
||||
pt.trackId: [pt.dRel, pt.yRel, pt.vRel]
|
||||
for pt in rr.points
|
||||
if radar_point_eligible_for_fusion(self.CP, self.CP_SP, pt)
|
||||
}
|
||||
ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points}
|
||||
|
||||
# *** remove missing points from meta data ***
|
||||
for ids in list(self.tracks.keys()):
|
||||
|
||||
@@ -100,19 +100,7 @@ class TogglesLayout(Widget):
|
||||
icon="speed_limit.png"
|
||||
)
|
||||
|
||||
|
||||
self._radar_tracks_setting = None
|
||||
self._toggles: dict[str, ListItem] = {}
|
||||
if gui_app.sunnypilot_ui():
|
||||
self._radar_tracks_setting = multiple_button_item(
|
||||
lambda: tr("Radar Tracks"),
|
||||
"",
|
||||
buttons=[lambda: tr("Off"), lambda: tr("Lead Only"), lambda: tr("Full Radar")],
|
||||
button_width=250,
|
||||
callback=self._set_radar_tracks,
|
||||
selected_index=self._params.get("RadarTracks", return_default=True),
|
||||
)
|
||||
self._toggles["RadarTracks"] = self._radar_tracks_setting
|
||||
self._initial_cruise_speed = ListItem(
|
||||
title=lambda: tr("Initial Max Speed"),
|
||||
description=lambda: tr("Max speed when engaging openpilot. If you are already driving faster, your current speed is used. " +
|
||||
@@ -181,8 +169,6 @@ class TogglesLayout(Widget):
|
||||
# refresh toggles from params to mirror external changes
|
||||
for param in self._toggle_defs:
|
||||
self._toggles[param].action_item.set_state(self._params.get_bool(param))
|
||||
if self._radar_tracks_setting is not None:
|
||||
self._radar_tracks_setting.action_item.set_selected_button(self._params.get("RadarTracks", return_default=True))
|
||||
|
||||
# these toggles need restart, block while engaged
|
||||
for toggle_def in self._toggle_defs:
|
||||
@@ -202,6 +188,3 @@ class TogglesLayout(Widget):
|
||||
|
||||
def _set_longitudinal_personality(self, button_index: int):
|
||||
self._params.put("LongitudinalPersonality", button_index, block=True)
|
||||
|
||||
def _set_radar_tracks(self, button_index: int):
|
||||
self._params.put("RadarTracks", button_index, block=True)
|
||||
|
||||
@@ -100,8 +100,6 @@ class Sidebar(Widget, SidebarSP):
|
||||
|
||||
self._draw_buttons(rect)
|
||||
self._draw_network_indicator(rect)
|
||||
if gui_app.sunnypilot_ui():
|
||||
SidebarSP._draw_bluetooth_indicator(self, rect)
|
||||
self._draw_metrics(rect)
|
||||
|
||||
def _update_state(self):
|
||||
|
||||
@@ -15,7 +15,6 @@ from openpilot.system.ui.lib.application import gui_app
|
||||
if gui_app.sunnypilot_ui():
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.home import MiciHomeLayoutSP as MiciHomeLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import RoboticOnroadView
|
||||
|
||||
ONROAD_DELAY = 2.5 # seconds
|
||||
GREET_IGNITION_OFF_TIME = 60 * 60 # greet again when the car turns on after being off this long
|
||||
@@ -38,34 +37,23 @@ class MiciMainLayout(Scroller):
|
||||
self._alerts_layout = MiciOffroadAlerts()
|
||||
self._settings_layout = SettingsLayout()
|
||||
self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked)
|
||||
self._robotic_onroad_layout = RoboticOnroadView(bookmark_callback=self._on_bookmark_clicked) if gui_app.sunnypilot_ui() else None
|
||||
self._body_onroad_layout = BodyLayout()
|
||||
self._prev_robotic_ui = bool(gui_app.sunnypilot_ui() and ui_state.mici_robotic_ui)
|
||||
|
||||
# Initialize widget rects
|
||||
all_widgets = [self._home_layout, self._alerts_layout, self._settings_layout,
|
||||
self._car_onroad_layout, self._body_onroad_layout]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
all_widgets.append(self._robotic_onroad_layout)
|
||||
for widget in all_widgets:
|
||||
for widget in (self._home_layout, self._alerts_layout, self._settings_layout,
|
||||
self._car_onroad_layout, self._body_onroad_layout):
|
||||
# TODO: set parent rect and use it if never passed rect from render (like in Scroller)
|
||||
widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
|
||||
|
||||
scroller_widgets = [
|
||||
self._scroller.add_widgets([
|
||||
self._home_layout,
|
||||
self._car_onroad_layout,
|
||||
]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
scroller_widgets.append(self._robotic_onroad_layout)
|
||||
scroller_widgets.append(self._body_onroad_layout)
|
||||
self._scroller.add_widgets(scroller_widgets)
|
||||
self._body_onroad_layout,
|
||||
])
|
||||
self._scroller.set_reset_scroll_at_show(False)
|
||||
|
||||
# Disable scrolling when onroad is interacting with bookmark
|
||||
self._scroller.set_scrolling_enabled(
|
||||
lambda: not (self._car_onroad_layout.is_swiping_left() or
|
||||
(self._robotic_onroad_layout is not None and self._robotic_onroad_layout.is_swiping_left()))
|
||||
)
|
||||
self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left())
|
||||
|
||||
# Set callbacks
|
||||
self._setup_callbacks()
|
||||
@@ -84,11 +72,7 @@ class MiciMainLayout(Scroller):
|
||||
@property
|
||||
def _onroad_layout(self) -> Widget:
|
||||
# For scroll_to
|
||||
if ui_state.is_body:
|
||||
return self._body_onroad_layout
|
||||
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui:
|
||||
return self._robotic_onroad_layout
|
||||
return self._car_onroad_layout
|
||||
return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout
|
||||
|
||||
def _setup_callbacks(self):
|
||||
self._alerts_layout.set_pairing_callback(self._settings_layout.show_pairing)
|
||||
@@ -98,10 +82,7 @@ class MiciMainLayout(Scroller):
|
||||
alert_count_callback=self._alerts_layout.active_alerts,
|
||||
alert_icon_callback=self._alerts_layout.highest_severity_icon,
|
||||
)
|
||||
onroad_layouts = [self._car_onroad_layout, self._body_onroad_layout]
|
||||
if self._robotic_onroad_layout is not None:
|
||||
onroad_layouts.append(self._robotic_onroad_layout)
|
||||
for layout in onroad_layouts:
|
||||
for layout in (self._car_onroad_layout, self._body_onroad_layout):
|
||||
layout.set_click_callback(lambda: self._scroll_to(self._home_layout))
|
||||
|
||||
device.add_interactive_timeout_callback(self._on_interactive_timeout)
|
||||
@@ -111,11 +92,6 @@ class MiciMainLayout(Scroller):
|
||||
layout_x = int(layout.rect.x)
|
||||
self._scroller.scroll_to(layout_x, smooth=True)
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui != self._prev_robotic_ui:
|
||||
self._prev_robotic_ui = ui_state.mici_robotic_ui
|
||||
self._on_body_changed()
|
||||
def _handle_transitions(self):
|
||||
# greet when getting in the car after it's been off for a while
|
||||
if ui_state.ignition != self._prev_ignition:
|
||||
@@ -170,8 +146,5 @@ class MiciMainLayout(Scroller):
|
||||
self._pm.send(service, msg)
|
||||
|
||||
def _on_body_changed(self):
|
||||
use_robotic = self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui
|
||||
self._car_onroad_layout.set_visible(not ui_state.is_body and not use_robotic)
|
||||
if self._robotic_onroad_layout is not None:
|
||||
self._robotic_onroad_layout.set_visible(not ui_state.is_body and use_robotic)
|
||||
self._car_onroad_layout.set_visible(not ui_state.is_body)
|
||||
self._body_onroad_layout.set_visible(bool(ui_state.is_body))
|
||||
|
||||
@@ -28,17 +28,9 @@ class DrivingLayoutMici(NavScroller):
|
||||
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback,
|
||||
description="Enable to use sunnypilot driver assistance.\n" +
|
||||
"Disable to use your car's stock driver assistance.")
|
||||
robotic_ui_toggle = BigParamControl(
|
||||
"robotic companion UI",
|
||||
"MiciRoboticUI",
|
||||
description="Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
|
||||
)
|
||||
radar_tracks = BigMultiParamToggle("radar tracks", "RadarTracks", ["off", "lead only", "full radar"])
|
||||
self._radar_tracks_toggle = radar_tracks
|
||||
|
||||
|
||||
self._scroller.add_widgets([
|
||||
robotic_ui_toggle,
|
||||
radar_tracks,
|
||||
self._personality_toggle,
|
||||
self._initial_cruise_speed,
|
||||
always_on_dm_toggle,
|
||||
@@ -48,7 +40,6 @@ class DrivingLayoutMici(NavScroller):
|
||||
|
||||
# Toggle lists
|
||||
self._refresh_toggles = (
|
||||
("MiciRoboticUI", robotic_ui_toggle),
|
||||
("IsLdwEnabled", ldw_toggle),
|
||||
("AlwaysOnDM", always_on_dm_toggle),
|
||||
("OpenpilotEnabledToggle", enable_openpilot),
|
||||
@@ -86,4 +77,3 @@ class DrivingLayoutMici(NavScroller):
|
||||
# Refresh toggles from params to mirror external changes
|
||||
for key, item in self._refresh_toggles:
|
||||
item.set_checked(ui_state.params.get_bool(key))
|
||||
self._radar_tracks_toggle._load_value()
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
"""Tests for MICI Robotic Companion onroad UI mood engine and telemetry helpers."""
|
||||
import random
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
EyeGlyph,
|
||||
MouthGlyph,
|
||||
PALETTE,
|
||||
RoboticMood,
|
||||
RoboticMoodEngine,
|
||||
STANDSTILL_POUT_DELAY,
|
||||
STANDSTILL_SLEEPY_DELAY,
|
||||
display_speed_and_set_speed,
|
||||
)
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
|
||||
|
||||
class TestRoboticMoodEngine(OpenpilotTestCase):
|
||||
def _engine(self) -> RoboticMoodEngine:
|
||||
return RoboticMoodEngine(rng=random.Random(42))
|
||||
|
||||
def test_engaged_happy_then_speed_then_cruising(self):
|
||||
engine = self._engine()
|
||||
# Initially disengaged
|
||||
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
|
||||
target = engine.update(snap, now=10.0)
|
||||
assert engine.mood == RoboticMood.IDLE_CURIOUS
|
||||
assert target.color == PALETTE["disengaged"]
|
||||
|
||||
# Engage triggers HAPPY_ENGAGE crescent eyes
|
||||
snap_eng = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
|
||||
target = engine.update(snap_eng, now=11.0)
|
||||
assert engine.mood == RoboticMood.HAPPY_ENGAGE
|
||||
assert target.glyph == EyeGlyph.CRESCENT
|
||||
assert target.color == PALETTE["engaged"]
|
||||
|
||||
# After happy hold, briefly shows speed confirmation
|
||||
engine.update(snap_eng, now=12.2)
|
||||
assert engine.mood == RoboticMood.SPEED_DISPLAY
|
||||
assert engine.showing_speed is True
|
||||
|
||||
# After speed confirm expires, settles into CRUISING_HAPPY
|
||||
target = engine.update(snap_eng, now=15.0)
|
||||
assert engine.mood == RoboticMood.CRUISING_HAPPY
|
||||
assert engine.showing_speed is False
|
||||
assert target.color == PALETTE["engaged"]
|
||||
|
||||
def test_critical_alert_overrides_all_moods(self):
|
||||
engine = self._engine()
|
||||
engine.trigger_love(now=10.0)
|
||||
engine.trigger_speed_peek(now=10.0)
|
||||
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, alert=alert)
|
||||
|
||||
target = engine.update(snap, now=10.1)
|
||||
assert engine.mood == RoboticMood.CRITICAL
|
||||
assert target.glyph == EyeGlyph.LASER_ALERT
|
||||
assert target.color == PALETTE["critical"]
|
||||
assert engine.showing_speed is False
|
||||
|
||||
def test_distracted_driver_monitoring(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, dm_alert_level=1)
|
||||
target = engine.update(snap, now=20.0)
|
||||
assert engine.mood == RoboticMood.DISTRACTED
|
||||
assert target.color == PALETTE["prompt"]
|
||||
assert target.mouth == MouthGlyph.FROWN
|
||||
|
||||
def test_hard_decel_triggers_star_eyes(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, a_ego=-3.8)
|
||||
target = engine.update(snap, now=30.0)
|
||||
assert engine.mood == RoboticMood.STARTLED_STARS
|
||||
assert target.glyph == EyeGlyph.STAR
|
||||
assert target.mouth == MouthGlyph.SURPRISED
|
||||
|
||||
def test_lane_change_and_blind_spot(self):
|
||||
engine = self._engine()
|
||||
snap_lc = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, pre_lane_change_left=True)
|
||||
target = engine.update(snap_lc, now=40.0)
|
||||
assert engine.mood == RoboticMood.LANE_CHANGE
|
||||
assert target.glyph == EyeGlyph.ARROW_LEFT
|
||||
assert target.gaze_x < 0
|
||||
|
||||
snap_bsm = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, right_blinker=True, right_blindspot=True)
|
||||
target = engine.update(snap_bsm, now=41.0)
|
||||
assert engine.mood == RoboticMood.BLIND_SPOT
|
||||
assert target.gaze_x > 0
|
||||
assert target.blind_spot_side == 1
|
||||
|
||||
def test_standstill_pout_and_sleepy_progression(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
|
||||
engine.update(snap, now=100.0)
|
||||
# Past happy engage & speed confirm, still before pout
|
||||
engine.update(snap, now=105.0)
|
||||
assert engine.mood == RoboticMood.CRUISING_HAPPY
|
||||
|
||||
# Past pout threshold
|
||||
target = engine.update(snap, now=100.0 + STANDSTILL_POUT_DELAY + 1.0)
|
||||
assert engine.mood == RoboticMood.POUT_STANDSTILL
|
||||
assert target.mouth == MouthGlyph.FROWN
|
||||
|
||||
# Past sleepy threshold
|
||||
target = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 1.0)
|
||||
assert engine.mood == RoboticMood.SLEEPY
|
||||
assert target.top_lid >= 0.5
|
||||
|
||||
def test_set_speed_change_triggers_speed_display(self):
|
||||
engine = self._engine()
|
||||
snap1 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
|
||||
engine.update(snap1, now=10.0)
|
||||
engine.update(snap1, now=15.0)
|
||||
assert engine.showing_speed is False
|
||||
|
||||
snap2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=110.0)
|
||||
engine.update(snap2, now=16.0)
|
||||
assert engine.mood == RoboticMood.SPEED_DISPLAY
|
||||
assert engine.showing_speed is True
|
||||
assert engine.speed_reason == "set_speed"
|
||||
|
||||
def test_mads_lat_only_warm_peach_palette(self):
|
||||
engine = self._engine()
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=18.0)
|
||||
engine.update(snap, now=10.0)
|
||||
target = engine.update(snap, now=15.0)
|
||||
assert target.color == PALETTE["lat_only"]
|
||||
|
||||
def test_display_speed_conversion(self):
|
||||
snap_mph = DrivingSnapshot(v_ego=26.8224, set_speed_kph=100.0, is_metric=False)
|
||||
cur, set_s = display_speed_and_set_speed(snap_mph)
|
||||
assert cur == 60
|
||||
assert set_s == 62
|
||||
|
||||
snap_kph = DrivingSnapshot(v_ego=27.7778, set_speed_kph=100.0, is_metric=True)
|
||||
cur, set_s = display_speed_and_set_speed(snap_kph)
|
||||
assert cur == 100
|
||||
assert set_s == 100
|
||||
|
||||
def test_sharp_accel_turn_signal_sharp_turn_and_continuous_motion(self):
|
||||
engine = self._engine()
|
||||
# Sharp acceleration triggers BOOST_ACCEL with speed lines
|
||||
snap_boost = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, a_ego=2.8)
|
||||
engine.update(snap_boost, now=10.0)
|
||||
target = engine.update(snap_boost, now=14.0)
|
||||
# Trigger fresh boost after engage hold expires
|
||||
snap_boost2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, a_ego=2.9)
|
||||
target = engine.update(snap_boost2, now=15.0)
|
||||
assert engine.mood == RoboticMood.BOOST_ACCEL
|
||||
assert target.glyph == EyeGlyph.SPARKLE_BOOST
|
||||
assert target.show_speed_lines is True
|
||||
|
||||
# Turn indicator triggers TURN_SIGNAL with blinker side
|
||||
snap_turn = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0, left_blinker=True)
|
||||
target = engine.update(snap_turn, now=20.0)
|
||||
assert engine.mood == RoboticMood.TURN_SIGNAL
|
||||
assert target.blinker_side == -1
|
||||
|
||||
# Sharp high-speed turn triggers SHARP_TURN with centrifugal tilt
|
||||
snap_sharp = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=22.0, yaw_rate=-0.18)
|
||||
target = engine.update(snap_sharp, now=25.0)
|
||||
assert engine.mood == RoboticMood.SHARP_TURN
|
||||
assert abs(target.tilt_y) >= 10.0
|
||||
|
||||
# Bookmark wink triggers love with wink_right=True
|
||||
engine.trigger_love(now=30.0, wink=True)
|
||||
target = engine.update(DrivingSnapshot(started=True, engaged=False), now=30.2)
|
||||
assert engine.mood == RoboticMood.BOOKMARK_LOVE
|
||||
assert target.wink_right is True
|
||||
assert target.show_hearts is True
|
||||
|
||||
# Continuous motion check: idle bounce_y & gaze_x are never frozen across frames
|
||||
snap_idle = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=0.0)
|
||||
t1 = engine.update(snap_idle, now=40.0)
|
||||
t2 = engine.update(snap_idle, now=40.5)
|
||||
assert (t1.bounce_y != t2.bounce_y) or (t1.gaze_x != t2.gaze_x)
|
||||
|
||||
def test_music_analyzer_rejects_road_noise_and_speech_detects_music(self):
|
||||
import numpy as np
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import (
|
||||
DEFAULT_SAMPLE_RATE,
|
||||
MusicAnalyzer,
|
||||
MusicState,
|
||||
)
|
||||
|
||||
sr = DEFAULT_SAMPLE_RATE
|
||||
chunk_len = 800 # 50 ms @ 16 kHz
|
||||
rng = np.random.default_rng(7)
|
||||
|
||||
# 1. Broadband cabin road/wind noise -> MUST be rejected
|
||||
road_analyzer = MusicAnalyzer(sr)
|
||||
for _ in range(90): # 4.5 s
|
||||
noise = rng.normal(0.0, 0.08, size=chunk_len).astype(np.float32)
|
||||
state = road_analyzer.process_samples(noise)
|
||||
assert state.is_music is False, f"Road noise falsely triggered music (conf={state.confidence:.2f})"
|
||||
|
||||
# 2. Simulated human talking (irregular vocal-band bursts with speech pauses) -> MUST be rejected
|
||||
speech_analyzer = MusicAnalyzer(sr)
|
||||
t_total = np.arange(90 * chunk_len, dtype=np.float32) / sr
|
||||
# Speech formants (550Hz + 1200Hz) modulated by irregular syllables & pauses
|
||||
vocal = 0.09 * np.sin(2 * np.pi * 550 * t_total) + 0.06 * np.sin(2 * np.pi * 1250 * t_total)
|
||||
for idx in range(90):
|
||||
# Irregular talk/pause pattern (approx 45% active)
|
||||
speaking = (idx % 11) in (0, 1, 2, 5, 6)
|
||||
seg = vocal[idx * chunk_len:(idx + 1) * chunk_len] * (1.0 if speaking else 0.02)
|
||||
seg = seg + rng.normal(0.0, 0.01, size=chunk_len).astype(np.float32)
|
||||
state = speech_analyzer.process_samples(seg)
|
||||
assert state.is_music is False, f"Talking falsely triggered music (conf={state.confidence:.2f})"
|
||||
|
||||
# 3. Simulated quiet cabin music mixed with highway road rumble -> MUST be detected
|
||||
music_analyzer = MusicAnalyzer(sr)
|
||||
beat_period = 0.5 # 120 BPM
|
||||
for idx in range(100): # 5.0 s
|
||||
t = (idx * chunk_len + np.arange(chunk_len, dtype=np.float32)) / sr
|
||||
beat_t = t % beat_period
|
||||
kick = 0.035 * np.exp(-beat_t * 18.0) * np.sin(2 * np.pi * 95.0 * t)
|
||||
chord = (
|
||||
0.018 * np.sin(2 * np.pi * 261.6 * t)
|
||||
+ 0.015 * np.sin(2 * np.pi * 329.6 * t)
|
||||
+ 0.015 * np.sin(2 * np.pi * 392.0 * t)
|
||||
)
|
||||
hihat_t = (t + 0.25) % beat_period
|
||||
hihat = 0.014 * np.exp(-hihat_t * 35.0) * np.sin(2 * np.pi * 5200.0 * t)
|
||||
road_rumble = rng.normal(0.0, 0.008, size=chunk_len).astype(np.float32)
|
||||
mix = (kick + chord + hihat + road_rumble).astype(np.float32)
|
||||
state = music_analyzer.process_samples(mix)
|
||||
assert state.is_music is True, f"Quiet cabin music over road rumble was not detected (conf={state.confidence:.2f})"
|
||||
assert max(state.bands) > 0.2
|
||||
|
||||
# 4. Mood engine enters MUSIC_GROOVE when cruising/idling (even during gentle low-speed turn), overridden by alerts
|
||||
engine = self._engine()
|
||||
music_on = MusicState(is_music=True, confidence=0.85, beat_pulse=0.7, groove_phase=1.2, bpm=120.0, energy=0.7)
|
||||
snap_cruise = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, steering_angle_deg=20.0, music=music_on)
|
||||
engine.update(snap_cruise, now=10.0)
|
||||
engine.update(snap_cruise, now=15.0)
|
||||
assert engine.mood == RoboticMood.MUSIC_GROOVE
|
||||
|
||||
# Alert overrides MUSIC_GROOVE immediately
|
||||
snap_alert = DrivingSnapshot(
|
||||
started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on,
|
||||
alert=Alert("Pay Attention", "Eyes on road", status=AlertStatus.userPrompt),
|
||||
)
|
||||
engine.update(snap_alert, now=15.5)
|
||||
assert engine.mood == RoboticMood.USER_PROMPT
|
||||
|
||||
def test_centrifugal_turn_squish_direction_speed_gate_and_no_vertical(self):
|
||||
engine = self._engine()
|
||||
# Low-speed controlled turn (v_ego=5 m/s) -> stays calm, zero squish, zero vertical movement
|
||||
snap_slow = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=5.0, yaw_rate=0.25, pitch_rad=0.10, pitch_rate=0.2)
|
||||
engine.update(snap_slow, now=10.0)
|
||||
t_slow = engine.update(snap_slow, now=15.0)
|
||||
assert t_slow.squish_force == 0.0
|
||||
assert t_slow.pitch_offset_y == 0.0
|
||||
assert engine.mood == RoboticMood.CRUISING_HAPPY
|
||||
|
||||
# High-speed RIGHT turn (yaw_rate > 0 in FRD) -> pushed LEFT (squish_force < 0, opposite side of turn)
|
||||
snap_right_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=0.19, pitch_rad=0.10)
|
||||
t_right = engine.update(snap_right_fast, now=16.0)
|
||||
assert engine.mood == RoboticMood.SHARP_TURN
|
||||
assert t_right.squish_force < -0.65
|
||||
assert t_right.pitch_offset_y == 0.0
|
||||
assert t_right.mouth == MouthGlyph.SURPRISED
|
||||
|
||||
# High-speed LEFT turn (yaw_rate < 0 in FRD) -> pushed RIGHT (squish_force > 0, opposite side of turn)
|
||||
snap_left_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=-0.19)
|
||||
t_left = engine.update(snap_left_fast, now=17.0)
|
||||
assert engine.mood == RoboticMood.SHARP_TURN
|
||||
assert t_left.squish_force > 0.65
|
||||
assert t_left.pitch_offset_y == 0.0
|
||||
@@ -1,4 +1,3 @@
|
||||
import contextlib
|
||||
import math
|
||||
import numpy as np
|
||||
import time
|
||||
@@ -9,27 +8,29 @@ from openpilot.cereal import log, messaging, custom
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.realtime import Ratekeeper
|
||||
from openpilot.common.utils import retry
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
from openpilot.system import micd
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
|
||||
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
|
||||
|
||||
SAMPLE_RATE = 48000
|
||||
SAMPLE_BUFFER = 4096 # (approx 100ms)
|
||||
MAX_VOLUME = 1.0
|
||||
|
||||
AMBIENT_DB = 10.0 # DB where MIN_VOLUME is applied
|
||||
DB_SCALE = 25.0 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
|
||||
MIN_VOLUME = 0.45
|
||||
|
||||
MIN_VOLUME = 0.1
|
||||
ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for immediate warnings
|
||||
SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds
|
||||
FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES)
|
||||
|
||||
AMBIENT_DB = 26 # DB where MIN_VOLUME is applied
|
||||
DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
|
||||
|
||||
VOLUME_BASE = 20
|
||||
REINIT_RETRY_INTERVAL = 3.0
|
||||
if HARDWARE.get_device_type() == "tizi":
|
||||
AMBIENT_DB = 30
|
||||
VOLUME_BASE = 10
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
|
||||
@@ -77,7 +78,6 @@ def check_selfdrive_timeout_alert(sm):
|
||||
class Soundd(QuietMode):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.robotic_sound_pack = RoboticSoundPack(self.params, SAMPLE_RATE)
|
||||
|
||||
self.load_sounds()
|
||||
|
||||
@@ -92,7 +92,6 @@ class Soundd(QuietMode):
|
||||
self.pending_stop = False
|
||||
|
||||
self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False)
|
||||
self.spl_received = False
|
||||
|
||||
def load_sounds(self):
|
||||
self.loaded_sounds: dict[int, np.ndarray] = {}
|
||||
@@ -109,32 +108,13 @@ class Soundd(QuietMode):
|
||||
length = wavefile.getnframes()
|
||||
self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2)
|
||||
|
||||
self.robotic_sound_pack.load()
|
||||
|
||||
def load_param(self) -> None:
|
||||
prev_frame = self._frame
|
||||
super().load_param()
|
||||
if self._frame != prev_frame and self._frame % 50 == 0:
|
||||
if self.robotic_sound_pack.refresh_param():
|
||||
self.current_sound_frame = 0
|
||||
|
||||
def _sound_buffer(self, alert_id: int) -> np.ndarray | None:
|
||||
"""Resolve the buffer for an alert id, or None when this id has no sound loaded."""
|
||||
if alert_id == AudibleAlert.none:
|
||||
return None
|
||||
try:
|
||||
return self.robotic_sound_pack.get_buffer(alert_id, self.loaded_sounds)
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required
|
||||
|
||||
ret = np.zeros(frames, dtype=np.float32)
|
||||
sound_data = self._sound_buffer(self.current_alert)
|
||||
|
||||
if sound_data is not None:
|
||||
audible = self.should_play_sound(self.current_alert)
|
||||
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
|
||||
if self.should_play_sound(self.current_alert):
|
||||
num_loops = sound_list[self.current_alert][1]
|
||||
sound_data = self.loaded_sounds[self.current_alert]
|
||||
written_frames = 0
|
||||
|
||||
current_sound_frame = self.current_sound_frame % len(sound_data)
|
||||
@@ -143,8 +123,7 @@ class Soundd(QuietMode):
|
||||
while written_frames < frames and (num_loops is None or loops < num_loops):
|
||||
available_frames = sound_data.shape[0] - current_sound_frame
|
||||
frames_to_write = min(available_frames, frames - written_frames)
|
||||
if audible:
|
||||
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
|
||||
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
|
||||
written_frames += frames_to_write
|
||||
self.current_sound_frame += frames_to_write
|
||||
current_sound_frame = self.current_sound_frame % len(sound_data)
|
||||
@@ -154,35 +133,17 @@ class Soundd(QuietMode):
|
||||
self.pending_stop = False
|
||||
break
|
||||
|
||||
vol = self.current_volume
|
||||
if self.robotic_sound_pack.enabled and not self.enabled and self.current_alert != AudibleAlert.none:
|
||||
vol = max(vol, 0.35)
|
||||
return ret * vol
|
||||
return ret * self.current_volume
|
||||
|
||||
def callback(self, data_out: np.ndarray, frames: int, time, status) -> None:
|
||||
if status:
|
||||
cloudlog.warning(f"soundd stream over/underflow: {status}")
|
||||
data_out[:frames, 0] = self.get_sound_data(frames)
|
||||
|
||||
def _note_play(self, alert_id: int) -> None:
|
||||
"""Log the alert start together with the routing decision and the gain it plays at."""
|
||||
if alert_id == AudibleAlert.none:
|
||||
return
|
||||
|
||||
audible = self.should_play_sound(alert_id)
|
||||
robotic = self.robotic_sound_pack.enabled and alert_id in self.robotic_sound_pack.sounds
|
||||
cloudlog.debug(f"soundd play alert={alert_id} robotic={robotic} audible={audible} gain={self.current_volume:.2f}")
|
||||
|
||||
def update_alert(self, new_alert):
|
||||
current_buffer = self._sound_buffer(self.current_alert)
|
||||
current_alert_played_once = current_buffer is None or self.current_sound_frame >= len(current_buffer)
|
||||
current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert])
|
||||
# let looping sounds finish the current loop instead of cutting off mid tone
|
||||
if (
|
||||
new_alert == AudibleAlert.none
|
||||
and self.current_alert != AudibleAlert.none
|
||||
and self.current_alert not in REACTIVE_CHIRP_IDS
|
||||
and sound_list[self.current_alert][1] is None
|
||||
):
|
||||
if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None:
|
||||
if current_alert_played_once:
|
||||
self.pending_stop = True
|
||||
else:
|
||||
@@ -196,7 +157,6 @@ class Soundd(QuietMode):
|
||||
self.ramp_start_time = time.monotonic()
|
||||
self.current_alert = new_alert
|
||||
self.current_sound_frame = 0
|
||||
self._note_play(new_alert)
|
||||
|
||||
def get_audible_alert(self, sm):
|
||||
if sm.updated['selfdriveState']:
|
||||
@@ -209,78 +169,38 @@ class Soundd(QuietMode):
|
||||
self.update_alert(AudibleAlert.none)
|
||||
self.selfdrive_timeout_alert = False
|
||||
|
||||
# Trigger playful one-shot robotic chirps only when idle (never preempting safety alerts)
|
||||
if self.robotic_sound_pack.enabled and self.current_alert == AudibleAlert.none:
|
||||
chirp = self.robotic_sound_pack.detect_reactive_chirp(sm)
|
||||
if chirp is not None:
|
||||
self.update_alert(chirp)
|
||||
|
||||
def calculate_volume(self, weighted_db):
|
||||
volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME
|
||||
return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1))
|
||||
|
||||
def _reinit_stream(self, sd, stream):
|
||||
if stream is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
stream.close()
|
||||
|
||||
# reload sounddevice to reinitialize portaudio, then open the output stream
|
||||
@retry(attempts=10, delay=3)
|
||||
def get_stream(self, sd):
|
||||
# reload sounddevice to reinitialize portaudio
|
||||
sd._terminate()
|
||||
sd._initialize()
|
||||
new_stream = sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
|
||||
try:
|
||||
new_stream.start()
|
||||
except Exception:
|
||||
with contextlib.suppress(Exception):
|
||||
new_stream.close()
|
||||
raise
|
||||
cloudlog.info(f"soundd stream started: {new_stream.samplerate=} {new_stream.channels=} {new_stream.dtype=} {new_stream.device=}, {new_stream.blocksize=}")
|
||||
return new_stream
|
||||
|
||||
def update_volume(self, valid: bool, sound_pressure_weighted_db: float) -> None:
|
||||
# Only adapt volume from valid mic data. With invalid (stale) soundPressure
|
||||
# we freeze instead of decaying towards MIN_VOLUME, so critical alerts can
|
||||
# never be silenced by a broken mic (https://github.com/commaai/openpilot/issues/36088)
|
||||
if not valid:
|
||||
if self.spl_received:
|
||||
cloudlog.warning("soundd: soundPressure invalid, freezing alert volume")
|
||||
self.spl_received = False
|
||||
return
|
||||
|
||||
self.spl_received = True
|
||||
self.spl_filter_weighted.update(sound_pressure_weighted_db)
|
||||
# freeze volume during alerts to avoid mic feedback increasing volume
|
||||
if self.current_alert == AudibleAlert.none:
|
||||
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
|
||||
return sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
|
||||
|
||||
def soundd_thread(self):
|
||||
# sounddevice must be imported after forking processes
|
||||
import sounddevice as sd
|
||||
micd.patch_sounddevice(sd)
|
||||
|
||||
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure', 'carState', 'controlsState', 'userBookmark', 'bookmarkButton'])
|
||||
rk = Ratekeeper(20)
|
||||
stream = None
|
||||
last_reinit_time: float | None = None
|
||||
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure'])
|
||||
|
||||
try:
|
||||
with self.get_stream(sd) as stream:
|
||||
rk = Ratekeeper(20)
|
||||
|
||||
cloudlog.info(f"soundd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}")
|
||||
while True:
|
||||
if stream is None or not stream.active:
|
||||
now = time.monotonic()
|
||||
if last_reinit_time is None or (now - last_reinit_time) >= REINIT_RETRY_INTERVAL:
|
||||
last_reinit_time = now
|
||||
try:
|
||||
stream = self._reinit_stream(sd, stream)
|
||||
except Exception:
|
||||
stream = None
|
||||
cloudlog.exception("soundd failed to open stream")
|
||||
|
||||
sm.update(0)
|
||||
|
||||
self.load_param()
|
||||
|
||||
# freeze volume during alerts to avoid mic feedback increasing volume
|
||||
if sm.updated['soundPressure']:
|
||||
self.update_volume(bool(sm.valid['soundPressure']), float(sm["soundPressure"].soundPressureWeightedDb))
|
||||
self.spl_filter_weighted.update(sm["soundPressure"].soundPressureWeightedDb)
|
||||
if self.current_alert == AudibleAlert.none:
|
||||
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
|
||||
|
||||
self.get_audible_alert(sm)
|
||||
|
||||
@@ -291,10 +211,8 @@ class Soundd(QuietMode):
|
||||
self.current_volume = max(self.current_volume, ramp_vol)
|
||||
|
||||
rk.keep_time()
|
||||
finally:
|
||||
if stream is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
stream.close()
|
||||
|
||||
assert stream.active
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.connect_phone import ConnectPhoneLayout
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.connect_phone import write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp, simple_button_item_sp, toggle_item_sp
|
||||
from openpilot.system.ui.widgets import DialogResult, Widget
|
||||
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
|
||||
from openpilot.system.ui.widgets.list_view import ITEM_TEXT_FONT_SIZE
|
||||
from openpilot.system.ui.widgets.scroller_tici import Scroller
|
||||
|
||||
POLL_INTERVAL = 1.0
|
||||
NAME_MAX_WIDTH = 1000 # px at the list font: leaves room for REMOVE in the settings panel
|
||||
|
||||
|
||||
def _fit_name(name: str) -> str:
|
||||
# a phone name is up to 80 bytes; list titles are single line and never elided by stock
|
||||
font = gui_app.font(FontWeight.NORMAL)
|
||||
if measure_text_cached(font, name, ITEM_TEXT_FONT_SIZE).x <= NAME_MAX_WIDTH:
|
||||
return name
|
||||
while name and measure_text_cached(font, name + "...", ITEM_TEXT_FONT_SIZE).x > NAME_MAX_WIDTH:
|
||||
name = name[:-1]
|
||||
return name.rstrip() + "..."
|
||||
|
||||
|
||||
class BluetoothLayout(Widget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = Params()
|
||||
|
||||
self._bluetooth_toggle = toggle_item_sp(
|
||||
title=lambda: tr("Bluetooth"),
|
||||
description=lambda: tr("Allow phones to connect to this device over Bluetooth."),
|
||||
param="BluetoothAllowed",
|
||||
)
|
||||
self._connect_phone_button = simple_button_item_sp(
|
||||
button_text=lambda: tr("Connect phone"),
|
||||
callback=lambda: gui_app.push_widget(ConnectPhoneLayout()),
|
||||
enabled=lambda: self._bluetooth_toggle.action_item.get_state(),
|
||||
)
|
||||
|
||||
self._phone_items = []
|
||||
self._grants: list[dict] | None = None
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
self._scroller = Scroller([self._bluetooth_toggle, self._connect_phone_button], line_separator=True, spacing=0)
|
||||
|
||||
def _bluetooth_on(self) -> bool:
|
||||
return self._bluetooth_toggle.action_item.get_state()
|
||||
|
||||
def _update_state(self):
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll < POLL_INTERVAL:
|
||||
return
|
||||
self._last_poll = now
|
||||
phones = grants.load(self._params)
|
||||
if phones != self._grants:
|
||||
self._grants = phones
|
||||
self._rebuild_phone_items()
|
||||
|
||||
def _rebuild_phone_items(self):
|
||||
for item in self._phone_items:
|
||||
self._scroller._items.remove(item)
|
||||
self._phone_items = [self._phone_item(phone) for phone in self._grants or []]
|
||||
for item in self._phone_items:
|
||||
item.set_visible(self._bluetooth_on)
|
||||
self._scroller.add_widget(item)
|
||||
|
||||
def _phone_item(self, phone: dict):
|
||||
spki, name = phone["spki"], _fit_name(phone["name"])
|
||||
return button_item_sp(title=name, button_text=lambda: tr("REMOVE"), callback=lambda: self._remove(spki, name))
|
||||
|
||||
def _remove(self, spki: str, name: str):
|
||||
def done(result: DialogResult):
|
||||
if result == DialogResult.CONFIRM:
|
||||
write_request(self._params, "remove", phone=spki)
|
||||
gui_app.push_widget(ConfirmDialog(tr("Remove \"{}\"?").format(name), tr("Remove"), tr("Cancel"), callback=done))
|
||||
|
||||
def _render(self, rect):
|
||||
self._scroller.render(rect)
|
||||
@@ -1,205 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import math
|
||||
import time
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.selfdrive.ui.ui_state import device
|
||||
from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog
|
||||
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, display_name, format_code, read_window, write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr, tr_noop
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.lib.wrap_text import wrap_text
|
||||
from openpilot.system.ui.widgets import DialogResult
|
||||
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
|
||||
|
||||
POLL_INTERVAL = 0.25
|
||||
START_TIMEOUT = 15
|
||||
STALE_SECONDS = 3
|
||||
CLOSE_REASON_MESSAGES = {
|
||||
"granted": tr_noop("Phone connected."),
|
||||
"denied": tr_noop("Phone not connected."),
|
||||
"no_answer": tr_noop("Phone not connected: Allow was not tapped in time."),
|
||||
"phone_left": tr_noop("Phone not connected: the phone disconnected."),
|
||||
"wrong_codes": tr_noop("Phone not connected: too many wrong codes. Try again."),
|
||||
"limit": tr_noop("Phone not connected: 8 phones are already connected. Remove one first."),
|
||||
"timeout": tr_noop("The connect window timed out. Try again."),
|
||||
"bluetooth_off": tr_noop("Bluetooth is off. Turn Bluetooth on to connect a phone."),
|
||||
"no_key": tr_noop("The device key is unavailable. Reboot and try again."),
|
||||
}
|
||||
|
||||
|
||||
class ConnectPhoneLayout(PairingDialog):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = Params()
|
||||
self._name = display_name(self._params)
|
||||
self._close_btn.set_click_callback(self._close_screen)
|
||||
self._started = False
|
||||
self._closed = False
|
||||
self._seq = 0
|
||||
self._opened_at = 0.0
|
||||
self._matched_at = 0.0
|
||||
self._window: dict | None = None
|
||||
self._last_poll = float("-inf")
|
||||
self._qr_source = ""
|
||||
self._check_dialog: ConfirmDialog | None = None
|
||||
self._check_shown_for: float | None = None
|
||||
|
||||
def show_event(self):
|
||||
super().show_event()
|
||||
device.set_override_interactive_timeout(WINDOW_SECONDS + 10)
|
||||
# a tick, not _update_state: it has to keep polling while the Allow dialog is on top
|
||||
gui_app.add_nav_stack_tick(self._tick)
|
||||
if not self._started:
|
||||
self._started = True
|
||||
self._seq = write_request(self._params, "open")
|
||||
self._opened_at = time.monotonic()
|
||||
|
||||
def hide_event(self):
|
||||
super().hide_event()
|
||||
gui_app.remove_nav_stack_tick(self._tick)
|
||||
device.set_override_interactive_timeout(None)
|
||||
if self._seq and not self._closed:
|
||||
write_request(self._params, "cancel")
|
||||
self._closed = True
|
||||
|
||||
def _update_state(self):
|
||||
pass # stock closes itself once the device is paired to comma connect
|
||||
|
||||
def _tick(self):
|
||||
if self._closed:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll >= POLL_INTERVAL:
|
||||
self._last_poll = now
|
||||
window = read_window(self._params)
|
||||
if window and window.get("seq") == self._seq:
|
||||
self._window = window
|
||||
self._matched_at = now
|
||||
if window.get("state") == "closed":
|
||||
self._on_closed(window.get("reason", ""))
|
||||
return
|
||||
self._sync_check_dialog(window.get("prompt") or {})
|
||||
|
||||
if self._window is not None and self._window.get("state") == "open":
|
||||
if not self._window.get("held") and now >= self._window.get("deadline", 0.0):
|
||||
self._on_closed("timeout")
|
||||
elif self._matched_at and now - self._matched_at > STALE_SECONDS:
|
||||
self._finish(None)
|
||||
elif now - self._opened_at > START_TIMEOUT:
|
||||
write_request(self._params, "cancel")
|
||||
self._finish(tr("Bluetooth did not start"))
|
||||
|
||||
def _sync_check_dialog(self, prompt: dict):
|
||||
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
|
||||
self._check_shown_for = prompt.get("until")
|
||||
text = tr("Code {}\nIs the same code on your phone?").format(prompt.get("check", ""))
|
||||
self._check_dialog = ConfirmDialog(text, tr("Allow"), tr("Deny"), callback=self._answer)
|
||||
gui_app.push_widget(self._check_dialog)
|
||||
elif prompt.get("step") != "allow" and self._check_dialog is not None:
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
self._check_dialog = None
|
||||
|
||||
def _answer(self, result: DialogResult):
|
||||
self._check_dialog = None
|
||||
write_request(self._params, "allow" if result == DialogResult.CONFIRM else "deny")
|
||||
|
||||
def _on_closed(self, reason: str):
|
||||
message = CLOSE_REASON_MESSAGES.get(reason)
|
||||
self._finish(tr(message) if message else None)
|
||||
|
||||
def _finish(self, message: str | None):
|
||||
self._closed = True
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
self._close_screen()
|
||||
if message:
|
||||
gui_app.push_widget(ConfirmDialog(message, tr("OK"), cancel_text=""))
|
||||
|
||||
def _close_screen(self):
|
||||
if gui_app.get_active_widget() is self:
|
||||
gui_app.pop_widget()
|
||||
|
||||
def _get_pairing_url(self) -> str:
|
||||
return self._qr_source
|
||||
|
||||
def _check_qr_refresh(self):
|
||||
qr = (self._window or {}).get("qr", "") if self._is_open() else ""
|
||||
if qr and qr != self._qr_source:
|
||||
self._qr_source = qr
|
||||
self._generate_qr_code()
|
||||
|
||||
def _is_open(self) -> bool:
|
||||
return self._window is not None and self._window.get("state") == "open" and not self._window.get("held")
|
||||
|
||||
def _render(self, rect: rl.Rectangle) -> int:
|
||||
# copied from PairingDialog._render: stock hardcodes its title and steps there
|
||||
rl.clear_background(rl.Color(224, 224, 224, 255))
|
||||
self._check_qr_refresh()
|
||||
|
||||
margin = 70
|
||||
content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin)
|
||||
y = content_rect.y
|
||||
close_size = 80
|
||||
pad = 20
|
||||
self._close_btn.render(rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2))
|
||||
y += close_size + 40
|
||||
|
||||
title_font = gui_app.font(FontWeight.NORMAL)
|
||||
left_width = int(content_rect.width * 0.5 - 15)
|
||||
title_wrapped = wrap_text(title_font, tr("Connect a phone to {}").format(self._name), 75, left_width)
|
||||
rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK)
|
||||
y += len(title_wrapped) * 75 + 60
|
||||
|
||||
remaining_height = content_rect.height - (y - content_rect.y)
|
||||
right_width = content_rect.width // 2 - 20
|
||||
self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height))
|
||||
|
||||
qr_size = min(right_width, content_rect.height) - 40
|
||||
qr_rect = rl.Rectangle(content_rect.x + left_width + 40 + (right_width - qr_size) // 2, content_rect.y, qr_size, qr_size)
|
||||
if self._is_open():
|
||||
self._render_qr_code(qr_rect)
|
||||
else:
|
||||
text = tr("Connecting phone") if self._window is not None and self._window.get("held") else tr("Starting Bluetooth")
|
||||
rl.draw_rectangle_rounded(qr_rect, 0.1, 20, rl.Color(240, 240, 240, 255))
|
||||
font = gui_app.font(FontWeight.BOLD)
|
||||
size = measure_text_cached(font, text, 47)
|
||||
rl.draw_text_ex(font, text, rl.Vector2(qr_rect.x + (qr_rect.width - size.x) / 2, qr_rect.y + (qr_rect.height - size.y) / 2), 47, 0,
|
||||
rl.BLACK)
|
||||
return -1
|
||||
|
||||
def _render_instructions(self, rect: rl.Rectangle) -> None:
|
||||
window = self._window if self._is_open() else None
|
||||
instructions = [
|
||||
tr("Open the sunnylink app and tap Connect phone"),
|
||||
tr("Scan the QR code on the right, or type {}").format(format_code(int(window["code"]))) if window else tr("Scan the QR code on the right"),
|
||||
tr("Check that both screens show the same code, then tap Allow"),
|
||||
]
|
||||
font = gui_app.font(FontWeight.BOLD)
|
||||
y = rect.y
|
||||
for i, text in enumerate(instructions):
|
||||
circle_radius = 25
|
||||
circle_x = rect.x + circle_radius + 15
|
||||
text_x = rect.x + circle_radius * 2 + 40
|
||||
wrapped = wrap_text(font, text, 47, int(rect.width - (circle_radius * 2 + 40)))
|
||||
text_height = len(wrapped) * 47
|
||||
circle_y = y + text_height // 2
|
||||
rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255))
|
||||
number = str(i + 1)
|
||||
number_size = measure_text_cached(font, number, 30)
|
||||
rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE)
|
||||
rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK)
|
||||
y += text_height + 50
|
||||
|
||||
if window:
|
||||
remaining = max(0, math.ceil(window.get("deadline", 0.0) - time.monotonic()))
|
||||
rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), tr("Time left {}:{:02d}").format(remaining // 60, remaining % 60),
|
||||
rl.Vector2(rect.x, y), 47, 0.0, rl.Color(70, 70, 70, 255))
|
||||
@@ -149,8 +149,7 @@ class DeviceLayoutSP(DeviceLayout):
|
||||
def _do_reset(result: int):
|
||||
if result == DialogResult.CONFIRM:
|
||||
for _key in ui_state.params.all_keys():
|
||||
if not _key.startswith("SunnylinkLocal"):
|
||||
ui_state.params.remove(_key)
|
||||
ui_state.params.remove(_key)
|
||||
HARDWARE.reboot()
|
||||
|
||||
def _second_confirm(result: int):
|
||||
|
||||
@@ -11,7 +11,6 @@ import raylib_nb as rl
|
||||
from openpilot.selfdrive.ui.layouts.settings import settings as OP
|
||||
from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout
|
||||
from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.bluetooth import BluetoothLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise import CruiseLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.developer import DeveloperLayoutSP
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.device import DeviceLayoutSP
|
||||
@@ -51,7 +50,6 @@ PanelType = IntEnum(
|
||||
"NAVIGATION",
|
||||
"TRIPS",
|
||||
"VEHICLE",
|
||||
"BLUETOOTH",
|
||||
],
|
||||
start=0,
|
||||
)
|
||||
@@ -114,7 +112,6 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
self._panels = {
|
||||
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
|
||||
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
|
||||
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
|
||||
PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
|
||||
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
|
||||
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
|
||||
|
||||
@@ -7,7 +7,7 @@ See the LICENSE.md file in the root directory for more details.
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp
|
||||
from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR
|
||||
|
||||
|
||||
@@ -16,9 +16,16 @@ class HyundaiSettings(BrandSettings):
|
||||
super().__init__()
|
||||
self.alpha_long_available = False
|
||||
|
||||
self.longitudinal_tuning_item = toggle_item_sp(tr("Custom Longitudinal Tuning"), "", param="HyundaiLongitudinalTuning")
|
||||
tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")]
|
||||
self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts,
|
||||
button_width=300, callback=self._on_tuning_selected,
|
||||
param="HyundaiLongitudinalTuning", inline=False)
|
||||
self.items = [self.longitudinal_tuning_item]
|
||||
|
||||
@staticmethod
|
||||
def _on_tuning_selected(index):
|
||||
ui_state.params.put("HyundaiLongitudinalTuning", index)
|
||||
|
||||
def update_settings(self):
|
||||
self.alpha_long_available = False
|
||||
bundle = ui_state.params.get("CarPlatformBundle")
|
||||
@@ -28,14 +35,25 @@ class HyundaiSettings(BrandSettings):
|
||||
elif ui_state.CP is not None:
|
||||
self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable
|
||||
|
||||
tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0")
|
||||
long_enabled = ui_state.has_longitudinal_control
|
||||
desc = tr("Accelerates and brakes the way your car's own cruise control does.")
|
||||
if not ui_state.is_offroad():
|
||||
desc = tr("This feature is unavailable while the car is onroad.")
|
||||
elif not long_enabled:
|
||||
desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
|
||||
|
||||
self.longitudinal_tuning_item.action_item.set_enabled(ui_state.is_offroad() and long_enabled)
|
||||
self.longitudinal_tuning_item.set_description(desc)
|
||||
long_tuning_descs = [
|
||||
tr("Your vehicle will use the Default longitudinal tuning."),
|
||||
tr("Your vehicle will use the Dynamic longitudinal tuning."),
|
||||
tr("Your vehicle will use the Predictive longitudinal tuning."),
|
||||
]
|
||||
long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0]
|
||||
|
||||
longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled
|
||||
if longitudinal_tuning_disabled:
|
||||
if not ui_state.is_offroad():
|
||||
long_tuning_desc = tr("This feature is unavailable while the car is onroad.")
|
||||
elif not long_enabled:
|
||||
long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
|
||||
|
||||
self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled)
|
||||
self.longitudinal_tuning_item.set_description(long_tuning_desc)
|
||||
self.longitudinal_tuning_item.show_description(True)
|
||||
self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param)
|
||||
self.longitudinal_tuning_item.set_visible(self.alpha_long_available)
|
||||
|
||||
@@ -11,7 +11,6 @@ import time
|
||||
from dataclasses import dataclass
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID
|
||||
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr_noop
|
||||
|
||||
@@ -24,11 +23,6 @@ HOME_BTN = rl.Rectangle(60, 860, 180, 180)
|
||||
|
||||
CHESTNUT_ICON_WIDTH = 180
|
||||
CHESTNUT_ICON_HEIGHT = 133
|
||||
BT_ICON_SIZE = 30
|
||||
BT_ICON_X = 250 # right of the signal dots, clear of the mic indicator
|
||||
BT_ICON_Y = 195
|
||||
BT_POLL_SECONDS = 1.0
|
||||
BT_WAITING_OPACITY = 0.35
|
||||
|
||||
|
||||
# Color scheme
|
||||
@@ -68,19 +62,6 @@ class SidebarSP:
|
||||
self._chestnut_green_img = gui_app.texture("icons_mici/chestnut_green.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_default_img = gui_app.texture("icons_mici/chestnut.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_orange_img = gui_app.texture("icons_mici/chestnut_orange.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._bt_img = gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", BT_ICON_SIZE, BT_ICON_SIZE)
|
||||
self._bt_state = "hidden"
|
||||
self._bt_polled_at = float("-inf")
|
||||
|
||||
def _draw_bluetooth_indicator(self, rect: rl.Rectangle):
|
||||
now = time.monotonic()
|
||||
if now - self._bt_polled_at >= BT_POLL_SECONDS:
|
||||
self._bt_polled_at = now
|
||||
self._bt_state = phone_indicator(read_status(ui_state.params))
|
||||
if self._bt_state == "hidden":
|
||||
return
|
||||
alpha = 255 if self._bt_state == "connected" else int(255 * BT_WAITING_OPACITY)
|
||||
rl.draw_texture_ex(self._bt_img, rl.Vector2(rect.x + BT_ICON_X, rect.y + BT_ICON_Y), 0.0, 1.0, rl.Color(255, 255, 255, alpha))
|
||||
|
||||
def _update_sunnylink_status(self):
|
||||
if not ui_state.params.get_bool("SunnylinkEnabled"):
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import time
|
||||
|
||||
from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigParamControl
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.connect_phone import start_connect_phone
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.connect_phone import display_name, write_request
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
|
||||
POLL_SECONDS = 1.0
|
||||
|
||||
|
||||
def _phone_count(n: int) -> str:
|
||||
return tr("none connected") if n == 0 else tr("{} connected").format(n)
|
||||
|
||||
|
||||
class BluetoothLayoutMici(NavScroller):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self._bluetooth_on = ui_state.params.get_bool("BluetoothAllowed")
|
||||
|
||||
def bluetooth_callback(checked: bool):
|
||||
self._bluetooth_on = checked
|
||||
|
||||
self._bluetooth_toggle = BigParamControl(tr("bluetooth"), "BluetoothAllowed", toggle_callback=bluetooth_callback)
|
||||
|
||||
self._connect_phone_btn = BigButton(tr("connect phone"), display_name(ui_state.params))
|
||||
self._connect_phone_btn.set_click_callback(start_connect_phone)
|
||||
self._connect_phone_btn.set_enabled(lambda: self._bluetooth_on)
|
||||
|
||||
self._phones_page = ConnectedPhonesMici()
|
||||
self._phones_btn = BigButton(tr("phones"), "")
|
||||
self._phones_btn.set_click_callback(lambda: gui_app.push_widget(self._phones_page))
|
||||
self._phones_btn.set_visible(lambda: self._bluetooth_on)
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
self._scroller.add_widgets([self._bluetooth_toggle, self._connect_phone_btn, self._phones_btn])
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll >= POLL_SECONDS:
|
||||
self._last_poll = now
|
||||
self._phones_btn.set_value(_phone_count(len(grants.load(ui_state.params))))
|
||||
|
||||
|
||||
class ConnectedPhonesMici(NavScroller):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._phone_items: list[BigButton] = []
|
||||
self._grants: list[dict] | None = None
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll < POLL_SECONDS:
|
||||
return
|
||||
self._last_poll = now
|
||||
phones = grants.load(ui_state.params)
|
||||
if phones != self._grants:
|
||||
self._grants = phones
|
||||
for item in self._phone_items:
|
||||
self._scroller._items.remove(item)
|
||||
self._phone_items = [self._phone_item(phone) for phone in phones] or [BigButton(tr("no phones connected yet"), "")]
|
||||
self._scroller.add_widgets(self._phone_items)
|
||||
|
||||
def _phone_item(self, phone: dict) -> BigButton:
|
||||
spki = phone["spki"]
|
||||
item = BigButton(phone["name"], tr("remove"), scroll=True)
|
||||
item.set_click_callback(lambda: self._remove(spki))
|
||||
return item
|
||||
|
||||
def _remove(self, spki: str) -> None:
|
||||
icon = gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64)
|
||||
gui_app.push_widget(BigConfirmationDialog(tr("slide to remove"), icon, lambda: write_request(ui_state.params, "remove", phone=spki), red=True))
|
||||
@@ -1,202 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import time
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.common.qrcode import make_texture
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton, BigDialog
|
||||
from openpilot.selfdrive.ui.ui_state import device, ui_state
|
||||
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, format_code, read_window, write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.mici_setup import GreyBigButton
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.system.ui.widgets.nav_widget import NavWidget
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
|
||||
POLL_SECONDS = 0.25
|
||||
START_TIMEOUT = 15 # seconds from open to the first window for this request
|
||||
LOST_SECONDS = 3 # the daemon restarted mid-window and no longer reports our seq
|
||||
INTERACTIVE_TIMEOUT = WINDOW_SECONDS + 10 # the offroad idle timeout would pop the screen mid-window
|
||||
|
||||
|
||||
def _closed_message(reason: str) -> str | None:
|
||||
messages = {
|
||||
"granted": tr("phone connected"),
|
||||
"denied": tr("phone not connected"),
|
||||
"no_answer": tr("allow not tapped in time"),
|
||||
"phone_left": tr("phone disconnected"),
|
||||
"wrong_codes": tr("too many wrong codes"),
|
||||
"limit": tr("8 phones already connected"),
|
||||
"timeout": tr("connect timed out"),
|
||||
"bluetooth_off": tr("turn on bluetooth"),
|
||||
"no_key": tr("device key unavailable"),
|
||||
}
|
||||
return messages.get(reason)
|
||||
|
||||
|
||||
def start_connect_phone() -> None:
|
||||
gui_app.push_widget(ConnectPhoneDialog())
|
||||
|
||||
|
||||
class ConnectPhoneDialog(NavWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = ui_state.params
|
||||
self._seq = write_request(self._params, "open")
|
||||
self._opened_at = time.monotonic()
|
||||
self._next_poll = 0.0
|
||||
self._was_open = False
|
||||
self._lost_since: float | None = None
|
||||
self._window: dict | None = None
|
||||
self._closing = False
|
||||
self._check_shown_for: float | None = None
|
||||
self._qr_source = ""
|
||||
self._qr_texture: rl.Texture | None = None
|
||||
|
||||
self._title = UnifiedLabel(tr("connect phone"), font_size=48, font_weight=FontWeight.BOLD,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=0.8)
|
||||
self._status = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.65)))
|
||||
self._code = UnifiedLabel("", font_size=48, font_weight=FontWeight.BOLD,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)))
|
||||
|
||||
self.set_back_callback(self._cancel)
|
||||
|
||||
def show_event(self):
|
||||
super().show_event()
|
||||
device.set_override_interactive_timeout(INTERACTIVE_TIMEOUT)
|
||||
|
||||
def hide_event(self):
|
||||
super().hide_event()
|
||||
device.set_override_interactive_timeout(None)
|
||||
if not self._closing:
|
||||
self._cancel()
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
if self._closing:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now < self._next_poll:
|
||||
return
|
||||
self._next_poll = now + POLL_SECONDS
|
||||
|
||||
window = read_window(self._params)
|
||||
# the request seq guards against a window left over from an earlier open
|
||||
if window is None or window.get("seq") != self._seq:
|
||||
self._window = None
|
||||
if self._was_open:
|
||||
# a daemon restart writes seq 0 and never reports our window again
|
||||
if self._lost_since is None:
|
||||
self._lost_since = now
|
||||
if now - self._lost_since > LOST_SECONDS:
|
||||
self._finish(None)
|
||||
elif now - self._opened_at > START_TIMEOUT:
|
||||
self._cancel()
|
||||
self._finish(tr("bluetooth did not start"))
|
||||
return
|
||||
self._lost_since = None
|
||||
self._window = window
|
||||
prompt = window.get("prompt") or {}
|
||||
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
|
||||
self._check_shown_for = prompt.get("until")
|
||||
gui_app.push_widget(ConnectPhoneCheckDialog(prompt.get("check", ""), self._params))
|
||||
if window.get("state") == "closed":
|
||||
self._finish(_closed_message(window.get("reason", "")))
|
||||
elif window.get("state") == "open":
|
||||
self._was_open = True
|
||||
if not window.get("held") and now >= window["deadline"]:
|
||||
self._finish(_closed_message("timeout"))
|
||||
|
||||
def _cancel(self) -> None:
|
||||
if not self._closing:
|
||||
self._closing = True
|
||||
write_request(self._params, "cancel")
|
||||
|
||||
def _finish(self, message: str | None) -> None:
|
||||
self._closing = True
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
if message is None:
|
||||
self.dismiss(lambda: None)
|
||||
else:
|
||||
self.dismiss(lambda: gui_app.push_widget(BigDialog(message, "")))
|
||||
|
||||
def _render(self, _):
|
||||
window = self._window
|
||||
held = window is not None and window.get("held", False)
|
||||
show_code = window is not None and window.get("state") == "open" and not held
|
||||
|
||||
if show_code:
|
||||
if window["qr"] != self._qr_source:
|
||||
self._load_qr(window["qr"])
|
||||
self._draw_qr()
|
||||
|
||||
label_x = self._rect.x + 8 + self._rect.height + 24 if show_code else self._rect.x + 20
|
||||
max_width = int(self._rect.x + self._rect.width - label_x)
|
||||
y = self._rect.y + 16
|
||||
self._title.set_text(tr("scan or type") if show_code else tr("connect phone"))
|
||||
self._title.set_max_width(max_width)
|
||||
self._title.set_position(label_x, y)
|
||||
self._title.render()
|
||||
y += self._title.get_content_height(max_width) + 16
|
||||
|
||||
if show_code:
|
||||
remaining = max(0, int(window["deadline"] - time.monotonic()))
|
||||
self._code.set_text(format_code(int(window["code"])))
|
||||
self._code.set_max_width(max_width)
|
||||
self._code.set_position(label_x, y)
|
||||
self._code.render()
|
||||
y += self._code.get_content_height(max_width) + 12
|
||||
self._status.set_text(f"{tr('expires in')} {remaining // 60}:{remaining % 60:02d}")
|
||||
elif held:
|
||||
self._status.set_text(tr("connecting phone"))
|
||||
else:
|
||||
self._status.set_text("" if self._closing else tr("starting bluetooth"))
|
||||
self._status._shimmer = not show_code and not self._closing
|
||||
self._status.set_max_width(max_width)
|
||||
self._status.set_position(label_x, y)
|
||||
self._status.render()
|
||||
|
||||
def _load_qr(self, text: str) -> None:
|
||||
self._unload_qr()
|
||||
self._qr_source = text
|
||||
try:
|
||||
self._qr_texture = make_texture(text, inverted=True)
|
||||
except Exception:
|
||||
cloudlog.exception("connect phone QR generation failed")
|
||||
self._qr_texture = None
|
||||
|
||||
def _draw_qr(self) -> None:
|
||||
if self._qr_texture is None:
|
||||
return
|
||||
scale = self._rect.height / self._qr_texture.height
|
||||
rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x + 8), round(self._rect.y)), 0.0, scale, rl.WHITE)
|
||||
|
||||
def _unload_qr(self) -> None:
|
||||
if self._qr_texture and self._qr_texture.id != 0:
|
||||
rl.unload_texture(self._qr_texture)
|
||||
self._qr_texture = None
|
||||
|
||||
def __del__(self):
|
||||
self._unload_qr()
|
||||
|
||||
|
||||
class ConnectPhoneCheckDialog(NavScroller):
|
||||
def __init__(self, check: str, params):
|
||||
super().__init__()
|
||||
self._params = params
|
||||
allow = BigConfirmationCircleButton(tr("allow\nthis phone"), gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64),
|
||||
lambda: self._answer("allow"))
|
||||
deny = BigConfirmationCircleButton(tr("deny"), gui_app.texture("icons_mici/setup/cancel.png", 64, 64), lambda: self._answer("deny"))
|
||||
self._scroller.add_widgets([GreyBigButton(check, tr("same code on your phone?"), gui_app.texture("icons_mici/setup/green_info.png", 64, 64)),
|
||||
allow, deny])
|
||||
|
||||
def _answer(self, action: str) -> None:
|
||||
self.dismiss(lambda: write_request(self._params, action))
|
||||
@@ -5,38 +5,19 @@ This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
|
||||
from openpilot.system.ui.lib.application import FontWeight
|
||||
from openpilot.system.ui.widgets.icon_widget import IconWidget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
BT_POLL_SECONDS = 1.0
|
||||
BT_WAITING_OPACITY = 0.35
|
||||
|
||||
|
||||
class MiciHomeLayoutSP(MiciHomeLayout):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._openpilot_label = UnifiedLabel("sunnypilot", font_size=88, font_weight=FontWeight.AUDIOWIDE, max_width=480, wrap_text=False)
|
||||
self._bluetooth_icon = IconWidget("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", (40, 40))
|
||||
self._bluetooth_icon.set_visible(False)
|
||||
self._bt_polled_at = float("-inf")
|
||||
self._status_bar_layout.add_widget(self._bluetooth_icon)
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._bt_polled_at >= BT_POLL_SECONDS:
|
||||
self._bt_polled_at = now
|
||||
state = phone_indicator(read_status(ui_state.params))
|
||||
self._bluetooth_icon.set_visible(state != "hidden")
|
||||
self._bluetooth_icon.set_opacity(1.0 if state == "connected" else BT_WAITING_OPACITY)
|
||||
|
||||
def _set_chestnut_visibility(self):
|
||||
usb_connected = ui_state.usb_connected
|
||||
|
||||
@@ -11,7 +11,6 @@ from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.bluetooth import BluetoothLayoutMici
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
@@ -51,12 +50,6 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
models_btn = SettingsBigButton(tr("models"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_models.png", ICON_SIZE, ICON_SIZE))
|
||||
models_btn.set_click_callback(lambda: gui_app.push_widget(models_panel))
|
||||
|
||||
network_btn = self._scroller._items[1]
|
||||
bluetooth_panel = BluetoothLayoutMici()
|
||||
bluetooth_btn = SettingsBigButton(tr("bluetooth"), "",
|
||||
gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", ICON_SIZE, ICON_SIZE))
|
||||
bluetooth_btn.set_click_callback(lambda: gui_app.push_widget(bluetooth_panel))
|
||||
|
||||
# onroad: enable button sits at the front (left of toggles)
|
||||
self._enable_offroad_btn_onroad = BigCircleButton(self.icon_offroad_enable, red=True)
|
||||
self._enable_offroad_btn_onroad.set_click_callback(lambda: self._handle_always_offroad(True))
|
||||
@@ -75,7 +68,6 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
|
||||
items.insert(1, models_btn)
|
||||
items.insert(5, sunnylink_btn)
|
||||
items.insert(items.index(network_btn) + 1, bluetooth_btn)
|
||||
|
||||
# front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad
|
||||
items.insert(0, self._enable_offroad_btn_onroad)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.robotic_view import RoboticOnroadView
|
||||
|
||||
__all__ = ["RoboticOnroadView"]
|
||||
@@ -1,136 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.onroad.alert_renderer import Alert, get_alert
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import FontWeight, TextAlignment, gui_app
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
|
||||
|
||||
class RoboticAlertOverlay:
|
||||
"""Harmonized alert overlay that keeps robotic expressions visible while preserving safety readability."""
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._prev_alert: Alert | None = None
|
||||
self._alpha_filter = FirstOrderFilter(0.0, 0.06, dt)
|
||||
|
||||
self._text1_label = UnifiedLabel(
|
||||
text="",
|
||||
font_size=44,
|
||||
font_weight=FontWeight.DISPLAY,
|
||||
alignment=TextAlignment.CENTER,
|
||||
line_height=0.9,
|
||||
)
|
||||
self._text2_label = UnifiedLabel(
|
||||
text="",
|
||||
font_size=26,
|
||||
font_weight=FontWeight.MEDIUM,
|
||||
alignment=TextAlignment.CENTER,
|
||||
line_height=0.95,
|
||||
)
|
||||
|
||||
def get_alert(self) -> Alert | None:
|
||||
alert = get_alert(ui_state.sm)
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.onroad_brightness_handle_alerts(ui_state, alert)
|
||||
return alert
|
||||
|
||||
def render(self, rect: rl.Rectangle, alert: Alert | None) -> float:
|
||||
"""Render alert overlay and return current alpha (0..1) so caller can shift face if needed."""
|
||||
alpha = self._alpha_filter.update(1.0 if alert is not None else 0.0)
|
||||
if alert is not None:
|
||||
self._prev_alert = alert
|
||||
elif alpha > 0.02 and self._prev_alert is not None:
|
||||
alert = self._prev_alert
|
||||
else:
|
||||
self._prev_alert = None
|
||||
return 0.0
|
||||
|
||||
is_critical = alert.status == AlertStatus.critical
|
||||
is_prompt = alert.status == AlertStatus.userPrompt
|
||||
|
||||
if is_critical:
|
||||
pulse = 0.65 + 0.35 * (0.5 + 0.5 * math.sin(rl.get_time() * 14.0))
|
||||
# Pulsing red edge frame + bottom dark backing so red eyes + takeover text are unmistakable
|
||||
border_col = rl.Color(255, 25, 35, int(230 * pulse * alpha))
|
||||
rl.draw_rectangle_rounded_lines_ex(
|
||||
rl.Rectangle(rect.x + 3, rect.y + 3, rect.width - 6, rect.height - 6),
|
||||
0.16,
|
||||
12,
|
||||
10.0,
|
||||
border_col,
|
||||
)
|
||||
band_h = 98
|
||||
rl.draw_rectangle_gradient_v(
|
||||
int(rect.x),
|
||||
int(rect.y + rect.height - band_h - 18),
|
||||
int(rect.width),
|
||||
band_h + 18,
|
||||
rl.Color(180, 0, 15, 0),
|
||||
rl.Color(210, 0, 20, int(230 * alpha)),
|
||||
)
|
||||
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 4, band_h, alpha, big=True)
|
||||
elif is_prompt:
|
||||
band_h = 84
|
||||
rl.draw_rectangle_gradient_v(
|
||||
int(rect.x),
|
||||
int(rect.y + rect.height - band_h - 14),
|
||||
int(rect.width),
|
||||
band_h + 14,
|
||||
rl.Color(220, 95, 0, 0),
|
||||
rl.Color(235, 105, 0, int(215 * alpha)),
|
||||
)
|
||||
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 6, band_h, alpha, big=False)
|
||||
else:
|
||||
# Soft / normal alert: compact bottom pill leaving the expressive eyes unobstructed
|
||||
band_h = 66
|
||||
pill = rl.Rectangle(rect.x + 24, rect.y + rect.height - band_h - 8, rect.width - 48, band_h)
|
||||
rl.draw_rectangle_rounded(pill, 0.38, 12, rl.Color(24, 28, 34, int(215 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill, 0.38, 12, 2.0, rl.Color(255, 255, 255, int(45 * alpha)))
|
||||
self._draw_banner_text(rect, alert, pill.y + 6, band_h - 8, alpha, big=False)
|
||||
|
||||
return alpha
|
||||
|
||||
def _draw_banner_text(
|
||||
self,
|
||||
rect: rl.Rectangle,
|
||||
alert: Alert,
|
||||
top_y: float,
|
||||
band_h: float,
|
||||
alpha: float,
|
||||
big: bool,
|
||||
) -> None:
|
||||
text1 = alert.text1.lower()
|
||||
text2 = alert.text2.lower()
|
||||
|
||||
if big:
|
||||
font1 = 42 if len(text1) <= 18 else 34
|
||||
else:
|
||||
font1 = 34 if len(text1) <= 22 else 28
|
||||
|
||||
margin_x = 34
|
||||
w = rect.width - margin_x * 2
|
||||
|
||||
self._text1_label.set_text(text1)
|
||||
self._text1_label.set_font_size(font1)
|
||||
self._text1_label.set_text_color(rl.Color(255, 255, 255, int(245 * alpha)))
|
||||
self._text1_label.render(rl.Rectangle(rect.x + margin_x, top_y, w, band_h))
|
||||
|
||||
if text2:
|
||||
font2 = 24 if len(text2) <= 28 else 20
|
||||
self._text2_label.set_text(text2)
|
||||
self._text2_label.set_font_size(font2)
|
||||
self._text2_label.set_text_color(rl.Color(255, 255, 255, int(195 * alpha)))
|
||||
self._text2_label.render(rl.Rectangle(rect.x + margin_x, top_y + font1 + 2, w, max(24.0, band_h - font1)))
|
||||
@@ -1,993 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import groove_prism_color
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
|
||||
AlertStatus = log.SelfdriveState.AlertStatus
|
||||
EventName = log.OnroadEvent.EventName
|
||||
|
||||
SET_SPEED_NA = 255
|
||||
KM_TO_MILE = 0.621371
|
||||
|
||||
# Thresholds & hold durations (seconds)
|
||||
HARD_DECEL_THRESHOLD = -3.0 # m/s^2 triggers startled star eyes
|
||||
SHARP_ACCEL_THRESHOLD = 2.2 # m/s^2 triggers excited boost eyes
|
||||
STANDSTILL_POUT_DELAY = 8.0 # seconds at standstill before pouting
|
||||
STANDSTILL_SLEEPY_DELAY = 35.0 # seconds at standstill before sleepy
|
||||
MIN_TURN_SPEED_MS = 6.5 # m/s (~15 mph) min speed for passenger centrifugal feel
|
||||
MIN_LAT_ACCEL_MS2 = 1.6
|
||||
FULL_LAT_ACCEL_MS2 = 3.6
|
||||
LAT_JERK_WEIGHT = 0.5
|
||||
LAT_JERK_LOW = 400.0
|
||||
LAT_JERK_HIGH = 900.0
|
||||
SQUISH_ATTACK_RATE = 20.0
|
||||
SQUISH_RELEASE_RATE = 3.3
|
||||
SET_SPEED_SHOW_DURATION = 3.0 # seconds to show speed arc on set-speed change
|
||||
ENGAGE_HAPPY_DURATION = 0.9 # seconds of joyful crescent eyes on engage
|
||||
ENGAGE_SPEED_CONFIRM = 2.0 # seconds of speed readout right after happy engage
|
||||
STARTLED_HOLD_DURATION = 1.5 # seconds to hold star-shock expression
|
||||
BOOST_HOLD_DURATION = 1.2 # seconds to hold sharp-accel boost expression
|
||||
LOVE_HOLD_DURATION = 1.6 # seconds to hold heart/pet expression
|
||||
MANUAL_SPEED_PEEK_DURATION = 4.0 # seconds for swipe-up speed peek
|
||||
|
||||
BLINK_CLOSE_S = 0.070
|
||||
BLINK_HOLD_S = 0.035
|
||||
BLINK_OPEN_S = 0.130
|
||||
BLINK_LID_MIN = 0.08
|
||||
BLINK_LID_MAX = 0.92
|
||||
|
||||
REACTION_DELAY_S = 0.10
|
||||
|
||||
DEBUG_PARAM = "MiciRoboticDebug"
|
||||
|
||||
|
||||
class RoboticMood(Enum):
|
||||
CRITICAL = "critical"
|
||||
DISTRACTED = "distracted"
|
||||
USER_PROMPT = "user_prompt"
|
||||
STARTLED_STARS = "startled_stars"
|
||||
LANE_CHANGE = "lane_change"
|
||||
BLIND_SPOT = "blind_spot"
|
||||
BOOKMARK_LOVE = "bookmark_love"
|
||||
HAPPY_ENGAGE = "happy_engage"
|
||||
BOOST_ACCEL = "boost_accel"
|
||||
TURN_SIGNAL = "turn_signal"
|
||||
SPEED_DISPLAY = "speed_display"
|
||||
POUT_STANDSTILL = "pout_standstill"
|
||||
SLEEPY = "sleepy"
|
||||
SHARP_TURN = "sharp_turn"
|
||||
CURVE_FOCUS = "curve_focus"
|
||||
MUSIC_GROOVE = "music_groove"
|
||||
CRUISING_HAPPY = "cruising_happy"
|
||||
IDLE_CURIOUS = "idle_curious"
|
||||
|
||||
|
||||
class IdleAction(Enum):
|
||||
"""Playful autonomous micro-behaviors during normal cruising & idle driving."""
|
||||
NONE = "none"
|
||||
HAPPY_SQUINT = "happy_squint"
|
||||
CURIOUS_LOOK = "curious_look"
|
||||
CHEEKY_WINK = "cheeky_wink"
|
||||
GROOVE_BOB = "groove_bob"
|
||||
STRETCH = "stretch"
|
||||
SETTLE = "settle"
|
||||
PERK_UP = "perk_up"
|
||||
DAYDREAM = "daydream"
|
||||
DOODLE = "doodle"
|
||||
DOUBLE_BLINK_TILT = "double_blink_tilt"
|
||||
|
||||
|
||||
class GrooveStyle(Enum):
|
||||
"""Music animations. One is picked per segment; the set reads as one character."""
|
||||
HEAD_BOB = "head_bob"
|
||||
SIDE_SWAY = "side_sway"
|
||||
JELLY = "jelly"
|
||||
SNARE_BLINK = "snare_blink"
|
||||
LOOK_AROUND = "look_around"
|
||||
ANTICIPATION_POP = "anticipation_pop"
|
||||
GLOW_PULSE = "glow_pulse"
|
||||
|
||||
|
||||
IDLE_ACTION_DURATION = {
|
||||
IdleAction.HAPPY_SQUINT: 0.9,
|
||||
IdleAction.CURIOUS_LOOK: 1.6,
|
||||
IdleAction.CHEEKY_WINK: 0.6,
|
||||
IdleAction.GROOVE_BOB: 2.0,
|
||||
IdleAction.STRETCH: 1.8,
|
||||
IdleAction.SETTLE: 2.4,
|
||||
IdleAction.PERK_UP: 1.0,
|
||||
IdleAction.DAYDREAM: 3.4,
|
||||
IdleAction.DOODLE: 2.8,
|
||||
IdleAction.DOUBLE_BLINK_TILT: 0.9,
|
||||
}
|
||||
|
||||
IDLE_ACTION_WEIGHTS = {
|
||||
IdleAction.HAPPY_SQUINT: 1.0,
|
||||
IdleAction.CURIOUS_LOOK: 1.2,
|
||||
IdleAction.CHEEKY_WINK: 0.7,
|
||||
IdleAction.GROOVE_BOB: 0.6,
|
||||
IdleAction.STRETCH: 0.8,
|
||||
IdleAction.SETTLE: 0.7,
|
||||
IdleAction.PERK_UP: 0.8,
|
||||
IdleAction.DAYDREAM: 0.9,
|
||||
IdleAction.DOODLE: 0.8,
|
||||
IdleAction.DOUBLE_BLINK_TILT: 1.1,
|
||||
}
|
||||
|
||||
GROOVE_WEIGHTS = {
|
||||
GrooveStyle.HEAD_BOB: 1.2,
|
||||
GrooveStyle.SIDE_SWAY: 1.1,
|
||||
GrooveStyle.JELLY: 1.0,
|
||||
GrooveStyle.SNARE_BLINK: 0.8,
|
||||
GrooveStyle.LOOK_AROUND: 0.9,
|
||||
GrooveStyle.ANTICIPATION_POP: 0.7,
|
||||
GrooveStyle.GLOW_PULSE: 0.6,
|
||||
}
|
||||
|
||||
|
||||
def _ease_in_quad(p: float) -> float:
|
||||
p = max(0.0, min(1.0, p))
|
||||
return p * p
|
||||
|
||||
|
||||
def _ease_out_back(p: float, s: float = 1.35) -> float:
|
||||
p = max(0.0, min(1.0, p)) - 1.0
|
||||
return p * p * ((s + 1.0) * p + s) + 1.0
|
||||
|
||||
|
||||
def _smoothstep(edge0: float, edge1: float, x: float) -> float:
|
||||
if edge1 <= edge0:
|
||||
return 1.0 if x >= edge1 else 0.0
|
||||
p = max(0.0, min(1.0, (x - edge0) / (edge1 - edge0)))
|
||||
return p * p * (3.0 - 2.0 * p)
|
||||
|
||||
|
||||
class MotionScheduler:
|
||||
"""Weighted random picker with per-clip cooldown and no immediate repeats.
|
||||
|
||||
Shared by groove and idle so the two systems cannot drift apart in behaviour. The old
|
||||
rng.choice() had no memory at all, so the same idle could repeat forever.
|
||||
"""
|
||||
|
||||
def __init__(self, options, rng: random.Random, weights: dict | None = None, cooldown: float = 30.0):
|
||||
self._options = list(options)
|
||||
self._rng = rng
|
||||
self._weights = {o: (weights or {}).get(o, 1.0) for o in self._options}
|
||||
self._cooldown = cooldown
|
||||
self._cooldowns = dict.fromkeys(self._options, -1e9)
|
||||
self._current = None
|
||||
|
||||
@property
|
||||
def current(self):
|
||||
return self._current
|
||||
|
||||
def pick(self, now: float):
|
||||
candidates = [o for o in self._options if o != self._current and now - self._cooldowns[o] >= self._cooldown]
|
||||
if not candidates:
|
||||
candidates = [o for o in self._options if o != self._current] or list(self._options)
|
||||
choice = self._rng.choices(candidates, weights=[self._weights[o] for o in candidates], k=1)[0]
|
||||
self._current = choice
|
||||
self._cooldowns[choice] = now
|
||||
return choice
|
||||
|
||||
|
||||
class _GyroBiasEstimator:
|
||||
"""Tracks the stationary yaw-gyro bias so a DC offset is not read as a permanent corner.
|
||||
|
||||
An uncalibrated bias of 0.03 rad/s at 20 m/s is 0.6 m/s^2 of phantom lateral acceleration,
|
||||
which is a third of the squish deadband.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.bias = 0.0
|
||||
self._seeded = False
|
||||
|
||||
def correct(self, yaw_rate: float, v_ego: float, dt: float) -> float:
|
||||
if v_ego < 0.5:
|
||||
if not self._seeded:
|
||||
self.bias = yaw_rate
|
||||
self._seeded = True
|
||||
elif dt > 0.0:
|
||||
self.bias += (yaw_rate - self.bias) * min(1.0, dt / 2.0)
|
||||
return yaw_rate - self.bias
|
||||
|
||||
|
||||
_GYRO_BIAS = _GyroBiasEstimator()
|
||||
|
||||
|
||||
class EyeGlyph(Enum):
|
||||
ROUND_RECT = "round_rect"
|
||||
STAR = "star"
|
||||
HEART = "heart"
|
||||
CRESCENT = "crescent"
|
||||
ARROW_LEFT = "arrow_left"
|
||||
ARROW_RIGHT = "arrow_right"
|
||||
LASER_ALERT = "laser_alert"
|
||||
SPARKLE_BOOST = "sparkle_boost"
|
||||
|
||||
|
||||
class MouthGlyph(Enum):
|
||||
NONE = "none"
|
||||
SMILE = "smile"
|
||||
BIG_GRIN = "big_grin"
|
||||
FROWN = "frown"
|
||||
SURPRISED = "surprised"
|
||||
|
||||
|
||||
# Dynamic status & mood palette (RGB tuples)
|
||||
PALETTE = {
|
||||
"engaged": (64, 240, 226), # EMO vibrant cyan-emerald
|
||||
"lat_only": (255, 212, 178), # Reference-video warm peach
|
||||
"long_only": (92, 198, 255), # Sky cyan
|
||||
"disengaged": (218, 232, 248), # Soft ice white
|
||||
"override": (255, 196, 68), # Warm amber
|
||||
"boost": (76, 178, 255), # Electric boost blue
|
||||
"prompt": (255, 125, 20), # Vivid orange
|
||||
"critical": (255, 38, 48), # Alert red
|
||||
"love": (255, 112, 168), # Rose pink
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class EyeTarget:
|
||||
width: float = 104.0
|
||||
height: float = 112.0
|
||||
roundness: float = 0.62 # Bubbly chunky squircle
|
||||
top_lid: float = 0.0 # 0..1 fraction covered from top
|
||||
bottom_lid: float = 0.0 # 0..1 fraction covered from bottom
|
||||
top_slant: float = 0.0 # degrees (+ = angry/inward, - = sad/outward)
|
||||
gaze_x: float = 0.0 # px shift (-42..+42)
|
||||
gaze_y: float = 0.0 # px shift (-22..+22)
|
||||
bounce_y: float = 0.0 # vertical expressiveness offset
|
||||
tilt_y: float = 0.0 # vertical asymmetry between left & right eye (playful head tilt)
|
||||
scale_x: float = 1.0 # squash-and-stretch horizontal multiplier
|
||||
scale_y: float = 1.0 # squash-and-stretch vertical multiplier
|
||||
wink_right: bool = False # cute asymmetric wink on bookmark or cheeky idle wink
|
||||
squish_force: float = 0.0 # -1..+1 centrifugal push (-1 left wall, +1 right wall)
|
||||
pitch_offset_y: float = 0.0 # px vertical bob from pitch / pitch-rate (bumps, hills, dive)
|
||||
glyph: EyeGlyph = EyeGlyph.ROUND_RECT
|
||||
mouth: MouthGlyph = MouthGlyph.NONE
|
||||
color: tuple[int, int, int] = PALETTE["engaged"]
|
||||
pulse_speed: float = 0.0 # Hz for alert pulsing
|
||||
blind_spot_side: int = 0 # -1 left, +1 right, 0 none
|
||||
blinker_side: int = 0 # -1 left, +1 right, 0 none
|
||||
show_speed_lines: bool = False
|
||||
show_zzz: bool = False
|
||||
show_hearts: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class DrivingSnapshot:
|
||||
"""Pure-data snapshot of driving signals for deterministic mood evaluation & testing."""
|
||||
started: bool = True
|
||||
engaged: bool = False
|
||||
status: UIStatus = UIStatus.DISENGAGED
|
||||
v_ego: float = 0.0 # m/s
|
||||
a_ego: float = 0.0 # m/s^2
|
||||
standstill: bool = False
|
||||
steering_angle_deg: float = 0.0
|
||||
yaw_rate: float = 0.0 # rad/s (+ = turning left -> centrifugal push right)
|
||||
pitch_rad: float = 0.0 # rad (+ = nose up / hill climb)
|
||||
pitch_rate: float = 0.0 # rad/s (bumps, crests, braking dive)
|
||||
curvature: float = 0.0 # rad/m fallback for centrifugal accel
|
||||
set_speed_kph: float = SET_SPEED_NA
|
||||
is_metric: bool = False
|
||||
left_blinker: bool = False
|
||||
right_blinker: bool = False
|
||||
left_blindspot: bool = False
|
||||
right_blindspot: bool = False
|
||||
pre_lane_change_left: bool = False
|
||||
pre_lane_change_right: bool = False
|
||||
lane_change: bool = False
|
||||
lane_change_blocked: bool = False
|
||||
dm_alert_level: int = 0 # 0=none, 1=warn, 2=critical
|
||||
alert: Alert | None = None
|
||||
music: MusicState | None = None
|
||||
|
||||
|
||||
class RoboticMoodEngine:
|
||||
"""Priority-based EMO-inspired mood & lively autonomous personality state machine."""
|
||||
|
||||
def __init__(self, rng: random.Random | None = None, params=None):
|
||||
self._rng = rng or random.Random()
|
||||
self._params = params
|
||||
self._debug_frame = 0
|
||||
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
|
||||
self.idle_action: IdleAction = IdleAction.NONE
|
||||
self.showing_speed: bool = False
|
||||
self.speed_reason: str = "" # "set_speed", "engage", "peek"
|
||||
self.cruising_smoothly: bool = False
|
||||
|
||||
self._prev_engaged: bool = False
|
||||
self._prev_set_speed: float = SET_SPEED_NA
|
||||
self._standstill_since: float | None = None
|
||||
self._last_lane_dir: int = 0 # -1 left, +1 right
|
||||
|
||||
# Hold / effect timers (monotonic timestamps)
|
||||
self._startled_until: float = 0.0
|
||||
self._boost_until: float = 0.0
|
||||
self._love_until: float = 0.0
|
||||
self._love_wink: bool = False
|
||||
self._happy_engage_until: float = 0.0
|
||||
self._speed_display_until: float = 0.0
|
||||
|
||||
# Blink, gaze, and playful idle personality schedulers
|
||||
now = time.monotonic()
|
||||
self._next_blink_at: float = now + self._rng.uniform(1.8, 3.6)
|
||||
self._blink_start_at: float = now - 999.0
|
||||
self._double_blink_pending: bool = False
|
||||
|
||||
self._next_glance_at: float = now + self._rng.uniform(2.5, 7.0)
|
||||
self._idle_gaze_x: float = 0.0
|
||||
self._idle_gaze_y: float = 0.0
|
||||
self._idle_tilt_y: float = 0.0
|
||||
|
||||
self._next_idle_action_at: float = now + self._rng.uniform(2.2, 3.8)
|
||||
self._idle_action_until: float = 0.0
|
||||
self._idle_action_dir: float = 1.0
|
||||
|
||||
self._idle_scheduler = MotionScheduler(
|
||||
[a for a in IdleAction if a is not IdleAction.NONE], self._rng,
|
||||
weights=IDLE_ACTION_WEIGHTS, cooldown=30.0,
|
||||
)
|
||||
self._groove_scheduler = MotionScheduler(list(GrooveStyle), self._rng, weights=GROOVE_WEIGHTS, cooldown=24.0)
|
||||
self._groove_style: GrooveStyle = GrooveStyle.HEAD_BOB
|
||||
self._groove_switch_at: float = 0.0
|
||||
self._groove_intensity: float = 0.0
|
||||
|
||||
self._prev_update_t: float | None = None
|
||||
self._prev_abs_lat: float = 0.0
|
||||
self._squish_shown: float = 0.0
|
||||
|
||||
self._love_from: float = 0.0
|
||||
|
||||
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._love_from = t + REACTION_DELAY_S
|
||||
self._love_until = self._love_from + LOVE_HOLD_DURATION
|
||||
self._love_wink = wink
|
||||
|
||||
def trigger_speed_peek(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._speed_display_until = max(self._speed_display_until, t + MANUAL_SPEED_PEEK_DURATION)
|
||||
self.speed_reason = "peek"
|
||||
|
||||
def trigger_startled(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
|
||||
|
||||
def trigger_boost(self, now: float | None = None) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
|
||||
|
||||
def _status_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
|
||||
if snap.status == UIStatus.ENGAGED:
|
||||
return PALETTE["engaged"]
|
||||
if snap.status == UIStatus.LAT_ONLY:
|
||||
return PALETTE["lat_only"]
|
||||
if snap.status == UIStatus.LONG_ONLY:
|
||||
return PALETTE["long_only"]
|
||||
if snap.status == UIStatus.OVERRIDE:
|
||||
return PALETTE["override"]
|
||||
return PALETTE["disengaged"]
|
||||
|
||||
def _update_blink_and_personality(self, now: float, sleepy: bool) -> tuple[float, float, float]:
|
||||
"""Returns (blink_closure, squash_x, stretch_y) and advances idle glances & micro-actions."""
|
||||
blink_closure = 0.0
|
||||
squash_x = 1.0
|
||||
stretch_y = 1.0
|
||||
|
||||
close_s = BLINK_CLOSE_S * (2.2 if sleepy else 1.0)
|
||||
hold_s = BLINK_HOLD_S * (2.0 if sleepy else 1.0)
|
||||
open_s = BLINK_OPEN_S * (1.8 if sleepy else 1.0)
|
||||
blink_total = close_s + hold_s + open_s
|
||||
|
||||
elapsed = now - self._blink_start_at
|
||||
if 0.0 <= elapsed <= blink_total:
|
||||
if elapsed <= close_s:
|
||||
blink_closure = _ease_in_quad(elapsed / close_s)
|
||||
squash_x = 1.0 + 0.10 * blink_closure
|
||||
stretch_y = 1.0 - 0.08 * blink_closure
|
||||
elif elapsed <= close_s + hold_s:
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.10
|
||||
stretch_y = 0.92
|
||||
else:
|
||||
open_p = (elapsed - close_s - hold_s) / open_s
|
||||
raw = 1.0 - _ease_out_back(open_p)
|
||||
pop = max(0.0, -raw)
|
||||
blink_closure = max(0.0, raw)
|
||||
squash_x = (1.0 + 0.10 * blink_closure) * (1.0 - 0.06 * pop)
|
||||
stretch_y = (1.0 - 0.08 * blink_closure) * (1.0 + 0.05 * pop)
|
||||
elif now >= self._next_blink_at:
|
||||
self._blink_start_at = now
|
||||
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.25:
|
||||
self._double_blink_pending = True
|
||||
self._next_blink_at = now + blink_total + 0.12
|
||||
else:
|
||||
self._double_blink_pending = False
|
||||
lo, hi = (1.8, 3.6) if sleepy else (2.4, 6.5)
|
||||
self._next_blink_at = now + blink_total + self._rng.uniform(lo, hi)
|
||||
|
||||
if now >= self._next_glance_at:
|
||||
roll = self._rng.random()
|
||||
if roll < 0.34:
|
||||
self._idle_gaze_x = 0.0
|
||||
self._idle_gaze_y = 0.0
|
||||
self._idle_tilt_y = 0.0
|
||||
else:
|
||||
self._idle_gaze_x = self._rng.uniform(-30.0, 30.0)
|
||||
self._idle_gaze_y = self._rng.uniform(-10.0, 8.0)
|
||||
self._idle_tilt_y = self._rng.uniform(-7.0, 7.0)
|
||||
self._next_glance_at = now + self._rng.uniform(2.5, 7.0)
|
||||
|
||||
if now >= self._idle_action_until:
|
||||
self.idle_action = IdleAction.NONE
|
||||
if not sleepy and now >= self._next_idle_action_at:
|
||||
choice = self._idle_scheduler.pick(now)
|
||||
self.idle_action = choice
|
||||
self._idle_action_dir = -1.0 if self._rng.random() < 0.5 else 1.0
|
||||
self._idle_action_until = now + IDLE_ACTION_DURATION[choice]
|
||||
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(6.0, 18.0)
|
||||
|
||||
return blink_closure, squash_x, stretch_y
|
||||
|
||||
def update(self, snap: DrivingSnapshot, now: float | None = None) -> EyeTarget:
|
||||
t = time.monotonic() if now is None else now
|
||||
dt = 0.0 if self._prev_update_t is None else max(0.0, min(0.5, t - self._prev_update_t))
|
||||
self._prev_update_t = t
|
||||
|
||||
# Track standstill duration
|
||||
if snap.standstill or not snap.started:
|
||||
if self._standstill_since is None:
|
||||
self._standstill_since = t
|
||||
else:
|
||||
self._standstill_since = None
|
||||
standstill_dur = (t - self._standstill_since) if self._standstill_since is not None else 0.0
|
||||
|
||||
# Track engagement rising edge
|
||||
if snap.engaged and not self._prev_engaged:
|
||||
self._happy_engage_until = t + ENGAGE_HAPPY_DURATION
|
||||
self._speed_display_until = max(
|
||||
self._speed_display_until,
|
||||
t + ENGAGE_HAPPY_DURATION + ENGAGE_SPEED_CONFIRM,
|
||||
)
|
||||
self.speed_reason = "engage"
|
||||
self._prev_engaged = snap.engaged
|
||||
|
||||
# Track set-speed change while cruise is set
|
||||
cruise_set = 0 < snap.set_speed_kph < SET_SPEED_NA
|
||||
if cruise_set and snap.set_speed_kph != self._prev_set_speed and self._prev_set_speed != SET_SPEED_NA:
|
||||
self._speed_display_until = max(self._speed_display_until, t + SET_SPEED_SHOW_DURATION)
|
||||
self.speed_reason = "set_speed"
|
||||
self._prev_set_speed = snap.set_speed_kph
|
||||
|
||||
# Track startling events & sharp acceleration
|
||||
if snap.a_ego < HARD_DECEL_THRESHOLD or snap.lane_change_blocked:
|
||||
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
|
||||
elif snap.a_ego > SHARP_ACCEL_THRESHOLD and not snap.standstill:
|
||||
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
|
||||
|
||||
# Track lane change direction
|
||||
if snap.pre_lane_change_left:
|
||||
self._last_lane_dir = -1
|
||||
elif snap.pre_lane_change_right:
|
||||
self._last_lane_dir = 1
|
||||
elif not snap.lane_change:
|
||||
self._last_lane_dir = 0
|
||||
|
||||
blinker_side = -1 if snap.left_blinker else (1 if snap.right_blinker else 0)
|
||||
|
||||
bsm_side = 0
|
||||
if snap.left_blindspot and (snap.left_blinker or snap.pre_lane_change_left):
|
||||
bsm_side = -1
|
||||
elif snap.right_blindspot and (snap.right_blinker or snap.pre_lane_change_right):
|
||||
bsm_side = 1
|
||||
elif snap.left_blindspot and not snap.standstill:
|
||||
bsm_side = -1
|
||||
elif snap.right_blindspot and not snap.standstill:
|
||||
bsm_side = 1
|
||||
|
||||
self.cruising_smoothly = snap.engaged and not snap.standstill and abs(snap.a_ego) < 0.8
|
||||
|
||||
# Evaluate mood priority
|
||||
alert = snap.alert
|
||||
alert_status = alert.status if alert is not None else -1
|
||||
alert_type = alert.alert_type if alert is not None else ""
|
||||
is_dm_alert = snap.dm_alert_level >= 1 or "Distracted" in alert_type or "Unresponsive" in alert_type
|
||||
|
||||
self.showing_speed = False
|
||||
|
||||
# Compute pure horizontal centrifugal force (-1 = pushed left, +1 = pushed right).
|
||||
# In openpilot FRD frame, yaw_rate > 0 is a RIGHT turn, which pushes a passenger to the LEFT (-1).
|
||||
# Only triggers on sharper / higher-speed turns (v_ego >= 6.5 m/s and |lat_accel| >= 1.8 m/s^2).
|
||||
effective_yaw = snap.yaw_rate
|
||||
if abs(effective_yaw) < 1e-4 and abs(snap.curvature) > 1e-5:
|
||||
effective_yaw = snap.v_ego * snap.curvature
|
||||
|
||||
squish_force = 0.0
|
||||
target_squish = 0.0
|
||||
jerk = 0.0
|
||||
abs_lat = 0.0
|
||||
if not snap.standstill and snap.v_ego >= MIN_TURN_SPEED_MS:
|
||||
lat_accel = -snap.v_ego * effective_yaw # opposite side of the turn
|
||||
abs_lat = abs(lat_accel)
|
||||
if abs_lat >= MIN_LAT_ACCEL_MS2:
|
||||
base = _smoothstep(MIN_LAT_ACCEL_MS2, FULL_LAT_ACCEL_MS2, abs_lat)
|
||||
if dt > 1e-4:
|
||||
jerk = abs(abs_lat - self._prev_abs_lat) / dt
|
||||
jerk_term = LAT_JERK_WEIGHT * _smoothstep(LAT_JERK_LOW, LAT_JERK_HIGH, jerk)
|
||||
mag = min(1.0, base + jerk_term)
|
||||
target_squish = mag if lat_accel > 0 else -mag
|
||||
self._prev_abs_lat = abs_lat
|
||||
|
||||
delta = target_squish - self._squish_shown
|
||||
if dt <= 0.0:
|
||||
step = abs(delta)
|
||||
elif abs(target_squish) < abs(self._squish_shown):
|
||||
step = SQUISH_RELEASE_RATE * dt
|
||||
else:
|
||||
step = SQUISH_ATTACK_RATE * dt
|
||||
self._squish_shown += max(-step, min(step, delta))
|
||||
squish_force = self._squish_shown
|
||||
|
||||
self._log_squish_debug(snap, abs_lat, jerk, effective_yaw, squish_force)
|
||||
|
||||
if alert is not None and alert_status == AlertStatus.critical:
|
||||
self.mood = RoboticMood.CRITICAL
|
||||
elif is_dm_alert:
|
||||
self.mood = RoboticMood.DISTRACTED
|
||||
elif alert is not None and alert_status == AlertStatus.userPrompt:
|
||||
self.mood = RoboticMood.USER_PROMPT
|
||||
elif t < self._startled_until:
|
||||
self.mood = RoboticMood.STARTLED_STARS
|
||||
elif snap.pre_lane_change_left or snap.pre_lane_change_right or snap.lane_change:
|
||||
self.mood = RoboticMood.LANE_CHANGE
|
||||
elif bsm_side != 0 and blinker_side != 0:
|
||||
self.mood = RoboticMood.BLIND_SPOT
|
||||
elif self._love_from <= t < self._love_until:
|
||||
self.mood = RoboticMood.BOOKMARK_LOVE
|
||||
elif t < self._happy_engage_until:
|
||||
self.mood = RoboticMood.HAPPY_ENGAGE
|
||||
elif t < self._speed_display_until and snap.started:
|
||||
self.mood = RoboticMood.SPEED_DISPLAY
|
||||
self.showing_speed = True
|
||||
elif t < self._boost_until:
|
||||
self.mood = RoboticMood.BOOST_ACCEL
|
||||
elif blinker_side != 0:
|
||||
self.mood = RoboticMood.TURN_SIGNAL
|
||||
elif abs(squish_force) >= 0.35:
|
||||
self.mood = RoboticMood.SHARP_TURN
|
||||
elif abs(squish_force) >= 0.12:
|
||||
self.mood = RoboticMood.CURVE_FOCUS
|
||||
elif snap.started and snap.music is not None and snap.music.is_music and alert is None:
|
||||
self.mood = RoboticMood.MUSIC_GROOVE
|
||||
elif not snap.started or standstill_dur >= STANDSTILL_SLEEPY_DELAY:
|
||||
self.mood = RoboticMood.SLEEPY
|
||||
elif standstill_dur >= STANDSTILL_POUT_DELAY:
|
||||
self.mood = RoboticMood.POUT_STANDSTILL
|
||||
elif snap.engaged:
|
||||
self.mood = RoboticMood.CRUISING_HAPPY
|
||||
else:
|
||||
self.mood = RoboticMood.IDLE_CURIOUS
|
||||
|
||||
base_color = self._status_color(snap)
|
||||
blink, squash_x, stretch_y = self._update_blink_and_personality(t, sleepy=(self.mood == RoboticMood.SLEEPY))
|
||||
|
||||
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
|
||||
bus_phase = t * 2.2 * energy
|
||||
breath = math.sin(bus_phase) * 0.72 + math.sin(bus_phase * 0.5 + 0.9) * 0.28
|
||||
breathe_y = breath * 6.5
|
||||
breathe_scale = 1.0 + 0.032 * breath
|
||||
micro_drift_x = math.sin(bus_phase * 0.33) * 5.0
|
||||
|
||||
# Steering-coupled gaze (clamped to [-40, +40])
|
||||
steer_gaze = max(-40.0, min(40.0, -snap.steering_angle_deg * 0.78))
|
||||
|
||||
target = EyeTarget(
|
||||
color=base_color,
|
||||
bounce_y=breathe_y,
|
||||
scale_x=squash_x * breathe_scale,
|
||||
scale_y=stretch_y * (2.0 - breathe_scale),
|
||||
squish_force=squish_force,
|
||||
pitch_offset_y=0.0,
|
||||
blind_spot_side=bsm_side,
|
||||
blinker_side=blinker_side,
|
||||
)
|
||||
|
||||
if self.mood == RoboticMood.CRITICAL:
|
||||
target.glyph = EyeGlyph.LASER_ALERT
|
||||
target.color = PALETTE["critical"]
|
||||
target.width = 114.0
|
||||
target.height = 84.0
|
||||
target.roundness = 0.42
|
||||
target.top_lid = 0.28
|
||||
target.top_slant = 18.0
|
||||
target.pulse_speed = 5.5
|
||||
target.bounce_y = math.sin(t * 28.0) * 3.5
|
||||
|
||||
elif self.mood == RoboticMood.DISTRACTED:
|
||||
target.color = PALETTE["prompt"]
|
||||
target.width = 108.0
|
||||
target.height = 96.0
|
||||
target.roundness = 0.48
|
||||
target.top_lid = 0.32
|
||||
target.top_slant = 12.0
|
||||
target.gaze_x = math.sin(t * 5.2) * 18.0
|
||||
target.mouth = MouthGlyph.FROWN
|
||||
target.pulse_speed = 2.5
|
||||
|
||||
elif self.mood == RoboticMood.USER_PROMPT:
|
||||
target.color = PALETTE["prompt"]
|
||||
target.width = 108.0
|
||||
target.height = 120.0
|
||||
target.top_lid = 0.06
|
||||
target.top_slant = -6.0
|
||||
target.gaze_x = micro_drift_x
|
||||
target.pulse_speed = 1.8
|
||||
|
||||
elif self.mood == RoboticMood.STARTLED_STARS:
|
||||
target.glyph = EyeGlyph.STAR
|
||||
target.color = PALETTE["override"]
|
||||
target.width = 114.0
|
||||
target.height = 114.0
|
||||
target.mouth = MouthGlyph.SURPRISED
|
||||
target.bounce_y = math.sin(t * 26.0) * 6.0
|
||||
target.scale_x = 1.0 + 0.08 * math.sin(t * 22.0)
|
||||
target.scale_y = 1.0 - 0.08 * math.sin(t * 22.0)
|
||||
|
||||
elif self.mood == RoboticMood.LANE_CHANGE:
|
||||
direction = -1 if snap.pre_lane_change_left else (1 if snap.pre_lane_change_right else self._last_lane_dir or 1)
|
||||
target.glyph = EyeGlyph.ARROW_LEFT if direction < 0 else EyeGlyph.ARROW_RIGHT
|
||||
target.gaze_x = direction * 32.0 + math.sin(t * 6.5) * 5.0
|
||||
target.height = 106.0
|
||||
target.top_lid = 0.10
|
||||
target.tilt_y = direction * 7.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.BLIND_SPOT:
|
||||
target.color = PALETTE["override"]
|
||||
target.gaze_x = bsm_side * 38.0
|
||||
target.height = 102.0
|
||||
target.top_lid = 0.22
|
||||
target.top_slant = 9.0
|
||||
target.pulse_speed = 3.2
|
||||
|
||||
elif self.mood == RoboticMood.BOOKMARK_LOVE:
|
||||
target.glyph = EyeGlyph.HEART
|
||||
target.color = PALETTE["love"]
|
||||
target.width = 114.0
|
||||
target.height = 114.0
|
||||
target.wink_right = self._love_wink
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 10.5)) * 15.0
|
||||
target.show_hearts = True
|
||||
|
||||
elif self.mood == RoboticMood.HAPPY_ENGAGE:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
target.color = PALETTE["engaged"]
|
||||
target.width = 116.0
|
||||
target.height = 100.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 9.5)) * 16.0
|
||||
|
||||
elif self.mood == RoboticMood.BOOST_ACCEL:
|
||||
target.glyph = EyeGlyph.SPARKLE_BOOST
|
||||
target.color = PALETTE["boost"]
|
||||
target.width = 116.0
|
||||
target.height = 120.0
|
||||
target.gaze_y = -7.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = math.sin(t * 18.0) * 5.0
|
||||
target.show_speed_lines = True
|
||||
|
||||
elif self.mood == RoboticMood.TURN_SIGNAL:
|
||||
beat = 0.5 + 0.5 * math.sin(t * 8.4)
|
||||
target.gaze_x = blinker_side * (22.0 + 14.0 * beat)
|
||||
target.tilt_y = blinker_side * 8.0
|
||||
target.width = 106.0
|
||||
target.height = 108.0
|
||||
target.top_lid = 0.08
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.POUT_STANDSTILL:
|
||||
target.width = 98.0
|
||||
target.height = 84.0
|
||||
target.roundness = 0.34
|
||||
target.top_lid = 0.26 + 0.05 * math.sin(t * 1.8)
|
||||
target.gaze_x = self._idle_gaze_x * 0.75 + micro_drift_x
|
||||
target.gaze_y = 6.0
|
||||
target.tilt_y = self._idle_tilt_y * 0.7
|
||||
target.mouth = MouthGlyph.FROWN
|
||||
|
||||
elif self.mood == RoboticMood.SLEEPY:
|
||||
target.width = 104.0
|
||||
target.height = 76.0
|
||||
target.roundness = 0.45
|
||||
target.top_lid = 0.60 + 0.06 * math.sin(t * 1.5)
|
||||
target.bottom_lid = 0.14
|
||||
target.gaze_y = 8.0
|
||||
target.gaze_x = math.sin(t * 0.7) * 8.0
|
||||
target.bounce_y = math.sin(t * 1.5) * 6.0
|
||||
target.show_zzz = True
|
||||
|
||||
elif self.mood == RoboticMood.SHARP_TURN:
|
||||
intensity = abs(squish_force)
|
||||
push_dir = 1.0 if squish_force >= 0 else -1.0
|
||||
target.squish_force = push_dir * intensity
|
||||
target.width = 108.0
|
||||
target.height = 104.0
|
||||
target.top_lid = 0.10 + 0.14 * intensity
|
||||
target.top_slant = 5.0 + 7.0 * intensity
|
||||
target.gaze_x = push_dir * 12.0 # squish renderer handles primary wall slide
|
||||
target.gaze_y = 0.0
|
||||
target.tilt_y = push_dir * (8.0 + 8.0 * intensity)
|
||||
target.mouth = MouthGlyph.SURPRISED if intensity >= 0.55 else MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.CURVE_FOCUS:
|
||||
intensity = abs(squish_force)
|
||||
push_dir = 1.0 if squish_force >= 0 else -1.0
|
||||
target.squish_force = push_dir * intensity
|
||||
target.width = 106.0
|
||||
target.height = 106.0
|
||||
target.top_lid = 0.08
|
||||
target.gaze_x = push_dir * 8.0
|
||||
target.gaze_y = 0.0
|
||||
target.tilt_y = push_dir * (5.0 + 6.0 * intensity)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
elif self.mood == RoboticMood.MUSIC_GROOVE:
|
||||
m = snap.music or MusicState()
|
||||
self._groove_intensity = 0.45 + 0.55 * _smoothstep(0.30, 0.80, m.confidence)
|
||||
if t >= self._groove_switch_at:
|
||||
self._groove_style = self._groove_scheduler.pick(t)
|
||||
self._groove_switch_at = t + max(8.0, 32.0 * 60.0 / max(60.0, m.bpm))
|
||||
self._apply_groove(target, t, m)
|
||||
|
||||
elif self.mood == RoboticMood.CRUISING_HAPPY:
|
||||
target.width = 106.0
|
||||
target.height = 114.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
target.gaze_x = steer_gaze * 0.35 + self._idle_gaze_x * 0.65 + micro_drift_x
|
||||
target.gaze_y = self._idle_gaze_y * 0.65
|
||||
target.tilt_y = self._idle_tilt_y * 0.75 + math.sin(t * 1.6) * 3.0
|
||||
self._apply_idle_action(target, t)
|
||||
|
||||
else: # IDLE_CURIOUS or SPEED_DISPLAY fallback
|
||||
target.width = 104.0
|
||||
target.height = 110.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
target.gaze_x = self._idle_gaze_x + micro_drift_x
|
||||
target.gaze_y = self._idle_gaze_y
|
||||
target.tilt_y = self._idle_tilt_y + math.sin(t * 1.4) * 3.0
|
||||
self._apply_idle_action(target, t)
|
||||
|
||||
if target.glyph == EyeGlyph.ROUND_RECT and not target.wink_right and blink > 0.0:
|
||||
cover = BLINK_LID_MIN + (BLINK_LID_MAX - BLINK_LID_MIN) * blink
|
||||
target.top_lid = max(target.top_lid, 0.55 * cover)
|
||||
target.bottom_lid = max(target.bottom_lid, 0.45 * cover)
|
||||
|
||||
return target
|
||||
|
||||
def _log_squish_debug(self, snap: DrivingSnapshot, abs_lat: float, jerk: float, yaw_rate: float, squish_force: float) -> None:
|
||||
"""Param-gated trace so the squish thresholds get set from a real drive, not a guess."""
|
||||
if self._params is None:
|
||||
return
|
||||
self._debug_frame += 1
|
||||
if self._debug_frame % 60 != 0:
|
||||
return
|
||||
try:
|
||||
if not self._params.get_bool(DEBUG_PARAM):
|
||||
return
|
||||
cloudlog.info(f"MICI squish lat={abs_lat:.2f} jerk={jerk:.0f} yaw={yaw_rate:.3f} bias={_GYRO_BIAS.bias:.4f} squish={squish_force:.2f} v={snap.v_ego:.1f}")
|
||||
except Exception:
|
||||
self._params = None
|
||||
|
||||
def _apply_groove(self, target: EyeTarget, t: float, m: MusicState) -> None:
|
||||
"""Render the currently scheduled groove variant, intensity-scaled by detector confidence."""
|
||||
style = self._groove_style
|
||||
beat = m.beat_pulse
|
||||
phase = m.groove_phase
|
||||
sway = math.sin(phase)
|
||||
amp = self._groove_intensity
|
||||
|
||||
target.color = groove_prism_color(t)
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.width = 108.0
|
||||
target.height = 112.0
|
||||
|
||||
if style is GrooveStyle.HEAD_BOB:
|
||||
target.bounce_y = (-13.0 * beat - abs(sway) * 4.0 - 6.0) * amp
|
||||
target.gaze_x = sway * 8.0 * amp
|
||||
target.gaze_y = -6.0 - 5.0 * beat * amp
|
||||
target.scale_x = 1.0 + 0.05 * beat * amp
|
||||
target.scale_y = 1.0 - 0.04 * beat * amp
|
||||
if beat > 0.58:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
elif style is GrooveStyle.SIDE_SWAY:
|
||||
target.bounce_y = -abs(sway) * 5.0 * amp - 4.0
|
||||
target.gaze_x = sway * 24.0 * amp
|
||||
target.tilt_y = sway * 14.0 * amp
|
||||
target.scale_x = 1.0 - 0.06 * abs(sway) * amp
|
||||
target.scale_y = 1.0 + 0.05 * abs(sway) * amp
|
||||
elif style is GrooveStyle.JELLY:
|
||||
target.height = 116.0
|
||||
target.scale_x = 1.0 + 0.13 * beat * amp
|
||||
target.scale_y = 1.0 - 0.11 * beat * amp
|
||||
target.bounce_y = -8.0 * beat * amp
|
||||
target.gaze_y = -4.0
|
||||
elif style is GrooveStyle.SNARE_BLINK:
|
||||
half = math.sin(phase * 0.5)
|
||||
target.height = 110.0
|
||||
target.gaze_x = sway * 10.0 * amp
|
||||
target.bounce_y = -abs(half) * 7.0 * amp
|
||||
target.glyph = EyeGlyph.CRESCENT if half > 0.6 else EyeGlyph.ROUND_RECT
|
||||
elif style is GrooveStyle.LOOK_AROUND:
|
||||
look = math.sin(phase * 0.5)
|
||||
target.gaze_x = look * 26.0 * amp
|
||||
target.tilt_y = look * 10.0 * amp
|
||||
target.bounce_y = -6.0 * beat * amp
|
||||
elif style is GrooveStyle.ANTICIPATION_POP:
|
||||
cycle = (phase / math.tau) % 1.0
|
||||
if cycle < 0.75:
|
||||
build = cycle / 0.75
|
||||
target.scale_y = 1.0 - 0.12 * build * amp
|
||||
target.scale_x = 1.0 + 0.10 * build * amp
|
||||
target.bounce_y = 6.0 * build * amp
|
||||
else:
|
||||
pop = math.sin((cycle - 0.75) / 0.25 * math.pi)
|
||||
target.scale_y = 1.0 + 0.16 * pop * amp
|
||||
target.scale_x = 1.0 - 0.12 * pop * amp
|
||||
target.bounce_y = -18.0 * pop * amp
|
||||
elif style is GrooveStyle.GLOW_PULSE:
|
||||
target.height = 110.0
|
||||
target.scale_x = 1.0 + 0.04 * beat * amp
|
||||
target.scale_y = 1.0 + 0.04 * beat * amp
|
||||
target.gaze_y = -4.0 - 3.0 * m.energy
|
||||
target.color = groove_prism_color(t * 0.6)
|
||||
|
||||
def _apply_idle_action(self, target: EyeTarget, t: float) -> None:
|
||||
"""Layer bubbly autonomous micro-behaviors onto normal cruising/idle states."""
|
||||
if self.idle_action == IdleAction.HAPPY_SQUINT:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.bounce_y = -abs(math.sin(t * 9.0)) * 12.0
|
||||
elif self.idle_action == IdleAction.CURIOUS_LOOK:
|
||||
target.gaze_x = self._idle_action_dir * 34.0
|
||||
target.gaze_y = -6.0
|
||||
target.tilt_y = self._idle_action_dir * 10.0
|
||||
target.height = 118.0
|
||||
elif self.idle_action == IdleAction.CHEEKY_WINK:
|
||||
target.wink_right = True
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.tilt_y = 6.0
|
||||
target.bounce_y = -8.0
|
||||
elif self.idle_action == IdleAction.GROOVE_BOB:
|
||||
target.bounce_y = math.sin(t * 7.2) * 11.0
|
||||
target.tilt_y = math.sin(t * 3.6) * 8.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
elif self.idle_action == IdleAction.STRETCH:
|
||||
s = math.sin(t * 3.0)
|
||||
target.scale_y = 1.0 + 0.12 * s
|
||||
target.scale_x = 1.0 - 0.09 * s
|
||||
target.bounce_y = -10.0 * abs(s)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.SETTLE:
|
||||
target.top_lid = 0.34
|
||||
target.height = 92.0
|
||||
target.bounce_y = 6.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.PERK_UP:
|
||||
target.width = 112.0
|
||||
target.height = 122.0
|
||||
target.gaze_x = math.sin(t * 11.0) * 16.0
|
||||
target.gaze_y = -8.0
|
||||
target.mouth = MouthGlyph.SURPRISED
|
||||
elif self.idle_action == IdleAction.DAYDREAM:
|
||||
target.gaze_x = 26.0 + math.sin(t * 0.9) * 4.0
|
||||
target.gaze_y = -10.0 - math.sin(t * 0.6) * 3.0
|
||||
target.tilt_y = 7.0
|
||||
target.top_lid = 0.16
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.DOODLE:
|
||||
ang = t * 3.4
|
||||
target.gaze_x = math.cos(ang) * 20.0
|
||||
target.gaze_y = math.sin(ang * 2.0) * 8.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.DOUBLE_BLINK_TILT:
|
||||
target.tilt_y = 5.0
|
||||
target.top_lid = max(target.top_lid, 0.30)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
|
||||
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
|
||||
"""Build a DrivingSnapshot safely from ui_state.sm."""
|
||||
sm = ui_state.sm
|
||||
cs = sm["carState"]
|
||||
controls = sm["controlsState"]
|
||||
dm = sm["driverMonitoringState"]
|
||||
events = sm["onroadEvents"]
|
||||
|
||||
v_cruise_cluster = cs.vCruiseCluster
|
||||
set_speed_kph = controls.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
|
||||
|
||||
pre_left = any(e.name == EventName.preLaneChangeLeft for e in events)
|
||||
pre_right = any(e.name == EventName.preLaneChangeRight for e in events)
|
||||
lane_change = any(e.name == EventName.laneChange for e in events)
|
||||
lane_blocked = any(e.name == EventName.laneChangeBlocked for e in events)
|
||||
|
||||
v_ego_cluster = cs.vEgoCluster
|
||||
v_ego = v_ego_cluster if v_ego_cluster != 0.0 else cs.vEgo
|
||||
|
||||
# Extract pitch, pitch rate, and yaw rate from modelV2 orientation + gyroscope (104 Hz)
|
||||
yaw_rate = 0.0
|
||||
pitch_rad = 0.0
|
||||
pitch_rate = 0.0
|
||||
if sm.valid.get("modelV2"):
|
||||
mv2 = sm["modelV2"]
|
||||
if len(mv2.orientation.y) > 0:
|
||||
pitch_rad = float(mv2.orientation.y[0])
|
||||
if len(mv2.orientationRate.y) > 0 and len(mv2.orientationRate.z) > 0:
|
||||
pitch_rate = float(mv2.orientationRate.y[0])
|
||||
yaw_rate = float(mv2.orientationRate.z[0])
|
||||
if sm.valid.get("gyroscope"):
|
||||
gyro_msg = sm["gyroscope"]
|
||||
gyro_which = gyro_msg.which()
|
||||
gv = gyro_msg.gyroUncalibrated.v if gyro_which == "gyroUncalibrated" else (gyro_msg.gyro.v if gyro_which == "gyro" else ())
|
||||
if len(gv) >= 3:
|
||||
# Blend crisp high-rate gyro directly with model orientation rate
|
||||
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
|
||||
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
|
||||
|
||||
yaw_rate = _GYRO_BIAS.correct(yaw_rate, max(0.0, float(v_ego)), 1.0 / 60.0)
|
||||
|
||||
return DrivingSnapshot(
|
||||
started=ui_state.started,
|
||||
engaged=ui_state.engaged,
|
||||
status=ui_state.status,
|
||||
v_ego=max(0.0, float(v_ego)),
|
||||
a_ego=float(cs.aEgo),
|
||||
standstill=bool(cs.standstill),
|
||||
steering_angle_deg=float(cs.steeringAngleDeg),
|
||||
yaw_rate=yaw_rate,
|
||||
pitch_rad=pitch_rad,
|
||||
pitch_rate=pitch_rate,
|
||||
curvature=float(controls.curvature) if sm.valid.get("controlsState") else 0.0,
|
||||
set_speed_kph=float(set_speed_kph),
|
||||
is_metric=bool(ui_state.is_metric),
|
||||
left_blinker=bool(cs.leftBlinker),
|
||||
right_blinker=bool(cs.rightBlinker),
|
||||
left_blindspot=bool(cs.leftBlindspot),
|
||||
right_blindspot=bool(cs.rightBlindspot),
|
||||
pre_lane_change_left=pre_left,
|
||||
pre_lane_change_right=pre_right,
|
||||
lane_change=lane_change,
|
||||
lane_change_blocked=lane_blocked,
|
||||
dm_alert_level=int(dm.alertLevel.raw) if sm.valid["driverMonitoringState"] else 0,
|
||||
alert=alert,
|
||||
)
|
||||
|
||||
|
||||
def display_speed_and_set_speed(snap: DrivingSnapshot) -> tuple[int, int | None]:
|
||||
"""Convert current speed and cruise set speed to display units (mph or km/h)."""
|
||||
speed_conv = CV.MS_TO_KPH if snap.is_metric else CV.MS_TO_MPH
|
||||
cur_speed = round(max(0.0, snap.v_ego * speed_conv))
|
||||
if 0 < snap.set_speed_kph < SET_SPEED_NA:
|
||||
set_val = snap.set_speed_kph if snap.is_metric else snap.set_speed_kph * KM_TO_MILE
|
||||
return cur_speed, round(set_val)
|
||||
return cur_speed, None
|
||||
@@ -1,384 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
EyeGlyph,
|
||||
EyeTarget,
|
||||
MouthGlyph,
|
||||
)
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
|
||||
|
||||
class ProceduralFaceRenderer:
|
||||
"""60 FPS bubbly EMO-inspired procedural vector face renderer for 536x240 MICI OLED."""
|
||||
|
||||
EYE_SPACING = 166.0 # distance between left and right eye centers
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
# Bubbly spring-overshoot filters for juicy EMO-style squash-and-stretch motion
|
||||
self._w = BounceFilter(104.0, 0.065, dt, bounce=4.2)
|
||||
self._h = BounceFilter(112.0, 0.065, dt, bounce=4.2)
|
||||
self._gaze_x = BounceFilter(0.0, 0.050, dt, bounce=3.4)
|
||||
self._gaze_y = BounceFilter(0.0, 0.055, dt, bounce=3.0)
|
||||
self._bounce_y = BounceFilter(0.0, 0.055, dt, bounce=4.4)
|
||||
self._tilt_y = BounceFilter(0.0, 0.095, dt, bounce=3.2)
|
||||
self._scale_x = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._scale_y = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._squish = BounceFilter(0.0, 0.075, dt, bounce=3.6)
|
||||
self._pitch_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
|
||||
|
||||
# Crisp first-order filters for eyelids, roundness, and smooth color blending
|
||||
self._roundness = FirstOrderFilter(0.62, 0.08, dt)
|
||||
self._top_lid = FirstOrderFilter(0.0, 0.032, dt)
|
||||
self._bottom_lid = FirstOrderFilter(0.0, 0.032, dt)
|
||||
self._top_slant = FirstOrderFilter(0.0, 0.065, dt)
|
||||
self._r = FirstOrderFilter(218.0, 0.14, dt)
|
||||
self._g = FirstOrderFilter(232.0, 0.14, dt)
|
||||
self._b = FirstOrderFilter(248.0, 0.14, dt)
|
||||
self._bsm_alpha = FirstOrderFilter(0.0, 0.07, dt)
|
||||
self._blinker_alpha = FirstOrderFilter(0.0, 0.06, dt)
|
||||
|
||||
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
|
||||
|
||||
def render(self, rect: rl.Rectangle, target: EyeTarget, alpha: float = 1.0, y_shift: float = 0.0) -> None:
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
|
||||
# Update bubbly & smooth filters
|
||||
w = max(24.0, self._w.update(target.width) * self._scale_x.update(target.scale_x))
|
||||
h = max(20.0, self._h.update(target.height) * self._scale_y.update(target.scale_y))
|
||||
roundness = max(0.15, min(0.85, self._roundness.update(target.roundness)))
|
||||
top_lid = max(0.0, min(0.95, self._top_lid.update(target.top_lid)))
|
||||
bottom_lid = max(0.0, min(0.95, self._bottom_lid.update(target.bottom_lid)))
|
||||
top_slant = self._top_slant.update(target.top_slant)
|
||||
gaze_x = self._gaze_x.update(target.gaze_x)
|
||||
gaze_y = self._gaze_y.update(target.gaze_y)
|
||||
bounce_y = self._bounce_y.update(target.bounce_y)
|
||||
tilt_y = self._tilt_y.update(target.tilt_y)
|
||||
squish = max(-1.0, min(1.0, self._squish.update(target.squish_force)))
|
||||
self._pitch_y.update(target.pitch_offset_y)
|
||||
squish_abs = abs(squish)
|
||||
|
||||
r = max(0, min(255, int(self._r.update(target.color[0]))))
|
||||
g = max(0, min(255, int(self._g.update(target.color[1]))))
|
||||
b = max(0, min(255, int(self._b.update(target.color[2]))))
|
||||
|
||||
# Optional alert brightness pulse
|
||||
pulse = 1.0
|
||||
if target.pulse_speed > 0.0:
|
||||
pulse = 0.72 + 0.28 * (0.5 + 0.5 * math.sin(t * target.pulse_speed * math.tau))
|
||||
|
||||
eff_alpha = max(0.0, min(1.0, alpha * pulse))
|
||||
core_color = rl.Color(r, g, b, int(255 * eff_alpha))
|
||||
|
||||
# Subtle wall-cushion glow when centrifugal force squishes the bot strongly to one side
|
||||
if squish_abs > 0.35:
|
||||
wall_a = (squish_abs - 0.35) / 0.65
|
||||
self._draw_wall_squish_glow(rect, 1 if squish > 0 else -1, core_color, wall_a * eff_alpha)
|
||||
|
||||
# Ambient edge accents (blind spot glow, blinker chevrons, boost speed lines)
|
||||
bsm_a = self._bsm_alpha.update(1.0 if target.blind_spot_side != 0 else 0.0)
|
||||
if bsm_a > 0.02 and target.blind_spot_side != 0:
|
||||
self._draw_bsm_edge_glow(rect, target.blind_spot_side, bsm_a * alpha)
|
||||
|
||||
blinker_a = self._blinker_alpha.update(1.0 if target.blinker_side != 0 else 0.0)
|
||||
if blinker_a > 0.02 and target.blinker_side != 0:
|
||||
self._draw_blinker_indicator(rect, target.blinker_side, blinker_a * alpha, t)
|
||||
|
||||
if target.show_speed_lines:
|
||||
self._draw_speed_lines(rect, core_color, eff_alpha, t)
|
||||
|
||||
# Slide the whole face horizontally toward the opposite side of the turn under centrifugal force
|
||||
centrifugal_shift_x = squish * 76.0
|
||||
cx = rect.x + rect.width / 2.0 + gaze_x + centrifugal_shift_x
|
||||
cy = rect.y + rect.height / 2.0 - 8.0 + gaze_y + bounce_y + y_shift
|
||||
|
||||
# Compress spacing between eyes as the bot gets smooshed against the side wall
|
||||
spacing = self.EYE_SPACING * (1.0 - 0.24 * squish_abs)
|
||||
left_cx = cx - spacing / 2.0
|
||||
right_cx = cx + spacing / 2.0
|
||||
left_cy = cy - tilt_y
|
||||
right_cy = cy + tilt_y
|
||||
|
||||
# Asymmetric centrifugal wall-squish: outer pressed eye squishes narrower & taller!
|
||||
left_w_mult = (1.0 - 0.36 * max(0.0, -squish)) * (1.0 - 0.14 * max(0.0, squish))
|
||||
left_h_mult = (1.0 + 0.16 * max(0.0, -squish)) * (1.0 - 0.05 * max(0.0, squish))
|
||||
right_w_mult = (1.0 - 0.36 * max(0.0, squish)) * (1.0 - 0.14 * max(0.0, -squish))
|
||||
right_h_mult = (1.0 + 0.16 * max(0.0, squish)) * (1.0 - 0.05 * max(0.0, -squish))
|
||||
|
||||
# Subtle 3D perspective scaling when glancing left/right
|
||||
left_scale = 1.0 - max(0.0, gaze_x / 210.0)
|
||||
right_scale = 1.0 + min(0.0, gaze_x / 210.0)
|
||||
|
||||
eye_configs = (
|
||||
(left_cx, left_cy, w * left_scale * left_w_mult, h * left_scale * left_h_mult),
|
||||
(right_cx, right_cy, w * right_scale * right_w_mult, h * right_scale * right_h_mult),
|
||||
)
|
||||
for side_idx, (ecx, ecy, ew, eh) in enumerate(eye_configs):
|
||||
slant = top_slant if side_idx == 0 else -top_slant
|
||||
glyph = EyeGlyph.CRESCENT if (side_idx == 1 and target.wink_right) else target.glyph
|
||||
self._draw_eye(ecx, ecy, ew, eh, roundness, top_lid, bottom_lid, slant, glyph, core_color, eff_alpha, gaze_x, gaze_y, t)
|
||||
|
||||
if target.mouth != MouthGlyph.NONE:
|
||||
self._draw_mouth(cx, cy + h * 0.72, target.mouth, core_color)
|
||||
|
||||
if target.show_zzz:
|
||||
self._draw_floating_zzz(right_cx + w * 0.58, right_cy - h * 0.35, core_color, eff_alpha, t)
|
||||
|
||||
if target.show_hearts:
|
||||
self._draw_floating_mini_hearts(cx, cy - h * 0.58, core_color, eff_alpha, t)
|
||||
|
||||
def _draw_wall_squish_glow(self, rect: rl.Rectangle, side: int, color: rl.Color, alpha: float) -> None:
|
||||
glow_w = 46
|
||||
edge = rl.Color(color.r, color.g, color.b, int(95 * alpha))
|
||||
clear = rl.Color(color.r, color.g, color.b, 0)
|
||||
if side < 0:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), edge, clear)
|
||||
else:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, edge)
|
||||
|
||||
def _draw_bsm_edge_glow(self, rect: rl.Rectangle, side: int, alpha: float) -> None:
|
||||
glow_w = 56
|
||||
amber = rl.Color(255, 160, 30, int(145 * alpha))
|
||||
clear = rl.Color(255, 160, 30, 0)
|
||||
if side < 0:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), amber, clear)
|
||||
else:
|
||||
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, amber)
|
||||
|
||||
def _draw_blinker_indicator(self, rect: rl.Rectangle, side: int, alpha: float, t: float) -> None:
|
||||
"""Crisp pulsing directional chevron on the left/right edge for turn signals."""
|
||||
pulse = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(t * 8.4))
|
||||
col = rl.Color(85, 240, 140, int(235 * pulse * alpha))
|
||||
glow = rl.Color(85, 240, 140, int(65 * pulse * alpha))
|
||||
cy = rect.y + rect.height / 2.0
|
||||
sign = 1.0 if side > 0 else -1.0
|
||||
base_x = (rect.x + rect.width - 34.0) if side > 0 else (rect.x + 34.0)
|
||||
|
||||
for idx in range(2):
|
||||
ox = base_x - sign * idx * 14.0
|
||||
p_top = rl.Vector2(ox - sign * 10.0, cy - 18.0)
|
||||
p_tip = rl.Vector2(ox + sign * 8.0, cy)
|
||||
p_bot = rl.Vector2(ox - sign * 10.0, cy + 18.0)
|
||||
rl.draw_line_ex(p_top, p_tip, 9.0, glow)
|
||||
rl.draw_line_ex(p_tip, p_bot, 9.0, glow)
|
||||
rl.draw_line_ex(p_top, p_tip, 4.5, col)
|
||||
rl.draw_line_ex(p_tip, p_bot, 4.5, col)
|
||||
|
||||
def _draw_speed_lines(self, rect: rl.Rectangle, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Energetic animated speed streaks on the screen edges during sharp acceleration."""
|
||||
for i in range(4):
|
||||
phase = (t * 4.5 + i * 0.25) % 1.0
|
||||
y = rect.y + 68.0 + i * 44.0
|
||||
line_len = 26.0 + 22.0 * math.sin(phase * math.pi)
|
||||
a = int(170 * math.sin(phase * math.pi) * alpha)
|
||||
col = rl.Color(color.r, color.g, color.b, a)
|
||||
# Left & right symmetrical streaks
|
||||
lx = rect.x + 12.0 + (1.0 - phase) * 28.0
|
||||
rx = rect.x + rect.width - 12.0 - (1.0 - phase) * 28.0
|
||||
rl.draw_line_ex(rl.Vector2(lx, y), rl.Vector2(lx + line_len, y), 3.5, col)
|
||||
rl.draw_line_ex(rl.Vector2(rx - line_len, y), rl.Vector2(rx, y), 3.5, col)
|
||||
|
||||
def _draw_floating_zzz(self, x: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Softly drifting Zzz bubbles so sleepy/standstill state is continuously animated."""
|
||||
for idx, ch in enumerate(("z", "Z")):
|
||||
phase = (t * 0.55 + idx * 0.5) % 1.0
|
||||
zx = x + phase * 18.0 + math.sin(phase * math.tau) * 4.0
|
||||
zy = y - phase * 34.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
size = 20 + idx * 8
|
||||
col = rl.Color(color.r, color.g, color.b, int(190 * fade * alpha))
|
||||
rl.draw_text_ex(self._font_semi_bold, ch, rl.Vector2(zx, zy), size, 0, col)
|
||||
|
||||
def _draw_floating_mini_hearts(self, cx: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
"""Floating mini-hearts above the face during pet/bookmark reactions."""
|
||||
for idx, dx in enumerate((-62.0, 0.0, 62.0)):
|
||||
phase = (t * 1.4 + idx * 0.33) % 1.0
|
||||
hx = cx + dx + math.sin(phase * math.tau) * 6.0
|
||||
hy = y - phase * 26.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
col = rl.Color(color.r, color.g, color.b, int(210 * fade * alpha))
|
||||
self._draw_heart_eye(hx, hy, 8.5, col, fade * alpha, with_glow=False)
|
||||
|
||||
def _draw_eye(
|
||||
self,
|
||||
cx: float,
|
||||
cy: float,
|
||||
w: float,
|
||||
h: float,
|
||||
roundness: float,
|
||||
top_lid: float,
|
||||
bottom_lid: float,
|
||||
slant_deg: float,
|
||||
glyph: EyeGlyph,
|
||||
color: rl.Color,
|
||||
alpha: float,
|
||||
gaze_x: float,
|
||||
gaze_y: float,
|
||||
t: float,
|
||||
) -> None:
|
||||
if glyph == EyeGlyph.STAR:
|
||||
self._draw_star_eye(cx, cy, min(w, h) * 0.48, color, alpha, t)
|
||||
return
|
||||
if glyph == EyeGlyph.HEART:
|
||||
self._draw_heart_eye(cx, cy, min(w, h) * 0.48, color, alpha, with_glow=True)
|
||||
return
|
||||
if glyph == EyeGlyph.CRESCENT:
|
||||
self._draw_crescent_eye(cx, cy, w, h, color, alpha)
|
||||
return
|
||||
|
||||
# Silky radial OLED bloom (zero banding, consistent with star & heart eyes)
|
||||
visible_frac = max(0.25, 1.0 - top_lid - bottom_lid)
|
||||
bloom_r = max(w, h) * 0.78 * (0.65 + 0.35 * visible_frac)
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy),
|
||||
bloom_r,
|
||||
rl.Color(color.r, color.g, color.b, int(92 * visible_frac * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
|
||||
# Crisp eye core
|
||||
core_rec = rl.Rectangle(cx - w / 2.0, cy - h / 2.0, w, h)
|
||||
rl.draw_rectangle_rounded(core_rec, min(0.85, roundness), 24, color)
|
||||
|
||||
# Glossy dual specular catchlights (centered-dynamic so eyes never appear stuck staring at top-left)
|
||||
glint_dx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.8
|
||||
glint_dy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.4
|
||||
glint_fade = 0.30 + 0.70 * visible_frac
|
||||
hi_col = rl.Color(255, 255, 255, int(105 * alpha * glint_fade))
|
||||
rl.draw_rectangle_rounded(
|
||||
rl.Rectangle(cx - w * 0.14 + glint_dx, cy - h * 0.30 + glint_dy, w * 0.28, h * 0.16),
|
||||
0.90,
|
||||
12,
|
||||
hi_col,
|
||||
)
|
||||
rl.draw_circle(
|
||||
int(cx + w * 0.18 + glint_dx * 0.6),
|
||||
int(cy + h * 0.22 + glint_dy * 0.6),
|
||||
max(3.5, min(w, h) * 0.055),
|
||||
rl.Color(255, 255, 255, int(75 * alpha * glint_fade)),
|
||||
)
|
||||
|
||||
# Sparkle glint inside eyes during sharp acceleration boost
|
||||
if glyph == EyeGlyph.SPARKLE_BOOST:
|
||||
self._draw_boost_sparkle(cx, cy, min(w, h) * 0.22, alpha, t)
|
||||
|
||||
# Directional chevron glint inside eye during lane changes
|
||||
if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT):
|
||||
self._draw_chevron_glint(cx, cy, w * 0.24, glyph == EyeGlyph.ARROW_RIGHT, alpha)
|
||||
|
||||
# Laser-alert inner bright core bar
|
||||
if glyph == EyeGlyph.LASER_ALERT:
|
||||
inner_col = rl.Color(255, 235, 235, int(215 * alpha))
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(cx - w * 0.36, cy - 5, w * 0.72, 10), 0.85, 10, inner_col)
|
||||
|
||||
# Eyelid masks (pure black polygons over the OLED canvas, tall enough to cleanly clip outer halo)
|
||||
if top_lid > 0.01 or abs(slant_deg) > 0.5:
|
||||
lid_h = max(42.0, h * (top_lid + 0.55))
|
||||
lid_w = w + 80.0
|
||||
lid_cy = (cy - h / 2.0) + h * top_lid - lid_h / 2.0 - 4.0
|
||||
if abs(slant_deg) > 0.01:
|
||||
rad = math.radians(slant_deg)
|
||||
c_ang, s_ang = math.cos(rad), math.sin(rad)
|
||||
hw, hh = lid_w / 2.0, lid_h / 2.0
|
||||
# CCW quad around (cx, lid_cy) in y-down screen coordinates
|
||||
corners = [(-hw, -hh), (-hw, hh), (hw, hh), (hw, -hh)]
|
||||
quad = [rl.Vector2(cx + x * c_ang - y * s_ang, lid_cy + x * s_ang + y * c_ang) for x, y in corners]
|
||||
rl.draw_triangle_fan(quad, 4, rl.BLACK)
|
||||
else:
|
||||
rl.draw_rectangle_rec(rl.Rectangle(cx - lid_w / 2.0, lid_cy - lid_h / 2.0, lid_w, lid_h), rl.BLACK)
|
||||
|
||||
if bottom_lid > 0.01:
|
||||
lid_h = max(36.0, h * (bottom_lid + 0.45))
|
||||
lid_w = w + 80.0
|
||||
lid_cy = (cy + h / 2.0) - h * bottom_lid + lid_h / 2.0 + 4.0
|
||||
rl.draw_rectangle_rec(rl.Rectangle(cx - lid_w / 2.0, lid_cy - lid_h / 2.0, lid_w, lid_h), rl.BLACK)
|
||||
|
||||
def _draw_boost_sparkle(self, cx: float, cy: float, size: float, alpha: float, t: float) -> None:
|
||||
"""4-point pulsing star sparkle inside eyes during sharp acceleration."""
|
||||
s = size * (0.85 + 0.25 * math.sin(t * 14.0))
|
||||
col = rl.Color(255, 255, 255, int(210 * alpha))
|
||||
rl.draw_line_ex(rl.Vector2(cx - s, cy), rl.Vector2(cx + s, cy), 4.0, col)
|
||||
rl.draw_line_ex(rl.Vector2(cx, cy - s), rl.Vector2(cx, cy + s), 4.0, col)
|
||||
|
||||
def _draw_chevron_glint(self, cx: float, cy: float, size: float, right: bool, alpha: float) -> None:
|
||||
sign = 1.0 if right else -1.0
|
||||
col = rl.Color(0, 0, 0, int(135 * alpha))
|
||||
p_top = rl.Vector2(cx - sign * size * 0.35, cy - size * 0.75)
|
||||
p_tip = rl.Vector2(cx + sign * size * 0.55, cy)
|
||||
p_bot = rl.Vector2(cx - sign * size * 0.35, cy + size * 0.75)
|
||||
rl.draw_line_ex(p_top, p_tip, 7.0, col)
|
||||
rl.draw_line_ex(p_tip, p_bot, 7.0, col)
|
||||
|
||||
def _draw_star_eye(self, cx: float, cy: float, outer_r: float, color: rl.Color, alpha: float, t: float) -> None:
|
||||
inner_r = outer_r * 0.44
|
||||
spin = math.sin(t * 7.0) * 0.14 # playful wobble
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(10):
|
||||
angle = -math.pi / 2.0 + spin + i * (math.pi / 5.0)
|
||||
rad = outer_r if i % 2 == 0 else inner_r
|
||||
pts.append(rl.Vector2(cx + math.cos(angle) * rad, cy + math.sin(angle) * rad))
|
||||
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy), outer_r * 1.25,
|
||||
rl.Color(color.r, color.g, color.b, int(90 * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
center = rl.Vector2(cx, cy)
|
||||
fan = [center, *reversed(pts), pts[-1]]
|
||||
rl.draw_triangle_fan(fan, len(fan), color)
|
||||
|
||||
def _draw_heart_eye(self, cx: float, cy: float, radius: float, color: rl.Color, alpha: float, with_glow: bool = True) -> None:
|
||||
"""Seamless, perfectly symmetrical 48-point parametric smooth heart curve."""
|
||||
if with_glow:
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(cx, cy), radius * 1.4,
|
||||
rl.Color(color.r, color.g, color.b, int(92 * alpha)),
|
||||
rl.Color(color.r, color.g, color.b, 0),
|
||||
)
|
||||
|
||||
# Classic smooth parametric heart:
|
||||
# x(t) = 16 sin^3(t), y(t) = -(13 cos(t) - 5 cos(2t) - 2 cos(3t) - cos(4t))
|
||||
# Normalized so half-width ~= radius; centered vertically around cy
|
||||
scale = radius / 16.0
|
||||
n_pts = 48
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(n_pts):
|
||||
ang = (i / n_pts) * math.tau
|
||||
s = math.sin(ang)
|
||||
hx = 16.0 * (s * s * s)
|
||||
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
|
||||
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
|
||||
|
||||
center = rl.Vector2(cx, cy + radius * 0.05)
|
||||
# Parametric curve runs clockwise in screen coords (y-down), so reversed fan is CCW
|
||||
fan = [center, *reversed(pts), pts[-1]]
|
||||
rl.draw_triangle_fan(fan, len(fan), color)
|
||||
|
||||
def _draw_crescent_eye(self, cx: float, cy: float, w: float, h: float, color: rl.Color, alpha: float) -> None:
|
||||
radius = min(w, h) * 0.50
|
||||
arc_cy = cy + radius * 0.35
|
||||
glow_col = rl.Color(color.r, color.g, color.b, int(55 * alpha))
|
||||
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 22.0, radius + 8.0, 200.0, 340.0, 28, glow_col)
|
||||
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 14.0, radius, 202.0, 338.0, 28, color)
|
||||
|
||||
def _draw_mouth(self, cx: float, cy: float, mouth: MouthGlyph, color: rl.Color) -> None:
|
||||
if mouth == MouthGlyph.SMILE:
|
||||
rl.draw_ring(rl.Vector2(cx, cy - 10.0), 17.0, 23.0, 25.0, 155.0, 20, color)
|
||||
elif mouth == MouthGlyph.BIG_GRIN:
|
||||
rl.draw_ring(rl.Vector2(cx, cy - 12.0), 19.0, 26.0, 18.0, 162.0, 24, color)
|
||||
elif mouth == MouthGlyph.FROWN:
|
||||
rl.draw_ring(rl.Vector2(cx, cy + 16.0), 17.0, 23.0, 205.0, 335.0, 20, color)
|
||||
elif mouth == MouthGlyph.SURPRISED:
|
||||
rl.draw_ring(rl.Vector2(cx, cy + 2.0), 9.0, 15.0, 0.0, 360.0, 24, color)
|
||||
@@ -1,365 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
DEFAULT_SAMPLE_RATE = 16000
|
||||
FRAME_RATE = 20.0
|
||||
FFT_SIZE = 1024 # ~64ms analysis window
|
||||
NUM_BANDS = 12
|
||||
HISTORY_FRAMES = 50 # 2.5 seconds of flux/energy history @ 20 Hz
|
||||
|
||||
MIC_TARGET_RMS = 0.12
|
||||
MIC_MAX_GAIN = 6.0
|
||||
SOFT_KNEE = 0.7
|
||||
|
||||
# Tempo autocorrelation lag bounds @ 20 Hz: 7..18 frames -> 67..171 BPM
|
||||
MIN_TEMPO_LAG = 7
|
||||
MAX_TEMPO_LAG = 18
|
||||
|
||||
ENTER_MUSIC_CONF = 0.44
|
||||
EXIT_MUSIC_CONF = 0.26
|
||||
ENTER_DWELL_S = 0.9
|
||||
ENTER_DWELL_NO_BEAT_S = 2.0
|
||||
EXIT_DWELL_S = 2.5
|
||||
HOLDOFF_S = 3.0
|
||||
|
||||
BEAT_LOCK_PERIODS = 3
|
||||
BEAT_PERIOD_CV_TOLERANCE = 0.25
|
||||
BEAT_HISTORY = 32
|
||||
|
||||
SYLLABIC_LOW_HZ = 3.0
|
||||
SYLLABIC_HIGH_HZ = 8.0
|
||||
SYLLABIC_FRAMES = 40
|
||||
|
||||
MIN_ACTIVE_RMS = 0.0025 # pre-gain RMS (~ -52 dBFS)
|
||||
|
||||
|
||||
def _soft_limit(x: np.ndarray, knee: float = SOFT_KNEE) -> np.ndarray:
|
||||
"""Linear below `knee`, smoothly saturating above it. Unlike np.clip this adds no harmonics."""
|
||||
ax = np.abs(x)
|
||||
if not np.any(ax > knee):
|
||||
return x.astype(np.float32)
|
||||
out = x.astype(np.float32).copy()
|
||||
over = ax > knee
|
||||
span = 1.0 - knee
|
||||
out[over] = np.sign(x[over]) * (knee + span * np.tanh((ax[over] - knee) / span))
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class MusicState:
|
||||
is_music: bool = False
|
||||
confidence: float = 0.0
|
||||
beat_pulse: float = 0.0 # 0..1 sharp onset with smooth decay
|
||||
groove_phase: float = 0.0
|
||||
bpm: float = 116.0
|
||||
energy: float = 0.0 # 0..1 normalized musical loudness
|
||||
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
|
||||
beat_locked: bool = False
|
||||
|
||||
|
||||
class MusicAnalyzer:
|
||||
"""Low-CPU pure-NumPy cabin music detector, beat tracker, and 12-band equalizer analyzer.
|
||||
|
||||
Tuned for real car cabins (road/wind/HVAC rumble + conversation):
|
||||
1. Adaptive mic gain + soft limiting (never hard-clips the analysis buffer)
|
||||
2. Per-bin adaptive spectral noise-floor subtraction
|
||||
3. Harmonic peak prominence & spectral tonality (rejects broadband road/wind noise)
|
||||
4. Musical bandwidth + spectral frame stability (rejects speech formants)
|
||||
5. Rhythmic tempo periodicity (spectral flux autocorrelation at 67-171 BPM)
|
||||
6. Syllabic 3-8 Hz envelope modulation as an explicit speech term
|
||||
7. Dwell + holdoff + beat lock before claiming "music"
|
||||
"""
|
||||
|
||||
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE):
|
||||
self._sample_rate = sample_rate
|
||||
self._window = np.hanning(FFT_SIZE).astype(np.float32)
|
||||
self._ring = np.zeros(FFT_SIZE, dtype=np.float32)
|
||||
self._prev_mag: np.ndarray | None = None
|
||||
self._prev_excess_norm: np.ndarray | None = None
|
||||
self._noise_spec: np.ndarray | None = None
|
||||
|
||||
self._confidence: float = 0.0
|
||||
self._is_music: bool = False
|
||||
self._beat_pulse: float = 0.0
|
||||
self._groove_phase: float = 0.0
|
||||
self._bpm: float = 116.0
|
||||
self._energy: float = 0.0
|
||||
self._bands = np.zeros(NUM_BANDS, dtype=np.float32)
|
||||
|
||||
self._flux_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
|
||||
self._active_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
|
||||
self._bass_flux_hist: deque[float] = deque(maxlen=20)
|
||||
self._stability_hist: deque[float] = deque(maxlen=20)
|
||||
self._speech_env: deque[float] = deque(maxlen=SYLLABIC_FRAMES)
|
||||
self._beat_onsets: deque[float] = deque(maxlen=BEAT_HISTORY)
|
||||
|
||||
self._t: float = 0.0
|
||||
self._enter_timer: float = 0.0
|
||||
self._exit_timer: float = 0.0
|
||||
self._holdoff_until: float = 0.0
|
||||
self._beat_locked: bool = False
|
||||
|
||||
self._build_frequency_masks(sample_rate)
|
||||
|
||||
def _build_frequency_masks(self, sr: int) -> None:
|
||||
self._sample_rate = sr
|
||||
freqs = np.fft.rfftfreq(FFT_SIZE, d=1.0 / sr)
|
||||
self._freqs = freqs
|
||||
self._bass_mask = (freqs >= 55.0) & (freqs < 230.0)
|
||||
self._speech_mask = (freqs >= 300.0) & (freqs < 2400.0)
|
||||
self._treble_mask = (freqs >= 2600.0) & (freqs < min(7600.0, sr * 0.48))
|
||||
self._tonal_mask = (freqs >= 85.0) & (freqs < 4500.0)
|
||||
|
||||
# 12 log-spaced equalizer bands (60 Hz .. 7200 Hz)
|
||||
edges = np.geomspace(60.0, min(7200.0, sr * 0.47), NUM_BANDS + 1)
|
||||
self._band_slices: list[tuple[int, int]] = []
|
||||
for i in range(NUM_BANDS):
|
||||
lo = int(np.searchsorted(freqs, edges[i]))
|
||||
hi = max(lo + 1, int(np.searchsorted(freqs, edges[i + 1])))
|
||||
self._band_slices.append((lo, min(hi, len(freqs))))
|
||||
|
||||
@property
|
||||
def state(self) -> MusicState:
|
||||
return MusicState(
|
||||
is_music=self._is_music,
|
||||
confidence=self._confidence,
|
||||
beat_pulse=self._beat_pulse,
|
||||
groove_phase=self._groove_phase,
|
||||
bpm=self._bpm,
|
||||
energy=self._energy,
|
||||
bands=tuple(float(b) for b in self._bands),
|
||||
beat_locked=self._beat_locked,
|
||||
)
|
||||
|
||||
def step_visual_decay(self, dt: float) -> MusicState:
|
||||
"""Advance smooth 60 FPS groove phase and beat decay between 20 Hz audio chunks."""
|
||||
if self._is_music:
|
||||
rad_per_sec = (self._bpm / 60.0) * math.tau
|
||||
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % math.tau
|
||||
decay = math.exp(-dt * 7.5)
|
||||
self._beat_pulse *= decay
|
||||
if not self._is_music:
|
||||
self._bands *= math.exp(-dt * 6.0)
|
||||
return self.state
|
||||
|
||||
def process_audio_bytes(self, data: bytes, sample_rate: int = DEFAULT_SAMPLE_RATE) -> MusicState:
|
||||
"""Process a rawAudioData int16 PCM byte buffer from micd."""
|
||||
if not data:
|
||||
return self.state
|
||||
if sample_rate > 0 and sample_rate != self._sample_rate:
|
||||
self._build_frequency_masks(sample_rate)
|
||||
samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
|
||||
return self.process_samples(samples)
|
||||
|
||||
def process_samples(self, samples: np.ndarray) -> MusicState:
|
||||
"""Analyze a normalized float32 [-1, 1] mono audio chunk (~50 ms)."""
|
||||
n = len(samples)
|
||||
if n == 0:
|
||||
return self.state
|
||||
|
||||
dt = 1.0 / FRAME_RATE
|
||||
self._t += dt
|
||||
|
||||
raw_rms = float(np.sqrt(np.mean(samples * samples)))
|
||||
|
||||
if raw_rms > 1e-6:
|
||||
mic_gain = float(np.clip(MIC_TARGET_RMS / raw_rms, 1.0, MIC_MAX_GAIN))
|
||||
else:
|
||||
mic_gain = MIC_MAX_GAIN
|
||||
boosted = _soft_limit(samples * mic_gain)
|
||||
|
||||
if n >= FFT_SIZE:
|
||||
self._ring[:] = boosted[-FFT_SIZE:]
|
||||
else:
|
||||
self._ring[:-n] = self._ring[n:]
|
||||
self._ring[-n:] = boosted
|
||||
|
||||
rms = float(np.sqrt(np.mean(self._ring * self._ring)))
|
||||
|
||||
# FFT magnitude & power spectrum
|
||||
spec = np.abs(np.fft.rfft(self._ring * self._window)) / (FFT_SIZE * 0.5)
|
||||
power = spec * spec + 1e-12
|
||||
|
||||
# Per-bin slow stationary cabin noise floor (tracks down quickly, creeps up very slowly)
|
||||
if self._noise_spec is None or len(self._noise_spec) != len(power):
|
||||
self._noise_spec = power.copy()
|
||||
else:
|
||||
lower = power < self._noise_spec
|
||||
self._noise_spec = np.where(
|
||||
lower,
|
||||
0.92 * self._noise_spec + 0.08 * power,
|
||||
0.9985 * self._noise_spec + 0.0015 * power,
|
||||
)
|
||||
|
||||
# Spectral subtraction removes steady highway/HVAC rumble while preserving harmonic music peaks
|
||||
excess_power = np.maximum(0.0, power - 1.25 * self._noise_spec)
|
||||
excess_mag = np.sqrt(excess_power + 1e-12)
|
||||
excess_total = float(np.sum(excess_power[self._tonal_mask]))
|
||||
|
||||
above_floor = raw_rms >= MIN_ACTIVE_RMS and excess_total > 1e-6
|
||||
self._active_hist.append(1.0 if above_floor else 0.0)
|
||||
|
||||
# 1. Harmonic peak prominence & tonality (rejects flat broadband road/wind noise)
|
||||
tonal_p = power[self._tonal_mask]
|
||||
median_p = float(np.median(tonal_p)) + 1e-12
|
||||
# Top 8% harmonic bins vs median: music has crisp harmonic peaks (>12x), road noise is ~2-4x
|
||||
p92 = float(np.percentile(tonal_p, 92))
|
||||
peak_ratio = p92 / median_p
|
||||
peak_score = float(np.clip((math.log10(max(1.0, peak_ratio)) - 0.72) / 0.85, 0.0, 1.0))
|
||||
|
||||
geo_mean = float(np.exp(np.mean(np.log(tonal_p))))
|
||||
arith_mean = float(np.mean(tonal_p))
|
||||
flatness = geo_mean / max(arith_mean, 1e-12)
|
||||
flat_score = float(np.clip((0.56 - flatness) / 0.36, 0.0, 1.0))
|
||||
tonality_score = max(peak_score, flat_score * 0.85)
|
||||
|
||||
# 2. Musical bandwidth balance (bass + treble vs pure narrowband human speech)
|
||||
total_p = float(np.sum(power[1:])) + 1e-12
|
||||
bass_ratio = float(np.sum(power[self._bass_mask])) / total_p
|
||||
speech_ratio = float(np.sum(power[self._speech_mask])) / total_p
|
||||
treble_ratio = float(np.sum(power[self._treble_mask])) / total_p
|
||||
non_speech_ratio = bass_ratio + treble_ratio
|
||||
bandwidth_score = float(np.clip(non_speech_ratio / 0.24, 0.0, 1.0))
|
||||
narrowband_speech = speech_ratio > 0.82 and bass_ratio < 0.09 and treble_ratio < 0.06
|
||||
if narrowband_speech:
|
||||
bandwidth_score *= 0.20
|
||||
|
||||
# 3. Spectral harmonic stability (sustained musical chords/notes vs shifting speech formants)
|
||||
tonal_vec = excess_mag[self._tonal_mask]
|
||||
vec_norm = float(np.linalg.norm(tonal_vec)) + 1e-9
|
||||
norm_vec = tonal_vec / vec_norm
|
||||
if self._prev_excess_norm is not None and len(self._prev_excess_norm) == len(norm_vec):
|
||||
sim = float(np.dot(norm_vec, self._prev_excess_norm))
|
||||
self._stability_hist.append(sim)
|
||||
self._prev_excess_norm = norm_vec
|
||||
stability = float(np.mean(self._stability_hist)) if self._stability_hist else 0.0
|
||||
stability_score = float(np.clip((stability - 0.55) / 0.32, 0.0, 1.0))
|
||||
|
||||
# 4. Spectral flux & tempo periodicity (67-171 BPM)
|
||||
if self._prev_mag is None:
|
||||
flux = 0.0
|
||||
bass_flux = 0.0
|
||||
else:
|
||||
diff = np.maximum(0.0, spec - self._prev_mag)
|
||||
flux = float(np.sum(diff))
|
||||
bass_flux = float(np.sum(diff[self._bass_mask]))
|
||||
self._prev_mag = spec
|
||||
|
||||
self._flux_hist.append(flux)
|
||||
self._bass_flux_hist.append(bass_flux)
|
||||
|
||||
rhythm_score = 0.0
|
||||
if len(self._flux_hist) >= MAX_TEMPO_LAG + 10:
|
||||
arr = np.array(self._flux_hist, dtype=np.float32)
|
||||
arr_centered = arr - np.mean(arr)
|
||||
denom = float(np.dot(arr_centered, arr_centered))
|
||||
if denom > 1e-9:
|
||||
best_corr = 0.0
|
||||
best_lag = 10
|
||||
for lag in range(MIN_TEMPO_LAG, MAX_TEMPO_LAG + 1):
|
||||
c = float(np.dot(arr_centered[:-lag], arr_centered[lag:])) / denom
|
||||
if c > best_corr:
|
||||
best_corr = c
|
||||
best_lag = lag
|
||||
rhythm_score = float(np.clip((best_corr - 0.12) / 0.30, 0.0, 1.0))
|
||||
if best_corr > 0.20:
|
||||
est_bpm = (60.0 * FRAME_RATE) / best_lag
|
||||
self._bpm = 0.88 * self._bpm + 0.12 * float(np.clip(est_bpm, 72.0, 172.0))
|
||||
|
||||
beat_onset = False
|
||||
if len(self._bass_flux_hist) >= 6:
|
||||
bf_mean = float(np.mean(self._bass_flux_hist))
|
||||
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
|
||||
if bass_flux > bf_mean + 0.85 * bf_std and bass_flux > 0.008:
|
||||
beat_onset = True
|
||||
strength = float(np.clip((bass_flux - bf_mean) / (2.0 * bf_std), 0.45, 1.0))
|
||||
if self._is_music:
|
||||
self._beat_pulse = max(self._beat_pulse, strength)
|
||||
self._beat_onsets.append(self._t)
|
||||
|
||||
self._beat_locked = False
|
||||
if len(self._beat_onsets) >= BEAT_LOCK_PERIODS:
|
||||
recent = np.array(list(self._beat_onsets)[-BEAT_LOCK_PERIODS:], dtype=np.float32)
|
||||
periods = np.diff(recent)
|
||||
if periods.size and float(periods.mean()) > 1e-3:
|
||||
cv = float(periods.std() / periods.mean())
|
||||
self._beat_locked = cv <= BEAT_PERIOD_CV_TOLERANCE
|
||||
if self._beat_locked and beat_onset and self._is_music:
|
||||
self._groove_phase = 0.0
|
||||
|
||||
speech_band = float(np.sqrt(np.sum(power[self._speech_mask]) + 1e-12))
|
||||
self._speech_env.append(speech_band)
|
||||
syllabic_score = 0.0
|
||||
if len(self._speech_env) >= SYLLABIC_FRAMES:
|
||||
env = np.array(self._speech_env, dtype=np.float32)
|
||||
env = env - float(env.mean())
|
||||
if float(np.abs(env).sum()) > 1e-9:
|
||||
env_spec = np.abs(np.fft.rfft(env * np.hanning(env.size)))
|
||||
env_freqs = np.fft.rfftfreq(env.size, d=1.0 / FRAME_RATE)
|
||||
band = (env_freqs >= SYLLABIC_LOW_HZ) & (env_freqs <= SYLLABIC_HIGH_HZ)
|
||||
total_env = float(env_spec.sum()) + 1e-9
|
||||
ratio = float(env_spec[band].sum()) / total_env
|
||||
syllabic_score = float(np.clip((ratio - 0.20) / 0.45, 0.0, 1.0))
|
||||
|
||||
speech_likeness = max(syllabic_score, 0.75 if narrowband_speech else 0.0)
|
||||
|
||||
continuity = float(np.mean(self._active_hist)) if self._active_hist else 0.0
|
||||
continuity_score = float(np.clip((continuity - 0.48) / 0.40, 0.0, 1.0))
|
||||
|
||||
# Combine features: accepts both rhythmic pop/EDM/hip-hop AND harmonic acoustic/chill music,
|
||||
if not above_floor:
|
||||
frame_score = 0.0
|
||||
else:
|
||||
musical_drive = max(rhythm_score, 0.72 * stability_score)
|
||||
frame_score = (
|
||||
0.26 * tonality_score
|
||||
+ 0.24 * bandwidth_score
|
||||
+ 0.26 * musical_drive
|
||||
+ 0.16 * continuity_score
|
||||
- 0.22 * speech_likeness
|
||||
)
|
||||
frame_score = float(np.clip(frame_score, 0.0, 1.0))
|
||||
if tonality_score < 0.24 or bandwidth_score < 0.22:
|
||||
frame_score *= 0.25
|
||||
|
||||
alpha = 0.075 if frame_score > self._confidence else 0.035
|
||||
self._confidence = (1.0 - alpha) * self._confidence + alpha * frame_score
|
||||
|
||||
if self._is_music:
|
||||
self._exit_timer = self._exit_timer + dt if self._confidence <= EXIT_MUSIC_CONF else 0.0
|
||||
if self._exit_timer >= EXIT_DWELL_S:
|
||||
self._is_music = False
|
||||
self._exit_timer = 0.0
|
||||
self._enter_timer = 0.0
|
||||
self._holdoff_until = self._t + HOLDOFF_S
|
||||
elif self._t >= self._holdoff_until:
|
||||
confident = self._confidence >= ENTER_MUSIC_CONF
|
||||
eligible = confident and (self._beat_locked or self._confidence >= ENTER_MUSIC_CONF + 0.12)
|
||||
self._enter_timer = self._enter_timer + dt if eligible else 0.0
|
||||
required = ENTER_DWELL_S if self._beat_locked else ENTER_DWELL_NO_BEAT_S
|
||||
if self._enter_timer >= required:
|
||||
self._is_music = True
|
||||
self._enter_timer = 0.0
|
||||
self._exit_timer = 0.0
|
||||
|
||||
# Normalized energy & 12-band equalizer bars
|
||||
self._energy = float(np.clip(rms / 0.35, 0.0, 1.0))
|
||||
for i, (lo, hi) in enumerate(self._band_slices):
|
||||
band_mag = float(np.sqrt(np.mean(power[lo:hi])))
|
||||
tilt = 1.0 + 0.16 * i
|
||||
norm = float(np.clip(math.log1p(band_mag * 95.0 * tilt) / 2.1, 0.0, 1.0))
|
||||
if norm > self._bands[i]:
|
||||
self._bands[i] = 0.45 * self._bands[i] + 0.55 * norm
|
||||
else:
|
||||
self._bands[i] = 0.78 * self._bands[i] + 0.22 * norm
|
||||
|
||||
return self.state
|
||||
@@ -1,127 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState, NUM_BANDS
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
|
||||
|
||||
def groove_prism_color(t: float) -> tuple[int, int, int]:
|
||||
"""Smoothly cycle vibrant OLED-friendly cyan -> aqua -> orchid -> mint hues while grooving."""
|
||||
# Smooth cosine palette keeping high brightness and pleasant saturation
|
||||
r = int(125 + 95 * math.sin(t * 0.9 + 2.2))
|
||||
g = int(195 + 55 * math.sin(t * 0.9 + 0.4))
|
||||
b = int(215 + 40 * math.sin(t * 0.9 + 4.1))
|
||||
return (max(50, min(255, r)), max(90, min(255, g)), max(140, min(255, b)))
|
||||
|
||||
|
||||
class MusicVisualizerRenderer:
|
||||
"""Smooth 60 FPS OLED equalizer bars, bass pulse aura, and floating musical notes."""
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._alpha = FirstOrderFilter(0.0, 0.16, dt)
|
||||
self._bar_filters = [FirstOrderFilter(0.0, 0.06, dt) for _ in range(NUM_BANDS)]
|
||||
|
||||
def render_background(self, rect: rl.Rectangle, music: MusicState, active: bool) -> float:
|
||||
"""Render smooth ambient bass aura & bottom pill equalizer bars; returns current visualizer alpha."""
|
||||
alpha = self._alpha.update(1.0 if active else 0.0)
|
||||
if alpha < 0.01:
|
||||
return 0.0
|
||||
|
||||
t = rl.get_time()
|
||||
cr, cg, cb = groove_prism_color(t)
|
||||
|
||||
# 1. Soft beat-reactive ambient bass aura along bottom center
|
||||
aura_r = 140.0 + 75.0 * music.beat_pulse + 35.0 * music.energy
|
||||
aura_alpha = int((42 + 52 * music.beat_pulse) * alpha)
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(rect.x + rect.width / 2.0, rect.y + rect.height + 10.0),
|
||||
aura_r,
|
||||
rl.Color(cr, cg, cb, aura_alpha),
|
||||
rl.Color(cr, cg, cb, 0),
|
||||
)
|
||||
|
||||
# 2. Smooth 12-band symmetric pill equalizer along the bottom edge
|
||||
bar_count = NUM_BANDS
|
||||
total_w = rect.width - 76.0
|
||||
gap = 10.0
|
||||
bar_w = (total_w - gap * (bar_count - 1)) / bar_count
|
||||
start_x = rect.x + (rect.width - total_w) / 2.0
|
||||
base_y = rect.y + rect.height - 8.0
|
||||
max_bar_h = 44.0
|
||||
|
||||
for i in range(bar_count):
|
||||
raw_level = music.bands[i] if i < len(music.bands) else 0.0
|
||||
# Keep a smooth living wave + subtle beat lift on bass/mid bars
|
||||
wave = 0.14 + 0.10 * math.sin(t * 5.0 + i * 0.65)
|
||||
beat_lift = music.beat_pulse * (0.28 if i < 6 else 0.16)
|
||||
level = self._bar_filters[i].update(min(1.0, max(wave, raw_level + beat_lift)))
|
||||
bar_h = max(8.0, level * max_bar_h)
|
||||
|
||||
bx = start_x + i * (bar_w + gap)
|
||||
by = base_y - bar_h
|
||||
|
||||
# Subtle color gradient across the spectrum (cyan -> violet -> pink)
|
||||
frac = i / max(1, bar_count - 1)
|
||||
br = int(min(255, cr * (1.0 - frac * 0.25) + 255 * frac * 0.25))
|
||||
bg = int(min(255, cg * (1.0 - frac * 0.30) + 120 * frac * 0.30))
|
||||
bb = int(min(255, cb * 0.85 + 255 * 0.15))
|
||||
|
||||
# Soft glow cap on taller bars
|
||||
if level > 0.35:
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(bx + bar_w / 2.0, by + 4.0),
|
||||
bar_w * 1.15,
|
||||
rl.Color(br, bg, bb, int(75 * level * alpha)),
|
||||
rl.Color(br, bg, bb, 0),
|
||||
)
|
||||
|
||||
bar_col = rl.Color(br, bg, bb, int((155 + 90 * level) * alpha))
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(bx, by, bar_w, bar_h), 0.9, 10, bar_col)
|
||||
|
||||
return alpha
|
||||
|
||||
def render_foreground_notes(self, rect: rl.Rectangle, music: MusicState, alpha: float) -> None:
|
||||
"""Draw cute floating vector musical notes on the left and right edges while grooving."""
|
||||
if alpha < 0.05:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
cr, cg, cb = groove_prism_color(t + 1.2)
|
||||
note_specs = (
|
||||
(rect.x + 48.0, 0.0, 1.0),
|
||||
(rect.x + rect.width - 48.0, 0.5, -1.0),
|
||||
(rect.x + 82.0, 0.28, 0.8),
|
||||
(rect.x + rect.width - 82.0, 0.76, -0.8),
|
||||
)
|
||||
|
||||
for base_x, phase_off, sway_dir in note_specs:
|
||||
phase = (t * 0.65 + phase_off) % 1.0
|
||||
fade = math.sin(phase * math.pi)
|
||||
nx = base_x + math.sin(phase * math.tau) * 10.0 * sway_dir
|
||||
ny = rect.y + 150.0 - phase * 98.0
|
||||
scale = 0.85 + 0.25 * music.beat_pulse
|
||||
col = rl.Color(cr, cg, cb, int(215 * fade * alpha))
|
||||
self._draw_eighth_note(nx, ny, 7.5 * scale, col)
|
||||
|
||||
def _draw_eighth_note(self, cx: float, cy: float, r: float, color: rl.Color) -> None:
|
||||
"""Crisp vector eighth-note glyph (♪) — zero font dependency."""
|
||||
rl.draw_circle(int(cx), int(cy), r * 0.72, color)
|
||||
stem_x = cx + r * 0.58
|
||||
stem_top = cy - r * 2.5
|
||||
rl.draw_line_ex(rl.Vector2(stem_x, cy), rl.Vector2(stem_x, stem_top), 2.8, color)
|
||||
# Curved flag
|
||||
rl.draw_line_ex(
|
||||
rl.Vector2(stem_x, stem_top),
|
||||
rl.Vector2(stem_x + r * 1.15, stem_top + r * 0.95),
|
||||
2.8,
|
||||
color,
|
||||
)
|
||||
@@ -1,214 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import BookmarkIcon
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.alert_overlay import RoboticAlertOverlay
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
RoboticMood,
|
||||
RoboticMoodEngine,
|
||||
snapshot_from_ui_state,
|
||||
)
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.face_renderer import ProceduralFaceRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicAnalyzer, MusicState
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import MusicVisualizerRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.speed_arc_renderer import SpeedArcRenderer
|
||||
from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state
|
||||
from openpilot.system.ui.lib.application import (
|
||||
FontWeight,
|
||||
MouseEvent,
|
||||
MousePos,
|
||||
TextAlignment,
|
||||
TextAlignmentVertical,
|
||||
gui_app,
|
||||
)
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
VERTICAL_SWIPE_THRESHOLD = 45.0 # px
|
||||
|
||||
|
||||
class RoboticOnroadView(Widget):
|
||||
"""Full-screen EMO-inspired Robotic Companion onroad view for MICI (536x240 @ 60 FPS)."""
|
||||
|
||||
def __init__(self, bookmark_callback=None):
|
||||
super().__init__()
|
||||
self._bookmark_callback = bookmark_callback
|
||||
|
||||
self._mood_engine = RoboticMoodEngine(params=getattr(ui_state, "params", None))
|
||||
self._face_renderer = ProceduralFaceRenderer()
|
||||
self._speed_renderer = SpeedArcRenderer()
|
||||
self._alert_overlay = RoboticAlertOverlay()
|
||||
self._music_analyzer = MusicAnalyzer()
|
||||
self._music_visualizer = MusicVisualizerRenderer()
|
||||
|
||||
self._bookmark_icon = BookmarkIcon(self._on_bookmark_triggered)
|
||||
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._speed_blend = FirstOrderFilter(0.0, 0.08, dt)
|
||||
|
||||
# Vertical swipe tracking (up = speed peek, down = pet robot)
|
||||
self._touch_start_y: float = 0.0
|
||||
self._touch_start_x: float = 0.0
|
||||
self._vertical_swipe_handled: bool = False
|
||||
|
||||
self._offroad_label = UnifiedLabel(
|
||||
"start the car to\nuse sunnypilot",
|
||||
54,
|
||||
FontWeight.DISPLAY,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
|
||||
alignment=TextAlignment.CENTER,
|
||||
alignment_vertical=TextAlignmentVertical.MIDDLE,
|
||||
)
|
||||
|
||||
def _on_bookmark_triggered(self) -> None:
|
||||
self._mood_engine.trigger_love(wink=True)
|
||||
if self._bookmark_callback is not None:
|
||||
self._bookmark_callback()
|
||||
|
||||
def is_swiping_left(self) -> bool:
|
||||
"""Match AugmentedRoadView API so MiciMainLayout disables horizontal scroller during bookmark swipe."""
|
||||
return self._bookmark_icon.is_swiping_left()
|
||||
|
||||
def _update_state(self) -> None:
|
||||
super()._update_state()
|
||||
if ui_state.panda_type == log.PandaState.PandaType.unknown:
|
||||
self._offroad_label.set_text("system booting")
|
||||
elif ui_state.ignition and not ui_state.started:
|
||||
self._offroad_label.set_text("openpilot can't start\ncheck alerts")
|
||||
else:
|
||||
self._offroad_label.set_text("start the car to\nuse sunnypilot")
|
||||
|
||||
def _handle_mouse_event(self, mouse_event: MouseEvent) -> None:
|
||||
if ui_state.started:
|
||||
if mouse_event.left_pressed:
|
||||
self._touch_start_x = mouse_event.pos.x
|
||||
self._touch_start_y = mouse_event.pos.y
|
||||
self._vertical_swipe_handled = False
|
||||
elif mouse_event.left_down and not self._vertical_swipe_handled:
|
||||
dx = abs(mouse_event.pos.x - self._touch_start_x)
|
||||
dy = mouse_event.pos.y - self._touch_start_y
|
||||
if abs(dy) > VERTICAL_SWIPE_THRESHOLD and abs(dy) > dx * 1.4:
|
||||
self._vertical_swipe_handled = True
|
||||
if dy < 0:
|
||||
self._mood_engine.trigger_speed_peek()
|
||||
else:
|
||||
self._mood_engine.trigger_love()
|
||||
|
||||
self._bookmark_icon._handle_mouse_event(mouse_event)
|
||||
super()._handle_mouse_event(mouse_event)
|
||||
|
||||
def _handle_mouse_release(self, mouse_pos: MousePos) -> None:
|
||||
if self._vertical_swipe_handled:
|
||||
self._vertical_swipe_handled = False
|
||||
return
|
||||
if not self._bookmark_icon.interacting():
|
||||
super()._handle_mouse_release(mouse_pos)
|
||||
|
||||
def _render(self, _) -> None:
|
||||
rl.draw_rectangle_rec(self.rect, rl.BLACK)
|
||||
|
||||
if not ui_state.started:
|
||||
# Keep subtle animated sleepy eyes behind the offroad message so the screen is never static
|
||||
sleepy_snap = DrivingSnapshot(started=False, standstill=True)
|
||||
eye_target = self._mood_engine.update(sleepy_snap)
|
||||
self._face_renderer.render(self.rect, eye_target, alpha=0.28, y_shift=16.0)
|
||||
self._offroad_label.render(self._rect)
|
||||
return
|
||||
|
||||
alert = self._alert_overlay.get_alert()
|
||||
if ui_state.sm.updated["rawAudioData"] and alert is None:
|
||||
raw_audio = ui_state.sm["rawAudioData"]
|
||||
self._music_analyzer.process_audio_bytes(raw_audio.data, int(raw_audio.sampleRate))
|
||||
music_state = self._music_analyzer.step_visual_decay(1.0 / max(gui_app.target_fps, 1))
|
||||
|
||||
snap = snapshot_from_ui_state(ui_state, alert)
|
||||
snap.music = music_state
|
||||
self._render_from_snapshot(snap, alert)
|
||||
|
||||
self._bookmark_icon.render(self.rect)
|
||||
|
||||
def _render_from_snapshot(self, snap: DrivingSnapshot, alert) -> None:
|
||||
eye_target = self._mood_engine.update(snap)
|
||||
speed_alpha = self._speed_blend.update(1.0 if self._mood_engine.showing_speed else 0.0)
|
||||
face_alpha = 1.0 - speed_alpha
|
||||
|
||||
# Shift eyes slightly upward when a bottom alert banner or music equalizer is visible
|
||||
grooving = self._mood_engine.mood == RoboticMood.MUSIC_GROOVE and alert is None
|
||||
alert_shift = -26.0 if alert is not None else (-14.0 if grooving else 0.0)
|
||||
music_state = snap.music or MusicState()
|
||||
|
||||
viz_alpha = 0.0
|
||||
if face_alpha > 0.01:
|
||||
viz_alpha = self._music_visualizer.render_background(self.rect, music_state, active=grooving)
|
||||
self._face_renderer.render(self.rect, eye_target, alpha=face_alpha, y_shift=alert_shift)
|
||||
if viz_alpha > 0.05:
|
||||
self._music_visualizer.render_foreground_notes(self.rect, music_state, alpha=viz_alpha * face_alpha)
|
||||
if alert is None:
|
||||
self._speed_renderer.render_corner_badge(self.rect, snap, alpha=face_alpha)
|
||||
|
||||
if speed_alpha > 0.01:
|
||||
self._speed_renderer.render_speed_mode(
|
||||
self.rect,
|
||||
snap,
|
||||
alpha=speed_alpha,
|
||||
cruising_smoothly=self._mood_engine.cruising_smoothly,
|
||||
reason=self._mood_engine.speed_reason,
|
||||
)
|
||||
|
||||
self._alert_overlay.render(self.rect, alert)
|
||||
|
||||
def show_event(self) -> None:
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME)
|
||||
|
||||
def hide_event(self) -> None:
|
||||
if gui_app.sunnypilot_ui():
|
||||
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
|
||||
gui_app.init_window("MICI Robotic Companion Preview")
|
||||
view = RoboticOnroadView()
|
||||
view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
|
||||
|
||||
print("Keys: [1] Engaged [2] MADS [3] Disengaged [4] Speed Peek [5] Stars [6] Love [7] Prompt [8] Critical [9] Pout [Left/Right] Steer")
|
||||
for _ in gui_app.render():
|
||||
if rl.is_key_pressed(rl.KeyboardKey.KEY_ONE):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_TWO):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=20.0, set_speed_kph=90.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_THREE):
|
||||
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FOUR):
|
||||
view._mood_engine.trigger_speed_peek()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FIVE):
|
||||
view._mood_engine.trigger_startled()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SIX):
|
||||
view._mood_engine.trigger_love()
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SEVEN):
|
||||
snap.alert = Alert("Pay Attention", "Eyes on road", status=log.SelfdriveState.AlertStatus.userPrompt)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_EIGHT):
|
||||
snap.alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=log.SelfdriveState.AlertStatus.critical)
|
||||
elif rl.is_key_pressed(rl.KeyboardKey.KEY_NINE):
|
||||
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
|
||||
elif rl.is_key_down(rl.KeyboardKey.KEY_LEFT):
|
||||
snap.steering_angle_deg = 30.0
|
||||
elif rl.is_key_down(rl.KeyboardKey.KEY_RIGHT):
|
||||
snap.steering_angle_deg = -30.0
|
||||
else:
|
||||
snap.steering_angle_deg = 0.0
|
||||
|
||||
rl.draw_rectangle_rec(view.rect, rl.BLACK)
|
||||
view._render_from_snapshot(snap, snap.alert)
|
||||
@@ -1,218 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import raylib_nb as rl
|
||||
|
||||
from openpilot.common.filter_simple import BounceFilter
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
|
||||
DrivingSnapshot,
|
||||
PALETTE,
|
||||
display_speed_and_set_speed,
|
||||
)
|
||||
from openpilot.selfdrive.ui.ui_state import UIStatus
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
|
||||
|
||||
class SpeedArcRenderer:
|
||||
"""Reference-video-inspired color-coded speed + curved arc gauge and subtle Set-Speed badge."""
|
||||
|
||||
SPEED_FONT_SIZE = 114
|
||||
UNIT_FONT_SIZE = 24
|
||||
BADGE_SPEED_FONT_SIZE = 32
|
||||
|
||||
def __init__(self):
|
||||
dt = 1.0 / max(gui_app.target_fps, 1)
|
||||
self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY)
|
||||
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
|
||||
self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM)
|
||||
self._arc_progress = BounceFilter(0.0, 0.11, dt, bounce=2.4)
|
||||
|
||||
def _speed_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
|
||||
if snap.status == UIStatus.OVERRIDE or snap.a_ego > 1.8:
|
||||
return (255, 205, 65) # Warm yellow/amber
|
||||
if snap.status == UIStatus.ENGAGED:
|
||||
return (85, 238, 150) # Vibrant green
|
||||
if snap.status == UIStatus.LAT_ONLY:
|
||||
return PALETTE["lat_only"]
|
||||
return (240, 245, 255) # Crisp white
|
||||
|
||||
def render_speed_mode(
|
||||
self,
|
||||
rect: rl.Rectangle,
|
||||
snap: DrivingSnapshot,
|
||||
alpha: float,
|
||||
cruising_smoothly: bool,
|
||||
reason: str,
|
||||
) -> None:
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
cur_speed, set_speed = display_speed_and_set_speed(snap)
|
||||
sr, sg, sb = self._speed_color(snap)
|
||||
speed_color = rl.Color(sr, sg, sb, int(255 * alpha))
|
||||
sub_color = rl.Color(255, 255, 255, int(195 * alpha))
|
||||
|
||||
cx = rect.x + rect.width / 2.0
|
||||
# Subtle breathing float so speed mode is alive and never frozen
|
||||
float_y = math.sin(t * 2.2) * 2.0
|
||||
|
||||
# Top accent above speed: MAX set-speed pill or gently pulsing heart
|
||||
if reason == "set_speed" and set_speed is not None:
|
||||
pill_text = f"{tr('MAX')} {set_speed}"
|
||||
pill_sz = measure_text_cached(self._font_semi_bold, pill_text, 26)
|
||||
pill_w = pill_sz.x + 28
|
||||
pill_h = 34
|
||||
pill_rect = rl.Rectangle(cx - pill_w / 2.0, rect.y + 14 + float_y * 0.5, pill_w, pill_h)
|
||||
rl.draw_rectangle_rounded(pill_rect, 0.5, 14, rl.Color(sr, sg, sb, int(48 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill_rect, 0.5, 14, 2.0, rl.Color(sr, sg, sb, int(180 * alpha)))
|
||||
rl.draw_text_ex(
|
||||
self._font_semi_bold,
|
||||
pill_text,
|
||||
rl.Vector2(cx - pill_sz.x / 2.0, pill_rect.y + (pill_h - pill_sz.y) / 2.0),
|
||||
26,
|
||||
0,
|
||||
speed_color,
|
||||
)
|
||||
elif cruising_smoothly:
|
||||
heart_r = 10.0 * (1.0 + 0.10 * math.sin(t * 4.5))
|
||||
self._draw_tiny_heart(cx, rect.y + 30 + float_y * 0.5, heart_r, rl.Color(255, 118, 168, int(240 * alpha)))
|
||||
elif set_speed is not None:
|
||||
max_lbl = f"{tr('MAX')} {set_speed}"
|
||||
lbl_sz = measure_text_cached(self._font_medium, max_lbl, self.UNIT_FONT_SIZE)
|
||||
rl.draw_text_ex(
|
||||
self._font_medium,
|
||||
max_lbl,
|
||||
rl.Vector2(cx - lbl_sz.x / 2.0, rect.y + 18 + float_y * 0.5),
|
||||
self.UNIT_FONT_SIZE,
|
||||
0,
|
||||
sub_color,
|
||||
)
|
||||
|
||||
# Big centered speed number
|
||||
speed_text = str(cur_speed)
|
||||
speed_sz = measure_text_cached(self._font_display, speed_text, self.SPEED_FONT_SIZE)
|
||||
speed_y = rect.y + rect.height / 2.0 - speed_sz.y / 2.0 - 8.0 + float_y
|
||||
rl.draw_text_ex(
|
||||
self._font_display,
|
||||
speed_text,
|
||||
rl.Vector2(cx - speed_sz.x / 2.0, speed_y),
|
||||
self.SPEED_FONT_SIZE,
|
||||
0,
|
||||
speed_color,
|
||||
)
|
||||
|
||||
# Unit beside speed (small & subtle)
|
||||
unit_text = tr("km/h") if snap.is_metric else tr("mph")
|
||||
rl.draw_text_ex(
|
||||
self._font_medium,
|
||||
unit_text,
|
||||
rl.Vector2(cx + speed_sz.x / 2.0 + 10.0, speed_y + speed_sz.y - 34.0),
|
||||
self.UNIT_FONT_SIZE,
|
||||
0,
|
||||
rl.Color(255, 255, 255, int(150 * alpha)),
|
||||
)
|
||||
|
||||
# Curved arc speedometer gauge underneath (matches reference video)
|
||||
max_ref = float(set_speed) if (set_speed is not None and set_speed > 0) else (130.0 if snap.is_metric else 85.0)
|
||||
raw_frac = max(0.0, min(1.0, cur_speed / max_ref))
|
||||
frac = max(0.0, min(1.0, self._arc_progress.update(raw_frac)))
|
||||
|
||||
arc_center = rl.Vector2(cx, rect.y + rect.height + 74.0)
|
||||
inner_r = 104.0
|
||||
outer_r = 114.0
|
||||
mid_r = (inner_r + outer_r) / 2.0
|
||||
cap_r = (outer_r - inner_r) / 2.0
|
||||
start_deg = 228.0
|
||||
end_deg = 312.0
|
||||
span_deg = end_deg - start_deg
|
||||
|
||||
# Track background arc with rounded caps
|
||||
track_col = rl.Color(255, 255, 255, int(45 * alpha))
|
||||
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, end_deg, 32, track_col)
|
||||
for deg in (start_deg, end_deg):
|
||||
rad = math.radians(deg)
|
||||
rl.draw_circle(int(arc_center.x + math.cos(rad) * mid_r), int(arc_center.y + math.sin(rad) * mid_r), cap_r, track_col)
|
||||
|
||||
# Active glowing arc + bright animated tip pip
|
||||
if frac > 0.01:
|
||||
active_end = start_deg + span_deg * frac
|
||||
glow_pulse = 0.78 + 0.22 * math.sin(t * 3.5)
|
||||
rl.draw_ring(
|
||||
arc_center,
|
||||
inner_r - 4.0,
|
||||
outer_r + 4.0,
|
||||
start_deg,
|
||||
active_end,
|
||||
32,
|
||||
rl.Color(sr, sg, sb, int(65 * glow_pulse * alpha)),
|
||||
)
|
||||
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, active_end, 32, speed_color)
|
||||
|
||||
# Rounded start cap & bright glowing tip pip
|
||||
s_rad = math.radians(start_deg)
|
||||
e_rad = math.radians(active_end)
|
||||
rl.draw_circle(int(arc_center.x + math.cos(s_rad) * mid_r), int(arc_center.y + math.sin(s_rad) * mid_r), cap_r, speed_color)
|
||||
tip_x = arc_center.x + math.cos(e_rad) * mid_r
|
||||
tip_y = arc_center.y + math.sin(e_rad) * mid_r
|
||||
rl.draw_circle_gradient(
|
||||
rl.Vector2(tip_x, tip_y),
|
||||
14.0,
|
||||
rl.Color(255, 255, 255, int(140 * glow_pulse * alpha)),
|
||||
rl.Color(sr, sg, sb, 0),
|
||||
)
|
||||
rl.draw_circle(int(tip_x), int(tip_y), cap_r + 1.5, rl.Color(255, 255, 255, int(235 * alpha)))
|
||||
|
||||
def render_corner_badge(self, rect: rl.Rectangle, snap: DrivingSnapshot, alpha: float) -> None:
|
||||
"""Subtle top-left Set-Speed / engagement pill visible during normal hero-face mode."""
|
||||
if alpha < 0.01:
|
||||
return
|
||||
|
||||
t = rl.get_time()
|
||||
_, set_speed = display_speed_and_set_speed(snap)
|
||||
sr, sg, sb = self._speed_color(snap)
|
||||
dot_pulse = 0.72 + 0.28 * math.sin(t * 3.0)
|
||||
|
||||
x = rect.x + 16.0
|
||||
y = rect.y + 12.0
|
||||
|
||||
if set_speed is not None:
|
||||
text = str(set_speed)
|
||||
sz = measure_text_cached(self._font_semi_bold, text, self.BADGE_SPEED_FONT_SIZE)
|
||||
pill_w = sz.x + 48.0
|
||||
pill_h = 38.0
|
||||
pill_rec = rl.Rectangle(x, y, pill_w, pill_h)
|
||||
rl.draw_rectangle_rounded(pill_rec, 0.5, 14, rl.Color(255, 255, 255, int(22 * alpha)))
|
||||
rl.draw_rectangle_rounded_lines_ex(pill_rec, 0.5, 14, 1.5, rl.Color(255, 255, 255, int(35 * alpha)))
|
||||
rl.draw_circle(int(x + 16), int(y + pill_h / 2.0), 5.0, rl.Color(sr, sg, sb, int(235 * dot_pulse * alpha)))
|
||||
rl.draw_text_ex(
|
||||
self._font_semi_bold,
|
||||
text,
|
||||
rl.Vector2(x + 28.0, y + (pill_h - sz.y) / 2.0),
|
||||
self.BADGE_SPEED_FONT_SIZE,
|
||||
0,
|
||||
rl.Color(255, 255, 255, int(210 * alpha)),
|
||||
)
|
||||
else:
|
||||
rl.draw_circle(int(x + 10), int(y + 12), 5.5, rl.Color(sr, sg, sb, int(200 * dot_pulse * alpha)))
|
||||
|
||||
def _draw_tiny_heart(self, cx: float, cy: float, radius: float, color: rl.Color) -> None:
|
||||
scale = radius / 16.0
|
||||
n_pts = 32
|
||||
pts: list[rl.Vector2] = []
|
||||
for i in range(n_pts):
|
||||
ang = (i / n_pts) * math.tau
|
||||
s = math.sin(ang)
|
||||
hx = 16.0 * (s * s * s)
|
||||
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
|
||||
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
|
||||
center = rl.Vector2(cx, cy + radius * 0.05)
|
||||
fan = [center, *reversed(pts), pts[-1]]
|
||||
rl.draw_triangle_fan(fan, len(fan), color)
|
||||
@@ -44,8 +44,7 @@ class UIStateSP:
|
||||
self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch")
|
||||
self.sm_services_ext = [
|
||||
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
|
||||
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP",
|
||||
"gyroscope",
|
||||
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP"
|
||||
]
|
||||
|
||||
self.sunnylink_state = SunnylinkState()
|
||||
@@ -61,7 +60,6 @@ class UIStateSP:
|
||||
self.custom_interactive_timeout: int = 0
|
||||
self.developer_ui = None
|
||||
self.hide_v_ego_ui: bool = False
|
||||
self.mici_robotic_ui: bool = self.params.get_bool("MiciRoboticUI")
|
||||
self.onroad_brightness: int = 0
|
||||
self.onroad_brightness_timer: int = 0
|
||||
self.onroad_brightness_timer_param: int = 0
|
||||
@@ -186,7 +184,6 @@ class UIStateSP:
|
||||
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
|
||||
self.developer_ui = self.params.get("DevUIInfo")
|
||||
self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI")
|
||||
self.mici_robotic_ui = self.params.get_bool("MiciRoboticUI")
|
||||
self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True)))
|
||||
self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True)
|
||||
self.rainbow_path = self.params.get_bool("RainbowMode")
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import wave
|
||||
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.cereal.messaging import SubMaster, PubMaster
|
||||
from openpilot.selfdrive.ui.soundd import SAMPLE_RATE, SELFDRIVE_STATE_TIMEOUT, Soundd, check_selfdrive_timeout_alert
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import ROBOTIC_SOUND_FILES, ROBOTIC_SOUNDS_DIR, RoboticSoundPack
|
||||
from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
|
||||
@@ -59,87 +56,4 @@ class TestSoundd(OpenpilotTestCase):
|
||||
|
||||
assert check_selfdrive_timeout_alert(sm)
|
||||
|
||||
def test_robotic_sound_pack_wav_formats(self):
|
||||
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
|
||||
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
|
||||
assert os.path.exists(path), f"Missing robotic sound for {alert_id}: {path}"
|
||||
with wave.open(path, "r") as wf:
|
||||
assert wf.getnchannels() == 1, f"{filename} must be mono"
|
||||
assert wf.getsampwidth() == 2, f"{filename} must be 16-bit PCM"
|
||||
assert wf.getframerate() == SAMPLE_RATE, f"{filename} must be {SAMPLE_RATE} Hz"
|
||||
assert wf.getnframes() > 0, f"{filename} must not be empty"
|
||||
|
||||
def test_robotic_sound_pack_switching_and_quiet_mode(self):
|
||||
class _FakeParams:
|
||||
def __init__(self):
|
||||
self.vals = {"MiciRoboticUI": False, "QuietMode": False}
|
||||
|
||||
def get_bool(self, key: str) -> bool:
|
||||
return self.vals.get(key, False)
|
||||
|
||||
fake_params = _FakeParams()
|
||||
pack = RoboticSoundPack(fake_params, SAMPLE_RATE)
|
||||
pack.load()
|
||||
assert set(ROBOTIC_SOUND_FILES).issubset(pack.sounds)
|
||||
|
||||
soundd = Soundd.__new__(Soundd)
|
||||
soundd.params = fake_params
|
||||
soundd.enabled = False
|
||||
soundd._frame = 0
|
||||
soundd.robotic_sound_pack = pack
|
||||
soundd.load_sounds()
|
||||
soundd.current_alert = AudibleAlert.engage
|
||||
soundd.current_volume = 1.0
|
||||
soundd.current_sound_frame = 0
|
||||
soundd.pending_stop = False
|
||||
|
||||
# Default buffer used when MiciRoboticUI is False
|
||||
buf_default = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
|
||||
assert buf_default is soundd.loaded_sounds[AudibleAlert.engage]
|
||||
|
||||
# Switching MiciRoboticUI to True swaps buffer to robotic sound
|
||||
fake_params.vals["MiciRoboticUI"] = True
|
||||
assert pack.refresh_param() is True
|
||||
buf_robotic = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
|
||||
assert buf_robotic is pack.sounds[AudibleAlert.engage]
|
||||
assert buf_robotic is not buf_default
|
||||
|
||||
# QuietMode still suppresses non-critical robotic engage chirp
|
||||
soundd.enabled = True
|
||||
assert not soundd.should_play_sound(AudibleAlert.engage)
|
||||
assert soundd.should_play_sound(AudibleAlert.warningImmediateUser)
|
||||
assert soundd.should_play_sound(AudibleAlert.warningImmediateSystem)
|
||||
|
||||
def test_robotic_sound_pack_lfs_fallback_and_reactive_chirps(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import (
|
||||
CHIRP_BOOST,
|
||||
CHIRP_SPEED_UP,
|
||||
CHIRP_STARTLED,
|
||||
REACTIVE_CHIRP_IDS,
|
||||
)
|
||||
|
||||
class _FakeParams:
|
||||
def get_bool(self, key: str) -> bool:
|
||||
return key == "MiciRoboticUI"
|
||||
|
||||
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
|
||||
pack.load()
|
||||
for cid in REACTIVE_CHIRP_IDS:
|
||||
assert cid in pack.sounds and len(pack.sounds[cid]) > 0
|
||||
|
||||
class _FakeSM:
|
||||
def __init__(self, v_cruise=100.0, a_ego=0.0):
|
||||
self.updated = {"carState": True, "userBookmark": False, "bookmarkButton": False}
|
||||
self.valid = {"controlsState": False}
|
||||
self._cs = SimpleNamespace(vCruiseCluster=v_cruise, leftBlinker=False, rightBlinker=False, standstill=False, aEgo=a_ego)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self._cs
|
||||
|
||||
assert pack.detect_reactive_chirp(_FakeSM(100.0, 0.0), now=10.0) is None # first sample seeds prev_set_speed
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, 0.0), now=11.0) == CHIRP_SPEED_UP
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, -3.5), now=12.0) == CHIRP_STARTLED
|
||||
assert pack.detect_reactive_chirp(_FakeSM(110.0, 2.6), now=13.0) == CHIRP_BOOST
|
||||
|
||||
# TODO: add test with micd for checking that soundd actually outputs sounds
|
||||
|
||||
@@ -18,12 +18,6 @@ MIN_SPEED = 5.0 # m/s
|
||||
LINE_STD = (0.2, 0.6)
|
||||
POINT_STD = 0.1
|
||||
YIELD = (0.2, 0.45)
|
||||
CURVE_ACCEL = (0.3, 0.9) # m/s^2, lane curvature lateral accel for full curve authority
|
||||
PLAN_SHARE_CURVE = 0.65 # plan y share at full curve authority; straights keep the 0.3-0.5 ramp
|
||||
MANEUVER_OFFSET = (0.55, 0.75) # m, |plan offset from usual| where extra curve authority is withheld
|
||||
TRUST_RISE = (1.5, 0.6) # s, trust recovery time on straights and in curves
|
||||
MAX_ADDED_LAT_ACCEL = 1.0 # m/s^2, cap on Blendful's own curvature contribution
|
||||
DK_RATE = 1e-3 # 1/(m*s), max dk change per second while trust falls
|
||||
X_IDXS = np.array(ModelConstants.X_IDXS)
|
||||
|
||||
|
||||
@@ -44,10 +38,6 @@ class Blendful:
|
||||
self.model_curvature = 0.0
|
||||
self.smooth = 0.0 # smooths the correction target below .53 lat accel
|
||||
self.curvature = 0.0
|
||||
self.lane_curvature = 0.0
|
||||
self.curve_gate = 0.0
|
||||
self.maneuver_free = 1.0
|
||||
self.plan_share = 0.0
|
||||
|
||||
def update(self, model_output: dict[str, np.ndarray], v_ego: float, active: bool, model_curvature: float, enabled: bool = True) -> float:
|
||||
self.l_prob = self.r_prob = 0.0
|
||||
@@ -63,14 +53,11 @@ class Blendful:
|
||||
self.lane_width.initialized = False
|
||||
self.going_around = False
|
||||
target = 0.0 if fading else self._target(model_output, v_ego, model_curvature)
|
||||
curve_lat_accel = max(abs(model_curvature), abs(self.lane_curvature)) * v_ego ** 2
|
||||
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(curve_lat_accel, [0.18, 0.53], [0.5, 0.0]))
|
||||
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 0.0]))
|
||||
build = 0.5 / max(v_ego, 1.0) ** 2 * DT_MDL # jerk over 1 second
|
||||
release = (0.5 if fading else 2.0) / max(v_ego, 1.0) ** 2 * DT_MDL # lets go fast, but past zero it builds like any other pull
|
||||
k = self.curvature
|
||||
self.curvature = float(np.clip(target, max(k - release, -build) if k > 0 else k - build, min(k + release, build) if k < 0 else k + build))
|
||||
cap = MAX_ADDED_LAT_ACCEL / max(v_ego, 1.0) ** 2
|
||||
self.curvature = float(np.clip(self.curvature, -cap, cap))
|
||||
return self.curvature
|
||||
|
||||
def _target(self, model_output: dict[str, np.ndarray], v_ego: float, model_curvature: float) -> float:
|
||||
@@ -118,6 +105,12 @@ class Blendful:
|
||||
center = (r_var * (lines[1, win] + half_width) + l_var * (lines[2, win] - half_width)) / (l_var + r_var)
|
||||
weight = 1.0 / (l_var * r_var / (l_var + r_var) + POINT_STD ** 2)
|
||||
|
||||
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
|
||||
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
|
||||
plan_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
|
||||
error = np.clip(center - ((1 - plan_share) * model_curvature * x ** 2 / 2 + plan_share * plan_x), -1.0, 1.0)
|
||||
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
|
||||
|
||||
# A model planning to end up further from its usual spot in the lane than the plant is now is likely going around something
|
||||
hw_now = np.clip(lines[2, 0] - lines[1, 0], *LANE_WIDTH_CLIP) / 2 if l_prob * r_prob > 0.5 else self.lane_width.x / 2
|
||||
center_now = (l_prob * (lines[1, 0] + hw_now) + r_prob * (lines[2, 0] - hw_now)) / (l_prob + r_prob)
|
||||
@@ -140,29 +133,13 @@ class Blendful:
|
||||
self.usual_offset.update_alpha(20.0 if self.going_around else 10.0)
|
||||
self.usual_offset.update(offset)
|
||||
|
||||
# Curves seen by the lane fit, not only by the model's own curvature (which can under-read a curve it is cutting).
|
||||
self.lane_curvature = float(lane_curvature)
|
||||
self.curve_gate = float(np.interp(abs(lane_curvature) * v_ego ** 2, CURVE_ACCEL, [0.0, 1.0]))
|
||||
# Hold the extra curve authority while the model is settled in its lane. A large deviation from its usual spot is a maneuver.
|
||||
self.maneuver_free = 0.0 if self.going_around else float(np.interp(abs(offset - usual), MANEUVER_OFFSET, [1.0, 0.0]))
|
||||
|
||||
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
|
||||
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
|
||||
base_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
|
||||
self.plan_share = base_share + (PLAN_SHARE_CURVE - base_share) * self.curve_gate * self.maneuver_free
|
||||
error = np.clip(center - ((1 - self.plan_share) * model_curvature * x ** 2 / 2 + self.plan_share * plan_x), -1.0, 1.0)
|
||||
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
|
||||
|
||||
if inside_curve:
|
||||
lane_trust *= np.interp(abs(offset) - abs(center_now) - 0.25 * abs(model_curvature) * lookahead ** 2 / 2, (0.5, 1.0), [1.0, 0.0])
|
||||
else:
|
||||
lane_trust *= np.interp(swerve, (YIELD[0] / 2, YIELD[0]), [1.0, 0.0]) if self.going_around else np.interp(away, YIELD, [1.0, 0.0])
|
||||
|
||||
# While trust falls, move dk at a bounded rate instead of clipping it to its previous sign. The old clip could pin dk at
|
||||
# zero and block a needed correction or sign reversal (seen as 1.5 s dead spots in sharp curves).
|
||||
if lane_trust < self.trust:
|
||||
dk = self.dk + float(np.clip(dk - self.dk, -DK_RATE * DT_MDL, DK_RATE * DT_MDL))
|
||||
trust_tau = TRUST_RISE[0] + (TRUST_RISE[1] - TRUST_RISE[0]) * self.curve_gate
|
||||
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (trust_tau + DT_MDL)
|
||||
dk = float(np.clip(dk, min(self.dk, 0.0), max(self.dk, 0.0)))
|
||||
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (1.5 + DT_MDL)
|
||||
self.dk = dk
|
||||
return float(self.trust * dk)
|
||||
|
||||
@@ -8,7 +8,7 @@ import numpy as np
|
||||
|
||||
from openpilot.common.realtime import DT_MDL
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.sunnypilot.modeld_v2.blendful import Blendful, DK_RATE, MAX_ADDED_LAT_ACCEL
|
||||
from openpilot.sunnypilot.modeld_v2.blendful import Blendful
|
||||
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants
|
||||
|
||||
X = np.array(ModelConstants.X_IDXS)
|
||||
@@ -95,7 +95,7 @@ class TestBlendful(OpenpilotTestCase):
|
||||
p = 0.9 - 0.02 * i
|
||||
self.bf.update(frame(center=0.3, plan=-0.02 * i, probs=(p, p)), 20.0, True, 0.0)
|
||||
if self.bf.trust < trust:
|
||||
assert abs(self.bf.dk - dk) <= DK_RATE * DT_MDL + 1e-12
|
||||
assert abs(self.bf.dk) <= abs(dk) + 1e-12
|
||||
|
||||
def test_toggle_off_returns_zero_and_resets(self):
|
||||
drive(self.bf, 5.0, center=0.5)
|
||||
@@ -110,48 +110,3 @@ class TestBlendful(OpenpilotTestCase):
|
||||
assert self.bf.trust == 0.0
|
||||
assert abs(out[0]) < abs(start)
|
||||
assert abs(out[-1]) < 1e-6
|
||||
|
||||
def test_trust_fall_allows_sign_reversal(self):
|
||||
drive(self.bf, 5.0, center=0.4)
|
||||
assert self.bf.dk > 0
|
||||
# Keep trust falling every frame while the lane moves to the other side. The old sign-preserving clip pinned dk at 0.
|
||||
for i in range(300):
|
||||
p = max(0.45, 0.9 - 0.0015 * i)
|
||||
self.bf.update(frame(center=-0.4, probs=(p, p)), 20.0, True, 0.0)
|
||||
assert self.bf.dk < 0
|
||||
|
||||
def test_curve_gate_opens_on_lane_curvature(self):
|
||||
# The model under-reads the curve: lane lines curve, model_curvature stays 0.
|
||||
for _ in range(400):
|
||||
self.bf.update(frame(k=0.003, center=0.2), 25.0, True, 0.0)
|
||||
assert self.bf.curve_gate > 0.9
|
||||
assert self.bf.plan_share >= 0.6
|
||||
|
||||
straight = Blendful()
|
||||
for _ in range(400):
|
||||
straight.update(frame(), 25.0, True, 0.0)
|
||||
assert straight.curve_gate < 0.05
|
||||
|
||||
def test_trust_recovers_faster_in_curves(self):
|
||||
curve, straight = Blendful(), Blendful()
|
||||
for bf, k in ((curve, 0.004), (straight, 0.0)):
|
||||
drive(bf, 2.0, v=25.0, k=k)
|
||||
bf.trust = 0.0
|
||||
for _ in range(30):
|
||||
bf.update(frame(k=k), 25.0, True, k)
|
||||
assert curve.curve_gate > 0.9 and straight.curve_gate < 0.05
|
||||
assert curve.trust > straight.trust + 0.1
|
||||
|
||||
def test_maneuver_gate_holds_extra_share(self):
|
||||
drive(self.bf, 5.0, k=0.003, center=0.2)
|
||||
self.bf.usual_offset.x = -0.2
|
||||
self.bf.usual_offset.initialized = True
|
||||
for _ in range(20):
|
||||
self.bf.update(frame(k=0.003, center=0.2, plan=1.2), 25.0, True, 0.003)
|
||||
assert self.bf.maneuver_free < 0.1
|
||||
assert self.bf.plan_share < 0.55
|
||||
|
||||
def test_added_curvature_is_capped(self):
|
||||
self.bf.curvature = 1.0
|
||||
self.bf.update(frame(), 30.0, True, 0.0)
|
||||
assert abs(self.bf.curvature) <= MAX_ADDED_LAT_ACCEL / 30.0 ** 2 + 1e-9
|
||||
|
||||
@@ -112,7 +112,7 @@ class ModelCache:
|
||||
|
||||
class ModelFetcher:
|
||||
"""Handles fetching and caching of model data from remote source"""
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v26.json"
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v25.json"
|
||||
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v28.json"
|
||||
|
||||
MODEL_SOURCES = {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:f7df0485754b51731fc60b4cb324d75c7058c0e20c7c979ac84aa5273e29aa83
|
||||
size 5956
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:bd28c1e0a0dc15f5a1abc97cea2817f437880ed9e04fd7fc2ab1fb1b6a694ab0
|
||||
size 65812
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2edd557bb2fc417f6039dbc98f9895557a049c757dd4e31619f3f2e7a092386e
|
||||
size 35084
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:4d94997ee61f7ba0f3afece1db5b0c9c16f32512832380fc0ac13c384d360efd
|
||||
size 56152
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:9c85ee1bdbede640c484da13c5a25bd40f7c165df5d2ed9b1db3edf15712aae7
|
||||
size 115522
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:f7a6f3b314b37ed6c7c374104989b1f02f065c60a25104b371966f7c27a2fda7
|
||||
size 40364
|
||||
@@ -1,229 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate EMO-inspired robotic chirps and vocoded voice alert WAVs (48 kHz, mono, 16-bit PCM).
|
||||
|
||||
Run this script whenever tweaking the robotic sound pack:
|
||||
python3 openpilot/sunnypilot/selfdrive/assets/sounds/robotic/generate_robotic_sounds.py
|
||||
"""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
|
||||
import numpy as np
|
||||
|
||||
SAMPLE_RATE = 48000
|
||||
MAX_INT16 = 32767
|
||||
OUT_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def write_wav(path: Path, samples: np.ndarray) -> None:
|
||||
clipped = np.clip(samples, -1.0, 1.0)
|
||||
pcm = (clipped * MAX_INT16).astype(np.int16)
|
||||
with wave.open(str(path), "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(SAMPLE_RATE)
|
||||
wf.writeframes(pcm.tobytes())
|
||||
|
||||
|
||||
def adsr(n: int, attack: float = 0.015, release: float = 0.04) -> np.ndarray:
|
||||
env = np.ones(n, dtype=np.float32)
|
||||
a_n = min(n // 2, int(attack * SAMPLE_RATE))
|
||||
r_n = min(n // 2, int(release * SAMPLE_RATE))
|
||||
if a_n > 0:
|
||||
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
|
||||
if r_n > 0:
|
||||
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
|
||||
return env
|
||||
|
||||
|
||||
def emo_chirp(f_start: float, f_end: float, duration: float, vibrato_hz: float = 0.0, vibrato_depth: float = 0.0, gain: float = 0.65) -> np.ndarray:
|
||||
"""Synthesize an expressive EMO-like harmonic chirp with smooth pitch glide."""
|
||||
n = int(SAMPLE_RATE * duration)
|
||||
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
|
||||
# Smooth cubic-ish frequency glide
|
||||
progress = t / max(duration, 1e-6)
|
||||
s_curve = progress * progress * (3.0 - 2.0 * progress)
|
||||
freq = f_start + (f_end - f_start) * s_curve
|
||||
if vibrato_hz > 0.0:
|
||||
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
|
||||
phase = 2.0 * np.pi * np.cumsum(freq) / SAMPLE_RATE
|
||||
|
||||
# Warm robotic timbre: fundamental + soft 2nd & 3rd harmonics
|
||||
sig = (
|
||||
0.72 * np.sin(phase)
|
||||
+ 0.22 * np.sin(2.0 * phase + 0.3)
|
||||
+ 0.08 * np.sin(3.0 * phase)
|
||||
)
|
||||
env = adsr(n, attack=min(0.015, duration * 0.2), release=min(0.055, duration * 0.35))
|
||||
return (sig * env * gain).astype(np.float32)
|
||||
|
||||
|
||||
def silence(duration: float) -> np.ndarray:
|
||||
return np.zeros(int(SAMPLE_RATE * duration), dtype=np.float32)
|
||||
|
||||
|
||||
def robotize_voice(samples: np.ndarray, carrier_hz: float = 165.0) -> np.ndarray:
|
||||
"""Apply a clean EMO-style robotic vocoder / comb-resonance effect while keeping speech crisp."""
|
||||
n = len(samples)
|
||||
if n == 0:
|
||||
return samples
|
||||
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
|
||||
|
||||
# Normalize speech input
|
||||
peak = float(np.max(np.abs(samples)))
|
||||
if peak > 1e-5:
|
||||
samples = samples / peak
|
||||
|
||||
# Short metallic comb resonance (~5.5 ms delay) for unmistakable robot character
|
||||
delay = int(0.0055 * SAMPLE_RATE)
|
||||
comb = samples.copy()
|
||||
if delay < n:
|
||||
comb[delay:] += 0.42 * samples[:-delay]
|
||||
|
||||
# Gentle ring modulation blended with intelligible dry+comb voice
|
||||
carrier = 0.65 * np.sin(2.0 * np.pi * carrier_hz * t) + 0.35 * np.sin(2.0 * np.pi * carrier_hz * 2.0 * t)
|
||||
ring = comb * carrier
|
||||
blended = 0.62 * comb + 0.38 * ring
|
||||
|
||||
# Soft saturation & normalization
|
||||
blended = np.tanh(blended * 1.45)
|
||||
peak = float(np.max(np.abs(blended)))
|
||||
if peak > 1e-5:
|
||||
blended = blended / peak * 0.94
|
||||
return blended.astype(np.float32)
|
||||
|
||||
|
||||
def synthesize_robotic_phrase(text: str, rate: int = 205, carrier_hz: float = 175.0) -> np.ndarray | None:
|
||||
"""Render a short spoken phrase via macOS `say` + `ffmpeg`/`afconvert`, then robotize it."""
|
||||
say_bin = shutil.which("say")
|
||||
ffmpeg_bin = shutil.which("ffmpeg")
|
||||
if not say_bin or not ffmpeg_bin:
|
||||
return None
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
aiff_path = Path(tmpdir) / "speech.aiff"
|
||||
wav_path = Path(tmpdir) / "speech.wav"
|
||||
# Use a crisp clear voice ("Samantha" or system default) pitched up slightly via ffmpeg asetrate
|
||||
cmd_say = [say_bin, "-r", str(rate), "-o", str(aiff_path), text]
|
||||
subprocess.run(cmd_say, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
# Convert to 48kHz mono 16-bit WAV, slight pitch-up (+12%) for cute EMO-like robot timbre, trim silence
|
||||
cmd_ff = [
|
||||
ffmpeg_bin, "-y", "-i", str(aiff_path),
|
||||
"-af", "silenceremove=start_periods=1:start_threshold=-40dB:stop_periods=1:stop_threshold=-40dB,asetrate=22050*1.12,aresample=48000",
|
||||
"-ac", "1", "-ar", str(SAMPLE_RATE), "-sample_fmt", "s16",
|
||||
str(wav_path),
|
||||
]
|
||||
subprocess.run(cmd_ff, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
with wave.open(str(wav_path), "rb") as wf:
|
||||
raw = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0
|
||||
return robotize_voice(raw, carrier_hz=carrier_hz)
|
||||
|
||||
|
||||
def build_all_sounds() -> None:
|
||||
# 1. EMO-style expressive chirps & vocalizations (punchy multi-syllable trills)
|
||||
engage = np.concatenate([
|
||||
emo_chirp(620, 980, 0.10, gain=0.92),
|
||||
silence(0.02),
|
||||
emo_chirp(920, 1340, 0.10, gain=0.94),
|
||||
silence(0.02),
|
||||
emo_chirp(1220, 1780, 0.18, vibrato_hz=28, vibrato_depth=40, gain=0.96),
|
||||
])
|
||||
write_wav(OUT_DIR / "engage.wav", engage)
|
||||
|
||||
disengage = np.concatenate([
|
||||
emo_chirp(1240, 880, 0.12, gain=0.90),
|
||||
silence(0.025),
|
||||
emo_chirp(820, 480, 0.22, vibrato_hz=18, vibrato_depth=22, gain=0.90),
|
||||
])
|
||||
write_wav(OUT_DIR / "disengage.wav", disengage)
|
||||
|
||||
refuse = np.concatenate([
|
||||
emo_chirp(520, 340, 0.12, vibrato_hz=36, vibrato_depth=35, gain=0.92),
|
||||
silence(0.035),
|
||||
emo_chirp(420, 260, 0.18, vibrato_hz=36, vibrato_depth=35, gain=0.92),
|
||||
])
|
||||
write_wav(OUT_DIR / "refuse.wav", refuse)
|
||||
|
||||
pre_alert = emo_chirp(880, 1620, 0.24, vibrato_hz=30, vibrato_depth=32, gain=0.92)
|
||||
write_wav(OUT_DIR / "pre_alert.wav", pre_alert)
|
||||
|
||||
prompt_low = np.concatenate([
|
||||
emo_chirp(960, 680, 0.10, gain=0.88),
|
||||
silence(0.02),
|
||||
emo_chirp(660, 460, 0.14, gain=0.88),
|
||||
])
|
||||
write_wav(OUT_DIR / "prompt_single_low.wav", prompt_low)
|
||||
|
||||
prompt_high = np.concatenate([
|
||||
emo_chirp(780, 1180, 0.09, gain=0.90),
|
||||
silence(0.02),
|
||||
emo_chirp(1160, 1640, 0.15, vibrato_hz=26, vibrato_depth=30, gain=0.94),
|
||||
])
|
||||
write_wav(OUT_DIR / "prompt_single_high.wav", prompt_high)
|
||||
|
||||
# 2. Hybrid chirp + vocoded robotic spoken phrases for warnings & critical alerts
|
||||
def hybrid(intro: np.ndarray, phrase: str, fallback: np.ndarray, tail_pause: float = 0.0, carrier_hz: float = 175.0) -> np.ndarray:
|
||||
voice = synthesize_robotic_phrase(phrase, carrier_hz=carrier_hz)
|
||||
body = voice if voice is not None else fallback
|
||||
parts = [intro, silence(0.04), body]
|
||||
if tail_pause > 0.0:
|
||||
parts.append(silence(tail_pause))
|
||||
return np.concatenate(parts)
|
||||
|
||||
warning = hybrid(
|
||||
emo_chirp(820, 1120, 0.12, gain=0.65),
|
||||
"Heads up",
|
||||
emo_chirp(1120, 880, 0.22, gain=0.65),
|
||||
carrier_hz=185.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "warning.wav", warning)
|
||||
|
||||
warning_repeat = hybrid(
|
||||
emo_chirp(860, 1180, 0.12, gain=0.68),
|
||||
"Attention",
|
||||
emo_chirp(1180, 900, 0.22, gain=0.68),
|
||||
tail_pause=0.35,
|
||||
carrier_hz=185.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "warning_repeat.wav", warning_repeat)
|
||||
|
||||
dm_warning = hybrid(
|
||||
np.concatenate([emo_chirp(740, 1080, 0.10, gain=0.68), silence(0.03), emo_chirp(880, 1240, 0.10, gain=0.68)]),
|
||||
"Eyes on road",
|
||||
emo_chirp(1050, 780, 0.25, gain=0.68),
|
||||
tail_pause=0.35,
|
||||
carrier_hz=190.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "dm_warning.wav", dm_warning)
|
||||
|
||||
critical = hybrid(
|
||||
np.concatenate([emo_chirp(1320, 1520, 0.11, gain=0.80), silence(0.03), emo_chirp(1520, 1320, 0.11, gain=0.80)]),
|
||||
"Take control",
|
||||
emo_chirp(1480, 1100, 0.26, gain=0.80),
|
||||
tail_pause=0.28,
|
||||
carrier_hz=160.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "critical.wav", critical)
|
||||
|
||||
dm_critical = hybrid(
|
||||
np.concatenate([
|
||||
emo_chirp(1450, 1720, 0.09, gain=0.85),
|
||||
silence(0.025),
|
||||
emo_chirp(1450, 1720, 0.09, gain=0.85),
|
||||
]),
|
||||
"Take control now",
|
||||
emo_chirp(1680, 1200, 0.28, gain=0.85),
|
||||
tail_pause=0.22,
|
||||
carrier_hz=150.0,
|
||||
)
|
||||
write_wav(OUT_DIR / "dm_critical.wav", dm_critical)
|
||||
|
||||
print(f"Generated 11 robotic WAV files in {OUT_DIR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_all_sounds()
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:65679dc91bdc2cabd4349d4ffd178ae7a7fa928552e036bc54d52c8ad6a8caf3
|
||||
size 23084
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:00e3e854edcdcbae267fab69a0144c1689a7fe88e40010ed3bd7c0229c48b77d
|
||||
size 25004
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:d997b9d15a4083ca0300809bd38b0666f25de3a9be3f7180f54d7415408c196a
|
||||
size 25004
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:765f6d6496b24794f71249f16f3bc2df0993e9c8d465a7429715ab138c20eb43
|
||||
size 32204
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:ed26262d283e696b73452e63486b656c777a4fe24914090e07e8f95f7a5c2461
|
||||
size 42098
|
||||
@@ -1,3 +0,0 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2e172036401b6c5d81ce922b6e5ed9e1bc39320646f8b7aa1df223f9e392fe90
|
||||
size 52158
|
||||
@@ -5,7 +5,6 @@ This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.cereal import log, custom
|
||||
from opendbc.car import structs
|
||||
|
||||
@@ -24,15 +23,10 @@ class CarSpecificEventsSP:
|
||||
self.CP_SP = CP_SP
|
||||
|
||||
self.low_speed_alert = False
|
||||
self.sm = messaging.SubMaster(['carStateSP'])
|
||||
|
||||
def update(self, CS: structs.CarState, events: Events):
|
||||
events_sp = EventsSP()
|
||||
|
||||
self.sm.update(0)
|
||||
if self.sm['carStateSP'].stockSteerIntervention:
|
||||
events_sp.add(EventNameSP.stockSteerIntervention)
|
||||
|
||||
if self.CP.brand == 'chrysler':
|
||||
if self.CP.carFingerprint in RAM_DT:
|
||||
# remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic
|
||||
|
||||
@@ -11,7 +11,6 @@ from opendbc.car.interfaces import CarInterfaceBase
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import PIDD_VERSION
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability
|
||||
|
||||
from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP
|
||||
@@ -56,18 +55,10 @@ def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_S
|
||||
CP_SP.pcmCruiseSpeed = False
|
||||
|
||||
|
||||
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool,
|
||||
params: Params | None = None) -> None:
|
||||
if params is None:
|
||||
params = Params()
|
||||
|
||||
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None:
|
||||
if nnlc_enabled or enforce_torque:
|
||||
CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning)
|
||||
|
||||
if enforce_torque and not nnlc_enabled and CP.steerControlType == structs.CarParams.SteerControlType.torque \
|
||||
and params.get("TorqueControlTune") == PIDD_VERSION:
|
||||
CP.lateralTuning.init('pid')
|
||||
|
||||
|
||||
def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params | None = None) -> None:
|
||||
if params is None:
|
||||
@@ -101,7 +92,7 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
|
||||
enforce_torque = _enforce_torque_lateral_control(CI.CP, params)
|
||||
nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params)
|
||||
_initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params)
|
||||
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled, params)
|
||||
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled)
|
||||
_cleanup_unsupported_params(CI.CP, CI.CP_SP)
|
||||
|
||||
try:
|
||||
@@ -114,8 +105,6 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
|
||||
def initialize_params(params) -> list[dict[str, Any]]:
|
||||
keys: list = []
|
||||
|
||||
keys.append("RadarTracks")
|
||||
|
||||
# hyundai
|
||||
keys.extend([
|
||||
"HyundaiLongitudinalTuning",
|
||||
|
||||
@@ -6,8 +6,6 @@ See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.cereal import log, custom
|
||||
|
||||
@@ -19,27 +17,6 @@ from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
|
||||
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, pidd_selected
|
||||
|
||||
|
||||
PATH_CURVATURE_PREVIEW_START = 15.0 # m ahead of the car
|
||||
PATH_CURVATURE_PREVIEW_END = 45.0 # m ahead of the car
|
||||
PATH_CURVATURE_MIN_SPEED = 1.0 # m/s
|
||||
|
||||
|
||||
def path_curvature_ahead(model_v2) -> float:
|
||||
vx = np.asarray(model_v2.velocity.x, dtype=np.float64)
|
||||
if len(vx) < 3 or vx[0] < PATH_CURVATURE_MIN_SPEED:
|
||||
return 0.0
|
||||
|
||||
# averaged over a fixed distance ahead, so the preview does not shrink with speed
|
||||
position = model_v2.position
|
||||
distance = np.concatenate([[0.0], np.cumsum(np.hypot(np.diff(position.x), np.diff(position.y)))])
|
||||
start = min(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_START)), len(distance) - 1)
|
||||
end = min(max(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_END)), start + 1), len(distance))
|
||||
|
||||
oz = np.asarray(model_v2.orientationRate.z, dtype=np.float64)[start:end]
|
||||
return float(np.mean(oz / np.maximum(vx[start:end], PATH_CURVATURE_MIN_SPEED)))
|
||||
|
||||
|
||||
class ControlsExt(ModelStateBase):
|
||||
@@ -53,15 +30,11 @@ class ControlsExt(ModelStateBase):
|
||||
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
|
||||
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
|
||||
cloudlog.info("controlsd_ext got CarParamsSP")
|
||||
self.pidd: LatControlPidd | None = None
|
||||
|
||||
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
|
||||
self.pm_services_ext = ['carControlSP']
|
||||
|
||||
def initialize_lateral_control(self, lac, CI, dt):
|
||||
if pidd_selected(self.CP):
|
||||
self.pidd = LatControlPidd(self.CP, self.CP_SP, CI, dt)
|
||||
return self.pidd
|
||||
enforce_torque_control = self.params.get_bool("EnforceTorqueControl")
|
||||
torque_versions = self.params.get("TorqueControlTune")
|
||||
if not enforce_torque_control:
|
||||
@@ -131,8 +104,6 @@ class ControlsExt(ModelStateBase):
|
||||
CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton
|
||||
CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget
|
||||
|
||||
CC_SP.pathCurvature = path_curvature_ahead(sm['modelV2'])
|
||||
|
||||
return CC_SP
|
||||
|
||||
@staticmethod
|
||||
@@ -143,13 +114,6 @@ class ControlsExt(ModelStateBase):
|
||||
|
||||
pm.send('carControlSP', cc_sp_send)
|
||||
|
||||
def update_pidd_torque_params(self, sm: messaging.SubMaster) -> None:
|
||||
torque_params = sm['lateralTorqueParameters']
|
||||
if self.pidd is not None and sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
|
||||
self.pidd.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
|
||||
torque_params.frictionCoefficientFiltered)
|
||||
|
||||
def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None:
|
||||
self.update_pidd_torque_params(sm)
|
||||
CC_SP = self.state_control_ext(sm)
|
||||
self.publish_ext(CC_SP, sm, pm)
|
||||
|
||||
@@ -18,7 +18,6 @@ class LatControlTorqueExt(NeuralNetworkLateralControl, LatControlTorqueExtOverri
|
||||
desired_lateral_accel, actual_lateral_accel, lateral_accel_deadzone, gravity_adjusted_lateral_accel,
|
||||
desired_curvature, actual_curvature, steer_limited_by_safety, output_torque):
|
||||
self._ff = ff
|
||||
self._pid = pid
|
||||
self._pid_log = pid_log
|
||||
self._setpoint = setpoint
|
||||
self._measurement = measurement
|
||||
|
||||
@@ -63,7 +63,7 @@ class LatControlTorqueExtBase:
|
||||
self.torque_params = lac_torque.torque_params
|
||||
|
||||
self._ff = 0.0
|
||||
self._pid = PIDController(KP, KI)
|
||||
self._pid = PIDController(KP, KI, pos_limit=lac_torque.steer_max, neg_limit=-lac_torque.steer_max, rate=1 / lac_torque.dt)
|
||||
self._pid_log = log.ControlsState.LateralTorqueState.new_message()
|
||||
self._setpoint = 0.0
|
||||
self._measurement = 0.0
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"pidd": {
|
||||
"version": "2.0"
|
||||
},
|
||||
"v1.0": {
|
||||
"version": "1.0"
|
||||
},
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from collections import deque
|
||||
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.pid import PIDController
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
|
||||
# gains are in lateral acceleration, scaled to torque per degree by each car's vehicle model and latAccelFactor
|
||||
PIDD_VERSION = 2.0
|
||||
INTERP_SPEEDS = [1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 30.0]
|
||||
KP_INTERP = [250.0, 120.0, 65.0, 30.0, 11.5, 5.5, 3.5, 2.0, 0.8]
|
||||
TD_INTERP = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15, 0.2]
|
||||
HIGH_SPEED_BP = [25.0, 29.0]
|
||||
TURN_RATE_BP = [5.0, 20.0]
|
||||
TURN_LAT_ACCEL_BP = [0.18, 0.53]
|
||||
DESIRED_ANGLE_BUFFER_SECONDS = 1.0
|
||||
LIVE_LAT_ACCEL_FACTOR_RANGE = [1.0, 2.0]
|
||||
LIVE_FRICTION_RANGE = [0.5, 2.0]
|
||||
SWING_CAP_FRICTION = 1.3
|
||||
|
||||
|
||||
def pidd_selected(CP):
|
||||
return CP.steerControlType == 'torque' and CP.lateralTuning.which() == 'pid' and len(CP.lateralTuning.pid.kpBP) == 0 and \
|
||||
CP.carFingerprint in get_torque_params()
|
||||
|
||||
|
||||
def filter_rc(hz):
|
||||
return 1 / (2 * math.pi * hz)
|
||||
|
||||
|
||||
def lat_accel_per_deg(VM, v_ego):
|
||||
return VM.calc_curvature(math.radians(1.0), v_ego, 0.0) * v_ego**2
|
||||
|
||||
|
||||
class LatControlPidd(LatControl):
|
||||
def __init__(self, CP, CP_SP, CI, dt):
|
||||
super().__init__(CP, CP_SP, CI, dt)
|
||||
|
||||
torque_params = get_torque_params()[CP.carFingerprint]
|
||||
self.VM = VehicleModel(CP)
|
||||
self.pid = PIDController(0.0, 0.0, 0.0, pos_limit=self.steer_max, neg_limit=-self.steer_max)
|
||||
self.offline_lat_accel_factor, self.offline_friction = float(torque_params['LAT_ACCEL_FACTOR']), float(torque_params['FRICTION'])
|
||||
self.lat_accel_factor = self.friction = None
|
||||
self.update_torque_parameters(self.offline_lat_accel_factor, 0.0, self.offline_friction)
|
||||
|
||||
self.error_filter = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.request_filter = FirstOrderFilter(0.0, filter_rc(3.0), dt, initialized=False)
|
||||
self.error_rate_filter = FirstOrderFilter(0.0, 0.0354, dt)
|
||||
self.wheel_angle_filter = FirstOrderFilter(0.0, filter_rc(10.0), dt, initialized=False)
|
||||
self.wheel_rate_filter = FirstOrderFilter(0.0, 0.005, dt)
|
||||
self.request_rate_ref = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.break_rate = FirstOrderFilter(0.0, filter_rc(0.5), dt)
|
||||
self.break_rate2 = FirstOrderFilter(0.0, filter_rc(0.5), dt)
|
||||
self.break_error = FirstOrderFilter(0.0, filter_rc(1.0), dt)
|
||||
self.command_slow = FirstOrderFilter(0.0, filter_rc(0.5), dt, initialized=False)
|
||||
self.last_error = 0.0
|
||||
self.wheel_angle_held = None
|
||||
self.swing = 0.0
|
||||
|
||||
buffer_len = int(DESIRED_ANGLE_BUFFER_SECONDS / dt)
|
||||
self.desired_angle_buffer = deque([0.0] * buffer_len, maxlen=buffer_len)
|
||||
self.delay_frames = int(np.clip(CP.steerActuatorDelay / dt + 1, 1, buffer_len))
|
||||
self.rate_span_frames = max(1, int(0.1 / dt))
|
||||
|
||||
def update_torque_parameters(self, latAccelFactor, latAccelOffset, friction):
|
||||
# a learned factor below the offline one would raise every gain
|
||||
latAccelFactor = float(np.clip(latAccelFactor, *(r * self.offline_lat_accel_factor for r in LIVE_LAT_ACCEL_FACTOR_RANGE)))
|
||||
friction = float(np.clip(friction, *(r * self.offline_friction for r in LIVE_FRICTION_RANGE)))
|
||||
if (latAccelFactor, friction) == (self.lat_accel_factor, self.friction):
|
||||
return
|
||||
self.lat_accel_factor, self.friction = latAccelFactor, friction
|
||||
self.kp = [kp * lat_accel_per_deg(self.VM, v) / latAccelFactor for kp, v in zip(KP_INTERP, INTERP_SPEEDS, strict=True)]
|
||||
self.pid._k_p = (INTERP_SPEEDS, self.kp)
|
||||
self.pid._k_i = (INTERP_SPEEDS, [kp / 6.0 for kp in self.kp])
|
||||
self.pid._k_d = (INTERP_SPEEDS, [kp * td for kp, td in zip(self.kp, TD_INTERP, strict=True)])
|
||||
|
||||
def reset(self):
|
||||
super().reset()
|
||||
self.pid.reset()
|
||||
self.swing = self.last_error = 0.0
|
||||
self.command_slow.initialized = False
|
||||
for f in (self.error_filter, self.error_rate_filter, self.wheel_rate_filter, self.request_rate_ref, self.break_error, self.break_rate, self.break_rate2):
|
||||
f.x = 0.0
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay):
|
||||
pid_log = log.ControlsState.LateralPIDState.new_message()
|
||||
pid_log.steeringAngleDeg = float(CS.steeringAngleDeg)
|
||||
pid_log.steeringRateDeg = float(CS.steeringRateDeg)
|
||||
|
||||
high_speed = float(np.interp(CS.vEgo, HIGH_SPEED_BP, [0.0, 1.0]))
|
||||
angle_steers_des_no_offset = self.request_filter.update(math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)))
|
||||
angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg
|
||||
|
||||
self.desired_angle_buffer.append(angle_steers_des)
|
||||
expected_angle = self.desired_angle_buffer[-self.delay_frames]
|
||||
request_rate = (self.desired_angle_buffer[-1] - self.desired_angle_buffer[-1 - self.rate_span_frames]) / (self.rate_span_frames * self.dt)
|
||||
request_rate_ref = self.request_rate_ref.update(request_rate)
|
||||
break_rate = self.break_rate2.update(self.break_rate.update(request_rate))
|
||||
# a 1 Hz error filter lags enough for P to pump a 2 Hz wheel swing, so it opens up only while the request turns the wheel
|
||||
error_filter_hz = float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [1.0, 3.0]))
|
||||
self.error_filter.update_alpha(filter_rc(float(np.interp(CS.vEgo, HIGH_SPEED_BP, [error_filter_hz, 1.0]))))
|
||||
error = self.error_filter.update(expected_angle - CS.steeringAngleDeg)
|
||||
# at highway speed, ignore the angle sensor toggling one count
|
||||
held = self.wheel_angle_held if self.wheel_angle_held is not None else CS.steeringAngleDeg
|
||||
wheel_backlash = 0.08 * high_speed
|
||||
self.wheel_angle_held = held = CS.steeringAngleDeg - float(np.clip(CS.steeringAngleDeg - held, -wheel_backlash, wheel_backlash))
|
||||
wheel_angle_last = self.wheel_angle_filter.x if self.wheel_angle_filter.initialized else held
|
||||
wheel_rate = self.wheel_rate_filter.update((self.wheel_angle_filter.update(held) - wheel_angle_last) / self.dt)
|
||||
|
||||
wheel_swing = 0.0 if CS.steeringPressed else min(abs(wheel_rate - request_rate_ref), 60.0)
|
||||
self.swing = max(wheel_swing, self.swing * (1.0 - self.dt))
|
||||
|
||||
pid_log.steeringAngleDesiredDeg = float(angle_steers_des)
|
||||
pid_log.angleError = float(error)
|
||||
|
||||
if not active:
|
||||
output_torque = 0.0
|
||||
pid_log.active = False
|
||||
self.reset()
|
||||
else:
|
||||
error_rate = self.error_rate_filter.update((error - self.last_error) / self.dt)
|
||||
self.last_error = error
|
||||
error_rate += high_speed * (-wheel_rate - error_rate)
|
||||
ff = angle_steers_des_no_offset * lat_accel_per_deg(VM, CS.vEgo) / self.lat_accel_factor
|
||||
ff += 0.4 * params.roll * ACCELERATION_DUE_TO_GRAVITY / self.lat_accel_factor
|
||||
|
||||
# break rack friction as soon as the request moves, before the error builds up
|
||||
error_deadzone = error - float(np.clip(error, -0.3, 0.3))
|
||||
turn_lat_accel = abs(desired_curvature) * max(CS.vEgo, 8.0) ** 2
|
||||
friction_scale = float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.6, 1.0]))
|
||||
friction = self.friction * (friction_scale + high_speed * (0.1 - friction_scale))
|
||||
friction_rate_gain = 0.75 - 0.25 * high_speed
|
||||
ff += friction * float(np.tanh((error_deadzone + friction_rate_gain * request_rate) * 0.1887))
|
||||
kp = float(np.interp(CS.vEgo, INTERP_SPEEDS, self.kp))
|
||||
# damp the wheel toward the request's rate; the rack rings near 2 Hz without it
|
||||
wheel_damp = 0.0 if CS.steeringPressed else (1.0 - high_speed) * kp * 0.05 * (wheel_rate - request_rate_ref)
|
||||
ff -= wheel_damp
|
||||
# half P on a straight, flat road; the cut goes through the feedforward so the integrator still holds a crown
|
||||
kp_load = max(float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0])),
|
||||
float(np.interp(abs(params.roll) * ACCELERATION_DUE_TO_GRAVITY, [0.35, 0.7], [0.0, 1.0])))
|
||||
kp_scale = 0.5 + 0.5 * kp_load
|
||||
ff -= (1.0 - float(np.interp(CS.vEgo, [12.0, 18.0], [kp_scale, 1.0]))) * kp * error
|
||||
ff += high_speed * 0.325 * self.friction * float(np.tanh((self.break_error.update(error) + 0.35 * break_rate) / 0.5))
|
||||
|
||||
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
|
||||
error_rate_clean = error_rate - float(np.clip(error_rate, -0.3, 0.3))
|
||||
output_torque = self.pid.update(error, error_rate=error_rate_clean, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
|
||||
|
||||
# a swing the request isn't asking for: pass only the command's slow part
|
||||
command = output_torque + wheel_damp
|
||||
self.command_slow.update(command)
|
||||
if CS.steeringPressed:
|
||||
self.command_slow.x = command
|
||||
swing_gate = float(np.interp(self.swing, [16.0, 30.0], [0.0, 1.0])) * float(np.interp(CS.vEgo, [3.0, 5.0, 10.0, 14.0], [0.0, 1.0, 1.0, 0.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [0.0, 1.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0]))
|
||||
swing_gate *= 1.0 - float(np.interp(abs(error), [3.0, 6.0], [0.0, 1.0]))
|
||||
if not (CS.steeringPressed or CS.leftBlinker or CS.rightBlinker):
|
||||
cap = SWING_CAP_FRICTION * self.friction
|
||||
output_torque += swing_gate * float(np.clip(self.command_slow.x - command, -cap, cap))
|
||||
output_torque = float(np.clip(output_torque, -self.steer_max, self.steer_max))
|
||||
|
||||
pid_log.active = True
|
||||
pid_log.p = float(self.pid.p)
|
||||
pid_log.i = float(self.pid.i)
|
||||
pid_log.f = float(self.pid.f)
|
||||
pid_log.output = float(output_torque)
|
||||
pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
|
||||
return output_torque, angle_steers_des, pid_log
|
||||
@@ -4,6 +4,7 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
from openpilot.cereal import log, messaging
|
||||
@@ -59,9 +60,9 @@ def _make_model_v2():
|
||||
return model
|
||||
|
||||
|
||||
def _run_update(controller, VM):
|
||||
def _run_update(controller, VM, v_ego=30, desired_curvature=0.5):
|
||||
CS = car.CarState.new_message()
|
||||
CS.vEgo = 30
|
||||
CS.vEgo = v_ego
|
||||
CS.steeringPressed = False
|
||||
lp = generate_deviceMotion()
|
||||
pose = Pose.from_device_motion(lp.deviceMotion)
|
||||
@@ -69,7 +70,7 @@ def _run_update(controller, VM):
|
||||
model_v2 = _make_model_v2().modelV2
|
||||
controller.extension.update_model_v2(model_v2)
|
||||
controller.extension.update_lateral_lag(0.2)
|
||||
return controller.update(True, CS, VM, params, False, 0.5, pose, False, 0.2)
|
||||
return controller.update(True, CS, VM, params, False, desired_curvature, pose, False, 0.2)
|
||||
|
||||
|
||||
class TestLatControlTorqueExt(OpenpilotTestCase):
|
||||
@@ -107,3 +108,12 @@ class TestLatControlTorqueExt(OpenpilotTestCase):
|
||||
controller, VM, _ = _make_controller(enhanced=True, nnlc=True)
|
||||
output_torque, _, pid_log = _run_update(controller, VM)
|
||||
assert pid_log.active
|
||||
|
||||
def test_low_speed_gain_bounded(self):
|
||||
for kwargs in ({"nnlc": True}, {"enhanced": True}):
|
||||
controller, VM, _ = _make_controller(**kwargs)
|
||||
one_degree = -VM.calc_curvature(math.radians(1.0), 2.0, 0.0)
|
||||
output_torque, _, _ = _run_update(controller, VM, v_ego=2.0, desired_curvature=one_degree)
|
||||
assert controller.extension._nnlc_enabled or controller.extension._jerk_aware_enabled
|
||||
assert controller.extension._pid is not controller.pid
|
||||
assert abs(output_torque) < 0.3, kwargs
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.honda.values import CAR as HONDA
|
||||
from opendbc.car.hyundai.values import CAR as HYUNDAI
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.nissan.values import CAR as NISSAN
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.mock.generators import generate_deviceMotion
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import DT_CTRL
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.selfdrive.car.helpers import convert_to_capnp
|
||||
from openpilot.selfdrive.locationd.helpers import Pose
|
||||
from openpilot.selfdrive.locationd.torqued import TorqueEstimator
|
||||
from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces
|
||||
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, PIDD_VERSION
|
||||
|
||||
|
||||
def setup_car(car_name):
|
||||
CarInterface = interfaces[car_name]
|
||||
CP = CarInterface.get_non_essential_params(car_name)
|
||||
CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name)
|
||||
CI = CarInterface(CP, CP_SP)
|
||||
sunnypilot_interfaces.setup_interfaces(CI)
|
||||
return CI
|
||||
|
||||
|
||||
def make_controller(CI):
|
||||
return LatControlPidd(CI.CP.as_reader(), convert_to_capnp(CI.CP_SP).as_reader(), CI, DT_CTRL)
|
||||
|
||||
|
||||
def drive(controller, CS, VM, angles, curvature=0.0):
|
||||
params = log.VehicleParameters.new_message()
|
||||
pose = Pose.from_device_motion(generate_deviceMotion().deviceMotion)
|
||||
return [controller.update(True, CS, VM, params, False, curvature, pose, False, 0.2)[0] for CS.steeringAngleDeg in angles]
|
||||
|
||||
|
||||
class TestPidd(OpenpilotTestCase):
|
||||
def setup_method(self):
|
||||
self.params = Params()
|
||||
self.params.put_bool("EnforceTorqueControl", True, block=True)
|
||||
self.params.put("TorqueControlTune", PIDD_VERSION, block=True)
|
||||
|
||||
def test_selected_on_any_torque_car(self):
|
||||
for car_name in (HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.KIA_NIRO_EV):
|
||||
assert setup_car(car_name).CP.lateralTuning.which() == 'pid'
|
||||
|
||||
def test_needs_enforce_torque(self):
|
||||
self.params.remove("EnforceTorqueControl")
|
||||
assert setup_car(HYUNDAI.KIA_NIRO_EV).CP.lateralTuning.which() == 'torque'
|
||||
|
||||
def test_not_on_angle_cars(self):
|
||||
CI = setup_car(NISSAN.NISSAN_LEAF)
|
||||
assert CI.CP.steerControlType == car.CarParams.SteerControlType.angle
|
||||
assert not self.params.get_bool("EnforceTorqueControl")
|
||||
|
||||
def test_controlsd_builds_it(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
|
||||
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
|
||||
|
||||
def test_selection_follows_car_params(self):
|
||||
# params changing after card picked pidd must not leave controlsd with a pid that has no gains
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
self.params.remove("EnforceTorqueControl")
|
||||
self.params.put("TorqueControlTune", 1.0, block=True)
|
||||
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
|
||||
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
|
||||
|
||||
def test_damps_wheel_swing(self):
|
||||
CI = setup_car(HONDA.HONDA_CIVIC)
|
||||
VM = VehicleModel(CI.CP)
|
||||
corr = {}
|
||||
for pressed in (False, True):
|
||||
controller = make_controller(CI)
|
||||
CS = car.CarState.new_message(vEgo=8.0, steeringPressed=pressed)
|
||||
angles = [2.0 * math.sin(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(300)]
|
||||
out = drive(controller, CS, VM, angles)[100:]
|
||||
rate = [math.cos(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(100, 300)]
|
||||
corr[pressed] = float(np.corrcoef(out, rate)[0, 1])
|
||||
assert corr[False] < corr[True] - 0.3
|
||||
|
||||
def test_output_within_steer_max(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
controller = make_controller(CI)
|
||||
controller.pid.update = lambda *args, **kwargs: controller.steer_max
|
||||
CS = car.CarState.new_message(vEgo=8.0)
|
||||
out = drive(controller, CS, VehicleModel(CI.CP), [2.0 * math.sin(2 * math.pi * 2.5 * i * DT_CTRL) for i in range(500)])
|
||||
assert max(abs(x) for x in out) <= controller.steer_max
|
||||
|
||||
def test_reset_clears_swing_gate(self):
|
||||
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
|
||||
controller = make_controller(CI)
|
||||
drive(controller, car.CarState.new_message(vEgo=8.0), VehicleModel(CI.CP), [30.0] * 200, curvature=-0.02)
|
||||
controller.reset()
|
||||
assert not controller.command_slow.initialized
|
||||
|
||||
def test_live_torque_params_rescale_gains(self):
|
||||
controller = make_controller(setup_car(HYUNDAI.KIA_NIRO_EV))
|
||||
kp = list(controller.kp)
|
||||
controller.update_torque_parameters(2 * controller.lat_accel_factor, 0.0, controller.friction)
|
||||
assert np.allclose(controller.kp, [k / 2 for k in kp])
|
||||
assert np.allclose(controller.pid._k_p[1], controller.kp)
|
||||
controller.update_torque_parameters(0.5 * controller.offline_lat_accel_factor, 0.0, 0.0)
|
||||
assert np.allclose(controller.kp, kp)
|
||||
|
||||
def test_torqued_learns_under_pidd(self):
|
||||
estimator = TorqueEstimator(setup_car(HYUNDAI.KIA_NIRO_EV).CP.as_reader())
|
||||
offline = get_torque_params()[HYUNDAI.KIA_NIRO_EV]
|
||||
self.assertAlmostEqual(estimator.offline_latAccelFactor, offline['LAT_ACCEL_FACTOR'])
|
||||
self.assertAlmostEqual(estimator.offline_friction, offline['FRICTION'])
|
||||
assert estimator.max_lataccel_factor > estimator.min_lataccel_factor
|
||||
@@ -6,13 +6,11 @@ See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.structs import car
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import DT_MDL
|
||||
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import pidd_selected
|
||||
|
||||
RELAXED_MIN_BUCKET_POINTS = np.array([1, 200, 300, 500, 500, 300, 200, 1])
|
||||
|
||||
@@ -39,11 +37,6 @@ class TorqueEstimatorExt:
|
||||
def initialize_custom_params(self, decimated=False):
|
||||
self.update_use_params()
|
||||
|
||||
if pidd_selected(self.CP):
|
||||
torque_params = get_torque_params()[self.CP.carFingerprint]
|
||||
self.offline_latAccelFactor = float(torque_params['LAT_ACCEL_FACTOR'])
|
||||
self.offline_friction = float(torque_params['FRICTION'])
|
||||
|
||||
if self.enforce_torque_control_toggle:
|
||||
if self._params.get_bool("LiveTorqueParamsRelaxedToggle"):
|
||||
self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS / (10 if decimated else 1)
|
||||
|
||||
@@ -249,14 +249,6 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
|
||||
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
|
||||
},
|
||||
|
||||
EventNameSP.stockSteerIntervention: {
|
||||
ET.PERMANENT: Alert(
|
||||
"TAKE CONTROL",
|
||||
"Stock Emergency Assist: Risk of Collision",
|
||||
AlertStatus.critical, AlertSize.mid,
|
||||
Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.none, 2.),
|
||||
},
|
||||
|
||||
EventNameSP.bigModelReady: {
|
||||
ET.PERMANENT: Alert(
|
||||
"Big Model Ready",
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import wave
|
||||
|
||||
import numpy as np
|
||||
|
||||
from openpilot.cereal import custom, log
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
|
||||
|
||||
ROBOTIC_SOUNDS_DIR = os.path.join(BASEDIR, "openpilot/sunnypilot/selfdrive/assets/sounds/robotic")
|
||||
|
||||
ROBOTIC_SOUND_FILES: dict[int, str] = {
|
||||
AudibleAlert.engage: "engage.wav",
|
||||
AudibleAlert.disengage: "disengage.wav",
|
||||
AudibleAlert.refuse: "refuse.wav",
|
||||
AudibleAlert.prompt: "warning.wav",
|
||||
AudibleAlert.promptRepeat: "warning_repeat.wav",
|
||||
AudibleAlert.promptDistracted: "dm_warning.wav",
|
||||
AudibleAlert.preAlert: "pre_alert.wav",
|
||||
AudibleAlert.warningSoft: "critical.wav",
|
||||
AudibleAlert.warningImmediateSystem: "critical.wav",
|
||||
AudibleAlert.warningImmediateUser: "dm_critical.wav",
|
||||
AudibleAlertSP.promptSingleLow: "prompt_single_low.wav",
|
||||
AudibleAlertSP.promptSingleHigh: "prompt_single_high.wav",
|
||||
}
|
||||
|
||||
# Custom reactive robotic chirp IDs (non-overlapping with AudibleAlert / AudibleAlertSP enums)
|
||||
CHIRP_SPEED_UP = 1001
|
||||
CHIRP_SPEED_DOWN = 1002
|
||||
CHIRP_STARTLED = 1003
|
||||
CHIRP_BOOST = 1004
|
||||
CHIRP_BOOKMARK = 1005
|
||||
CHIRP_BLINKER = 1006
|
||||
|
||||
REACTIVE_CHIRP_IDS = {
|
||||
CHIRP_SPEED_UP,
|
||||
CHIRP_SPEED_DOWN,
|
||||
CHIRP_STARTLED,
|
||||
CHIRP_BOOST,
|
||||
CHIRP_BOOKMARK,
|
||||
CHIRP_BLINKER,
|
||||
}
|
||||
|
||||
SET_SPEED_NA = 255
|
||||
CHIRP_COOLDOWN = 0.6 # minimum seconds between reactive chirps
|
||||
|
||||
|
||||
def _adsr(n: int, sr: int, attack: float = 0.012, release: float = 0.035) -> np.ndarray:
|
||||
env = np.ones(n, dtype=np.float32)
|
||||
a_n = min(n // 2, int(attack * sr))
|
||||
r_n = min(n // 2, int(release * sr))
|
||||
if a_n > 0:
|
||||
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
|
||||
if r_n > 0:
|
||||
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
|
||||
return env
|
||||
|
||||
|
||||
def synth_emo_chirp(
|
||||
f_start: float,
|
||||
f_end: float,
|
||||
duration: float,
|
||||
sr: int = 48000,
|
||||
vibrato_hz: float = 0.0,
|
||||
vibrato_depth: float = 0.0,
|
||||
gain: float = 0.92,
|
||||
) -> np.ndarray:
|
||||
"""Synthesize a bright, bubbly, unmistakable EMO/R2-D2-style formant chirp in pure NumPy."""
|
||||
n = max(1, int(sr * duration))
|
||||
t = np.arange(n, dtype=np.float32) / sr
|
||||
p = t / max(duration, 1e-6)
|
||||
s_curve = p * p * (3.0 - 2.0 * p)
|
||||
freq = f_start + (f_end - f_start) * s_curve
|
||||
if vibrato_hz > 0.0:
|
||||
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
|
||||
phase = 2.0 * np.pi * np.cumsum(freq) / sr
|
||||
sig = (
|
||||
0.55 * np.sin(phase)
|
||||
+ 0.28 * np.sin(2.0 * phase + 0.35)
|
||||
+ 0.14 * np.sin(3.0 * phase + 0.7)
|
||||
+ 0.07 * np.sin(4.0 * phase)
|
||||
)
|
||||
env = _adsr(n, sr, attack=min(0.010, duration * 0.18), release=min(0.040, duration * 0.32))
|
||||
out = np.tanh(sig * env * 1.45) * gain
|
||||
return np.clip(out, -0.98, 0.98).astype(np.float32)
|
||||
|
||||
|
||||
def _sil(duration: float, sr: int = 48000) -> np.ndarray:
|
||||
return np.zeros(int(sr * duration), dtype=np.float32)
|
||||
|
||||
|
||||
def build_procedural_sounds(sr: int = 48000) -> dict[int, np.ndarray]:
|
||||
"""Build bubbly EMO chirps in pure NumPy (used for reactive chirps and guaranteed WAV fallback)."""
|
||||
return {
|
||||
# Core alert fallbacks (punchy, unmistakably robotic multi-syllable EMO trills)
|
||||
AudibleAlert.engage: np.concatenate([
|
||||
synth_emo_chirp(620, 980, 0.10, sr, gain=0.92),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(920, 1340, 0.10, sr, gain=0.94),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1220, 1780, 0.18, sr, vibrato_hz=28, vibrato_depth=40, gain=0.96),
|
||||
]),
|
||||
AudibleAlert.disengage: np.concatenate([
|
||||
synth_emo_chirp(1240, 880, 0.12, sr, gain=0.90),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(820, 480, 0.22, sr, vibrato_hz=18, vibrato_depth=22, gain=0.90),
|
||||
]),
|
||||
AudibleAlert.refuse: np.concatenate([
|
||||
synth_emo_chirp(520, 340, 0.12, sr, vibrato_hz=36, vibrato_depth=35, gain=0.92),
|
||||
_sil(0.035, sr),
|
||||
synth_emo_chirp(420, 260, 0.18, sr, vibrato_hz=36, vibrato_depth=35, gain=0.92),
|
||||
]),
|
||||
AudibleAlert.preAlert: synth_emo_chirp(880, 1620, 0.24, sr, vibrato_hz=30, vibrato_depth=32, gain=0.92),
|
||||
AudibleAlertSP.promptSingleLow: np.concatenate([
|
||||
synth_emo_chirp(960, 680, 0.10, sr, gain=0.88),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(660, 460, 0.14, sr, gain=0.88),
|
||||
]),
|
||||
AudibleAlertSP.promptSingleHigh: np.concatenate([
|
||||
synth_emo_chirp(780, 1180, 0.09, sr, gain=0.90),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1160, 1640, 0.15, sr, vibrato_hz=26, vibrato_depth=30, gain=0.94),
|
||||
]),
|
||||
AudibleAlert.prompt: np.concatenate([
|
||||
synth_emo_chirp(920, 1420, 0.12, sr, gain=0.92),
|
||||
_sil(0.03, sr),
|
||||
synth_emo_chirp(1380, 1020, 0.18, sr, gain=0.92),
|
||||
]),
|
||||
AudibleAlert.promptRepeat: np.concatenate([
|
||||
synth_emo_chirp(960, 1460, 0.12, sr, gain=0.92),
|
||||
_sil(0.03, sr),
|
||||
synth_emo_chirp(1420, 1060, 0.16, sr, gain=0.92),
|
||||
_sil(0.28, sr),
|
||||
]),
|
||||
AudibleAlert.promptDistracted: np.concatenate([
|
||||
synth_emo_chirp(860, 1340, 0.10, sr, gain=0.94),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(1020, 1580, 0.14, sr, vibrato_hz=26, vibrato_depth=28, gain=0.94),
|
||||
_sil(0.28, sr),
|
||||
]),
|
||||
AudibleAlert.warningSoft: np.concatenate([
|
||||
synth_emo_chirp(1380, 1740, 0.11, sr, gain=0.96),
|
||||
_sil(0.025, sr),
|
||||
synth_emo_chirp(1740, 1280, 0.15, sr, gain=0.96),
|
||||
_sil(0.22, sr),
|
||||
]),
|
||||
AudibleAlert.warningImmediateSystem: np.concatenate([
|
||||
synth_emo_chirp(1480, 1860, 0.10, sr, gain=0.98),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1860, 1380, 0.14, sr, gain=0.98),
|
||||
_sil(0.18, sr),
|
||||
]),
|
||||
AudibleAlert.warningImmediateUser: np.concatenate([
|
||||
synth_emo_chirp(1540, 1920, 0.09, sr, gain=0.98),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1540, 1920, 0.09, sr, gain=0.98),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1920, 1420, 0.13, sr, gain=0.98),
|
||||
_sil(0.18, sr),
|
||||
]),
|
||||
# Reactive chirps for driving & user interactions (clearly audible & bubbly)
|
||||
CHIRP_SPEED_UP: np.concatenate([
|
||||
synth_emo_chirp(860, 1240, 0.09, sr, gain=0.88),
|
||||
_sil(0.018, sr),
|
||||
synth_emo_chirp(1220, 1680, 0.12, sr, vibrato_hz=24, vibrato_depth=26, gain=0.92),
|
||||
]),
|
||||
CHIRP_SPEED_DOWN: np.concatenate([
|
||||
synth_emo_chirp(1280, 920, 0.09, sr, gain=0.88),
|
||||
_sil(0.018, sr),
|
||||
synth_emo_chirp(920, 620, 0.12, sr, gain=0.88),
|
||||
]),
|
||||
CHIRP_STARTLED: np.concatenate([
|
||||
synth_emo_chirp(740, 1780, 0.13, sr, vibrato_hz=42, vibrato_depth=55, gain=0.94),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1560, 980, 0.12, sr, gain=0.90),
|
||||
]),
|
||||
CHIRP_BOOST: np.concatenate([
|
||||
synth_emo_chirp(660, 1120, 0.08, sr, gain=0.90),
|
||||
_sil(0.015, sr),
|
||||
synth_emo_chirp(1100, 1760, 0.16, sr, vibrato_hz=30, vibrato_depth=40, gain=0.94),
|
||||
]),
|
||||
CHIRP_BOOKMARK: np.concatenate([
|
||||
synth_emo_chirp(980, 1440, 0.09, sr, gain=0.92),
|
||||
_sil(0.02, sr),
|
||||
synth_emo_chirp(1280, 1820, 0.14, sr, vibrato_hz=28, vibrato_depth=32, gain=0.94),
|
||||
]),
|
||||
CHIRP_BLINKER: np.concatenate([
|
||||
synth_emo_chirp(920, 1260, 0.08, sr, gain=0.80),
|
||||
_sil(0.015, sr),
|
||||
synth_emo_chirp(1160, 1420, 0.08, sr, gain=0.80),
|
||||
]),
|
||||
}
|
||||
|
||||
|
||||
class RoboticSoundPack:
|
||||
"""Manages pre-loaded robotic voice/chirp buffers and reactive driving chirps for Soundd."""
|
||||
|
||||
def __init__(self, params, sample_rate: int = 48000):
|
||||
self._params = params
|
||||
self._sample_rate = sample_rate
|
||||
self.enabled: bool = self._params.get_bool("MiciRoboticUI")
|
||||
self.sounds: dict[int, np.ndarray] = {}
|
||||
|
||||
# Edge-detection state for reactive chirps
|
||||
self._prev_set_speed: float = SET_SPEED_NA
|
||||
self._prev_blinker: bool = False
|
||||
self._last_chirp_time: float = 0.0
|
||||
|
||||
def load(self) -> None:
|
||||
# Start with guaranteed pure-NumPy procedural chirps so soundd never fails if LFS WAVs are missing
|
||||
self.sounds = build_procedural_sounds(self._sample_rate)
|
||||
|
||||
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
|
||||
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
|
||||
if not os.path.exists(path):
|
||||
cloudlog.warning(f"Robotic sound file missing, using procedural fallback: {path}")
|
||||
continue
|
||||
try:
|
||||
with wave.open(path, "r") as wavefile:
|
||||
if (
|
||||
wavefile.getnchannels() != 1
|
||||
or wavefile.getsampwidth() != 2
|
||||
or wavefile.getframerate() != self._sample_rate
|
||||
):
|
||||
cloudlog.warning(f"Robotic sound format mismatch, using procedural fallback: {path}")
|
||||
continue
|
||||
length = wavefile.getnframes()
|
||||
if length > 0:
|
||||
self.sounds[alert_id] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16 / 2)
|
||||
except Exception as e:
|
||||
cloudlog.warning(f"Failed to load robotic WAV (possible Git LFS pointer), using procedural fallback: {path} ({e})")
|
||||
|
||||
def refresh_param(self) -> bool:
|
||||
"""Refresh MiciRoboticUI param; returns True if the enabled state changed."""
|
||||
new_val = self._params.get_bool("MiciRoboticUI")
|
||||
changed = new_val != self.enabled
|
||||
self.enabled = new_val
|
||||
if changed:
|
||||
cloudlog.info(f"RoboticSoundPack enabled={self.enabled}")
|
||||
return changed
|
||||
|
||||
def get_buffer(self, alert_id: int, default_sounds: dict[int, np.ndarray]) -> np.ndarray:
|
||||
if self.enabled and alert_id in self.sounds:
|
||||
return self.sounds[alert_id]
|
||||
return default_sounds[alert_id]
|
||||
|
||||
def detect_reactive_chirp(self, sm, now: float | None = None) -> int | None:
|
||||
"""Detect driving/user events that should emit a cute one-shot robotic chirp."""
|
||||
if not self.enabled:
|
||||
return None
|
||||
|
||||
t = time.monotonic() if now is None else now
|
||||
if t - self._last_chirp_time < CHIRP_COOLDOWN:
|
||||
return None
|
||||
|
||||
chirp: int | None = None
|
||||
|
||||
if sm.updated.get("userBookmark") or sm.updated.get("bookmarkButton"):
|
||||
chirp = CHIRP_BOOKMARK
|
||||
elif sm.updated.get("carState"):
|
||||
cs = sm["carState"]
|
||||
v_cruise = cs.vCruiseCluster
|
||||
if v_cruise == 0.0 and sm.valid.get("controlsState"):
|
||||
v_cruise = sm["controlsState"].deprecated.vCruise
|
||||
|
||||
cruise_set = 0 < v_cruise < SET_SPEED_NA
|
||||
if cruise_set and self._prev_set_speed != SET_SPEED_NA and v_cruise != self._prev_set_speed:
|
||||
chirp = CHIRP_SPEED_UP if v_cruise > self._prev_set_speed else CHIRP_SPEED_DOWN
|
||||
self._prev_set_speed = v_cruise
|
||||
|
||||
blinker = bool(cs.leftBlinker or cs.rightBlinker)
|
||||
if chirp is None and blinker and not self._prev_blinker:
|
||||
chirp = CHIRP_BLINKER
|
||||
self._prev_blinker = blinker
|
||||
|
||||
if chirp is None and not cs.standstill:
|
||||
if cs.aEgo < -3.0:
|
||||
chirp = CHIRP_STARTLED
|
||||
elif cs.aEgo > 2.2:
|
||||
chirp = CHIRP_BOOST
|
||||
|
||||
if chirp is not None:
|
||||
self._last_chirp_time = t
|
||||
return chirp
|
||||
@@ -1,25 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
# Parameters that should never be remotely modified
|
||||
BLOCKED_PARAMS = {
|
||||
"AdbEnabled",
|
||||
"BluetoothAllowed",
|
||||
"BluetoothEnabled",
|
||||
"CompletedSunnylinkConsentVersion",
|
||||
"CompletedTrainingVersion",
|
||||
"GithubUsername", # Could grant SSH access
|
||||
"GithubSshKeys", # Direct SSH key injection
|
||||
"HasAcceptedTerms",
|
||||
"HasAcceptedTermsSP",
|
||||
"OnroadCycleRequested", # Prevent remote cycle trigger
|
||||
"ParamsVersion", # Device-managed version counter
|
||||
}
|
||||
|
||||
|
||||
def is_local_param(key: str) -> bool:
|
||||
return key.startswith("SunnylinkLocal")
|
||||
|
||||
@@ -50,7 +50,18 @@ DISALLOW_LOG_UPLOAD = threading.Event()
|
||||
|
||||
params = Params()
|
||||
|
||||
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
|
||||
# Parameters that should never be remotely modified
|
||||
BLOCKED_PARAMS = {
|
||||
"AdbEnabled",
|
||||
"CompletedSunnylinkConsentVersion",
|
||||
"CompletedTrainingVersion",
|
||||
"GithubUsername", # Could grant SSH access
|
||||
"GithubSshKeys", # Direct SSH key injection
|
||||
"HasAcceptedTerms",
|
||||
"HasAcceptedTermsSP",
|
||||
"OnroadCycleRequested", # Prevent remote cycle trigger
|
||||
"ParamsVersion", # Device-managed version counter
|
||||
}
|
||||
|
||||
|
||||
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
|
||||
@@ -161,7 +172,7 @@ def toggleLogUpload(enabled: bool):
|
||||
@dispatcher.add_method
|
||||
def getParamsAllKeys() -> list[str]:
|
||||
keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()]
|
||||
return [key for key in keys if not is_local_param(key)]
|
||||
return keys
|
||||
|
||||
|
||||
@dispatcher.add_method
|
||||
@@ -203,7 +214,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
|
||||
ParamKeyType.BYTES.value: b"",
|
||||
}
|
||||
|
||||
param_keys_validated = [key for key in params_keys if key in available_keys and not is_local_param(key)]
|
||||
param_keys_validated = [key for key in params_keys if key in available_keys]
|
||||
params_dict: dict[str, list[dict[str, str | bool | int]]] = {"params": []}
|
||||
for key in param_keys_validated:
|
||||
value = get_param_as_byte(key)
|
||||
@@ -233,7 +244,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
|
||||
def saveParams(params_to_update: dict[str, str], compression: bool = False) -> None:
|
||||
for key, value in params_to_update.items():
|
||||
# disallow modifications to blocked parameters
|
||||
if key in BLOCKED_PARAMS or is_local_param(key):
|
||||
if key in BLOCKED_PARAMS:
|
||||
cloudlog.warning(f"sunnylinkd.saveParams.blocked: Attempted to modify blocked parameter '{key}'")
|
||||
continue
|
||||
|
||||
|
||||
@@ -58,24 +58,3 @@ class TestSunnylinkdMethods(OpenpilotTestCase):
|
||||
assert len(self.saved_params) == 1
|
||||
assert self.saved_params[0][0] == "SpeedLimitOffset"
|
||||
assert self.saved_params[0][1] == "10"
|
||||
|
||||
def test_saveParams_refuses_local_and_bluetooth_params(self):
|
||||
sunnylinkd.saveParams({
|
||||
"SunnylinkLocalBleGrants": "e30=",
|
||||
"SunnylinkLocalConnectPhoneRequest": "e30=",
|
||||
"BluetoothAllowed": "MQ==",
|
||||
"BluetoothEnabled": "MQ==",
|
||||
"SpeedLimitOffset": "5",
|
||||
})
|
||||
|
||||
assert [p[0] for p in self.saved_params] == ["SpeedLimitOffset"]
|
||||
|
||||
def test_local_params_are_hidden(self, mocker):
|
||||
params = mocker.patch.object(sunnylinkd, "Params").return_value
|
||||
params.all_keys.return_value = [b"SunnylinkEnabled", b"SunnylinkLocalBleGrants", b"SunnylinkLocalConnectPhoneWindow"]
|
||||
mocker.patch.object(sunnylinkd, "get_param_as_byte", return_value=b"1")
|
||||
|
||||
assert sunnylinkd.getParamsAllKeys() == ["SunnylinkEnabled"]
|
||||
response = sunnylinkd.getParams(["SunnylinkEnabled", "SunnylinkLocalBleGrants", "SunnylinkLocalConnectPhoneWindow"])
|
||||
assert set(response) == {"SunnylinkEnabled", "params"}
|
||||
assert "SunnylinkLocal" not in response["params"]
|
||||
|
||||
@@ -44,7 +44,6 @@ CAPABILITY_FIELDS = (
|
||||
"device_type",
|
||||
"subaru_has_sng",
|
||||
"hyundai_alpha_long_available",
|
||||
"hyundai_radar_tracks_available",
|
||||
"toyota_tss2",
|
||||
"custom_model_active",
|
||||
)
|
||||
@@ -69,7 +68,6 @@ CAPABILITY_LABELS: dict[str, str] = {
|
||||
"device_type": "Device type",
|
||||
"subaru_has_sng": "Subaru Stop-and-Go available",
|
||||
"hyundai_alpha_long_available": "Hyundai Alpha Longitudinal available",
|
||||
"hyundai_radar_tracks_available": "Hyundai radar tracks available",
|
||||
"toyota_tss2": "Toyota TSS2 platform",
|
||||
"custom_model_active": "Non-Default model selected",
|
||||
}
|
||||
@@ -90,7 +88,6 @@ CAR_CAPABILITY_FIELDS = (
|
||||
"has_stop_and_go",
|
||||
"subaru_has_sng",
|
||||
"hyundai_alpha_long_available",
|
||||
"hyundai_radar_tracks_available",
|
||||
"toyota_tss2",
|
||||
)
|
||||
|
||||
@@ -125,7 +122,6 @@ def _resolve_brand_capabilities(caps: dict, bundle_platform: str, CP) -> None:
|
||||
cloudlog.exception(f"capabilities: unknown hyundai platform {bundle_platform!r}")
|
||||
elif CP is not None:
|
||||
caps["hyundai_alpha_long_available"] = bool(CP.alphaLongitudinalAvailable)
|
||||
caps["hyundai_radar_tracks_available"] = not CP.radarUnavailable
|
||||
|
||||
elif brand == "subaru":
|
||||
if bundle_platform:
|
||||
|
||||
@@ -484,10 +484,6 @@
|
||||
"value": "",
|
||||
"label": "Default"
|
||||
},
|
||||
{
|
||||
"value": 2.0,
|
||||
"label": "pidd"
|
||||
},
|
||||
{
|
||||
"value": 1.0,
|
||||
"label": "v1.0"
|
||||
@@ -1540,19 +1536,6 @@
|
||||
"widget": "toggle",
|
||||
"title": "Tesla Rainbow Mode",
|
||||
"description": "Display a rainbow effect on the path the model wants to take. It does not affect driving in any way."
|
||||
},
|
||||
{
|
||||
"key": "MiciRoboticUI",
|
||||
"widget": "toggle",
|
||||
"title": "Robotic Companion UI",
|
||||
"description": "Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
"field": "device_type",
|
||||
"equals": "mici"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2203,9 +2186,22 @@
|
||||
"items": [
|
||||
{
|
||||
"key": "HyundaiLongitudinalTuning",
|
||||
"widget": "toggle",
|
||||
"widget": "multiple_button",
|
||||
"title": "Custom Longitudinal Tuning",
|
||||
"description": "Accelerates and brakes the way your car's own cruise control does.",
|
||||
"options": [
|
||||
{
|
||||
"value": 0,
|
||||
"label": "Off"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"label": "Dynamic"
|
||||
},
|
||||
{
|
||||
"value": 2,
|
||||
"label": "Predictive"
|
||||
}
|
||||
],
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
@@ -2223,37 +2219,6 @@
|
||||
"equals": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "RadarTracks",
|
||||
"widget": "multiple_button",
|
||||
"title": "Radar Tracks",
|
||||
"options": [
|
||||
{
|
||||
"value": 0,
|
||||
"label": "Off"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"label": "Lead Only"
|
||||
},
|
||||
{
|
||||
"value": 2,
|
||||
"label": "Full Radar"
|
||||
}
|
||||
],
|
||||
"visibility": [
|
||||
{
|
||||
"type": "capability",
|
||||
"field": "hyundai_radar_tracks_available",
|
||||
"equals": true
|
||||
}
|
||||
],
|
||||
"enablement": [
|
||||
{
|
||||
"type": "offroad_only"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -31,10 +31,6 @@ macros:
|
||||
- type: not
|
||||
condition: {type: capability, field: device_type, equals: mici}
|
||||
|
||||
# Show only on MICI hardware.
|
||||
mici_only:
|
||||
- {type: capability, field: device_type, equals: mici}
|
||||
|
||||
# Mirrors selfdrive/ui/sunnypilot/layouts/.../mads_settings.py:_mads_limited_settings()
|
||||
# Rivian + Tesla-without-vehicle-bus get the limited MADS UI (3-toggle subset).
|
||||
# On those platforms these toggles are disabled — full MADS settings are
|
||||
|
||||
@@ -225,8 +225,6 @@ sections:
|
||||
options:
|
||||
- value: ''
|
||||
label: Default
|
||||
- value: 2.0
|
||||
label: pidd
|
||||
- value: 1.0
|
||||
label: v1.0
|
||||
- value: 0.0
|
||||
|
||||
@@ -11,9 +11,15 @@ sections:
|
||||
description: ''
|
||||
items:
|
||||
- key: HyundaiLongitudinalTuning
|
||||
widget: toggle
|
||||
widget: multiple_button
|
||||
title: Custom Longitudinal Tuning
|
||||
description: Accelerates and brakes the way your car's own cruise control does.
|
||||
options:
|
||||
- value: 0
|
||||
label: 'Off'
|
||||
- value: 1
|
||||
label: Dynamic
|
||||
- value: 2
|
||||
label: Predictive
|
||||
visibility:
|
||||
- type: capability
|
||||
field: hyundai_alpha_long_available
|
||||
@@ -21,22 +27,6 @@ sections:
|
||||
enablement:
|
||||
- $ref: '#/macros/offroad'
|
||||
- $ref: '#/macros/longitudinal'
|
||||
- key: RadarTracks
|
||||
widget: multiple_button
|
||||
title: Radar Tracks
|
||||
options:
|
||||
- value: 0
|
||||
label: 'Off'
|
||||
- value: 1
|
||||
label: Lead Only
|
||||
- value: 2
|
||||
label: Full Radar
|
||||
visibility:
|
||||
- type: capability
|
||||
field: hyundai_radar_tracks_available
|
||||
equals: true
|
||||
enablement:
|
||||
- $ref: '#/macros/offroad'
|
||||
- id: subaru
|
||||
title: Subaru Settings
|
||||
description: ''
|
||||
|
||||
@@ -111,9 +111,3 @@ sections:
|
||||
widget: toggle
|
||||
title: Tesla Rainbow Mode
|
||||
description: Display a rainbow effect on the path the model wants to take. It does not affect driving in any way.
|
||||
- key: MiciRoboticUI
|
||||
widget: toggle
|
||||
title: Robotic Companion UI
|
||||
description: Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.
|
||||
visibility:
|
||||
- $ref: '#/macros/mici_only'
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
||||
|
||||
# draft-irtf-cfrg-cpace-21, CPACE-X25519-SHA512 (the same test vectors as -20)
|
||||
PAKE_SUITE = 1
|
||||
DSI = b"CPace255"
|
||||
CI = b"sunnylink-ble-connect-v1"
|
||||
|
||||
P = 2**255 - 19
|
||||
J = 486662
|
||||
C2 = pow(2, (P + 3) // 8, P)
|
||||
C3 = pow(2, (P - 1) // 4, P) # sqrt(-1)
|
||||
C4 = (P - 5) // 8
|
||||
|
||||
|
||||
class CpaceError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def lv(data: bytes) -> bytes:
|
||||
# LEB128 length prefix, as the draft's prepend_len
|
||||
n = len(data)
|
||||
head = bytearray()
|
||||
while True:
|
||||
head.append((n & 0x7F) | (0x80 if n >> 7 else 0))
|
||||
n >>= 7
|
||||
if not n:
|
||||
return bytes(head) + data
|
||||
|
||||
|
||||
def _cmov(a: int, b: int, cond: bool) -> int:
|
||||
# b if cond else a, as a mask select; Python bigints are not constant time regardless
|
||||
mask = -int(cond)
|
||||
return (a & ~mask) | (b & mask)
|
||||
|
||||
|
||||
def map_to_curve_elligator2_curve25519(u: int) -> int:
|
||||
# RFC 9380 G.2.1 straight-line map, Z = 2. Only x is returned: the RFC's y, x2 sign fix and y2 steps
|
||||
# feed nothing CPace uses, and x only depends on e3 (which needs y1).
|
||||
tv1 = 2 * u * u % P
|
||||
xd = (tv1 + 1) % P
|
||||
x1n = -J % P
|
||||
tv2 = xd * xd % P
|
||||
gxd = tv2 * xd % P
|
||||
gx1 = J * tv1 % P * x1n % P
|
||||
gx1 = (gx1 + tv2) % P * x1n % P
|
||||
tv3 = gxd * gxd % P
|
||||
tv2 = tv3 * tv3 % P
|
||||
tv3 = tv3 * gxd % P
|
||||
tv3 = tv3 * gx1 % P
|
||||
tv2 = tv2 * tv3 % P
|
||||
y11 = pow(tv2, C4, P) * tv3 % P
|
||||
y12 = y11 * C3 % P
|
||||
e1 = (y11 * y11 % P * gxd - gx1) % P == 0
|
||||
y1 = _cmov(y12, y11, e1)
|
||||
x2n = x1n * tv1 % P
|
||||
e3 = (y1 * y1 % P * gxd - gx1) % P == 0
|
||||
xn = _cmov(x2n, x1n, e3)
|
||||
return xn * pow(xd, P - 2, P) % P
|
||||
|
||||
|
||||
def generator(prs: bytes, ci: bytes, sid: bytes) -> bytes:
|
||||
zpad = max(0, 128 - len(lv(prs)) - len(lv(DSI)) - 1)
|
||||
gen_str = lv(DSI) + lv(prs) + lv(bytes(zpad)) + lv(ci) + lv(sid)
|
||||
u = int.from_bytes(hashlib.sha512(gen_str).digest()[:32], "little") & ((1 << 255) - 1)
|
||||
return map_to_curve_elligator2_curve25519(u % P).to_bytes(32, "little")
|
||||
|
||||
|
||||
def _scalar_mult(scalar: bytes, point: bytes) -> bytes:
|
||||
try:
|
||||
k = X25519PrivateKey.from_private_bytes(scalar).exchange(X25519PublicKey.from_public_bytes(point))
|
||||
except ValueError as e:
|
||||
raise CpaceError("low-order or malformed point") from e
|
||||
if k == bytes(32):
|
||||
raise CpaceError("low-order point")
|
||||
return k
|
||||
|
||||
|
||||
def _tag(isk: bytes, sid: bytes, share: bytes, ad: bytes) -> bytes:
|
||||
mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()
|
||||
return hmac.new(mac_key, lv(share) + lv(ad), hashlib.sha512).digest()
|
||||
|
||||
|
||||
class Cpace:
|
||||
def __init__(self, initiator: bool, prs: bytes, sid: bytes, ad_a: bytes, ad_b: bytes, *, scalar: bytes | None = None):
|
||||
self._initiator = initiator
|
||||
self._sid = sid
|
||||
self._ad_a, self._ad_b = ad_a, ad_b
|
||||
self._scalar = scalar if scalar is not None else secrets.token_bytes(32)
|
||||
self.public = _scalar_mult(self._scalar, generator(prs, CI, sid))
|
||||
|
||||
def isk(self, peer_share: bytes) -> bytes:
|
||||
k = _scalar_mult(self._scalar, peer_share)
|
||||
ya, yb = (self.public, peer_share) if self._initiator else (peer_share, self.public)
|
||||
transcript = lv(ya) + lv(self._ad_a) + lv(yb) + lv(self._ad_b)
|
||||
return hashlib.sha512(lv(DSI + b"_ISK") + lv(self._sid) + lv(k) + transcript).digest()
|
||||
|
||||
def tag(self, isk: bytes) -> bytes:
|
||||
own_ad = self._ad_a if self._initiator else self._ad_b
|
||||
return _tag(isk, self._sid, self.public, own_ad)
|
||||
|
||||
def check(self, isk: bytes, peer_share: bytes, peer_tag: bytes) -> bool:
|
||||
peer_ad = self._ad_b if self._initiator else self._ad_a
|
||||
return hmac.compare_digest(_tag(isk, self._sid, peer_share, peer_ad), peer_tag)
|
||||
@@ -1,39 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import base64
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
|
||||
GRANTS_KEY = "SunnylinkLocalBleGrants"
|
||||
KEY_KEY = "SunnylinkLocalBleKey"
|
||||
MAX_PHONES = 8
|
||||
|
||||
|
||||
def b64(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def unb64(text: str) -> bytes:
|
||||
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||
|
||||
|
||||
def load(params) -> list[dict]:
|
||||
grants = params.get(GRANTS_KEY)
|
||||
return grants if isinstance(grants, list) else []
|
||||
|
||||
|
||||
def save(params, grants: list[dict]):
|
||||
params.put(GRANTS_KEY, grants, block=True)
|
||||
|
||||
|
||||
def static_private(params) -> X25519PrivateKey:
|
||||
raw = params.get(KEY_KEY)
|
||||
if not isinstance(raw, bytes) or len(raw) != 32:
|
||||
raw = secrets.token_bytes(32)
|
||||
params.put(KEY_KEY, raw, block=True)
|
||||
return X25519PrivateKey.from_private_bytes(raw)
|
||||
@@ -1,141 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
from cryptography.exceptions import InvalidSignature, InvalidTag
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
MORE = 0x01
|
||||
PAKE_SUITE = 1 # CPACE-X25519-SHA512; 0 is a development build with no PAKE
|
||||
MTU_MIN = 23
|
||||
FRAME_HEADER = 3
|
||||
MAX_ATT_VALUE = 512 # Bluetooth caps an attribute value at 512 bytes whatever the MTU
|
||||
PRE_SESSION_CAP = 1024
|
||||
SESSION_CAP = 65536
|
||||
RECORD_TYPE = 0x20
|
||||
REKEY_INTERVAL = 65536
|
||||
KEYS_INFO = b"sunnylink-ble-connect-v1 keys"
|
||||
KEYS_SIGNED_TAG = b"sunnylink-ble-keys-v1\x00"
|
||||
|
||||
|
||||
class LinkError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def frames(message: bytes, link_id: int, max_frame: int) -> list[bytes]:
|
||||
# max_frame is the ATT payload (MTU - 3); each frame carries 3 header bytes of it
|
||||
max_frame = min(max_frame, MAX_ATT_VALUE)
|
||||
if not 1 <= link_id <= 0xFFFF:
|
||||
raise LinkError("link id")
|
||||
if max_frame < MTU_MIN - 3 or not message:
|
||||
raise LinkError("frame size or empty message")
|
||||
size = max_frame - FRAME_HEADER
|
||||
chunks = [message[i:i + size] for i in range(0, len(message), size)]
|
||||
return [bytes([MORE if i < len(chunks) - 1 else 0]) + link_id.to_bytes(2, "big") + c for i, c in enumerate(chunks)]
|
||||
|
||||
|
||||
class Reassembler:
|
||||
def __init__(self, link_id: int, cap: int = PRE_SESSION_CAP):
|
||||
self.link_id = link_id
|
||||
self.cap = cap # set to SESSION_CAP once the session is up
|
||||
self._buf = bytearray()
|
||||
|
||||
def feed(self, frame: bytes) -> bytes | None:
|
||||
if len(frame) <= FRAME_HEADER or frame[0] & ~MORE or int.from_bytes(frame[1:3], "big") != self.link_id:
|
||||
self._buf.clear()
|
||||
raise LinkError("malformed frame")
|
||||
self._buf += frame[FRAME_HEADER:]
|
||||
if len(self._buf) > self.cap:
|
||||
self._buf.clear()
|
||||
raise LinkError("message over cap")
|
||||
if frame[0] & MORE:
|
||||
return None
|
||||
message, self._buf = bytes(self._buf), bytearray()
|
||||
return message
|
||||
|
||||
|
||||
def _nonce(n: int) -> bytes:
|
||||
return b"\x00" * 4 + n.to_bytes(8, "little")
|
||||
|
||||
|
||||
def _rekey(key: bytes) -> bytes:
|
||||
return ChaCha20Poly1305(key).encrypt(_nonce(2**64 - 1), bytes(32), b"")[:32]
|
||||
|
||||
|
||||
class Records:
|
||||
def __init__(self, send_key: bytes, recv_key: bytes, link_id: int, *, rekey_interval: int = REKEY_INTERVAL):
|
||||
self._send, self._recv = send_key, recv_key
|
||||
self._aad = bytes([RECORD_TYPE]) + link_id.to_bytes(2, "big")
|
||||
self._interval = rekey_interval
|
||||
self._ns = 0
|
||||
self._nr = 0
|
||||
|
||||
def seal(self, inner: bytes) -> bytes:
|
||||
if self._ns and self._ns % self._interval == 0:
|
||||
self._send = _rekey(self._send)
|
||||
ct = ChaCha20Poly1305(self._send).encrypt(_nonce(self._ns), inner, self._aad)
|
||||
self._ns += 1
|
||||
return bytes([RECORD_TYPE]) + ct
|
||||
|
||||
def open(self, record: bytes) -> bytes:
|
||||
if len(record) < 1 + 1 + 16 or record[0] != RECORD_TYPE:
|
||||
raise LinkError("not a record")
|
||||
if self._nr and self._nr % self._interval == 0:
|
||||
self._recv = _rekey(self._recv)
|
||||
try:
|
||||
inner = ChaCha20Poly1305(self._recv).decrypt(_nonce(self._nr), record[1:], self._aad)
|
||||
except InvalidTag as e:
|
||||
raise LinkError("record authentication failed") from e
|
||||
self._nr += 1
|
||||
return inner
|
||||
|
||||
|
||||
def transcript(*bodies: bytes) -> bytes:
|
||||
# connect_start, connect_window, pake_a, pake_b, confirm_a, confirm_b: clear bodies, fixed sizes, no separators
|
||||
if len(bodies) != 6:
|
||||
raise ValueError("transcript takes six bodies")
|
||||
return hashlib.sha256(b"".join(bodies)).digest()
|
||||
|
||||
|
||||
def session_keys(isk: bytes, sid: bytes) -> tuple[bytes, bytes, str]:
|
||||
okm = HKDF(algorithm=hashes.SHA256(), length=68, salt=sid, info=KEYS_INFO).derive(isk)
|
||||
check = int.from_bytes(okm[64:68], "big") % 1_000_000
|
||||
return okm[:32], okm[32:64], f"{check:06d}"
|
||||
|
||||
|
||||
def signed_bytes(role: str, th: bytes, spki: bytes, static: bytes) -> bytes:
|
||||
if role not in ("D", "P") or len(th) != 32 or len(static) != 32:
|
||||
raise ValueError("signed bytes")
|
||||
return KEYS_SIGNED_TAG + role.encode() + th + hashlib.sha256(spki).digest() + static
|
||||
|
||||
|
||||
def sign(key, data: bytes) -> tuple[str, bytes]:
|
||||
if isinstance(key, rsa.RSAPrivateKey):
|
||||
return "RS256", key.sign(data, padding.PKCS1v15(), hashes.SHA256())
|
||||
if isinstance(key, ec.EllipticCurvePrivateKey) and key.curve.name == "secp256r1":
|
||||
return "ES256", key.sign(data, ec.ECDSA(hashes.SHA256()))
|
||||
raise ValueError("unsupported key")
|
||||
|
||||
|
||||
def verify(alg: str, spki: bytes, data: bytes, sig: bytes) -> bool:
|
||||
try:
|
||||
pub = serialization.load_der_public_key(spki)
|
||||
except ValueError:
|
||||
return False
|
||||
try:
|
||||
if alg == "RS256" and isinstance(pub, rsa.RSAPublicKey):
|
||||
pub.verify(sig, data, padding.PKCS1v15(), hashes.SHA256())
|
||||
elif alg == "ES256" and isinstance(pub, ec.EllipticCurvePublicKey) and pub.curve.name == "secp256r1":
|
||||
pub.verify(sig, data, ec.ECDSA(hashes.SHA256()))
|
||||
else:
|
||||
return False
|
||||
except InvalidSignature:
|
||||
return False
|
||||
return True
|
||||
@@ -1,125 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
# Noise revision 34, pattern KK only
|
||||
PROTOCOL = b"Noise_KK_25519_ChaChaPoly_SHA256" # exactly 32 bytes, so h starts as the name itself
|
||||
PROLOGUE = b"sunnylink-ble-v1"
|
||||
|
||||
|
||||
class NoiseError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _hkdf2(ck: bytes, ikm: bytes) -> tuple[bytes, bytes]:
|
||||
temp = hmac.new(ck, ikm, hashlib.sha256).digest()
|
||||
out1 = hmac.new(temp, b"\x01", hashlib.sha256).digest()
|
||||
return out1, hmac.new(temp, out1 + b"\x02", hashlib.sha256).digest()
|
||||
|
||||
|
||||
def _nonce(n: int) -> bytes:
|
||||
return b"\x00" * 4 + n.to_bytes(8, "little")
|
||||
|
||||
|
||||
def _dh(priv: X25519PrivateKey, pub: bytes) -> bytes:
|
||||
try:
|
||||
return priv.exchange(X25519PublicKey.from_public_bytes(pub))
|
||||
except ValueError as e:
|
||||
raise NoiseError("low-order or malformed key") from e
|
||||
|
||||
|
||||
class KKHandshake:
|
||||
# Messages: -> e, es, ss <- e, ee, se (initiator = phone, responder = comma)
|
||||
def __init__(self, initiator: bool, s: X25519PrivateKey, rs: bytes, *, e: X25519PrivateKey | None = None,
|
||||
prologue: bytes = PROLOGUE):
|
||||
self._initiator = initiator
|
||||
self._s = s
|
||||
self._rs = rs
|
||||
self._e = e
|
||||
self._re: bytes | None = None
|
||||
self._step = 0 # 0 first message, 1 second, 2 done
|
||||
self._h = PROTOCOL
|
||||
self._ck = PROTOCOL
|
||||
self._k: bytes | None = None
|
||||
self._n = 0
|
||||
s_pub = s.public_key().public_bytes_raw()
|
||||
self._mix_hash(prologue)
|
||||
# pre-messages, initiator's static key first
|
||||
self._mix_hash(s_pub if initiator else rs)
|
||||
self._mix_hash(rs if initiator else s_pub)
|
||||
|
||||
def _mix_hash(self, data: bytes):
|
||||
self._h = hashlib.sha256(self._h + data).digest()
|
||||
|
||||
def _mix_key(self, ikm: bytes):
|
||||
self._ck, temp = _hkdf2(self._ck, ikm)
|
||||
self._k, self._n = temp, 0
|
||||
|
||||
def _encrypt(self, plaintext: bytes) -> bytes:
|
||||
ct = ChaCha20Poly1305(self._k).encrypt(_nonce(self._n), plaintext, self._h)
|
||||
self._n += 1
|
||||
self._mix_hash(ct)
|
||||
return ct
|
||||
|
||||
def _decrypt(self, ciphertext: bytes) -> bytes:
|
||||
try:
|
||||
pt = ChaCha20Poly1305(self._k).decrypt(_nonce(self._n), ciphertext, self._h)
|
||||
except InvalidTag as e:
|
||||
raise NoiseError("handshake authentication failed") from e
|
||||
self._n += 1
|
||||
self._mix_hash(ciphertext)
|
||||
return pt
|
||||
|
||||
def _local_e(self) -> bytes:
|
||||
if self._e is None:
|
||||
self._e = X25519PrivateKey.generate()
|
||||
e_pub = self._e.public_key().public_bytes_raw()
|
||||
self._mix_hash(e_pub)
|
||||
return e_pub
|
||||
|
||||
def write(self, payload: bytes = b"") -> bytes:
|
||||
if self._initiator and self._step == 0:
|
||||
e_pub = self._local_e()
|
||||
self._mix_key(_dh(self._e, self._rs)) # es
|
||||
self._mix_key(_dh(self._s, self._rs)) # ss
|
||||
elif not self._initiator and self._step == 1:
|
||||
e_pub = self._local_e()
|
||||
self._mix_key(_dh(self._e, self._re)) # ee
|
||||
self._mix_key(_dh(self._e, self._rs)) # se
|
||||
else:
|
||||
raise NoiseError("write out of order")
|
||||
self._step += 1
|
||||
return e_pub + self._encrypt(payload)
|
||||
|
||||
def read(self, message: bytes) -> bytes:
|
||||
if len(message) < 32 + 16:
|
||||
raise NoiseError("short handshake message")
|
||||
e_pub, body = message[:32], message[32:]
|
||||
if not self._initiator and self._step == 0:
|
||||
self._re = e_pub
|
||||
self._mix_hash(e_pub)
|
||||
self._mix_key(_dh(self._s, e_pub)) # es
|
||||
self._mix_key(_dh(self._s, self._rs)) # ss
|
||||
elif self._initiator and self._step == 1:
|
||||
self._mix_hash(e_pub)
|
||||
self._mix_key(_dh(self._e, e_pub)) # ee
|
||||
self._mix_key(_dh(self._s, e_pub)) # se
|
||||
else:
|
||||
raise NoiseError("read out of order")
|
||||
self._step += 1
|
||||
return self._decrypt(body)
|
||||
|
||||
def split(self) -> tuple[bytes, bytes]:
|
||||
if self._step != 2:
|
||||
raise NoiseError("handshake not finished")
|
||||
k1, k2 = _hkdf2(self._ck, b"")
|
||||
return (k1, k2) if self._initiator else (k2, k1)
|
||||
@@ -1,202 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import base64
|
||||
import gzip
|
||||
import json
|
||||
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
from openpilot.common.params import ParamKeyType
|
||||
from openpilot.common.version import get_version
|
||||
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
|
||||
|
||||
# what sunnylink's getParams reports for a key that was never set and has no default
|
||||
UNSET_VALUES = {ParamKeyType.BOOL: False, ParamKeyType.INT: 0, ParamKeyType.FLOAT: 0.0, ParamKeyType.STRING: "", ParamKeyType.JSON: {}}
|
||||
|
||||
METHOD_NOT_FOUND = -32601
|
||||
INVALID_REQUEST = -32600
|
||||
REFUSED = -32001
|
||||
MAX_PARAM_KEYS = 32
|
||||
HOTSPOT_WAIT = 30.0 # seconds for the hotspot to come up after hotspot.start
|
||||
|
||||
|
||||
class RpcError(Exception):
|
||||
def __init__(self, code: int, message: str):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _refused(message: str) -> RpcError:
|
||||
return RpcError(REFUSED, message)
|
||||
|
||||
|
||||
def _wifi_status() -> dict:
|
||||
# wpa_supplicant answers at once; a fresh WifiManager reports no SSID until its own thread catches up
|
||||
try:
|
||||
from openpilot.common.hardware.comma.hardware import wpa_supplicant_cmd
|
||||
status = wpa_supplicant_cmd("STATUS")
|
||||
except (OSError, ImportError):
|
||||
return {"wifi_ssid": None, "hotspot": False}
|
||||
hotspot = status.get("mode") == "AP"
|
||||
connected = status.get("wpa_state") == "COMPLETED" and not hotspot
|
||||
return {"wifi_ssid": (status.get("ssid") or None) if connected else None, "hotspot": hotspot}
|
||||
|
||||
|
||||
def _default_wifi():
|
||||
from openpilot.system.ui.lib.wifi_manager import WifiManager
|
||||
return WifiManager()
|
||||
|
||||
|
||||
class Rpc:
|
||||
def __init__(self, params, wifi=None):
|
||||
self._params = params
|
||||
self._wifi_factory = wifi or _default_wifi
|
||||
self._wifi_obj = None
|
||||
self._pending: list[tuple[str, int, float]] = [] # hotspot.start waiting for the hotspot
|
||||
|
||||
def handle(self, token: str, body: bytes, grants: list[dict], this: str | None, now: float) -> tuple[dict | None, str | None]:
|
||||
# returns (response, after): response None means answered later by poll(); after "forget" drops the link
|
||||
try:
|
||||
request = json.loads(body)
|
||||
rid, method = request["id"], request["method"]
|
||||
if not isinstance(rid, int) or not isinstance(method, str):
|
||||
raise TypeError("id and method")
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return _envelope(None, error=(INVALID_REQUEST, "invalid request")), None
|
||||
args = request.get("params") or {}
|
||||
try:
|
||||
return self._dispatch(token, rid, method, args, grants, this, now)
|
||||
except RpcError as e:
|
||||
return _envelope(rid, error=(e.code, str(e))), None
|
||||
|
||||
def poll(self, now: float) -> list[tuple[str, dict]]:
|
||||
done, waiting = [], []
|
||||
for token, rid, deadline in self._pending:
|
||||
wifi = self._wifi()
|
||||
if wifi.is_tethering_active():
|
||||
done.append((token, _envelope(rid, result=self._credentials(wifi))))
|
||||
elif now >= deadline:
|
||||
done.append((token, _envelope(rid, error=(REFUSED, "hotspot did not start"))))
|
||||
else:
|
||||
waiting.append((token, rid, deadline))
|
||||
self._pending = waiting
|
||||
return done
|
||||
|
||||
def _dispatch(self, token, rid, method, args, grants, this, now):
|
||||
if method == "status.get":
|
||||
return _envelope(rid, result=self._status(grants)), None
|
||||
if method == "params.get":
|
||||
return _envelope(rid, result=self._get(args)), None
|
||||
if method == "params.set":
|
||||
return _envelope(rid, result=self._set(args)), None
|
||||
if method == "params.metadata":
|
||||
return _envelope(rid, result=self._params_metadata()), None
|
||||
if method == "hotspot.start":
|
||||
wifi = self._wifi()
|
||||
if wifi.is_tethering_active():
|
||||
return _envelope(rid, result=self._credentials(wifi)), None
|
||||
wifi.set_tethering_active(True)
|
||||
self._pending.append((token, rid, now + HOTSPOT_WAIT))
|
||||
return None, None
|
||||
if method == "hotspot.stop":
|
||||
self._wifi().set_tethering_active(False)
|
||||
return _envelope(rid, result={}), None
|
||||
if method == "hotspot.credentials":
|
||||
wifi = self._wifi()
|
||||
if not wifi.is_tethering_active():
|
||||
raise _refused("hotspot is off")
|
||||
return _envelope(rid, result=self._credentials(wifi)), None
|
||||
if method == "phones.list":
|
||||
return _envelope(rid, result=[{"name": g["name"], "added": g["added"], "last_seen": g["last_seen"],
|
||||
"this": g["spki"] == this} for g in grants]), None
|
||||
if method == "phones.forgetSelf":
|
||||
return _envelope(rid, result={}), "forget"
|
||||
raise RpcError(METHOD_NOT_FOUND, f"unknown method {method}")
|
||||
|
||||
def _wifi(self):
|
||||
if self._wifi_obj is None:
|
||||
try:
|
||||
self._wifi_obj = self._wifi_factory()
|
||||
except Exception as e:
|
||||
raise _refused("wifi unavailable") from e
|
||||
return self._wifi_obj
|
||||
|
||||
def _credentials(self, wifi) -> dict:
|
||||
return {"ssid": wifi.tethering_ssid, "password": wifi.tethering_password}
|
||||
|
||||
def _status(self, grants: list[dict]) -> dict:
|
||||
return {"version": get_version(), "agnos": HARDWARE.get_os_version(), "dongle_id": self._params.get("DongleId"),
|
||||
"onroad": not self._params.get_bool("IsOffroad"), "engaged": self._params.get_bool("IsEngaged"),
|
||||
"network": _wifi_status(), "phones": len(grants), "capabilities": ["ssh"]}
|
||||
|
||||
def _known(self) -> set[str]:
|
||||
return {key.decode() for key in self._params.all_keys()}
|
||||
|
||||
def _check_keys(self, keys: list[str]):
|
||||
for key in keys:
|
||||
if key in BLOCKED_PARAMS or is_local_param(key):
|
||||
raise _refused(f"{key} is not available")
|
||||
|
||||
def _check_known(self, keys: list[str]):
|
||||
known = self._known()
|
||||
for key in keys:
|
||||
if key not in known:
|
||||
raise _refused(f"unknown param {key}")
|
||||
|
||||
def _get(self, args: dict) -> dict:
|
||||
keys = args.get("keys")
|
||||
if not isinstance(keys, list) or len(keys) > MAX_PARAM_KEYS or not all(isinstance(k, str) for k in keys):
|
||||
raise _refused("keys must be a list of at most 32 names")
|
||||
known = self._known()
|
||||
values = {}
|
||||
for key in keys:
|
||||
value = self._params.get(key, return_default=True) if key in known else None
|
||||
if value is None and key in known:
|
||||
value = UNSET_VALUES.get(self._params.get_type(key))
|
||||
values[key] = None if isinstance(value, bytes) else value # raw bytes have no JSON form
|
||||
return {"values": values}
|
||||
|
||||
def _set(self, args: dict) -> dict:
|
||||
values = args.get("values")
|
||||
if not isinstance(values, dict):
|
||||
raise _refused("values must be an object")
|
||||
self._check_keys(list(values))
|
||||
self._check_known(list(values))
|
||||
for key, value in values.items():
|
||||
try:
|
||||
self._params.put(key, value, block=True)
|
||||
except (TypeError, ValueError, KeyError) as e:
|
||||
raise _refused(f"bad value for {key}") from e
|
||||
return {"ok": list(values)}
|
||||
|
||||
def _params_metadata(self) -> dict:
|
||||
from openpilot.sunnypilot.models.model_name import DEFAULT_BIG_MODEL, DEFAULT_MODEL
|
||||
from openpilot.sunnypilot.sunnylink.capabilities import (
|
||||
CAPABILITY_LABELS,
|
||||
CAR_CAPABILITY_FIELDS,
|
||||
generate_capabilities,
|
||||
)
|
||||
from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import generate_schema
|
||||
|
||||
try:
|
||||
schema = generate_schema()
|
||||
schema["capabilities"] = generate_capabilities(self._params)
|
||||
schema["capability_labels"] = CAPABILITY_LABELS
|
||||
schema["car_capability_fields"] = CAR_CAPABILITY_FIELDS
|
||||
schema["default_model"] = DEFAULT_MODEL
|
||||
schema["default_big_model"] = DEFAULT_BIG_MODEL
|
||||
schema["chestnut_active"] = self._params.get_bool("ChestnutActive")
|
||||
raw = json.dumps(schema, separators=(",", ":")).encode("utf-8")
|
||||
encoded = base64.b64encode(gzip.compress(raw)).decode("utf-8")
|
||||
return {"params_metadata": encoded}
|
||||
except Exception as e:
|
||||
raise _refused("params metadata unavailable") from e
|
||||
|
||||
|
||||
def _envelope(rid, result=None, error=None) -> dict:
|
||||
if error is not None:
|
||||
return {"jsonrpc": "2.0", "id": rid, "error": {"code": error[0], "message": error[1]}}
|
||||
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
||||
@@ -1,346 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from openpilot.sunnypilot.system import connect_phone
|
||||
from openpilot.sunnypilot.system.ble import cpace, grants, link, noise
|
||||
from openpilot.sunnypilot.system.ble.rpc import Rpc
|
||||
from openpilot.sunnypilot.system.ble.stream import Streams
|
||||
|
||||
PROTO = 1
|
||||
CONNECT_START, CONNECT_WINDOW, PAKE_A, PAKE_B, CONFIRM_A, CONFIRM_B = 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
|
||||
RESUME_1, RESUME_2, ERROR = 0x10, 0x11, 0x7F
|
||||
DECISION, DEVICE_KEYS, PHONE_KEYS, GRANT_RESULT, RPC, STREAM = 0x30, 0x31, 0x32, 0x33, 0x40, 0x50
|
||||
ERR_NO_WINDOW, ERR_BUSY, ERR_VERSION, ERR_WRONG_CODE, ERR_WINDOW_CLOSED, ERR_TIMEOUT, ERR_UNKNOWN_PHONE = 1, 2, 3, 4, 5, 6, 8
|
||||
ALLOW, DENY, NO_ANSWER = 1, 2, 3
|
||||
GRANT_ADDED, GRANT_REFUSED = 1, 2 # 3 reserved
|
||||
RESUMED = 1
|
||||
RESUME_1_LEN = 32 + 1 + 16 # e, then one AEAD of the proto byte
|
||||
MAX_WRONG = 5
|
||||
IDLE_SECONDS = 10.0
|
||||
TOTAL_SECONDS = 60.0
|
||||
ALLOW_SECONDS = 30.0
|
||||
PRE_AUTH = ("new", "start", "confirm")
|
||||
CEREMONY = ("start", "confirm", "decide", "keys")
|
||||
HELD = ("decide", "keys") # the phone proved the code; the window waits on these
|
||||
|
||||
Action = tuple[str, object] # ("notify", frame bytes) or ("disconnect", device path)
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _Link:
|
||||
device: str
|
||||
connected: float
|
||||
last: float
|
||||
mtu: int = 23
|
||||
link_id: int = 0
|
||||
reasm: link.Reassembler | None = None
|
||||
phase: str = "new"
|
||||
since: float = 0.0
|
||||
nonce: bytes = b""
|
||||
sid: bytes = b""
|
||||
start_body: bytes = b""
|
||||
window_body: bytes = b""
|
||||
cp: cpace.Cpace | None = None
|
||||
isk: bytes = b""
|
||||
ya: bytes = b""
|
||||
yb: bytes = b""
|
||||
th: bytes = b""
|
||||
check: str = ""
|
||||
records: link.Records | None = None
|
||||
phone: dict | None = None
|
||||
grant: str = ""
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, params, window, *, wifi: Callable | None = None, wall: Callable[[], float] = time.time, # noqa: TID251 unix time: the app shows added and last_seen
|
||||
stream_host: str = "127.0.0.1"):
|
||||
self._params = params
|
||||
self._window = window
|
||||
self._wall = wall
|
||||
self._links: dict[str, _Link] = {}
|
||||
self._fail_nonce = b""
|
||||
self._fails = 0
|
||||
self._rpc = Rpc(params, wifi)
|
||||
self._streams = Streams(target_host=stream_host)
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int, now: float) -> list[Action]:
|
||||
lk = self._links.get(device)
|
||||
if lk is None:
|
||||
lk = self._links[device] = _Link(device, connected=now, last=now)
|
||||
lk.mtu = mtu
|
||||
if lk.reasm is None:
|
||||
if len(value) < 3:
|
||||
return self._drop(lk)
|
||||
lid = int.from_bytes(value[1:3], "big")
|
||||
# the id is bound to the first connection that uses it; a newcomer with a used id is dropped
|
||||
if lid == 0 or any(o.link_id == lid for o in self._links.values() if o is not lk):
|
||||
return self._drop(lk)
|
||||
lk.link_id, lk.reasm = lid, link.Reassembler(lid)
|
||||
lk.last = now
|
||||
try:
|
||||
msg = lk.reasm.feed(value)
|
||||
if msg is None:
|
||||
return []
|
||||
return self._message(lk, msg, now)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return self._drop(lk)
|
||||
|
||||
def on_disconnect(self, device: str):
|
||||
if (lk := self._links.get(device)) is not None:
|
||||
self._drop(lk)
|
||||
|
||||
def tick(self, now: float) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
secret = self._window.secret()
|
||||
for lk in list(self._links.values()):
|
||||
if self._links.get(lk.device) is not lk:
|
||||
continue
|
||||
if lk.phase in CEREMONY and (secret is None or lk.nonce != secret[1]):
|
||||
acts += self._drop(lk)
|
||||
elif lk.phase in PRE_AUTH and (now - lk.last >= IDLE_SECONDS or now - lk.connected >= TOTAL_SECONDS):
|
||||
acts += self._error(lk, ERR_TIMEOUT)
|
||||
elif lk.phase == "decide" and now - lk.since >= ALLOW_SECONDS:
|
||||
self._window.cancel("no_answer")
|
||||
acts += self._record(lk, DECISION, bytes([NO_ANSWER])) + self._drop(lk)
|
||||
elif lk.phase == "keys" and now - lk.since >= ALLOW_SECONDS:
|
||||
self._window.cancel("timeout")
|
||||
acts += self._drop(lk)
|
||||
for device, response in self._rpc.poll(now):
|
||||
lk = self._links.get(device)
|
||||
if lk is not None and lk.phase == "session":
|
||||
acts += self._record(lk, RPC, _json(response))
|
||||
acts += self._stream_actions(self._streams.tick(now))
|
||||
return acts
|
||||
|
||||
def stream_selector_entries(self) -> list[tuple[int, int]]:
|
||||
return self._streams.selector_entries()
|
||||
|
||||
def on_stream_ready(self, fd: int, readable: bool, writable: bool) -> list[Action]:
|
||||
return self._stream_actions(self._streams.on_socket_ready(fd, readable, writable))
|
||||
|
||||
def prompt(self, now: float) -> dict | None:
|
||||
lk = next((o for o in self._links.values() if o.phase == "decide"), None)
|
||||
if lk is None:
|
||||
return None
|
||||
return {"step": "allow", "check": f"{lk.check[:3]} {lk.check[3:]}", "until": lk.since + ALLOW_SECONDS}
|
||||
|
||||
def connected(self) -> int:
|
||||
return sum(1 for lk in self._links.values() if lk.phase == "session")
|
||||
|
||||
def answer(self, allow: bool, now: float) -> list[Action]:
|
||||
lk = next((o for o in self._links.values() if o.phase == "decide"), None)
|
||||
if lk is None:
|
||||
return []
|
||||
if not allow:
|
||||
self._window.cancel("denied")
|
||||
return self._record(lk, DECISION, bytes([DENY])) + self._drop(lk)
|
||||
acts = self._record(lk, DECISION, bytes([ALLOW]))
|
||||
try:
|
||||
spki, key = connect_phone.device_identity()
|
||||
except RuntimeError:
|
||||
self._window.cancel("no_key")
|
||||
return acts + self._drop(lk)
|
||||
static = grants.static_private(self._params).public_key().public_bytes_raw()
|
||||
alg, sig = link.sign(key, link.signed_bytes("D", lk.th, spki, static))
|
||||
ids = {"dongle_id": self._params.get("DongleId"), "serial": self._params.get("HardwareSerial")}
|
||||
doc = {"v": 1, "spki": grants.b64(spki), "alg": alg, "static": grants.b64(static), "id": ids, "sig": grants.b64(sig)}
|
||||
lk.phase, lk.since, lk.last = "keys", now, now
|
||||
return acts + self._record(lk, DEVICE_KEYS, _json(doc))
|
||||
|
||||
def remove(self, phone: str | None) -> list[Action]:
|
||||
if not phone or not any(g["spki"] == phone for g in grants.load(self._params)):
|
||||
return []
|
||||
return self._remove_grant(phone)
|
||||
|
||||
def _message(self, lk: _Link, msg: bytes, now: float) -> list[Action]:
|
||||
if lk.records is not None:
|
||||
inner = lk.records.open(msg)
|
||||
if not inner:
|
||||
return self._drop(lk)
|
||||
typ, body = inner[0], inner[1:]
|
||||
if lk.phase == "keys" and typ == PHONE_KEYS:
|
||||
return self._phone_keys(lk, body, now)
|
||||
if lk.phase == "session" and typ == RPC:
|
||||
return self._rpc_request(lk, body, now)
|
||||
if lk.phase == "session" and typ == STREAM:
|
||||
return self._stream_actions(self._streams.handle(lk.device, body, now))
|
||||
return self._drop(lk)
|
||||
typ, body = msg[0], msg[1:]
|
||||
if lk.phase == "new" and typ == CONNECT_START:
|
||||
return self._start(lk, body, now)
|
||||
if lk.phase == "new" and typ == RESUME_1:
|
||||
return self._resume(lk, body, now)
|
||||
if lk.phase == "start" and typ == PAKE_A:
|
||||
return self._pake(lk, body)
|
||||
if lk.phase == "confirm" and typ == CONFIRM_A:
|
||||
return self._confirm(lk, body, now)
|
||||
return self._drop(lk)
|
||||
|
||||
def _start(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if body != bytes([PROTO]):
|
||||
return self._error(lk, ERR_VERSION)
|
||||
secret = self._window.secret()
|
||||
if secret is None:
|
||||
return self._error(lk, ERR_NO_WINDOW)
|
||||
if any(o is not lk and o.phase in CEREMONY for o in self._links.values()):
|
||||
return self._error(lk, ERR_BUSY)
|
||||
prs, nonce = secret
|
||||
attempt = secrets.token_bytes(16)
|
||||
lk.nonce, lk.sid = nonce, nonce + attempt
|
||||
lk.start_body = body
|
||||
lk.window_body = bytes([PROTO, link.PAKE_SUITE]) + nonce + attempt
|
||||
lk.cp = cpace.Cpace(False, prs, lk.sid, lk.start_body, lk.window_body)
|
||||
lk.phase, lk.since = "start", now
|
||||
return self._plain(lk, CONNECT_WINDOW, lk.window_body)
|
||||
|
||||
def _pake(self, lk: _Link, body: bytes) -> list[Action]:
|
||||
if len(body) != 32:
|
||||
return self._drop(lk)
|
||||
try:
|
||||
lk.isk = lk.cp.isk(body)
|
||||
except cpace.CpaceError:
|
||||
return self._drop(lk)
|
||||
lk.ya, lk.yb = body, lk.cp.public
|
||||
lk.phase = "confirm"
|
||||
return self._plain(lk, PAKE_B, lk.yb)
|
||||
|
||||
def _confirm(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if len(body) != 64:
|
||||
return self._drop(lk)
|
||||
if not lk.cp.check(lk.isk, lk.ya, body):
|
||||
return self._wrong_code(lk)
|
||||
tag = lk.cp.tag(lk.isk)
|
||||
lk.th = link.transcript(lk.start_body, lk.window_body, lk.ya, lk.yb, body, tag)
|
||||
p2c, c2p, lk.check = link.session_keys(lk.isk, lk.sid)
|
||||
lk.records = link.Records(c2p, p2c, lk.link_id)
|
||||
lk.reasm.cap = link.SESSION_CAP
|
||||
lk.phase, lk.since, lk.last = "decide", now, now
|
||||
self._window.hold()
|
||||
return self._plain(lk, CONFIRM_B, tag)
|
||||
|
||||
def _wrong_code(self, lk: _Link) -> list[Action]:
|
||||
if lk.nonce != self._fail_nonce:
|
||||
self._fail_nonce, self._fails = lk.nonce, 0
|
||||
self._fails += 1
|
||||
if self._fails >= MAX_WRONG:
|
||||
self._window.cancel("wrong_codes")
|
||||
return self._error(lk, ERR_WINDOW_CLOSED)
|
||||
return self._error(lk, ERR_WRONG_CODE)
|
||||
|
||||
def _phone_keys(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
doc = json.loads(body)
|
||||
if doc.get("v") != 1 or doc.get("alg") != "ES256":
|
||||
return self._drop(lk)
|
||||
spki, static, sig = grants.unb64(doc["spki"]), grants.unb64(doc["static"]), grants.unb64(doc["sig"])
|
||||
name = doc["id"]["name"]
|
||||
if len(static) != 32 or not isinstance(name, str) or len(name.encode()) > 80:
|
||||
return self._drop(lk)
|
||||
if not link.verify("ES256", spki, link.signed_bytes("P", lk.th, spki, static), sig):
|
||||
return self._drop(lk)
|
||||
lk.phone = {"spki": grants.b64(spki), "static": grants.b64(static), "name": " ".join(name.split()) or "phone"}
|
||||
lk.last = now
|
||||
saved = grants.load(self._params)
|
||||
known = any(g["spki"] == lk.phone["spki"] for g in saved)
|
||||
if not known and len(saved) >= grants.MAX_PHONES:
|
||||
self._window.cancel("limit")
|
||||
return self._record(lk, GRANT_RESULT, bytes([GRANT_REFUSED])) + self._drop(lk)
|
||||
return self._grant(lk)
|
||||
|
||||
def _grant(self, lk: _Link) -> list[Action]:
|
||||
wall = int(self._wall())
|
||||
saved = grants.load(self._params)
|
||||
old = next((g for g in saved if g["spki"] == lk.phone["spki"]), None)
|
||||
kept = [g for g in saved if g is not old]
|
||||
kept.append(lk.phone | {"added": old["added"] if old else wall, "last_seen": wall})
|
||||
grants.save(self._params, kept)
|
||||
self._window.cancel("granted")
|
||||
lk.grant, lk.phone, lk.phase = lk.phone["spki"], None, "session"
|
||||
return self._drop_grant(lk.grant, keep=lk) + self._record(lk, GRANT_RESULT, bytes([GRANT_ADDED]))
|
||||
|
||||
def _resume(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if len(body) != RESUME_1_LEN:
|
||||
return self._drop(lk)
|
||||
static = grants.static_private(self._params)
|
||||
for g in grants.load(self._params):
|
||||
hs = noise.KKHandshake(False, static, grants.unb64(g["static"]))
|
||||
try:
|
||||
payload = hs.read(body)
|
||||
except noise.NoiseError:
|
||||
continue
|
||||
if payload != bytes([PROTO]):
|
||||
return self._error(lk, ERR_VERSION)
|
||||
reply = hs.write(bytes([RESUMED]))
|
||||
send, recv = hs.split()
|
||||
lk.records = link.Records(send, recv, lk.link_id)
|
||||
lk.reasm.cap = link.SESSION_CAP
|
||||
lk.grant, lk.phase, lk.last = g["spki"], "session", now
|
||||
self._touch(g["spki"])
|
||||
return self._drop_grant(lk.grant, keep=lk) + self._plain(lk, RESUME_2, reply)
|
||||
return self._error(lk, ERR_UNKNOWN_PHONE)
|
||||
|
||||
def _touch(self, spki: str):
|
||||
saved = grants.load(self._params)
|
||||
for g in saved:
|
||||
if g["spki"] == spki:
|
||||
g["last_seen"] = int(self._wall())
|
||||
grants.save(self._params, saved)
|
||||
|
||||
def _rpc_request(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
response, after = self._rpc.handle(lk.device, body, grants.load(self._params), lk.grant, now)
|
||||
acts = self._record(lk, RPC, _json(response)) if response is not None else []
|
||||
if after == "forget":
|
||||
acts += self._remove_grant(lk.grant)
|
||||
return acts
|
||||
|
||||
def _remove_grant(self, spki: str) -> list[Action]:
|
||||
grants.save(self._params, [g for g in grants.load(self._params) if g["spki"] != spki])
|
||||
return self._drop_grant(spki)
|
||||
|
||||
def _drop_grant(self, spki: str, keep: _Link | None = None) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
for lk in list(self._links.values()):
|
||||
if lk.grant == spki and lk is not keep:
|
||||
acts += self._drop(lk)
|
||||
return acts
|
||||
|
||||
def _send(self, lk: _Link, message: bytes) -> list[Action]:
|
||||
return [("notify", frame) for frame in link.frames(message, lk.link_id, lk.mtu - link.FRAME_HEADER)]
|
||||
|
||||
def _plain(self, lk: _Link, typ: int, body: bytes) -> list[Action]:
|
||||
return self._send(lk, bytes([typ]) + body)
|
||||
|
||||
def _record(self, lk: _Link, typ: int, body: bytes) -> list[Action]:
|
||||
return self._send(lk, lk.records.seal(bytes([typ]) + body))
|
||||
|
||||
def _error(self, lk: _Link, code: int) -> list[Action]:
|
||||
return self._plain(lk, ERROR, bytes([code])) + self._drop(lk)
|
||||
|
||||
def _stream_actions(self, events: list[tuple[str, bytes]]) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
for device, payload in events:
|
||||
lk = self._links.get(device)
|
||||
if lk is not None and lk.phase == "session":
|
||||
acts += self._record(lk, STREAM, payload)
|
||||
return acts
|
||||
|
||||
def _drop(self, lk: _Link) -> list[Action]:
|
||||
self._streams.close_device(lk.device)
|
||||
if self._links.get(lk.device) is lk:
|
||||
del self._links[lk.device]
|
||||
if lk.phase in HELD:
|
||||
# the window was held for this phone; it does not reopen for another
|
||||
self._window.cancel("phone_left")
|
||||
return [("disconnect", lk.device)]
|
||||
|
||||
|
||||
def _json(obj) -> bytes:
|
||||
return json.dumps(obj, separators=(",", ":")).encode()
|
||||
@@ -1,291 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import errno
|
||||
import select
|
||||
import selectors
|
||||
import socket
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
STREAM_OPEN = 0x01
|
||||
STREAM_OPEN_OK = 0x02
|
||||
STREAM_DATA = 0x03
|
||||
STREAM_WINDOW = 0x04
|
||||
STREAM_CLOSE = 0x05
|
||||
STREAM_ERROR = 0x06
|
||||
|
||||
ERR_REFUSED = 1
|
||||
ERR_UNSUPPORTED_PORT = 2
|
||||
ERR_LIMIT = 3
|
||||
ERR_PROTOCOL = 4
|
||||
|
||||
INITIAL_WINDOW = 8_192
|
||||
WINDOW_UPDATE_THRESHOLD = 2_048
|
||||
MAX_DATA_CHUNK = 1_024
|
||||
MAX_STREAMS_PER_DEVICE = 8
|
||||
OPEN_TIMEOUT = 5.0
|
||||
ALLOWED_PORTS = (22,)
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _TcpStream:
|
||||
device: str
|
||||
stream_id: int
|
||||
sock: socket.socket
|
||||
opened_at: float
|
||||
peer_window: int
|
||||
local_window: int = INITIAL_WINDOW
|
||||
consumed_since_ack: int = 0
|
||||
connecting: bool = True
|
||||
eof_from_phone: bool = False
|
||||
tx_queue: deque[bytes] = field(default_factory=deque)
|
||||
|
||||
@property
|
||||
def fd(self) -> int:
|
||||
return self.sock.fileno()
|
||||
|
||||
@property
|
||||
def want_write(self) -> bool:
|
||||
return self.connecting or bool(self.tx_queue)
|
||||
|
||||
|
||||
class Streams:
|
||||
def __init__(self, target_host: str = "127.0.0.1"):
|
||||
self._target_host = target_host
|
||||
self._streams: dict[tuple[str, int], _TcpStream] = {}
|
||||
self._by_fd: dict[int, _TcpStream] = {}
|
||||
|
||||
def has_streams(self) -> bool:
|
||||
return bool(self._streams)
|
||||
|
||||
def selector_entries(self) -> list[tuple[int, int]]:
|
||||
entries: list[tuple[int, int]] = []
|
||||
for st in self._streams.values():
|
||||
events = selectors.EVENT_READ
|
||||
if st.want_write:
|
||||
events |= selectors.EVENT_WRITE
|
||||
entries.append((st.fd, events))
|
||||
return entries
|
||||
|
||||
def handle(self, device: str, body: bytes, now: float) -> list[tuple[str, bytes]]:
|
||||
if len(body) < 3:
|
||||
return []
|
||||
stream_id = int.from_bytes(body[0:2], "big")
|
||||
kind = body[2]
|
||||
payload = body[3:]
|
||||
if stream_id == 0:
|
||||
return []
|
||||
|
||||
key = (device, stream_id)
|
||||
if kind == STREAM_OPEN:
|
||||
return self._open(device, stream_id, payload, now)
|
||||
|
||||
st = self._streams.get(key)
|
||||
if st is None:
|
||||
return []
|
||||
|
||||
if kind == STREAM_DATA:
|
||||
if not payload or st.eof_from_phone:
|
||||
return []
|
||||
if len(payload) > st.local_window:
|
||||
self._close_stream(st)
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "window exceeded"))]
|
||||
st.local_window -= len(payload)
|
||||
st.tx_queue.append(payload)
|
||||
return self._flush_tx(st)
|
||||
|
||||
if kind == STREAM_WINDOW:
|
||||
if len(payload) != 4:
|
||||
return []
|
||||
credit = int.from_bytes(payload, "big")
|
||||
st.peer_window += credit
|
||||
return self._drain_rx(st)
|
||||
|
||||
if kind == STREAM_CLOSE:
|
||||
st.eof_from_phone = True
|
||||
if not st.tx_queue and not st.connecting:
|
||||
self._close_stream(st)
|
||||
return []
|
||||
|
||||
return []
|
||||
|
||||
def on_socket_ready(self, fd: int, readable: bool, writable: bool) -> list[tuple[str, bytes]]:
|
||||
st = self._by_fd.get(fd)
|
||||
if st is None:
|
||||
return []
|
||||
out: list[tuple[str, bytes]] = []
|
||||
if st.connecting and writable:
|
||||
err = st.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
||||
if err != 0:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
return [(device, _err(sid, ERR_REFUSED, f"connect failed ({err})"))]
|
||||
st.connecting = False
|
||||
out.append((st.device, _open_ok(st.stream_id, st.local_window)))
|
||||
if st.tx_queue:
|
||||
out += self._flush_tx(st)
|
||||
elif st.eof_from_phone:
|
||||
self._close_stream(st)
|
||||
return out
|
||||
|
||||
if (st.device, st.stream_id) not in self._streams:
|
||||
return out
|
||||
|
||||
if writable and st.tx_queue:
|
||||
out += self._flush_tx(st)
|
||||
|
||||
if (st.device, st.stream_id) not in self._streams:
|
||||
return out
|
||||
|
||||
if readable and not st.connecting:
|
||||
out += self._drain_rx(st)
|
||||
return out
|
||||
|
||||
def tick(self, now: float) -> list[tuple[str, bytes]]:
|
||||
out: list[tuple[str, bytes]] = []
|
||||
for st in list(self._streams.values()):
|
||||
if st.connecting and now - st.opened_at >= OPEN_TIMEOUT:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _err(sid, ERR_REFUSED, "connect timed out")))
|
||||
return out
|
||||
|
||||
def close_device(self, device: str):
|
||||
for st in [s for s in self._streams.values() if s.device == device]:
|
||||
self._close_stream(st)
|
||||
|
||||
def _open(self, device: str, stream_id: int, payload: bytes, now: float) -> list[tuple[str, bytes]]:
|
||||
if len(payload) != 6:
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "bad open"))]
|
||||
port = int.from_bytes(payload[0:2], "big")
|
||||
peer_window = int.from_bytes(payload[2:6], "big")
|
||||
if port not in ALLOWED_PORTS:
|
||||
return [(device, _err(stream_id, ERR_UNSUPPORTED_PORT, f"port {port} not allowed"))]
|
||||
if (device, stream_id) in self._streams:
|
||||
return [(device, _err(stream_id, ERR_PROTOCOL, "duplicate stream id"))]
|
||||
if sum(1 for d, _ in self._streams if d == device) >= MAX_STREAMS_PER_DEVICE:
|
||||
return [(device, _err(stream_id, ERR_LIMIT, "too many open streams"))]
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.setblocking(False)
|
||||
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
try:
|
||||
err = sock.connect_ex((self._target_host, port))
|
||||
except OSError as e:
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, str(e)))]
|
||||
if err not in (0, errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, f"connect failed ({err})"))]
|
||||
|
||||
if err != 0:
|
||||
_, writable, _ = select.select([], [sock], [], 0.05)
|
||||
if writable:
|
||||
so_err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
||||
if so_err != 0:
|
||||
sock.close()
|
||||
return [(device, _err(stream_id, ERR_REFUSED, f"connect failed ({so_err})"))]
|
||||
err = 0
|
||||
|
||||
st = _TcpStream(
|
||||
device=device,
|
||||
stream_id=stream_id,
|
||||
sock=sock,
|
||||
opened_at=now,
|
||||
peer_window=peer_window,
|
||||
connecting=(err != 0),
|
||||
)
|
||||
self._streams[(device, stream_id)] = st
|
||||
self._by_fd[st.fd] = st
|
||||
if not st.connecting:
|
||||
return [(device, _open_ok(stream_id, st.local_window))]
|
||||
return []
|
||||
|
||||
def _flush_tx(self, st: _TcpStream) -> list[tuple[str, bytes]]:
|
||||
if st.connecting:
|
||||
return []
|
||||
written_total = 0
|
||||
while st.tx_queue:
|
||||
chunk = st.tx_queue[0]
|
||||
try:
|
||||
sent = st.sock.send(chunk)
|
||||
except BlockingIOError:
|
||||
break
|
||||
except OSError:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
return [(device, _close(sid, 1))]
|
||||
if sent == 0:
|
||||
break
|
||||
written_total += sent
|
||||
if sent < len(chunk):
|
||||
st.tx_queue[0] = chunk[sent:]
|
||||
break
|
||||
st.tx_queue.popleft()
|
||||
|
||||
out: list[tuple[str, bytes]] = []
|
||||
if written_total > 0:
|
||||
st.consumed_since_ack += written_total
|
||||
st.local_window += written_total
|
||||
if st.consumed_since_ack >= WINDOW_UPDATE_THRESHOLD:
|
||||
ack = st.consumed_since_ack
|
||||
st.consumed_since_ack = 0
|
||||
out.append((st.device, _window(st.stream_id, ack)))
|
||||
|
||||
if st.eof_from_phone and not st.tx_queue:
|
||||
self._close_stream(st)
|
||||
return out
|
||||
|
||||
def _drain_rx(self, st: _TcpStream) -> list[tuple[str, bytes]]:
|
||||
out: list[tuple[str, bytes]] = []
|
||||
while st.peer_window > 0:
|
||||
to_read = min(MAX_DATA_CHUNK, st.peer_window)
|
||||
try:
|
||||
data = st.sock.recv(to_read)
|
||||
except BlockingIOError:
|
||||
break
|
||||
except OSError:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _close(sid, 1)))
|
||||
return out
|
||||
if not data:
|
||||
device, sid = st.device, st.stream_id
|
||||
self._close_stream(st)
|
||||
out.append((device, _close(sid, 0)))
|
||||
return out
|
||||
st.peer_window -= len(data)
|
||||
out.append((st.device, _data(st.stream_id, data)))
|
||||
return out
|
||||
|
||||
def _close_stream(self, st: _TcpStream):
|
||||
self._streams.pop((st.device, st.stream_id), None)
|
||||
self._by_fd.pop(st.fd, None)
|
||||
try:
|
||||
st.sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_ok(stream_id: int, window: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_OPEN_OK]) + window.to_bytes(4, "big")
|
||||
|
||||
|
||||
def _data(stream_id: int, payload: bytes) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_DATA]) + payload
|
||||
|
||||
|
||||
def _window(stream_id: int, credit: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_WINDOW]) + credit.to_bytes(4, "big")
|
||||
|
||||
|
||||
def _close(stream_id: int, reason: int) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_CLOSE, reason & 0xFF])
|
||||
|
||||
|
||||
def _err(stream_id: int, code: int, message: str) -> bytes:
|
||||
return stream_id.to_bytes(2, "big") + bytes([STREAM_ERROR, code & 0xFF]) + message.encode()
|
||||
@@ -1,486 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import selectors
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from jeepney import DBusAddress, HeaderFields, Message, MessageFlag, MessageType, new_error, new_method_call, new_method_return, new_signal
|
||||
from jeepney.io.threading import open_dbus_connection
|
||||
from jeepney.wrappers import Properties
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.sunnypilot.system.ble.session import Engine
|
||||
from openpilot.sunnypilot.system.connect_phone import REQUEST_KEY, STATUS_KEY, WINDOW_KEY, ConnectPhoneWindow, grant_count
|
||||
|
||||
BLUEZ = "org.bluez"
|
||||
ADAPTER_IFACE = "org.bluez.Adapter1"
|
||||
DEVICE_IFACE = "org.bluez.Device1"
|
||||
GATT_MANAGER_IFACE = "org.bluez.GattManager1"
|
||||
ADVERTISING_MANAGER_IFACE = "org.bluez.LEAdvertisingManager1"
|
||||
GATT_SERVICE_IFACE = "org.bluez.GattService1"
|
||||
GATT_CHARACTERISTIC_IFACE = "org.bluez.GattCharacteristic1"
|
||||
ADVERTISEMENT_IFACE = "org.bluez.LEAdvertisement1"
|
||||
OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES_IFACE = "org.freedesktop.DBus.Properties"
|
||||
|
||||
SERVICE_UUID = "6530b12c-c8cc-4b5c-a767-5b842c630dfa"
|
||||
RX_UUID = "a8b19254-6b8c-4074-8846-40b50f7f9583"
|
||||
TX_UUID = "936a1543-21ef-40a0-9318-201db2f992f7"
|
||||
|
||||
APP_PATH = "/sunnypilot/gatt"
|
||||
SERVICE_PATH = APP_PATH + "/service"
|
||||
RX_PATH = SERVICE_PATH + "/rx"
|
||||
TX_PATH = SERVICE_PATH + "/tx"
|
||||
ADVERTISEMENT_PATH = "/sunnypilot/advertisement"
|
||||
|
||||
# no characteristic may carry an encrypt, secure or authorize flag: those start OS pairing
|
||||
GATT_OBJECTS = {
|
||||
SERVICE_PATH: {GATT_SERVICE_IFACE: {"UUID": ("s", SERVICE_UUID), "Primary": ("b", True)}},
|
||||
RX_PATH: {GATT_CHARACTERISTIC_IFACE: {"UUID": ("s", RX_UUID), "Service": ("o", SERVICE_PATH), "Flags": ("as", ["write", "write-without-response"])}},
|
||||
TX_PATH: {GATT_CHARACTERISTIC_IFACE: {"UUID": ("s", TX_UUID), "Service": ("o", SERVICE_PATH), "Flags": ("as", ["notify"])}},
|
||||
}
|
||||
# no LocalName and no Includes: the advertisement carries neither a name nor TX power
|
||||
OBJECTS = GATT_OBJECTS | {ADVERTISEMENT_PATH: {ADVERTISEMENT_IFACE: {"Type": ("s", "peripheral"), "ServiceUUIDs": ("as", [SERVICE_UUID])}}}
|
||||
|
||||
# GAP Device Name, readable by any phone before it authenticates; the default is the hostname, which carries the serial.
|
||||
# At most 10 bytes: the kernel shortens a longer name in the default scan response.
|
||||
ALIAS = "comma"
|
||||
|
||||
RECONCILE_PERIOD = 1.0 # seconds
|
||||
CALL_TIMEOUT = 5.0 # seconds
|
||||
STOP_CALL_TIMEOUT = 0.5 # seconds, once stop() is called: the manager kills the process 5 s after SIGINT
|
||||
ENABLE_RETRY_AFTER = 10.0 # seconds enabled without a ready adapter
|
||||
RESTART_BACKOFF = 1.0 # seconds before a new manager replaces a failed one, doubling up to the maximum
|
||||
RESTART_BACKOFF_MAX = 60.0 # seconds
|
||||
|
||||
|
||||
def _prop(ifaces: dict, iface: str, name: str, default=None):
|
||||
return ifaces.get(iface, {}).get(name, (None, default))[1]
|
||||
|
||||
|
||||
class BluetoothManager:
|
||||
def __init__(self, on_write: Callable[[str, bytes, int], None], on_disconnect: Callable[[str], None] | None = None,
|
||||
on_tick: Callable[[], None] | None = None,
|
||||
stream_fds: Callable[[], list[tuple[int, int]]] | None = None,
|
||||
on_stream_ready: Callable[[int, bool, bool], None] | None = None,
|
||||
has_active_session: Callable[[], bool] | None = None):
|
||||
# all callbacks run on the run() thread
|
||||
self._on_write = on_write # device path, value, mtu
|
||||
self._on_disconnect = on_disconnect # device path
|
||||
self._on_tick = on_tick
|
||||
self._stream_fds = stream_fds
|
||||
self._on_stream_ready = on_stream_ready
|
||||
self._has_active_session = has_active_session
|
||||
self._params = Params()
|
||||
self._conn = None
|
||||
self._enabled = False
|
||||
self._exit = False
|
||||
self._adapter: str | None = None # the adapter this manager has changed; ready implies it is set
|
||||
self._ready = False
|
||||
self._connected: frozenset[str] = frozenset()
|
||||
self._stale_connected_since: float | None = None
|
||||
self._failed_step: str | None = None
|
||||
self._last_reconcile = 0.0
|
||||
self._last_tick = 0.0
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self._ready
|
||||
|
||||
@property
|
||||
def connected(self) -> frozenset[str]:
|
||||
return self._connected
|
||||
|
||||
def set_enabled(self, enabled: bool):
|
||||
# off is written by run() after its teardown: AGNOS removes the adapter as soon as the param clears
|
||||
if enabled and not self._params.get_bool("BluetoothEnabled"):
|
||||
self._params.put_bool("BluetoothEnabled", True)
|
||||
self._enabled = enabled
|
||||
|
||||
def notify(self, data: bytes) -> bool:
|
||||
# BlueZ sends a notification to every subscribed device, never to one
|
||||
return self._send(new_signal(DBusAddress(TX_PATH, interface=PROPERTIES_IFACE), "PropertiesChanged", "sa{sv}as",
|
||||
(GATT_CHARACTERISTIC_IFACE, {"Value": ("ay", data)}, [])))
|
||||
|
||||
def disconnect(self, device: str):
|
||||
cloudlog.warning(f"bluetooth: disconnecting {device}")
|
||||
self._send(new_method_call(DBusAddress(device, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
|
||||
def stop(self):
|
||||
self._exit = True
|
||||
|
||||
def run(self):
|
||||
self._conn = open_dbus_connection(bus="SYSTEM")
|
||||
try:
|
||||
while not self._exit:
|
||||
self._tick() # tick before reconcile so the first tick is not delayed by a slow bluetoothd
|
||||
if time.monotonic() - self._last_reconcile >= RECONCILE_PERIOD:
|
||||
self._last_reconcile = time.monotonic()
|
||||
self._reconcile()
|
||||
self._wait_and_dispatch()
|
||||
finally:
|
||||
try:
|
||||
self._teardown()
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: teardown failed")
|
||||
conn, self._conn = self._conn, None
|
||||
conn.close()
|
||||
self._set_connected(frozenset())
|
||||
|
||||
def _wait_and_dispatch(self):
|
||||
# Drain any already-buffered D-Bus messages without blocking.
|
||||
while not self._exit:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=0))
|
||||
except TimeoutError:
|
||||
break
|
||||
if self._exit:
|
||||
return
|
||||
|
||||
entries = self._stream_fds() if self._stream_fds is not None else []
|
||||
if not entries:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
pass
|
||||
return
|
||||
|
||||
dbus_fd = self._conn.sock.fileno()
|
||||
sel = selectors.DefaultSelector()
|
||||
try:
|
||||
sel.register(dbus_fd, selectors.EVENT_READ, data="dbus")
|
||||
for fd, events in entries:
|
||||
try:
|
||||
sel.register(fd, events, data="stream")
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
ready = sel.select(timeout=RECONCILE_PERIOD)
|
||||
for key, mask in ready:
|
||||
if key.data == "dbus":
|
||||
while not self._exit:
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=0))
|
||||
except TimeoutError:
|
||||
break
|
||||
else:
|
||||
self._callback(
|
||||
self._on_stream_ready,
|
||||
key.fd,
|
||||
bool(mask & selectors.EVENT_READ),
|
||||
bool(mask & selectors.EVENT_WRITE),
|
||||
)
|
||||
finally:
|
||||
sel.close()
|
||||
|
||||
def _send(self, msg: Message) -> bool:
|
||||
conn = self._conn
|
||||
if conn is None:
|
||||
return False
|
||||
try:
|
||||
conn.send(msg)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _callback(self, callback: Callable | None, *args):
|
||||
if callback is None:
|
||||
return
|
||||
try:
|
||||
callback(*args)
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: callback failed")
|
||||
|
||||
def _tick(self):
|
||||
if not self._exit and time.monotonic() - self._last_tick >= RECONCILE_PERIOD:
|
||||
self._last_tick = time.monotonic()
|
||||
self._callback(self._on_tick)
|
||||
|
||||
def _set_connected(self, connected: frozenset[str]):
|
||||
gone, self._connected = self._connected - connected, connected
|
||||
for device in gone:
|
||||
self._callback(self._on_disconnect, device)
|
||||
|
||||
def _call(self, msg: Message) -> tuple | None:
|
||||
# RegisterApplication is answered only after BlueZ has read our objects, so keep serving while waiting
|
||||
serial = next(self._conn.outgoing_serial)
|
||||
self._conn.send(msg, serial=serial)
|
||||
stopping = self._exit
|
||||
deadline = time.monotonic() + (STOP_CALL_TIMEOUT if stopping else CALL_TIMEOUT)
|
||||
# a stop() abandons a call that is still waiting, and the tick keeps running while bluetoothd does not answer
|
||||
while (remaining := deadline - time.monotonic()) > 0 and self._exit == stopping:
|
||||
try:
|
||||
reply = self._conn.receive(timeout=min(remaining, RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
self._tick()
|
||||
continue
|
||||
if reply.header.fields.get(HeaderFields.reply_serial) == serial:
|
||||
return reply.body if reply.header.message_type == MessageType.method_return else None
|
||||
self._dispatch(reply)
|
||||
return None
|
||||
|
||||
def _reconcile(self):
|
||||
if not self._enabled:
|
||||
self._teardown()
|
||||
self._set_connected(frozenset())
|
||||
if self._params.get_bool("BluetoothEnabled"):
|
||||
self._params.put_bool("BluetoothEnabled", False)
|
||||
return
|
||||
|
||||
reply = self._call(new_method_call(DBusAddress("/", BLUEZ, OBJECT_MANAGER_IFACE), "GetManagedObjects"))
|
||||
if reply is None:
|
||||
# no answer says nothing about the adapter: forgetting it here would make the teardown skip the power-off
|
||||
return
|
||||
objects = reply[0]
|
||||
self._set_connected(frozenset(path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Connected")))
|
||||
adapter = next((path for path, ifaces in objects.items() if GATT_MANAGER_IFACE in ifaces and ADVERTISING_MANAGER_IFACE in ifaces), None)
|
||||
|
||||
if self._connected and self._has_active_session is not None and not self._has_active_session():
|
||||
now = time.monotonic()
|
||||
if self._stale_connected_since is None:
|
||||
self._stale_connected_since = now
|
||||
elif now - self._stale_connected_since >= 15.0:
|
||||
cloudlog.warning(f"bluetooth: disconnecting stale idle devices {sorted(self._connected)}")
|
||||
for path in self._connected:
|
||||
self._call(new_method_call(DBusAddress(path, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
self._stale_connected_since = None
|
||||
self._set_connected(frozenset())
|
||||
else:
|
||||
self._stale_connected_since = None
|
||||
|
||||
if self._ready and adapter == self._adapter:
|
||||
ifaces = objects[adapter]
|
||||
# a restarted bluetoothd keeps the adapter powered but has no advertisement;
|
||||
# while a phone is connected, single-role controllers may pause advertising without losing the app.
|
||||
if (_prop(ifaces, ADAPTER_IFACE, "Powered") and not _prop(ifaces, ADAPTER_IFACE, "Pairable", True) and
|
||||
(self._connected or _prop(ifaces, ADVERTISING_MANAGER_IFACE, "ActiveInstances", 0) >= 1)):
|
||||
return
|
||||
cloudlog.warning(f"bluetooth: lost {adapter}, setting up again")
|
||||
|
||||
self._ready = False
|
||||
self._adapter = adapter
|
||||
if adapter is not None:
|
||||
self._setup(adapter, objects)
|
||||
|
||||
def _setup(self, adapter: str, objects: dict):
|
||||
self._unregister(adapter)
|
||||
for path, ifaces in objects.items():
|
||||
if _prop(ifaces, DEVICE_IFACE, "Connected"):
|
||||
cloudlog.warning(f"bluetooth: disconnecting leftover {path} before setup")
|
||||
self._call(new_method_call(DBusAddress(path, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
adapter_address = DBusAddress(adapter, BLUEZ, ADAPTER_IFACE)
|
||||
props = Properties(adapter_address)
|
||||
paired = [path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Paired")]
|
||||
steps = (
|
||||
# never advertise while bondable: phones authenticate in the app layer
|
||||
("Pairable", props.set("Pairable", "b", False)),
|
||||
("Alias", props.set("Alias", "s", ALIAS)),
|
||||
("Powered", props.set("Powered", "b", True)),
|
||||
# BlueZ refuses RemoveDevice on an unpowered adapter
|
||||
*(("RemoveDevice", new_method_call(adapter_address, "RemoveDevice", "o", (path,))) for path in paired),
|
||||
# on the adapter, not the advertisement: this kernel always writes its own Flags field and would send a second one
|
||||
("DiscoverableTimeout", props.set("DiscoverableTimeout", "u", 0)),
|
||||
("Discoverable", props.set("Discoverable", "b", True)),
|
||||
("RegisterApplication", new_method_call(DBusAddress(adapter, BLUEZ, GATT_MANAGER_IFACE), "RegisterApplication", "oa{sv}", (APP_PATH, {}))),
|
||||
("RegisterAdvertisement", new_method_call(DBusAddress(adapter, BLUEZ, ADVERTISING_MANAGER_IFACE), "RegisterAdvertisement", "oa{sv}",
|
||||
(ADVERTISEMENT_PATH, {}))),
|
||||
)
|
||||
for step, msg in steps:
|
||||
failed = not self._exit and self._call(msg) is None
|
||||
if self._exit:
|
||||
return
|
||||
if failed:
|
||||
if step != self._failed_step:
|
||||
cloudlog.warning(f"bluetooth: {step} failed on {adapter}")
|
||||
self._failed_step = step
|
||||
self._unregister(adapter)
|
||||
return
|
||||
|
||||
self._failed_step = None
|
||||
self._ready = True
|
||||
cloudlog.info(f"bluetooth: advertising on {adapter}")
|
||||
|
||||
def _unregister(self, adapter: str):
|
||||
self._ready = False
|
||||
self._call(new_method_call(DBusAddress(adapter, BLUEZ, ADVERTISING_MANAGER_IFACE), "UnregisterAdvertisement", "o", (ADVERTISEMENT_PATH,)))
|
||||
self._call(new_method_call(DBusAddress(adapter, BLUEZ, GATT_MANAGER_IFACE), "UnregisterApplication", "o", (APP_PATH,)))
|
||||
|
||||
def _teardown(self):
|
||||
adapter, self._adapter = self._adapter, None
|
||||
if adapter is None:
|
||||
return
|
||||
self._unregister(adapter)
|
||||
props = Properties(DBusAddress(adapter, BLUEZ, ADAPTER_IFACE))
|
||||
# BlueZ stores Discoverable and applies it again to every new adapter
|
||||
self._call(props.set("Discoverable", "b", False))
|
||||
self._call(props.set("Powered", "b", False))
|
||||
|
||||
def _dispatch(self, msg: Message):
|
||||
if msg.header.message_type != MessageType.method_call:
|
||||
return
|
||||
|
||||
fields = msg.header.fields
|
||||
target = (fields.get(HeaderFields.path), fields.get(HeaderFields.interface), fields.get(HeaderFields.member))
|
||||
|
||||
if target == (APP_PATH, OBJECT_MANAGER_IFACE, "GetManagedObjects"):
|
||||
reply = new_method_return(msg, "a{oa{sa{sv}}}", (GATT_OBJECTS,))
|
||||
elif target[1:] == (PROPERTIES_IFACE, "GetAll") and msg.body and msg.body[0] in OBJECTS.get(target[0], {}):
|
||||
reply = new_method_return(msg, "a{sv}", (OBJECTS[target[0]][msg.body[0]],))
|
||||
elif target == (RX_PATH, GATT_CHARACTERISTIC_IFACE, "WriteValue"):
|
||||
value, options = msg.body
|
||||
device, mtu = options["device"][1], options["mtu"][1]
|
||||
self._connected |= {device}
|
||||
# BlueZ has already acked the write and discards this reply, so the only refusal is a disconnect.
|
||||
# A long write arrives joined at offset 0, so the length is checked as well.
|
||||
if options.get("offset", ("q", 0))[1] != 0 or len(value) > mtu - 3:
|
||||
cloudlog.warning(f"bluetooth: bad WriteValue offset={options.get('offset')} len={len(value)} mtu={mtu} from {device}")
|
||||
self.disconnect(device)
|
||||
else:
|
||||
self._callback(self._on_write, device, bytes(value), mtu)
|
||||
reply = new_method_return(msg)
|
||||
elif target in ((TX_PATH, GATT_CHARACTERISTIC_IFACE, "StartNotify"), (TX_PATH, GATT_CHARACTERISTIC_IFACE, "StopNotify")):
|
||||
reply = new_method_return(msg)
|
||||
elif target == (ADVERTISEMENT_PATH, ADVERTISEMENT_IFACE, "Release"):
|
||||
self._ready = False
|
||||
reply = new_method_return(msg)
|
||||
else:
|
||||
reply = new_error(msg, "org.freedesktop.DBus.Error.UnknownMethod")
|
||||
|
||||
if not msg.header.flags & MessageFlag.no_reply_expected:
|
||||
self._conn.send(reply)
|
||||
|
||||
|
||||
class Daemon:
|
||||
def __init__(self, params, window: ConnectPhoneWindow):
|
||||
self._params = params
|
||||
self._window = window
|
||||
self._engine = Engine(params, window)
|
||||
self.bt = self.new_manager()
|
||||
self._refused: dict | None = None # shown in place of the window state until the next request
|
||||
self._written: dict | None = None
|
||||
self._status: dict | None = None
|
||||
self._retry_at: float | None = None
|
||||
|
||||
def new_manager(self) -> BluetoothManager:
|
||||
self.bt = BluetoothManager(
|
||||
self.on_write,
|
||||
self._engine.on_disconnect,
|
||||
self.tick,
|
||||
stream_fds=self._engine.stream_selector_entries,
|
||||
on_stream_ready=self.on_stream_ready,
|
||||
has_active_session=lambda: self._engine.connected() > 0,
|
||||
)
|
||||
return self.bt
|
||||
|
||||
def on_stream_ready(self, fd: int, readable: bool, writable: bool):
|
||||
self._act(self._engine.on_stream_ready(fd, readable, writable))
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int):
|
||||
self._act(self._engine.on_write(device, value, mtu, time.monotonic()))
|
||||
|
||||
def _act(self, actions: list):
|
||||
for kind, data in actions:
|
||||
if kind == "notify":
|
||||
self.bt.notify(data)
|
||||
else:
|
||||
self.bt.disconnect(data)
|
||||
|
||||
def tick(self):
|
||||
try:
|
||||
self.step(time.monotonic())
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: tick failed")
|
||||
|
||||
def step(self, now: float):
|
||||
params, bt, window = self._params, self.bt, self._window
|
||||
allowed = params.get_bool("BluetoothAllowed")
|
||||
|
||||
request = params.get(REQUEST_KEY)
|
||||
if request is not None:
|
||||
params.remove(REQUEST_KEY)
|
||||
if isinstance(request, dict):
|
||||
self._refused = None
|
||||
seq, action = request.get("seq", 0), request.get("action")
|
||||
if action == "cancel":
|
||||
window.cancel()
|
||||
elif action == "open" and not allowed:
|
||||
self._refused = {"seq": seq, "state": "closed", "reason": "bluetooth_off"}
|
||||
elif action == "open":
|
||||
try:
|
||||
window.open(now, seq)
|
||||
except Exception as e:
|
||||
cloudlog.exception("bluetooth: connect phone window not opened")
|
||||
self._refused = {"seq": seq, "state": "closed", "reason": "no_key" if isinstance(e, RuntimeError) else "error"}
|
||||
elif action in ("allow", "deny") and allowed:
|
||||
self._act(self._engine.answer(action == "allow", now))
|
||||
elif action == "remove" and allowed:
|
||||
self._act(self._engine.remove(request.get("phone")))
|
||||
|
||||
if not allowed:
|
||||
window.cancel("bluetooth_off")
|
||||
window.tick(now, bt.ready)
|
||||
self._act(self._engine.tick(now))
|
||||
|
||||
phones = grant_count()
|
||||
enabled = allowed and (window.active or phones >= 1)
|
||||
bt.set_enabled(enabled)
|
||||
if not enabled or bt.ready:
|
||||
self._retry_at = None
|
||||
elif self._retry_at is None:
|
||||
self._retry_at = now + ENABLE_RETRY_AFTER
|
||||
elif now >= self._retry_at:
|
||||
self._retry_at = float("inf")
|
||||
cloudlog.warning("bluetooth: no adapter, writing BluetoothEnabled again")
|
||||
params.put_bool("BluetoothEnabled", True)
|
||||
|
||||
state = self._refused or (window.state() | {"prompt": self._engine.prompt(now)})
|
||||
if state != self._written:
|
||||
params.put(WINDOW_KEY, state)
|
||||
self._written = state
|
||||
|
||||
status = {"enabled": enabled, "connected": self._engine.connected(), "phones": phones}
|
||||
if status != self._status:
|
||||
params.put(STATUS_KEY, status)
|
||||
self._status = status
|
||||
|
||||
|
||||
def main():
|
||||
# selfdrived blocks engagement while an always-run process is dead, and the manager never starts it again:
|
||||
# only a signal ends this loop
|
||||
exiting = threading.Event()
|
||||
daemon = Daemon(Params(), ConnectPhoneWindow())
|
||||
|
||||
def on_signal(*_):
|
||||
exiting.set()
|
||||
daemon.bt.stop()
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, on_signal)
|
||||
|
||||
backoff = RESTART_BACKOFF
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
daemon.bt.run()
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: manager failed")
|
||||
if time.monotonic() - started >= RESTART_BACKOFF_MAX:
|
||||
backoff = RESTART_BACKOFF
|
||||
retry_at = time.monotonic() + backoff
|
||||
backoff = min(backoff * 2, RESTART_BACKOFF_MAX)
|
||||
while not exiting.is_set() and time.monotonic() < retry_at:
|
||||
exiting.wait(RECONCILE_PERIOD)
|
||||
daemon.tick()
|
||||
if exiting.is_set():
|
||||
return
|
||||
daemon.new_manager()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,173 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||||
|
||||
from openpilot.common.api.base import BaseApi
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.ble.link import PAKE_SUITE
|
||||
from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID
|
||||
|
||||
WINDOW_SECONDS = 120
|
||||
|
||||
REQUEST_KEY = "SunnylinkLocalConnectPhoneRequest"
|
||||
REQUEST_ACTIONS = ("open", "cancel", "allow", "deny", "remove")
|
||||
WINDOW_KEY = "SunnylinkLocalConnectPhoneWindow"
|
||||
STATUS_KEY = "SunnylinkLocalBluetoothStatus"
|
||||
|
||||
# Matter's IsValidSetupPIN list; 00000000 and 99999999 are outside the drawn range
|
||||
REFUSED_CODES = frozenset({11111111 * digit for digit in range(1, 9)} | {12345678, 87654321})
|
||||
|
||||
def _private_key_pem() -> bytes:
|
||||
_, private, _ = BaseApi.get_key_pair()
|
||||
if private is None:
|
||||
raise RuntimeError("device key unavailable")
|
||||
return private.encode() if isinstance(private, str) else private
|
||||
|
||||
|
||||
def generate_code() -> int:
|
||||
while (code := secrets.randbelow(99_999_998) + 1) in REFUSED_CODES:
|
||||
pass
|
||||
return code
|
||||
|
||||
|
||||
def format_code(code: int) -> str:
|
||||
digits = f"{code:08d}"
|
||||
return f"{digits[:4]} {digits[4:]}"
|
||||
|
||||
|
||||
def device_identity() -> tuple[bytes, rsa.RSAPrivateKey | ec.EllipticCurvePrivateKey]:
|
||||
key = serialization.load_pem_private_key(_private_key_pem(), password=None)
|
||||
return key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo), key
|
||||
|
||||
|
||||
def device_key_hash() -> bytes:
|
||||
return hashlib.sha256(device_identity()[0]).digest()
|
||||
|
||||
|
||||
def qr_text(code: int, nonce: bytes) -> str:
|
||||
payload = code.to_bytes(4, "big") + device_key_hash() + nonce
|
||||
return f"SLC{PAKE_SUITE}:" + base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def grant_count() -> int:
|
||||
return len(grants.load(Params()))
|
||||
|
||||
|
||||
def display_name(params) -> str:
|
||||
# the sunnylink app builds the same name from DEVICE_KEYS: change both together
|
||||
dongle_id = params.get("DongleId")
|
||||
ident = dongle_id if dongle_id and dongle_id != UNREGISTERED_DONGLE_ID else params.get("HardwareSerial")
|
||||
return f"comma {ident[:4]}" if ident else "comma"
|
||||
|
||||
|
||||
def write_request(params, action: str, phone: str | None = None) -> int:
|
||||
if action not in REQUEST_ACTIONS:
|
||||
raise ValueError(action)
|
||||
seq = time.monotonic_ns()
|
||||
request = {"seq": seq, "action": action}
|
||||
if phone is not None:
|
||||
request["phone"] = phone
|
||||
params.put(REQUEST_KEY, request)
|
||||
return seq
|
||||
|
||||
|
||||
def read_window(params) -> dict | None:
|
||||
window = params.get(WINDOW_KEY)
|
||||
return window if isinstance(window, dict) else None
|
||||
|
||||
|
||||
def read_status(params) -> dict:
|
||||
status = params.get(STATUS_KEY)
|
||||
return status if isinstance(status, dict) else {}
|
||||
|
||||
|
||||
def phone_indicator(status: dict) -> str:
|
||||
# "hidden" radio off; "connected" at least one authenticated session; otherwise "waiting"
|
||||
if not status.get("enabled"):
|
||||
return "hidden"
|
||||
return "connected" if status.get("connected", 0) >= 1 else "waiting"
|
||||
|
||||
|
||||
class ConnectPhoneWindow:
|
||||
def __init__(self):
|
||||
self._open = False
|
||||
self._ready = False
|
||||
self._seq = 0
|
||||
self._reason = ""
|
||||
self._code = 0
|
||||
self._nonce = b""
|
||||
self._qr = ""
|
||||
self._deadline = 0.0
|
||||
self._shown = False
|
||||
self._held = False
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self._open
|
||||
|
||||
def open(self, now: float, seq: int = 0) -> str:
|
||||
if self._open and seq == self._seq:
|
||||
return "busy"
|
||||
# a new request never inherits the old window's code or what is left of its time
|
||||
self._close("replaced")
|
||||
self._seq = seq
|
||||
code = generate_code()
|
||||
nonce = secrets.token_bytes(8)
|
||||
self._qr = qr_text(code, nonce)
|
||||
self._code = code
|
||||
self._nonce = nonce
|
||||
self._deadline = now + WINDOW_SECONDS
|
||||
self._ready = False
|
||||
self._shown = False
|
||||
self._held = False
|
||||
self._reason = ""
|
||||
self._open = True
|
||||
return "ok"
|
||||
|
||||
def cancel(self, reason: str = "cancel"):
|
||||
self._close(reason)
|
||||
|
||||
def hold(self):
|
||||
# a phone proved the code: the Allow prompt has its own timer from here
|
||||
self._held = True
|
||||
|
||||
def tick(self, now: float, ready: bool = True):
|
||||
if now >= self._deadline and not self._held:
|
||||
self._close("timeout")
|
||||
return
|
||||
if ready and not self._shown:
|
||||
# the full time counts from when the code can first be used, not from the radio starting
|
||||
self._shown = True
|
||||
self._deadline = now + WINDOW_SECONDS
|
||||
self._ready = ready
|
||||
|
||||
def secret(self) -> tuple[bytes, bytes] | None:
|
||||
# the 8 ASCII digits (the CPace PRS) and the window nonce; None once the window is closed
|
||||
if not self._open:
|
||||
return None
|
||||
return f"{self._code:08d}".encode(), self._nonce
|
||||
|
||||
def state(self) -> dict:
|
||||
if not self._open:
|
||||
return {"seq": self._seq, "state": "closed", "reason": self._reason}
|
||||
return {"seq": self._seq, "state": "open" if self._ready else "starting", "code": f"{self._code:08d}", "qr": self._qr,
|
||||
"deadline": self._deadline, "held": self._held, "reason": ""}
|
||||
|
||||
def _close(self, reason: str):
|
||||
if self._open:
|
||||
self._open = False
|
||||
self._code = 0
|
||||
self._nonce = b""
|
||||
self._qr = ""
|
||||
self._reason = reason
|
||||
@@ -1,94 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from openpilot.sunnypilot.system.ble import cpace
|
||||
|
||||
# draft-irtf-cfrg-cpace-21 appendix B.1 (identical in -20)
|
||||
DRAFT_CI = bytes.fromhex("0b415f696e69746961746f720b425f726573706f6e646572")
|
||||
DRAFT_SID = bytes.fromhex("7e4b4791d6a8ef019b936c79fb7f2c57")
|
||||
DRAFT_G = "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f"
|
||||
DRAFT_YA_SCALAR = bytes.fromhex("21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080")
|
||||
DRAFT_YA = "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32"
|
||||
DRAFT_YB_SCALAR = bytes.fromhex("848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a")
|
||||
DRAFT_YB = "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623"
|
||||
DRAFT_K = "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b"
|
||||
DRAFT_ISK = "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"
|
||||
|
||||
SID = bytes(range(24))
|
||||
|
||||
|
||||
class TestCpace(unittest.TestCase):
|
||||
def setUp(self):
|
||||
patch = mock.patch.object(cpace, "CI", DRAFT_CI)
|
||||
patch.start()
|
||||
self.addCleanup(patch.stop)
|
||||
|
||||
def test_lv_encoding(self):
|
||||
self.assertEqual(cpace.lv(b"1234") + cpace.lv(b"5") + cpace.lv(b"") + cpace.lv(b"678"),
|
||||
bytes.fromhex("043132333401350003363738"))
|
||||
self.assertEqual(cpace.lv(bytes(128))[:2], b"\x80\x01")
|
||||
|
||||
def test_map_matches_draft_a5_reference(self):
|
||||
# draft appendix A.5 (Z = 2, A = 486662), an independent formulation of the same map
|
||||
p, a, z = cpace.P, cpace.J, 2
|
||||
for r in (2, 3, 0x123456789ABCDEF, p - 2):
|
||||
v = -a * pow(1 + z * r * r, -1, p) % p
|
||||
eps = pow((v**3 + a * v * v + v) % p, (p - 1) // 2, p)
|
||||
x = (eps * v - (1 - eps) * a * pow(2, -1, p)) % p
|
||||
self.assertEqual(cpace.map_to_curve_elligator2_curve25519(r), x)
|
||||
|
||||
def test_generator_draft_vector(self):
|
||||
self.assertEqual(cpace.generator(b"Password", DRAFT_CI, DRAFT_SID).hex(), DRAFT_G)
|
||||
|
||||
def test_shares_and_isk_draft_vector(self):
|
||||
a = cpace.Cpace(True, b"Password", DRAFT_SID, b"ADa", b"ADb", scalar=DRAFT_YA_SCALAR)
|
||||
b = cpace.Cpace(False, b"Password", DRAFT_SID, b"ADa", b"ADb", scalar=DRAFT_YB_SCALAR)
|
||||
self.assertEqual(a.public.hex(), DRAFT_YA)
|
||||
self.assertEqual(b.public.hex(), DRAFT_YB)
|
||||
self.assertEqual(cpace._scalar_mult(DRAFT_YA_SCALAR, b.public).hex(), DRAFT_K)
|
||||
self.assertEqual(cpace._scalar_mult(DRAFT_YB_SCALAR, a.public).hex(), DRAFT_K)
|
||||
isk = a.isk(b.public)
|
||||
self.assertEqual(isk.hex(), DRAFT_ISK)
|
||||
self.assertEqual(b.isk(a.public), isk)
|
||||
|
||||
def test_round_trip_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x02")
|
||||
isk = a.isk(b.public)
|
||||
self.assertEqual(b.isk(a.public), isk)
|
||||
ta, tb = a.tag(isk), b.tag(isk)
|
||||
self.assertEqual(len(ta), 64)
|
||||
self.assertTrue(b.check(isk, a.public, ta))
|
||||
self.assertTrue(a.check(isk, b.public, tb))
|
||||
|
||||
def test_wrong_code_fails_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x02")
|
||||
c = cpace.Cpace(False, b"12345679", SID, b"\x01", b"\x02")
|
||||
isk = a.isk(c.public)
|
||||
self.assertFalse(c.check(c.isk(a.public), a.public, a.tag(isk)))
|
||||
self.assertNotEqual(b.isk(a.public), c.isk(a.public))
|
||||
|
||||
def test_tampered_ad_fails_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x03")
|
||||
isk_a = a.isk(b.public)
|
||||
self.assertFalse(b.check(b.isk(a.public), a.public, a.tag(isk_a)))
|
||||
|
||||
def test_low_order_point_aborts(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
for bad in (bytes(32), b"\x01" + bytes(31), bytes.fromhex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")):
|
||||
with self.assertRaises(cpace.CpaceError):
|
||||
a.isk(bad)
|
||||
with self.assertRaises(cpace.CpaceError):
|
||||
a.isk(bytes(31))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,163 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
from openpilot.sunnypilot.system.ble import link
|
||||
|
||||
LINK = 0x1234
|
||||
|
||||
|
||||
class TestFraming(unittest.TestCase):
|
||||
def test_mtu_23_fragments(self):
|
||||
msg = bytes(range(40))
|
||||
frames = link.frames(msg, LINK, 20)
|
||||
self.assertEqual([len(f) for f in frames], [20, 20, 9])
|
||||
self.assertEqual([f[0] for f in frames], [1, 1, 0])
|
||||
self.assertEqual({f[1:3] for f in frames}, {LINK.to_bytes(2, "big")})
|
||||
r = link.Reassembler(LINK)
|
||||
out = [r.feed(f) for f in frames]
|
||||
self.assertEqual(out, [None, None, msg])
|
||||
|
||||
def test_single_frame_and_empty_rejected(self):
|
||||
self.assertEqual(len(link.frames(b"\x01", LINK, 20)), 1)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"", LINK, 20)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"\x01", 0, 20)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"\x01", LINK, 19)
|
||||
|
||||
def test_frames_never_exceed_att_value_cap(self):
|
||||
frames = link.frames(bytes(900), LINK, 517 - 3)
|
||||
self.assertEqual([len(f) for f in frames], [512, 3 + 900 - 509])
|
||||
|
||||
def test_cap_before_and_after_session(self):
|
||||
r = link.Reassembler(LINK)
|
||||
with self.assertRaises(link.LinkError):
|
||||
for f in link.frames(bytes(1025), LINK, 244):
|
||||
r.feed(f)
|
||||
out = None
|
||||
for f in link.frames(bytes(1024), LINK, 244):
|
||||
out = r.feed(f)
|
||||
self.assertEqual(len(out), 1024)
|
||||
r.cap = link.SESSION_CAP
|
||||
for f in link.frames(bytes(16384), LINK, 244):
|
||||
out = r.feed(f)
|
||||
self.assertEqual(len(out), 16384)
|
||||
|
||||
def test_malformed_frames_rejected(self):
|
||||
r = link.Reassembler(LINK)
|
||||
bad = [
|
||||
b"\x02" + LINK.to_bytes(2, "big") + b"x", # bit 1 set
|
||||
b"\x80" + LINK.to_bytes(2, "big") + b"x", # bit 7 set
|
||||
b"\x00" + (LINK + 1).to_bytes(2, "big") + b"x", # other link id
|
||||
b"\x00" + LINK.to_bytes(2, "big"), # no fragment
|
||||
b"\x01\x00", # short
|
||||
]
|
||||
for frame in bad:
|
||||
with self.assertRaises(link.LinkError):
|
||||
r.feed(frame)
|
||||
|
||||
def test_reassembly_resets_after_error(self):
|
||||
r = link.Reassembler(LINK)
|
||||
r.feed(b"\x01" + LINK.to_bytes(2, "big") + b"ab")
|
||||
with self.assertRaises(link.LinkError):
|
||||
r.feed(b"\x02" + LINK.to_bytes(2, "big") + b"c")
|
||||
self.assertEqual(r.feed(b"\x00" + LINK.to_bytes(2, "big") + b"z"), b"z")
|
||||
|
||||
|
||||
class TestRecords(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.k_a, self.k_b = bytes([1]) * 32, bytes([2]) * 32
|
||||
|
||||
def pair(self, interval=link.REKEY_INTERVAL):
|
||||
return (link.Records(self.k_a, self.k_b, LINK, rekey_interval=interval),
|
||||
link.Records(self.k_b, self.k_a, LINK, rekey_interval=interval))
|
||||
|
||||
def test_round_trip_both_directions(self):
|
||||
a, b = self.pair()
|
||||
self.assertEqual(b.open(a.seal(b"\x30hi")), b"\x30hi")
|
||||
self.assertEqual(a.open(b.seal(b"\x40{}")), b"\x40{}")
|
||||
self.assertEqual(a.seal(b"\x30")[0], link.RECORD_TYPE)
|
||||
|
||||
def test_replay_and_reorder_rejected(self):
|
||||
a, b = self.pair()
|
||||
r0, r1 = a.seal(b"\x30zero"), a.seal(b"\x30one")
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(r1)
|
||||
self.assertEqual(b.open(r0), b"\x30zero")
|
||||
self.assertEqual(b.open(r1), b"\x30one")
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(r1)
|
||||
|
||||
def test_tamper_and_wrong_link_id_rejected(self):
|
||||
a, b = self.pair()
|
||||
rec = bytearray(a.seal(b"\x30x"))
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.Records(self.k_b, self.k_a, LINK + 1).open(bytes(rec))
|
||||
rec[-1] ^= 1
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(bytes(rec))
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(b"\x21" + bytes(20))
|
||||
|
||||
def test_rekey_at_boundary(self):
|
||||
a, b = self.pair(interval=4)
|
||||
recs = [a.seal(bytes([0x30, i])) for i in range(10)]
|
||||
self.assertEqual([b.open(r) for r in recs], [bytes([0x30, i]) for i in range(10)])
|
||||
old = ChaCha20Poly1305(self.k_a)
|
||||
nonce = bytes(4) + (4).to_bytes(8, "little")
|
||||
with self.assertRaises(InvalidTag):
|
||||
old.decrypt(nonce, recs[4][1:], bytes([link.RECORD_TYPE]) + LINK.to_bytes(2, "big"))
|
||||
self.assertNotEqual(link._rekey(self.k_a), self.k_a)
|
||||
|
||||
|
||||
class TestKeysAndSignatures(unittest.TestCase):
|
||||
def test_transcript_and_signed_bytes_layout(self):
|
||||
with self.assertRaises(ValueError):
|
||||
link.transcript(b"\x01", b"")
|
||||
th = link.transcript(b"\x01", bytes(26), bytes(32), bytes(32), bytes(64), bytes(64))
|
||||
self.assertEqual(len(th), 32)
|
||||
signed = link.signed_bytes("D", th, b"spki", bytes(32))
|
||||
self.assertEqual(signed[:22], b"sunnylink-ble-keys-v1\x00")
|
||||
self.assertEqual(signed[22:23], b"D")
|
||||
self.assertEqual(len(signed), 22 + 1 + 32 + 32 + 32)
|
||||
with self.assertRaises(ValueError):
|
||||
link.signed_bytes("X", th, b"spki", bytes(32))
|
||||
|
||||
def test_session_keys(self):
|
||||
k1, k2, code = link.session_keys(bytes(64), bytes(24))
|
||||
self.assertEqual((len(k1), len(k2), len(code)), (32, 32, 6))
|
||||
self.assertNotEqual(k1, k2)
|
||||
self.assertEqual(link.session_keys(bytes(64), bytes(24)), (k1, k2, code))
|
||||
self.assertNotEqual(link.session_keys(bytes(64), bytes([1]) * 24)[0], k1)
|
||||
|
||||
def test_sign_verify_rs256_and_es256(self):
|
||||
data = b"signed bytes"
|
||||
for key in (rsa.generate_private_key(public_exponent=65537, key_size=2048), ec.generate_private_key(ec.SECP256R1())):
|
||||
alg, sig = link.sign(key, data)
|
||||
spki = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
self.assertEqual(alg, "RS256" if isinstance(key, rsa.RSAPrivateKey) else "ES256")
|
||||
self.assertTrue(link.verify(alg, spki, data, sig))
|
||||
self.assertFalse(link.verify(alg, spki, data + b"!", sig))
|
||||
self.assertFalse(link.verify(alg, spki, data, sig[:-1]))
|
||||
other = "ES256" if alg == "RS256" else "RS256"
|
||||
self.assertFalse(link.verify(other, spki, data, sig))
|
||||
self.assertFalse(link.verify(alg, b"junk", data, sig))
|
||||
|
||||
def test_unsupported_key_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
link.sign(ec.generate_private_key(ec.SECP384R1()), b"x")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,111 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
from openpilot.sunnypilot.system.ble import noise
|
||||
|
||||
# Cacophony (noiseprotocol test vectors, centromere/cacophony vectors/cacophony.txt), the KK 25519 ChaChaPoly SHA256 entry
|
||||
VECTOR = {
|
||||
"init_prologue": "4a6f686e2047616c74",
|
||||
"init_static": "e61ef9919cde45dd5f82166404bd08e38bceb5dfdfded0a34c8df7ed542214d1",
|
||||
"init_ephemeral": "893e28b9dc6ca8d611ab664754b8ceb7bac5117349a4439a6b0569da977c464a",
|
||||
"init_remote_static": "31e0303fd6418d2f8c0e78b91f22e8caed0fbe48656dcf4767e4834f701b8f62",
|
||||
"resp_prologue": "4a6f686e2047616c74",
|
||||
"resp_static": "4a3acbfdb163dec651dfa3194dece676d437029c62a408b4c5ea9114246e4893",
|
||||
"resp_ephemeral": "bbdb4cdbd309f1a1f2e1456967fe288cadd6f712d65dc7b7793d5e63da6b375b",
|
||||
"resp_remote_static": "6bc3822a2aa7f4e6981d6538692b3cdf3e6df9eea6ed269eb41d93c22757b75a",
|
||||
"handshake_hash": "24c6b51ecb76277140ca018b5985bc9f03de321dae2d34dcae433dafef0131d9",
|
||||
"messages": [
|
||||
("4c756477696720766f6e204d69736573",
|
||||
"ca35def5ae56cec33dc2036731ab14896bc4c75dbb07a61f879f8e3afa4c79440177015efc1fe7a37c629af7120a9627" +
|
||||
"4e6ab7afcc9261901d0e09ae32a5bb96"),
|
||||
("4d757272617920526f746862617264",
|
||||
"95ebc60d2b1fa672c1f46a8aa265ef51bfe38e7ccb39ec5be34069f144808843b274d3429adc47ca093ba63ef90f8da8" +
|
||||
"9fda108db471dccfa4894aa7b00003"),
|
||||
("462e20412e20486179656b", "966b05bc69ec01b8454d3160a214e6f24a3d884eb31ec2408af63f"),
|
||||
("4361726c204d656e676572", "0ad887fba4f611bbb4afe44ba3556b8164332ca7d5934634d63d80"),
|
||||
("4a65616e2d426170746973746520536179", "012b28ae646ae7830e2c5472cb023eab071c1db3d8413ec69b513b83832f974c2d"),
|
||||
("457567656e2042f6686d20766f6e2042617765726b", "bb3e6a48160d9c5971d37f975727294e0d868342db31832e54d07191ab0ca3c3703b5ed3d9"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _priv(hex_key: str) -> X25519PrivateKey:
|
||||
return X25519PrivateKey.from_private_bytes(bytes.fromhex(hex_key))
|
||||
|
||||
|
||||
def _pub(priv: X25519PrivateKey) -> bytes:
|
||||
return priv.public_key().public_bytes_raw()
|
||||
|
||||
|
||||
class TestNoiseKK(unittest.TestCase):
|
||||
def test_cacophony_vector(self):
|
||||
v = VECTOR
|
||||
ini = noise.KKHandshake(True, _priv(v["init_static"]), bytes.fromhex(v["init_remote_static"]),
|
||||
e=_priv(v["init_ephemeral"]), prologue=bytes.fromhex(v["init_prologue"]))
|
||||
res = noise.KKHandshake(False, _priv(v["resp_static"]), bytes.fromhex(v["resp_remote_static"]),
|
||||
e=_priv(v["resp_ephemeral"]), prologue=bytes.fromhex(v["resp_prologue"]))
|
||||
payload0, ct0 = v["messages"][0]
|
||||
payload1, ct1 = v["messages"][1]
|
||||
self.assertEqual(ini.write(bytes.fromhex(payload0)).hex(), ct0)
|
||||
self.assertEqual(res.read(bytes.fromhex(ct0)).hex(), payload0)
|
||||
self.assertEqual(res.write(bytes.fromhex(payload1)).hex(), ct1)
|
||||
self.assertEqual(ini.read(bytes.fromhex(ct1)).hex(), payload1)
|
||||
self.assertEqual(ini._h.hex(), v["handshake_hash"])
|
||||
|
||||
to_resp, to_ini = ini.split()
|
||||
self.assertEqual(res.split(), (to_ini, to_resp))
|
||||
for i, (payload, ct) in enumerate(v["messages"][2:], start=2):
|
||||
key = to_resp if i % 2 == 0 else to_ini
|
||||
counter = i // 2 - 1
|
||||
self.assertEqual(ChaCha20Poly1305(key).encrypt(bytes(4) + counter.to_bytes(8, "little"), bytes.fromhex(payload), b"").hex(), ct)
|
||||
|
||||
def test_round_trip_and_split_pairing(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
ini = noise.KKHandshake(True, si, _pub(sr))
|
||||
res = noise.KKHandshake(False, sr, _pub(si))
|
||||
self.assertEqual(res.read(ini.write(b"hello")), b"hello")
|
||||
self.assertEqual(ini.read(res.write(b"comma")), b"comma")
|
||||
i_send, i_recv = ini.split()
|
||||
r_send, r_recv = res.split()
|
||||
self.assertEqual((i_send, i_recv), (r_recv, r_send))
|
||||
self.assertNotEqual(i_send, i_recv)
|
||||
|
||||
def test_wrong_static_key_rejected(self):
|
||||
si, sr, other = (X25519PrivateKey.generate() for _ in range(3))
|
||||
ini = noise.KKHandshake(True, si, _pub(sr))
|
||||
msg = ini.write(b"")
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, other, _pub(si)).read(msg)
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, sr, _pub(other)).read(msg)
|
||||
|
||||
def test_tampered_message_rejected(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
msg = bytearray(noise.KKHandshake(True, si, _pub(sr)).write(b"\x01"))
|
||||
msg[-1] ^= 1
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, sr, _pub(si)).read(bytes(msg))
|
||||
|
||||
def test_low_order_remote_static_rejected(self):
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(True, X25519PrivateKey.generate(), bytes(32)).write()
|
||||
|
||||
def test_out_of_order_rejected(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
res = noise.KKHandshake(False, sr, _pub(si))
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
res.write()
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
res.split()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,702 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import json
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
|
||||
from openpilot.common.params import ParamKeyType
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
from openpilot.sunnypilot.system.ble import cpace, grants, link, noise, session as s
|
||||
|
||||
DEVICE = "/org/bluez/hci0/dev_A"
|
||||
WALL = 1_700_000_000
|
||||
|
||||
|
||||
class MemParams:
|
||||
def __init__(self, values: dict | None = None, known: set[str] | None = None):
|
||||
self.data = dict(values or {})
|
||||
self.known = known if known is not None else set(self.data)
|
||||
self.types: dict[str, ParamKeyType] = {}
|
||||
self.defaults: dict = {}
|
||||
|
||||
def get(self, key, block=False, return_default=False):
|
||||
return self.data.get(key, self.defaults.get(key) if return_default else None)
|
||||
|
||||
def get_type(self, key):
|
||||
return self.types.get(key, ParamKeyType.BYTES)
|
||||
|
||||
def get_bool(self, key):
|
||||
return bool(self.data.get(key))
|
||||
|
||||
def put(self, key, value, block=False):
|
||||
self.data[key] = value
|
||||
|
||||
def put_bool(self, key, value, block=False):
|
||||
self.data[key] = value
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
def all_keys(self):
|
||||
return [k.encode() for k in self.known]
|
||||
|
||||
|
||||
def spki_of(key) -> bytes:
|
||||
return key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
|
||||
|
||||
class Phone:
|
||||
"""An initiator built from the protocol core: CPace party A, Noise KK initiator, one link id."""
|
||||
|
||||
def __init__(self, h: "Harness", device: str, lid: int, name: str = "test phone"):
|
||||
self.h, self.device, self.lid, self.name = h, device, lid, name
|
||||
self.mtu = 23
|
||||
self.connected = True
|
||||
self.inbox: list[bytes] = []
|
||||
self.reasm = link.Reassembler(lid)
|
||||
self.broken = False
|
||||
self.static = X25519PrivateKey.generate()
|
||||
self.key = ec.generate_private_key(ec.SECP256R1())
|
||||
self.records: link.Records | None = None
|
||||
self.th = b""
|
||||
self.cp = None
|
||||
self.ya = self.yb = self.isk = b""
|
||||
self.sid = b""
|
||||
|
||||
def receive(self, frame: bytes):
|
||||
if int.from_bytes(frame[1:3], "big") != self.lid:
|
||||
return
|
||||
try:
|
||||
msg = self.reasm.feed(frame)
|
||||
except link.LinkError:
|
||||
self.broken = True
|
||||
return
|
||||
if msg is not None:
|
||||
self.inbox.append(msg)
|
||||
|
||||
def pop(self, typ: int) -> bytes:
|
||||
msg = self.inbox.pop(0)
|
||||
assert msg[0] == typ, (msg[0], typ)
|
||||
return msg[1:]
|
||||
|
||||
def pop_record(self, typ: int) -> bytes:
|
||||
inner = self.records.open(self.inbox.pop(0))
|
||||
assert inner[0] == typ, (inner[0], typ)
|
||||
return inner[1:]
|
||||
|
||||
def pop_error(self) -> int:
|
||||
return self.pop(s.ERROR)[0]
|
||||
|
||||
def start(self, now: float):
|
||||
return self.h.send(self, bytes([s.CONNECT_START, s.PROTO]), now)
|
||||
|
||||
def pake(self, prs: bytes, now: float):
|
||||
self.wbody = self.pop(s.CONNECT_WINDOW)
|
||||
self.sid = self.wbody[2:26]
|
||||
self.cp = cpace.Cpace(True, prs, self.sid, bytes([s.PROTO]), self.wbody)
|
||||
self.ya = self.cp.public
|
||||
self.h.send(self, bytes([s.PAKE_A]) + self.ya, now)
|
||||
if self.broken or not self.inbox:
|
||||
return
|
||||
self.yb = self.pop(s.PAKE_B)
|
||||
self.isk = self.cp.isk(self.yb)
|
||||
self.ta = self.cp.tag(self.isk)
|
||||
self.h.send(self, bytes([s.CONFIRM_A]) + self.ta, now)
|
||||
|
||||
def confirm(self):
|
||||
tb = self.pop(s.CONFIRM_B)
|
||||
assert self.cp.check(self.isk, self.yb, tb)
|
||||
self.th = link.transcript(bytes([s.PROTO]), self.wbody, self.ya, self.yb, self.ta, tb)
|
||||
p2c, c2p, self.check = link.session_keys(self.isk, self.sid)
|
||||
self.records = link.Records(p2c, c2p, self.lid)
|
||||
self.reasm.cap = link.SESSION_CAP
|
||||
|
||||
def ceremony(self, prs: bytes, now: float):
|
||||
self.start(now)
|
||||
self.pake(prs, now)
|
||||
if self.inbox and self.inbox[0][0] == s.CONFIRM_B:
|
||||
self.confirm()
|
||||
|
||||
def phone_keys(self, now: float):
|
||||
dev = self.pop_record(s.DEVICE_KEYS)
|
||||
doc = json.loads(dev)
|
||||
spki, static, sig = (grants.unb64(doc[k]) for k in ("spki", "static", "sig"))
|
||||
assert spki == self.h.identity_spki
|
||||
assert link.verify(doc["alg"], spki, link.signed_bytes("D", self.th, spki, static), sig)
|
||||
own_spki = spki_of(self.key)
|
||||
own_static = self.static.public_key().public_bytes_raw()
|
||||
alg, own_sig = link.sign(self.key, link.signed_bytes("P", self.th, own_spki, own_static))
|
||||
doc = {"v": 1, "spki": grants.b64(own_spki), "alg": alg, "static": grants.b64(own_static),
|
||||
"id": {"name": self.name}, "sig": grants.b64(own_sig)}
|
||||
self.h.send_record(self, s.PHONE_KEYS, json.dumps(doc).encode(), now)
|
||||
|
||||
def resume_start(self, comma_static: bytes, now: float):
|
||||
hs = noise.KKHandshake(True, self.static, comma_static)
|
||||
self.h.send(self, bytes([s.RESUME_1]) + hs.write(bytes([s.PROTO])), now)
|
||||
if self.broken or not self.inbox or self.inbox[0][0] == s.ERROR:
|
||||
return
|
||||
body = self.pop(s.RESUME_2)
|
||||
assert hs.read(body) == bytes([1])
|
||||
send, recv = hs.split()
|
||||
self.records = link.Records(send, recv, self.lid)
|
||||
self.reasm.cap = link.SESSION_CAP
|
||||
|
||||
def rpc(self, method: str, now: float, params=None, rid: int = 1) -> dict:
|
||||
body = json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}).encode()
|
||||
self.h.send_record(self, s.RPC, body, now)
|
||||
return json.loads(self.pop_record(s.RPC))
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, mocker: Mocker, values=None, known=None):
|
||||
self.identity = ec.generate_private_key(ec.SECP256R1())
|
||||
self.identity_spki = spki_of(self.identity)
|
||||
pem = self.identity.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
serialization.NoEncryption()).decode()
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=("ES256", pem, "unused"))
|
||||
self.clock = {"wall": WALL}
|
||||
self.params = MemParams({"DongleId": "dongle", "HardwareSerial": "serial"} | (values or {}), known=known)
|
||||
self.window = cp.ConnectPhoneWindow()
|
||||
self.engine = s.Engine(self.params, self.window, wifi=lambda: self.wifi, wall=lambda: self.clock["wall"])
|
||||
self.wifi = FakeWifi()
|
||||
self.phones: dict[str, Phone] = {}
|
||||
|
||||
def new_phone(self, lid: int = 0x1234, device: str = DEVICE, name: str = "test phone") -> Phone:
|
||||
phone = self.phones[device] = Phone(self, device, lid, name)
|
||||
return phone
|
||||
|
||||
def open_window(self, now: float = 0.0):
|
||||
assert self.window.open(now, 1) == "ok"
|
||||
|
||||
def send(self, phone: Phone, message: bytes, now: float):
|
||||
for frame in link.frames(message, phone.lid, phone.mtu - 3):
|
||||
if not phone.connected:
|
||||
return
|
||||
self.route(self.engine.on_write(phone.device, frame, phone.mtu, now))
|
||||
|
||||
def send_record(self, phone: Phone, typ: int, body: bytes, now: float):
|
||||
self.send(phone, phone.records.seal(bytes([typ]) + body), now)
|
||||
|
||||
def route(self, actions):
|
||||
for kind, data in actions:
|
||||
if kind == "notify":
|
||||
for phone in self.phones.values():
|
||||
if phone.connected:
|
||||
phone.receive(data)
|
||||
else:
|
||||
self.engine.on_disconnect(data)
|
||||
self.phones[data].connected = False
|
||||
|
||||
def tick(self, now: float):
|
||||
self.route(self.engine.tick(now))
|
||||
|
||||
def allow(self, now: float, allow: bool = True):
|
||||
self.route(self.engine.answer(allow, now))
|
||||
|
||||
def grant_list(self) -> list[dict]:
|
||||
return grants.load(self.params)
|
||||
|
||||
|
||||
class FakeWifi:
|
||||
def __init__(self):
|
||||
self.active = False # what the radio reports
|
||||
self.requested: bool | None = None # last set_tethering_active call
|
||||
self.connected_ssid = "home"
|
||||
self.tethering_ssid = "weedle-test"
|
||||
self.tethering_password = "pw-test"
|
||||
|
||||
def is_tethering_active(self):
|
||||
return self.active
|
||||
|
||||
def set_tethering_active(self, active: bool):
|
||||
self.requested = active
|
||||
|
||||
|
||||
def full_ceremony(h: Harness, phone: Phone, now: float = 0.0) -> int:
|
||||
prs, _ = h.window.secret()
|
||||
phone.ceremony(prs, now)
|
||||
h.allow(now)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.phone_keys(now)
|
||||
return phone.pop_record(s.GRANT_RESULT)[0]
|
||||
|
||||
|
||||
class TestCeremony(OpenpilotTestCase):
|
||||
def test_full_ceremony(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
prs = h.window.secret()[0]
|
||||
phone.ceremony(prs, 0.0)
|
||||
assert h.window.active and h.engine.prompt(0.0) == {"step": "allow", "check": phone.check[:3] + " " + phone.check[3:],
|
||||
"until": 30.0}
|
||||
h.allow(0.0)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.ALLOW])
|
||||
phone.phone_keys(0.0)
|
||||
assert phone.pop_record(s.GRANT_RESULT) == bytes([s.GRANT_ADDED])
|
||||
|
||||
grant = h.grant_list()
|
||||
assert [(g["name"], g["added"], g["last_seen"]) for g in grant] == [("test phone", WALL, WALL)]
|
||||
assert not h.window.active and h.engine.connected() == 1
|
||||
assert len(phone.inbox) == 0
|
||||
|
||||
def test_window_is_held_once_the_phone_proves_the_code(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
h.window.tick(0.0)
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 110.0)
|
||||
h.window.tick(130.0)
|
||||
assert h.window.active
|
||||
h.allow(135.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.phone_keys(136.0)
|
||||
assert phone.pop_record(s.GRANT_RESULT) == bytes([s.GRANT_ADDED])
|
||||
assert h.window.state()["reason"] == "granted"
|
||||
|
||||
def test_phone_keys_not_sent_in_time(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(0.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
h.tick(30.0)
|
||||
assert h.grant_list() == [] and not phone.connected
|
||||
assert h.window.state()["reason"] == "timeout"
|
||||
|
||||
def test_phone_leaving_closes_the_held_window(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.route([("disconnect", phone.device)])
|
||||
assert not h.window.active and h.window.state()["reason"] == "phone_left"
|
||||
|
||||
def test_deny_closes_window_without_a_grant(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(1.0, allow=False)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.DENY])
|
||||
assert not phone.connected and not h.window.active
|
||||
assert h.window.state()["reason"] == "denied" and h.grant_list() == []
|
||||
|
||||
def test_no_answer_after_thirty_seconds(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.tick(29.9)
|
||||
assert phone.connected and h.engine.prompt(29.9) is not None
|
||||
h.tick(30.0)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.NO_ANSWER])
|
||||
assert not phone.connected and h.window.state()["reason"] == "no_answer"
|
||||
|
||||
def test_check_code_wait_is_not_cut_by_the_idle_rule(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.tick(20.0)
|
||||
assert phone.connected and not phone.broken
|
||||
|
||||
def test_no_idle_drop_after_allow(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(5.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
h.tick(25.0)
|
||||
assert phone.connected and h.engine.prompt(25.0) is None
|
||||
|
||||
def test_wrong_code_five_times_closes_the_window(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
for attempt in range(5):
|
||||
phone = h.new_phone(lid=0x100 + attempt, device=f"/dev/{attempt}")
|
||||
phone.ceremony(b"00000001" if attempt % 2 else b"00000002", 0.0)
|
||||
assert phone.pop_error() == (s.ERR_WINDOW_CLOSED if attempt == 4 else s.ERR_WRONG_CODE)
|
||||
assert not phone.connected
|
||||
assert h.window.active == (attempt < 4)
|
||||
assert h.window.state()["reason"] == "wrong_codes"
|
||||
|
||||
def test_wrong_code_counts_only_the_window_it_was_made_for(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window(0.0)
|
||||
for attempt in range(4):
|
||||
phone = h.new_phone(lid=0x200 + attempt, device=f"/w/{attempt}")
|
||||
phone.ceremony(b"00000001", 0.0)
|
||||
assert phone.pop_error() == s.ERR_WRONG_CODE
|
||||
h.window.cancel()
|
||||
h.open_window(1.0)
|
||||
phone = h.new_phone(lid=0x300, device="/w/new")
|
||||
phone.ceremony(h.window.secret()[0], 1.0)
|
||||
assert phone.connected and not phone.broken
|
||||
|
||||
def test_connect_start_with_no_window_gets_error_one(self, mocker):
|
||||
h = Harness(mocker)
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
assert phone.pop_error() == s.ERR_NO_WINDOW and not phone.connected
|
||||
|
||||
def test_wrong_protocol_version_gets_error_three(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
h.send(phone, bytes([s.CONNECT_START, 2]), 0.0)
|
||||
assert phone.pop_error() == s.ERR_VERSION
|
||||
|
||||
def test_second_ceremony_while_one_is_running_gets_busy(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
first = h.new_phone(lid=0x10, device="/a")
|
||||
second = h.new_phone(lid=0x20, device="/b")
|
||||
first.start(0.0)
|
||||
second.start(0.0)
|
||||
assert second.pop_error() == s.ERR_BUSY and not second.connected
|
||||
assert first.connected
|
||||
|
||||
def test_unauthenticated_idle_timeout(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
h.tick(9.9)
|
||||
assert phone.connected
|
||||
h.tick(10.0)
|
||||
assert phone.pop_error() == s.ERR_TIMEOUT and not phone.connected
|
||||
|
||||
def test_unauthenticated_total_timeout_is_sixty_seconds(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
h.engine.on_write(phone.device, link.frames(bytes([s.PAKE_A]) + b"\x00" * 32, phone.lid, 20)[0], 23, 55.0)
|
||||
h.tick(59.9)
|
||||
assert phone.connected
|
||||
h.tick(60.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_window_closing_drops_a_ceremony_in_progress(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.window.cancel("cancel")
|
||||
h.tick(1.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_new_window_drops_the_old_ceremony(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.window.open(1.0, 2)
|
||||
h.tick(1.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_bad_device_signature_drops_without_a_grant(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(0.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.pop_record(s.DEVICE_KEYS)
|
||||
bad = {"v": 1, "spki": grants.b64(spki_of(phone.key)), "alg": "ES256", "static": grants.b64(b"\x01" * 32),
|
||||
"id": {"name": "x"}, "sig": grants.b64(b"\x00" * 70)}
|
||||
h.send_record(phone, s.PHONE_KEYS, json.dumps(bad).encode(), 0.0)
|
||||
assert not phone.connected and h.grant_list() == []
|
||||
|
||||
def test_limit_of_eight_phones(self, mocker):
|
||||
values = {"SunnylinkLocalBleGrants": [{"spki": f"x{i}", "static": grants.b64(b"\x02" * 32), "name": "p", "added": 1,
|
||||
"last_seen": 1} for i in range(grants.MAX_PHONES)]}
|
||||
h = Harness(mocker, values)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_REFUSED
|
||||
assert len(h.grant_list()) == grants.MAX_PHONES and not h.window.active
|
||||
assert not phone.connected
|
||||
|
||||
def test_duplicate_link_id_is_dropped(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
first = h.new_phone(lid=0x77, device="/first")
|
||||
second = h.new_phone(lid=0x77, device="/second")
|
||||
first.start(0.0)
|
||||
second.start(0.0)
|
||||
assert not second.connected and first.connected
|
||||
assert first.pop(s.CONNECT_WINDOW)[0] == s.PROTO
|
||||
|
||||
def test_bad_frame_flags_drop_the_link(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
frame = bytes([0x02]) + phone.lid.to_bytes(2, "big") + bytes([s.PROTO])
|
||||
h.engine.on_write(phone.device, frame, 23, 0.0)
|
||||
assert h.engine.on_write(phone.device, frame, 23, 0.0) == [("disconnect", phone.device)]
|
||||
|
||||
def test_oversized_clear_message_before_session_is_dropped(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
phone.mtu = 247
|
||||
h.send(phone, bytes([s.PAKE_A]) + b"\x00" * 1100, 0.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_grants_key_is_created_once(self, mocker):
|
||||
h = Harness(mocker)
|
||||
first = grants.static_private(h.params).public_key().public_bytes_raw()
|
||||
assert len(h.params.data[grants.KEY_KEY]) == 32
|
||||
assert grants.static_private(h.params).public_key().public_bytes_raw() == first
|
||||
|
||||
|
||||
class TestReconnect(OpenpilotTestCase):
|
||||
def granted(self, mocker) -> tuple[Harness, Phone]:
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_ADDED
|
||||
h.engine.on_disconnect(phone.device)
|
||||
phone.connected = False
|
||||
return h, phone
|
||||
|
||||
def comma_static(self, h: Harness) -> bytes:
|
||||
return grants.static_private(h.params).public_key().public_bytes_raw()
|
||||
|
||||
def test_resume_with_a_known_phone(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
h.clock["wall"] = WALL + 500
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.connected and again.records is not None
|
||||
assert h.grant_list()[0]["last_seen"] == WALL + 500
|
||||
assert len(again.rpc("phones.list", 10.0)["result"]) == 1
|
||||
|
||||
def test_removed_phone_gets_error_eight(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
h.route(h.engine.remove(h.grant_list()[0]["spki"]))
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.pop_error() == s.ERR_UNKNOWN_PHONE and not again.connected
|
||||
assert h.grant_list() == []
|
||||
|
||||
def test_remove_drops_a_live_link_at_once(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.connected
|
||||
h.route(h.engine.remove(h.grant_list()[0]["spki"]))
|
||||
assert not again.connected
|
||||
|
||||
def test_no_idle_drop_on_an_authenticated_session(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 0.0)
|
||||
h.tick(500.0)
|
||||
assert again.connected and h.engine.connected() == 1
|
||||
|
||||
def test_resumed_phone_is_the_only_live_link_for_its_grant(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
first = h.new_phone(lid=0x4321, device="/one")
|
||||
first.static = phone.static
|
||||
first.resume_start(self.comma_static(h), 0.0)
|
||||
second = h.new_phone(lid=0x4322, device="/two")
|
||||
second.static = phone.static
|
||||
second.resume_start(self.comma_static(h), 1.0)
|
||||
assert second.connected and not first.connected
|
||||
|
||||
|
||||
class TestRpcOverSession(OpenpilotTestCase):
|
||||
def session(self, mocker, values=None) -> tuple[Harness, Phone]:
|
||||
known = {"DongleId", "CarParamsSP", "SunnylinkTempFault", "BluetoothAllowed", "BluetoothEnabled", "SunnylinkLocalBleGrants"}
|
||||
h = Harness(mocker, {"SunnylinkEnabled": True} | (values or {}), known)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_ADDED
|
||||
return h, phone
|
||||
|
||||
def test_status_get(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
mocker.patch("openpilot.sunnypilot.system.ble.rpc.get_version", return_value="0.9.0")
|
||||
mocker.patch("openpilot.sunnypilot.system.ble.rpc.HARDWARE.get_os_version", return_value="19.9")
|
||||
wpa = mocker.patch("openpilot.common.hardware.comma.hardware.wpa_supplicant_cmd",
|
||||
return_value={"mode": "station", "wpa_state": "COMPLETED", "ssid": "home"})
|
||||
result = phone.rpc("status.get", 0.0, rid=5)
|
||||
assert result["id"] == 5
|
||||
assert result["result"]["network"] == {"wifi_ssid": "home", "hotspot": False}
|
||||
assert result["result"]["phones"] == 1 and result["result"]["dongle_id"] == "dongle"
|
||||
wpa.return_value = {"mode": "AP", "wpa_state": "COMPLETED", "ssid": "weedle-1234"}
|
||||
assert phone.rpc("status.get", 1.0, rid=6)["result"]["network"] == {"wifi_ssid": None, "hotspot": True}
|
||||
|
||||
def test_unknown_method_is_not_found(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("nope", 0.0)["error"]["code"] == -32601
|
||||
|
||||
def test_params_set_and_get(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "x"}})["result"] == {"ok": ["CarParamsSP"]}
|
||||
got = phone.rpc("params.get", 0.0, {"keys": ["CarParamsSP", "SunnylinkTempFault"]})
|
||||
assert got["result"] == {"values": {"CarParamsSP": "x", "SunnylinkTempFault": None}}
|
||||
|
||||
def test_params_get_unset_reads_like_sunnylink(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.params.known |= {"IsMetric", "LongitudinalPersonality", "LanguageSetting"}
|
||||
h.params.types |= {"IsMetric": ParamKeyType.BOOL, "LongitudinalPersonality": ParamKeyType.INT, "LanguageSetting": ParamKeyType.STRING}
|
||||
h.params.defaults["LanguageSetting"] = "main_en"
|
||||
got = phone.rpc("params.get", 0.0, {"keys": ["IsMetric", "LongitudinalPersonality", "LanguageSetting"]})
|
||||
assert got["result"] == {"values": {"IsMetric": False, "LongitudinalPersonality": 0, "LanguageSetting": "main_en"}}
|
||||
|
||||
def test_params_refusals_are_all_or_nothing(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
for keys in (["BluetoothAllowed"], ["BluetoothEnabled"], ["SunnylinkLocalBleGrants"], ["AdbEnabled"]):
|
||||
assert "result" in phone.rpc("params.get", 0.0, {"keys": keys})
|
||||
refused = phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "y", "BluetoothAllowed": False}})
|
||||
assert refused["error"]["code"] == -32001
|
||||
assert h.params.data.get("CarParamsSP") is None
|
||||
assert phone.rpc("params.set", 0.0, {"values": {"NotAKey": 1}})["error"]["code"] == -32001
|
||||
|
||||
def test_params_get_limits_the_key_count(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("params.get", 0.0, {"keys": ["DongleId"] * 33})["error"]["code"] == -32001
|
||||
|
||||
def test_hotspot_start_answers_when_up(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.send_record(phone, s.RPC, json.dumps({"jsonrpc": "2.0", "id": 4, "method": "hotspot.start"}).encode(), 0.0)
|
||||
assert phone.inbox == [] and h.wifi.requested is True
|
||||
h.wifi.active = True
|
||||
h.tick(1.0)
|
||||
assert json.loads(phone.pop_record(s.RPC)) == {"jsonrpc": "2.0", "id": 4, "result": {"ssid": "weedle-test", "password": "pw-test"}}
|
||||
|
||||
def test_hotspot_start_times_out(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.send_record(phone, s.RPC, json.dumps({"jsonrpc": "2.0", "id": 9, "method": "hotspot.start"}).encode(), 0.0)
|
||||
h.tick(30.0)
|
||||
reply = json.loads(phone.pop_record(s.RPC))
|
||||
assert reply["id"] == 9 and reply["error"]["code"] == -32001
|
||||
|
||||
def test_hotspot_credentials_refused_while_off(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("hotspot.credentials", 0.0)["error"]["code"] == -32001
|
||||
h.wifi.active = True
|
||||
assert phone.rpc("hotspot.credentials", 0.0)["result"] == {"ssid": "weedle-test", "password": "pw-test"}
|
||||
|
||||
def test_hotspot_stop(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.wifi.active = True
|
||||
assert phone.rpc("hotspot.stop", 0.0)["result"] == {}
|
||||
assert h.wifi.requested is False
|
||||
|
||||
def test_phones_list_marks_this_phone(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
listing = phone.rpc("phones.list", 0.0)["result"]
|
||||
assert listing == [{"name": "test phone", "added": WALL, "last_seen": WALL, "this": True}]
|
||||
|
||||
def test_forget_self_drops_the_grant_and_the_link(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
response = phone.rpc("phones.forgetSelf", 0.0)
|
||||
assert response["result"] == {}
|
||||
assert h.grant_list() == [] and not phone.connected
|
||||
|
||||
def test_record_cap_after_session(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
phone.mtu = 247
|
||||
big = {"jsonrpc": "2.0", "id": 3, "method": "nope", "params": {"pad": "x" * 9000}}
|
||||
h.send_record(phone, s.RPC, json.dumps(big).encode(), 0.0)
|
||||
assert phone.connected and json.loads(phone.pop_record(s.RPC))["error"]["code"] == -32601
|
||||
h.send(phone, phone.records.seal(bytes([s.RPC]) + b" " * (s.link.SESSION_CAP + 1000)), 0.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_params_metadata(self, mocker):
|
||||
import base64
|
||||
import gzip
|
||||
|
||||
h, phone = self.session(mocker)
|
||||
phone.mtu = 247
|
||||
mocker.patch("openpilot.sunnypilot.sunnylink.tools.generate_settings_schema.generate_schema", return_value={"panels": []})
|
||||
mocker.patch("openpilot.sunnypilot.sunnylink.capabilities.generate_capabilities", return_value={"protocol_version": 1})
|
||||
response = phone.rpc("params.metadata", 0.0)
|
||||
encoded = response["result"]["params_metadata"]
|
||||
decoded = json.loads(gzip.decompress(base64.b64decode(encoded)).decode("utf-8"))
|
||||
assert decoded["panels"] == []
|
||||
assert decoded["capabilities"] == {"protocol_version": 1}
|
||||
assert "chestnut_active" in decoded
|
||||
|
||||
def test_stream_rejects_disallowed_port(self, mocker):
|
||||
from openpilot.sunnypilot.system.ble import stream as st
|
||||
h, phone = self.session(mocker)
|
||||
open_req = (1).to_bytes(2, "big") + bytes([st.STREAM_OPEN]) + (80).to_bytes(2, "big") + (16384).to_bytes(4, "big")
|
||||
h.send_record(phone, s.STREAM, open_req, 0.0)
|
||||
reply = phone.pop_record(s.STREAM)
|
||||
assert int.from_bytes(reply[0:2], "big") == 1
|
||||
assert reply[2] == st.STREAM_ERROR
|
||||
assert reply[3] == st.ERR_UNSUPPORTED_PORT
|
||||
|
||||
def test_stream_proxies_tcp_echo(self, mocker):
|
||||
import selectors
|
||||
import socket
|
||||
from openpilot.sunnypilot.system.ble import stream as st
|
||||
|
||||
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
srv.bind(("127.0.0.1", 0))
|
||||
srv.listen(1)
|
||||
port = srv.getsockname()[1]
|
||||
try:
|
||||
mocker.patch.object(st, "ALLOWED_PORTS", (port,))
|
||||
h, phone = self.session(mocker)
|
||||
phone.mtu = 247
|
||||
open_req = (7).to_bytes(2, "big") + bytes([st.STREAM_OPEN]) + port.to_bytes(2, "big") + (16384).to_bytes(4, "big")
|
||||
h.send_record(phone, s.STREAM, open_req, 0.0)
|
||||
|
||||
conn, _ = srv.accept()
|
||||
try:
|
||||
# Pump until OPEN_OK arrives
|
||||
for _ in range(10):
|
||||
for fd, events in h.engine.stream_selector_entries():
|
||||
h._deliver(h.engine.on_stream_ready(fd, bool(events & selectors.EVENT_READ), bool(events & selectors.EVENT_WRITE)))
|
||||
if phone.inbox:
|
||||
break
|
||||
ok = phone.pop_record(s.STREAM)
|
||||
assert ok[0:3] == (7).to_bytes(2, "big") + bytes([st.STREAM_OPEN_OK])
|
||||
|
||||
# Phone -> TCP server
|
||||
data_req = (7).to_bytes(2, "big") + bytes([st.STREAM_DATA]) + b"SSH-2.0-test\r\n"
|
||||
h.send_record(phone, s.STREAM, data_req, 0.0)
|
||||
assert conn.recv(64) == b"SSH-2.0-test\r\n"
|
||||
|
||||
# TCP server -> Phone
|
||||
conn.sendall(b"SSH-2.0-OpenSSH\r\n")
|
||||
for _ in range(10):
|
||||
for fd, events in h.engine.stream_selector_entries():
|
||||
h._deliver(h.engine.on_stream_ready(fd, bool(events & selectors.EVENT_READ), bool(events & selectors.EVENT_WRITE)))
|
||||
if phone.inbox:
|
||||
break
|
||||
echoed = phone.pop_record(s.STREAM)
|
||||
assert echoed[0:3] == (7).to_bytes(2, "big") + bytes([st.STREAM_DATA])
|
||||
assert echoed[3:] == b"SSH-2.0-OpenSSH\r\n"
|
||||
|
||||
# Disconnect cleans up stream
|
||||
h.engine.on_disconnect(phone.device)
|
||||
assert h.engine.stream_selector_entries() == []
|
||||
finally:
|
||||
conn.close()
|
||||
finally:
|
||||
srv.close()
|
||||
@@ -1,669 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import signal
|
||||
import time
|
||||
from collections import deque
|
||||
from itertools import count
|
||||
|
||||
from jeepney import DBusAddress, HeaderFields, MessageType, new_error, new_method_call, new_method_return
|
||||
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import bluetooth_manager as bm
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
|
||||
ADAPTER = "/org/bluez/hci0"
|
||||
DEVICE = ADAPTER + "/dev_4A_3B_2C_1D_0E_0F"
|
||||
SETUP = ["GetManagedObjects", "UnregisterAdvertisement", "UnregisterApplication", "Pairable", "Alias", "Powered",
|
||||
"DiscoverableTimeout", "Discoverable", "RegisterApplication", "RegisterAdvertisement"]
|
||||
TEARDOWN = ["UnregisterAdvertisement", "UnregisterApplication", "Discoverable", "Powered"]
|
||||
|
||||
|
||||
def variant(value) -> tuple:
|
||||
return "b" if isinstance(value, bool) else "s" if isinstance(value, str) else "u", value
|
||||
|
||||
|
||||
class FakeBus:
|
||||
"""Stands in for the system bus: records what is sent and answers method calls the way BlueZ does."""
|
||||
|
||||
def __init__(self, failing: tuple[str, ...] = (), adapter: bool = True):
|
||||
self.outgoing_serial = count(1)
|
||||
self.sent: list = []
|
||||
self.inbox: deque = deque()
|
||||
self.failing = failing # method names, or property names for Set
|
||||
self.adapter = adapter
|
||||
self.owner = 5 # bluetoothd is ":1.<owner>" on the bus
|
||||
self.registered: set[str] = set() # object paths registered with the running bluetoothd
|
||||
self.props = {"Powered": False, "Pairable": True, "Alias": "comma-0a1b2c3d", "Discoverable": False}
|
||||
self.devices: dict[str, dict[str, bool]] = {}
|
||||
self.dead = False
|
||||
self.hung = False # bluetoothd takes calls and never answers
|
||||
self.closed = False
|
||||
self.timeout = 0.0
|
||||
|
||||
def restart_bluetoothd(self):
|
||||
# a killed bluetoothd comes back under a new name without its registrations; the kernel keeps the adapter powered
|
||||
self.owner += 1
|
||||
self.registered.clear()
|
||||
|
||||
def objects(self) -> dict:
|
||||
if not self.adapter:
|
||||
return {}
|
||||
adapter = {
|
||||
bm.ADAPTER_IFACE: {name: variant(value) for name, value in self.props.items()},
|
||||
bm.GATT_MANAGER_IFACE: {},
|
||||
bm.ADVERTISING_MANAGER_IFACE: {"ActiveInstances": ("y", int(bm.ADVERTISEMENT_PATH in self.registered))},
|
||||
}
|
||||
return {ADAPTER: adapter} | {path: {bm.DEVICE_IFACE: {name: variant(value) for name, value in props.items()}}
|
||||
for path, props in self.devices.items()}
|
||||
|
||||
def send(self, msg, serial=None):
|
||||
if self.dead:
|
||||
raise BrokenPipeError
|
||||
msg.header.serial = next(self.outgoing_serial) if serial is None else serial
|
||||
msg.serialise() # raises when a body does not match its signature # codespell:ignore serialise
|
||||
self.sent.append(msg)
|
||||
if msg.header.message_type != MessageType.method_call or self.hung:
|
||||
return
|
||||
|
||||
member = msg.header.fields[HeaderFields.member]
|
||||
if (msg.body[1] if member == "Set" else member) in self.failing:
|
||||
reply = new_error(msg, "org.bluez.Error.Failed")
|
||||
elif not self.adapter and msg.header.fields[HeaderFields.path].startswith(ADAPTER):
|
||||
reply = new_error(msg, "org.freedesktop.DBus.Error.UnknownObject")
|
||||
elif member == "RemoveDevice" and not self.props["Powered"]:
|
||||
reply = new_error(msg, "org.bluez.Error.NotReady")
|
||||
elif member == "GetManagedObjects":
|
||||
reply = new_method_return(msg, "a{oa{sa{sv}}}", (self.objects(),))
|
||||
else:
|
||||
if member == "Set":
|
||||
self.props[msg.body[1]] = msg.body[2][1]
|
||||
elif member.startswith("Register"):
|
||||
self.registered.add(msg.body[0])
|
||||
elif member.startswith("Unregister"):
|
||||
self.registered.discard(msg.body[0])
|
||||
elif member == "RemoveDevice":
|
||||
del self.devices[msg.body[0]]
|
||||
reply = new_method_return(msg)
|
||||
reply.header.fields[HeaderFields.sender] = f":1.{self.owner}"
|
||||
self.inbox.append(reply)
|
||||
|
||||
def receive(self, timeout: float = 0.0):
|
||||
self.timeout = timeout
|
||||
if self.dead:
|
||||
raise ConnectionResetError
|
||||
if not self.inbox:
|
||||
raise TimeoutError
|
||||
return self.inbox.popleft()
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
def calls(self) -> list[str]:
|
||||
return [m.body[1] if (member := m.header.fields[HeaderFields.member]) == "Set" else member
|
||||
for m in self.sent if m.header.message_type == MessageType.method_call]
|
||||
|
||||
|
||||
class FakeParams:
|
||||
def __init__(self, values: dict | None = None, bus: FakeBus | None = None):
|
||||
self.bus = bus
|
||||
self.data = values or {}
|
||||
self.puts: list[str] = []
|
||||
|
||||
def get(self, key):
|
||||
return self.data.get(key)
|
||||
|
||||
def get_bool(self, key):
|
||||
return bool(self.data.get(key))
|
||||
|
||||
def put(self, key, value):
|
||||
self.data[key] = value
|
||||
self.puts.append(key)
|
||||
if self.bus is not None and key == "BluetoothEnabled" and not value:
|
||||
self.bus.adapter = False # AGNOS stops the UART attach, and BlueZ drops the adapter
|
||||
|
||||
put_bool = put
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
def make(mocker: Mocker, **bus_kwargs) -> tuple[bm.BluetoothManager, FakeBus]:
|
||||
bus = FakeBus(**bus_kwargs)
|
||||
mocker.patch.object(bm, "Params", return_value=FakeParams(bus=bus))
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 0.01)
|
||||
manager = bm.BluetoothManager(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock())
|
||||
manager._conn = bus
|
||||
return manager, bus
|
||||
|
||||
|
||||
def make_ready(mocker: Mocker) -> tuple[bm.BluetoothManager, FakeBus]:
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
bus.sent.clear()
|
||||
return manager, bus
|
||||
|
||||
|
||||
def incoming(path: str, iface: str, member: str, signature: str | None = None, body: tuple = ()):
|
||||
msg = new_method_call(DBusAddress(path, ":1.42", iface), member, signature, body)
|
||||
msg.header.serial = 1000
|
||||
msg.header.fields[HeaderFields.sender] = ":1.5"
|
||||
return msg
|
||||
|
||||
|
||||
def from_bluez(manager: bm.BluetoothManager, bus: FakeBus, *call):
|
||||
"""Deliver a method call from BlueZ and return the reply."""
|
||||
bus.sent.clear()
|
||||
manager._dispatch(incoming(*call))
|
||||
return bus.sent[-1]
|
||||
|
||||
|
||||
def write(manager: bm.BluetoothManager, bus: FakeBus, value: bytes, **options):
|
||||
options = {"device": ("o", DEVICE), "mtu": ("q", 247), "link": ("s", "LE")} | options
|
||||
return from_bluez(manager, bus, bm.RX_PATH, bm.GATT_CHARACTERISTIC_IFACE, "WriteValue", "aya{sv}", (value, options))
|
||||
|
||||
|
||||
def disconnects(bus: FakeBus) -> list[str]:
|
||||
return [m.header.fields[HeaderFields.path] for m in bus.sent if m.header.fields.get(HeaderFields.member) == "Disconnect"]
|
||||
|
||||
|
||||
class TestObjects(OpenpilotTestCase):
|
||||
def test_gatt_tree_never_asks_for_pairing(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.APP_PATH, bm.OBJECT_MANAGER_IFACE, "GetManagedObjects")
|
||||
|
||||
tree = reply.body[0]
|
||||
assert set(tree) == {bm.SERVICE_PATH, bm.RX_PATH, bm.TX_PATH}
|
||||
flags = [f for path in (bm.RX_PATH, bm.TX_PATH) for f in tree[path][bm.GATT_CHARACTERISTIC_IFACE]["Flags"][1]]
|
||||
assert sorted(flags) == ["notify", "write", "write-without-response"]
|
||||
|
||||
def test_advertisement_has_no_name_or_tx_power(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.ADVERTISEMENT_PATH, bm.PROPERTIES_IFACE, "GetAll", "s", (bm.ADVERTISEMENT_IFACE,))
|
||||
|
||||
assert reply.body[0] == {"Type": ("s", "peripheral"), "ServiceUUIDs": ("as", [bm.SERVICE_UUID])}
|
||||
|
||||
def test_unknown_method_gets_an_error(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.RX_PATH, bm.GATT_CHARACTERISTIC_IFACE, "ReadValue", "a{sv}", ({},))
|
||||
|
||||
assert reply.header.message_type == MessageType.error
|
||||
|
||||
|
||||
class TestWrite(OpenpilotTestCase):
|
||||
def test_write_reaches_callback(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = write(manager, bus, b"\x01\x02")
|
||||
|
||||
manager._on_write.assert_called_once_with(DEVICE, b"\x01\x02", 247)
|
||||
assert manager.connected == {DEVICE}
|
||||
assert disconnects(bus) == []
|
||||
assert reply.header.message_type == MessageType.method_return
|
||||
assert reply.header.fields[HeaderFields.reply_serial] == 1000
|
||||
|
||||
def test_write_at_an_offset_disconnects(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
write(manager, bus, b"\x01", offset=("q", 20))
|
||||
|
||||
manager._on_write.assert_not_called()
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
|
||||
def test_write_longer_than_one_packet_disconnects(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
write(manager, bus, bytes(244))
|
||||
manager._on_write.assert_called_once()
|
||||
|
||||
write(manager, bus, bytes(245))
|
||||
manager._on_write.assert_called_once()
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
|
||||
def test_failing_callback_keeps_serving(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._on_write.side_effect = ValueError
|
||||
reply = write(manager, bus, b"\x01")
|
||||
|
||||
assert reply.header.message_type == MessageType.method_return
|
||||
|
||||
def test_notify_sends_value(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
assert manager.notify(b"\x05\x06")
|
||||
|
||||
signal = bus.sent[-1]
|
||||
assert signal.header.fields[HeaderFields.path] == bm.TX_PATH
|
||||
assert signal.body == (bm.GATT_CHARACTERISTIC_IFACE, {"Value": ("ay", b"\x05\x06")}, [])
|
||||
|
||||
def test_notify_reports_what_was_not_sent(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
bus.dead = True
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
manager._conn = None
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
def test_disconnect(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.disconnect(DEVICE)
|
||||
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
assert bus.sent[-1].header.fields[HeaderFields.interface] == bm.DEVICE_IFACE
|
||||
|
||||
|
||||
class TestReconcile(OpenpilotTestCase):
|
||||
def test_setup_order(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert bus.props == {"Powered": True, "Pairable": False, "Alias": "comma", "DiscoverableTimeout": 0, "Discoverable": True}
|
||||
|
||||
def test_set_enabled_writes_only_on_change(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(False)
|
||||
manager._reconcile()
|
||||
assert manager._params.puts == []
|
||||
|
||||
manager.set_enabled(True)
|
||||
manager.set_enabled(True)
|
||||
assert manager._params.puts == ["BluetoothEnabled"]
|
||||
assert manager._params.data["BluetoothEnabled"] is True
|
||||
|
||||
def test_disabled_does_nothing(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls() == []
|
||||
|
||||
def test_waits_for_adapter(self, mocker):
|
||||
manager, bus = make(mocker, adapter=False)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
assert not manager.ready
|
||||
|
||||
bus.adapter = True
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
def test_never_advertises_while_bondable(self, mocker):
|
||||
manager, bus = make(mocker, failing=("Pairable",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert "Powered" not in bus.calls()
|
||||
assert "RegisterAdvertisement" not in bus.calls()
|
||||
|
||||
def test_never_powers_on_under_the_hostname(self, mocker):
|
||||
manager, bus = make(mocker, failing=("Alias",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert "Powered" not in bus.calls()
|
||||
|
||||
def test_failed_registration_is_rolled_back(self, mocker):
|
||||
manager, bus = make(mocker, failing=("RegisterAdvertisement",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls()[-2:] == ["UnregisterAdvertisement", "UnregisterApplication"]
|
||||
|
||||
def test_healthy_adapter_costs_one_call(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == ["GetManagedObjects"]
|
||||
|
||||
def test_registers_again_after_power_loss(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Powered"] = False
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
|
||||
def test_registers_again_when_made_pairable(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Pairable"] = True
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert not bus.props["Pairable"]
|
||||
|
||||
def test_registers_again_after_bluetoothd_restart(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.restart_bluetoothd()
|
||||
assert bus.props["Powered"]
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert bus.registered == {bm.APP_PATH, bm.ADVERTISEMENT_PATH}
|
||||
|
||||
def test_paired_device_is_removed_before_advertising(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Pairable"] = True
|
||||
bus.devices[DEVICE] = {"Connected": False, "Paired": True}
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.devices == {}
|
||||
calls = bus.calls()
|
||||
assert calls.index("Powered") < calls.index("RemoveDevice") < calls.index("RegisterApplication")
|
||||
|
||||
def test_registers_again_after_release(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
from_bluez(manager, bus, bm.ADVERTISEMENT_PATH, bm.ADVERTISEMENT_IFACE, "Release")
|
||||
assert not manager.ready
|
||||
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
def test_disable_powers_off_before_the_param_clears(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
manager.set_enabled(False)
|
||||
assert manager._params.data["BluetoothEnabled"] is True
|
||||
|
||||
manager._reconcile()
|
||||
assert not manager.ready
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert not bus.props["Powered"] and not bus.props["Discoverable"]
|
||||
assert manager._params.data["BluetoothEnabled"] is False
|
||||
assert not bus.adapter
|
||||
|
||||
manager._reconcile()
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert manager._params.puts.count("BluetoothEnabled") == 2
|
||||
|
||||
def test_tick_runs_while_bluetoothd_does_not_answer(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.hung = True
|
||||
manager._reconcile()
|
||||
|
||||
manager._on_tick.assert_called_once_with()
|
||||
|
||||
def test_unanswered_reconcile_keeps_the_adapter_for_teardown(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.hung = True
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
bus.hung = False
|
||||
bus.sent.clear()
|
||||
manager.set_enabled(False)
|
||||
manager._reconcile()
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert not bus.props["Powered"]
|
||||
|
||||
def test_stop_abandons_a_waiting_call(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 5.0)
|
||||
mocker.patch.object(manager, "_on_tick", side_effect=manager.stop)
|
||||
bus.hung = True
|
||||
started = time.monotonic()
|
||||
manager._reconcile()
|
||||
|
||||
assert time.monotonic() - started < 1.0
|
||||
|
||||
def test_stop_skips_the_remaining_setup_steps(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
send = bus.send
|
||||
|
||||
def stop_after_alias(msg, serial=None):
|
||||
send(msg, serial)
|
||||
if msg.body[1:2] == ("Alias",):
|
||||
manager.stop()
|
||||
mocker.patch.object(bus, "send", side_effect=stop_after_alias)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls()[-1] == "Alias"
|
||||
|
||||
def test_connected_devices(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
mocker.patch.object(manager, "_on_disconnect", side_effect=ValueError)
|
||||
bus.devices[DEVICE] = {"Connected": True, "Paired": False}
|
||||
manager._reconcile()
|
||||
assert manager.connected == {DEVICE}
|
||||
manager._on_disconnect.assert_not_called()
|
||||
|
||||
bus.devices[DEVICE]["Connected"] = False
|
||||
manager._reconcile()
|
||||
assert manager.connected == frozenset()
|
||||
manager._on_disconnect.assert_called_once_with(DEVICE)
|
||||
assert manager.ready
|
||||
|
||||
def test_device_seen_only_by_its_write_is_reported_gone(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
write(manager, bus, b"\x01")
|
||||
manager._reconcile()
|
||||
|
||||
manager._on_disconnect.assert_called_once_with(DEVICE)
|
||||
|
||||
def test_serves_bluez_while_waiting_for_a_reply(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
bus.inbox.append(incoming(bm.APP_PATH, bm.OBJECT_MANAGER_IFACE, "GetManagedObjects"))
|
||||
|
||||
assert manager._call(new_method_call(DBusAddress(ADAPTER, bm.BLUEZ, bm.GATT_MANAGER_IFACE), "RegisterApplication", "oa{sv}", (bm.APP_PATH, {}))) == ()
|
||||
assert bus.sent[-1].header.fields[HeaderFields.reply_serial] == 1000
|
||||
|
||||
|
||||
class TestRun(OpenpilotTestCase):
|
||||
def run_manager(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._conn = None
|
||||
mocker.patch.object(bm, "open_dbus_connection", return_value=bus)
|
||||
mocker.patch.object(bm, "RECONCILE_PERIOD", 0)
|
||||
manager.set_enabled(True)
|
||||
return manager, bus
|
||||
|
||||
def test_stop_powers_off_and_closes(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
manager._on_tick.side_effect = manager.stop
|
||||
manager.run()
|
||||
|
||||
manager._on_tick.assert_called_once_with()
|
||||
assert bus.calls() == SETUP + TEARDOWN
|
||||
assert not bus.props["Powered"] and not bus.props["Discoverable"]
|
||||
assert bus.closed
|
||||
assert not manager.ready
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
def test_dead_bus_still_closes(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
manager._on_tick.side_effect = lambda: setattr(bus, "dead", True)
|
||||
|
||||
with self.assertRaises(ConnectionResetError):
|
||||
manager.run()
|
||||
assert bus.closed
|
||||
assert manager._conn is None
|
||||
assert not manager.ready
|
||||
|
||||
def test_calls_are_short_once_stopping(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 5.0)
|
||||
manager.stop()
|
||||
manager._call(new_method_call(DBusAddress(ADAPTER, bm.BLUEZ, bm.GATT_MANAGER_IFACE), "UnregisterApplication", "o", (bm.APP_PATH,)))
|
||||
|
||||
assert 0 < bus.timeout <= bm.STOP_CALL_TIMEOUT
|
||||
|
||||
def test_failing_tick_keeps_running(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
|
||||
def tick():
|
||||
if manager._on_tick.call_count == 1:
|
||||
raise ValueError
|
||||
manager.stop()
|
||||
manager._on_tick.side_effect = tick
|
||||
manager.run()
|
||||
|
||||
assert manager._on_tick.call_count == 2
|
||||
assert bus.closed
|
||||
|
||||
|
||||
def make_daemon(mocker: Mocker, **values):
|
||||
mocker.patch.object(cp, "qr_text", return_value="SLC1:qr")
|
||||
mocker.patch.object(bm, "grant_count", return_value=0)
|
||||
params = FakeParams({"BluetoothAllowed": True} | values)
|
||||
bt = mocker.patch.object(bm, "BluetoothManager").return_value
|
||||
bt.ready = False
|
||||
return bm.Daemon(params, cp.ConnectPhoneWindow()), params, bt
|
||||
|
||||
|
||||
def request(params: FakeParams, action: str, seq: int):
|
||||
params.data[cp.REQUEST_KEY] = {"seq": seq, "action": action}
|
||||
|
||||
|
||||
class TestDaemon(OpenpilotTestCase):
|
||||
def test_open_then_ready(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert cp.REQUEST_KEY not in params.data
|
||||
window = params.data[cp.WINDOW_KEY]
|
||||
assert (window["seq"], window["state"], window["qr"], window["deadline"]) == (7, "starting", "SLC1:qr", 100.0 + cp.WINDOW_SECONDS)
|
||||
bt.set_enabled.assert_called_with(True)
|
||||
|
||||
bt.ready = True
|
||||
daemon.step(101.0)
|
||||
assert params.data[cp.WINDOW_KEY]["state"] == "open"
|
||||
|
||||
def test_window_is_written_only_when_it_changes(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
daemon.step(100.0)
|
||||
daemon.step(101.0)
|
||||
assert params.puts == [cp.WINDOW_KEY, bm.STATUS_KEY]
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 0, "state": "closed", "reason": "", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_cancel(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
request(params, "cancel", 8)
|
||||
daemon.step(101.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "cancel", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_not_opened_while_bluetooth_is_off(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker, BluetoothAllowed=False)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "bluetooth_off"}
|
||||
cp.qr_text.assert_not_called()
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_turning_bluetooth_off_closes_the_window(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
params.data["BluetoothAllowed"] = False
|
||||
daemon.step(101.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "bluetooth_off", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_missing_device_key(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
cp.qr_text.side_effect = RuntimeError
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "no_key"}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
cp.qr_text.side_effect = ValueError
|
||||
request(params, "open", 8)
|
||||
daemon.step(101.0)
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 8, "state": "closed", "reason": "error"}
|
||||
|
||||
cp.qr_text.side_effect = None
|
||||
request(params, "open", 9)
|
||||
daemon.step(102.0)
|
||||
assert params.data[cp.WINDOW_KEY]["state"] == "starting"
|
||||
|
||||
def test_a_grant_keeps_bluetooth_on_without_a_window(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
mocker.patch.object(bm, "grant_count", return_value=1)
|
||||
daemon.step(100.0)
|
||||
bt.set_enabled.assert_called_with(True)
|
||||
|
||||
params.data["BluetoothAllowed"] = False
|
||||
daemon.step(101.0)
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_enable_is_written_again_once_without_an_adapter(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
mocker.patch.object(bm, "grant_count", return_value=1)
|
||||
for now in (100.0, 109.9):
|
||||
daemon.step(now)
|
||||
assert "BluetoothEnabled" not in params.puts
|
||||
|
||||
for now in (110.0, 111.0, 130.0):
|
||||
daemon.step(now)
|
||||
assert params.puts.count("BluetoothEnabled") == 1
|
||||
|
||||
bt.ready = True
|
||||
daemon.step(131.0)
|
||||
bt.ready = False
|
||||
for now in (132.0, 142.0):
|
||||
daemon.step(now)
|
||||
assert params.puts.count("BluetoothEnabled") == 2
|
||||
|
||||
def test_write_disconnects_the_phone(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
daemon.on_write(DEVICE, b"\x01", 247)
|
||||
|
||||
bt.disconnect.assert_called_once_with(DEVICE)
|
||||
|
||||
def run_main(self, mocker, runs: list):
|
||||
handlers = mocker.patch.object(bm.signal, "signal")
|
||||
params = FakeParams({"BluetoothAllowed": True})
|
||||
mocker.patch.object(bm, "Params", return_value=params)
|
||||
mocker.patch.object(bm, "RESTART_BACKOFF", 0.03)
|
||||
mocker.patch.object(bm, "RECONCILE_PERIOD", 0.01)
|
||||
mocker.patch.object(bm, "grant_count", return_value=0)
|
||||
manager = mocker.patch.object(bm, "BluetoothManager")
|
||||
def run(*_):
|
||||
outcome = runs.pop(0)
|
||||
if outcome == "signal":
|
||||
handlers.call_args.args[1](signal.SIGTERM, None)
|
||||
else:
|
||||
raise outcome
|
||||
manager.return_value.run.side_effect = run
|
||||
bm.main()
|
||||
return manager, handlers, params
|
||||
|
||||
def test_main_wires_the_manager(self, mocker):
|
||||
manager, handlers, params = self.run_main(mocker, ["signal"])
|
||||
|
||||
bt = manager.return_value
|
||||
bt.run.assert_called_once_with()
|
||||
bt.stop.assert_called_once_with()
|
||||
assert [call.args[0] for call in handlers.call_args_list] == [signal.SIGINT, signal.SIGTERM]
|
||||
on_write, on_disconnect, on_tick = manager.call_args.args
|
||||
on_write(DEVICE, b"\x01", 247)
|
||||
bt.disconnect.assert_called_once_with(DEVICE)
|
||||
on_tick()
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_main_replaces_a_failed_manager_and_keeps_ticking(self, mocker):
|
||||
manager, handlers, params = self.run_main(mocker, [ConnectionResetError(), ValueError(), "signal"])
|
||||
|
||||
assert manager.call_count == 3
|
||||
assert manager.return_value.run.call_count == 3
|
||||
assert params.puts == [cp.WINDOW_KEY, bm.STATUS_KEY]
|
||||
@@ -1,269 +0,0 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
|
||||
DEVICE = "/org/bluez/hci0/dev_4A_3B_2C_1D_0E_0F"
|
||||
|
||||
|
||||
class FakeParams:
|
||||
"""Stores JSON text like the real JSON params, so values that cannot be stored fail here too."""
|
||||
|
||||
def __init__(self):
|
||||
self.data: dict[str, str] = {}
|
||||
|
||||
def get(self, key, block=False, return_default=False):
|
||||
return json.loads(self.data[key]) if key in self.data else None
|
||||
|
||||
def put(self, key, value, block=False):
|
||||
self.data[key] = json.dumps(value)
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
def use_key(mocker: Mocker) -> ec.EllipticCurvePrivateKey:
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()).decode()
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=("ES256", pem, "unused"))
|
||||
return key
|
||||
|
||||
|
||||
def spki_hash(key: ec.EllipticCurvePrivateKey) -> bytes:
|
||||
return hashlib.sha256(key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)).digest()
|
||||
|
||||
|
||||
class TestCode(OpenpilotTestCase):
|
||||
def test_refused_codes_are_redrawn(self, mocker):
|
||||
randbelow = mocker.patch.object(cp.secrets, "randbelow", side_effect=[11111110, 88888887, 12345677, 87654320, 0])
|
||||
|
||||
assert cp.generate_code() == 1
|
||||
assert randbelow.call_args_list == [mocker.call(99_999_998)] * 5
|
||||
|
||||
def test_highest_code(self, mocker):
|
||||
mocker.patch.object(cp.secrets, "randbelow", return_value=99_999_997)
|
||||
|
||||
assert cp.generate_code() == 99_999_998
|
||||
|
||||
def test_format(self):
|
||||
assert cp.format_code(12345679) == "1234 5679"
|
||||
assert cp.format_code(1) == "0000 0001"
|
||||
|
||||
|
||||
class TestQr(OpenpilotTestCase):
|
||||
def test_device_key_hash_is_sha256_of_spki(self, mocker):
|
||||
key = use_key(mocker)
|
||||
|
||||
assert cp.device_key_hash() == spki_hash(key)
|
||||
|
||||
def test_missing_device_key_raises(self, mocker):
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=(None, None, None))
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
cp.device_key_hash()
|
||||
|
||||
def test_payload(self, mocker):
|
||||
key = use_key(mocker)
|
||||
text = cp.qr_text(1234, b"\xaa" * 8)
|
||||
|
||||
assert text.startswith("SLC1:") and len(text) == 64
|
||||
payload = base64.urlsafe_b64decode(text[5:] + "=")
|
||||
assert payload == (1234).to_bytes(4, "big") + spki_hash(key) + b"\xaa" * 8
|
||||
|
||||
|
||||
class TestWindow(OpenpilotTestCase):
|
||||
def test_open_starts_then_reports_ready(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", return_value=42)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": ""}
|
||||
assert window.open(1000.0, seq=7) == "ok"
|
||||
assert window.active
|
||||
state = window.state()
|
||||
assert state == {"seq": 7, "state": "starting", "code": "00000042", "qr": state["qr"],
|
||||
"deadline": 1000.0 + cp.WINDOW_SECONDS, "held": False, "reason": ""}
|
||||
assert state["qr"].startswith("SLC1:")
|
||||
|
||||
window.tick(1001.0, ready=False)
|
||||
assert window.state()["state"] == "starting"
|
||||
window.tick(1002.0)
|
||||
assert window.state()["state"] == "open"
|
||||
|
||||
def test_same_request_again_changes_nothing(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=1)
|
||||
first = window.state()
|
||||
|
||||
assert window.open(1050.0, seq=1) == "busy"
|
||||
assert window.state() == first
|
||||
|
||||
def test_new_request_replaces_the_open_window(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", side_effect=[11, 22])
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=1)
|
||||
window.tick(1001.0)
|
||||
first = window.state()
|
||||
|
||||
assert window.open(1050.0, seq=2) == "ok"
|
||||
second = window.state()
|
||||
assert second == {"seq": 2, "state": "starting", "code": "00000022", "qr": second["qr"],
|
||||
"deadline": 1050.0 + cp.WINDOW_SECONDS, "held": False, "reason": ""}
|
||||
assert second["qr"] != first["qr"]
|
||||
|
||||
def test_closes_itself_after_the_window(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1004.0)
|
||||
|
||||
window.tick(1004.0 + cp.WINDOW_SECONDS - 0.1)
|
||||
assert window.active
|
||||
window.tick(1004.0 + cp.WINDOW_SECONDS)
|
||||
assert not window.active
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "timeout"}
|
||||
|
||||
def test_full_time_counts_from_ready(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1003.0, ready=False)
|
||||
window.tick(1005.0)
|
||||
assert window.state()["deadline"] == 1005.0 + cp.WINDOW_SECONDS
|
||||
window.tick(1006.0, ready=False)
|
||||
window.tick(1007.0)
|
||||
assert window.state()["deadline"] == 1005.0 + cp.WINDOW_SECONDS
|
||||
|
||||
def test_held_window_does_not_time_out(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1000.0)
|
||||
window.hold()
|
||||
window.tick(1000.0 + cp.WINDOW_SECONDS + 60)
|
||||
assert window.active
|
||||
window.cancel("granted")
|
||||
assert window.state()["reason"] == "granted"
|
||||
|
||||
def test_cancel(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.cancel()
|
||||
assert window.state()["reason"] == ""
|
||||
|
||||
window.open(1000.0)
|
||||
window.cancel()
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "cancel"}
|
||||
|
||||
window.open(1000.0)
|
||||
window.cancel("bluetooth_off")
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "bluetooth_off"}
|
||||
|
||||
def test_reopen_draws_a_new_code_and_nonce(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", side_effect=[11, 22])
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
first = window.state()
|
||||
window.cancel()
|
||||
|
||||
assert window.open(1010.0) == "ok"
|
||||
second = window.state()
|
||||
assert (first["code"], second["code"]) == ("00000011", "00000022")
|
||||
assert first["qr"] != second["qr"]
|
||||
assert second["deadline"] == 1010.0 + cp.WINDOW_SECONDS
|
||||
|
||||
def test_missing_device_key_leaves_the_window_closed(self, mocker):
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=(None, None, None))
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
window.open(1000.0)
|
||||
assert not window.active
|
||||
|
||||
def test_secret_only_while_open(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
assert cp.PAKE_SUITE == 1
|
||||
assert window.secret() is None
|
||||
window.open(1000.0)
|
||||
digits, nonce = window.secret()
|
||||
assert len(digits) == 8 and digits.isdigit() and len(nonce) == 8
|
||||
window.cancel()
|
||||
assert window.secret() is None
|
||||
|
||||
|
||||
class TestParams(OpenpilotTestCase):
|
||||
def test_request(self):
|
||||
params = FakeParams()
|
||||
|
||||
first = cp.write_request(params, "open")
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": first, "action": "open"}
|
||||
second = cp.write_request(params, "cancel")
|
||||
assert second > first
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": second, "action": "cancel"}
|
||||
|
||||
def test_unknown_action_is_refused(self):
|
||||
params = FakeParams()
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
cp.write_request(params, "bogus")
|
||||
assert params.data == {}
|
||||
|
||||
def test_window_round_trip(self, mocker):
|
||||
use_key(mocker)
|
||||
params = FakeParams()
|
||||
assert cp.read_window(params) is None
|
||||
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=5)
|
||||
params.put(cp.WINDOW_KEY, window.state())
|
||||
assert cp.read_window(params) == window.state()
|
||||
|
||||
def test_remove_request_carries_the_phone(self):
|
||||
params = FakeParams()
|
||||
|
||||
seq = cp.write_request(params, "remove", phone="abc")
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": seq, "action": "remove", "phone": "abc"}
|
||||
|
||||
def test_status_and_indicator(self):
|
||||
params = FakeParams()
|
||||
assert cp.read_status(params) == {}
|
||||
assert cp.phone_indicator({}) == "hidden"
|
||||
|
||||
params.put(cp.STATUS_KEY, {"enabled": True, "connected": 0, "phones": 1})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "waiting"
|
||||
params.put(cp.STATUS_KEY, {"enabled": True, "connected": 2, "phones": 1})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "connected"
|
||||
params.put(cp.STATUS_KEY, {"enabled": False, "connected": 0, "phones": 0})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "hidden"
|
||||
|
||||
def test_no_grants_yet(self, mocker):
|
||||
mocker.patch.object(cp, "Params", return_value=FakeParams())
|
||||
assert cp.grant_count() == 0
|
||||
|
||||
|
||||
class TestDisplayName(OpenpilotTestCase):
|
||||
def test_dongle_id_then_serial(self):
|
||||
params = FakeParams()
|
||||
assert cp.display_name(params) == "comma"
|
||||
params.put("HardwareSerial", "a1b2c3d4")
|
||||
assert cp.display_name(params) == "comma a1b2"
|
||||
params.put("DongleId", cp.UNREGISTERED_DONGLE_ID)
|
||||
assert cp.display_name(params) == "comma a1b2"
|
||||
params.put("DongleId", "3f12aa0000000000")
|
||||
assert cp.display_name(params) == "comma 3f12"
|
||||
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
import datetime
|
||||
import os
|
||||
import platform
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
@@ -222,8 +221,7 @@ def main() -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if platform.system() != "Darwin":
|
||||
unblock_stdout()
|
||||
unblock_stdout()
|
||||
|
||||
try:
|
||||
main()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user