Compare commits

...

37 Commits

Author SHA1 Message Date
Jason Wen a6e313bb9a agnos: test AGNOS 19.9-sunnypilot.2-dae64af 2026-11-25 14:57:15 -05:00
Jason Wen cb95d65923 bluetooth: read unset params like sunnylink 2026-11-25 13:30:31 -05:00
Jason Wen 2bdcb77ed2 [MICI] ui: show the comma name under connect phone 2026-11-25 13:09:16 -05:00
Jason Wen 5f86bd34dc [TIZI/TICI] ui: name the comma on Connect phone 2026-11-25 13:09:16 -05:00
Jason Wen e675689ded bluetooth: add comma display name 2026-11-25 13:09:15 -05:00
Jason Wen 4f8d054cf3 [TIZI/TICI] ui: simplify Bluetooth phone list 2026-11-25 12:25:44 -05:00
Jason Wen 1c9fa16a9a [MICI] ui: show Connect phone timeout message 2026-11-25 12:14:19 -05:00
Jason Wen 0c8e4665a1 [MICI] ui: fix stuck Connect phone screen 2026-11-25 11:51:20 -05:00
Jason Wen 59ac80f0d9 [TIZI/TICI] ui: fix Bluetooth text overflow 2026-11-25 11:05:09 -05:00
Jason Wen 87167d7403 [MICI] ui: fix Bluetooth text overlap 2026-11-25 11:05:09 -05:00
Jason Wen 8004e0305e bluetooth: normalize phone names 2026-11-25 11:05:09 -05:00
Jason Wen 3343e9fde8 Merge master into agnos-19.9-bluetooth 2026-11-25 11:05:03 -05:00
Jason Wen 6732fcc52a bump opendbc and update CARS.md 2026-11-25 03:12:54 -05:00
Jason Wen 9b514ae0a7 [TIZI/TICI] ui: add Bluetooth settings panel 2026-11-25 01:51:01 -05:00
Jason Wen 7d93cd16cd [MICI] ui: add Bluetooth settings panel 2026-11-25 01:50:53 -05:00
Jason Wen cb6b5d6913 bluetooth: add bluetooth_manager daemon 2026-11-25 01:50:52 -05:00
Jason Wen 3c4f6b5e0e bluetooth: add BLE Connect phone protocol 2026-11-25 01:50:52 -05:00
Jason Wen 3fb02ca1f6 Merge master into agnos-19.9-bluetooth 2026-11-25 01:50:44 -05:00
Jason Wen 1d23066201 bump opendbc and update CARS.md 2026-11-25 00:55:35 -05:00
Jason Wen 1f15111e33 agnos: 19.9-sunnypilot.2 release build 2026-11-24 23:41:46 -05:00
Jason Wen 368ea8c3d9 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into agnos-19.9-bluetooth 2026-11-24 23:41:41 -05:00
Jason Wen 202ee8d64e agnos: 19.9 Bluetooth watcher fix build 2026-11-24 19:46:58 -05:00
Jason Wen c410198c80 bump opendbc and update CARS.md 2026-11-24 17:31:04 -05:00
Jason Wen 4023e5d616 agnos: 19.9 IMU interrupt fix build 2026-11-24 00:27:48 -05:00
Jason Wen 035f5ce655 agnos: 19.9-sunnypilot.1 release build 2026-11-23 13:54:17 -05:00
Jason Wen ec2edb34f7 agnos: 19.9 Bluetooth pairing refusal build 2026-11-23 11:50:57 -05:00
Jason Wen 74f99e04e4 agnos: 19.9 Bluetooth address fix build 2026-11-23 04:28:46 -05:00
Jason Wen 85c794547a agnos: 19.9 Bluetooth baud event build 2026-11-23 03:49:59 -05:00
Jason Wen 9caada9700 agnos: 19.9 Bluetooth 3.2 Mbaud build 2026-11-23 01:26:16 -05:00
Jason Wen f733eba7f6 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into agnos-19.9-bluetooth 2026-11-23 01:26:16 -05:00
Jason Wen abada6315d locationd: replace LLK with GPS fuser (#2112)
* locationd: replace llk with a GPS fuser

* gps_fuser: keep gpsOK when GPS is newer
2026-11-22 22:59:16 -05:00
Jason Wen 2b203a5237 params: don't back up BluetoothEnabled 2026-11-22 22:39:51 -05:00
Jason Wen efe7b30b4c agnos: 19.9 Bluetooth LE only build 2026-11-22 22:39:50 -05:00
Jason Wen 74c14722be params: add BluetoothEnabled 2026-11-22 17:13:24 -05:00
Jason Wen edaf055284 agnos: 19.9 Bluetooth v2 test build 2026-11-22 16:42:13 -05:00
Jason Wen 1527c52bf1 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into agnos-19.9-bluetooth 2026-11-22 16:41:58 -05:00
Jason Wen c78f4c4549 agnos: 19.9 Bluetooth test build 2026-11-21 16:15:12 -05:00
64 changed files with 4442 additions and 2062 deletions
@@ -168,7 +168,7 @@ jobs:
echo "Building locationd..."
# -j1: parallel rednose generators OOM the device
scons -j1 cache_dir="$SCONS_CACHE" --minimal \
openpilot/selfdrive/locationd openpilot/sunnypilot/selfdrive/locationd
openpilot/selfdrive/locationd
echo "Building rest of sunnypilot"
sudo rm -rf /tmp/* || true
mkdir -p "$BUILD_DIR/tmp"
-2
View File
@@ -293,8 +293,6 @@ SConscript([
'openpilot/selfdrive/ui/SConscript',
])
SConscript(['openpilot/sunnypilot/SConscript'])
# Build desktop-only tools
if GetOption('extras') and arch != "comma_arm64":
SConscript([
+2 -1
View File
@@ -4,7 +4,7 @@
A supported vehicle is one that just works when you install a comma device. All supported cars provide a better experience than any stock system. Supported vehicles reference the US market unless otherwise specified.
# 358 Supported Cars
# 359 Supported Cars
|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|<a href="##"><img width=2000></a>Hardware Needed<br>&nbsp;|Video|Setup Video|
|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
@@ -161,6 +161,7 @@ A supported vehicle is one that just works when you install a comma device. All
|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai L connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2021">Buy Here</a></sub></details>|||
|Hyundai|Tucson 2022|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2022">Buy Here</a></sub></details>|||
|Hyundai|Tucson 2023-24|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson 2023-24">Buy Here</a></sub></details>|||
|Hyundai|Tucson (without HDA II) 2025-26|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson (without HDA II) 2025-26">Buy Here</a></sub></details>|||
|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai L connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Diesel 2019">Buy Here</a></sub></details>|||
|Hyundai|Tucson Hybrid 2022-24|All|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Hybrid 2022-24">Buy Here</a></sub></details>|||
|Hyundai|Tucson Hybrid (without HDA II) 2025-26|Smart Cruise Control (SCC)|openpilot available[<sup>1</sup>](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|<details><summary>Parts</summary><sub>- 1 Hyundai N connector<br>- 1 OBD-C cable (2 ft)<br>- 1 comma four<br>- 1 comma power v3<br>- 1 harness box<br>- 1 mount<br><a href="https://comma.ai/shop/comma-3x?harness=Hyundai Tucson Hybrid (without HDA II) 2025-26">Buy Here</a></sub></details>|||
+1 -1
View File
@@ -16,7 +16,7 @@ export VECLIB_MAXIMUM_THREADS=1
export QCOM_PRIORITY=12
if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="19.9"
export AGNOS_VERSION="19.9-sunnypilot.2-dae64af"
fi
export STAGING_ROOT="/data/safe_staging"
+10 -1
View File
@@ -483,7 +483,16 @@ struct ModelDataV2SP @0xa1680744031fdb2d {
}
}
struct CustomReserved10 @0xcb9fd56c7057593a {
struct GpsLocationSP @0xcb9fd56c7057593a {
latitude @0 :Float64;
longitude @1 :Float64;
speed @2 :Float32;
bearingDeg @3 :Float32;
horizontalAccuracy @4 :Float32; # m
bearingAccuracyDeg @5 :Float32;
hasFix @6 :Bool;
gpsOK @7 :Bool; # a raw fix arrived in the last 2 s
fused @8 :Bool; # false while passing the raw fix through
}
struct CustomReserved11 @0xc2243c65e0340384 {
+2 -2
View File
@@ -2648,7 +2648,7 @@ struct Event {
carStateSP @114 :Custom.CarStateSP;
liveMapDataSP @115 :Custom.LiveMapDataSP;
modelDataV2SP @116 :Custom.ModelDataV2SP;
customReserved10 @136 :Custom.CustomReserved10;
gpsLocationSP @136 :Custom.GpsLocationSP;
customReserved11 @137 :Custom.CustomReserved11;
customReserved12 @138 :Custom.CustomReserved12;
customReserved13 @139 :Custom.CustomReserved13;
@@ -2701,7 +2701,7 @@ struct Event {
lateralPlanDEPRECATED @64 :LateralPlan;
navModelDEPRECATED @104 :Deprecated.NavModelData;
uiPlanDEPRECATED @106 :UiPlan;
liveLocationKalman @72 :LiveLocationKalman;
liveLocationKalmanDEPRECATED @72 :LiveLocationKalman;
liveTracksDEPRECATED @16 :List(Deprecated.LiveTracksDEPRECATED);
onroadEventsDEPRECATED @68: List(Car.OnroadEventDEPRECATED);
gyroscope2DEPRECATED @100 :SensorEventData;
+1 -1
View File
@@ -95,7 +95,7 @@ _services: dict[str, tuple] = {
"carStateSP": (True, 100., 10),
"liveMapDataSP": (True, 1., 1),
"modelDataV2SP": (True, 20., 10, QueueSize.BIG),
"liveLocationKalman": (True, 20.),
"gpsLocationSP": (True, 20., 20),
# debug
"uiDebug": (True, 0., 1),
+16 -16
View File
@@ -1,7 +1,7 @@
[
{
"name": "xbl",
"url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
"size": 3282256,
@@ -12,7 +12,7 @@
},
{
"name": "xbl_config",
"url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
"size": 98124,
@@ -23,7 +23,7 @@
},
{
"name": "abl",
"url": "https://commadist.azureedge.net/agnosupdate/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
"size": 274432,
@@ -34,7 +34,7 @@
},
{
"name": "aop",
"url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
"size": 184364,
@@ -45,7 +45,7 @@
},
{
"name": "devcfg",
"url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
"size": 40336,
@@ -56,28 +56,28 @@
},
{
"name": "boot",
"url": "https://commadist.azureedge.net/agnosupdate/boot-b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615.img.xz",
"hash": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
"hash_raw": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
"size": 46962688,
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/boot-6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b.img.xz",
"hash": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
"hash_raw": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
"size": 47859712,
"sparse": false,
"full_check": true,
"has_ab": true,
"ondevice_hash": "3ef4769bb1cc73bfc31f96f073b46af42dcc0bad4ab2dde32d11929745d0cd28"
"ondevice_hash": "71f49de9dcb8b8181a47695a4390d5a934ac59e92ce398bbfe5767ce01f78e4f"
},
{
"name": "system",
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img.xz",
"hash": "9aebca09b9d142718e71efbfe44b723010eec6e70067c043c63186067291739d",
"hash_raw": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img.xz",
"hash": "b959d05e5000ba590b0d47f8394a4024d3d5d348eadb8cc85f4aa7c15f8b7c20",
"hash_raw": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
"size": 4718592000,
"sparse": true,
"full_check": false,
"has_ab": true,
"ondevice_hash": "270b76c5c5568828e3883390b83ea445425a104dd42119d68f06093ce6b6fcef",
"ondevice_hash": "872ca1b96c0d26d8fdaa74ab019b8c58de36c66afb4fc765681d265d17e80e9d",
"alt": {
"hash": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img",
"hash": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img",
"size": 4718592000
}
}
+8 -1
View File
@@ -156,6 +156,8 @@ 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}},
@@ -178,7 +180,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"InteractivityTimeout", {PERSISTENT | BACKUP, INT, "0"}},
{"IsDevelopmentBranch", {CLEAR_ON_MANAGER_START, BOOL}},
{"IsReleaseSpBranch", {CLEAR_ON_MANAGER_START, BOOL}},
{"LastGPSPositionLLK", {PERSISTENT, STRING}},
{"LastGPSPositionFused", {PERSISTENT, STRING}},
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
@@ -232,6 +234,11 @@ 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
@@ -101,6 +101,8 @@ 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):
@@ -0,0 +1,91 @@
"""
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)
@@ -0,0 +1,205 @@
"""
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 pyray 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,7 +149,8 @@ class DeviceLayoutSP(DeviceLayout):
def _do_reset(result: int):
if result == DialogResult.CONFIRM:
for _key in ui_state.params.all_keys():
ui_state.params.remove(_key)
if not _key.startswith("SunnylinkLocal"):
ui_state.params.remove(_key)
HARDWARE.reboot()
def _second_confirm(result: int):
@@ -11,6 +11,7 @@ import pyray 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
@@ -50,6 +51,7 @@ OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignm
"NAVIGATION",
"TRIPS",
"VEHICLE",
"BLUETOOTH",
],
start=0,
)
@@ -111,6 +113,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
self._panels = {
OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
@@ -11,6 +11,7 @@ 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
@@ -23,6 +24,11 @@ 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
@@ -62,6 +68,19 @@ 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"):
@@ -0,0 +1,86 @@
"""
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))
@@ -0,0 +1,202 @@
"""
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 pyray 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,19 +5,38 @@ 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 pyray 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,6 +11,7 @@ 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
@@ -50,6 +51,12 @@ 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))
@@ -68,6 +75,7 @@ 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)
-2
View File
@@ -1,2 +0,0 @@
SConscript(['common/transformations/SConscript'])
SConscript(['selfdrive/locationd/SConscript'])
@@ -1,4 +0,0 @@
Import('env')
transformations = env.Library('transformations', ['orientation.cc', 'coordinates.cc'])
Export('transformations')
@@ -1,100 +0,0 @@
#define _USE_MATH_DEFINES
#include "sunnypilot/common/transformations/coordinates.hpp"
#include <iostream>
#include <cmath>
#include <eigen3/Eigen/Dense>
double a = 6378137; // lgtm [cpp/short-global-name]
double b = 6356752.3142; // lgtm [cpp/short-global-name]
double esq = 6.69437999014 * 0.001; // lgtm [cpp/short-global-name]
double e1sq = 6.73949674228 * 0.001;
static Geodetic to_degrees(Geodetic geodetic){
geodetic.lat = RAD2DEG(geodetic.lat);
geodetic.lon = RAD2DEG(geodetic.lon);
return geodetic;
}
static Geodetic to_radians(Geodetic geodetic){
geodetic.lat = DEG2RAD(geodetic.lat);
geodetic.lon = DEG2RAD(geodetic.lon);
return geodetic;
}
ECEF geodetic2ecef(const Geodetic &geodetic) {
auto g = to_radians(geodetic);
double xi = sqrt(1.0 - esq * pow(sin(g.lat), 2));
double x = (a / xi + g.alt) * cos(g.lat) * cos(g.lon);
double y = (a / xi + g.alt) * cos(g.lat) * sin(g.lon);
double z = (a / xi * (1.0 - esq) + g.alt) * sin(g.lat);
return {x, y, z};
}
Geodetic ecef2geodetic(const ECEF &e) {
// Convert from ECEF to geodetic using Ferrari's methods
// https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#Ferrari.27s_solution
double x = e.x;
double y = e.y;
double z = e.z;
double r = sqrt(x * x + y * y);
double Esq = a * a - b * b;
double F = 54 * b * b * z * z;
double G = r * r + (1 - esq) * z * z - esq * Esq;
double C = (esq * esq * F * r * r) / (pow(G, 3));
double S = cbrt(1 + C + sqrt(C * C + 2 * C));
double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G);
double Q = sqrt(1 + 2 * esq * esq * P);
double r_0 = -(P * esq * r) / (1 + Q) + sqrt(0.5 * a * a*(1 + 1.0 / Q) - P * (1 - esq) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r);
double U = sqrt(pow((r - esq * r_0), 2) + z * z);
double V = sqrt(pow((r - esq * r_0), 2) + (1 - esq) * z * z);
double Z_0 = b * b * z / (a * V);
double h = U * (1 - b * b / (a * V));
double lat = atan((z + e1sq * Z_0) / r);
double lon = atan2(y, x);
return to_degrees({lat, lon, h});
}
LocalCoord::LocalCoord(const Geodetic &geodetic, const ECEF &e) {
init_ecef << e.x, e.y, e.z;
auto g = to_radians(geodetic);
ned2ecef_matrix <<
-sin(g.lat)*cos(g.lon), -sin(g.lon), -cos(g.lat)*cos(g.lon),
-sin(g.lat)*sin(g.lon), cos(g.lon), -cos(g.lat)*sin(g.lon),
cos(g.lat), 0, -sin(g.lat);
ecef2ned_matrix = ned2ecef_matrix.transpose();
}
NED LocalCoord::ecef2ned(const ECEF &e) {
Eigen::Vector3d ecef;
ecef << e.x, e.y, e.z;
Eigen::Vector3d ned = (ecef2ned_matrix * (ecef - init_ecef));
return {ned[0], ned[1], ned[2]};
}
ECEF LocalCoord::ned2ecef(const NED &n) {
Eigen::Vector3d ned;
ned << n.n, n.e, n.d;
Eigen::Vector3d ecef = (ned2ecef_matrix * ned) + init_ecef;
return {ecef[0], ecef[1], ecef[2]};
}
NED LocalCoord::geodetic2ned(const Geodetic &g) {
ECEF e = ::geodetic2ecef(g);
return ecef2ned(e);
}
Geodetic LocalCoord::ned2geodetic(const NED &n) {
ECEF e = ned2ecef(n);
return ::ecef2geodetic(e);
}
@@ -1,43 +0,0 @@
#pragma once
#include <eigen3/Eigen/Dense>
#define DEG2RAD(x) ((x) * M_PI / 180.0)
#define RAD2DEG(x) ((x) * 180.0 / M_PI)
struct ECEF {
double x, y, z;
Eigen::Vector3d to_vector() const {
return Eigen::Vector3d(x, y, z);
}
};
struct NED {
double n, e, d;
Eigen::Vector3d to_vector() const {
return Eigen::Vector3d(n, e, d);
}
};
struct Geodetic {
double lat, lon, alt;
bool radians=false;
};
ECEF geodetic2ecef(const Geodetic &g);
Geodetic ecef2geodetic(const ECEF &e);
class LocalCoord {
public:
Eigen::Matrix3d ned2ecef_matrix;
Eigen::Matrix3d ecef2ned_matrix;
Eigen::Vector3d init_ecef;
LocalCoord(const Geodetic &g, const ECEF &e);
LocalCoord(const Geodetic &g) : LocalCoord(g, ::geodetic2ecef(g)) {}
LocalCoord(const ECEF &e) : LocalCoord(::ecef2geodetic(e), e) {}
NED ecef2ned(const ECEF &e);
ECEF ned2ecef(const NED &n);
NED geodetic2ned(const Geodetic &g);
Geodetic ned2geodetic(const NED &n);
};
@@ -1,143 +0,0 @@
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <eigen3/Eigen/Dense>
#include "sunnypilot/common/transformations/orientation.hpp"
#include "sunnypilot/common/transformations/coordinates.hpp"
Eigen::Quaterniond ensure_unique(const Eigen::Quaterniond &quat) {
if (quat.w() > 0){
return quat;
} else {
return Eigen::Quaterniond(-quat.w(), -quat.x(), -quat.y(), -quat.z());
}
}
Eigen::Quaterniond euler2quat(const Eigen::Vector3d &euler) {
Eigen::Quaterniond q;
q = Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitX());
return ensure_unique(q);
}
Eigen::Vector3d quat2euler(const Eigen::Quaterniond &quat) {
// TODO: switch to eigen implementation if the range of the Euler angles doesn't matter anymore
// Eigen::Vector3d euler = quat.toRotationMatrix().eulerAngles(2, 1, 0);
// return {euler(2), euler(1), euler(0)};
double gamma = atan2(2 * (quat.w() * quat.x() + quat.y() * quat.z()), 1 - 2 * (quat.x()*quat.x() + quat.y()*quat.y()));
double asin_arg_clipped = std::clamp(2 * (quat.w() * quat.y() - quat.z() * quat.x()), -1.0, 1.0);
double theta = asin(asin_arg_clipped);
double psi = atan2(2 * (quat.w() * quat.z() + quat.x() * quat.y()), 1 - 2 * (quat.y()*quat.y() + quat.z()*quat.z()));
return {gamma, theta, psi};
}
Eigen::Matrix3d quat2rot(const Eigen::Quaterniond &quat) {
return quat.toRotationMatrix();
}
Eigen::Quaterniond rot2quat(const Eigen::Matrix3d &rot) {
return ensure_unique(Eigen::Quaterniond(rot));
}
Eigen::Matrix3d euler2rot(const Eigen::Vector3d &euler) {
return quat2rot(euler2quat(euler));
}
Eigen::Vector3d rot2euler(const Eigen::Matrix3d &rot) {
return quat2euler(rot2quat(rot));
}
Eigen::Matrix3d rot_matrix(double roll, double pitch, double yaw) {
return euler2rot({roll, pitch, yaw});
}
Eigen::Matrix3d rot(const Eigen::Vector3d &axis, double angle) {
Eigen::Quaterniond q;
q = Eigen::AngleAxisd(angle, axis);
return q.toRotationMatrix();
}
Eigen::Vector3d ecef_euler_from_ned(const ECEF &ecef_init, const Eigen::Vector3d &ned_pose) {
/*
Using Rotations to Build Aerospace Coordinate Systems
Don Koks
https://apps.dtic.mil/dtic/tr/fulltext/u2/a484864.pdf
*/
LocalCoord converter = LocalCoord(ecef_init);
Eigen::Vector3d zero = ecef_init.to_vector();
Eigen::Vector3d x0 = converter.ned2ecef({1, 0, 0}).to_vector() - zero;
Eigen::Vector3d y0 = converter.ned2ecef({0, 1, 0}).to_vector() - zero;
Eigen::Vector3d z0 = converter.ned2ecef({0, 0, 1}).to_vector() - zero;
Eigen::Vector3d x1 = rot(z0, ned_pose(2)) * x0;
Eigen::Vector3d y1 = rot(z0, ned_pose(2)) * y0;
Eigen::Vector3d z1 = rot(z0, ned_pose(2)) * z0;
Eigen::Vector3d x2 = rot(y1, ned_pose(1)) * x1;
Eigen::Vector3d y2 = rot(y1, ned_pose(1)) * y1;
Eigen::Vector3d z2 = rot(y1, ned_pose(1)) * z1;
Eigen::Vector3d x3 = rot(x2, ned_pose(0)) * x2;
Eigen::Vector3d y3 = rot(x2, ned_pose(0)) * y2;
x0 = Eigen::Vector3d(1, 0, 0);
y0 = Eigen::Vector3d(0, 1, 0);
z0 = Eigen::Vector3d(0, 0, 1);
double psi = atan2(x3.dot(y0), x3.dot(x0));
double theta = atan2(-x3.dot(z0), sqrt(pow(x3.dot(x0), 2) + pow(x3.dot(y0), 2)));
y2 = rot(z0, psi) * y0;
z2 = rot(y2, theta) * z0;
double phi = atan2(y3.dot(z2), y3.dot(y2));
return {phi, theta, psi};
}
Eigen::Vector3d ned_euler_from_ecef(const ECEF &ecef_init, const Eigen::Vector3d &ecef_pose) {
/*
Using Rotations to Build Aerospace Coordinate Systems
Don Koks
https://apps.dtic.mil/dtic/tr/fulltext/u2/a484864.pdf
*/
LocalCoord converter = LocalCoord(ecef_init);
Eigen::Vector3d x0 = Eigen::Vector3d(1, 0, 0);
Eigen::Vector3d y0 = Eigen::Vector3d(0, 1, 0);
Eigen::Vector3d z0 = Eigen::Vector3d(0, 0, 1);
Eigen::Vector3d x1 = rot(z0, ecef_pose(2)) * x0;
Eigen::Vector3d y1 = rot(z0, ecef_pose(2)) * y0;
Eigen::Vector3d z1 = rot(z0, ecef_pose(2)) * z0;
Eigen::Vector3d x2 = rot(y1, ecef_pose(1)) * x1;
Eigen::Vector3d y2 = rot(y1, ecef_pose(1)) * y1;
Eigen::Vector3d z2 = rot(y1, ecef_pose(1)) * z1;
Eigen::Vector3d x3 = rot(x2, ecef_pose(0)) * x2;
Eigen::Vector3d y3 = rot(x2, ecef_pose(0)) * y2;
Eigen::Vector3d zero = ecef_init.to_vector();
x0 = converter.ned2ecef({1, 0, 0}).to_vector() - zero;
y0 = converter.ned2ecef({0, 1, 0}).to_vector() - zero;
z0 = converter.ned2ecef({0, 0, 1}).to_vector() - zero;
double psi = atan2(x3.dot(y0), x3.dot(x0));
double theta = atan2(-x3.dot(z0), sqrt(pow(x3.dot(x0), 2) + pow(x3.dot(y0), 2)));
y2 = rot(z0, psi) * y0;
z2 = rot(y2, theta) * z0;
double phi = atan2(y3.dot(z2), y3.dot(y2));
return {phi, theta, psi};
}
@@ -1,17 +0,0 @@
#pragma once
#include <eigen3/Eigen/Dense>
#include "sunnypilot/common/transformations/coordinates.hpp"
Eigen::Quaterniond ensure_unique(const Eigen::Quaterniond &quat);
Eigen::Quaterniond euler2quat(const Eigen::Vector3d &euler);
Eigen::Vector3d quat2euler(const Eigen::Quaterniond &quat);
Eigen::Matrix3d quat2rot(const Eigen::Quaterniond &quat);
Eigen::Quaterniond rot2quat(const Eigen::Matrix3d &rot);
Eigen::Matrix3d euler2rot(const Eigen::Vector3d &euler);
Eigen::Vector3d rot2euler(const Eigen::Matrix3d &rot);
Eigen::Matrix3d rot_matrix(double roll, double pitch, double yaw);
Eigen::Matrix3d rot(const Eigen::Vector3d &axis, double angle);
Eigen::Vector3d ecef_euler_from_ned(const ECEF &ecef_init, const Eigen::Vector3d &ned_pose);
Eigen::Vector3d ned_euler_from_ecef(const ECEF &ecef_init, const Eigen::Vector3d &ecef_pose);
@@ -19,12 +19,12 @@ class BaseMapData(ABC):
def __init__(self):
self.params = Params()
self.sm = messaging.SubMaster(['liveLocationKalman'])
self.sm = messaging.SubMaster(['gpsLocationSP'])
self.pm = messaging.PubMaster(['liveMapDataSP'])
self.localizer_valid = False
self.last_bearing = None
self.last_position = coordinate_from_param("LastGPSPositionLLK", self.params)
self.last_position = coordinate_from_param("LastGPSPositionFused", self.params)
@abstractmethod
def update_location(self) -> None:
@@ -47,7 +47,7 @@ class BaseMapData(ABC):
next_speed_limit, next_speed_limit_distance = self.get_next_speed_limit_and_distance()
mapd_sp_send = messaging.new_message('liveMapDataSP')
mapd_sp_send.valid = self.sm['liveLocationKalman'].gpsOK
mapd_sp_send.valid = self.sm['gpsLocationSP'].gpsOK
live_map_data = mapd_sp_send.liveMapDataSP
live_map_data.speedLimitValid = bool(MAX_SPEED_LIMIT > speed_limit > 0)
@@ -5,10 +5,8 @@ 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 math
import platform
from openpilot.cereal import log
from openpilot.common.params import Params
from openpilot.sunnypilot.mapd.live_map_data.base_map_data import BaseMapData
from openpilot.sunnypilot.navd.helpers import Coordinate
@@ -20,12 +18,12 @@ class OsmMapData(BaseMapData):
self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else self.params
def update_location(self) -> None:
location = self.sm['liveLocationKalman']
self.localizer_valid = (location.status == log.LiveLocationKalman.Status.valid) and location.positionGeodetic.valid
location = self.sm['gpsLocationSP']
self.localizer_valid = self.sm.valid['gpsLocationSP'] and location.hasFix
if self.localizer_valid:
self.last_bearing = math.degrees(location.calibratedOrientationNED.value[2])
self.last_position = Coordinate(location.positionGeodetic.value[0], location.positionGeodetic.value[1])
self.last_bearing = location.bearingDeg
self.last_position = Coordinate(location.latitude, location.longitude)
if self.last_position is None:
return
@@ -5,11 +5,9 @@ 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 math
import platform
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log
from openpilot.common.params import Params
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot.mapd.live_map_data.osm_map_data import OsmMapData
@@ -20,28 +18,26 @@ class TestOsmMapData(OpenpilotTestCase):
LATITUDE = 32.875134
LONGITUDE = -117.209777
ALTITUDE = 42.0
BEARING = 90.0
def setup_method(self):
self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else Params()
self.mem_params.remove("LastGPSPosition")
self.map_data = OsmMapData()
self.pm = messaging.PubMaster(['liveLocationKalman'])
self.pm = messaging.PubMaster(['gpsLocationSP'])
def location_message(self, status: log.LiveLocationKalman.Status, position_valid: bool):
msg = messaging.new_message('liveLocationKalman', valid=True)
location = msg.liveLocationKalman
location.status = status
location.positionGeodetic = {'value': [self.LATITUDE, self.LONGITUDE, self.ALTITUDE], 'valid': position_valid}
location.calibratedOrientationNED = {'value': [0.0, 0.0, math.radians(self.BEARING)], 'valid': True}
def location_message(self, has_fix: bool):
msg = messaging.new_message('gpsLocationSP', valid=has_fix)
location = msg.gpsLocationSP
location.hasFix = has_fix
location.latitude, location.longitude, location.bearingDeg = self.LATITUDE, self.LONGITUDE, self.BEARING
return msg
def send_location(self, status: log.LiveLocationKalman.Status, position_valid: bool) -> None:
def send_location(self, has_fix: bool) -> None:
# the first exchange synchronizes the PUB/SUB connection, the second one is actually received
self.pm.send('liveLocationKalman', self.location_message(status, position_valid))
self.pm.send('gpsLocationSP', self.location_message(has_fix))
self.map_data.sm.update(1000)
self.pm.send('liveLocationKalman', self.location_message(status, position_valid))
self.pm.send('gpsLocationSP', self.location_message(has_fix))
self.map_data.sm.update(1000)
def read_position(self) -> dict:
@@ -50,7 +46,7 @@ class TestOsmMapData(OpenpilotTestCase):
return json.loads(value)
def test_writes_position_for_mapd(self):
self.send_location(log.LiveLocationKalman.Status.valid, True)
self.send_location(True)
self.map_data.tick()
position = self.read_position()
@@ -59,10 +55,10 @@ class TestOsmMapData(OpenpilotTestCase):
self.assertAlmostEqual(position['bearing'], self.BEARING, delta=1e-6)
def test_invalid_localizer_keeps_last_known_position(self):
self.send_location(log.LiveLocationKalman.Status.valid, True)
self.send_location(True)
self.map_data.tick()
self.send_location(log.LiveLocationKalman.Status.uninitialized, False)
self.send_location(False)
self.map_data.tick()
position = self.read_position()
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f7df0485754b51731fc60b4cb324d75c7058c0e20c7c979ac84aa5273e29aa83
size 5956
@@ -1,3 +0,0 @@
params_learner
paramsd
locationd
@@ -1,30 +0,0 @@
Import('env', 'arch', 'common', 'messaging', 'rednose', 'transformations')
loc_libs = [messaging, common, 'pthread', 'dl']
# build ekf models
rednose_gen_dir = 'models/generated'
rednose_gen_deps = [
"models/constants.py",
]
live_ekf = env.RednoseCompileFilter(
target='live',
filter_gen_script='models/live_kf.py',
output_dir=rednose_gen_dir,
extra_gen_artifacts=['live_kf_constants.h'],
gen_script_deps=rednose_gen_deps,
)
# locationd build
locationd_sources = ["locationd.cc", "models/live_kf.cc"]
lenv = env.Clone()
# ekf filter libraries need to be linked, even if no symbols are used
if arch != "Darwin":
lenv["LINKFLAGS"] += ["-Wl,--no-as-needed"]
lenv["LIBPATH"].append(Dir(rednose_gen_dir).abspath)
lenv["RPATH"].append(Dir(rednose_gen_dir).abspath)
locationd = lenv.Program("locationd", locationd_sources, LIBS=["live", "ekf_sym"] + loc_libs + transformations)
lenv.Depends(locationd, rednose)
lenv.Depends(locationd, live_ekf)
@@ -0,0 +1,181 @@
"""
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 math
import time
from collections import deque
import numpy as np
import openpilot.cereal.messaging as messaging
from openpilot.common.gps import get_gps_location_service
from openpilot.common.params import Params
from openpilot.common.transformations.orientation import rot_from_euler
EARTH_RADIUS = 6378137.0
GPS_LATENCY = {'gpsLocation': 0.630, 'gpsLocationExternal': 0.095} # s, empirical fix latency per receiver
RESET_DISTANCE = 100.0 # m
MAX_REJECTS = 5
MAX_POS_STD = 50.0 # m
MIN_BEARING_SPEED = 5.0 # m/s
MAX_BEARING_ACCURACY = 10.0 # deg
GPS_TIMEOUT = 2.0 # s
SEED_INTERVAL = 60.0 # s
def wrap(a: float) -> float:
return (a + math.pi) % (2 * math.pi) - math.pi
class GpsFuser:
def __init__(self):
self.t: float | None = None
self.lat = self.lon = self.heading = math.nan
self.pos_var = self.heading_var = math.inf
self.history: deque = deque(maxlen=40)
self.rejects = 0
@property
def initialized(self) -> bool:
return math.isfinite(self.lat)
@property
def valid(self) -> bool:
return self.initialized and math.isfinite(self.heading) and self.pos_var < MAX_POS_STD ** 2
def _move(self, north: float, east: float) -> None:
self.lat += math.degrees(north / EARTH_RADIUS)
self.lon += math.degrees(east / (EARTH_RADIUS * math.cos(math.radians(self.lat))))
@staticmethod
def _offset(lat: float, lon: float, ref_lat: float, ref_lon: float) -> tuple[float, float]:
north = math.radians(lat - ref_lat) * EARTH_RADIUS
east = math.radians(lon - ref_lon) * EARTH_RADIUS * math.cos(math.radians(ref_lat))
return north, east
def _state_at(self, t: float) -> tuple[float, float, float]:
for ht, lat, lon, heading in reversed(self.history):
if ht <= t:
return lat, lon, heading
return self.lat, self.lon, self.heading
def predict(self, t: float, speed: float, yaw_rate: float) -> None:
dt = 0.0 if self.t is None else t - self.t
self.t = t
if not 0.0 < dt < 1.0 or not self.initialized:
return
if math.isfinite(self.heading):
self.heading = (self.heading + yaw_rate * dt) % (2 * math.pi)
self._move(speed * dt * math.cos(self.heading), speed * dt * math.sin(self.heading))
# dead reckoning error grows with distance driven (speed scale and heading error), not as a random walk
drift = (0.03 + math.sqrt(min(self.heading_var, 1.0))) * abs(speed) * dt
self.pos_var = (math.sqrt(self.pos_var) + drift) ** 2 + 0.01 * dt
self.heading_var += 1e-5 * dt
self.history.append((t, self.lat, self.lon, self.heading))
def update_gps(self, t: float, gps, latency: float) -> None:
# qcom reports no horizontal accuracy
accuracy = gps.horizontalAccuracy if gps.horizontalAccuracy > 0 else math.sqrt(3) * gps.verticalAccuracy
if not gps.hasFix or not 0 < accuracy < 1500 or gps.speedAccuracy <= 0:
return
if abs(gps.latitude) > 90 or abs(gps.longitude) > 180:
return
then_lat, then_lon, then_heading = self._state_at(t - latency)
moved = self._offset(self.lat, self.lon, then_lat, then_lon) if self.initialized else (0.0, 0.0)
bearing = math.radians(gps.bearingDeg)
bearing_ok = gps.speed > MIN_BEARING_SPEED and 0 < gps.bearingAccuracyDeg < MAX_BEARING_ACCURACY
pos_r = accuracy ** 2
innov = self._offset(gps.latitude, gps.longitude, then_lat, then_lon) if self.initialized else (math.inf, math.inf)
dist = math.hypot(*innov)
if not self.initialized or dist > RESET_DISTANCE or self.rejects >= MAX_REJECTS:
self.lat, self.lon = gps.latitude, gps.longitude
self._move(*moved)
self.pos_var = pos_r
self.rejects = 0
self.history.clear()
if bearing_ok:
self.heading, self.heading_var = bearing, math.radians(gps.bearingAccuracyDeg) ** 2
return
s = self.pos_var + pos_r
if dist ** 2 > 9.0 * s and dist > 10.0:
self.rejects += 1
return
self.rejects = 0
k = self.pos_var / s
lat0, lon0 = self.lat, self.lon
self._move(k * innov[0], k * innov[1])
dlat, dlon = self.lat - lat0, self.lon - lon0
self.history = deque(((ht, lat + dlat, lon + dlon, h) for ht, lat, lon, h in self.history), maxlen=self.history.maxlen)
self.pos_var *= 1 - k
if bearing_ok:
head_r = math.radians(gps.bearingAccuracyDeg) ** 2
if not math.isfinite(self.heading):
self.heading, self.heading_var = bearing, head_r
else:
kh = self.heading_var / (self.heading_var + head_r)
self.heading = (self.heading + kh * wrap(bearing - then_heading)) % (2 * math.pi)
self.heading_var *= 1 - kh
def main():
params = Params()
gps_service = get_gps_location_service(params)
latency = GPS_LATENCY[gps_service]
sm = messaging.SubMaster(['deviceMotion', 'carState', 'extrinsicsCalibration', gps_service], poll='deviceMotion')
pm = messaging.PubMaster(['gpsLocationSP'])
fuser = GpsFuser()
calib_from_device = np.eye(3)
last_seed = 0.0
while True:
sm.update()
t = sm.logMonoTime['deviceMotion'] * 1e-9
rpy = list(sm['extrinsicsCalibration'].rpyCalib)
if sm.updated['extrinsicsCalibration'] and len(rpy) == 3:
calib_from_device = rot_from_euler(rpy).T
gps = sm[gps_service]
gps_t = sm.logMonoTime[gps_service] * 1e-9
if sm.updated[gps_service] and sm.valid[gps_service]:
fuser.update_gps(gps_t, gps, latency)
if sm.valid['deviceMotion']:
w = sm['deviceMotion'].angularVelocityDevice
yaw_rate = float((calib_from_device @ np.array([w.x, w.y, w.z]))[2])
fuser.predict(t, sm['carState'].vEgo, yaw_rate)
gps_ok = gps.hasFix and t - gps_t < GPS_TIMEOUT
msg = messaging.new_message('gpsLocationSP', valid=fuser.valid or gps_ok)
out = msg.gpsLocationSP
out.gpsOK = gps_ok
out.fused = fuser.valid
if fuser.valid:
out.hasFix = True
out.latitude, out.longitude = fuser.lat, fuser.lon
out.bearingDeg = math.degrees(fuser.heading) % 360
out.bearingAccuracyDeg = math.degrees(math.sqrt(fuser.heading_var))
out.horizontalAccuracy = math.sqrt(fuser.pos_var)
out.speed = sm['carState'].vEgo
elif gps_ok:
out.hasFix = True
out.latitude, out.longitude = gps.latitude, gps.longitude
out.bearingDeg, out.bearingAccuracyDeg = gps.bearingDeg, gps.bearingAccuracyDeg
out.horizontalAccuracy, out.speed = gps.horizontalAccuracy, gps.speed
pm.send('gpsLocationSP', msg)
if fuser.valid and time.monotonic() - last_seed > SEED_INTERVAL:
params.put("LastGPSPositionFused", json.dumps({"latitude": fuser.lat, "longitude": fuser.lon}))
last_seed = time.monotonic()
if __name__ == "__main__":
main()
@@ -1,750 +0,0 @@
#include "sunnypilot/selfdrive/locationd/locationd.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace EKFS;
using namespace Eigen;
ExitHandler do_exit;
const double ACCEL_SANITY_CHECK = 100.0; // m/s^2
const double ROTATION_SANITY_CHECK = 10.0; // rad/s
const double TRANS_SANITY_CHECK = 200.0; // m/s
const double CALIB_RPY_SANITY_CHECK = 0.5; // rad (+- 30 deg)
const double ALTITUDE_SANITY_CHECK = 10000; // m
const double MIN_STD_SANITY_CHECK = 1e-5; // m or rad
const double VALID_TIME_SINCE_RESET = 1.0; // s
const double VALID_POS_STD = 50.0; // m
const double MAX_RESET_TRACKER = 5.0;
const double SANE_GPS_UNCERTAINTY = 1500.0; // m
const double INPUT_INVALID_THRESHOLD = 0.5; // same as reset tracker
const double RESET_TRACKER_DECAY = 0.99995;
const double DECAY = 0.9993; // ~10 secs to resume after a bad input
const double MAX_FILTER_REWIND_TIME = 0.8; // s
const double YAWRATE_CROSS_ERR_CHECK_FACTOR = 30;
// TODO: GPS sensor time offsets are empirically calculated
// They should be replaced with synced time from a real clock
const double GPS_QUECTEL_SENSOR_TIME_OFFSET = 0.630; // s
const double GPS_UBLOX_SENSOR_TIME_OFFSET = 0.095; // s
const float GPS_POS_STD_THRESHOLD = 50.0;
const float GPS_VEL_STD_THRESHOLD = 5.0;
const float GPS_POS_ERROR_RESET_THRESHOLD = 300.0;
const float GPS_POS_STD_RESET_THRESHOLD = 2.0;
const float GPS_VEL_STD_RESET_THRESHOLD = 0.5;
const float GPS_ORIENTATION_ERROR_RESET_THRESHOLD = 1.0;
const int GPS_ORIENTATION_ERROR_RESET_CNT = 3;
const bool DEBUG = getenv("DEBUG") != nullptr && std::string(getenv("DEBUG")) != "0";
static VectorXd floatlist2vector(const capnp::List<float, capnp::Kind::PRIMITIVE>::Reader& floatlist) {
VectorXd res(floatlist.size());
for (int i = 0; i < floatlist.size(); i++) {
res[i] = floatlist[i];
}
return res;
}
static Vector4d quat2vector(const Quaterniond& quat) {
return Vector4d(quat.w(), quat.x(), quat.y(), quat.z());
}
static Quaterniond vector2quat(const VectorXd& vec) {
return Quaterniond(vec(0), vec(1), vec(2), vec(3));
}
static void init_measurement(cereal::LiveLocationKalman::Measurement::Builder meas, const VectorXd& val, const VectorXd& std, bool valid) {
meas.setValue(kj::arrayPtr(val.data(), val.size()));
meas.setStd(kj::arrayPtr(std.data(), std.size()));
meas.setValid(valid);
}
static MatrixXdr rotate_cov(const MatrixXdr& rot_matrix, const MatrixXdr& cov_in) {
// To rotate a covariance matrix, the cov matrix needs to multiplied left and right by the transform matrix
return ((rot_matrix * cov_in) * rot_matrix.transpose());
}
static VectorXd rotate_std(const MatrixXdr& rot_matrix, const VectorXd& std_in) {
// Stds cannot be rotated like values, only covariances can be rotated
return rotate_cov(rot_matrix, std_in.array().square().matrix().asDiagonal()).diagonal().array().sqrt();
}
Localizer::Localizer(LocalizerGnssSource gnss_source) {
this->kf = std::make_unique<LiveKalman>();
this->reset_kalman();
this->calib = Vector3d(0.0, 0.0, 0.0);
this->device_from_calib = MatrixXdr::Identity(3, 3);
this->calib_from_device = MatrixXdr::Identity(3, 3);
for (int i = 0; i < POSENET_STD_HIST_HALF * 2; i++) {
this->posenet_stds.push_back(10.0);
}
VectorXd ecef_pos = this->kf->get_x().segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START);
this->converter = std::make_unique<LocalCoord>((ECEF) { .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] });
this->configure_gnss_source(gnss_source);
}
void Localizer::build_live_location(cereal::LiveLocationKalman::Builder& fix) {
VectorXd predicted_state = this->kf->get_x();
MatrixXdr predicted_cov = this->kf->get_P();
VectorXd predicted_std = predicted_cov.diagonal().array().sqrt();
VectorXd fix_ecef = predicted_state.segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START);
ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) };
VectorXd fix_ecef_std = predicted_std.segment<STATE_ECEF_POS_ERR_LEN>(STATE_ECEF_POS_ERR_START);
VectorXd vel_ecef = predicted_state.segment<STATE_ECEF_VELOCITY_LEN>(STATE_ECEF_VELOCITY_START);
VectorXd vel_ecef_std = predicted_std.segment<STATE_ECEF_VELOCITY_ERR_LEN>(STATE_ECEF_VELOCITY_ERR_START);
VectorXd fix_pos_geo_vec = this->get_position_geodetic();
VectorXd orientation_ecef = quat2euler(vector2quat(predicted_state.segment<STATE_ECEF_ORIENTATION_LEN>(STATE_ECEF_ORIENTATION_START)));
VectorXd orientation_ecef_std = predicted_std.segment<STATE_ECEF_ORIENTATION_ERR_LEN>(STATE_ECEF_ORIENTATION_ERR_START);
MatrixXdr orientation_ecef_cov = predicted_cov.block<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START);
MatrixXdr device_from_ecef = euler2rot(orientation_ecef).transpose();
VectorXd calibrated_orientation_ecef = rot2euler((this->calib_from_device * device_from_ecef).transpose());
VectorXd acc_calib = this->calib_from_device * predicted_state.segment<STATE_ACCELERATION_LEN>(STATE_ACCELERATION_START);
MatrixXdr acc_calib_cov = predicted_cov.block<STATE_ACCELERATION_ERR_LEN, STATE_ACCELERATION_ERR_LEN>(STATE_ACCELERATION_ERR_START, STATE_ACCELERATION_ERR_START);
VectorXd acc_calib_std = rotate_cov(this->calib_from_device, acc_calib_cov).diagonal().array().sqrt();
VectorXd ang_vel_calib = this->calib_from_device * predicted_state.segment<STATE_ANGULAR_VELOCITY_LEN>(STATE_ANGULAR_VELOCITY_START);
MatrixXdr vel_angular_cov = predicted_cov.block<STATE_ANGULAR_VELOCITY_ERR_LEN, STATE_ANGULAR_VELOCITY_ERR_LEN>(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START);
VectorXd ang_vel_calib_std = rotate_cov(this->calib_from_device, vel_angular_cov).diagonal().array().sqrt();
VectorXd vel_device = device_from_ecef * vel_ecef;
VectorXd device_from_ecef_eul = quat2euler(vector2quat(predicted_state.segment<STATE_ECEF_ORIENTATION_LEN>(STATE_ECEF_ORIENTATION_START))).transpose();
MatrixXdr condensed_cov(STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN);
condensed_cov.topLeftCorner<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>() =
predicted_cov.block<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START);
condensed_cov.topRightCorner<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_VELOCITY_ERR_LEN>() =
predicted_cov.block<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_VELOCITY_ERR_LEN>(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_VELOCITY_ERR_START);
condensed_cov.bottomRightCorner<STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_VELOCITY_ERR_LEN>() =
predicted_cov.block<STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_VELOCITY_ERR_LEN>(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START);
condensed_cov.bottomLeftCorner<STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>() =
predicted_cov.block<STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_ORIENTATION_ERR_START);
VectorXd H_input(device_from_ecef_eul.size() + vel_ecef.size());
H_input << device_from_ecef_eul, vel_ecef;
MatrixXdr HH = this->kf->H(H_input);
MatrixXdr vel_device_cov = (HH * condensed_cov) * HH.transpose();
VectorXd vel_device_std = vel_device_cov.diagonal().array().sqrt();
VectorXd vel_calib = this->calib_from_device * vel_device;
VectorXd vel_calib_std = rotate_cov(this->calib_from_device, vel_device_cov).diagonal().array().sqrt();
VectorXd orientation_ned = ned_euler_from_ecef(fix_ecef_ecef, orientation_ecef);
VectorXd orientation_ned_std = rotate_cov(this->converter->ecef2ned_matrix, orientation_ecef_cov).diagonal().array().sqrt();
VectorXd calibrated_orientation_ned = ned_euler_from_ecef(fix_ecef_ecef, calibrated_orientation_ecef);
VectorXd nextfix_ecef = fix_ecef + vel_ecef;
VectorXd ned_vel = this->converter->ecef2ned((ECEF) { .x = nextfix_ecef(0), .y = nextfix_ecef(1), .z = nextfix_ecef(2) }).to_vector() - converter->ecef2ned(fix_ecef_ecef).to_vector();
VectorXd accDevice = predicted_state.segment<STATE_ACCELERATION_LEN>(STATE_ACCELERATION_START);
VectorXd accDeviceErr = predicted_std.segment<STATE_ACCELERATION_ERR_LEN>(STATE_ACCELERATION_ERR_START);
VectorXd angVelocityDevice = predicted_state.segment<STATE_ANGULAR_VELOCITY_LEN>(STATE_ANGULAR_VELOCITY_START);
VectorXd angVelocityDeviceErr = predicted_std.segment<STATE_ANGULAR_VELOCITY_ERR_LEN>(STATE_ANGULAR_VELOCITY_ERR_START);
Vector3d nans = Vector3d(NAN, NAN, NAN);
// TODO fill in NED and Calibrated stds
// write measurements to msg
init_measurement(fix.initPositionGeodetic(), fix_pos_geo_vec, nans, this->gps_mode);
init_measurement(fix.initPositionECEF(), fix_ecef, fix_ecef_std, this->gps_mode);
init_measurement(fix.initVelocityECEF(), vel_ecef, vel_ecef_std, this->gps_mode);
init_measurement(fix.initVelocityNED(), ned_vel, nans, this->gps_mode);
init_measurement(fix.initVelocityDevice(), vel_device, vel_device_std, true);
init_measurement(fix.initAccelerationDevice(), accDevice, accDeviceErr, true);
init_measurement(fix.initOrientationECEF(), orientation_ecef, orientation_ecef_std, this->gps_mode);
init_measurement(fix.initCalibratedOrientationECEF(), calibrated_orientation_ecef, nans, this->calibrated && this->gps_mode);
init_measurement(fix.initOrientationNED(), orientation_ned, orientation_ned_std, this->gps_mode);
init_measurement(fix.initCalibratedOrientationNED(), calibrated_orientation_ned, nans, this->calibrated && this->gps_mode);
init_measurement(fix.initAngularVelocityDevice(), angVelocityDevice, angVelocityDeviceErr, true);
init_measurement(fix.initVelocityCalibrated(), vel_calib, vel_calib_std, this->calibrated);
init_measurement(fix.initAngularVelocityCalibrated(), ang_vel_calib, ang_vel_calib_std, this->calibrated);
init_measurement(fix.initAccelerationCalibrated(), acc_calib, acc_calib_std, this->calibrated);
if (DEBUG) {
init_measurement(fix.initFilterState(), predicted_state, predicted_std, true);
}
double old_mean = 0.0, new_mean = 0.0;
int i = 0;
for (double x : this->posenet_stds) {
if (i < POSENET_STD_HIST_HALF) {
old_mean += x;
} else {
new_mean += x;
}
i++;
}
old_mean /= POSENET_STD_HIST_HALF;
new_mean /= POSENET_STD_HIST_HALF;
// experimentally found these values, no false positives in 20k minutes of driving
bool std_spike = (new_mean / old_mean > 4.0 && new_mean > 7.0);
fix.setPosenetOK(!(std_spike && this->car_speed > 5.0));
fix.setDeviceStable(!this->device_fell);
fix.setExcessiveResets(this->reset_tracker > MAX_RESET_TRACKER);
fix.setTimeToFirstFix(std::isnan(this->ttff) ? -1. : this->ttff);
this->device_fell = false;
//fix.setGpsWeek(this->time.week);
//fix.setGpsTimeOfWeek(this->time.tow);
fix.setUnixTimestampMillis(this->unix_timestamp_millis);
double time_since_reset = this->kf->get_filter_time() - this->last_reset_time;
fix.setTimeSinceReset(time_since_reset);
if (fix_ecef_std.norm() < VALID_POS_STD && this->calibrated && time_since_reset > VALID_TIME_SINCE_RESET) {
fix.setStatus(cereal::LiveLocationKalman::Status::VALID);
} else if (fix_ecef_std.norm() < VALID_POS_STD && time_since_reset > VALID_TIME_SINCE_RESET) {
fix.setStatus(cereal::LiveLocationKalman::Status::UNCALIBRATED);
} else {
fix.setStatus(cereal::LiveLocationKalman::Status::UNINITIALIZED);
}
}
VectorXd Localizer::get_position_geodetic() {
VectorXd fix_ecef = this->kf->get_x().segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START);
ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) };
Geodetic fix_pos_geo = ecef2geodetic(fix_ecef_ecef);
return Vector3d(fix_pos_geo.lat, fix_pos_geo.lon, fix_pos_geo.alt);
}
VectorXd Localizer::get_state() {
return this->kf->get_x();
}
VectorXd Localizer::get_stdev() {
return this->kf->get_P().diagonal().array().sqrt();
}
bool Localizer::are_inputs_ok() {
return this->critical_services_valid(this->observation_values_invalid) && !this->observation_timings_invalid;
}
void Localizer::observation_timings_invalid_reset(){
this->observation_timings_invalid = false;
}
void Localizer::handle_sensor(double current_time, const cereal::SensorEventData::Reader& log) {
// TODO does not yet account for double sensor readings in the log
// Ignore empty readings (e.g. in case the magnetometer had no data ready)
if (log.getTimestamp() == 0) {
return;
}
double sensor_time = 1e-9 * log.getTimestamp();
// sensor time and log time should be close
if (std::abs(current_time - sensor_time) > 0.1) {
LOGE("Sensor reading ignored, sensor timestamp more than 100ms off from log time");
this->observation_timings_invalid = true;
return;
} else if (!this->is_timestamp_valid(sensor_time)) {
this->observation_timings_invalid = true;
return;
}
// TODO: handle messages from two IMUs at the same time
if (log.getSource() == cereal::SensorEventData::SensorSource::BMX055) {
return;
}
// Gyro Uncalibrated
if (log.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {
auto v = log.getGyroUncalibrated().getV();
auto meas = Vector3d(-v[2], -v[1], -v[0]);
VectorXd gyro_bias = this->kf->get_x().segment<STATE_GYRO_BIAS_LEN>(STATE_GYRO_BIAS_START);
float gyro_camodo_yawrate_err = std::abs((meas[2] - gyro_bias[2]) - this->camodo_yawrate_distribution[0]);
float gyro_camodo_yawrate_err_threshold = YAWRATE_CROSS_ERR_CHECK_FACTOR * this->camodo_yawrate_distribution[1];
bool gyro_valid = gyro_camodo_yawrate_err < gyro_camodo_yawrate_err_threshold;
if ((meas.norm() < ROTATION_SANITY_CHECK) && gyro_valid) {
this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_GYRO, { meas });
this->observation_values_invalid["gyroscope"] *= DECAY;
} else {
this->observation_values_invalid["gyroscope"] += 1.0;
}
}
// Accelerometer
if (log.which() == cereal::SensorEventData::ACCELERATION) {
auto v = log.getAcceleration().getV();
// TODO: reduce false positives and re-enable this check
// check if device fell, estimate 10 for g
// 40m/s**2 is a good filter for falling detection, no false positives in 20k minutes of driving
// this->device_fell |= (floatlist2vector(v) - Vector3d(10.0, 0.0, 0.0)).norm() > 40.0;
auto meas = Vector3d(-v[2], -v[1], -v[0]);
if (meas.norm() < ACCEL_SANITY_CHECK) {
this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_ACCEL, { meas });
this->observation_values_invalid["accelerometer"] *= DECAY;
} else {
this->observation_values_invalid["accelerometer"] += 1.0;
}
}
}
void Localizer::input_fake_gps_observations(double current_time) {
// This is done to make sure that the error estimate of the position does not blow up
// when the filter is in no-gps mode
// Steps : first predict -> observe current obs with reasonable STD
this->kf->predict(current_time);
VectorXd current_x = this->kf->get_x();
VectorXd ecef_pos = current_x.segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START);
VectorXd ecef_vel = current_x.segment<STATE_ECEF_VELOCITY_LEN>(STATE_ECEF_VELOCITY_START);
const MatrixXdr &ecef_pos_R = this->kf->get_fake_gps_pos_cov();
const MatrixXdr &ecef_vel_R = this->kf->get_fake_gps_vel_cov();
this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R });
this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R });
}
void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset) {
bool gps_unreasonable = (Vector2d(log.getHorizontalAccuracy(), log.getVerticalAccuracy()).norm() >= SANE_GPS_UNCERTAINTY);
bool gps_accuracy_insane = ((log.getVerticalAccuracy() <= 0) || (log.getSpeedAccuracy() <= 0) || (log.getBearingAccuracyDeg() <= 0));
bool gps_lat_lng_alt_insane = ((std::abs(log.getLatitude()) > 90) || (std::abs(log.getLongitude()) > 180) || (std::abs(log.getAltitude()) > ALTITUDE_SANITY_CHECK));
bool gps_vel_insane = (floatlist2vector(log.getVNED()).norm() > TRANS_SANITY_CHECK);
if (!log.getHasFix() || gps_unreasonable || gps_accuracy_insane || gps_lat_lng_alt_insane || gps_vel_insane) {
//this->gps_valid = false;
this->determine_gps_mode(current_time);
return;
}
double sensor_time = current_time - sensor_time_offset;
// Process message
//this->gps_valid = true;
this->gps_mode = true;
Geodetic geodetic = { log.getLatitude(), log.getLongitude(), log.getAltitude() };
this->converter = std::make_unique<LocalCoord>(geodetic);
VectorXd ecef_pos = this->converter->ned2ecef({ 0.0, 0.0, 0.0 }).to_vector();
VectorXd ecef_vel = this->converter->ned2ecef({ log.getVNED()[0], log.getVNED()[1], log.getVNED()[2] }).to_vector() - ecef_pos;
float ecef_pos_std = std::sqrt(this->gps_variance_factor * std::pow(log.getHorizontalAccuracy(), 2) + this->gps_vertical_variance_factor * std::pow(log.getVerticalAccuracy(), 2));
MatrixXdr ecef_pos_R = Vector3d::Constant(std::pow(this->gps_std_factor * ecef_pos_std, 2)).asDiagonal();
MatrixXdr ecef_vel_R = Vector3d::Constant(std::pow(this->gps_std_factor * log.getSpeedAccuracy(), 2)).asDiagonal();
this->unix_timestamp_millis = log.getUnixTimestampMillis();
double gps_est_error = (this->kf->get_x().segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START) - ecef_pos).norm();
VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment<STATE_ECEF_ORIENTATION_LEN>(STATE_ECEF_ORIENTATION_START)));
VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ecef);
VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, DEG2RAD(log.getBearingDeg()));
VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI;
for (int i = 0; i < orientation_error.size(); i++) {
orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI);
if (orientation_error(i) < 0.0) {
orientation_error(i) += 2.0 * M_PI;
}
orientation_error(i) -= M_PI;
}
VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps)));
if (ecef_vel.norm() > 5.0 && orientation_error.norm() > 1.0) {
LOGE("Locationd vs ubloxLocation orientation difference too large, kalman reset");
this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R);
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat });
} else if (gps_est_error > 100.0) {
LOGE("Locationd vs ubloxLocation position difference too large, kalman reset");
this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R);
}
this->last_gps_msg = sensor_time;
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R });
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R });
}
void Localizer::handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log) {
if (!log.getPositionECEF().getValid() || !log.getVelocityECEF().getValid()) {
this->determine_gps_mode(current_time);
return;
}
double sensor_time = log.getMeasTime() * 1e-9;
sensor_time -= this->gps_time_offset;
auto ecef_pos_v = log.getPositionECEF().getValue();
VectorXd ecef_pos = Vector3d(ecef_pos_v[0], ecef_pos_v[1], ecef_pos_v[2]);
// indexed at 0 cause all std values are the same MAE
auto ecef_pos_std = log.getPositionECEF().getStd()[0];
MatrixXdr ecef_pos_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_pos_std, 2)).asDiagonal();
auto ecef_vel_v = log.getVelocityECEF().getValue();
VectorXd ecef_vel = Vector3d(ecef_vel_v[0], ecef_vel_v[1], ecef_vel_v[2]);
// indexed at 0 cause all std values are the same MAE
auto ecef_vel_std = log.getVelocityECEF().getStd()[0];
MatrixXdr ecef_vel_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_vel_std, 2)).asDiagonal();
double gps_est_error = (this->kf->get_x().segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START) - ecef_pos).norm();
VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment<STATE_ECEF_ORIENTATION_LEN>(STATE_ECEF_ORIENTATION_START)));
VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos[0], ecef_pos[1], ecef_pos[2] }, orientation_ecef);
LocalCoord convs((ECEF){ .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] });
ECEF next_ecef = {.x = ecef_pos[0] + ecef_vel[0], .y = ecef_pos[1] + ecef_vel[1], .z = ecef_pos[2] + ecef_vel[2]};
VectorXd ned_vel = convs.ecef2ned(next_ecef).to_vector();
double bearing_rad = atan2(ned_vel[1], ned_vel[0]);
VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, bearing_rad);
VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI;
for (int i = 0; i < orientation_error.size(); i++) {
orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI);
if (orientation_error(i) < 0.0) {
orientation_error(i) += 2.0 * M_PI;
}
orientation_error(i) -= M_PI;
}
VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps)));
if (ecef_pos_std > GPS_POS_STD_THRESHOLD || ecef_vel_std > GPS_VEL_STD_THRESHOLD) {
this->determine_gps_mode(current_time);
return;
}
// prevent jumping gnss measurements (covered lots, standstill...)
bool orientation_reset = ecef_vel_std < GPS_VEL_STD_RESET_THRESHOLD;
orientation_reset &= orientation_error.norm() > GPS_ORIENTATION_ERROR_RESET_THRESHOLD;
orientation_reset &= !this->standstill;
if (orientation_reset) {
this->orientation_reset_count++;
} else {
this->orientation_reset_count = 0;
}
if ((gps_est_error > GPS_POS_ERROR_RESET_THRESHOLD && ecef_pos_std < GPS_POS_STD_RESET_THRESHOLD) || this->last_gps_msg == 0) {
// always reset on first gps message and if the location is off but the accuracy is high
LOGE("Locationd vs gnssMeasurement position difference too large, kalman reset");
this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R);
} else if (orientation_reset_count > GPS_ORIENTATION_ERROR_RESET_CNT) {
LOGE("Locationd vs gnssMeasurement orientation difference too large, kalman reset");
this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R);
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat });
this->orientation_reset_count = 0;
}
this->gps_mode = true;
this->last_gps_msg = sensor_time;
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R });
this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R });
}
void Localizer::handle_car_state(double current_time, const cereal::CarState::Reader& log) {
this->car_speed = std::abs(log.getVEgo());
this->standstill = log.getStandstill();
if (this->standstill) {
this->kf->predict_and_observe(current_time, OBSERVATION_NO_ROT, { Vector3d(0.0, 0.0, 0.0) });
this->kf->predict_and_observe(current_time, OBSERVATION_NO_ACCEL, { Vector3d(0.0, 0.0, 0.0) });
}
}
void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log) {
VectorXd rot_device = this->device_from_calib * floatlist2vector(log.getRot());
VectorXd trans_device = this->device_from_calib * floatlist2vector(log.getTrans());
if (!this->is_timestamp_valid(current_time)) {
this->observation_timings_invalid = true;
return;
}
if ((rot_device.norm() > ROTATION_SANITY_CHECK) || (trans_device.norm() > TRANS_SANITY_CHECK)) {
this->observation_values_invalid["cameraOdometry"] += 1.0;
return;
}
VectorXd rot_calib_std = floatlist2vector(log.getRotStd());
VectorXd trans_calib_std = floatlist2vector(log.getTransStd());
if ((rot_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK) || (trans_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK)) {
this->observation_values_invalid["cameraOdometry"] += 1.0;
return;
}
if ((rot_calib_std.norm() > 10 * ROTATION_SANITY_CHECK) || (trans_calib_std.norm() > 10 * TRANS_SANITY_CHECK)) {
this->observation_values_invalid["cameraOdometry"] += 1.0;
return;
}
this->posenet_stds.pop_front();
this->posenet_stds.push_back(trans_calib_std[0]);
// Multiply by 10 to avoid to high certainty in kalman filter because of temporally correlated noise
trans_calib_std *= 10.0;
rot_calib_std *= 10.0;
MatrixXdr rot_device_cov = rotate_std(this->device_from_calib, rot_calib_std).array().square().matrix().asDiagonal();
MatrixXdr trans_device_cov = rotate_std(this->device_from_calib, trans_calib_std).array().square().matrix().asDiagonal();
this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_ROTATION,
{ rot_device }, { rot_device_cov });
this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_TRANSLATION,
{ trans_device }, { trans_device_cov });
this->observation_values_invalid["cameraOdometry"] *= DECAY;
this->camodo_yawrate_distribution = Vector2d(rot_device[2], rotate_std(this->device_from_calib, rot_calib_std)[2]);
}
void Localizer::handle_live_calib(double current_time, const cereal::ExtrinsicsCalibration::Reader& log) {
if (!this->is_timestamp_valid(current_time)) {
this->observation_timings_invalid = true;
return;
}
if (log.getRpyCalib().size() > 0) {
auto live_calib = floatlist2vector(log.getRpyCalib());
if ((live_calib.minCoeff() < -CALIB_RPY_SANITY_CHECK) || (live_calib.maxCoeff() > CALIB_RPY_SANITY_CHECK)) {
this->observation_values_invalid["extrinsicsCalibration"] += 1.0;
return;
}
this->calib = live_calib;
this->device_from_calib = euler2rot(this->calib);
this->calib_from_device = this->device_from_calib.transpose();
this->calibrated = log.getCalStatus() == cereal::ExtrinsicsCalibration::Status::CALIBRATED;
this->observation_values_invalid["extrinsicsCalibration"] *= DECAY;
}
}
void Localizer::reset_kalman(double current_time) {
const VectorXd &init_x = this->kf->get_initial_x();
const MatrixXdr &init_P = this->kf->get_initial_P();
this->reset_kalman(current_time, init_x, init_P);
}
void Localizer::finite_check(double current_time) {
bool all_finite = this->kf->get_x().array().isFinite().all() or this->kf->get_P().array().isFinite().all();
if (!all_finite) {
LOGE("Non-finite values detected, kalman reset");
this->reset_kalman(current_time);
}
}
void Localizer::time_check(double current_time) {
if (std::isnan(this->last_reset_time)) {
this->last_reset_time = current_time;
}
if (std::isnan(this->first_valid_log_time)) {
this->first_valid_log_time = current_time;
}
double filter_time = this->kf->get_filter_time();
bool big_time_gap = !std::isnan(filter_time) && (current_time - filter_time > 10);
if (big_time_gap) {
LOGE("Time gap of over 10s detected, kalman reset");
this->reset_kalman(current_time);
}
}
void Localizer::update_reset_tracker() {
// reset tracker is tuned to trigger when over 1reset/10s over 2min period
if (this->is_gps_ok()) {
this->reset_tracker *= RESET_TRACKER_DECAY;
} else {
this->reset_tracker = 0.0;
}
}
void Localizer::reset_kalman(double current_time, const VectorXd &init_orient, const VectorXd &init_pos, const VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R) {
// too nonlinear to init on completely wrong
VectorXd current_x = this->kf->get_x();
MatrixXdr current_P = this->kf->get_P();
MatrixXdr init_P = this->kf->get_initial_P();
const MatrixXdr &reset_orientation_P = this->kf->get_reset_orientation_P();
int non_ecef_state_err_len = init_P.rows() - (STATE_ECEF_POS_ERR_LEN + STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN);
current_x.segment<STATE_ECEF_ORIENTATION_LEN>(STATE_ECEF_ORIENTATION_START) = init_orient;
current_x.segment<STATE_ECEF_VELOCITY_LEN>(STATE_ECEF_VELOCITY_START) = init_vel;
current_x.segment<STATE_ECEF_POS_LEN>(STATE_ECEF_POS_START) = init_pos;
init_P.block<STATE_ECEF_POS_ERR_LEN, STATE_ECEF_POS_ERR_LEN>(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal() = init_pos_R.diagonal();
init_P.block<STATE_ECEF_ORIENTATION_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN>(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START).diagonal() = reset_orientation_P.diagonal();
init_P.block<STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_VELOCITY_ERR_LEN>(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START).diagonal() = init_vel_R.diagonal();
init_P.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal() = current_P.block(STATE_ANGULAR_VELOCITY_ERR_START,
STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal();
this->reset_kalman(current_time, current_x, init_P);
}
void Localizer::reset_kalman(double current_time, const VectorXd &init_x, const MatrixXdr &init_P) {
this->kf->init_state(init_x, init_P, current_time);
this->last_reset_time = current_time;
this->reset_tracker += 1.0;
}
void Localizer::handle_msg_bytes(const char *data, const size_t size) {
AlignedBuffer aligned_buf;
capnp::FlatArrayMessageReader cmsg(aligned_buf.align(data, size));
cereal::Event::Reader event = cmsg.getRoot<cereal::Event>();
this->handle_msg(event);
}
void Localizer::handle_msg(const cereal::Event::Reader& log) {
double t = log.getLogMonoTime() * 1e-9;
this->time_check(t);
if (log.isAccelerometer()) {
this->handle_sensor(t, log.getAccelerometer());
} else if (log.isGyroscope()) {
this->handle_sensor(t, log.getGyroscope());
} else if (log.isGpsLocation()) {
this->handle_gps(t, log.getGpsLocation(), GPS_QUECTEL_SENSOR_TIME_OFFSET);
} else if (log.isGpsLocationExternal()) {
this->handle_gps(t, log.getGpsLocationExternal(), GPS_UBLOX_SENSOR_TIME_OFFSET);
//} else if (log.isGnssMeasurements()) {
// this->handle_gnss(t, log.getGnssMeasurements());
} else if (log.isCarState()) {
this->handle_car_state(t, log.getCarState());
} else if (log.isCameraOdometry()) {
this->handle_cam_odo(t, log.getCameraOdometry());
} else if (log.isExtrinsicsCalibration()) {
this->handle_live_calib(t, log.getExtrinsicsCalibration());
}
this->finite_check();
this->update_reset_tracker();
}
kj::ArrayPtr<capnp::byte> Localizer::get_message_bytes(MessageBuilder& msg_builder, bool inputsOK,
bool sensorsOK, bool gpsOK, bool msgValid) {
cereal::Event::Builder evt = msg_builder.initEvent();
evt.setValid(msgValid);
cereal::LiveLocationKalman::Builder liveLoc = evt.initLiveLocationKalman();
this->build_live_location(liveLoc);
liveLoc.setSensorsOK(sensorsOK);
liveLoc.setGpsOK(gpsOK);
liveLoc.setInputsOK(inputsOK);
return msg_builder.toBytes();
}
bool Localizer::is_gps_ok() {
return (this->kf->get_filter_time() - this->last_gps_msg) < 2.0;
}
bool Localizer::critical_services_valid(const std::map<std::string, double> &critical_services) {
for (auto &kv : critical_services){
if (kv.second >= INPUT_INVALID_THRESHOLD){
return false;
}
}
return true;
}
bool Localizer::is_timestamp_valid(double current_time) {
double filter_time = this->kf->get_filter_time();
if (!std::isnan(filter_time) && ((filter_time - current_time) > MAX_FILTER_REWIND_TIME)) {
LOGE("Observation timestamp is older than the max rewind threshold of the filter");
return false;
}
return true;
}
void Localizer::determine_gps_mode(double current_time) {
// 1. If the pos_std is greater than what's not acceptable and localizer is in gps-mode, reset to no-gps-mode
// 2. If the pos_std is greater than what's not acceptable and localizer is in no-gps-mode, fake obs
// 3. If the pos_std is smaller than what's not acceptable, let gps-mode be whatever it is
VectorXd current_pos_std = this->kf->get_P().block<STATE_ECEF_POS_ERR_LEN, STATE_ECEF_POS_ERR_LEN>(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal().array().sqrt();
if (current_pos_std.norm() > SANE_GPS_UNCERTAINTY){
if (this->gps_mode){
this->gps_mode = false;
this->reset_kalman(current_time);
} else {
this->input_fake_gps_observations(current_time);
}
}
}
void Localizer::configure_gnss_source(const LocalizerGnssSource &source) {
this->gnss_source = source;
if (source == LocalizerGnssSource::UBLOX) {
this->gps_std_factor = 10.0;
this->gps_variance_factor = 1.0;
this->gps_vertical_variance_factor = 1.0;
this->gps_time_offset = GPS_UBLOX_SENSOR_TIME_OFFSET;
} else {
this->gps_std_factor = 2.0;
this->gps_variance_factor = 0.0;
this->gps_vertical_variance_factor = 3.0;
this->gps_time_offset = GPS_QUECTEL_SENSOR_TIME_OFFSET;
}
}
int Localizer::locationd_thread() {
Params params;
LocalizerGnssSource source;
const char* gps_location_socket;
if (params.getBool("UbloxAvailable")) {
source = LocalizerGnssSource::UBLOX;
gps_location_socket = "gpsLocationExternal";
} else {
source = LocalizerGnssSource::QCOM;
gps_location_socket = "gpsLocation";
}
this->configure_gnss_source(source);
const std::initializer_list<const char *> service_list = {gps_location_socket, "cameraOdometry", "extrinsicsCalibration",
"carState", "accelerometer", "gyroscope"};
SubMaster sm(service_list, {}, nullptr, {gps_location_socket});
PubMaster pm({"liveLocationKalman"});
uint64_t cnt = 0;
bool filterInitialized = false;
const std::vector<std::string> critical_input_services = {"cameraOdometry", "extrinsicsCalibration", "accelerometer", "gyroscope"};
for (std::string service : critical_input_services) {
this->observation_values_invalid.insert({service, 0.0});
}
while (!do_exit) {
sm.update();
if (filterInitialized){
this->observation_timings_invalid_reset();
for (const char* service : service_list) {
if (sm.updated(service) && sm.valid(service)){
const cereal::Event::Reader log = sm[service];
this->handle_msg(log);
}
}
} else {
filterInitialized = sm.allAliveAndValid();
}
const char* trigger_msg = "cameraOdometry";
if (sm.updated(trigger_msg)) {
bool inputsOK = sm.allValid() && this->are_inputs_ok();
bool gpsOK = this->is_gps_ok();
bool sensorsOK = sm.allAliveAndValid({"accelerometer", "gyroscope"});
// Log time to first fix
if (gpsOK && std::isnan(this->ttff) && !std::isnan(this->first_valid_log_time)) {
this->ttff = std::max(1e-3, (sm[trigger_msg].getLogMonoTime() * 1e-9) - this->first_valid_log_time);
}
MessageBuilder msg_builder;
kj::ArrayPtr<capnp::byte> bytes = this->get_message_bytes(msg_builder, inputsOK, sensorsOK, gpsOK, filterInitialized);
pm.send("liveLocationKalman", bytes.begin(), bytes.size());
if (cnt % 1200 == 0 && gpsOK) { // once a minute
VectorXd posGeo = this->get_position_geodetic();
std::string lastGPSPosJSON = util::string_format(
"{\"latitude\": %.15f, \"longitude\": %.15f, \"altitude\": %.15f}", posGeo(0), posGeo(1), posGeo(2));
params.putNonBlocking("LastGPSPositionLLK", lastGPSPosJSON);
}
cnt++;
}
}
return 0;
}
int main() {
util::set_realtime_priority(5);
Localizer localizer;
return localizer.locationd_thread();
}
@@ -1,100 +0,0 @@
#pragma once
#include <eigen3/Eigen/Dense>
#include <deque>
#include <fstream>
#include <memory>
#include <map>
#include <string>
#include "cereal/messaging/messaging.h"
#include "common/params.h"
#include "common/swaglog.h"
#include "common/timing.h"
#include "common/util.h"
#include "sunnypilot/common/transformations/coordinates.hpp"
#include "sunnypilot/common/transformations/orientation.hpp"
#include "sunnypilot/system/sensord/sensors/constants.h"
#include "sunnypilot/selfdrive/locationd/models/live_kf.h"
#define VISION_DECIMATION 2
#define SENSOR_DECIMATION 10
#define POSENET_STD_HIST_HALF 20
enum LocalizerGnssSource {
UBLOX, QCOM
};
class Localizer {
public:
Localizer(LocalizerGnssSource gnss_source = LocalizerGnssSource::UBLOX);
int locationd_thread();
void reset_kalman(double current_time = NAN);
void reset_kalman(double current_time, const Eigen::VectorXd &init_orient, const Eigen::VectorXd &init_pos, const Eigen::VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R);
void reset_kalman(double current_time, const Eigen::VectorXd &init_x, const MatrixXdr &init_P);
void finite_check(double current_time = NAN);
void time_check(double current_time = NAN);
void update_reset_tracker();
bool is_gps_ok();
bool critical_services_valid(const std::map<std::string, double> &critical_services);
bool is_timestamp_valid(double current_time);
void determine_gps_mode(double current_time);
bool are_inputs_ok();
void observation_timings_invalid_reset();
kj::ArrayPtr<capnp::byte> get_message_bytes(MessageBuilder& msg_builder,
bool inputsOK, bool sensorsOK, bool gpsOK, bool msgValid);
void build_live_location(cereal::LiveLocationKalman::Builder& fix);
Eigen::VectorXd get_position_geodetic();
Eigen::VectorXd get_state();
Eigen::VectorXd get_stdev();
void handle_msg_bytes(const char *data, const size_t size);
void handle_msg(const cereal::Event::Reader& log);
void handle_sensor(double current_time, const cereal::SensorEventData::Reader& log);
void handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset);
void handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log);
void handle_car_state(double current_time, const cereal::CarState::Reader& log);
void handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log);
void handle_live_calib(double current_time, const cereal::ExtrinsicsCalibration::Reader& log);
void input_fake_gps_observations(double current_time);
private:
std::unique_ptr<LiveKalman> kf;
Eigen::VectorXd calib;
MatrixXdr device_from_calib;
MatrixXdr calib_from_device;
bool calibrated = false;
double car_speed = 0.0;
double last_reset_time = NAN;
std::deque<double> posenet_stds;
std::unique_ptr<LocalCoord> converter;
int64_t unix_timestamp_millis = 0;
double reset_tracker = 0.0;
bool device_fell = false;
bool gps_mode = false;
double first_valid_log_time = NAN;
double ttff = NAN;
double last_gps_msg = 0;
LocalizerGnssSource gnss_source;
bool observation_timings_invalid = false;
std::map<std::string, double> observation_values_invalid;
bool standstill = true;
int32_t orientation_reset_count = 0;
float gps_std_factor;
float gps_variance_factor;
float gps_vertical_variance_factor;
double gps_time_offset;
Eigen::VectorXd camodo_yawrate_distribution = Eigen::Vector2d(0.0, 10.0); // mean, std
void configure_gnss_source(const LocalizerGnssSource &source);
};
@@ -1 +0,0 @@
generated/
@@ -1,180 +0,0 @@
#!/usr/bin/env python3
import math
import sys
from typing import Any
import numpy as np
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
from openpilot.sunnypilot.selfdrive.locationd.models.constants import ObservationKind
from openpilot.common.swaglog import cloudlog
from rednose.helpers.kalmanfilter import KalmanFilter
if __name__ == '__main__': # Generating sympy
import sympy as sp
from rednose.helpers.ekf_sym import gen_code
else:
from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx
i = 0
def _slice(n):
global i
s = slice(i, i + n)
i += n
return s
class States:
# Vehicle model params
STIFFNESS = _slice(1) # [-]
STEER_RATIO = _slice(1) # [-]
ANGLE_OFFSET = _slice(1) # [rad]
ANGLE_OFFSET_FAST = _slice(1) # [rad]
VELOCITY = _slice(2) # (x, y) [m/s]
YAW_RATE = _slice(1) # [rad/s]
STEER_ANGLE = _slice(1) # [rad]
ROAD_ROLL = _slice(1) # [rad]
class CarKalman(KalmanFilter):
name = 'car'
initial_x = np.array([
1.0,
15.0,
0.0,
0.0,
10.0, 0.0,
0.0,
0.0,
0.0
])
# process noise
Q = np.diag([
(.05 / 100)**2,
.01**2,
math.radians(0.02)**2,
math.radians(0.25)**2,
.1**2, .01**2,
math.radians(0.1)**2,
math.radians(0.1)**2,
math.radians(1)**2,
])
P_initial = Q.copy()
obs_noise: dict[int, Any] = {
ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.05)**2),
ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(10.0)**2),
ObservationKind.ROAD_ROLL: np.atleast_2d(math.radians(1.0)**2),
ObservationKind.STEER_RATIO: np.atleast_2d(5.0**2),
ObservationKind.STIFFNESS: np.atleast_2d(0.5**2),
ObservationKind.ROAD_FRAME_X_SPEED: np.atleast_2d(0.1**2),
}
global_vars = [
'mass',
'rotational_inertia',
'center_to_front',
'center_to_rear',
'stiffness_front',
'stiffness_rear',
]
@staticmethod
def generate_code(generated_dir):
dim_state = CarKalman.initial_x.shape[0]
name = CarKalman.name
# Linearized single-track lateral dynamics, equations 7.211-7.213
# Massimo Guiggiani, The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars
# Springer Cham, 2023. doi: https://doi.org/10.1007/978-3-031-06461-6
# globals
global_vars = [sp.Symbol(name) for name in CarKalman.global_vars]
m, j, aF, aR, cF_orig, cR_orig = global_vars
# make functions and jacobians with sympy
# state variables
state_sym = sp.MatrixSymbol('state', dim_state, 1)
state = sp.Matrix(state_sym)
# Vehicle model constants
sf = state[States.STIFFNESS, :][0, 0]
cF, cR = sf * cF_orig, sf * cR_orig
angle_offset = state[States.ANGLE_OFFSET, :][0, 0]
angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0]
theta = state[States.ROAD_ROLL, :][0, 0]
sa = state[States.STEER_ANGLE, :][0, 0]
sR = state[States.STEER_RATIO, :][0, 0]
u, v = state[States.VELOCITY, :]
r = state[States.YAW_RATE, :][0, 0]
A = sp.Matrix(np.zeros((2, 2)))
A[0, 0] = -(cF + cR) / (m * u)
A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u
A[1, 0] = -(cF * aF - cR * aR) / (j * u)
A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u)
B = sp.Matrix(np.zeros((2, 1)))
B[0, 0] = cF / m / sR
B[1, 0] = (cF * aF) / j / sR
C = sp.Matrix(np.zeros((2, 1)))
C[0, 0] = ACCELERATION_DUE_TO_GRAVITY
C[1, 0] = 0
x = sp.Matrix([v, r]) # lateral velocity, yaw rate
x_dot = A * x + B * (sa - angle_offset - angle_offset_fast) - C * theta
dt = sp.Symbol('dt')
state_dot = sp.Matrix(np.zeros((dim_state, 1)))
state_dot[States.VELOCITY.start + 1, 0] = x_dot[0]
state_dot[States.YAW_RATE.start, 0] = x_dot[1]
# Basic descretization, 1st order integrator
# Can be pretty bad if dt is big
f_sym = state + dt * state_dot
#
# Observation functions
#
obs_eqs = [
[sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None],
[sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None],
[sp.Matrix([u]), ObservationKind.ROAD_FRAME_X_SPEED, None],
[sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None],
[sp.Matrix([angle_offset_fast]), ObservationKind.ANGLE_OFFSET_FAST, None],
[sp.Matrix([sR]), ObservationKind.STEER_RATIO, None],
[sp.Matrix([sf]), ObservationKind.STIFFNESS, None],
[sp.Matrix([theta]), ObservationKind.ROAD_ROLL, None],
]
gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, global_vars=global_vars)
def __init__(self, generated_dir):
dim_state, dim_state_err = CarKalman.initial_x.shape[0], CarKalman.P_initial.shape[0]
self.filter = EKF_sym_pyx(generated_dir, CarKalman.name, CarKalman.Q, CarKalman.initial_x, CarKalman.P_initial,
dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog)
def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear):
self.filter.set_global("mass", mass)
self.filter.set_global("rotational_inertia", rotational_inertia)
self.filter.set_global("center_to_front", center_to_front)
self.filter.set_global("center_to_rear", center_to_rear)
self.filter.set_global("stiffness_front", stiffness_front)
self.filter.set_global("stiffness_rear", stiffness_rear)
if __name__ == "__main__":
generated_dir = sys.argv[2]
CarKalman.generate_code(generated_dir)
@@ -1,92 +0,0 @@
import os
GENERATED_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'generated'))
class ObservationKind:
UNKNOWN = 0
NO_OBSERVATION = 1
GPS_NED = 2
ODOMETRIC_SPEED = 3
PHONE_GYRO = 4
GPS_VEL = 5
PSEUDORANGE_GPS = 6
PSEUDORANGE_RATE_GPS = 7
SPEED = 8
NO_ROT = 9
PHONE_ACCEL = 10
ORB_POINT = 11
ECEF_POS = 12
CAMERA_ODO_TRANSLATION = 13
CAMERA_ODO_ROTATION = 14
ORB_FEATURES = 15
MSCKF_TEST = 16
FEATURE_TRACK_TEST = 17
LANE_PT = 18
IMU_FRAME = 19
PSEUDORANGE_GLONASS = 20
PSEUDORANGE_RATE_GLONASS = 21
PSEUDORANGE = 22
PSEUDORANGE_RATE = 23
ECEF_VEL = 35
ECEF_ORIENTATION_FROM_GPS = 32
NO_ACCEL = 33
ORB_FEATURES_WIDE = 34
ROAD_FRAME_XY_SPEED = 24 # (x, y) [m/s]
ROAD_FRAME_YAW_RATE = 25 # [rad/s]
STEER_ANGLE = 26 # [rad]
ANGLE_OFFSET_FAST = 27 # [rad]
STIFFNESS = 28 # [-]
STEER_RATIO = 29 # [-]
ROAD_FRAME_X_SPEED = 30 # (x) [m/s]
ROAD_ROLL = 31 # [rad]
names = [
'Unknown',
'No observation',
'GPS NED',
'Odometric speed',
'Phone gyro',
'GPS velocity',
'GPS pseudorange',
'GPS pseudorange rate',
'Speed',
'No rotation',
'Phone acceleration',
'ORB point',
'ECEF pos',
'camera odometric translation',
'camera odometric rotation',
'ORB features',
'MSCKF test',
'Feature track test',
'Lane ecef point',
'imu frame eulers',
'GLONASS pseudorange',
'GLONASS pseudorange rate',
'pseudorange',
'pseudorange rate',
'Road Frame x,y speed',
'Road Frame yaw rate',
'Steer Angle',
'Fast Angle Offset',
'Stiffness',
'Steer Ratio',
'Road Frame x speed',
'Road Roll',
'ECEF orientation from GPS',
'NO accel',
'ORB features wide camera',
'ECEF_VEL',
]
@classmethod
def to_string(cls, kind):
return cls.names[kind]
SAT_OBS = [ObservationKind.PSEUDORANGE_GPS,
ObservationKind.PSEUDORANGE_RATE_GPS,
ObservationKind.PSEUDORANGE_GLONASS,
ObservationKind.PSEUDORANGE_RATE_GLONASS]
@@ -1,122 +0,0 @@
#include "sunnypilot/selfdrive/locationd/models/live_kf.h"
using namespace EKFS;
using namespace Eigen;
Eigen::Map<Eigen::VectorXd> get_mapvec(const Eigen::VectorXd &vec) {
return Eigen::Map<Eigen::VectorXd>((double*)vec.data(), vec.rows(), vec.cols());
}
Eigen::Map<MatrixXdr> get_mapmat(const MatrixXdr &mat) {
return Eigen::Map<MatrixXdr>((double*)mat.data(), mat.rows(), mat.cols());
}
std::vector<Eigen::Map<Eigen::VectorXd>> get_vec_mapvec(const std::vector<Eigen::VectorXd> &vec_vec) {
std::vector<Eigen::Map<Eigen::VectorXd>> res;
for (const Eigen::VectorXd &vec : vec_vec) {
res.push_back(get_mapvec(vec));
}
return res;
}
std::vector<Eigen::Map<MatrixXdr>> get_vec_mapmat(const std::vector<MatrixXdr> &mat_vec) {
std::vector<Eigen::Map<MatrixXdr>> res;
for (const MatrixXdr &mat : mat_vec) {
res.push_back(get_mapmat(mat));
}
return res;
}
LiveKalman::LiveKalman() {
this->dim_state = live_initial_x.rows();
this->dim_state_err = live_initial_P_diag.rows();
this->initial_x = live_initial_x;
this->initial_P = live_initial_P_diag.asDiagonal();
this->fake_gps_pos_cov = live_fake_gps_pos_cov_diag.asDiagonal();
this->fake_gps_vel_cov = live_fake_gps_vel_cov_diag.asDiagonal();
this->reset_orientation_P = live_reset_orientation_diag.asDiagonal();
this->Q = live_Q_diag.asDiagonal();
for (auto& pair : live_obs_noise_diag) {
this->obs_noise[pair.first] = pair.second.asDiagonal();
}
// init filter
this->filter = std::make_shared<EKFSym>(this->name, get_mapmat(this->Q), get_mapvec(this->initial_x),
get_mapmat(initial_P), this->dim_state, this->dim_state_err, 0, 0, 0, std::vector<int>(),
std::vector<int>{3}, std::vector<std::string>(), 0.8);
}
void LiveKalman::init_state(const VectorXd &state, const VectorXd &covs_diag, double filter_time) {
MatrixXdr covs = covs_diag.asDiagonal();
this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time);
}
void LiveKalman::init_state(const VectorXd &state, const MatrixXdr &covs, double filter_time) {
this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time);
}
void LiveKalman::init_state(const VectorXd &state, double filter_time) {
MatrixXdr covs = this->filter->covs();
this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time);
}
VectorXd LiveKalman::get_x() {
return this->filter->state();
}
MatrixXdr LiveKalman::get_P() {
return this->filter->covs();
}
double LiveKalman::get_filter_time() {
return this->filter->get_filter_time();
}
std::vector<MatrixXdr> LiveKalman::get_R(int kind, int n) {
std::vector<MatrixXdr> R;
for (int i = 0; i < n; i++) {
R.push_back(this->obs_noise[kind]);
}
return R;
}
std::optional<Estimate> LiveKalman::predict_and_observe(double t, int kind, const std::vector<VectorXd> &meas, std::vector<MatrixXdr> R) {
std::optional<Estimate> r;
if (R.size() == 0) {
R = this->get_R(kind, meas.size());
}
r = this->filter->predict_and_update_batch(t, kind, get_vec_mapvec(meas), get_vec_mapmat(R));
return r;
}
void LiveKalman::predict(double t) {
this->filter->predict(t);
}
const Eigen::VectorXd &LiveKalman::get_initial_x() {
return this->initial_x;
}
const MatrixXdr &LiveKalman::get_initial_P() {
return this->initial_P;
}
const MatrixXdr &LiveKalman::get_fake_gps_pos_cov() {
return this->fake_gps_pos_cov;
}
const MatrixXdr &LiveKalman::get_fake_gps_vel_cov() {
return this->fake_gps_vel_cov;
}
const MatrixXdr &LiveKalman::get_reset_orientation_P() {
return this->reset_orientation_P;
}
MatrixXdr LiveKalman::H(const VectorXd &in) {
assert(in.size() == 6);
Matrix<double, 3, 6, Eigen::RowMajor> res;
this->filter->get_extra_routine("H")((double*)in.data(), res.data());
return res;
}
@@ -1,66 +0,0 @@
#pragma once
#include <string>
#include <cmath>
#include <memory>
#include <unordered_map>
#include <vector>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include "generated/live_kf_constants.h"
#include "rednose/helpers/ekf_sym.h"
#define EARTH_GM 3.986005e14 // m^3/s^2 (gravitational constant * mass of earth)
using namespace EKFS;
Eigen::Map<Eigen::VectorXd> get_mapvec(const Eigen::VectorXd &vec);
Eigen::Map<MatrixXdr> get_mapmat(const MatrixXdr &mat);
std::vector<Eigen::Map<Eigen::VectorXd>> get_vec_mapvec(const std::vector<Eigen::VectorXd> &vec_vec);
std::vector<Eigen::Map<MatrixXdr>> get_vec_mapmat(const std::vector<MatrixXdr> &mat_vec);
class LiveKalman {
public:
LiveKalman();
void init_state(const Eigen::VectorXd &state, const Eigen::VectorXd &covs_diag, double filter_time);
void init_state(const Eigen::VectorXd &state, const MatrixXdr &covs, double filter_time);
void init_state(const Eigen::VectorXd &state, double filter_time);
Eigen::VectorXd get_x();
MatrixXdr get_P();
double get_filter_time();
std::vector<MatrixXdr> get_R(int kind, int n);
std::optional<Estimate> predict_and_observe(double t, int kind, const std::vector<Eigen::VectorXd> &meas, std::vector<MatrixXdr> R = {});
std::optional<Estimate> predict_and_update_odo_speed(std::vector<Eigen::VectorXd> speed, double t, int kind);
std::optional<Estimate> predict_and_update_odo_trans(std::vector<Eigen::VectorXd> trans, double t, int kind);
std::optional<Estimate> predict_and_update_odo_rot(std::vector<Eigen::VectorXd> rot, double t, int kind);
void predict(double t);
const Eigen::VectorXd &get_initial_x();
const MatrixXdr &get_initial_P();
const MatrixXdr &get_fake_gps_pos_cov();
const MatrixXdr &get_fake_gps_vel_cov();
const MatrixXdr &get_reset_orientation_P();
MatrixXdr H(const Eigen::VectorXd &in);
private:
std::string name = "live";
std::shared_ptr<EKFSym> filter;
int dim_state;
int dim_state_err;
Eigen::VectorXd initial_x;
MatrixXdr initial_P;
MatrixXdr fake_gps_pos_cov;
MatrixXdr fake_gps_vel_cov;
MatrixXdr reset_orientation_P;
MatrixXdr Q; // process noise
std::unordered_map<int, MatrixXdr> obs_noise;
};
@@ -1,242 +0,0 @@
#!/usr/bin/env python3
import sys
import os
import numpy as np
from openpilot.sunnypilot.selfdrive.locationd.models.constants import ObservationKind
import sympy as sp
import inspect
from rednose.helpers.sympy_helpers import euler_rotate, quat_matrix_r, quat_rotate
from rednose.helpers.ekf_sym import gen_code
EARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth)
def numpy2eigenstring(arr):
assert(len(arr.shape) == 1)
arr_str = np.array2string(arr, precision=20, separator=',')[1:-1].replace(' ', '').replace('\n', '')
return f"(Eigen::VectorXd({len(arr)}) << {arr_str}).finished()"
class States:
ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters
ECEF_ORIENTATION = slice(3, 7) # quat for pose of phone in ecef
ECEF_VELOCITY = slice(7, 10) # ecef velocity in m/s
ANGULAR_VELOCITY = slice(10, 13) # roll, pitch and yaw rates in device frame in radians/s
GYRO_BIAS = slice(13, 16) # roll, pitch and yaw biases
ACCELERATION = slice(16, 19) # Acceleration in device frame in m/s**2
ACC_BIAS = slice(19, 22) # Acceletometer bias in m/s**2
# Error-state has different slices because it is an ESKF
ECEF_POS_ERR = slice(0, 3)
ECEF_ORIENTATION_ERR = slice(3, 6) # euler angles for orientation error
ECEF_VELOCITY_ERR = slice(6, 9)
ANGULAR_VELOCITY_ERR = slice(9, 12)
GYRO_BIAS_ERR = slice(12, 15)
ACCELERATION_ERR = slice(15, 18)
ACC_BIAS_ERR = slice(18, 21)
class LiveKalman:
name = 'live'
initial_x = np.array([3.88e6, -3.37e6, 3.76e6,
0.42254641, -0.31238054, -0.83602975, -0.15788347, # NED [0,0,0] -> ECEF Quat
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0])
# state covariance
initial_P_diag = np.array([10**2, 10**2, 10**2,
0.01**2, 0.01**2, 0.01**2,
10**2, 10**2, 10**2,
1**2, 1**2, 1**2,
1**2, 1**2, 1**2,
100**2, 100**2, 100**2,
0.01**2, 0.01**2, 0.01**2])
# state covariance when resetting midway in a segment
reset_orientation_diag = np.array([1**2, 1**2, 1**2])
# fake observation covariance, to ensure the uncertainty estimate of the filter is under control
fake_gps_pos_cov_diag = np.array([1000**2, 1000**2, 1000**2])
fake_gps_vel_cov_diag = np.array([10**2, 10**2, 10**2])
# process noise
Q_diag = np.array([0.03**2, 0.03**2, 0.03**2,
0.001**2, 0.001**2, 0.001**2,
0.01**2, 0.01**2, 0.01**2,
0.1**2, 0.1**2, 0.1**2,
(0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2,
3**2, 3**2, 3**2,
0.005**2, 0.005**2, 0.005**2])
obs_noise_diag = {ObservationKind.PHONE_GYRO: np.array([0.025**2, 0.025**2, 0.025**2]),
ObservationKind.PHONE_ACCEL: np.array([.5**2, .5**2, .5**2]),
ObservationKind.CAMERA_ODO_ROTATION: np.array([0.05**2, 0.05**2, 0.05**2]),
ObservationKind.NO_ROT: np.array([0.005**2, 0.005**2, 0.005**2]),
ObservationKind.NO_ACCEL: np.array([0.05**2, 0.05**2, 0.05**2]),
ObservationKind.ECEF_POS: np.array([5**2, 5**2, 5**2]),
ObservationKind.ECEF_VEL: np.array([.5**2, .5**2, .5**2]),
ObservationKind.ECEF_ORIENTATION_FROM_GPS: np.array([.2**2, .2**2, .2**2, .2**2])}
@staticmethod
def generate_code(generated_dir):
name = LiveKalman.name
dim_state = LiveKalman.initial_x.shape[0]
dim_state_err = LiveKalman.initial_P_diag.shape[0]
state_sym = sp.MatrixSymbol('state', dim_state, 1)
state = sp.Matrix(state_sym)
x, y, z = state[States.ECEF_POS, :]
q = state[States.ECEF_ORIENTATION, :]
v = state[States.ECEF_VELOCITY, :]
vx, vy, vz = v
omega = state[States.ANGULAR_VELOCITY, :]
vroll, vpitch, vyaw = omega
roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :]
acceleration = state[States.ACCELERATION, :]
acc_bias = state[States.ACC_BIAS, :]
dt = sp.Symbol('dt')
# calibration and attitude rotation matrices
quat_rot = quat_rotate(*q)
# Got the quat predict equations from here
# A New Quaternion-Based Kalman Filter for
# Real-Time Attitude Estimation Using the Two-Step
# Geometrically-Intuitive Correction Algorithm
A = 0.5 * sp.Matrix([[0, -vroll, -vpitch, -vyaw],
[vroll, 0, vyaw, -vpitch],
[vpitch, -vyaw, 0, vroll],
[vyaw, vpitch, -vroll, 0]])
q_dot = A * q
# Time derivative of the state as a function of state
state_dot = sp.Matrix(np.zeros((dim_state, 1)))
state_dot[States.ECEF_POS, :] = v
state_dot[States.ECEF_ORIENTATION, :] = q_dot
state_dot[States.ECEF_VELOCITY, 0] = quat_rot * acceleration
# Basic descretization, 1st order intergrator
# Can be pretty bad if dt is big
f_sym = state + dt * state_dot
state_err_sym = sp.MatrixSymbol('state_err', dim_state_err, 1)
state_err = sp.Matrix(state_err_sym)
quat_err = state_err[States.ECEF_ORIENTATION_ERR, :]
v_err = state_err[States.ECEF_VELOCITY_ERR, :]
omega_err = state_err[States.ANGULAR_VELOCITY_ERR, :]
acceleration_err = state_err[States.ACCELERATION_ERR, :]
# Time derivative of the state error as a function of state error and state
quat_err_matrix = euler_rotate(quat_err[0], quat_err[1], quat_err[2])
q_err_dot = quat_err_matrix * quat_rot * (omega + omega_err)
state_err_dot = sp.Matrix(np.zeros((dim_state_err, 1)))
state_err_dot[States.ECEF_POS_ERR, :] = v_err
state_err_dot[States.ECEF_ORIENTATION_ERR, :] = q_err_dot
state_err_dot[States.ECEF_VELOCITY_ERR, :] = quat_err_matrix * quat_rot * (acceleration + acceleration_err)
f_err_sym = state_err + dt * state_err_dot
# Observation matrix modifier
H_mod_sym = sp.Matrix(np.zeros((dim_state, dim_state_err)))
H_mod_sym[States.ECEF_POS, States.ECEF_POS_ERR] = np.eye(States.ECEF_POS.stop - States.ECEF_POS.start)
H_mod_sym[States.ECEF_ORIENTATION, States.ECEF_ORIENTATION_ERR] = 0.5 * quat_matrix_r(state[3:7])[:, 1:]
H_mod_sym[States.ECEF_ORIENTATION.stop:, States.ECEF_ORIENTATION_ERR.stop:] = np.eye(dim_state - States.ECEF_ORIENTATION.stop)
# these error functions are defined so that say there
# is a nominal x and true x:
# true x = err_function(nominal x, delta x)
# delta x = inv_err_function(nominal x, true x)
nom_x = sp.MatrixSymbol('nom_x', dim_state, 1)
true_x = sp.MatrixSymbol('true_x', dim_state, 1)
delta_x = sp.MatrixSymbol('delta_x', dim_state_err, 1)
err_function_sym = sp.Matrix(np.zeros((dim_state, 1)))
delta_quat = sp.Matrix(np.ones(4))
delta_quat[1:, :] = sp.Matrix(0.5 * delta_x[States.ECEF_ORIENTATION_ERR, :])
err_function_sym[States.ECEF_POS, :] = sp.Matrix(nom_x[States.ECEF_POS, :] + delta_x[States.ECEF_POS_ERR, :])
err_function_sym[States.ECEF_ORIENTATION, 0] = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]) * delta_quat
err_function_sym[States.ECEF_ORIENTATION.stop:, :] = sp.Matrix(nom_x[States.ECEF_ORIENTATION.stop:, :] + delta_x[States.ECEF_ORIENTATION_ERR.stop:, :])
inv_err_function_sym = sp.Matrix(np.zeros((dim_state_err, 1)))
inv_err_function_sym[States.ECEF_POS_ERR, 0] = sp.Matrix(-nom_x[States.ECEF_POS, 0] + true_x[States.ECEF_POS, 0])
delta_quat = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]).T * true_x[States.ECEF_ORIENTATION, 0]
inv_err_function_sym[States.ECEF_ORIENTATION_ERR, 0] = sp.Matrix(2 * delta_quat[1:])
inv_err_function_sym[States.ECEF_ORIENTATION_ERR.stop:, 0] = sp.Matrix(-nom_x[States.ECEF_ORIENTATION.stop:, 0] + true_x[States.ECEF_ORIENTATION.stop:, 0])
eskf_params = [[err_function_sym, nom_x, delta_x],
[inv_err_function_sym, nom_x, true_x],
H_mod_sym, f_err_sym, state_err_sym]
#
# Observation functions
#
h_gyro_sym = sp.Matrix([
vroll + roll_bias,
vpitch + pitch_bias,
vyaw + yaw_bias])
pos = sp.Matrix([x, y, z])
gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2)**(3.0 / 2.0))) * pos)
h_acc_sym = (gravity + acceleration + acc_bias)
h_acc_stationary_sym = acceleration
h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw])
h_pos_sym = sp.Matrix([x, y, z])
h_vel_sym = sp.Matrix([vx, vy, vz])
h_orientation_sym = q
h_relative_motion = sp.Matrix(quat_rot.T * v)
obs_eqs = [[h_gyro_sym, ObservationKind.PHONE_GYRO, None],
[h_phone_rot_sym, ObservationKind.NO_ROT, None],
[h_acc_sym, ObservationKind.PHONE_ACCEL, None],
[h_pos_sym, ObservationKind.ECEF_POS, None],
[h_vel_sym, ObservationKind.ECEF_VEL, None],
[h_orientation_sym, ObservationKind.ECEF_ORIENTATION_FROM_GPS, None],
[h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None],
[h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None],
[h_acc_stationary_sym, ObservationKind.NO_ACCEL, None]]
# this returns a sympy routine for the jacobian of the observation function of the local vel
in_vec = sp.MatrixSymbol('in_vec', 6, 1) # roll, pitch, yaw, vx, vy, vz
h = euler_rotate(in_vec[0], in_vec[1], in_vec[2]).T * (sp.Matrix([in_vec[3], in_vec[4], in_vec[5]]))
extra_routines = [('H', h.jacobian(in_vec), [in_vec])]
gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params, extra_routines=extra_routines)
# write constants to extra header file for use in cpp
live_kf_header = "#pragma once\n\n"
live_kf_header += "#include <unordered_map>\n"
live_kf_header += "#include <eigen3/Eigen/Dense>\n\n"
for state, slc in inspect.getmembers(States, lambda x: isinstance(x, slice)):
assert(slc.step is None) # unsupported
live_kf_header += f'#define STATE_{state}_START {slc.start}\n'
live_kf_header += f'#define STATE_{state}_END {slc.stop}\n'
live_kf_header += f'#define STATE_{state}_LEN {slc.stop - slc.start}\n'
live_kf_header += "\n"
for kind, val in inspect.getmembers(ObservationKind, lambda x: isinstance(x, int)):
live_kf_header += f'#define OBSERVATION_{kind} {val}\n'
live_kf_header += "\n"
live_kf_header += f"static const Eigen::VectorXd live_initial_x = {numpy2eigenstring(LiveKalman.initial_x)};\n"
live_kf_header += f"static const Eigen::VectorXd live_initial_P_diag = {numpy2eigenstring(LiveKalman.initial_P_diag)};\n"
live_kf_header += f"static const Eigen::VectorXd live_fake_gps_pos_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_pos_cov_diag)};\n"
live_kf_header += f"static const Eigen::VectorXd live_fake_gps_vel_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_vel_cov_diag)};\n"
live_kf_header += f"static const Eigen::VectorXd live_reset_orientation_diag = {numpy2eigenstring(LiveKalman.reset_orientation_diag)};\n"
live_kf_header += f"static const Eigen::VectorXd live_Q_diag = {numpy2eigenstring(LiveKalman.Q_diag)};\n"
live_kf_header += "static const std::unordered_map<int, Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> live_obs_noise_diag = {\n"
for kind, noise in LiveKalman.obs_noise_diag.items():
live_kf_header += f" {{ {kind}, {numpy2eigenstring(noise)} }},\n"
live_kf_header += "};\n\n"
open(os.path.join(generated_dir, "live_kf_constants.h"), 'w').write(live_kf_header)
if __name__ == "__main__":
generated_dir = sys.argv[2]
LiveKalman.generate_code(generated_dir)
@@ -1 +0,0 @@
out/
@@ -0,0 +1,73 @@
"""
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
from types import SimpleNamespace
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot.selfdrive.locationd.gps_fuser import EARTH_RADIUS, GPS_LATENCY, GpsFuser
LAT0, LON0 = 39.0, -77.0
LATENCY = GPS_LATENCY['gpsLocation']
def fix(north, east, speed=30.0, bearing=90.0, h_acc=0.0, v_acc=1.5):
return SimpleNamespace(latitude=LAT0 + math.degrees(north / EARTH_RADIUS),
longitude=LON0 + math.degrees(east / (EARTH_RADIUS * math.cos(math.radians(LAT0)))),
speed=speed, bearingDeg=bearing, horizontalAccuracy=h_acc, verticalAccuracy=v_acc,
speedAccuracy=0.3, bearingAccuracyDeg=0.5, hasFix=True)
def position(f: GpsFuser) -> tuple[float, float]:
north = math.radians(f.lat - LAT0) * EARTH_RADIUS
east = math.radians(f.lon - LON0) * EARTH_RADIUS * math.cos(math.radians(LAT0))
return north, east
class TestGpsFuser(OpenpilotTestCase):
def drive(self, f, seconds, speed=30.0, start=0.0, gps=lambda t, true_east: fix(0.0, true_east)):
t = start
while t < start + seconds:
t = round(t + 0.05, 2)
f.predict(t, speed, 0.0)
if abs(t - round(t)) < 1e-6:
f.update_gps(t, gps(t, speed * (t - LATENCY)), LATENCY)
return t
def test_compensates_latency(self):
f = GpsFuser()
t = self.drive(f, 30)
self.assertTrue(f.valid)
north, east = position(f)
self.assertAlmostEqual(east, 30.0 * t, delta=3.0)
self.assertAlmostEqual(north, 0.0, delta=1.0)
def test_rejects_single_jump(self):
f = GpsFuser()
t = self.drive(f, 20)
f.predict(t + 0.05, 30.0, 0.0)
f.update_gps(t + 0.05, fix(40.0, 30.0 * (t + 0.05 - LATENCY)), LATENCY)
self.assertAlmostEqual(position(f)[0], 0.0, delta=2.0)
def test_follows_persistent_offset(self):
f = GpsFuser()
t = self.drive(f, 20)
self.drive(f, 10, start=t, gps=lambda _, e: fix(150.0, e))
self.assertAlmostEqual(position(f)[0], 150.0, delta=3.0)
def test_ignores_bearing_when_slow(self):
f = GpsFuser()
t = self.drive(f, 20)
self.drive(f, 5, speed=1.0, start=t, gps=lambda _, e: fix(0.0, e, speed=1.0, bearing=270.0))
self.assertAlmostEqual(math.degrees(f.heading), 90.0, delta=1.0)
def test_invalid_after_long_outage(self):
f = GpsFuser()
t = self.drive(f, 20)
self.drive(f, 120, start=t, gps=lambda _, e: SimpleNamespace(hasFix=False, horizontalAccuracy=0.0, verticalAccuracy=0.0,
speedAccuracy=0.0, latitude=0.0, longitude=0.0))
self.assertFalse(f.valid)
@@ -1,96 +0,0 @@
import platform
import unittest
import json
import random
import time
import capnp
import openpilot.cereal.messaging as messaging
from openpilot.cereal.services import SERVICE_LIST
from openpilot.common.params import Params
from openpilot.common.transformations.coordinates import ecef2geodetic
from openpilot.system.manager.process_config import managed_processes
from openpilot.common.test import OpenpilotTestCase
@unittest.skipIf(platform.system() == 'Darwin', "msgq unsupported on macOS")
class TestLocationdProc(OpenpilotTestCase):
LLD_MSGS = ['gpsLocationExternal', 'cameraOdometry', 'carState', 'extrinsicsCalibration',
'accelerometer', 'gyroscope']
def setup_method(self):
self.pm = messaging.PubMaster(self.LLD_MSGS)
self.params = Params()
self.params.put_bool("UbloxAvailable", True)
managed_processes['locationd_llk'].start()
def teardown_method(self):
managed_processes['locationd_llk'].stop()
def get_msg(self, name, t):
try:
msg = messaging.new_message(name)
except capnp.lib.capnp.KjException:
msg = messaging.new_message(name, 0)
if name == "gpsLocationExternal":
msg.gpsLocationExternal.flags = 1
msg.gpsLocationExternal.hasFix = True
msg.gpsLocationExternal.verticalAccuracy = 1.0
msg.gpsLocationExternal.speedAccuracy = 1.0
msg.gpsLocationExternal.bearingAccuracyDeg = 1.0
msg.gpsLocationExternal.vNED = [0.0, 0.0, 0.0]
msg.gpsLocationExternal.latitude = float(self.lat)
msg.gpsLocationExternal.longitude = float(self.lon)
msg.gpsLocationExternal.unixTimestampMillis = t * 1e6
msg.gpsLocationExternal.altitude = float(self.alt)
#if name == "gnssMeasurements":
# msg.gnssMeasurements.measTime = t
# msg.gnssMeasurements.positionECEF.value = [self.x , self.y, self.z]
# msg.gnssMeasurements.positionECEF.std = [0,0,0]
# msg.gnssMeasurements.positionECEF.valid = True
# msg.gnssMeasurements.velocityECEF.value = []
# msg.gnssMeasurements.velocityECEF.std = [0,0,0]
# msg.gnssMeasurements.velocityECEF.valid = True
elif name == 'cameraOdometry':
msg.cameraOdometry.rot = [0.0, 0.0, 0.0]
msg.cameraOdometry.rotStd = [0.0, 0.0, 0.0]
msg.cameraOdometry.trans = [0.0, 0.0, 0.0]
msg.cameraOdometry.transStd = [0.0, 0.0, 0.0]
msg.logMonoTime = t
msg.valid = True
return msg
def test_params_gps(self):
random.seed(123489234)
self.params.remove('LastGPSPositionLLK')
self.x = -2710700 + (random.random() * 1e5)
self.y = -4280600 + (random.random() * 1e5)
self.z = 3850300 + (random.random() * 1e5)
self.lat, self.lon, self.alt = ecef2geodetic([self.x, self.y, self.z])
# get fake messages at the correct frequency, listed in services.py
msgs = []
for sec in range(65):
for name in self.LLD_MSGS:
for j in range(int(SERVICE_LIST[name].frequency)):
msgs.append(self.get_msg(name, int((sec + j / SERVICE_LIST[name].frequency) * 1e9)))
for msg in sorted(msgs, key=lambda x: x.logMonoTime):
self.pm.send(msg.which(), msg)
if msg.which() == "cameraOdometry":
self.pm.wait_for_readers_to_update(msg.which(), timeout=1, dt=0.005)
for _ in range(50):
val = self.params.get('LastGPSPositionLLK')
if val is not None:
break
time.sleep(0.1)
self.assertIsNotNone(val, "LastGPSPositionLLK not written within 5s")
lastGPS = json.loads(val)
self.assertAlmostEqual(lastGPS['latitude'], self.lat, delta=0.001)
self.assertAlmostEqual(lastGPS['longitude'], self.lon, delta=0.001)
self.assertAlmostEqual(lastGPS['altitude'], self.alt, delta=0.001)
@@ -0,0 +1,25 @@
"""
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")
@@ -44,18 +44,7 @@ DISALLOW_LOG_UPLOAD = threading.Event()
params = Params()
# 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
}
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
@@ -166,7 +155,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 keys
return [key for key in keys if not is_local_param(key)]
@dispatcher.add_method
@@ -208,7 +197,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]
param_keys_validated = [key for key in params_keys if key in available_keys and not is_local_param(key)]
params_dict: dict[str, list[dict[str, str | bool | int]]] = {"params": []}
for key in param_keys_validated:
value = get_param_as_byte(key)
@@ -238,7 +227,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:
if key in BLOCKED_PARAMS or is_local_param(key):
cloudlog.warning(f"sunnylinkd.saveParams.blocked: Attempted to modify blocked parameter '{key}'")
continue
@@ -58,3 +58,24 @@ 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"]
+113
View File
@@ -0,0 +1,113 @@
"""
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)
+39
View File
@@ -0,0 +1,39 @@
"""
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)
+141
View File
@@ -0,0 +1,141 @@
"""
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 = 16384
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
+125
View File
@@ -0,0 +1,125 @@
"""
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)
+176
View File
@@ -0,0 +1,176 @@
"""
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 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 == "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)}
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")
self._check_keys(keys)
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 _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}
+325
View File
@@ -0,0 +1,325 @@
"""
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
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 = 0x30, 0x31, 0x32, 0x33, 0x40
ERR_NO_WINDOW, ERR_BUSY, ERR_VERSION, ERR_WRONG_CODE, ERR_WINDOW_CLOSED, ERR_TIMEOUT, ERR_UNKNOWN_PHONE = 1, 2, 3, 4, 5, 6, 8
ALLOW, DENY, NO_ANSWER = 1, 2, 3
GRANT_ADDED, GRANT_REFUSED = 1, 2 # 3 reserved
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
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)
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))
return acts
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)
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 _drop(self, lk: _Link) -> list[Action]:
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()
@@ -0,0 +1,406 @@
"""
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 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):
# all three run on the run() thread
self._on_write = on_write # device path, value, mtu
self._on_disconnect = on_disconnect # device path
self._on_tick = on_tick
self._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._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):
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:
if time.monotonic() - self._last_reconcile >= RECONCILE_PERIOD:
self._last_reconcile = time.monotonic()
self._reconcile()
self._tick()
try:
self._dispatch(self._conn.receive(timeout=RECONCILE_PERIOD))
except TimeoutError:
pass
finally:
try:
self._teardown()
except Exception:
cloudlog.exception("bluetooth: teardown failed")
conn, self._conn = self._conn, None
conn.close()
self._set_connected(frozenset())
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._ready and adapter == self._adapter:
ifaces = objects[adapter]
# a restarted bluetoothd keeps the adapter powered but has no advertisement
if (_prop(ifaces, ADAPTER_IFACE, "Powered") and not _prop(ifaces, ADAPTER_IFACE, "Pairable", True) and
_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)
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:
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)
return self.bt
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()
@@ -0,0 +1,173 @@
"""
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
@@ -0,0 +1,94 @@
"""
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()
@@ -0,0 +1,163 @@
"""
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()
@@ -0,0 +1,111 @@
"""
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()
@@ -0,0 +1,626 @@
"""
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 phone.rpc("params.get", 0.0, {"keys": keys})["error"]["code"] == -32001
refused = phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "y", "BluetoothAllowed": False}})
assert refused["error"]["code"] == -32001
assert h.params.data.get("CarParamsSP") is None
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" " * 17000), 0.0)
assert not phone.connected
@@ -0,0 +1,669 @@
"""
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]
@@ -0,0 +1,269 @@
"""
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"
+3 -2
View File
@@ -184,8 +184,9 @@ procs += [
NativeProcess("mapd", Paths.mapd_root(), ["bash", "-c", f"{MAPD_PATH} > /dev/null 2>&1"], mapd_ready),
PythonProcess("mapd_manager", "openpilot.sunnypilot.mapd.mapd_manager", always_run),
# locationd
NativeProcess("locationd_llk", "openpilot/sunnypilot/selfdrive/locationd", ["./locationd"], only_onroad),
PythonProcess("gps_fuser", "openpilot.sunnypilot.selfdrive.locationd.gps_fuser", only_onroad),
PythonProcess("bluetooth_manager", "openpilot.sunnypilot.system.bluetooth_manager", always_run, enabled=not PC),
]
if os.path.exists("../../sunnypilot/sunnylink/uploader.py"):
+4
View File
@@ -302,6 +302,10 @@ class WifiManager:
wifi_state = self._wifi_state
return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTED else None
@property
def tethering_ssid(self) -> str:
return self._tethering_ssid
@property
def tethering_password(self) -> str:
return self._tethering_password