Compare commits

..

20 Commits

Author SHA1 Message Date
nayan e67f48ddb9 add params.metadata BLE RPC and raise session cap to 64 KiB 2026-11-29 14:10:33 -05:00
nayan 0637e1f6f9 hud curvature: show futher ahead 2026-11-29 10:28:16 -05:00
nayan 95b45d23cb bump opendbc 2026-11-29 09:49:57 -05:00
nayan ca1f0ec67f bump opendbc 2026-11-29 09:19:17 -05:00
nayan 01c46b011a blendful: be more assertive in curves and remove zero dead spots
Use lane curvature for the curve gate, raise the curve plan share to 0.65
when no maneuver is active, recover trust faster in curves, and smooth
curve entry based on the lane fit. Replace the trust-fall sign clip with
a bounded dk rate limit so corrections can grow or reverse instead of
latching at zero, and cap the added curvature.
2026-11-29 09:17:53 -05:00
nayan c9adedad05 soundd/micd: recover from audio device failures without blocking engagement
micd and soundd can fail to start or go silent in the field
(commaai/openpilot#36088): a transient portaudio/mic device failure leaves
micd broadcasting valid=True soundPressure flatlined at zero, soundd decays
its ambient-volume filter to MIN_VOLUME, and manager keeps the dead process
marked shouldBeRunning until the device is power cycled — blocking engage
with "micd soundd process not running".

- micd: mark soundPressure/rawAudioData invalid while the stream is down,
  automatically re-open the stream (portaudio reinit + InputStream retry),
  and flag input overflow status in rawAudioData validity
- soundd: only adapt volume from valid soundPressure; freeze instead of
  decaying to silence when mic data goes stale, and log the transition
- manager: add opt-in supervision to Python/Native processes so a dead
  process is reaped and restarted on the next manager loop instead of
  lingering dead; enable it for micd and soundd

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-29 09:17:53 -05:00
nayan d76f5ea33a fix manager on mac 2026-11-29 09:17:53 -05:00
nayan ec3aa64d25 robo-ui: more expressive, better sound control 2026-11-29 09:17:53 -05:00
nayan f39d013f1a robo-ui: tune centrifugal turn squish, boost cabin music detection, and raise robotic audio audibility 2026-11-29 09:17:52 -05:00
nayan 28fc25d84b robo-ui: use standalone get_alert and guard gyroscope union in robotic UI 2026-11-29 09:17:51 -05:00
nayan 155f5b4936 robo-ui: migrate robotic UI and connect_phone from pyray to raylib_nb 2026-11-29 09:17:51 -05:00
nayan e05413ac75 radar tracks 2026-11-29 09:17:48 -05:00
nayan be2a26e487 agnos-20.6-bluetooth 2026-11-29 09:16:11 -05:00
nayan b2838ae561 bump opendbc 2026-11-29 09:14:03 -05:00
nayan ad1ab57e00 robo-ui: add optional robotic companion onroad UI and voice pack 2026-11-29 09:14:00 -05:00
nayan e703a4feda esc long tuning 2026-11-29 09:14:00 -05:00
nayan 746c9d8bbb pidd 2026-11-29 09:14:00 -05:00
nayan c129a8b017 use curvature from model 2026-11-29 09:14:00 -05:00
nayan d8bcadba27 hkg-adas-ecu-drv-interceptor-sim-new 2026-11-29 09:13:59 -05:00
nayan 1a6ba6b4ef models v26 2026-11-29 09:13:59 -05:00
86 changed files with 12525 additions and 202 deletions
+1
View File
@@ -2,5 +2,6 @@ Wen
REGIST
PullRequest
cancelled
indeces
FOF
NoO
+1
View File
@@ -149,6 +149,7 @@ jobs:
process_replay:
name: process replay
if: false #process replay disabled for angle steering until we are ready to merge it
runs-on: ${{
(github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') ||
+7
View File
@@ -21,5 +21,12 @@
</clean>
</configuration>
</target>
<target id="f2590b2b-9b93-49f9-8510-da3f3724a2ae" name="replay" defaultType="TOOL">
<configuration id="d475264f-6f4c-4092-9b4e-6773309f38b7" name="replay" toolchainName="Default">
<build type="TOOL">
<tool actionId="Tool_External Tools_uv build tools replay" />
</build>
</configuration>
</target>
</component>
</project>
+7
View File
@@ -20,4 +20,11 @@
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
<tool name="uv build tools replay" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true">
<exec>
<option name="COMMAND" value="bash" />
<option name="PARAMETERS" value="-c &quot;source .venv/bin/activate &amp;&amp; scons -u -j$(nproc) tools/replay/&quot;" />
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
</toolSet>
+1 -1
View File
@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="sunnypilot" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<envs>
<env name="QT_DBL_CLICK_DIST" value="150" />
</envs>
+27
View File
@@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Debug Route Controls" type="PythonConfigurationType" factoryName="Python">
<module name="openpilot-special" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
<env name="FINGERPRINT" value="KIA_EV9" />
<env name="SKIP_FW_QUERY" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/selfdrive/car" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/selfdrive/car/card.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="true" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Replay for controls + ui" type="Multirun" separateTabs="false" reuseTabsWithFailures="false" startOneByOne="true" markFailedProcess="true" hideSuccessProcess="false" delayTime="0.0">
<runConfiguration name="replay for controls" type="Native Application" />
<runConfiguration name="Build Debug" type="Custom Build Application" />
<method v="2" />
</configuration>
</component>
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="replay for controls" type="CLionNativeAppRunConfigurationType" focusToolWindowBeforeRun="true" PROGRAM_PARAMS="&quot;$Prompt$&quot; --block &quot;sendcan,carState,carParams,carOutput,liveTracks,carParamsSP,carStateSP,bookmarkButton&quot;" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="true" WORKING_DIR="file://$ProjectFileDir$/tools/replay" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="replay" CONFIG_NAME="replay" version="1" RUN_PATH="replay">
<method v="2">
<option name="CLION.COMPOUND.BUILD" enabled="true" />
</method>
</configuration>
</component>
+1 -1
View File
@@ -7,7 +7,7 @@ export OPENBLAS_NUM_THREADS=1
export VECLIB_MAXIMUM_THREADS=1
if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="20.6-2fac79a"
export AGNOS_VERSION="20.6-994bc1b"
fi
export STAGING_ROOT="/data/safe_staging"
+3
View File
@@ -360,6 +360,7 @@ struct OnroadEventSP @0xda96579883444c35 {
e2eChime @23;
laneChangeRoadEdge @24;
bigModelReady @25;
stockSteerIntervention @26;
}
}
@@ -389,6 +390,7 @@ struct CarControlSP @0xa5cd762cd951a455 {
leadOne @2 :LeadData;
leadTwo @3 :LeadData;
intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement;
pathCurvature @5 :Float32;
struct Param {
key @0 :Text;
@@ -453,6 +455,7 @@ struct BackupManagerSP @0xf98d843bfd7004a3 {
struct CarStateSP @0xb86e6369214c01c8 {
speedLimit @0 :Float32;
stockSteerIntervention @1 :Bool;
}
struct LiveMapDataSP @0xf416ec09499d9d19 {
+10 -10
View File
@@ -56,28 +56,28 @@
},
{
"name": "boot",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10.img.xz",
"hash": "549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10",
"hash_raw": "549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4.img.xz",
"hash": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
"hash_raw": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
"size": 47855616,
"sparse": false,
"full_check": true,
"has_ab": true,
"ondevice_hash": "7d0a8ec435d9840fa010b2661fd3588993b756e6d09501b934573d3c89896b3f"
"ondevice_hash": "f456444afa8d821c5e482240af5bcfb717d8c840d16dd98100941e5f665eefa1"
},
{
"name": "system",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016.img.xz",
"hash": "1b4a360c5bd0ba30c50dbcf7d6a180b602fe7ff20989aab1d4252661fa28be6e",
"hash_raw": "a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img.xz",
"hash": "bd3c6cc917f8fdd74c1248324fa1518b091a8e810d1466c5e8fea9cf1e23f6d0",
"hash_raw": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
"size": 2147483648,
"sparse": true,
"full_check": false,
"has_ab": true,
"ondevice_hash": "5bbe888093d4b5468fe2707723bc519f0334dbc9f236281602811af4534ff7c6",
"ondevice_hash": "71814ad7b2ab4344790f660d463a1dc12142a8cf6a31dfabf4c43bd8545f152d",
"alt": {
"hash": "a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016.img",
"hash": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img",
"size": 2147483648
}
}
@@ -339,28 +339,28 @@
},
{
"name": "boot",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10.img.xz",
"hash": "549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10",
"hash_raw": "549c739c15904d887619440f21c5df8849b8b545d5a9eab118f967a40856cc10",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/boot-7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4.img.xz",
"hash": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
"hash_raw": "7da6f3e3defcc90c599d6a941df0240555d687d0d0c9df83a3e186b83424a0e4",
"size": 47855616,
"sparse": false,
"full_check": true,
"has_ab": true,
"ondevice_hash": "7d0a8ec435d9840fa010b2661fd3588993b756e6d09501b934573d3c89896b3f"
"ondevice_hash": "f456444afa8d821c5e482240af5bcfb717d8c840d16dd98100941e5f665eefa1"
},
{
"name": "system",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016.img.xz",
"hash": "1b4a360c5bd0ba30c50dbcf7d6a180b602fe7ff20989aab1d4252661fa28be6e",
"hash_raw": "a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img.xz",
"hash": "bd3c6cc917f8fdd74c1248324fa1518b091a8e810d1466c5e8fea9cf1e23f6d0",
"hash_raw": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
"size": 2147483648,
"sparse": true,
"full_check": false,
"has_ab": true,
"ondevice_hash": "5bbe888093d4b5468fe2707723bc519f0334dbc9f236281602811af4534ff7c6",
"ondevice_hash": "71814ad7b2ab4344790f660d463a1dc12142a8cf6a31dfabf4c43bd8545f152d",
"alt": {
"hash": "a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-a228d9f809d80ac733c6c86b3bf0428cc8455c03ce4b8718610978413a3e7016.img",
"hash": "cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a",
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-20/system-cb1d8ac3c8c8917e584d4a37a78e80dfb614ceed626fdd91f8125ee54baeb97a.img",
"size": 2147483648
}
}
+3 -1
View File
@@ -182,6 +182,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LastGPSPositionFused", {PERSISTENT, STRING}},
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
{"MiciRoboticUI", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
{"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}},
{"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}},
@@ -192,6 +193,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}},
{"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}},
{"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RadarTracks", {PERSISTENT | BACKUP, INT, "0"}},
{"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RoadEdgeLaneChangeEnabled", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}},
@@ -245,7 +247,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"BackupManager_RestoreVersion", {PERSISTENT, STRING}},
// sunnypilot car specific params
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}},
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, BOOL, "0"}},
{"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}},
{"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}},
{"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}},
+2
View File
@@ -37,6 +37,8 @@ SP_BRANCH_MIGRATIONS = {
("tizi", "release3-staging"): "release-tizi-staging",
("mici", "release3"): "release-mici",
("mici", "release3-staging"): "release-mici-staging",
("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici",
("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt"
}
BUILD_METADATA_FILENAME = "build.json"
+17
View File
@@ -180,6 +180,8 @@ class Car:
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
self._applied_radar_tracks = getattr(self.RI, "radar_mode", self.radar_tracks)
# card is driven by can recv, expected at 100Hz
self.rk = Ratekeeper(100, print_delay_threshold=None)
@@ -194,6 +196,8 @@ class Car:
CS, CS_SP = self.CI.update(can_list)
CS_SP = convert_to_capnp(CS_SP)
self._update_radar_tracks()
# Update radar tracks from CAN
RD: structs.RadarDataT | None = self.RI.update(can_list)
@@ -220,6 +224,18 @@ class Car:
return CS, CS_SP, RD
def _update_radar_tracks(self) -> None:
if self.CP.brand != "hyundai" or self.radar_tracks == self._applied_radar_tracks:
return
if self.RI.set_radar_mode(self.radar_tracks):
self.CP_SP_capnp = convert_to_capnp(self.CP_SP)
cp_sp_bytes = self.CP_SP_capnp.to_bytes()
self.params.put("CarParamsSP", cp_sp_bytes)
self.params.put("CarParamsSPCache", cp_sp_bytes)
self.params.put("CarParamsSPPersistent", cp_sp_bytes)
self._applied_radar_tracks = self.radar_tracks
def state_publish(self, CS: car.CarState, CS_SP: custom.CarStateSP, RD: structs.RadarDataT | None):
"""carState and carParams publish loop"""
@@ -299,6 +315,7 @@ class Car:
while not evt.is_set():
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
# sunnypilot
self.v_cruise_helper.read_custom_set_speed_params()
+14 -2
View File
@@ -26,6 +26,8 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum
# stationary qualification parameters
V_EGO_STATIONARY = 4. # no stationary object flag below this speed
DBC_MOTION_STATIONARY = 1
DBC_MOTION_MOVING = 2
RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame
@@ -191,8 +193,14 @@ def get_custom_yrel(CP: structs.CarParams, CP_SP: structs.CarParamsSP, lead_dict
return lead_dict
def radar_point_eligible_for_fusion(CP: structs.CarParams, CP_SP: structs.CarParamsSP,
point: car.RadarData.RadarPoint) -> bool:
use_dbc_motion = CP.brand == "hyundai" and CP_SP.flags & HyundaiFlagsSP.RADAR_FULL_RADAR
return not use_dbc_motion or point.motionState in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING)
class RadarD:
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParams, delay: float = 0.0):
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, delay: float = 0.0):
self.CP = CP
self.CP_SP = CP_SP
@@ -218,7 +226,11 @@ class RadarD:
self.v_ego_hist.append(self.v_ego)
self.last_v_ego_frame = sm.recv_frame['carState']
ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points}
ar_pts = {
pt.trackId: [pt.dRel, pt.yRel, pt.vRel]
for pt in rr.points
if radar_point_eligible_for_fusion(self.CP, self.CP_SP, pt)
}
# *** remove missing points from meta data ***
for ids in list(self.tracks.keys()):
+1 -7
View File
@@ -52,13 +52,7 @@ std::vector<std::string> PandaSafety::fetchCarParams() {
if (!params_.getBool("ControlsReady")) {
return {};
}
std::string car_params = params_.get("CarParams");
std::string car_params_sp = params_.get("CarParamsSP");
if (car_params.empty() || car_params_sp.empty()) {
return {};
}
return {car_params, car_params_sp};
return {params_.get("CarParams"), params_.get("CarParamsSP")};
}
// TODO-SP: Use structs instead of vector
@@ -100,7 +100,19 @@ class TogglesLayout(Widget):
icon="speed_limit.png"
)
self._radar_tracks_setting = None
self._toggles: dict[str, ListItem] = {}
if gui_app.sunnypilot_ui():
self._radar_tracks_setting = multiple_button_item(
lambda: tr("Radar Tracks"),
"",
buttons=[lambda: tr("Off"), lambda: tr("Lead Only"), lambda: tr("Full Radar")],
button_width=250,
callback=self._set_radar_tracks,
selected_index=self._params.get("RadarTracks", return_default=True),
)
self._toggles["RadarTracks"] = self._radar_tracks_setting
self._initial_cruise_speed = ListItem(
title=lambda: tr("Initial Max Speed"),
description=lambda: tr("Max speed when engaging openpilot. If you are already driving faster, your current speed is used. " +
@@ -169,6 +181,8 @@ class TogglesLayout(Widget):
# refresh toggles from params to mirror external changes
for param in self._toggle_defs:
self._toggles[param].action_item.set_state(self._params.get_bool(param))
if self._radar_tracks_setting is not None:
self._radar_tracks_setting.action_item.set_selected_button(self._params.get("RadarTracks", return_default=True))
# these toggles need restart, block while engaged
for toggle_def in self._toggle_defs:
@@ -188,3 +202,6 @@ class TogglesLayout(Widget):
def _set_longitudinal_personality(self, button_index: int):
self._params.put("LongitudinalPersonality", button_index, block=True)
def _set_radar_tracks(self, button_index: int):
self._params.put("RadarTracks", button_index, block=True)
+36 -9
View File
@@ -15,6 +15,7 @@ from openpilot.system.ui.lib.application import gui_app
if gui_app.sunnypilot_ui():
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.home import MiciHomeLayoutSP as MiciHomeLayout
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import RoboticOnroadView
ONROAD_DELAY = 2.5 # seconds
GREET_IGNITION_OFF_TIME = 60 * 60 # greet again when the car turns on after being off this long
@@ -37,23 +38,34 @@ class MiciMainLayout(Scroller):
self._alerts_layout = MiciOffroadAlerts()
self._settings_layout = SettingsLayout()
self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked)
self._robotic_onroad_layout = RoboticOnroadView(bookmark_callback=self._on_bookmark_clicked) if gui_app.sunnypilot_ui() else None
self._body_onroad_layout = BodyLayout()
self._prev_robotic_ui = bool(gui_app.sunnypilot_ui() and ui_state.mici_robotic_ui)
# Initialize widget rects
for widget in (self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout):
all_widgets = [self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
all_widgets.append(self._robotic_onroad_layout)
for widget in all_widgets:
# TODO: set parent rect and use it if never passed rect from render (like in Scroller)
widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
self._scroller.add_widgets([
scroller_widgets = [
self._home_layout,
self._car_onroad_layout,
self._body_onroad_layout,
])
]
if self._robotic_onroad_layout is not None:
scroller_widgets.append(self._robotic_onroad_layout)
scroller_widgets.append(self._body_onroad_layout)
self._scroller.add_widgets(scroller_widgets)
self._scroller.set_reset_scroll_at_show(False)
# Disable scrolling when onroad is interacting with bookmark
self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left())
self._scroller.set_scrolling_enabled(
lambda: not (self._car_onroad_layout.is_swiping_left() or
(self._robotic_onroad_layout is not None and self._robotic_onroad_layout.is_swiping_left()))
)
# Set callbacks
self._setup_callbacks()
@@ -72,7 +84,11 @@ class MiciMainLayout(Scroller):
@property
def _onroad_layout(self) -> Widget:
# For scroll_to
return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout
if ui_state.is_body:
return self._body_onroad_layout
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui:
return self._robotic_onroad_layout
return self._car_onroad_layout
def _setup_callbacks(self):
self._alerts_layout.set_pairing_callback(self._settings_layout.show_pairing)
@@ -82,7 +98,10 @@ class MiciMainLayout(Scroller):
alert_count_callback=self._alerts_layout.active_alerts,
alert_icon_callback=self._alerts_layout.highest_severity_icon,
)
for layout in (self._car_onroad_layout, self._body_onroad_layout):
onroad_layouts = [self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
onroad_layouts.append(self._robotic_onroad_layout)
for layout in onroad_layouts:
layout.set_click_callback(lambda: self._scroll_to(self._home_layout))
device.add_interactive_timeout_callback(self._on_interactive_timeout)
@@ -92,6 +111,11 @@ class MiciMainLayout(Scroller):
layout_x = int(layout.rect.x)
self._scroller.scroll_to(layout_x, smooth=True)
def _update_state(self):
super()._update_state()
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui != self._prev_robotic_ui:
self._prev_robotic_ui = ui_state.mici_robotic_ui
self._on_body_changed()
def _handle_transitions(self):
# greet when getting in the car after it's been off for a while
if ui_state.ignition != self._prev_ignition:
@@ -146,5 +170,8 @@ class MiciMainLayout(Scroller):
self._pm.send(service, msg)
def _on_body_changed(self):
self._car_onroad_layout.set_visible(not ui_state.is_body)
use_robotic = self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui
self._car_onroad_layout.set_visible(not ui_state.is_body and not use_robotic)
if self._robotic_onroad_layout is not None:
self._robotic_onroad_layout.set_visible(not ui_state.is_body and use_robotic)
self._body_onroad_layout.set_visible(bool(ui_state.is_body))
@@ -28,9 +28,17 @@ class DrivingLayoutMici(NavScroller):
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback,
description="Enable to use sunnypilot driver assistance.\n" +
"Disable to use your car's stock driver assistance.")
robotic_ui_toggle = BigParamControl(
"robotic companion UI",
"MiciRoboticUI",
description="Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
)
radar_tracks = BigMultiParamToggle("radar tracks", "RadarTracks", ["off", "lead only", "full radar"])
self._radar_tracks_toggle = radar_tracks
self._scroller.add_widgets([
robotic_ui_toggle,
radar_tracks,
self._personality_toggle,
self._initial_cruise_speed,
always_on_dm_toggle,
@@ -40,6 +48,7 @@ class DrivingLayoutMici(NavScroller):
# Toggle lists
self._refresh_toggles = (
("MiciRoboticUI", robotic_ui_toggle),
("IsLdwEnabled", ldw_toggle),
("AlwaysOnDM", always_on_dm_toggle),
("OpenpilotEnabledToggle", enable_openpilot),
@@ -77,3 +86,4 @@ class DrivingLayoutMici(NavScroller):
# Refresh toggles from params to mirror external changes
for key, item in self._refresh_toggles:
item.set_checked(ui_state.params.get_bool(key))
self._radar_tracks_toggle._load_value()
@@ -0,0 +1,274 @@
"""Tests for MICI Robotic Companion onroad UI mood engine and telemetry helpers."""
import random
from openpilot.cereal import log
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
EyeGlyph,
MouthGlyph,
PALETTE,
RoboticMood,
RoboticMoodEngine,
STANDSTILL_POUT_DELAY,
STANDSTILL_SLEEPY_DELAY,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
class TestRoboticMoodEngine(OpenpilotTestCase):
def _engine(self) -> RoboticMoodEngine:
return RoboticMoodEngine(rng=random.Random(42))
def test_engaged_happy_then_speed_then_cruising(self):
engine = self._engine()
# Initially disengaged
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
target = engine.update(snap, now=10.0)
assert engine.mood == RoboticMood.IDLE_CURIOUS
assert target.color == PALETTE["disengaged"]
# Engage triggers HAPPY_ENGAGE crescent eyes
snap_eng = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
target = engine.update(snap_eng, now=11.0)
assert engine.mood == RoboticMood.HAPPY_ENGAGE
assert target.glyph == EyeGlyph.CRESCENT
assert target.color == PALETTE["engaged"]
# After happy hold, briefly shows speed confirmation
engine.update(snap_eng, now=12.2)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
# After speed confirm expires, settles into CRUISING_HAPPY
target = engine.update(snap_eng, now=15.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
assert engine.showing_speed is False
assert target.color == PALETTE["engaged"]
def test_critical_alert_overrides_all_moods(self):
engine = self._engine()
engine.trigger_love(now=10.0)
engine.trigger_speed_peek(now=10.0)
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, alert=alert)
target = engine.update(snap, now=10.1)
assert engine.mood == RoboticMood.CRITICAL
assert target.glyph == EyeGlyph.LASER_ALERT
assert target.color == PALETTE["critical"]
assert engine.showing_speed is False
def test_distracted_driver_monitoring(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, dm_alert_level=1)
target = engine.update(snap, now=20.0)
assert engine.mood == RoboticMood.DISTRACTED
assert target.color == PALETTE["prompt"]
assert target.mouth == MouthGlyph.FROWN
def test_hard_decel_triggers_star_eyes(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, a_ego=-3.8)
target = engine.update(snap, now=30.0)
assert engine.mood == RoboticMood.STARTLED_STARS
assert target.glyph == EyeGlyph.STAR
assert target.mouth == MouthGlyph.SURPRISED
def test_lane_change_and_blind_spot(self):
engine = self._engine()
snap_lc = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, pre_lane_change_left=True)
target = engine.update(snap_lc, now=40.0)
assert engine.mood == RoboticMood.LANE_CHANGE
assert target.glyph == EyeGlyph.ARROW_LEFT
assert target.gaze_x < 0
snap_bsm = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, right_blinker=True, right_blindspot=True)
target = engine.update(snap_bsm, now=41.0)
assert engine.mood == RoboticMood.BLIND_SPOT
assert target.gaze_x > 0
assert target.blind_spot_side == 1
def test_standstill_pout_and_sleepy_progression(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
engine.update(snap, now=100.0)
# Past happy engage & speed confirm, still before pout
engine.update(snap, now=105.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
# Past pout threshold
target = engine.update(snap, now=100.0 + STANDSTILL_POUT_DELAY + 1.0)
assert engine.mood == RoboticMood.POUT_STANDSTILL
assert target.mouth == MouthGlyph.FROWN
# Past sleepy threshold
target = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 1.0)
assert engine.mood == RoboticMood.SLEEPY
assert target.top_lid >= 0.5
def test_set_speed_change_triggers_speed_display(self):
engine = self._engine()
snap1 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
engine.update(snap1, now=10.0)
engine.update(snap1, now=15.0)
assert engine.showing_speed is False
snap2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=110.0)
engine.update(snap2, now=16.0)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
assert engine.speed_reason == "set_speed"
def test_mads_lat_only_warm_peach_palette(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=18.0)
engine.update(snap, now=10.0)
target = engine.update(snap, now=15.0)
assert target.color == PALETTE["lat_only"]
def test_display_speed_conversion(self):
snap_mph = DrivingSnapshot(v_ego=26.8224, set_speed_kph=100.0, is_metric=False)
cur, set_s = display_speed_and_set_speed(snap_mph)
assert cur == 60
assert set_s == 62
snap_kph = DrivingSnapshot(v_ego=27.7778, set_speed_kph=100.0, is_metric=True)
cur, set_s = display_speed_and_set_speed(snap_kph)
assert cur == 100
assert set_s == 100
def test_sharp_accel_turn_signal_sharp_turn_and_continuous_motion(self):
engine = self._engine()
# Sharp acceleration triggers BOOST_ACCEL with speed lines
snap_boost = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, a_ego=2.8)
engine.update(snap_boost, now=10.0)
target = engine.update(snap_boost, now=14.0)
# Trigger fresh boost after engage hold expires
snap_boost2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, a_ego=2.9)
target = engine.update(snap_boost2, now=15.0)
assert engine.mood == RoboticMood.BOOST_ACCEL
assert target.glyph == EyeGlyph.SPARKLE_BOOST
assert target.show_speed_lines is True
# Turn indicator triggers TURN_SIGNAL with blinker side
snap_turn = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0, left_blinker=True)
target = engine.update(snap_turn, now=20.0)
assert engine.mood == RoboticMood.TURN_SIGNAL
assert target.blinker_side == -1
# Sharp high-speed turn triggers SHARP_TURN with centrifugal tilt
snap_sharp = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=22.0, yaw_rate=-0.18)
target = engine.update(snap_sharp, now=25.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert abs(target.tilt_y) >= 10.0
# Bookmark wink triggers love with wink_right=True
engine.trigger_love(now=30.0, wink=True)
target = engine.update(DrivingSnapshot(started=True, engaged=False), now=30.2)
assert engine.mood == RoboticMood.BOOKMARK_LOVE
assert target.wink_right is True
assert target.show_hearts is True
# Continuous motion check: idle bounce_y & gaze_x are never frozen across frames
snap_idle = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=0.0)
t1 = engine.update(snap_idle, now=40.0)
t2 = engine.update(snap_idle, now=40.5)
assert (t1.bounce_y != t2.bounce_y) or (t1.gaze_x != t2.gaze_x)
def test_music_analyzer_rejects_road_noise_and_speech_detects_music(self):
import numpy as np
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import (
DEFAULT_SAMPLE_RATE,
MusicAnalyzer,
MusicState,
)
sr = DEFAULT_SAMPLE_RATE
chunk_len = 800 # 50 ms @ 16 kHz
rng = np.random.default_rng(7)
# 1. Broadband cabin road/wind noise -> MUST be rejected
road_analyzer = MusicAnalyzer(sr)
for _ in range(90): # 4.5 s
noise = rng.normal(0.0, 0.08, size=chunk_len).astype(np.float32)
state = road_analyzer.process_samples(noise)
assert state.is_music is False, f"Road noise falsely triggered music (conf={state.confidence:.2f})"
# 2. Simulated human talking (irregular vocal-band bursts with speech pauses) -> MUST be rejected
speech_analyzer = MusicAnalyzer(sr)
t_total = np.arange(90 * chunk_len, dtype=np.float32) / sr
# Speech formants (550Hz + 1200Hz) modulated by irregular syllables & pauses
vocal = 0.09 * np.sin(2 * np.pi * 550 * t_total) + 0.06 * np.sin(2 * np.pi * 1250 * t_total)
for idx in range(90):
# Irregular talk/pause pattern (approx 45% active)
speaking = (idx % 11) in (0, 1, 2, 5, 6)
seg = vocal[idx * chunk_len:(idx + 1) * chunk_len] * (1.0 if speaking else 0.02)
seg = seg + rng.normal(0.0, 0.01, size=chunk_len).astype(np.float32)
state = speech_analyzer.process_samples(seg)
assert state.is_music is False, f"Talking falsely triggered music (conf={state.confidence:.2f})"
# 3. Simulated quiet cabin music mixed with highway road rumble -> MUST be detected
music_analyzer = MusicAnalyzer(sr)
beat_period = 0.5 # 120 BPM
for idx in range(100): # 5.0 s
t = (idx * chunk_len + np.arange(chunk_len, dtype=np.float32)) / sr
beat_t = t % beat_period
kick = 0.035 * np.exp(-beat_t * 18.0) * np.sin(2 * np.pi * 95.0 * t)
chord = (
0.018 * np.sin(2 * np.pi * 261.6 * t)
+ 0.015 * np.sin(2 * np.pi * 329.6 * t)
+ 0.015 * np.sin(2 * np.pi * 392.0 * t)
)
hihat_t = (t + 0.25) % beat_period
hihat = 0.014 * np.exp(-hihat_t * 35.0) * np.sin(2 * np.pi * 5200.0 * t)
road_rumble = rng.normal(0.0, 0.008, size=chunk_len).astype(np.float32)
mix = (kick + chord + hihat + road_rumble).astype(np.float32)
state = music_analyzer.process_samples(mix)
assert state.is_music is True, f"Quiet cabin music over road rumble was not detected (conf={state.confidence:.2f})"
assert max(state.bands) > 0.2
# 4. Mood engine enters MUSIC_GROOVE when cruising/idling (even during gentle low-speed turn), overridden by alerts
engine = self._engine()
music_on = MusicState(is_music=True, confidence=0.85, beat_pulse=0.7, groove_phase=1.2, bpm=120.0, energy=0.7)
snap_cruise = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, steering_angle_deg=20.0, music=music_on)
engine.update(snap_cruise, now=10.0)
engine.update(snap_cruise, now=15.0)
assert engine.mood == RoboticMood.MUSIC_GROOVE
# Alert overrides MUSIC_GROOVE immediately
snap_alert = DrivingSnapshot(
started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on,
alert=Alert("Pay Attention", "Eyes on road", status=AlertStatus.userPrompt),
)
engine.update(snap_alert, now=15.5)
assert engine.mood == RoboticMood.USER_PROMPT
def test_centrifugal_turn_squish_direction_speed_gate_and_no_vertical(self):
engine = self._engine()
# Low-speed controlled turn (v_ego=5 m/s) -> stays calm, zero squish, zero vertical movement
snap_slow = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=5.0, yaw_rate=0.25, pitch_rad=0.10, pitch_rate=0.2)
engine.update(snap_slow, now=10.0)
t_slow = engine.update(snap_slow, now=15.0)
assert t_slow.squish_force == 0.0
assert t_slow.pitch_offset_y == 0.0
assert engine.mood == RoboticMood.CRUISING_HAPPY
# High-speed RIGHT turn (yaw_rate > 0 in FRD) -> pushed LEFT (squish_force < 0, opposite side of turn)
snap_right_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=0.19, pitch_rad=0.10)
t_right = engine.update(snap_right_fast, now=16.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert t_right.squish_force < -0.65
assert t_right.pitch_offset_y == 0.0
assert t_right.mouth == MouthGlyph.SURPRISED
# High-speed LEFT turn (yaw_rate < 0 in FRD) -> pushed RIGHT (squish_force > 0, opposite side of turn)
snap_left_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=-0.19)
t_left = engine.update(snap_left_fast, now=17.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert t_left.squish_force > 0.65
assert t_left.pitch_offset_y == 0.0
+113 -31
View File
@@ -1,3 +1,4 @@
import contextlib
import math
import numpy as np
import time
@@ -8,29 +9,27 @@ from openpilot.cereal import log, messaging, custom
from openpilot.common.basedir import BASEDIR
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.realtime import Ratekeeper
from openpilot.common.utils import retry
from openpilot.common.swaglog import cloudlog
from openpilot.system import micd
from openpilot.common.hardware import HARDWARE
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
SAMPLE_RATE = 48000
SAMPLE_BUFFER = 4096 # (approx 100ms)
MAX_VOLUME = 1.0
MIN_VOLUME = 0.1
AMBIENT_DB = 10.0 # DB where MIN_VOLUME is applied
DB_SCALE = 25.0 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
MIN_VOLUME = 0.45
ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for immediate warnings
SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds
FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES)
AMBIENT_DB = 26 # DB where MIN_VOLUME is applied
DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
VOLUME_BASE = 20
if HARDWARE.get_device_type() == "tizi":
AMBIENT_DB = 30
VOLUME_BASE = 10
REINIT_RETRY_INTERVAL = 3.0
AudibleAlert = log.SelfdriveState.AudibleAlert
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
@@ -78,6 +77,7 @@ def check_selfdrive_timeout_alert(sm):
class Soundd(QuietMode):
def __init__(self):
super().__init__()
self.robotic_sound_pack = RoboticSoundPack(self.params, SAMPLE_RATE)
self.load_sounds()
@@ -92,6 +92,7 @@ class Soundd(QuietMode):
self.pending_stop = False
self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False)
self.spl_received = False
def load_sounds(self):
self.loaded_sounds: dict[int, np.ndarray] = {}
@@ -108,13 +109,32 @@ class Soundd(QuietMode):
length = wavefile.getnframes()
self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2)
self.robotic_sound_pack.load()
def load_param(self) -> None:
prev_frame = self._frame
super().load_param()
if self._frame != prev_frame and self._frame % 50 == 0:
if self.robotic_sound_pack.refresh_param():
self.current_sound_frame = 0
def _sound_buffer(self, alert_id: int) -> np.ndarray | None:
"""Resolve the buffer for an alert id, or None when this id has no sound loaded."""
if alert_id == AudibleAlert.none:
return None
try:
return self.robotic_sound_pack.get_buffer(alert_id, self.loaded_sounds)
except KeyError:
return None
def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required
ret = np.zeros(frames, dtype=np.float32)
sound_data = self._sound_buffer(self.current_alert)
if self.should_play_sound(self.current_alert):
num_loops = sound_list[self.current_alert][1]
sound_data = self.loaded_sounds[self.current_alert]
if sound_data is not None:
audible = self.should_play_sound(self.current_alert)
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
written_frames = 0
current_sound_frame = self.current_sound_frame % len(sound_data)
@@ -123,7 +143,8 @@ class Soundd(QuietMode):
while written_frames < frames and (num_loops is None or loops < num_loops):
available_frames = sound_data.shape[0] - current_sound_frame
frames_to_write = min(available_frames, frames - written_frames)
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
if audible:
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
written_frames += frames_to_write
self.current_sound_frame += frames_to_write
current_sound_frame = self.current_sound_frame % len(sound_data)
@@ -133,17 +154,35 @@ class Soundd(QuietMode):
self.pending_stop = False
break
return ret * self.current_volume
vol = self.current_volume
if self.robotic_sound_pack.enabled and not self.enabled and self.current_alert != AudibleAlert.none:
vol = max(vol, 0.35)
return ret * vol
def callback(self, data_out: np.ndarray, frames: int, time, status) -> None:
if status:
cloudlog.warning(f"soundd stream over/underflow: {status}")
data_out[:frames, 0] = self.get_sound_data(frames)
def _note_play(self, alert_id: int) -> None:
"""Log the alert start together with the routing decision and the gain it plays at."""
if alert_id == AudibleAlert.none:
return
audible = self.should_play_sound(alert_id)
robotic = self.robotic_sound_pack.enabled and alert_id in self.robotic_sound_pack.sounds
cloudlog.debug(f"soundd play alert={alert_id} robotic={robotic} audible={audible} gain={self.current_volume:.2f}")
def update_alert(self, new_alert):
current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert])
current_buffer = self._sound_buffer(self.current_alert)
current_alert_played_once = current_buffer is None or self.current_sound_frame >= len(current_buffer)
# let looping sounds finish the current loop instead of cutting off mid tone
if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None:
if (
new_alert == AudibleAlert.none
and self.current_alert != AudibleAlert.none
and self.current_alert not in REACTIVE_CHIRP_IDS
and sound_list[self.current_alert][1] is None
):
if current_alert_played_once:
self.pending_stop = True
else:
@@ -157,6 +196,7 @@ class Soundd(QuietMode):
self.ramp_start_time = time.monotonic()
self.current_alert = new_alert
self.current_sound_frame = 0
self._note_play(new_alert)
def get_audible_alert(self, sm):
if sm.updated['selfdriveState']:
@@ -169,38 +209,78 @@ class Soundd(QuietMode):
self.update_alert(AudibleAlert.none)
self.selfdrive_timeout_alert = False
# Trigger playful one-shot robotic chirps only when idle (never preempting safety alerts)
if self.robotic_sound_pack.enabled and self.current_alert == AudibleAlert.none:
chirp = self.robotic_sound_pack.detect_reactive_chirp(sm)
if chirp is not None:
self.update_alert(chirp)
def calculate_volume(self, weighted_db):
volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME
return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1))
@retry(attempts=10, delay=3)
def get_stream(self, sd):
# reload sounddevice to reinitialize portaudio
def _reinit_stream(self, sd, stream):
if stream is not None:
with contextlib.suppress(Exception):
stream.close()
# reload sounddevice to reinitialize portaudio, then open the output stream
sd._terminate()
sd._initialize()
return sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
new_stream = sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
try:
new_stream.start()
except Exception:
with contextlib.suppress(Exception):
new_stream.close()
raise
cloudlog.info(f"soundd stream started: {new_stream.samplerate=} {new_stream.channels=} {new_stream.dtype=} {new_stream.device=}, {new_stream.blocksize=}")
return new_stream
def update_volume(self, valid: bool, sound_pressure_weighted_db: float) -> None:
# Only adapt volume from valid mic data. With invalid (stale) soundPressure
# we freeze instead of decaying towards MIN_VOLUME, so critical alerts can
# never be silenced by a broken mic (https://github.com/commaai/openpilot/issues/36088)
if not valid:
if self.spl_received:
cloudlog.warning("soundd: soundPressure invalid, freezing alert volume")
self.spl_received = False
return
self.spl_received = True
self.spl_filter_weighted.update(sound_pressure_weighted_db)
# freeze volume during alerts to avoid mic feedback increasing volume
if self.current_alert == AudibleAlert.none:
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
def soundd_thread(self):
# sounddevice must be imported after forking processes
import sounddevice as sd
micd.patch_sounddevice(sd)
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure'])
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure', 'carState', 'controlsState', 'userBookmark', 'bookmarkButton'])
rk = Ratekeeper(20)
stream = None
last_reinit_time: float | None = None
with self.get_stream(sd) as stream:
rk = Ratekeeper(20)
cloudlog.info(f"soundd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}")
try:
while True:
if stream is None or not stream.active:
now = time.monotonic()
if last_reinit_time is None or (now - last_reinit_time) >= REINIT_RETRY_INTERVAL:
last_reinit_time = now
try:
stream = self._reinit_stream(sd, stream)
except Exception:
stream = None
cloudlog.exception("soundd failed to open stream")
sm.update(0)
self.load_param()
# freeze volume during alerts to avoid mic feedback increasing volume
if sm.updated['soundPressure']:
self.spl_filter_weighted.update(sm["soundPressure"].soundPressureWeightedDb)
if self.current_alert == AudibleAlert.none:
self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x))
self.update_volume(bool(sm.valid['soundPressure']), float(sm["soundPressure"].soundPressureWeightedDb))
self.get_audible_alert(sm)
@@ -211,8 +291,10 @@ class Soundd(QuietMode):
self.current_volume = max(self.current_volume, ramp_vol)
rk.keep_time()
assert stream.active
finally:
if stream is not None:
with contextlib.suppress(Exception):
stream.close()
def main():
@@ -195,7 +195,7 @@ class ConnectPhoneLayout(PairingDialog):
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, rl.Vector2(circle_x - number_size.x // 2, circle_y - number_size.y // 2), 30, 0.0, rl.WHITE)
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
@@ -114,7 +114,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
self._panels = {
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
@@ -7,7 +7,7 @@ See the LICENSE.md file in the root directory for more details.
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR
@@ -16,16 +16,9 @@ class HyundaiSettings(BrandSettings):
super().__init__()
self.alpha_long_available = False
tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")]
self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts,
button_width=300, callback=self._on_tuning_selected,
param="HyundaiLongitudinalTuning", inline=False)
self.longitudinal_tuning_item = toggle_item_sp(tr("Custom Longitudinal Tuning"), "", param="HyundaiLongitudinalTuning")
self.items = [self.longitudinal_tuning_item]
@staticmethod
def _on_tuning_selected(index):
ui_state.params.put("HyundaiLongitudinalTuning", index)
def update_settings(self):
self.alpha_long_available = False
bundle = ui_state.params.get("CarPlatformBundle")
@@ -35,25 +28,14 @@ class HyundaiSettings(BrandSettings):
elif ui_state.CP is not None:
self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable
tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0")
long_enabled = ui_state.has_longitudinal_control
desc = tr("Accelerates and brakes the way your car's own cruise control does.")
if not ui_state.is_offroad():
desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
long_tuning_descs = [
tr("Your vehicle will use the Default longitudinal tuning."),
tr("Your vehicle will use the Dynamic longitudinal tuning."),
tr("Your vehicle will use the Predictive longitudinal tuning."),
]
long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0]
longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled
if longitudinal_tuning_disabled:
if not ui_state.is_offroad():
long_tuning_desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled)
self.longitudinal_tuning_item.set_description(long_tuning_desc)
self.longitudinal_tuning_item.action_item.set_enabled(ui_state.is_offroad() and long_enabled)
self.longitudinal_tuning_item.set_description(desc)
self.longitudinal_tuning_item.show_description(True)
self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param)
self.longitudinal_tuning_item.set_visible(self.alpha_long_available)
@@ -0,0 +1,9 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.robotic_view import RoboticOnroadView
__all__ = ["RoboticOnroadView"]
@@ -0,0 +1,136 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import raylib_nb as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.onroad.alert_renderer import Alert, get_alert
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.application import FontWeight, TextAlignment, gui_app
from openpilot.system.ui.widgets.label import UnifiedLabel
AlertStatus = log.SelfdriveState.AlertStatus
class RoboticAlertOverlay:
"""Harmonized alert overlay that keeps robotic expressions visible while preserving safety readability."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._prev_alert: Alert | None = None
self._alpha_filter = FirstOrderFilter(0.0, 0.06, dt)
self._text1_label = UnifiedLabel(
text="",
font_size=44,
font_weight=FontWeight.DISPLAY,
alignment=TextAlignment.CENTER,
line_height=0.9,
)
self._text2_label = UnifiedLabel(
text="",
font_size=26,
font_weight=FontWeight.MEDIUM,
alignment=TextAlignment.CENTER,
line_height=0.95,
)
def get_alert(self) -> Alert | None:
alert = get_alert(ui_state.sm)
if gui_app.sunnypilot_ui():
ui_state.onroad_brightness_handle_alerts(ui_state, alert)
return alert
def render(self, rect: rl.Rectangle, alert: Alert | None) -> float:
"""Render alert overlay and return current alpha (0..1) so caller can shift face if needed."""
alpha = self._alpha_filter.update(1.0 if alert is not None else 0.0)
if alert is not None:
self._prev_alert = alert
elif alpha > 0.02 and self._prev_alert is not None:
alert = self._prev_alert
else:
self._prev_alert = None
return 0.0
is_critical = alert.status == AlertStatus.critical
is_prompt = alert.status == AlertStatus.userPrompt
if is_critical:
pulse = 0.65 + 0.35 * (0.5 + 0.5 * math.sin(rl.get_time() * 14.0))
# Pulsing red edge frame + bottom dark backing so red eyes + takeover text are unmistakable
border_col = rl.Color(255, 25, 35, int(230 * pulse * alpha))
rl.draw_rectangle_rounded_lines_ex(
rl.Rectangle(rect.x + 3, rect.y + 3, rect.width - 6, rect.height - 6),
0.16,
12,
10.0,
border_col,
)
band_h = 98
rl.draw_rectangle_gradient_v(
int(rect.x),
int(rect.y + rect.height - band_h - 18),
int(rect.width),
band_h + 18,
rl.Color(180, 0, 15, 0),
rl.Color(210, 0, 20, int(230 * alpha)),
)
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 4, band_h, alpha, big=True)
elif is_prompt:
band_h = 84
rl.draw_rectangle_gradient_v(
int(rect.x),
int(rect.y + rect.height - band_h - 14),
int(rect.width),
band_h + 14,
rl.Color(220, 95, 0, 0),
rl.Color(235, 105, 0, int(215 * alpha)),
)
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 6, band_h, alpha, big=False)
else:
# Soft / normal alert: compact bottom pill leaving the expressive eyes unobstructed
band_h = 66
pill = rl.Rectangle(rect.x + 24, rect.y + rect.height - band_h - 8, rect.width - 48, band_h)
rl.draw_rectangle_rounded(pill, 0.38, 12, rl.Color(24, 28, 34, int(215 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill, 0.38, 12, 2.0, rl.Color(255, 255, 255, int(45 * alpha)))
self._draw_banner_text(rect, alert, pill.y + 6, band_h - 8, alpha, big=False)
return alpha
def _draw_banner_text(
self,
rect: rl.Rectangle,
alert: Alert,
top_y: float,
band_h: float,
alpha: float,
big: bool,
) -> None:
text1 = alert.text1.lower()
text2 = alert.text2.lower()
if big:
font1 = 42 if len(text1) <= 18 else 34
else:
font1 = 34 if len(text1) <= 22 else 28
margin_x = 34
w = rect.width - margin_x * 2
self._text1_label.set_text(text1)
self._text1_label.set_font_size(font1)
self._text1_label.set_text_color(rl.Color(255, 255, 255, int(245 * alpha)))
self._text1_label.render(rl.Rectangle(rect.x + margin_x, top_y, w, band_h))
if text2:
font2 = 24 if len(text2) <= 28 else 20
self._text2_label.set_text(text2)
self._text2_label.set_font_size(font2)
self._text2_label.set_text_color(rl.Color(255, 255, 255, int(195 * alpha)))
self._text2_label.render(rl.Rectangle(rect.x + margin_x, top_y + font1 + 2, w, max(24.0, band_h - font1)))
@@ -0,0 +1,993 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from dataclasses import dataclass
from enum import Enum
import math
import random
import time
from openpilot.cereal import log
from openpilot.common.constants import CV
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import groove_prism_color
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
EventName = log.OnroadEvent.EventName
SET_SPEED_NA = 255
KM_TO_MILE = 0.621371
# Thresholds & hold durations (seconds)
HARD_DECEL_THRESHOLD = -3.0 # m/s^2 triggers startled star eyes
SHARP_ACCEL_THRESHOLD = 2.2 # m/s^2 triggers excited boost eyes
STANDSTILL_POUT_DELAY = 8.0 # seconds at standstill before pouting
STANDSTILL_SLEEPY_DELAY = 35.0 # seconds at standstill before sleepy
MIN_TURN_SPEED_MS = 6.5 # m/s (~15 mph) min speed for passenger centrifugal feel
MIN_LAT_ACCEL_MS2 = 1.6
FULL_LAT_ACCEL_MS2 = 3.6
LAT_JERK_WEIGHT = 0.5
LAT_JERK_LOW = 400.0
LAT_JERK_HIGH = 900.0
SQUISH_ATTACK_RATE = 20.0
SQUISH_RELEASE_RATE = 3.3
SET_SPEED_SHOW_DURATION = 3.0 # seconds to show speed arc on set-speed change
ENGAGE_HAPPY_DURATION = 0.9 # seconds of joyful crescent eyes on engage
ENGAGE_SPEED_CONFIRM = 2.0 # seconds of speed readout right after happy engage
STARTLED_HOLD_DURATION = 1.5 # seconds to hold star-shock expression
BOOST_HOLD_DURATION = 1.2 # seconds to hold sharp-accel boost expression
LOVE_HOLD_DURATION = 1.6 # seconds to hold heart/pet expression
MANUAL_SPEED_PEEK_DURATION = 4.0 # seconds for swipe-up speed peek
BLINK_CLOSE_S = 0.070
BLINK_HOLD_S = 0.035
BLINK_OPEN_S = 0.130
BLINK_LID_MIN = 0.08
BLINK_LID_MAX = 0.92
REACTION_DELAY_S = 0.10
DEBUG_PARAM = "MiciRoboticDebug"
class RoboticMood(Enum):
CRITICAL = "critical"
DISTRACTED = "distracted"
USER_PROMPT = "user_prompt"
STARTLED_STARS = "startled_stars"
LANE_CHANGE = "lane_change"
BLIND_SPOT = "blind_spot"
BOOKMARK_LOVE = "bookmark_love"
HAPPY_ENGAGE = "happy_engage"
BOOST_ACCEL = "boost_accel"
TURN_SIGNAL = "turn_signal"
SPEED_DISPLAY = "speed_display"
POUT_STANDSTILL = "pout_standstill"
SLEEPY = "sleepy"
SHARP_TURN = "sharp_turn"
CURVE_FOCUS = "curve_focus"
MUSIC_GROOVE = "music_groove"
CRUISING_HAPPY = "cruising_happy"
IDLE_CURIOUS = "idle_curious"
class IdleAction(Enum):
"""Playful autonomous micro-behaviors during normal cruising & idle driving."""
NONE = "none"
HAPPY_SQUINT = "happy_squint"
CURIOUS_LOOK = "curious_look"
CHEEKY_WINK = "cheeky_wink"
GROOVE_BOB = "groove_bob"
STRETCH = "stretch"
SETTLE = "settle"
PERK_UP = "perk_up"
DAYDREAM = "daydream"
DOODLE = "doodle"
DOUBLE_BLINK_TILT = "double_blink_tilt"
class GrooveStyle(Enum):
"""Music animations. One is picked per segment; the set reads as one character."""
HEAD_BOB = "head_bob"
SIDE_SWAY = "side_sway"
JELLY = "jelly"
SNARE_BLINK = "snare_blink"
LOOK_AROUND = "look_around"
ANTICIPATION_POP = "anticipation_pop"
GLOW_PULSE = "glow_pulse"
IDLE_ACTION_DURATION = {
IdleAction.HAPPY_SQUINT: 0.9,
IdleAction.CURIOUS_LOOK: 1.6,
IdleAction.CHEEKY_WINK: 0.6,
IdleAction.GROOVE_BOB: 2.0,
IdleAction.STRETCH: 1.8,
IdleAction.SETTLE: 2.4,
IdleAction.PERK_UP: 1.0,
IdleAction.DAYDREAM: 3.4,
IdleAction.DOODLE: 2.8,
IdleAction.DOUBLE_BLINK_TILT: 0.9,
}
IDLE_ACTION_WEIGHTS = {
IdleAction.HAPPY_SQUINT: 1.0,
IdleAction.CURIOUS_LOOK: 1.2,
IdleAction.CHEEKY_WINK: 0.7,
IdleAction.GROOVE_BOB: 0.6,
IdleAction.STRETCH: 0.8,
IdleAction.SETTLE: 0.7,
IdleAction.PERK_UP: 0.8,
IdleAction.DAYDREAM: 0.9,
IdleAction.DOODLE: 0.8,
IdleAction.DOUBLE_BLINK_TILT: 1.1,
}
GROOVE_WEIGHTS = {
GrooveStyle.HEAD_BOB: 1.2,
GrooveStyle.SIDE_SWAY: 1.1,
GrooveStyle.JELLY: 1.0,
GrooveStyle.SNARE_BLINK: 0.8,
GrooveStyle.LOOK_AROUND: 0.9,
GrooveStyle.ANTICIPATION_POP: 0.7,
GrooveStyle.GLOW_PULSE: 0.6,
}
def _ease_in_quad(p: float) -> float:
p = max(0.0, min(1.0, p))
return p * p
def _ease_out_back(p: float, s: float = 1.35) -> float:
p = max(0.0, min(1.0, p)) - 1.0
return p * p * ((s + 1.0) * p + s) + 1.0
def _smoothstep(edge0: float, edge1: float, x: float) -> float:
if edge1 <= edge0:
return 1.0 if x >= edge1 else 0.0
p = max(0.0, min(1.0, (x - edge0) / (edge1 - edge0)))
return p * p * (3.0 - 2.0 * p)
class MotionScheduler:
"""Weighted random picker with per-clip cooldown and no immediate repeats.
Shared by groove and idle so the two systems cannot drift apart in behaviour. The old
rng.choice() had no memory at all, so the same idle could repeat forever.
"""
def __init__(self, options, rng: random.Random, weights: dict | None = None, cooldown: float = 30.0):
self._options = list(options)
self._rng = rng
self._weights = {o: (weights or {}).get(o, 1.0) for o in self._options}
self._cooldown = cooldown
self._cooldowns = dict.fromkeys(self._options, -1e9)
self._current = None
@property
def current(self):
return self._current
def pick(self, now: float):
candidates = [o for o in self._options if o != self._current and now - self._cooldowns[o] >= self._cooldown]
if not candidates:
candidates = [o for o in self._options if o != self._current] or list(self._options)
choice = self._rng.choices(candidates, weights=[self._weights[o] for o in candidates], k=1)[0]
self._current = choice
self._cooldowns[choice] = now
return choice
class _GyroBiasEstimator:
"""Tracks the stationary yaw-gyro bias so a DC offset is not read as a permanent corner.
An uncalibrated bias of 0.03 rad/s at 20 m/s is 0.6 m/s^2 of phantom lateral acceleration,
which is a third of the squish deadband.
"""
def __init__(self):
self.bias = 0.0
self._seeded = False
def correct(self, yaw_rate: float, v_ego: float, dt: float) -> float:
if v_ego < 0.5:
if not self._seeded:
self.bias = yaw_rate
self._seeded = True
elif dt > 0.0:
self.bias += (yaw_rate - self.bias) * min(1.0, dt / 2.0)
return yaw_rate - self.bias
_GYRO_BIAS = _GyroBiasEstimator()
class EyeGlyph(Enum):
ROUND_RECT = "round_rect"
STAR = "star"
HEART = "heart"
CRESCENT = "crescent"
ARROW_LEFT = "arrow_left"
ARROW_RIGHT = "arrow_right"
LASER_ALERT = "laser_alert"
SPARKLE_BOOST = "sparkle_boost"
class MouthGlyph(Enum):
NONE = "none"
SMILE = "smile"
BIG_GRIN = "big_grin"
FROWN = "frown"
SURPRISED = "surprised"
# Dynamic status & mood palette (RGB tuples)
PALETTE = {
"engaged": (64, 240, 226), # EMO vibrant cyan-emerald
"lat_only": (255, 212, 178), # Reference-video warm peach
"long_only": (92, 198, 255), # Sky cyan
"disengaged": (218, 232, 248), # Soft ice white
"override": (255, 196, 68), # Warm amber
"boost": (76, 178, 255), # Electric boost blue
"prompt": (255, 125, 20), # Vivid orange
"critical": (255, 38, 48), # Alert red
"love": (255, 112, 168), # Rose pink
}
@dataclass
class EyeTarget:
width: float = 104.0
height: float = 112.0
roundness: float = 0.62 # Bubbly chunky squircle
top_lid: float = 0.0 # 0..1 fraction covered from top
bottom_lid: float = 0.0 # 0..1 fraction covered from bottom
top_slant: float = 0.0 # degrees (+ = angry/inward, - = sad/outward)
gaze_x: float = 0.0 # px shift (-42..+42)
gaze_y: float = 0.0 # px shift (-22..+22)
bounce_y: float = 0.0 # vertical expressiveness offset
tilt_y: float = 0.0 # vertical asymmetry between left & right eye (playful head tilt)
scale_x: float = 1.0 # squash-and-stretch horizontal multiplier
scale_y: float = 1.0 # squash-and-stretch vertical multiplier
wink_right: bool = False # cute asymmetric wink on bookmark or cheeky idle wink
squish_force: float = 0.0 # -1..+1 centrifugal push (-1 left wall, +1 right wall)
pitch_offset_y: float = 0.0 # px vertical bob from pitch / pitch-rate (bumps, hills, dive)
glyph: EyeGlyph = EyeGlyph.ROUND_RECT
mouth: MouthGlyph = MouthGlyph.NONE
color: tuple[int, int, int] = PALETTE["engaged"]
pulse_speed: float = 0.0 # Hz for alert pulsing
blind_spot_side: int = 0 # -1 left, +1 right, 0 none
blinker_side: int = 0 # -1 left, +1 right, 0 none
show_speed_lines: bool = False
show_zzz: bool = False
show_hearts: bool = False
@dataclass
class DrivingSnapshot:
"""Pure-data snapshot of driving signals for deterministic mood evaluation & testing."""
started: bool = True
engaged: bool = False
status: UIStatus = UIStatus.DISENGAGED
v_ego: float = 0.0 # m/s
a_ego: float = 0.0 # m/s^2
standstill: bool = False
steering_angle_deg: float = 0.0
yaw_rate: float = 0.0 # rad/s (+ = turning left -> centrifugal push right)
pitch_rad: float = 0.0 # rad (+ = nose up / hill climb)
pitch_rate: float = 0.0 # rad/s (bumps, crests, braking dive)
curvature: float = 0.0 # rad/m fallback for centrifugal accel
set_speed_kph: float = SET_SPEED_NA
is_metric: bool = False
left_blinker: bool = False
right_blinker: bool = False
left_blindspot: bool = False
right_blindspot: bool = False
pre_lane_change_left: bool = False
pre_lane_change_right: bool = False
lane_change: bool = False
lane_change_blocked: bool = False
dm_alert_level: int = 0 # 0=none, 1=warn, 2=critical
alert: Alert | None = None
music: MusicState | None = None
class RoboticMoodEngine:
"""Priority-based EMO-inspired mood & lively autonomous personality state machine."""
def __init__(self, rng: random.Random | None = None, params=None):
self._rng = rng or random.Random()
self._params = params
self._debug_frame = 0
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
self.idle_action: IdleAction = IdleAction.NONE
self.showing_speed: bool = False
self.speed_reason: str = "" # "set_speed", "engage", "peek"
self.cruising_smoothly: bool = False
self._prev_engaged: bool = False
self._prev_set_speed: float = SET_SPEED_NA
self._standstill_since: float | None = None
self._last_lane_dir: int = 0 # -1 left, +1 right
# Hold / effect timers (monotonic timestamps)
self._startled_until: float = 0.0
self._boost_until: float = 0.0
self._love_until: float = 0.0
self._love_wink: bool = False
self._happy_engage_until: float = 0.0
self._speed_display_until: float = 0.0
# Blink, gaze, and playful idle personality schedulers
now = time.monotonic()
self._next_blink_at: float = now + self._rng.uniform(1.8, 3.6)
self._blink_start_at: float = now - 999.0
self._double_blink_pending: bool = False
self._next_glance_at: float = now + self._rng.uniform(2.5, 7.0)
self._idle_gaze_x: float = 0.0
self._idle_gaze_y: float = 0.0
self._idle_tilt_y: float = 0.0
self._next_idle_action_at: float = now + self._rng.uniform(2.2, 3.8)
self._idle_action_until: float = 0.0
self._idle_action_dir: float = 1.0
self._idle_scheduler = MotionScheduler(
[a for a in IdleAction if a is not IdleAction.NONE], self._rng,
weights=IDLE_ACTION_WEIGHTS, cooldown=30.0,
)
self._groove_scheduler = MotionScheduler(list(GrooveStyle), self._rng, weights=GROOVE_WEIGHTS, cooldown=24.0)
self._groove_style: GrooveStyle = GrooveStyle.HEAD_BOB
self._groove_switch_at: float = 0.0
self._groove_intensity: float = 0.0
self._prev_update_t: float | None = None
self._prev_abs_lat: float = 0.0
self._squish_shown: float = 0.0
self._love_from: float = 0.0
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
t = time.monotonic() if now is None else now
self._love_from = t + REACTION_DELAY_S
self._love_until = self._love_from + LOVE_HOLD_DURATION
self._love_wink = wink
def trigger_speed_peek(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._speed_display_until = max(self._speed_display_until, t + MANUAL_SPEED_PEEK_DURATION)
self.speed_reason = "peek"
def trigger_startled(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
def trigger_boost(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
def _status_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.ENGAGED:
return PALETTE["engaged"]
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
if snap.status == UIStatus.LONG_ONLY:
return PALETTE["long_only"]
if snap.status == UIStatus.OVERRIDE:
return PALETTE["override"]
return PALETTE["disengaged"]
def _update_blink_and_personality(self, now: float, sleepy: bool) -> tuple[float, float, float]:
"""Returns (blink_closure, squash_x, stretch_y) and advances idle glances & micro-actions."""
blink_closure = 0.0
squash_x = 1.0
stretch_y = 1.0
close_s = BLINK_CLOSE_S * (2.2 if sleepy else 1.0)
hold_s = BLINK_HOLD_S * (2.0 if sleepy else 1.0)
open_s = BLINK_OPEN_S * (1.8 if sleepy else 1.0)
blink_total = close_s + hold_s + open_s
elapsed = now - self._blink_start_at
if 0.0 <= elapsed <= blink_total:
if elapsed <= close_s:
blink_closure = _ease_in_quad(elapsed / close_s)
squash_x = 1.0 + 0.10 * blink_closure
stretch_y = 1.0 - 0.08 * blink_closure
elif elapsed <= close_s + hold_s:
blink_closure = 1.0
squash_x = 1.10
stretch_y = 0.92
else:
open_p = (elapsed - close_s - hold_s) / open_s
raw = 1.0 - _ease_out_back(open_p)
pop = max(0.0, -raw)
blink_closure = max(0.0, raw)
squash_x = (1.0 + 0.10 * blink_closure) * (1.0 - 0.06 * pop)
stretch_y = (1.0 - 0.08 * blink_closure) * (1.0 + 0.05 * pop)
elif now >= self._next_blink_at:
self._blink_start_at = now
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.25:
self._double_blink_pending = True
self._next_blink_at = now + blink_total + 0.12
else:
self._double_blink_pending = False
lo, hi = (1.8, 3.6) if sleepy else (2.4, 6.5)
self._next_blink_at = now + blink_total + self._rng.uniform(lo, hi)
if now >= self._next_glance_at:
roll = self._rng.random()
if roll < 0.34:
self._idle_gaze_x = 0.0
self._idle_gaze_y = 0.0
self._idle_tilt_y = 0.0
else:
self._idle_gaze_x = self._rng.uniform(-30.0, 30.0)
self._idle_gaze_y = self._rng.uniform(-10.0, 8.0)
self._idle_tilt_y = self._rng.uniform(-7.0, 7.0)
self._next_glance_at = now + self._rng.uniform(2.5, 7.0)
if now >= self._idle_action_until:
self.idle_action = IdleAction.NONE
if not sleepy and now >= self._next_idle_action_at:
choice = self._idle_scheduler.pick(now)
self.idle_action = choice
self._idle_action_dir = -1.0 if self._rng.random() < 0.5 else 1.0
self._idle_action_until = now + IDLE_ACTION_DURATION[choice]
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(6.0, 18.0)
return blink_closure, squash_x, stretch_y
def update(self, snap: DrivingSnapshot, now: float | None = None) -> EyeTarget:
t = time.monotonic() if now is None else now
dt = 0.0 if self._prev_update_t is None else max(0.0, min(0.5, t - self._prev_update_t))
self._prev_update_t = t
# Track standstill duration
if snap.standstill or not snap.started:
if self._standstill_since is None:
self._standstill_since = t
else:
self._standstill_since = None
standstill_dur = (t - self._standstill_since) if self._standstill_since is not None else 0.0
# Track engagement rising edge
if snap.engaged and not self._prev_engaged:
self._happy_engage_until = t + ENGAGE_HAPPY_DURATION
self._speed_display_until = max(
self._speed_display_until,
t + ENGAGE_HAPPY_DURATION + ENGAGE_SPEED_CONFIRM,
)
self.speed_reason = "engage"
self._prev_engaged = snap.engaged
# Track set-speed change while cruise is set
cruise_set = 0 < snap.set_speed_kph < SET_SPEED_NA
if cruise_set and snap.set_speed_kph != self._prev_set_speed and self._prev_set_speed != SET_SPEED_NA:
self._speed_display_until = max(self._speed_display_until, t + SET_SPEED_SHOW_DURATION)
self.speed_reason = "set_speed"
self._prev_set_speed = snap.set_speed_kph
# Track startling events & sharp acceleration
if snap.a_ego < HARD_DECEL_THRESHOLD or snap.lane_change_blocked:
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
elif snap.a_ego > SHARP_ACCEL_THRESHOLD and not snap.standstill:
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
# Track lane change direction
if snap.pre_lane_change_left:
self._last_lane_dir = -1
elif snap.pre_lane_change_right:
self._last_lane_dir = 1
elif not snap.lane_change:
self._last_lane_dir = 0
blinker_side = -1 if snap.left_blinker else (1 if snap.right_blinker else 0)
bsm_side = 0
if snap.left_blindspot and (snap.left_blinker or snap.pre_lane_change_left):
bsm_side = -1
elif snap.right_blindspot and (snap.right_blinker or snap.pre_lane_change_right):
bsm_side = 1
elif snap.left_blindspot and not snap.standstill:
bsm_side = -1
elif snap.right_blindspot and not snap.standstill:
bsm_side = 1
self.cruising_smoothly = snap.engaged and not snap.standstill and abs(snap.a_ego) < 0.8
# Evaluate mood priority
alert = snap.alert
alert_status = alert.status if alert is not None else -1
alert_type = alert.alert_type if alert is not None else ""
is_dm_alert = snap.dm_alert_level >= 1 or "Distracted" in alert_type or "Unresponsive" in alert_type
self.showing_speed = False
# Compute pure horizontal centrifugal force (-1 = pushed left, +1 = pushed right).
# In openpilot FRD frame, yaw_rate > 0 is a RIGHT turn, which pushes a passenger to the LEFT (-1).
# Only triggers on sharper / higher-speed turns (v_ego >= 6.5 m/s and |lat_accel| >= 1.8 m/s^2).
effective_yaw = snap.yaw_rate
if abs(effective_yaw) < 1e-4 and abs(snap.curvature) > 1e-5:
effective_yaw = snap.v_ego * snap.curvature
squish_force = 0.0
target_squish = 0.0
jerk = 0.0
abs_lat = 0.0
if not snap.standstill and snap.v_ego >= MIN_TURN_SPEED_MS:
lat_accel = -snap.v_ego * effective_yaw # opposite side of the turn
abs_lat = abs(lat_accel)
if abs_lat >= MIN_LAT_ACCEL_MS2:
base = _smoothstep(MIN_LAT_ACCEL_MS2, FULL_LAT_ACCEL_MS2, abs_lat)
if dt > 1e-4:
jerk = abs(abs_lat - self._prev_abs_lat) / dt
jerk_term = LAT_JERK_WEIGHT * _smoothstep(LAT_JERK_LOW, LAT_JERK_HIGH, jerk)
mag = min(1.0, base + jerk_term)
target_squish = mag if lat_accel > 0 else -mag
self._prev_abs_lat = abs_lat
delta = target_squish - self._squish_shown
if dt <= 0.0:
step = abs(delta)
elif abs(target_squish) < abs(self._squish_shown):
step = SQUISH_RELEASE_RATE * dt
else:
step = SQUISH_ATTACK_RATE * dt
self._squish_shown += max(-step, min(step, delta))
squish_force = self._squish_shown
self._log_squish_debug(snap, abs_lat, jerk, effective_yaw, squish_force)
if alert is not None and alert_status == AlertStatus.critical:
self.mood = RoboticMood.CRITICAL
elif is_dm_alert:
self.mood = RoboticMood.DISTRACTED
elif alert is not None and alert_status == AlertStatus.userPrompt:
self.mood = RoboticMood.USER_PROMPT
elif t < self._startled_until:
self.mood = RoboticMood.STARTLED_STARS
elif snap.pre_lane_change_left or snap.pre_lane_change_right or snap.lane_change:
self.mood = RoboticMood.LANE_CHANGE
elif bsm_side != 0 and blinker_side != 0:
self.mood = RoboticMood.BLIND_SPOT
elif self._love_from <= t < self._love_until:
self.mood = RoboticMood.BOOKMARK_LOVE
elif t < self._happy_engage_until:
self.mood = RoboticMood.HAPPY_ENGAGE
elif t < self._speed_display_until and snap.started:
self.mood = RoboticMood.SPEED_DISPLAY
self.showing_speed = True
elif t < self._boost_until:
self.mood = RoboticMood.BOOST_ACCEL
elif blinker_side != 0:
self.mood = RoboticMood.TURN_SIGNAL
elif abs(squish_force) >= 0.35:
self.mood = RoboticMood.SHARP_TURN
elif abs(squish_force) >= 0.12:
self.mood = RoboticMood.CURVE_FOCUS
elif snap.started and snap.music is not None and snap.music.is_music and alert is None:
self.mood = RoboticMood.MUSIC_GROOVE
elif not snap.started or standstill_dur >= STANDSTILL_SLEEPY_DELAY:
self.mood = RoboticMood.SLEEPY
elif standstill_dur >= STANDSTILL_POUT_DELAY:
self.mood = RoboticMood.POUT_STANDSTILL
elif snap.engaged:
self.mood = RoboticMood.CRUISING_HAPPY
else:
self.mood = RoboticMood.IDLE_CURIOUS
base_color = self._status_color(snap)
blink, squash_x, stretch_y = self._update_blink_and_personality(t, sleepy=(self.mood == RoboticMood.SLEEPY))
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
bus_phase = t * 2.2 * energy
breath = math.sin(bus_phase) * 0.72 + math.sin(bus_phase * 0.5 + 0.9) * 0.28
breathe_y = breath * 6.5
breathe_scale = 1.0 + 0.032 * breath
micro_drift_x = math.sin(bus_phase * 0.33) * 5.0
# Steering-coupled gaze (clamped to [-40, +40])
steer_gaze = max(-40.0, min(40.0, -snap.steering_angle_deg * 0.78))
target = EyeTarget(
color=base_color,
bounce_y=breathe_y,
scale_x=squash_x * breathe_scale,
scale_y=stretch_y * (2.0 - breathe_scale),
squish_force=squish_force,
pitch_offset_y=0.0,
blind_spot_side=bsm_side,
blinker_side=blinker_side,
)
if self.mood == RoboticMood.CRITICAL:
target.glyph = EyeGlyph.LASER_ALERT
target.color = PALETTE["critical"]
target.width = 114.0
target.height = 84.0
target.roundness = 0.42
target.top_lid = 0.28
target.top_slant = 18.0
target.pulse_speed = 5.5
target.bounce_y = math.sin(t * 28.0) * 3.5
elif self.mood == RoboticMood.DISTRACTED:
target.color = PALETTE["prompt"]
target.width = 108.0
target.height = 96.0
target.roundness = 0.48
target.top_lid = 0.32
target.top_slant = 12.0
target.gaze_x = math.sin(t * 5.2) * 18.0
target.mouth = MouthGlyph.FROWN
target.pulse_speed = 2.5
elif self.mood == RoboticMood.USER_PROMPT:
target.color = PALETTE["prompt"]
target.width = 108.0
target.height = 120.0
target.top_lid = 0.06
target.top_slant = -6.0
target.gaze_x = micro_drift_x
target.pulse_speed = 1.8
elif self.mood == RoboticMood.STARTLED_STARS:
target.glyph = EyeGlyph.STAR
target.color = PALETTE["override"]
target.width = 114.0
target.height = 114.0
target.mouth = MouthGlyph.SURPRISED
target.bounce_y = math.sin(t * 26.0) * 6.0
target.scale_x = 1.0 + 0.08 * math.sin(t * 22.0)
target.scale_y = 1.0 - 0.08 * math.sin(t * 22.0)
elif self.mood == RoboticMood.LANE_CHANGE:
direction = -1 if snap.pre_lane_change_left else (1 if snap.pre_lane_change_right else self._last_lane_dir or 1)
target.glyph = EyeGlyph.ARROW_LEFT if direction < 0 else EyeGlyph.ARROW_RIGHT
target.gaze_x = direction * 32.0 + math.sin(t * 6.5) * 5.0
target.height = 106.0
target.top_lid = 0.10
target.tilt_y = direction * 7.0
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.BLIND_SPOT:
target.color = PALETTE["override"]
target.gaze_x = bsm_side * 38.0
target.height = 102.0
target.top_lid = 0.22
target.top_slant = 9.0
target.pulse_speed = 3.2
elif self.mood == RoboticMood.BOOKMARK_LOVE:
target.glyph = EyeGlyph.HEART
target.color = PALETTE["love"]
target.width = 114.0
target.height = 114.0
target.wink_right = self._love_wink
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 10.5)) * 15.0
target.show_hearts = True
elif self.mood == RoboticMood.HAPPY_ENGAGE:
target.glyph = EyeGlyph.CRESCENT
target.color = PALETTE["engaged"]
target.width = 116.0
target.height = 100.0
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 9.5)) * 16.0
elif self.mood == RoboticMood.BOOST_ACCEL:
target.glyph = EyeGlyph.SPARKLE_BOOST
target.color = PALETTE["boost"]
target.width = 116.0
target.height = 120.0
target.gaze_y = -7.0
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = math.sin(t * 18.0) * 5.0
target.show_speed_lines = True
elif self.mood == RoboticMood.TURN_SIGNAL:
beat = 0.5 + 0.5 * math.sin(t * 8.4)
target.gaze_x = blinker_side * (22.0 + 14.0 * beat)
target.tilt_y = blinker_side * 8.0
target.width = 106.0
target.height = 108.0
target.top_lid = 0.08
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.POUT_STANDSTILL:
target.width = 98.0
target.height = 84.0
target.roundness = 0.34
target.top_lid = 0.26 + 0.05 * math.sin(t * 1.8)
target.gaze_x = self._idle_gaze_x * 0.75 + micro_drift_x
target.gaze_y = 6.0
target.tilt_y = self._idle_tilt_y * 0.7
target.mouth = MouthGlyph.FROWN
elif self.mood == RoboticMood.SLEEPY:
target.width = 104.0
target.height = 76.0
target.roundness = 0.45
target.top_lid = 0.60 + 0.06 * math.sin(t * 1.5)
target.bottom_lid = 0.14
target.gaze_y = 8.0
target.gaze_x = math.sin(t * 0.7) * 8.0
target.bounce_y = math.sin(t * 1.5) * 6.0
target.show_zzz = True
elif self.mood == RoboticMood.SHARP_TURN:
intensity = abs(squish_force)
push_dir = 1.0 if squish_force >= 0 else -1.0
target.squish_force = push_dir * intensity
target.width = 108.0
target.height = 104.0
target.top_lid = 0.10 + 0.14 * intensity
target.top_slant = 5.0 + 7.0 * intensity
target.gaze_x = push_dir * 12.0 # squish renderer handles primary wall slide
target.gaze_y = 0.0
target.tilt_y = push_dir * (8.0 + 8.0 * intensity)
target.mouth = MouthGlyph.SURPRISED if intensity >= 0.55 else MouthGlyph.SMILE
elif self.mood == RoboticMood.CURVE_FOCUS:
intensity = abs(squish_force)
push_dir = 1.0 if squish_force >= 0 else -1.0
target.squish_force = push_dir * intensity
target.width = 106.0
target.height = 106.0
target.top_lid = 0.08
target.gaze_x = push_dir * 8.0
target.gaze_y = 0.0
target.tilt_y = push_dir * (5.0 + 6.0 * intensity)
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.MUSIC_GROOVE:
m = snap.music or MusicState()
self._groove_intensity = 0.45 + 0.55 * _smoothstep(0.30, 0.80, m.confidence)
if t >= self._groove_switch_at:
self._groove_style = self._groove_scheduler.pick(t)
self._groove_switch_at = t + max(8.0, 32.0 * 60.0 / max(60.0, m.bpm))
self._apply_groove(target, t, m)
elif self.mood == RoboticMood.CRUISING_HAPPY:
target.width = 106.0
target.height = 114.0
target.mouth = MouthGlyph.SMILE
target.gaze_x = steer_gaze * 0.35 + self._idle_gaze_x * 0.65 + micro_drift_x
target.gaze_y = self._idle_gaze_y * 0.65
target.tilt_y = self._idle_tilt_y * 0.75 + math.sin(t * 1.6) * 3.0
self._apply_idle_action(target, t)
else: # IDLE_CURIOUS or SPEED_DISPLAY fallback
target.width = 104.0
target.height = 110.0
target.mouth = MouthGlyph.SMILE
target.gaze_x = self._idle_gaze_x + micro_drift_x
target.gaze_y = self._idle_gaze_y
target.tilt_y = self._idle_tilt_y + math.sin(t * 1.4) * 3.0
self._apply_idle_action(target, t)
if target.glyph == EyeGlyph.ROUND_RECT and not target.wink_right and blink > 0.0:
cover = BLINK_LID_MIN + (BLINK_LID_MAX - BLINK_LID_MIN) * blink
target.top_lid = max(target.top_lid, 0.55 * cover)
target.bottom_lid = max(target.bottom_lid, 0.45 * cover)
return target
def _log_squish_debug(self, snap: DrivingSnapshot, abs_lat: float, jerk: float, yaw_rate: float, squish_force: float) -> None:
"""Param-gated trace so the squish thresholds get set from a real drive, not a guess."""
if self._params is None:
return
self._debug_frame += 1
if self._debug_frame % 60 != 0:
return
try:
if not self._params.get_bool(DEBUG_PARAM):
return
cloudlog.info(f"MICI squish lat={abs_lat:.2f} jerk={jerk:.0f} yaw={yaw_rate:.3f} bias={_GYRO_BIAS.bias:.4f} squish={squish_force:.2f} v={snap.v_ego:.1f}")
except Exception:
self._params = None
def _apply_groove(self, target: EyeTarget, t: float, m: MusicState) -> None:
"""Render the currently scheduled groove variant, intensity-scaled by detector confidence."""
style = self._groove_style
beat = m.beat_pulse
phase = m.groove_phase
sway = math.sin(phase)
amp = self._groove_intensity
target.color = groove_prism_color(t)
target.mouth = MouthGlyph.BIG_GRIN
target.width = 108.0
target.height = 112.0
if style is GrooveStyle.HEAD_BOB:
target.bounce_y = (-13.0 * beat - abs(sway) * 4.0 - 6.0) * amp
target.gaze_x = sway * 8.0 * amp
target.gaze_y = -6.0 - 5.0 * beat * amp
target.scale_x = 1.0 + 0.05 * beat * amp
target.scale_y = 1.0 - 0.04 * beat * amp
if beat > 0.58:
target.glyph = EyeGlyph.CRESCENT
elif style is GrooveStyle.SIDE_SWAY:
target.bounce_y = -abs(sway) * 5.0 * amp - 4.0
target.gaze_x = sway * 24.0 * amp
target.tilt_y = sway * 14.0 * amp
target.scale_x = 1.0 - 0.06 * abs(sway) * amp
target.scale_y = 1.0 + 0.05 * abs(sway) * amp
elif style is GrooveStyle.JELLY:
target.height = 116.0
target.scale_x = 1.0 + 0.13 * beat * amp
target.scale_y = 1.0 - 0.11 * beat * amp
target.bounce_y = -8.0 * beat * amp
target.gaze_y = -4.0
elif style is GrooveStyle.SNARE_BLINK:
half = math.sin(phase * 0.5)
target.height = 110.0
target.gaze_x = sway * 10.0 * amp
target.bounce_y = -abs(half) * 7.0 * amp
target.glyph = EyeGlyph.CRESCENT if half > 0.6 else EyeGlyph.ROUND_RECT
elif style is GrooveStyle.LOOK_AROUND:
look = math.sin(phase * 0.5)
target.gaze_x = look * 26.0 * amp
target.tilt_y = look * 10.0 * amp
target.bounce_y = -6.0 * beat * amp
elif style is GrooveStyle.ANTICIPATION_POP:
cycle = (phase / math.tau) % 1.0
if cycle < 0.75:
build = cycle / 0.75
target.scale_y = 1.0 - 0.12 * build * amp
target.scale_x = 1.0 + 0.10 * build * amp
target.bounce_y = 6.0 * build * amp
else:
pop = math.sin((cycle - 0.75) / 0.25 * math.pi)
target.scale_y = 1.0 + 0.16 * pop * amp
target.scale_x = 1.0 - 0.12 * pop * amp
target.bounce_y = -18.0 * pop * amp
elif style is GrooveStyle.GLOW_PULSE:
target.height = 110.0
target.scale_x = 1.0 + 0.04 * beat * amp
target.scale_y = 1.0 + 0.04 * beat * amp
target.gaze_y = -4.0 - 3.0 * m.energy
target.color = groove_prism_color(t * 0.6)
def _apply_idle_action(self, target: EyeTarget, t: float) -> None:
"""Layer bubbly autonomous micro-behaviors onto normal cruising/idle states."""
if self.idle_action == IdleAction.HAPPY_SQUINT:
target.glyph = EyeGlyph.CRESCENT
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 9.0)) * 12.0
elif self.idle_action == IdleAction.CURIOUS_LOOK:
target.gaze_x = self._idle_action_dir * 34.0
target.gaze_y = -6.0
target.tilt_y = self._idle_action_dir * 10.0
target.height = 118.0
elif self.idle_action == IdleAction.CHEEKY_WINK:
target.wink_right = True
target.mouth = MouthGlyph.BIG_GRIN
target.tilt_y = 6.0
target.bounce_y = -8.0
elif self.idle_action == IdleAction.GROOVE_BOB:
target.bounce_y = math.sin(t * 7.2) * 11.0
target.tilt_y = math.sin(t * 3.6) * 8.0
target.mouth = MouthGlyph.BIG_GRIN
elif self.idle_action == IdleAction.STRETCH:
s = math.sin(t * 3.0)
target.scale_y = 1.0 + 0.12 * s
target.scale_x = 1.0 - 0.09 * s
target.bounce_y = -10.0 * abs(s)
target.mouth = MouthGlyph.SMILE
elif self.idle_action == IdleAction.SETTLE:
target.top_lid = 0.34
target.height = 92.0
target.bounce_y = 6.0
target.mouth = MouthGlyph.SMILE
elif self.idle_action == IdleAction.PERK_UP:
target.width = 112.0
target.height = 122.0
target.gaze_x = math.sin(t * 11.0) * 16.0
target.gaze_y = -8.0
target.mouth = MouthGlyph.SURPRISED
elif self.idle_action == IdleAction.DAYDREAM:
target.gaze_x = 26.0 + math.sin(t * 0.9) * 4.0
target.gaze_y = -10.0 - math.sin(t * 0.6) * 3.0
target.tilt_y = 7.0
target.top_lid = 0.16
target.mouth = MouthGlyph.SMILE
elif self.idle_action == IdleAction.DOODLE:
ang = t * 3.4
target.gaze_x = math.cos(ang) * 20.0
target.gaze_y = math.sin(ang * 2.0) * 8.0
target.mouth = MouthGlyph.SMILE
elif self.idle_action == IdleAction.DOUBLE_BLINK_TILT:
target.tilt_y = 5.0
target.top_lid = max(target.top_lid, 0.30)
target.mouth = MouthGlyph.SMILE
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
"""Build a DrivingSnapshot safely from ui_state.sm."""
sm = ui_state.sm
cs = sm["carState"]
controls = sm["controlsState"]
dm = sm["driverMonitoringState"]
events = sm["onroadEvents"]
v_cruise_cluster = cs.vCruiseCluster
set_speed_kph = controls.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
pre_left = any(e.name == EventName.preLaneChangeLeft for e in events)
pre_right = any(e.name == EventName.preLaneChangeRight for e in events)
lane_change = any(e.name == EventName.laneChange for e in events)
lane_blocked = any(e.name == EventName.laneChangeBlocked for e in events)
v_ego_cluster = cs.vEgoCluster
v_ego = v_ego_cluster if v_ego_cluster != 0.0 else cs.vEgo
# Extract pitch, pitch rate, and yaw rate from modelV2 orientation + gyroscope (104 Hz)
yaw_rate = 0.0
pitch_rad = 0.0
pitch_rate = 0.0
if sm.valid.get("modelV2"):
mv2 = sm["modelV2"]
if len(mv2.orientation.y) > 0:
pitch_rad = float(mv2.orientation.y[0])
if len(mv2.orientationRate.y) > 0 and len(mv2.orientationRate.z) > 0:
pitch_rate = float(mv2.orientationRate.y[0])
yaw_rate = float(mv2.orientationRate.z[0])
if sm.valid.get("gyroscope"):
gyro_msg = sm["gyroscope"]
gyro_which = gyro_msg.which()
gv = gyro_msg.gyroUncalibrated.v if gyro_which == "gyroUncalibrated" else (gyro_msg.gyro.v if gyro_which == "gyro" else ())
if len(gv) >= 3:
# Blend crisp high-rate gyro directly with model orientation rate
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
yaw_rate = _GYRO_BIAS.correct(yaw_rate, max(0.0, float(v_ego)), 1.0 / 60.0)
return DrivingSnapshot(
started=ui_state.started,
engaged=ui_state.engaged,
status=ui_state.status,
v_ego=max(0.0, float(v_ego)),
a_ego=float(cs.aEgo),
standstill=bool(cs.standstill),
steering_angle_deg=float(cs.steeringAngleDeg),
yaw_rate=yaw_rate,
pitch_rad=pitch_rad,
pitch_rate=pitch_rate,
curvature=float(controls.curvature) if sm.valid.get("controlsState") else 0.0,
set_speed_kph=float(set_speed_kph),
is_metric=bool(ui_state.is_metric),
left_blinker=bool(cs.leftBlinker),
right_blinker=bool(cs.rightBlinker),
left_blindspot=bool(cs.leftBlindspot),
right_blindspot=bool(cs.rightBlindspot),
pre_lane_change_left=pre_left,
pre_lane_change_right=pre_right,
lane_change=lane_change,
lane_change_blocked=lane_blocked,
dm_alert_level=int(dm.alertLevel.raw) if sm.valid["driverMonitoringState"] else 0,
alert=alert,
)
def display_speed_and_set_speed(snap: DrivingSnapshot) -> tuple[int, int | None]:
"""Convert current speed and cruise set speed to display units (mph or km/h)."""
speed_conv = CV.MS_TO_KPH if snap.is_metric else CV.MS_TO_MPH
cur_speed = round(max(0.0, snap.v_ego * speed_conv))
if 0 < snap.set_speed_kph < SET_SPEED_NA:
set_val = snap.set_speed_kph if snap.is_metric else snap.set_speed_kph * KM_TO_MILE
return cur_speed, round(set_val)
return cur_speed, None
@@ -0,0 +1,384 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import raylib_nb as rl
from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
EyeGlyph,
EyeTarget,
MouthGlyph,
)
from openpilot.system.ui.lib.application import FontWeight, gui_app
class ProceduralFaceRenderer:
"""60 FPS bubbly EMO-inspired procedural vector face renderer for 536x240 MICI OLED."""
EYE_SPACING = 166.0 # distance between left and right eye centers
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
# Bubbly spring-overshoot filters for juicy EMO-style squash-and-stretch motion
self._w = BounceFilter(104.0, 0.065, dt, bounce=4.2)
self._h = BounceFilter(112.0, 0.065, dt, bounce=4.2)
self._gaze_x = BounceFilter(0.0, 0.050, dt, bounce=3.4)
self._gaze_y = BounceFilter(0.0, 0.055, dt, bounce=3.0)
self._bounce_y = BounceFilter(0.0, 0.055, dt, bounce=4.4)
self._tilt_y = BounceFilter(0.0, 0.095, dt, bounce=3.2)
self._scale_x = BounceFilter(1.0, 0.055, dt, bounce=4.5)
self._scale_y = BounceFilter(1.0, 0.055, dt, bounce=4.5)
self._squish = BounceFilter(0.0, 0.075, dt, bounce=3.6)
self._pitch_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
# Crisp first-order filters for eyelids, roundness, and smooth color blending
self._roundness = FirstOrderFilter(0.62, 0.08, dt)
self._top_lid = FirstOrderFilter(0.0, 0.032, dt)
self._bottom_lid = FirstOrderFilter(0.0, 0.032, dt)
self._top_slant = FirstOrderFilter(0.0, 0.065, dt)
self._r = FirstOrderFilter(218.0, 0.14, dt)
self._g = FirstOrderFilter(232.0, 0.14, dt)
self._b = FirstOrderFilter(248.0, 0.14, dt)
self._bsm_alpha = FirstOrderFilter(0.0, 0.07, dt)
self._blinker_alpha = FirstOrderFilter(0.0, 0.06, dt)
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
def render(self, rect: rl.Rectangle, target: EyeTarget, alpha: float = 1.0, y_shift: float = 0.0) -> None:
if alpha < 0.01:
return
t = rl.get_time()
# Update bubbly & smooth filters
w = max(24.0, self._w.update(target.width) * self._scale_x.update(target.scale_x))
h = max(20.0, self._h.update(target.height) * self._scale_y.update(target.scale_y))
roundness = max(0.15, min(0.85, self._roundness.update(target.roundness)))
top_lid = max(0.0, min(0.95, self._top_lid.update(target.top_lid)))
bottom_lid = max(0.0, min(0.95, self._bottom_lid.update(target.bottom_lid)))
top_slant = self._top_slant.update(target.top_slant)
gaze_x = self._gaze_x.update(target.gaze_x)
gaze_y = self._gaze_y.update(target.gaze_y)
bounce_y = self._bounce_y.update(target.bounce_y)
tilt_y = self._tilt_y.update(target.tilt_y)
squish = max(-1.0, min(1.0, self._squish.update(target.squish_force)))
self._pitch_y.update(target.pitch_offset_y)
squish_abs = abs(squish)
r = max(0, min(255, int(self._r.update(target.color[0]))))
g = max(0, min(255, int(self._g.update(target.color[1]))))
b = max(0, min(255, int(self._b.update(target.color[2]))))
# Optional alert brightness pulse
pulse = 1.0
if target.pulse_speed > 0.0:
pulse = 0.72 + 0.28 * (0.5 + 0.5 * math.sin(t * target.pulse_speed * math.tau))
eff_alpha = max(0.0, min(1.0, alpha * pulse))
core_color = rl.Color(r, g, b, int(255 * eff_alpha))
# Subtle wall-cushion glow when centrifugal force squishes the bot strongly to one side
if squish_abs > 0.35:
wall_a = (squish_abs - 0.35) / 0.65
self._draw_wall_squish_glow(rect, 1 if squish > 0 else -1, core_color, wall_a * eff_alpha)
# Ambient edge accents (blind spot glow, blinker chevrons, boost speed lines)
bsm_a = self._bsm_alpha.update(1.0 if target.blind_spot_side != 0 else 0.0)
if bsm_a > 0.02 and target.blind_spot_side != 0:
self._draw_bsm_edge_glow(rect, target.blind_spot_side, bsm_a * alpha)
blinker_a = self._blinker_alpha.update(1.0 if target.blinker_side != 0 else 0.0)
if blinker_a > 0.02 and target.blinker_side != 0:
self._draw_blinker_indicator(rect, target.blinker_side, blinker_a * alpha, t)
if target.show_speed_lines:
self._draw_speed_lines(rect, core_color, eff_alpha, t)
# Slide the whole face horizontally toward the opposite side of the turn under centrifugal force
centrifugal_shift_x = squish * 76.0
cx = rect.x + rect.width / 2.0 + gaze_x + centrifugal_shift_x
cy = rect.y + rect.height / 2.0 - 8.0 + gaze_y + bounce_y + y_shift
# Compress spacing between eyes as the bot gets smooshed against the side wall
spacing = self.EYE_SPACING * (1.0 - 0.24 * squish_abs)
left_cx = cx - spacing / 2.0
right_cx = cx + spacing / 2.0
left_cy = cy - tilt_y
right_cy = cy + tilt_y
# Asymmetric centrifugal wall-squish: outer pressed eye squishes narrower & taller!
left_w_mult = (1.0 - 0.36 * max(0.0, -squish)) * (1.0 - 0.14 * max(0.0, squish))
left_h_mult = (1.0 + 0.16 * max(0.0, -squish)) * (1.0 - 0.05 * max(0.0, squish))
right_w_mult = (1.0 - 0.36 * max(0.0, squish)) * (1.0 - 0.14 * max(0.0, -squish))
right_h_mult = (1.0 + 0.16 * max(0.0, squish)) * (1.0 - 0.05 * max(0.0, -squish))
# Subtle 3D perspective scaling when glancing left/right
left_scale = 1.0 - max(0.0, gaze_x / 210.0)
right_scale = 1.0 + min(0.0, gaze_x / 210.0)
eye_configs = (
(left_cx, left_cy, w * left_scale * left_w_mult, h * left_scale * left_h_mult),
(right_cx, right_cy, w * right_scale * right_w_mult, h * right_scale * right_h_mult),
)
for side_idx, (ecx, ecy, ew, eh) in enumerate(eye_configs):
slant = top_slant if side_idx == 0 else -top_slant
glyph = EyeGlyph.CRESCENT if (side_idx == 1 and target.wink_right) else target.glyph
self._draw_eye(ecx, ecy, ew, eh, roundness, top_lid, bottom_lid, slant, glyph, core_color, eff_alpha, gaze_x, gaze_y, t)
if target.mouth != MouthGlyph.NONE:
self._draw_mouth(cx, cy + h * 0.72, target.mouth, core_color)
if target.show_zzz:
self._draw_floating_zzz(right_cx + w * 0.58, right_cy - h * 0.35, core_color, eff_alpha, t)
if target.show_hearts:
self._draw_floating_mini_hearts(cx, cy - h * 0.58, core_color, eff_alpha, t)
def _draw_wall_squish_glow(self, rect: rl.Rectangle, side: int, color: rl.Color, alpha: float) -> None:
glow_w = 46
edge = rl.Color(color.r, color.g, color.b, int(95 * alpha))
clear = rl.Color(color.r, color.g, color.b, 0)
if side < 0:
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), edge, clear)
else:
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, edge)
def _draw_bsm_edge_glow(self, rect: rl.Rectangle, side: int, alpha: float) -> None:
glow_w = 56
amber = rl.Color(255, 160, 30, int(145 * alpha))
clear = rl.Color(255, 160, 30, 0)
if side < 0:
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), amber, clear)
else:
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, amber)
def _draw_blinker_indicator(self, rect: rl.Rectangle, side: int, alpha: float, t: float) -> None:
"""Crisp pulsing directional chevron on the left/right edge for turn signals."""
pulse = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(t * 8.4))
col = rl.Color(85, 240, 140, int(235 * pulse * alpha))
glow = rl.Color(85, 240, 140, int(65 * pulse * alpha))
cy = rect.y + rect.height / 2.0
sign = 1.0 if side > 0 else -1.0
base_x = (rect.x + rect.width - 34.0) if side > 0 else (rect.x + 34.0)
for idx in range(2):
ox = base_x - sign * idx * 14.0
p_top = rl.Vector2(ox - sign * 10.0, cy - 18.0)
p_tip = rl.Vector2(ox + sign * 8.0, cy)
p_bot = rl.Vector2(ox - sign * 10.0, cy + 18.0)
rl.draw_line_ex(p_top, p_tip, 9.0, glow)
rl.draw_line_ex(p_tip, p_bot, 9.0, glow)
rl.draw_line_ex(p_top, p_tip, 4.5, col)
rl.draw_line_ex(p_tip, p_bot, 4.5, col)
def _draw_speed_lines(self, rect: rl.Rectangle, color: rl.Color, alpha: float, t: float) -> None:
"""Energetic animated speed streaks on the screen edges during sharp acceleration."""
for i in range(4):
phase = (t * 4.5 + i * 0.25) % 1.0
y = rect.y + 68.0 + i * 44.0
line_len = 26.0 + 22.0 * math.sin(phase * math.pi)
a = int(170 * math.sin(phase * math.pi) * alpha)
col = rl.Color(color.r, color.g, color.b, a)
# Left & right symmetrical streaks
lx = rect.x + 12.0 + (1.0 - phase) * 28.0
rx = rect.x + rect.width - 12.0 - (1.0 - phase) * 28.0
rl.draw_line_ex(rl.Vector2(lx, y), rl.Vector2(lx + line_len, y), 3.5, col)
rl.draw_line_ex(rl.Vector2(rx - line_len, y), rl.Vector2(rx, y), 3.5, col)
def _draw_floating_zzz(self, x: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
"""Softly drifting Zzz bubbles so sleepy/standstill state is continuously animated."""
for idx, ch in enumerate(("z", "Z")):
phase = (t * 0.55 + idx * 0.5) % 1.0
zx = x + phase * 18.0 + math.sin(phase * math.tau) * 4.0
zy = y - phase * 34.0
fade = math.sin(phase * math.pi)
size = 20 + idx * 8
col = rl.Color(color.r, color.g, color.b, int(190 * fade * alpha))
rl.draw_text_ex(self._font_semi_bold, ch, rl.Vector2(zx, zy), size, 0, col)
def _draw_floating_mini_hearts(self, cx: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
"""Floating mini-hearts above the face during pet/bookmark reactions."""
for idx, dx in enumerate((-62.0, 0.0, 62.0)):
phase = (t * 1.4 + idx * 0.33) % 1.0
hx = cx + dx + math.sin(phase * math.tau) * 6.0
hy = y - phase * 26.0
fade = math.sin(phase * math.pi)
col = rl.Color(color.r, color.g, color.b, int(210 * fade * alpha))
self._draw_heart_eye(hx, hy, 8.5, col, fade * alpha, with_glow=False)
def _draw_eye(
self,
cx: float,
cy: float,
w: float,
h: float,
roundness: float,
top_lid: float,
bottom_lid: float,
slant_deg: float,
glyph: EyeGlyph,
color: rl.Color,
alpha: float,
gaze_x: float,
gaze_y: float,
t: float,
) -> None:
if glyph == EyeGlyph.STAR:
self._draw_star_eye(cx, cy, min(w, h) * 0.48, color, alpha, t)
return
if glyph == EyeGlyph.HEART:
self._draw_heart_eye(cx, cy, min(w, h) * 0.48, color, alpha, with_glow=True)
return
if glyph == EyeGlyph.CRESCENT:
self._draw_crescent_eye(cx, cy, w, h, color, alpha)
return
# Silky radial OLED bloom (zero banding, consistent with star & heart eyes)
visible_frac = max(0.25, 1.0 - top_lid - bottom_lid)
bloom_r = max(w, h) * 0.78 * (0.65 + 0.35 * visible_frac)
rl.draw_circle_gradient(
rl.Vector2(cx, cy),
bloom_r,
rl.Color(color.r, color.g, color.b, int(92 * visible_frac * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
# Crisp eye core
core_rec = rl.Rectangle(cx - w / 2.0, cy - h / 2.0, w, h)
rl.draw_rectangle_rounded(core_rec, min(0.85, roundness), 24, color)
# Glossy dual specular catchlights (centered-dynamic so eyes never appear stuck staring at top-left)
glint_dx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.8
glint_dy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.4
glint_fade = 0.30 + 0.70 * visible_frac
hi_col = rl.Color(255, 255, 255, int(105 * alpha * glint_fade))
rl.draw_rectangle_rounded(
rl.Rectangle(cx - w * 0.14 + glint_dx, cy - h * 0.30 + glint_dy, w * 0.28, h * 0.16),
0.90,
12,
hi_col,
)
rl.draw_circle(
int(cx + w * 0.18 + glint_dx * 0.6),
int(cy + h * 0.22 + glint_dy * 0.6),
max(3.5, min(w, h) * 0.055),
rl.Color(255, 255, 255, int(75 * alpha * glint_fade)),
)
# Sparkle glint inside eyes during sharp acceleration boost
if glyph == EyeGlyph.SPARKLE_BOOST:
self._draw_boost_sparkle(cx, cy, min(w, h) * 0.22, alpha, t)
# Directional chevron glint inside eye during lane changes
if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT):
self._draw_chevron_glint(cx, cy, w * 0.24, glyph == EyeGlyph.ARROW_RIGHT, alpha)
# Laser-alert inner bright core bar
if glyph == EyeGlyph.LASER_ALERT:
inner_col = rl.Color(255, 235, 235, int(215 * alpha))
rl.draw_rectangle_rounded(rl.Rectangle(cx - w * 0.36, cy - 5, w * 0.72, 10), 0.85, 10, inner_col)
# Eyelid masks (pure black polygons over the OLED canvas, tall enough to cleanly clip outer halo)
if top_lid > 0.01 or abs(slant_deg) > 0.5:
lid_h = max(42.0, h * (top_lid + 0.55))
lid_w = w + 80.0
lid_cy = (cy - h / 2.0) + h * top_lid - lid_h / 2.0 - 4.0
if abs(slant_deg) > 0.01:
rad = math.radians(slant_deg)
c_ang, s_ang = math.cos(rad), math.sin(rad)
hw, hh = lid_w / 2.0, lid_h / 2.0
# CCW quad around (cx, lid_cy) in y-down screen coordinates
corners = [(-hw, -hh), (-hw, hh), (hw, hh), (hw, -hh)]
quad = [rl.Vector2(cx + x * c_ang - y * s_ang, lid_cy + x * s_ang + y * c_ang) for x, y in corners]
rl.draw_triangle_fan(quad, 4, rl.BLACK)
else:
rl.draw_rectangle_rec(rl.Rectangle(cx - lid_w / 2.0, lid_cy - lid_h / 2.0, lid_w, lid_h), rl.BLACK)
if bottom_lid > 0.01:
lid_h = max(36.0, h * (bottom_lid + 0.45))
lid_w = w + 80.0
lid_cy = (cy + h / 2.0) - h * bottom_lid + lid_h / 2.0 + 4.0
rl.draw_rectangle_rec(rl.Rectangle(cx - lid_w / 2.0, lid_cy - lid_h / 2.0, lid_w, lid_h), rl.BLACK)
def _draw_boost_sparkle(self, cx: float, cy: float, size: float, alpha: float, t: float) -> None:
"""4-point pulsing star sparkle inside eyes during sharp acceleration."""
s = size * (0.85 + 0.25 * math.sin(t * 14.0))
col = rl.Color(255, 255, 255, int(210 * alpha))
rl.draw_line_ex(rl.Vector2(cx - s, cy), rl.Vector2(cx + s, cy), 4.0, col)
rl.draw_line_ex(rl.Vector2(cx, cy - s), rl.Vector2(cx, cy + s), 4.0, col)
def _draw_chevron_glint(self, cx: float, cy: float, size: float, right: bool, alpha: float) -> None:
sign = 1.0 if right else -1.0
col = rl.Color(0, 0, 0, int(135 * alpha))
p_top = rl.Vector2(cx - sign * size * 0.35, cy - size * 0.75)
p_tip = rl.Vector2(cx + sign * size * 0.55, cy)
p_bot = rl.Vector2(cx - sign * size * 0.35, cy + size * 0.75)
rl.draw_line_ex(p_top, p_tip, 7.0, col)
rl.draw_line_ex(p_tip, p_bot, 7.0, col)
def _draw_star_eye(self, cx: float, cy: float, outer_r: float, color: rl.Color, alpha: float, t: float) -> None:
inner_r = outer_r * 0.44
spin = math.sin(t * 7.0) * 0.14 # playful wobble
pts: list[rl.Vector2] = []
for i in range(10):
angle = -math.pi / 2.0 + spin + i * (math.pi / 5.0)
rad = outer_r if i % 2 == 0 else inner_r
pts.append(rl.Vector2(cx + math.cos(angle) * rad, cy + math.sin(angle) * rad))
rl.draw_circle_gradient(
rl.Vector2(cx, cy), outer_r * 1.25,
rl.Color(color.r, color.g, color.b, int(90 * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
center = rl.Vector2(cx, cy)
fan = [center, *reversed(pts), pts[-1]]
rl.draw_triangle_fan(fan, len(fan), color)
def _draw_heart_eye(self, cx: float, cy: float, radius: float, color: rl.Color, alpha: float, with_glow: bool = True) -> None:
"""Seamless, perfectly symmetrical 48-point parametric smooth heart curve."""
if with_glow:
rl.draw_circle_gradient(
rl.Vector2(cx, cy), radius * 1.4,
rl.Color(color.r, color.g, color.b, int(92 * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
# Classic smooth parametric heart:
# x(t) = 16 sin^3(t), y(t) = -(13 cos(t) - 5 cos(2t) - 2 cos(3t) - cos(4t))
# Normalized so half-width ~= radius; centered vertically around cy
scale = radius / 16.0
n_pts = 48
pts: list[rl.Vector2] = []
for i in range(n_pts):
ang = (i / n_pts) * math.tau
s = math.sin(ang)
hx = 16.0 * (s * s * s)
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
center = rl.Vector2(cx, cy + radius * 0.05)
# Parametric curve runs clockwise in screen coords (y-down), so reversed fan is CCW
fan = [center, *reversed(pts), pts[-1]]
rl.draw_triangle_fan(fan, len(fan), color)
def _draw_crescent_eye(self, cx: float, cy: float, w: float, h: float, color: rl.Color, alpha: float) -> None:
radius = min(w, h) * 0.50
arc_cy = cy + radius * 0.35
glow_col = rl.Color(color.r, color.g, color.b, int(55 * alpha))
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 22.0, radius + 8.0, 200.0, 340.0, 28, glow_col)
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 14.0, radius, 202.0, 338.0, 28, color)
def _draw_mouth(self, cx: float, cy: float, mouth: MouthGlyph, color: rl.Color) -> None:
if mouth == MouthGlyph.SMILE:
rl.draw_ring(rl.Vector2(cx, cy - 10.0), 17.0, 23.0, 25.0, 155.0, 20, color)
elif mouth == MouthGlyph.BIG_GRIN:
rl.draw_ring(rl.Vector2(cx, cy - 12.0), 19.0, 26.0, 18.0, 162.0, 24, color)
elif mouth == MouthGlyph.FROWN:
rl.draw_ring(rl.Vector2(cx, cy + 16.0), 17.0, 23.0, 205.0, 335.0, 20, color)
elif mouth == MouthGlyph.SURPRISED:
rl.draw_ring(rl.Vector2(cx, cy + 2.0), 9.0, 15.0, 0.0, 360.0, 24, color)
@@ -0,0 +1,365 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from collections import deque
from dataclasses import dataclass, field
import math
import numpy as np
DEFAULT_SAMPLE_RATE = 16000
FRAME_RATE = 20.0
FFT_SIZE = 1024 # ~64ms analysis window
NUM_BANDS = 12
HISTORY_FRAMES = 50 # 2.5 seconds of flux/energy history @ 20 Hz
MIC_TARGET_RMS = 0.12
MIC_MAX_GAIN = 6.0
SOFT_KNEE = 0.7
# Tempo autocorrelation lag bounds @ 20 Hz: 7..18 frames -> 67..171 BPM
MIN_TEMPO_LAG = 7
MAX_TEMPO_LAG = 18
ENTER_MUSIC_CONF = 0.44
EXIT_MUSIC_CONF = 0.26
ENTER_DWELL_S = 0.9
ENTER_DWELL_NO_BEAT_S = 2.0
EXIT_DWELL_S = 2.5
HOLDOFF_S = 3.0
BEAT_LOCK_PERIODS = 3
BEAT_PERIOD_CV_TOLERANCE = 0.25
BEAT_HISTORY = 32
SYLLABIC_LOW_HZ = 3.0
SYLLABIC_HIGH_HZ = 8.0
SYLLABIC_FRAMES = 40
MIN_ACTIVE_RMS = 0.0025 # pre-gain RMS (~ -52 dBFS)
def _soft_limit(x: np.ndarray, knee: float = SOFT_KNEE) -> np.ndarray:
"""Linear below `knee`, smoothly saturating above it. Unlike np.clip this adds no harmonics."""
ax = np.abs(x)
if not np.any(ax > knee):
return x.astype(np.float32)
out = x.astype(np.float32).copy()
over = ax > knee
span = 1.0 - knee
out[over] = np.sign(x[over]) * (knee + span * np.tanh((ax[over] - knee) / span))
return out
@dataclass
class MusicState:
is_music: bool = False
confidence: float = 0.0
beat_pulse: float = 0.0 # 0..1 sharp onset with smooth decay
groove_phase: float = 0.0
bpm: float = 116.0
energy: float = 0.0 # 0..1 normalized musical loudness
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
beat_locked: bool = False
class MusicAnalyzer:
"""Low-CPU pure-NumPy cabin music detector, beat tracker, and 12-band equalizer analyzer.
Tuned for real car cabins (road/wind/HVAC rumble + conversation):
1. Adaptive mic gain + soft limiting (never hard-clips the analysis buffer)
2. Per-bin adaptive spectral noise-floor subtraction
3. Harmonic peak prominence & spectral tonality (rejects broadband road/wind noise)
4. Musical bandwidth + spectral frame stability (rejects speech formants)
5. Rhythmic tempo periodicity (spectral flux autocorrelation at 67-171 BPM)
6. Syllabic 3-8 Hz envelope modulation as an explicit speech term
7. Dwell + holdoff + beat lock before claiming "music"
"""
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE):
self._sample_rate = sample_rate
self._window = np.hanning(FFT_SIZE).astype(np.float32)
self._ring = np.zeros(FFT_SIZE, dtype=np.float32)
self._prev_mag: np.ndarray | None = None
self._prev_excess_norm: np.ndarray | None = None
self._noise_spec: np.ndarray | None = None
self._confidence: float = 0.0
self._is_music: bool = False
self._beat_pulse: float = 0.0
self._groove_phase: float = 0.0
self._bpm: float = 116.0
self._energy: float = 0.0
self._bands = np.zeros(NUM_BANDS, dtype=np.float32)
self._flux_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
self._active_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
self._bass_flux_hist: deque[float] = deque(maxlen=20)
self._stability_hist: deque[float] = deque(maxlen=20)
self._speech_env: deque[float] = deque(maxlen=SYLLABIC_FRAMES)
self._beat_onsets: deque[float] = deque(maxlen=BEAT_HISTORY)
self._t: float = 0.0
self._enter_timer: float = 0.0
self._exit_timer: float = 0.0
self._holdoff_until: float = 0.0
self._beat_locked: bool = False
self._build_frequency_masks(sample_rate)
def _build_frequency_masks(self, sr: int) -> None:
self._sample_rate = sr
freqs = np.fft.rfftfreq(FFT_SIZE, d=1.0 / sr)
self._freqs = freqs
self._bass_mask = (freqs >= 55.0) & (freqs < 230.0)
self._speech_mask = (freqs >= 300.0) & (freqs < 2400.0)
self._treble_mask = (freqs >= 2600.0) & (freqs < min(7600.0, sr * 0.48))
self._tonal_mask = (freqs >= 85.0) & (freqs < 4500.0)
# 12 log-spaced equalizer bands (60 Hz .. 7200 Hz)
edges = np.geomspace(60.0, min(7200.0, sr * 0.47), NUM_BANDS + 1)
self._band_slices: list[tuple[int, int]] = []
for i in range(NUM_BANDS):
lo = int(np.searchsorted(freqs, edges[i]))
hi = max(lo + 1, int(np.searchsorted(freqs, edges[i + 1])))
self._band_slices.append((lo, min(hi, len(freqs))))
@property
def state(self) -> MusicState:
return MusicState(
is_music=self._is_music,
confidence=self._confidence,
beat_pulse=self._beat_pulse,
groove_phase=self._groove_phase,
bpm=self._bpm,
energy=self._energy,
bands=tuple(float(b) for b in self._bands),
beat_locked=self._beat_locked,
)
def step_visual_decay(self, dt: float) -> MusicState:
"""Advance smooth 60 FPS groove phase and beat decay between 20 Hz audio chunks."""
if self._is_music:
rad_per_sec = (self._bpm / 60.0) * math.tau
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % math.tau
decay = math.exp(-dt * 7.5)
self._beat_pulse *= decay
if not self._is_music:
self._bands *= math.exp(-dt * 6.0)
return self.state
def process_audio_bytes(self, data: bytes, sample_rate: int = DEFAULT_SAMPLE_RATE) -> MusicState:
"""Process a rawAudioData int16 PCM byte buffer from micd."""
if not data:
return self.state
if sample_rate > 0 and sample_rate != self._sample_rate:
self._build_frequency_masks(sample_rate)
samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
return self.process_samples(samples)
def process_samples(self, samples: np.ndarray) -> MusicState:
"""Analyze a normalized float32 [-1, 1] mono audio chunk (~50 ms)."""
n = len(samples)
if n == 0:
return self.state
dt = 1.0 / FRAME_RATE
self._t += dt
raw_rms = float(np.sqrt(np.mean(samples * samples)))
if raw_rms > 1e-6:
mic_gain = float(np.clip(MIC_TARGET_RMS / raw_rms, 1.0, MIC_MAX_GAIN))
else:
mic_gain = MIC_MAX_GAIN
boosted = _soft_limit(samples * mic_gain)
if n >= FFT_SIZE:
self._ring[:] = boosted[-FFT_SIZE:]
else:
self._ring[:-n] = self._ring[n:]
self._ring[-n:] = boosted
rms = float(np.sqrt(np.mean(self._ring * self._ring)))
# FFT magnitude & power spectrum
spec = np.abs(np.fft.rfft(self._ring * self._window)) / (FFT_SIZE * 0.5)
power = spec * spec + 1e-12
# Per-bin slow stationary cabin noise floor (tracks down quickly, creeps up very slowly)
if self._noise_spec is None or len(self._noise_spec) != len(power):
self._noise_spec = power.copy()
else:
lower = power < self._noise_spec
self._noise_spec = np.where(
lower,
0.92 * self._noise_spec + 0.08 * power,
0.9985 * self._noise_spec + 0.0015 * power,
)
# Spectral subtraction removes steady highway/HVAC rumble while preserving harmonic music peaks
excess_power = np.maximum(0.0, power - 1.25 * self._noise_spec)
excess_mag = np.sqrt(excess_power + 1e-12)
excess_total = float(np.sum(excess_power[self._tonal_mask]))
above_floor = raw_rms >= MIN_ACTIVE_RMS and excess_total > 1e-6
self._active_hist.append(1.0 if above_floor else 0.0)
# 1. Harmonic peak prominence & tonality (rejects flat broadband road/wind noise)
tonal_p = power[self._tonal_mask]
median_p = float(np.median(tonal_p)) + 1e-12
# Top 8% harmonic bins vs median: music has crisp harmonic peaks (>12x), road noise is ~2-4x
p92 = float(np.percentile(tonal_p, 92))
peak_ratio = p92 / median_p
peak_score = float(np.clip((math.log10(max(1.0, peak_ratio)) - 0.72) / 0.85, 0.0, 1.0))
geo_mean = float(np.exp(np.mean(np.log(tonal_p))))
arith_mean = float(np.mean(tonal_p))
flatness = geo_mean / max(arith_mean, 1e-12)
flat_score = float(np.clip((0.56 - flatness) / 0.36, 0.0, 1.0))
tonality_score = max(peak_score, flat_score * 0.85)
# 2. Musical bandwidth balance (bass + treble vs pure narrowband human speech)
total_p = float(np.sum(power[1:])) + 1e-12
bass_ratio = float(np.sum(power[self._bass_mask])) / total_p
speech_ratio = float(np.sum(power[self._speech_mask])) / total_p
treble_ratio = float(np.sum(power[self._treble_mask])) / total_p
non_speech_ratio = bass_ratio + treble_ratio
bandwidth_score = float(np.clip(non_speech_ratio / 0.24, 0.0, 1.0))
narrowband_speech = speech_ratio > 0.82 and bass_ratio < 0.09 and treble_ratio < 0.06
if narrowband_speech:
bandwidth_score *= 0.20
# 3. Spectral harmonic stability (sustained musical chords/notes vs shifting speech formants)
tonal_vec = excess_mag[self._tonal_mask]
vec_norm = float(np.linalg.norm(tonal_vec)) + 1e-9
norm_vec = tonal_vec / vec_norm
if self._prev_excess_norm is not None and len(self._prev_excess_norm) == len(norm_vec):
sim = float(np.dot(norm_vec, self._prev_excess_norm))
self._stability_hist.append(sim)
self._prev_excess_norm = norm_vec
stability = float(np.mean(self._stability_hist)) if self._stability_hist else 0.0
stability_score = float(np.clip((stability - 0.55) / 0.32, 0.0, 1.0))
# 4. Spectral flux & tempo periodicity (67-171 BPM)
if self._prev_mag is None:
flux = 0.0
bass_flux = 0.0
else:
diff = np.maximum(0.0, spec - self._prev_mag)
flux = float(np.sum(diff))
bass_flux = float(np.sum(diff[self._bass_mask]))
self._prev_mag = spec
self._flux_hist.append(flux)
self._bass_flux_hist.append(bass_flux)
rhythm_score = 0.0
if len(self._flux_hist) >= MAX_TEMPO_LAG + 10:
arr = np.array(self._flux_hist, dtype=np.float32)
arr_centered = arr - np.mean(arr)
denom = float(np.dot(arr_centered, arr_centered))
if denom > 1e-9:
best_corr = 0.0
best_lag = 10
for lag in range(MIN_TEMPO_LAG, MAX_TEMPO_LAG + 1):
c = float(np.dot(arr_centered[:-lag], arr_centered[lag:])) / denom
if c > best_corr:
best_corr = c
best_lag = lag
rhythm_score = float(np.clip((best_corr - 0.12) / 0.30, 0.0, 1.0))
if best_corr > 0.20:
est_bpm = (60.0 * FRAME_RATE) / best_lag
self._bpm = 0.88 * self._bpm + 0.12 * float(np.clip(est_bpm, 72.0, 172.0))
beat_onset = False
if len(self._bass_flux_hist) >= 6:
bf_mean = float(np.mean(self._bass_flux_hist))
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
if bass_flux > bf_mean + 0.85 * bf_std and bass_flux > 0.008:
beat_onset = True
strength = float(np.clip((bass_flux - bf_mean) / (2.0 * bf_std), 0.45, 1.0))
if self._is_music:
self._beat_pulse = max(self._beat_pulse, strength)
self._beat_onsets.append(self._t)
self._beat_locked = False
if len(self._beat_onsets) >= BEAT_LOCK_PERIODS:
recent = np.array(list(self._beat_onsets)[-BEAT_LOCK_PERIODS:], dtype=np.float32)
periods = np.diff(recent)
if periods.size and float(periods.mean()) > 1e-3:
cv = float(periods.std() / periods.mean())
self._beat_locked = cv <= BEAT_PERIOD_CV_TOLERANCE
if self._beat_locked and beat_onset and self._is_music:
self._groove_phase = 0.0
speech_band = float(np.sqrt(np.sum(power[self._speech_mask]) + 1e-12))
self._speech_env.append(speech_band)
syllabic_score = 0.0
if len(self._speech_env) >= SYLLABIC_FRAMES:
env = np.array(self._speech_env, dtype=np.float32)
env = env - float(env.mean())
if float(np.abs(env).sum()) > 1e-9:
env_spec = np.abs(np.fft.rfft(env * np.hanning(env.size)))
env_freqs = np.fft.rfftfreq(env.size, d=1.0 / FRAME_RATE)
band = (env_freqs >= SYLLABIC_LOW_HZ) & (env_freqs <= SYLLABIC_HIGH_HZ)
total_env = float(env_spec.sum()) + 1e-9
ratio = float(env_spec[band].sum()) / total_env
syllabic_score = float(np.clip((ratio - 0.20) / 0.45, 0.0, 1.0))
speech_likeness = max(syllabic_score, 0.75 if narrowband_speech else 0.0)
continuity = float(np.mean(self._active_hist)) if self._active_hist else 0.0
continuity_score = float(np.clip((continuity - 0.48) / 0.40, 0.0, 1.0))
# Combine features: accepts both rhythmic pop/EDM/hip-hop AND harmonic acoustic/chill music,
if not above_floor:
frame_score = 0.0
else:
musical_drive = max(rhythm_score, 0.72 * stability_score)
frame_score = (
0.26 * tonality_score
+ 0.24 * bandwidth_score
+ 0.26 * musical_drive
+ 0.16 * continuity_score
- 0.22 * speech_likeness
)
frame_score = float(np.clip(frame_score, 0.0, 1.0))
if tonality_score < 0.24 or bandwidth_score < 0.22:
frame_score *= 0.25
alpha = 0.075 if frame_score > self._confidence else 0.035
self._confidence = (1.0 - alpha) * self._confidence + alpha * frame_score
if self._is_music:
self._exit_timer = self._exit_timer + dt if self._confidence <= EXIT_MUSIC_CONF else 0.0
if self._exit_timer >= EXIT_DWELL_S:
self._is_music = False
self._exit_timer = 0.0
self._enter_timer = 0.0
self._holdoff_until = self._t + HOLDOFF_S
elif self._t >= self._holdoff_until:
confident = self._confidence >= ENTER_MUSIC_CONF
eligible = confident and (self._beat_locked or self._confidence >= ENTER_MUSIC_CONF + 0.12)
self._enter_timer = self._enter_timer + dt if eligible else 0.0
required = ENTER_DWELL_S if self._beat_locked else ENTER_DWELL_NO_BEAT_S
if self._enter_timer >= required:
self._is_music = True
self._enter_timer = 0.0
self._exit_timer = 0.0
# Normalized energy & 12-band equalizer bars
self._energy = float(np.clip(rms / 0.35, 0.0, 1.0))
for i, (lo, hi) in enumerate(self._band_slices):
band_mag = float(np.sqrt(np.mean(power[lo:hi])))
tilt = 1.0 + 0.16 * i
norm = float(np.clip(math.log1p(band_mag * 95.0 * tilt) / 2.1, 0.0, 1.0))
if norm > self._bands[i]:
self._bands[i] = 0.45 * self._bands[i] + 0.55 * norm
else:
self._bands[i] = 0.78 * self._bands[i] + 0.22 * norm
return self.state
@@ -0,0 +1,127 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import raylib_nb as rl
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState, NUM_BANDS
from openpilot.system.ui.lib.application import gui_app
def groove_prism_color(t: float) -> tuple[int, int, int]:
"""Smoothly cycle vibrant OLED-friendly cyan -> aqua -> orchid -> mint hues while grooving."""
# Smooth cosine palette keeping high brightness and pleasant saturation
r = int(125 + 95 * math.sin(t * 0.9 + 2.2))
g = int(195 + 55 * math.sin(t * 0.9 + 0.4))
b = int(215 + 40 * math.sin(t * 0.9 + 4.1))
return (max(50, min(255, r)), max(90, min(255, g)), max(140, min(255, b)))
class MusicVisualizerRenderer:
"""Smooth 60 FPS OLED equalizer bars, bass pulse aura, and floating musical notes."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._alpha = FirstOrderFilter(0.0, 0.16, dt)
self._bar_filters = [FirstOrderFilter(0.0, 0.06, dt) for _ in range(NUM_BANDS)]
def render_background(self, rect: rl.Rectangle, music: MusicState, active: bool) -> float:
"""Render smooth ambient bass aura & bottom pill equalizer bars; returns current visualizer alpha."""
alpha = self._alpha.update(1.0 if active else 0.0)
if alpha < 0.01:
return 0.0
t = rl.get_time()
cr, cg, cb = groove_prism_color(t)
# 1. Soft beat-reactive ambient bass aura along bottom center
aura_r = 140.0 + 75.0 * music.beat_pulse + 35.0 * music.energy
aura_alpha = int((42 + 52 * music.beat_pulse) * alpha)
rl.draw_circle_gradient(
rl.Vector2(rect.x + rect.width / 2.0, rect.y + rect.height + 10.0),
aura_r,
rl.Color(cr, cg, cb, aura_alpha),
rl.Color(cr, cg, cb, 0),
)
# 2. Smooth 12-band symmetric pill equalizer along the bottom edge
bar_count = NUM_BANDS
total_w = rect.width - 76.0
gap = 10.0
bar_w = (total_w - gap * (bar_count - 1)) / bar_count
start_x = rect.x + (rect.width - total_w) / 2.0
base_y = rect.y + rect.height - 8.0
max_bar_h = 44.0
for i in range(bar_count):
raw_level = music.bands[i] if i < len(music.bands) else 0.0
# Keep a smooth living wave + subtle beat lift on bass/mid bars
wave = 0.14 + 0.10 * math.sin(t * 5.0 + i * 0.65)
beat_lift = music.beat_pulse * (0.28 if i < 6 else 0.16)
level = self._bar_filters[i].update(min(1.0, max(wave, raw_level + beat_lift)))
bar_h = max(8.0, level * max_bar_h)
bx = start_x + i * (bar_w + gap)
by = base_y - bar_h
# Subtle color gradient across the spectrum (cyan -> violet -> pink)
frac = i / max(1, bar_count - 1)
br = int(min(255, cr * (1.0 - frac * 0.25) + 255 * frac * 0.25))
bg = int(min(255, cg * (1.0 - frac * 0.30) + 120 * frac * 0.30))
bb = int(min(255, cb * 0.85 + 255 * 0.15))
# Soft glow cap on taller bars
if level > 0.35:
rl.draw_circle_gradient(
rl.Vector2(bx + bar_w / 2.0, by + 4.0),
bar_w * 1.15,
rl.Color(br, bg, bb, int(75 * level * alpha)),
rl.Color(br, bg, bb, 0),
)
bar_col = rl.Color(br, bg, bb, int((155 + 90 * level) * alpha))
rl.draw_rectangle_rounded(rl.Rectangle(bx, by, bar_w, bar_h), 0.9, 10, bar_col)
return alpha
def render_foreground_notes(self, rect: rl.Rectangle, music: MusicState, alpha: float) -> None:
"""Draw cute floating vector musical notes on the left and right edges while grooving."""
if alpha < 0.05:
return
t = rl.get_time()
cr, cg, cb = groove_prism_color(t + 1.2)
note_specs = (
(rect.x + 48.0, 0.0, 1.0),
(rect.x + rect.width - 48.0, 0.5, -1.0),
(rect.x + 82.0, 0.28, 0.8),
(rect.x + rect.width - 82.0, 0.76, -0.8),
)
for base_x, phase_off, sway_dir in note_specs:
phase = (t * 0.65 + phase_off) % 1.0
fade = math.sin(phase * math.pi)
nx = base_x + math.sin(phase * math.tau) * 10.0 * sway_dir
ny = rect.y + 150.0 - phase * 98.0
scale = 0.85 + 0.25 * music.beat_pulse
col = rl.Color(cr, cg, cb, int(215 * fade * alpha))
self._draw_eighth_note(nx, ny, 7.5 * scale, col)
def _draw_eighth_note(self, cx: float, cy: float, r: float, color: rl.Color) -> None:
"""Crisp vector eighth-note glyph (♪) — zero font dependency."""
rl.draw_circle(int(cx), int(cy), r * 0.72, color)
stem_x = cx + r * 0.58
stem_top = cy - r * 2.5
rl.draw_line_ex(rl.Vector2(stem_x, cy), rl.Vector2(stem_x, stem_top), 2.8, color)
# Curved flag
rl.draw_line_ex(
rl.Vector2(stem_x, stem_top),
rl.Vector2(stem_x + r * 1.15, stem_top + r * 0.95),
2.8,
color,
)
@@ -0,0 +1,214 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import raylib_nb as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import BookmarkIcon
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.alert_overlay import RoboticAlertOverlay
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
RoboticMood,
RoboticMoodEngine,
snapshot_from_ui_state,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.face_renderer import ProceduralFaceRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicAnalyzer, MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import MusicVisualizerRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.speed_arc_renderer import SpeedArcRenderer
from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus
from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state
from openpilot.system.ui.lib.application import (
FontWeight,
MouseEvent,
MousePos,
TextAlignment,
TextAlignmentVertical,
gui_app,
)
from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.widgets.label import UnifiedLabel
VERTICAL_SWIPE_THRESHOLD = 45.0 # px
class RoboticOnroadView(Widget):
"""Full-screen EMO-inspired Robotic Companion onroad view for MICI (536x240 @ 60 FPS)."""
def __init__(self, bookmark_callback=None):
super().__init__()
self._bookmark_callback = bookmark_callback
self._mood_engine = RoboticMoodEngine(params=getattr(ui_state, "params", None))
self._face_renderer = ProceduralFaceRenderer()
self._speed_renderer = SpeedArcRenderer()
self._alert_overlay = RoboticAlertOverlay()
self._music_analyzer = MusicAnalyzer()
self._music_visualizer = MusicVisualizerRenderer()
self._bookmark_icon = BookmarkIcon(self._on_bookmark_triggered)
dt = 1.0 / max(gui_app.target_fps, 1)
self._speed_blend = FirstOrderFilter(0.0, 0.08, dt)
# Vertical swipe tracking (up = speed peek, down = pet robot)
self._touch_start_y: float = 0.0
self._touch_start_x: float = 0.0
self._vertical_swipe_handled: bool = False
self._offroad_label = UnifiedLabel(
"start the car to\nuse sunnypilot",
54,
FontWeight.DISPLAY,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
alignment=TextAlignment.CENTER,
alignment_vertical=TextAlignmentVertical.MIDDLE,
)
def _on_bookmark_triggered(self) -> None:
self._mood_engine.trigger_love(wink=True)
if self._bookmark_callback is not None:
self._bookmark_callback()
def is_swiping_left(self) -> bool:
"""Match AugmentedRoadView API so MiciMainLayout disables horizontal scroller during bookmark swipe."""
return self._bookmark_icon.is_swiping_left()
def _update_state(self) -> None:
super()._update_state()
if ui_state.panda_type == log.PandaState.PandaType.unknown:
self._offroad_label.set_text("system booting")
elif ui_state.ignition and not ui_state.started:
self._offroad_label.set_text("openpilot can't start\ncheck alerts")
else:
self._offroad_label.set_text("start the car to\nuse sunnypilot")
def _handle_mouse_event(self, mouse_event: MouseEvent) -> None:
if ui_state.started:
if mouse_event.left_pressed:
self._touch_start_x = mouse_event.pos.x
self._touch_start_y = mouse_event.pos.y
self._vertical_swipe_handled = False
elif mouse_event.left_down and not self._vertical_swipe_handled:
dx = abs(mouse_event.pos.x - self._touch_start_x)
dy = mouse_event.pos.y - self._touch_start_y
if abs(dy) > VERTICAL_SWIPE_THRESHOLD and abs(dy) > dx * 1.4:
self._vertical_swipe_handled = True
if dy < 0:
self._mood_engine.trigger_speed_peek()
else:
self._mood_engine.trigger_love()
self._bookmark_icon._handle_mouse_event(mouse_event)
super()._handle_mouse_event(mouse_event)
def _handle_mouse_release(self, mouse_pos: MousePos) -> None:
if self._vertical_swipe_handled:
self._vertical_swipe_handled = False
return
if not self._bookmark_icon.interacting():
super()._handle_mouse_release(mouse_pos)
def _render(self, _) -> None:
rl.draw_rectangle_rec(self.rect, rl.BLACK)
if not ui_state.started:
# Keep subtle animated sleepy eyes behind the offroad message so the screen is never static
sleepy_snap = DrivingSnapshot(started=False, standstill=True)
eye_target = self._mood_engine.update(sleepy_snap)
self._face_renderer.render(self.rect, eye_target, alpha=0.28, y_shift=16.0)
self._offroad_label.render(self._rect)
return
alert = self._alert_overlay.get_alert()
if ui_state.sm.updated["rawAudioData"] and alert is None:
raw_audio = ui_state.sm["rawAudioData"]
self._music_analyzer.process_audio_bytes(raw_audio.data, int(raw_audio.sampleRate))
music_state = self._music_analyzer.step_visual_decay(1.0 / max(gui_app.target_fps, 1))
snap = snapshot_from_ui_state(ui_state, alert)
snap.music = music_state
self._render_from_snapshot(snap, alert)
self._bookmark_icon.render(self.rect)
def _render_from_snapshot(self, snap: DrivingSnapshot, alert) -> None:
eye_target = self._mood_engine.update(snap)
speed_alpha = self._speed_blend.update(1.0 if self._mood_engine.showing_speed else 0.0)
face_alpha = 1.0 - speed_alpha
# Shift eyes slightly upward when a bottom alert banner or music equalizer is visible
grooving = self._mood_engine.mood == RoboticMood.MUSIC_GROOVE and alert is None
alert_shift = -26.0 if alert is not None else (-14.0 if grooving else 0.0)
music_state = snap.music or MusicState()
viz_alpha = 0.0
if face_alpha > 0.01:
viz_alpha = self._music_visualizer.render_background(self.rect, music_state, active=grooving)
self._face_renderer.render(self.rect, eye_target, alpha=face_alpha, y_shift=alert_shift)
if viz_alpha > 0.05:
self._music_visualizer.render_foreground_notes(self.rect, music_state, alpha=viz_alpha * face_alpha)
if alert is None:
self._speed_renderer.render_corner_badge(self.rect, snap, alpha=face_alpha)
if speed_alpha > 0.01:
self._speed_renderer.render_speed_mode(
self.rect,
snap,
alpha=speed_alpha,
cruising_smoothly=self._mood_engine.cruising_smoothly,
reason=self._mood_engine.speed_reason,
)
self._alert_overlay.render(self.rect, alert)
def show_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME)
def hide_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE)
if __name__ == "__main__":
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
gui_app.init_window("MICI Robotic Companion Preview")
view = RoboticOnroadView()
view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
print("Keys: [1] Engaged [2] MADS [3] Disengaged [4] Speed Peek [5] Stars [6] Love [7] Prompt [8] Critical [9] Pout [Left/Right] Steer")
for _ in gui_app.render():
if rl.is_key_pressed(rl.KeyboardKey.KEY_ONE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_TWO):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=20.0, set_speed_kph=90.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_THREE):
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FOUR):
view._mood_engine.trigger_speed_peek()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FIVE):
view._mood_engine.trigger_startled()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SIX):
view._mood_engine.trigger_love()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SEVEN):
snap.alert = Alert("Pay Attention", "Eyes on road", status=log.SelfdriveState.AlertStatus.userPrompt)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_EIGHT):
snap.alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=log.SelfdriveState.AlertStatus.critical)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_NINE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
elif rl.is_key_down(rl.KeyboardKey.KEY_LEFT):
snap.steering_angle_deg = 30.0
elif rl.is_key_down(rl.KeyboardKey.KEY_RIGHT):
snap.steering_angle_deg = -30.0
else:
snap.steering_angle_deg = 0.0
rl.draw_rectangle_rec(view.rect, rl.BLACK)
view._render_from_snapshot(snap, snap.alert)
@@ -0,0 +1,218 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import raylib_nb as rl
from openpilot.common.filter_simple import BounceFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
PALETTE,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.ui_state import UIStatus
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.lib.text_measure import measure_text_cached
class SpeedArcRenderer:
"""Reference-video-inspired color-coded speed + curved arc gauge and subtle Set-Speed badge."""
SPEED_FONT_SIZE = 114
UNIT_FONT_SIZE = 24
BADGE_SPEED_FONT_SIZE = 32
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY)
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM)
self._arc_progress = BounceFilter(0.0, 0.11, dt, bounce=2.4)
def _speed_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.OVERRIDE or snap.a_ego > 1.8:
return (255, 205, 65) # Warm yellow/amber
if snap.status == UIStatus.ENGAGED:
return (85, 238, 150) # Vibrant green
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
return (240, 245, 255) # Crisp white
def render_speed_mode(
self,
rect: rl.Rectangle,
snap: DrivingSnapshot,
alpha: float,
cruising_smoothly: bool,
reason: str,
) -> None:
if alpha < 0.01:
return
t = rl.get_time()
cur_speed, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
speed_color = rl.Color(sr, sg, sb, int(255 * alpha))
sub_color = rl.Color(255, 255, 255, int(195 * alpha))
cx = rect.x + rect.width / 2.0
# Subtle breathing float so speed mode is alive and never frozen
float_y = math.sin(t * 2.2) * 2.0
# Top accent above speed: MAX set-speed pill or gently pulsing heart
if reason == "set_speed" and set_speed is not None:
pill_text = f"{tr('MAX')} {set_speed}"
pill_sz = measure_text_cached(self._font_semi_bold, pill_text, 26)
pill_w = pill_sz.x + 28
pill_h = 34
pill_rect = rl.Rectangle(cx - pill_w / 2.0, rect.y + 14 + float_y * 0.5, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rect, 0.5, 14, rl.Color(sr, sg, sb, int(48 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rect, 0.5, 14, 2.0, rl.Color(sr, sg, sb, int(180 * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
pill_text,
rl.Vector2(cx - pill_sz.x / 2.0, pill_rect.y + (pill_h - pill_sz.y) / 2.0),
26,
0,
speed_color,
)
elif cruising_smoothly:
heart_r = 10.0 * (1.0 + 0.10 * math.sin(t * 4.5))
self._draw_tiny_heart(cx, rect.y + 30 + float_y * 0.5, heart_r, rl.Color(255, 118, 168, int(240 * alpha)))
elif set_speed is not None:
max_lbl = f"{tr('MAX')} {set_speed}"
lbl_sz = measure_text_cached(self._font_medium, max_lbl, self.UNIT_FONT_SIZE)
rl.draw_text_ex(
self._font_medium,
max_lbl,
rl.Vector2(cx - lbl_sz.x / 2.0, rect.y + 18 + float_y * 0.5),
self.UNIT_FONT_SIZE,
0,
sub_color,
)
# Big centered speed number
speed_text = str(cur_speed)
speed_sz = measure_text_cached(self._font_display, speed_text, self.SPEED_FONT_SIZE)
speed_y = rect.y + rect.height / 2.0 - speed_sz.y / 2.0 - 8.0 + float_y
rl.draw_text_ex(
self._font_display,
speed_text,
rl.Vector2(cx - speed_sz.x / 2.0, speed_y),
self.SPEED_FONT_SIZE,
0,
speed_color,
)
# Unit beside speed (small & subtle)
unit_text = tr("km/h") if snap.is_metric else tr("mph")
rl.draw_text_ex(
self._font_medium,
unit_text,
rl.Vector2(cx + speed_sz.x / 2.0 + 10.0, speed_y + speed_sz.y - 34.0),
self.UNIT_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(150 * alpha)),
)
# Curved arc speedometer gauge underneath (matches reference video)
max_ref = float(set_speed) if (set_speed is not None and set_speed > 0) else (130.0 if snap.is_metric else 85.0)
raw_frac = max(0.0, min(1.0, cur_speed / max_ref))
frac = max(0.0, min(1.0, self._arc_progress.update(raw_frac)))
arc_center = rl.Vector2(cx, rect.y + rect.height + 74.0)
inner_r = 104.0
outer_r = 114.0
mid_r = (inner_r + outer_r) / 2.0
cap_r = (outer_r - inner_r) / 2.0
start_deg = 228.0
end_deg = 312.0
span_deg = end_deg - start_deg
# Track background arc with rounded caps
track_col = rl.Color(255, 255, 255, int(45 * alpha))
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, end_deg, 32, track_col)
for deg in (start_deg, end_deg):
rad = math.radians(deg)
rl.draw_circle(int(arc_center.x + math.cos(rad) * mid_r), int(arc_center.y + math.sin(rad) * mid_r), cap_r, track_col)
# Active glowing arc + bright animated tip pip
if frac > 0.01:
active_end = start_deg + span_deg * frac
glow_pulse = 0.78 + 0.22 * math.sin(t * 3.5)
rl.draw_ring(
arc_center,
inner_r - 4.0,
outer_r + 4.0,
start_deg,
active_end,
32,
rl.Color(sr, sg, sb, int(65 * glow_pulse * alpha)),
)
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, active_end, 32, speed_color)
# Rounded start cap & bright glowing tip pip
s_rad = math.radians(start_deg)
e_rad = math.radians(active_end)
rl.draw_circle(int(arc_center.x + math.cos(s_rad) * mid_r), int(arc_center.y + math.sin(s_rad) * mid_r), cap_r, speed_color)
tip_x = arc_center.x + math.cos(e_rad) * mid_r
tip_y = arc_center.y + math.sin(e_rad) * mid_r
rl.draw_circle_gradient(
rl.Vector2(tip_x, tip_y),
14.0,
rl.Color(255, 255, 255, int(140 * glow_pulse * alpha)),
rl.Color(sr, sg, sb, 0),
)
rl.draw_circle(int(tip_x), int(tip_y), cap_r + 1.5, rl.Color(255, 255, 255, int(235 * alpha)))
def render_corner_badge(self, rect: rl.Rectangle, snap: DrivingSnapshot, alpha: float) -> None:
"""Subtle top-left Set-Speed / engagement pill visible during normal hero-face mode."""
if alpha < 0.01:
return
t = rl.get_time()
_, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
dot_pulse = 0.72 + 0.28 * math.sin(t * 3.0)
x = rect.x + 16.0
y = rect.y + 12.0
if set_speed is not None:
text = str(set_speed)
sz = measure_text_cached(self._font_semi_bold, text, self.BADGE_SPEED_FONT_SIZE)
pill_w = sz.x + 48.0
pill_h = 38.0
pill_rec = rl.Rectangle(x, y, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rec, 0.5, 14, rl.Color(255, 255, 255, int(22 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rec, 0.5, 14, 1.5, rl.Color(255, 255, 255, int(35 * alpha)))
rl.draw_circle(int(x + 16), int(y + pill_h / 2.0), 5.0, rl.Color(sr, sg, sb, int(235 * dot_pulse * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
text,
rl.Vector2(x + 28.0, y + (pill_h - sz.y) / 2.0),
self.BADGE_SPEED_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(210 * alpha)),
)
else:
rl.draw_circle(int(x + 10), int(y + 12), 5.5, rl.Color(sr, sg, sb, int(200 * dot_pulse * alpha)))
def _draw_tiny_heart(self, cx: float, cy: float, radius: float, color: rl.Color) -> None:
scale = radius / 16.0
n_pts = 32
pts: list[rl.Vector2] = []
for i in range(n_pts):
ang = (i / n_pts) * math.tau
s = math.sin(ang)
hx = 16.0 * (s * s * s)
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
center = rl.Vector2(cx, cy + radius * 0.05)
fan = [center, *reversed(pts), pts[-1]]
rl.draw_triangle_fan(fan, len(fan), color)
@@ -44,7 +44,8 @@ class UIStateSP:
self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch")
self.sm_services_ext = [
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP"
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP",
"gyroscope",
]
self.sunnylink_state = SunnylinkState()
@@ -60,6 +61,7 @@ class UIStateSP:
self.custom_interactive_timeout: int = 0
self.developer_ui = None
self.hide_v_ego_ui: bool = False
self.mici_robotic_ui: bool = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness: int = 0
self.onroad_brightness_timer: int = 0
self.onroad_brightness_timer_param: int = 0
@@ -184,6 +186,7 @@ class UIStateSP:
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
self.developer_ui = self.params.get("DevUIInfo")
self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI")
self.mici_robotic_ui = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True)))
self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True)
self.rainbow_path = self.params.get_bool("RainbowMode")
+87 -1
View File
@@ -1,10 +1,13 @@
import os
import threading
import time
import wave
from openpilot.common.test import OpenpilotTestCase
from openpilot.cereal import log, messaging
from openpilot.cereal.messaging import SubMaster, PubMaster
from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert
from openpilot.selfdrive.ui.soundd import SAMPLE_RATE, SELFDRIVE_STATE_TIMEOUT, Soundd, check_selfdrive_timeout_alert
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import ROBOTIC_SOUND_FILES, ROBOTIC_SOUNDS_DIR, RoboticSoundPack
AudibleAlert = log.SelfdriveState.AudibleAlert
@@ -56,4 +59,87 @@ class TestSoundd(OpenpilotTestCase):
assert check_selfdrive_timeout_alert(sm)
def test_robotic_sound_pack_wav_formats(self):
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
assert os.path.exists(path), f"Missing robotic sound for {alert_id}: {path}"
with wave.open(path, "r") as wf:
assert wf.getnchannels() == 1, f"{filename} must be mono"
assert wf.getsampwidth() == 2, f"{filename} must be 16-bit PCM"
assert wf.getframerate() == SAMPLE_RATE, f"{filename} must be {SAMPLE_RATE} Hz"
assert wf.getnframes() > 0, f"{filename} must not be empty"
def test_robotic_sound_pack_switching_and_quiet_mode(self):
class _FakeParams:
def __init__(self):
self.vals = {"MiciRoboticUI": False, "QuietMode": False}
def get_bool(self, key: str) -> bool:
return self.vals.get(key, False)
fake_params = _FakeParams()
pack = RoboticSoundPack(fake_params, SAMPLE_RATE)
pack.load()
assert set(ROBOTIC_SOUND_FILES).issubset(pack.sounds)
soundd = Soundd.__new__(Soundd)
soundd.params = fake_params
soundd.enabled = False
soundd._frame = 0
soundd.robotic_sound_pack = pack
soundd.load_sounds()
soundd.current_alert = AudibleAlert.engage
soundd.current_volume = 1.0
soundd.current_sound_frame = 0
soundd.pending_stop = False
# Default buffer used when MiciRoboticUI is False
buf_default = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_default is soundd.loaded_sounds[AudibleAlert.engage]
# Switching MiciRoboticUI to True swaps buffer to robotic sound
fake_params.vals["MiciRoboticUI"] = True
assert pack.refresh_param() is True
buf_robotic = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_robotic is pack.sounds[AudibleAlert.engage]
assert buf_robotic is not buf_default
# QuietMode still suppresses non-critical robotic engage chirp
soundd.enabled = True
assert not soundd.should_play_sound(AudibleAlert.engage)
assert soundd.should_play_sound(AudibleAlert.warningImmediateUser)
assert soundd.should_play_sound(AudibleAlert.warningImmediateSystem)
def test_robotic_sound_pack_lfs_fallback_and_reactive_chirps(self):
from types import SimpleNamespace
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import (
CHIRP_BOOST,
CHIRP_SPEED_UP,
CHIRP_STARTLED,
REACTIVE_CHIRP_IDS,
)
class _FakeParams:
def get_bool(self, key: str) -> bool:
return key == "MiciRoboticUI"
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
pack.load()
for cid in REACTIVE_CHIRP_IDS:
assert cid in pack.sounds and len(pack.sounds[cid]) > 0
class _FakeSM:
def __init__(self, v_cruise=100.0, a_ego=0.0):
self.updated = {"carState": True, "userBookmark": False, "bookmarkButton": False}
self.valid = {"controlsState": False}
self._cs = SimpleNamespace(vCruiseCluster=v_cruise, leftBlinker=False, rightBlinker=False, standstill=False, aEgo=a_ego)
def __getitem__(self, key):
return self._cs
assert pack.detect_reactive_chirp(_FakeSM(100.0, 0.0), now=10.0) is None # first sample seeds prev_set_speed
assert pack.detect_reactive_chirp(_FakeSM(110.0, 0.0), now=11.0) == CHIRP_SPEED_UP
assert pack.detect_reactive_chirp(_FakeSM(110.0, -3.5), now=12.0) == CHIRP_STARTLED
assert pack.detect_reactive_chirp(_FakeSM(110.0, 2.6), now=13.0) == CHIRP_BOOST
# TODO: add test with micd for checking that soundd actually outputs sounds
+32 -9
View File
@@ -18,6 +18,12 @@ MIN_SPEED = 5.0 # m/s
LINE_STD = (0.2, 0.6)
POINT_STD = 0.1
YIELD = (0.2, 0.45)
CURVE_ACCEL = (0.3, 0.9) # m/s^2, lane curvature lateral accel for full curve authority
PLAN_SHARE_CURVE = 0.65 # plan y share at full curve authority; straights keep the 0.3-0.5 ramp
MANEUVER_OFFSET = (0.55, 0.75) # m, |plan offset from usual| where extra curve authority is withheld
TRUST_RISE = (1.5, 0.6) # s, trust recovery time on straights and in curves
MAX_ADDED_LAT_ACCEL = 1.0 # m/s^2, cap on Blendful's own curvature contribution
DK_RATE = 1e-3 # 1/(m*s), max dk change per second while trust falls
X_IDXS = np.array(ModelConstants.X_IDXS)
@@ -38,6 +44,10 @@ class Blendful:
self.model_curvature = 0.0
self.smooth = 0.0 # smooths the correction target below .53 lat accel
self.curvature = 0.0
self.lane_curvature = 0.0
self.curve_gate = 0.0
self.maneuver_free = 1.0
self.plan_share = 0.0
def update(self, model_output: dict[str, np.ndarray], v_ego: float, active: bool, model_curvature: float, enabled: bool = True) -> float:
self.l_prob = self.r_prob = 0.0
@@ -53,11 +63,14 @@ class Blendful:
self.lane_width.initialized = False
self.going_around = False
target = 0.0 if fading else self._target(model_output, v_ego, model_curvature)
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 0.0]))
curve_lat_accel = max(abs(model_curvature), abs(self.lane_curvature)) * v_ego ** 2
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(curve_lat_accel, [0.18, 0.53], [0.5, 0.0]))
build = 0.5 / max(v_ego, 1.0) ** 2 * DT_MDL # jerk over 1 second
release = (0.5 if fading else 2.0) / max(v_ego, 1.0) ** 2 * DT_MDL # lets go fast, but past zero it builds like any other pull
k = self.curvature
self.curvature = float(np.clip(target, max(k - release, -build) if k > 0 else k - build, min(k + release, build) if k < 0 else k + build))
cap = MAX_ADDED_LAT_ACCEL / max(v_ego, 1.0) ** 2
self.curvature = float(np.clip(self.curvature, -cap, cap))
return self.curvature
def _target(self, model_output: dict[str, np.ndarray], v_ego: float, model_curvature: float) -> float:
@@ -105,12 +118,6 @@ class Blendful:
center = (r_var * (lines[1, win] + half_width) + l_var * (lines[2, win] - half_width)) / (l_var + r_var)
weight = 1.0 / (l_var * r_var / (l_var + r_var) + POINT_STD ** 2)
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
plan_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
error = np.clip(center - ((1 - plan_share) * model_curvature * x ** 2 / 2 + plan_share * plan_x), -1.0, 1.0)
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
# A model planning to end up further from its usual spot in the lane than the plant is now is likely going around something
hw_now = np.clip(lines[2, 0] - lines[1, 0], *LANE_WIDTH_CLIP) / 2 if l_prob * r_prob > 0.5 else self.lane_width.x / 2
center_now = (l_prob * (lines[1, 0] + hw_now) + r_prob * (lines[2, 0] - hw_now)) / (l_prob + r_prob)
@@ -133,13 +140,29 @@ class Blendful:
self.usual_offset.update_alpha(20.0 if self.going_around else 10.0)
self.usual_offset.update(offset)
# Curves seen by the lane fit, not only by the model's own curvature (which can under-read a curve it is cutting).
self.lane_curvature = float(lane_curvature)
self.curve_gate = float(np.interp(abs(lane_curvature) * v_ego ** 2, CURVE_ACCEL, [0.0, 1.0]))
# Hold the extra curve authority while the model is settled in its lane. A large deviation from its usual spot is a maneuver.
self.maneuver_free = 0.0 if self.going_around else float(np.interp(abs(offset - usual), MANEUVER_OFFSET, [1.0, 0.0]))
# Fit curvature to place the plant in center: e ~ dk x^2 / 2
plan_x = np.interp(x, model_output['plan'][0, :, 0], model_output['plan'][0, :, 1])
base_share = np.interp(abs(model_curvature) * lookahead ** 2 / 2, [0.5, 2.0], [0.3, 0.5]) # up to 50% plan y vs curvature parabola in sharp curves
self.plan_share = base_share + (PLAN_SHARE_CURVE - base_share) * self.curve_gate * self.maneuver_free
error = np.clip(center - ((1 - self.plan_share) * model_curvature * x ** 2 / 2 + self.plan_share * plan_x), -1.0, 1.0)
dk = 2.0 * np.sum(weight * error * x ** 2) / np.sum(weight * x ** 4)
if inside_curve:
lane_trust *= np.interp(abs(offset) - abs(center_now) - 0.25 * abs(model_curvature) * lookahead ** 2 / 2, (0.5, 1.0), [1.0, 0.0])
else:
lane_trust *= np.interp(swerve, (YIELD[0] / 2, YIELD[0]), [1.0, 0.0]) if self.going_around else np.interp(away, YIELD, [1.0, 0.0])
# While trust falls, move dk at a bounded rate instead of clipping it to its previous sign. The old clip could pin dk at
# zero and block a needed correction or sign reversal (seen as 1.5 s dead spots in sharp curves).
if lane_trust < self.trust:
dk = float(np.clip(dk, min(self.dk, 0.0), max(self.dk, 0.0)))
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (1.5 + DT_MDL)
dk = self.dk + float(np.clip(dk - self.dk, -DK_RATE * DT_MDL, DK_RATE * DT_MDL))
trust_tau = TRUST_RISE[0] + (TRUST_RISE[1] - TRUST_RISE[0]) * self.curve_gate
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (trust_tau + DT_MDL)
self.dk = dk
return float(self.trust * dk)
@@ -8,8 +8,6 @@ import numpy as np
from openpilot.common.transformations.camera import DEVICE_CAMERAS
MAX_CAMERA_OFFSET = 0.35 # m, the settings' range
class CameraOffsetHelper:
def __init__(self):
@@ -36,13 +34,6 @@ class CameraOffsetHelper:
def set_offset(self, offset):
self.camera_offset = offset
def load_offset(self, params):
offset = params.get("CameraOffset", return_default=True)
if offset is None or not np.isfinite(offset) or abs(offset) > MAX_CAMERA_OFFSET + 1e-6: # older sunnypilot stored whole centimeters
offset = 0.0
params.put("CameraOffset", offset)
self.set_offset(offset)
def update(self, model_transform_main, model_transform_extra, sm, main_wide_camera):
self.actual_camera_offset = (0.9 * self.actual_camera_offset) + (0.1 * self.camera_offset)
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['narrowRoadCameraState'].sensor))]
+1 -1
View File
@@ -424,7 +424,7 @@ def main(demo=False):
if sm.frame % 60 == 0:
model.lat_delay = get_lat_delay(params, sm["lateralDelay"].lateralDelay)
model.PLANPLUS_CONTROL = params.get("PlanplusControl", return_default=True)
camera_offset_helper.load_offset(params)
camera_offset_helper.set_offset(params.get("CameraOffset", return_default=True))
blendful_enabled = params.get_bool("Blendful")
lat_delay = model.lat_delay + model.LAT_SMOOTH_SECONDS
if sm.updated["extrinsicsCalibration"] and sm.seen['narrowRoadCameraState'] and sm.seen['deviceState']:
@@ -8,7 +8,7 @@ import numpy as np
from openpilot.common.realtime import DT_MDL
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot.modeld_v2.blendful import Blendful
from openpilot.sunnypilot.modeld_v2.blendful import Blendful, DK_RATE, MAX_ADDED_LAT_ACCEL
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants
X = np.array(ModelConstants.X_IDXS)
@@ -95,7 +95,7 @@ class TestBlendful(OpenpilotTestCase):
p = 0.9 - 0.02 * i
self.bf.update(frame(center=0.3, plan=-0.02 * i, probs=(p, p)), 20.0, True, 0.0)
if self.bf.trust < trust:
assert abs(self.bf.dk) <= abs(dk) + 1e-12
assert abs(self.bf.dk - dk) <= DK_RATE * DT_MDL + 1e-12
def test_toggle_off_returns_zero_and_resets(self):
drive(self.bf, 5.0, center=0.5)
@@ -110,3 +110,48 @@ class TestBlendful(OpenpilotTestCase):
assert self.bf.trust == 0.0
assert abs(out[0]) < abs(start)
assert abs(out[-1]) < 1e-6
def test_trust_fall_allows_sign_reversal(self):
drive(self.bf, 5.0, center=0.4)
assert self.bf.dk > 0
# Keep trust falling every frame while the lane moves to the other side. The old sign-preserving clip pinned dk at 0.
for i in range(300):
p = max(0.45, 0.9 - 0.0015 * i)
self.bf.update(frame(center=-0.4, probs=(p, p)), 20.0, True, 0.0)
assert self.bf.dk < 0
def test_curve_gate_opens_on_lane_curvature(self):
# The model under-reads the curve: lane lines curve, model_curvature stays 0.
for _ in range(400):
self.bf.update(frame(k=0.003, center=0.2), 25.0, True, 0.0)
assert self.bf.curve_gate > 0.9
assert self.bf.plan_share >= 0.6
straight = Blendful()
for _ in range(400):
straight.update(frame(), 25.0, True, 0.0)
assert straight.curve_gate < 0.05
def test_trust_recovers_faster_in_curves(self):
curve, straight = Blendful(), Blendful()
for bf, k in ((curve, 0.004), (straight, 0.0)):
drive(bf, 2.0, v=25.0, k=k)
bf.trust = 0.0
for _ in range(30):
bf.update(frame(k=k), 25.0, True, k)
assert curve.curve_gate > 0.9 and straight.curve_gate < 0.05
assert curve.trust > straight.trust + 0.1
def test_maneuver_gate_holds_extra_share(self):
drive(self.bf, 5.0, k=0.003, center=0.2)
self.bf.usual_offset.x = -0.2
self.bf.usual_offset.initialized = True
for _ in range(20):
self.bf.update(frame(k=0.003, center=0.2, plan=1.2), 25.0, True, 0.003)
assert self.bf.maneuver_free < 0.1
assert self.bf.plan_share < 0.55
def test_added_curvature_is_capped(self):
self.bf.curvature = 1.0
self.bf.update(frame(), 30.0, True, 0.0)
assert abs(self.bf.curvature) <= MAX_ADDED_LAT_ACCEL / 30.0 ** 2 + 1e-9
@@ -27,18 +27,6 @@ class TestCameraOffset(OpenpilotTestCase):
self.camera_offset = CameraOffsetHelper()
self.dc = DEVICE_CAMERAS[('mici', 'os04c10')]
def test_load_offset_resets_out_of_range(self):
class Params:
def __init__(self, v): self.v = v
def get(self, key, return_default=False): return self.v
def put(self, key, v): self.v = v
for stored, used in ((0.2, 0.2), (-0.35, -0.35), (4.0, 0.0), (-35.0, 0.0), (float('nan'), 0.0), (None, 0.0)):
params = Params(stored)
self.camera_offset.load_offset(params)
assert self.camera_offset.camera_offset == used
assert params.v == (stored if used == stored else 0.0)
def test_smoothing(self):
self.camera_offset.set_offset(0.2)
+1 -1
View File
@@ -112,7 +112,7 @@ class ModelCache:
class ModelFetcher:
"""Handles fetching and caching of model data from remote source"""
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v25.json"
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v26.json"
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v28.json"
MODEL_SOURCES = {
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:bd28c1e0a0dc15f5a1abc97cea2817f437880ed9e04fd7fc2ab1fb1b6a694ab0
size 65812
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2edd557bb2fc417f6039dbc98f9895557a049c757dd4e31619f3f2e7a092386e
size 35084
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4d94997ee61f7ba0f3afece1db5b0c9c16f32512832380fc0ac13c384d360efd
size 56152
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9c85ee1bdbede640c484da13c5a25bd40f7c165df5d2ed9b1db3edf15712aae7
size 115522
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f7a6f3b314b37ed6c7c374104989b1f02f065c60a25104b371966f7c27a2fda7
size 40364
@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Generate EMO-inspired robotic chirps and vocoded voice alert WAVs (48 kHz, mono, 16-bit PCM).
Run this script whenever tweaking the robotic sound pack:
python3 openpilot/sunnypilot/selfdrive/assets/sounds/robotic/generate_robotic_sounds.py
"""
from pathlib import Path
import shutil
import subprocess
import tempfile
import wave
import numpy as np
SAMPLE_RATE = 48000
MAX_INT16 = 32767
OUT_DIR = Path(__file__).resolve().parent
def write_wav(path: Path, samples: np.ndarray) -> None:
clipped = np.clip(samples, -1.0, 1.0)
pcm = (clipped * MAX_INT16).astype(np.int16)
with wave.open(str(path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLE_RATE)
wf.writeframes(pcm.tobytes())
def adsr(n: int, attack: float = 0.015, release: float = 0.04) -> np.ndarray:
env = np.ones(n, dtype=np.float32)
a_n = min(n // 2, int(attack * SAMPLE_RATE))
r_n = min(n // 2, int(release * SAMPLE_RATE))
if a_n > 0:
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
if r_n > 0:
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
return env
def emo_chirp(f_start: float, f_end: float, duration: float, vibrato_hz: float = 0.0, vibrato_depth: float = 0.0, gain: float = 0.65) -> np.ndarray:
"""Synthesize an expressive EMO-like harmonic chirp with smooth pitch glide."""
n = int(SAMPLE_RATE * duration)
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
# Smooth cubic-ish frequency glide
progress = t / max(duration, 1e-6)
s_curve = progress * progress * (3.0 - 2.0 * progress)
freq = f_start + (f_end - f_start) * s_curve
if vibrato_hz > 0.0:
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
phase = 2.0 * np.pi * np.cumsum(freq) / SAMPLE_RATE
# Warm robotic timbre: fundamental + soft 2nd & 3rd harmonics
sig = (
0.72 * np.sin(phase)
+ 0.22 * np.sin(2.0 * phase + 0.3)
+ 0.08 * np.sin(3.0 * phase)
)
env = adsr(n, attack=min(0.015, duration * 0.2), release=min(0.055, duration * 0.35))
return (sig * env * gain).astype(np.float32)
def silence(duration: float) -> np.ndarray:
return np.zeros(int(SAMPLE_RATE * duration), dtype=np.float32)
def robotize_voice(samples: np.ndarray, carrier_hz: float = 165.0) -> np.ndarray:
"""Apply a clean EMO-style robotic vocoder / comb-resonance effect while keeping speech crisp."""
n = len(samples)
if n == 0:
return samples
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
# Normalize speech input
peak = float(np.max(np.abs(samples)))
if peak > 1e-5:
samples = samples / peak
# Short metallic comb resonance (~5.5 ms delay) for unmistakable robot character
delay = int(0.0055 * SAMPLE_RATE)
comb = samples.copy()
if delay < n:
comb[delay:] += 0.42 * samples[:-delay]
# Gentle ring modulation blended with intelligible dry+comb voice
carrier = 0.65 * np.sin(2.0 * np.pi * carrier_hz * t) + 0.35 * np.sin(2.0 * np.pi * carrier_hz * 2.0 * t)
ring = comb * carrier
blended = 0.62 * comb + 0.38 * ring
# Soft saturation & normalization
blended = np.tanh(blended * 1.45)
peak = float(np.max(np.abs(blended)))
if peak > 1e-5:
blended = blended / peak * 0.94
return blended.astype(np.float32)
def synthesize_robotic_phrase(text: str, rate: int = 205, carrier_hz: float = 175.0) -> np.ndarray | None:
"""Render a short spoken phrase via macOS `say` + `ffmpeg`/`afconvert`, then robotize it."""
say_bin = shutil.which("say")
ffmpeg_bin = shutil.which("ffmpeg")
if not say_bin or not ffmpeg_bin:
return None
with tempfile.TemporaryDirectory() as tmpdir:
aiff_path = Path(tmpdir) / "speech.aiff"
wav_path = Path(tmpdir) / "speech.wav"
# Use a crisp clear voice ("Samantha" or system default) pitched up slightly via ffmpeg asetrate
cmd_say = [say_bin, "-r", str(rate), "-o", str(aiff_path), text]
subprocess.run(cmd_say, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Convert to 48kHz mono 16-bit WAV, slight pitch-up (+12%) for cute EMO-like robot timbre, trim silence
cmd_ff = [
ffmpeg_bin, "-y", "-i", str(aiff_path),
"-af", "silenceremove=start_periods=1:start_threshold=-40dB:stop_periods=1:stop_threshold=-40dB,asetrate=22050*1.12,aresample=48000",
"-ac", "1", "-ar", str(SAMPLE_RATE), "-sample_fmt", "s16",
str(wav_path),
]
subprocess.run(cmd_ff, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
with wave.open(str(wav_path), "rb") as wf:
raw = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0
return robotize_voice(raw, carrier_hz=carrier_hz)
def build_all_sounds() -> None:
# 1. EMO-style expressive chirps & vocalizations (punchy multi-syllable trills)
engage = np.concatenate([
emo_chirp(620, 980, 0.10, gain=0.92),
silence(0.02),
emo_chirp(920, 1340, 0.10, gain=0.94),
silence(0.02),
emo_chirp(1220, 1780, 0.18, vibrato_hz=28, vibrato_depth=40, gain=0.96),
])
write_wav(OUT_DIR / "engage.wav", engage)
disengage = np.concatenate([
emo_chirp(1240, 880, 0.12, gain=0.90),
silence(0.025),
emo_chirp(820, 480, 0.22, vibrato_hz=18, vibrato_depth=22, gain=0.90),
])
write_wav(OUT_DIR / "disengage.wav", disengage)
refuse = np.concatenate([
emo_chirp(520, 340, 0.12, vibrato_hz=36, vibrato_depth=35, gain=0.92),
silence(0.035),
emo_chirp(420, 260, 0.18, vibrato_hz=36, vibrato_depth=35, gain=0.92),
])
write_wav(OUT_DIR / "refuse.wav", refuse)
pre_alert = emo_chirp(880, 1620, 0.24, vibrato_hz=30, vibrato_depth=32, gain=0.92)
write_wav(OUT_DIR / "pre_alert.wav", pre_alert)
prompt_low = np.concatenate([
emo_chirp(960, 680, 0.10, gain=0.88),
silence(0.02),
emo_chirp(660, 460, 0.14, gain=0.88),
])
write_wav(OUT_DIR / "prompt_single_low.wav", prompt_low)
prompt_high = np.concatenate([
emo_chirp(780, 1180, 0.09, gain=0.90),
silence(0.02),
emo_chirp(1160, 1640, 0.15, vibrato_hz=26, vibrato_depth=30, gain=0.94),
])
write_wav(OUT_DIR / "prompt_single_high.wav", prompt_high)
# 2. Hybrid chirp + vocoded robotic spoken phrases for warnings & critical alerts
def hybrid(intro: np.ndarray, phrase: str, fallback: np.ndarray, tail_pause: float = 0.0, carrier_hz: float = 175.0) -> np.ndarray:
voice = synthesize_robotic_phrase(phrase, carrier_hz=carrier_hz)
body = voice if voice is not None else fallback
parts = [intro, silence(0.04), body]
if tail_pause > 0.0:
parts.append(silence(tail_pause))
return np.concatenate(parts)
warning = hybrid(
emo_chirp(820, 1120, 0.12, gain=0.65),
"Heads up",
emo_chirp(1120, 880, 0.22, gain=0.65),
carrier_hz=185.0,
)
write_wav(OUT_DIR / "warning.wav", warning)
warning_repeat = hybrid(
emo_chirp(860, 1180, 0.12, gain=0.68),
"Attention",
emo_chirp(1180, 900, 0.22, gain=0.68),
tail_pause=0.35,
carrier_hz=185.0,
)
write_wav(OUT_DIR / "warning_repeat.wav", warning_repeat)
dm_warning = hybrid(
np.concatenate([emo_chirp(740, 1080, 0.10, gain=0.68), silence(0.03), emo_chirp(880, 1240, 0.10, gain=0.68)]),
"Eyes on road",
emo_chirp(1050, 780, 0.25, gain=0.68),
tail_pause=0.35,
carrier_hz=190.0,
)
write_wav(OUT_DIR / "dm_warning.wav", dm_warning)
critical = hybrid(
np.concatenate([emo_chirp(1320, 1520, 0.11, gain=0.80), silence(0.03), emo_chirp(1520, 1320, 0.11, gain=0.80)]),
"Take control",
emo_chirp(1480, 1100, 0.26, gain=0.80),
tail_pause=0.28,
carrier_hz=160.0,
)
write_wav(OUT_DIR / "critical.wav", critical)
dm_critical = hybrid(
np.concatenate([
emo_chirp(1450, 1720, 0.09, gain=0.85),
silence(0.025),
emo_chirp(1450, 1720, 0.09, gain=0.85),
]),
"Take control now",
emo_chirp(1680, 1200, 0.28, gain=0.85),
tail_pause=0.22,
carrier_hz=150.0,
)
write_wav(OUT_DIR / "dm_critical.wav", dm_critical)
print(f"Generated 11 robotic WAV files in {OUT_DIR}")
if __name__ == "__main__":
build_all_sounds()
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:65679dc91bdc2cabd4349d4ffd178ae7a7fa928552e036bc54d52c8ad6a8caf3
size 23084
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:00e3e854edcdcbae267fab69a0144c1689a7fe88e40010ed3bd7c0229c48b77d
size 25004
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d997b9d15a4083ca0300809bd38b0666f25de3a9be3f7180f54d7415408c196a
size 25004
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:765f6d6496b24794f71249f16f3bc2df0993e9c8d465a7429715ab138c20eb43
size 32204
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:ed26262d283e696b73452e63486b656c777a4fe24914090e07e8f95f7a5c2461
size 42098
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2e172036401b6c5d81ce922b6e5ed9e1bc39320646f8b7aa1df223f9e392fe90
size 52158
@@ -5,6 +5,7 @@ This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
from opendbc.car import structs
@@ -23,10 +24,15 @@ class CarSpecificEventsSP:
self.CP_SP = CP_SP
self.low_speed_alert = False
self.sm = messaging.SubMaster(['carStateSP'])
def update(self, CS: structs.CarState, events: Events):
events_sp = EventsSP()
self.sm.update(0)
if self.sm['carStateSP'].stockSteerIntervention:
events_sp.add(EventNameSP.stockSteerIntervention)
if self.CP.brand == 'chrysler':
if self.CP.carFingerprint in RAM_DT:
# remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic
@@ -11,6 +11,7 @@ from opendbc.car.interfaces import CarInterfaceBase
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import PIDD_VERSION
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability
from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP
@@ -55,10 +56,18 @@ def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_S
CP_SP.pcmCruiseSpeed = False
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None:
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool,
params: Params | None = None) -> None:
if params is None:
params = Params()
if nnlc_enabled or enforce_torque:
CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning)
if enforce_torque and not nnlc_enabled and CP.steerControlType == structs.CarParams.SteerControlType.torque \
and params.get("TorqueControlTune") == PIDD_VERSION:
CP.lateralTuning.init('pid')
def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params | None = None) -> None:
if params is None:
@@ -92,7 +101,7 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
enforce_torque = _enforce_torque_lateral_control(CI.CP, params)
nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params)
_initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled, params)
_cleanup_unsupported_params(CI.CP, CI.CP_SP)
try:
@@ -105,6 +114,8 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
def initialize_params(params) -> list[dict[str, Any]]:
keys: list = []
keys.append("RadarTracks")
# hyundai
keys.extend([
"HyundaiLongitudinalTuning",
@@ -6,6 +6,8 @@ See the LICENSE.md file in the root directory for more details.
"""
import time
import numpy as np
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
@@ -17,6 +19,27 @@ from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, pidd_selected
PATH_CURVATURE_PREVIEW_START = 15.0 # m ahead of the car
PATH_CURVATURE_PREVIEW_END = 45.0 # m ahead of the car
PATH_CURVATURE_MIN_SPEED = 1.0 # m/s
def path_curvature_ahead(model_v2) -> float:
vx = np.asarray(model_v2.velocity.x, dtype=np.float64)
if len(vx) < 3 or vx[0] < PATH_CURVATURE_MIN_SPEED:
return 0.0
# averaged over a fixed distance ahead, so the preview does not shrink with speed
position = model_v2.position
distance = np.concatenate([[0.0], np.cumsum(np.hypot(np.diff(position.x), np.diff(position.y)))])
start = min(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_START)), len(distance) - 1)
end = min(max(int(np.searchsorted(distance, PATH_CURVATURE_PREVIEW_END)), start + 1), len(distance))
oz = np.asarray(model_v2.orientationRate.z, dtype=np.float64)[start:end]
return float(np.mean(oz / np.maximum(vx[start:end], PATH_CURVATURE_MIN_SPEED)))
class ControlsExt(ModelStateBase):
@@ -30,11 +53,15 @@ class ControlsExt(ModelStateBase):
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
cloudlog.info("controlsd_ext got CarParamsSP")
self.pidd: LatControlPidd | None = None
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
self.pm_services_ext = ['carControlSP']
def initialize_lateral_control(self, lac, CI, dt):
if pidd_selected(self.CP):
self.pidd = LatControlPidd(self.CP, self.CP_SP, CI, dt)
return self.pidd
enforce_torque_control = self.params.get_bool("EnforceTorqueControl")
torque_versions = self.params.get("TorqueControlTune")
if not enforce_torque_control:
@@ -104,6 +131,8 @@ class ControlsExt(ModelStateBase):
CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton
CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget
CC_SP.pathCurvature = path_curvature_ahead(sm['modelV2'])
return CC_SP
@staticmethod
@@ -114,6 +143,13 @@ class ControlsExt(ModelStateBase):
pm.send('carControlSP', cc_sp_send)
def update_pidd_torque_params(self, sm: messaging.SubMaster) -> None:
torque_params = sm['lateralTorqueParameters']
if self.pidd is not None and sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
self.pidd.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
torque_params.frictionCoefficientFiltered)
def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None:
self.update_pidd_torque_params(sm)
CC_SP = self.state_control_ext(sm)
self.publish_ext(CC_SP, sm, pm)
@@ -1,4 +1,7 @@
{
"pidd": {
"version": "2.0"
},
"v1.0": {
"version": "1.0"
},
@@ -0,0 +1,180 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import numpy as np
from collections import deque
from opendbc.car.interfaces import get_torque_params
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.pid import PIDController
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
# gains are in lateral acceleration, scaled to torque per degree by each car's vehicle model and latAccelFactor
PIDD_VERSION = 2.0
INTERP_SPEEDS = [1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 30.0]
KP_INTERP = [250.0, 120.0, 65.0, 30.0, 11.5, 5.5, 3.5, 2.0, 0.8]
TD_INTERP = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15, 0.2]
HIGH_SPEED_BP = [25.0, 29.0]
TURN_RATE_BP = [5.0, 20.0]
TURN_LAT_ACCEL_BP = [0.18, 0.53]
DESIRED_ANGLE_BUFFER_SECONDS = 1.0
LIVE_LAT_ACCEL_FACTOR_RANGE = [1.0, 2.0]
LIVE_FRICTION_RANGE = [0.5, 2.0]
SWING_CAP_FRICTION = 1.3
def pidd_selected(CP):
return CP.steerControlType == 'torque' and CP.lateralTuning.which() == 'pid' and len(CP.lateralTuning.pid.kpBP) == 0 and \
CP.carFingerprint in get_torque_params()
def filter_rc(hz):
return 1 / (2 * math.pi * hz)
def lat_accel_per_deg(VM, v_ego):
return VM.calc_curvature(math.radians(1.0), v_ego, 0.0) * v_ego**2
class LatControlPidd(LatControl):
def __init__(self, CP, CP_SP, CI, dt):
super().__init__(CP, CP_SP, CI, dt)
torque_params = get_torque_params()[CP.carFingerprint]
self.VM = VehicleModel(CP)
self.pid = PIDController(0.0, 0.0, 0.0, pos_limit=self.steer_max, neg_limit=-self.steer_max)
self.offline_lat_accel_factor, self.offline_friction = float(torque_params['LAT_ACCEL_FACTOR']), float(torque_params['FRICTION'])
self.lat_accel_factor = self.friction = None
self.update_torque_parameters(self.offline_lat_accel_factor, 0.0, self.offline_friction)
self.error_filter = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.request_filter = FirstOrderFilter(0.0, filter_rc(3.0), dt, initialized=False)
self.error_rate_filter = FirstOrderFilter(0.0, 0.0354, dt)
self.wheel_angle_filter = FirstOrderFilter(0.0, filter_rc(10.0), dt, initialized=False)
self.wheel_rate_filter = FirstOrderFilter(0.0, 0.005, dt)
self.request_rate_ref = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.break_rate = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_rate2 = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_error = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.command_slow = FirstOrderFilter(0.0, filter_rc(0.5), dt, initialized=False)
self.last_error = 0.0
self.wheel_angle_held = None
self.swing = 0.0
buffer_len = int(DESIRED_ANGLE_BUFFER_SECONDS / dt)
self.desired_angle_buffer = deque([0.0] * buffer_len, maxlen=buffer_len)
self.delay_frames = int(np.clip(CP.steerActuatorDelay / dt + 1, 1, buffer_len))
self.rate_span_frames = max(1, int(0.1 / dt))
def update_torque_parameters(self, latAccelFactor, latAccelOffset, friction):
# a learned factor below the offline one would raise every gain
latAccelFactor = float(np.clip(latAccelFactor, *(r * self.offline_lat_accel_factor for r in LIVE_LAT_ACCEL_FACTOR_RANGE)))
friction = float(np.clip(friction, *(r * self.offline_friction for r in LIVE_FRICTION_RANGE)))
if (latAccelFactor, friction) == (self.lat_accel_factor, self.friction):
return
self.lat_accel_factor, self.friction = latAccelFactor, friction
self.kp = [kp * lat_accel_per_deg(self.VM, v) / latAccelFactor for kp, v in zip(KP_INTERP, INTERP_SPEEDS, strict=True)]
self.pid._k_p = (INTERP_SPEEDS, self.kp)
self.pid._k_i = (INTERP_SPEEDS, [kp / 6.0 for kp in self.kp])
self.pid._k_d = (INTERP_SPEEDS, [kp * td for kp, td in zip(self.kp, TD_INTERP, strict=True)])
def reset(self):
super().reset()
self.pid.reset()
self.swing = self.last_error = 0.0
self.command_slow.initialized = False
for f in (self.error_filter, self.error_rate_filter, self.wheel_rate_filter, self.request_rate_ref, self.break_error, self.break_rate, self.break_rate2):
f.x = 0.0
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay):
pid_log = log.ControlsState.LateralPIDState.new_message()
pid_log.steeringAngleDeg = float(CS.steeringAngleDeg)
pid_log.steeringRateDeg = float(CS.steeringRateDeg)
high_speed = float(np.interp(CS.vEgo, HIGH_SPEED_BP, [0.0, 1.0]))
angle_steers_des_no_offset = self.request_filter.update(math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)))
angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg
self.desired_angle_buffer.append(angle_steers_des)
expected_angle = self.desired_angle_buffer[-self.delay_frames]
request_rate = (self.desired_angle_buffer[-1] - self.desired_angle_buffer[-1 - self.rate_span_frames]) / (self.rate_span_frames * self.dt)
request_rate_ref = self.request_rate_ref.update(request_rate)
break_rate = self.break_rate2.update(self.break_rate.update(request_rate))
# a 1 Hz error filter lags enough for P to pump a 2 Hz wheel swing, so it opens up only while the request turns the wheel
error_filter_hz = float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [1.0, 3.0]))
self.error_filter.update_alpha(filter_rc(float(np.interp(CS.vEgo, HIGH_SPEED_BP, [error_filter_hz, 1.0]))))
error = self.error_filter.update(expected_angle - CS.steeringAngleDeg)
# at highway speed, ignore the angle sensor toggling one count
held = self.wheel_angle_held if self.wheel_angle_held is not None else CS.steeringAngleDeg
wheel_backlash = 0.08 * high_speed
self.wheel_angle_held = held = CS.steeringAngleDeg - float(np.clip(CS.steeringAngleDeg - held, -wheel_backlash, wheel_backlash))
wheel_angle_last = self.wheel_angle_filter.x if self.wheel_angle_filter.initialized else held
wheel_rate = self.wheel_rate_filter.update((self.wheel_angle_filter.update(held) - wheel_angle_last) / self.dt)
wheel_swing = 0.0 if CS.steeringPressed else min(abs(wheel_rate - request_rate_ref), 60.0)
self.swing = max(wheel_swing, self.swing * (1.0 - self.dt))
pid_log.steeringAngleDesiredDeg = float(angle_steers_des)
pid_log.angleError = float(error)
if not active:
output_torque = 0.0
pid_log.active = False
self.reset()
else:
error_rate = self.error_rate_filter.update((error - self.last_error) / self.dt)
self.last_error = error
error_rate += high_speed * (-wheel_rate - error_rate)
ff = angle_steers_des_no_offset * lat_accel_per_deg(VM, CS.vEgo) / self.lat_accel_factor
ff += 0.4 * params.roll * ACCELERATION_DUE_TO_GRAVITY / self.lat_accel_factor
# break rack friction as soon as the request moves, before the error builds up
error_deadzone = error - float(np.clip(error, -0.3, 0.3))
turn_lat_accel = abs(desired_curvature) * max(CS.vEgo, 8.0) ** 2
friction_scale = float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.6, 1.0]))
friction = self.friction * (friction_scale + high_speed * (0.1 - friction_scale))
friction_rate_gain = 0.75 - 0.25 * high_speed
ff += friction * float(np.tanh((error_deadzone + friction_rate_gain * request_rate) * 0.1887))
kp = float(np.interp(CS.vEgo, INTERP_SPEEDS, self.kp))
# damp the wheel toward the request's rate; the rack rings near 2 Hz without it
wheel_damp = 0.0 if CS.steeringPressed else (1.0 - high_speed) * kp * 0.05 * (wheel_rate - request_rate_ref)
ff -= wheel_damp
# half P on a straight, flat road; the cut goes through the feedforward so the integrator still holds a crown
kp_load = max(float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0])),
float(np.interp(abs(params.roll) * ACCELERATION_DUE_TO_GRAVITY, [0.35, 0.7], [0.0, 1.0])))
kp_scale = 0.5 + 0.5 * kp_load
ff -= (1.0 - float(np.interp(CS.vEgo, [12.0, 18.0], [kp_scale, 1.0]))) * kp * error
ff += high_speed * 0.325 * self.friction * float(np.tanh((self.break_error.update(error) + 0.35 * break_rate) / 0.5))
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
error_rate_clean = error_rate - float(np.clip(error_rate, -0.3, 0.3))
output_torque = self.pid.update(error, error_rate=error_rate_clean, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
# a swing the request isn't asking for: pass only the command's slow part
command = output_torque + wheel_damp
self.command_slow.update(command)
if CS.steeringPressed:
self.command_slow.x = command
swing_gate = float(np.interp(self.swing, [16.0, 30.0], [0.0, 1.0])) * float(np.interp(CS.vEgo, [3.0, 5.0, 10.0, 14.0], [0.0, 1.0, 1.0, 0.0]))
swing_gate *= 1.0 - float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(abs(error), [3.0, 6.0], [0.0, 1.0]))
if not (CS.steeringPressed or CS.leftBlinker or CS.rightBlinker):
cap = SWING_CAP_FRICTION * self.friction
output_torque += swing_gate * float(np.clip(self.command_slow.x - command, -cap, cap))
output_torque = float(np.clip(output_torque, -self.steer_max, self.steer_max))
pid_log.active = True
pid_log.p = float(self.pid.p)
pid_log.i = float(self.pid.i)
pid_log.f = float(self.pid.f)
pid_log.output = float(output_torque)
pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
return output_torque, angle_steers_des, pid_log
@@ -0,0 +1,126 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
from types import SimpleNamespace
import numpy as np
from opendbc.car.car_helpers import interfaces
from opendbc.car.honda.values import CAR as HONDA
from opendbc.car.hyundai.values import CAR as HYUNDAI
from opendbc.car.interfaces import get_torque_params
from opendbc.car.nissan.values import CAR as NISSAN
from opendbc.car.structs import car
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.mock.generators import generate_deviceMotion
from openpilot.common.params import Params
from openpilot.common.realtime import DT_CTRL
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.car.helpers import convert_to_capnp
from openpilot.selfdrive.locationd.helpers import Pose
from openpilot.selfdrive.locationd.torqued import TorqueEstimator
from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, PIDD_VERSION
def setup_car(car_name):
CarInterface = interfaces[car_name]
CP = CarInterface.get_non_essential_params(car_name)
CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name)
CI = CarInterface(CP, CP_SP)
sunnypilot_interfaces.setup_interfaces(CI)
return CI
def make_controller(CI):
return LatControlPidd(CI.CP.as_reader(), convert_to_capnp(CI.CP_SP).as_reader(), CI, DT_CTRL)
def drive(controller, CS, VM, angles, curvature=0.0):
params = log.VehicleParameters.new_message()
pose = Pose.from_device_motion(generate_deviceMotion().deviceMotion)
return [controller.update(True, CS, VM, params, False, curvature, pose, False, 0.2)[0] for CS.steeringAngleDeg in angles]
class TestPidd(OpenpilotTestCase):
def setup_method(self):
self.params = Params()
self.params.put_bool("EnforceTorqueControl", True, block=True)
self.params.put("TorqueControlTune", PIDD_VERSION, block=True)
def test_selected_on_any_torque_car(self):
for car_name in (HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.KIA_NIRO_EV):
assert setup_car(car_name).CP.lateralTuning.which() == 'pid'
def test_needs_enforce_torque(self):
self.params.remove("EnforceTorqueControl")
assert setup_car(HYUNDAI.KIA_NIRO_EV).CP.lateralTuning.which() == 'torque'
def test_not_on_angle_cars(self):
CI = setup_car(NISSAN.NISSAN_LEAF)
assert CI.CP.steerControlType == car.CarParams.SteerControlType.angle
assert not self.params.get_bool("EnforceTorqueControl")
def test_controlsd_builds_it(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_selection_follows_car_params(self):
# params changing after card picked pidd must not leave controlsd with a pid that has no gains
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
self.params.remove("EnforceTorqueControl")
self.params.put("TorqueControlTune", 1.0, block=True)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_damps_wheel_swing(self):
CI = setup_car(HONDA.HONDA_CIVIC)
VM = VehicleModel(CI.CP)
corr = {}
for pressed in (False, True):
controller = make_controller(CI)
CS = car.CarState.new_message(vEgo=8.0, steeringPressed=pressed)
angles = [2.0 * math.sin(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(300)]
out = drive(controller, CS, VM, angles)[100:]
rate = [math.cos(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(100, 300)]
corr[pressed] = float(np.corrcoef(out, rate)[0, 1])
assert corr[False] < corr[True] - 0.3
def test_output_within_steer_max(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
controller.pid.update = lambda *args, **kwargs: controller.steer_max
CS = car.CarState.new_message(vEgo=8.0)
out = drive(controller, CS, VehicleModel(CI.CP), [2.0 * math.sin(2 * math.pi * 2.5 * i * DT_CTRL) for i in range(500)])
assert max(abs(x) for x in out) <= controller.steer_max
def test_reset_clears_swing_gate(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
drive(controller, car.CarState.new_message(vEgo=8.0), VehicleModel(CI.CP), [30.0] * 200, curvature=-0.02)
controller.reset()
assert not controller.command_slow.initialized
def test_live_torque_params_rescale_gains(self):
controller = make_controller(setup_car(HYUNDAI.KIA_NIRO_EV))
kp = list(controller.kp)
controller.update_torque_parameters(2 * controller.lat_accel_factor, 0.0, controller.friction)
assert np.allclose(controller.kp, [k / 2 for k in kp])
assert np.allclose(controller.pid._k_p[1], controller.kp)
controller.update_torque_parameters(0.5 * controller.offline_lat_accel_factor, 0.0, 0.0)
assert np.allclose(controller.kp, kp)
def test_torqued_learns_under_pidd(self):
estimator = TorqueEstimator(setup_car(HYUNDAI.KIA_NIRO_EV).CP.as_reader())
offline = get_torque_params()[HYUNDAI.KIA_NIRO_EV]
self.assertAlmostEqual(estimator.offline_latAccelFactor, offline['LAT_ACCEL_FACTOR'])
self.assertAlmostEqual(estimator.offline_friction, offline['FRICTION'])
assert estimator.max_lataccel_factor > estimator.min_lataccel_factor
@@ -6,11 +6,13 @@ See the LICENSE.md file in the root directory for more details.
"""
import numpy as np
from opendbc.car.interfaces import get_torque_params
from opendbc.car.structs import car
from openpilot.common.params import Params
from openpilot.common.realtime import DT_MDL
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import pidd_selected
RELAXED_MIN_BUCKET_POINTS = np.array([1, 200, 300, 500, 500, 300, 200, 1])
@@ -37,6 +39,11 @@ class TorqueEstimatorExt:
def initialize_custom_params(self, decimated=False):
self.update_use_params()
if pidd_selected(self.CP):
torque_params = get_torque_params()[self.CP.carFingerprint]
self.offline_latAccelFactor = float(torque_params['LAT_ACCEL_FACTOR'])
self.offline_friction = float(torque_params['FRICTION'])
if self.enforce_torque_control_toggle:
if self._params.get_bool("LiveTorqueParamsRelaxedToggle"):
self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS / (10 if decimated else 1)
@@ -249,6 +249,14 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
},
EventNameSP.stockSteerIntervention: {
ET.PERMANENT: Alert(
"TAKE CONTROL",
"Stock Emergency Assist: Risk of Collision",
AlertStatus.critical, AlertSize.mid,
Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.none, 2.),
},
EventNameSP.bigModelReady: {
ET.PERMANENT: Alert(
"Big Model Ready",
@@ -0,0 +1,294 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import os
import time
import wave
import numpy as np
from openpilot.cereal import custom, log
from openpilot.common.basedir import BASEDIR
from openpilot.common.swaglog import cloudlog
AudibleAlert = log.SelfdriveState.AudibleAlert
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
ROBOTIC_SOUNDS_DIR = os.path.join(BASEDIR, "openpilot/sunnypilot/selfdrive/assets/sounds/robotic")
ROBOTIC_SOUND_FILES: dict[int, str] = {
AudibleAlert.engage: "engage.wav",
AudibleAlert.disengage: "disengage.wav",
AudibleAlert.refuse: "refuse.wav",
AudibleAlert.prompt: "warning.wav",
AudibleAlert.promptRepeat: "warning_repeat.wav",
AudibleAlert.promptDistracted: "dm_warning.wav",
AudibleAlert.preAlert: "pre_alert.wav",
AudibleAlert.warningSoft: "critical.wav",
AudibleAlert.warningImmediateSystem: "critical.wav",
AudibleAlert.warningImmediateUser: "dm_critical.wav",
AudibleAlertSP.promptSingleLow: "prompt_single_low.wav",
AudibleAlertSP.promptSingleHigh: "prompt_single_high.wav",
}
# Custom reactive robotic chirp IDs (non-overlapping with AudibleAlert / AudibleAlertSP enums)
CHIRP_SPEED_UP = 1001
CHIRP_SPEED_DOWN = 1002
CHIRP_STARTLED = 1003
CHIRP_BOOST = 1004
CHIRP_BOOKMARK = 1005
CHIRP_BLINKER = 1006
REACTIVE_CHIRP_IDS = {
CHIRP_SPEED_UP,
CHIRP_SPEED_DOWN,
CHIRP_STARTLED,
CHIRP_BOOST,
CHIRP_BOOKMARK,
CHIRP_BLINKER,
}
SET_SPEED_NA = 255
CHIRP_COOLDOWN = 0.6 # minimum seconds between reactive chirps
def _adsr(n: int, sr: int, attack: float = 0.012, release: float = 0.035) -> np.ndarray:
env = np.ones(n, dtype=np.float32)
a_n = min(n // 2, int(attack * sr))
r_n = min(n // 2, int(release * sr))
if a_n > 0:
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
if r_n > 0:
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
return env
def synth_emo_chirp(
f_start: float,
f_end: float,
duration: float,
sr: int = 48000,
vibrato_hz: float = 0.0,
vibrato_depth: float = 0.0,
gain: float = 0.92,
) -> np.ndarray:
"""Synthesize a bright, bubbly, unmistakable EMO/R2-D2-style formant chirp in pure NumPy."""
n = max(1, int(sr * duration))
t = np.arange(n, dtype=np.float32) / sr
p = t / max(duration, 1e-6)
s_curve = p * p * (3.0 - 2.0 * p)
freq = f_start + (f_end - f_start) * s_curve
if vibrato_hz > 0.0:
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
phase = 2.0 * np.pi * np.cumsum(freq) / sr
sig = (
0.55 * np.sin(phase)
+ 0.28 * np.sin(2.0 * phase + 0.35)
+ 0.14 * np.sin(3.0 * phase + 0.7)
+ 0.07 * np.sin(4.0 * phase)
)
env = _adsr(n, sr, attack=min(0.010, duration * 0.18), release=min(0.040, duration * 0.32))
out = np.tanh(sig * env * 1.45) * gain
return np.clip(out, -0.98, 0.98).astype(np.float32)
def _sil(duration: float, sr: int = 48000) -> np.ndarray:
return np.zeros(int(sr * duration), dtype=np.float32)
def build_procedural_sounds(sr: int = 48000) -> dict[int, np.ndarray]:
"""Build bubbly EMO chirps in pure NumPy (used for reactive chirps and guaranteed WAV fallback)."""
return {
# Core alert fallbacks (punchy, unmistakably robotic multi-syllable EMO trills)
AudibleAlert.engage: np.concatenate([
synth_emo_chirp(620, 980, 0.10, sr, gain=0.92),
_sil(0.02, sr),
synth_emo_chirp(920, 1340, 0.10, sr, gain=0.94),
_sil(0.02, sr),
synth_emo_chirp(1220, 1780, 0.18, sr, vibrato_hz=28, vibrato_depth=40, gain=0.96),
]),
AudibleAlert.disengage: np.concatenate([
synth_emo_chirp(1240, 880, 0.12, sr, gain=0.90),
_sil(0.025, sr),
synth_emo_chirp(820, 480, 0.22, sr, vibrato_hz=18, vibrato_depth=22, gain=0.90),
]),
AudibleAlert.refuse: np.concatenate([
synth_emo_chirp(520, 340, 0.12, sr, vibrato_hz=36, vibrato_depth=35, gain=0.92),
_sil(0.035, sr),
synth_emo_chirp(420, 260, 0.18, sr, vibrato_hz=36, vibrato_depth=35, gain=0.92),
]),
AudibleAlert.preAlert: synth_emo_chirp(880, 1620, 0.24, sr, vibrato_hz=30, vibrato_depth=32, gain=0.92),
AudibleAlertSP.promptSingleLow: np.concatenate([
synth_emo_chirp(960, 680, 0.10, sr, gain=0.88),
_sil(0.02, sr),
synth_emo_chirp(660, 460, 0.14, sr, gain=0.88),
]),
AudibleAlertSP.promptSingleHigh: np.concatenate([
synth_emo_chirp(780, 1180, 0.09, sr, gain=0.90),
_sil(0.02, sr),
synth_emo_chirp(1160, 1640, 0.15, sr, vibrato_hz=26, vibrato_depth=30, gain=0.94),
]),
AudibleAlert.prompt: np.concatenate([
synth_emo_chirp(920, 1420, 0.12, sr, gain=0.92),
_sil(0.03, sr),
synth_emo_chirp(1380, 1020, 0.18, sr, gain=0.92),
]),
AudibleAlert.promptRepeat: np.concatenate([
synth_emo_chirp(960, 1460, 0.12, sr, gain=0.92),
_sil(0.03, sr),
synth_emo_chirp(1420, 1060, 0.16, sr, gain=0.92),
_sil(0.28, sr),
]),
AudibleAlert.promptDistracted: np.concatenate([
synth_emo_chirp(860, 1340, 0.10, sr, gain=0.94),
_sil(0.025, sr),
synth_emo_chirp(1020, 1580, 0.14, sr, vibrato_hz=26, vibrato_depth=28, gain=0.94),
_sil(0.28, sr),
]),
AudibleAlert.warningSoft: np.concatenate([
synth_emo_chirp(1380, 1740, 0.11, sr, gain=0.96),
_sil(0.025, sr),
synth_emo_chirp(1740, 1280, 0.15, sr, gain=0.96),
_sil(0.22, sr),
]),
AudibleAlert.warningImmediateSystem: np.concatenate([
synth_emo_chirp(1480, 1860, 0.10, sr, gain=0.98),
_sil(0.02, sr),
synth_emo_chirp(1860, 1380, 0.14, sr, gain=0.98),
_sil(0.18, sr),
]),
AudibleAlert.warningImmediateUser: np.concatenate([
synth_emo_chirp(1540, 1920, 0.09, sr, gain=0.98),
_sil(0.02, sr),
synth_emo_chirp(1540, 1920, 0.09, sr, gain=0.98),
_sil(0.02, sr),
synth_emo_chirp(1920, 1420, 0.13, sr, gain=0.98),
_sil(0.18, sr),
]),
# Reactive chirps for driving & user interactions (clearly audible & bubbly)
CHIRP_SPEED_UP: np.concatenate([
synth_emo_chirp(860, 1240, 0.09, sr, gain=0.88),
_sil(0.018, sr),
synth_emo_chirp(1220, 1680, 0.12, sr, vibrato_hz=24, vibrato_depth=26, gain=0.92),
]),
CHIRP_SPEED_DOWN: np.concatenate([
synth_emo_chirp(1280, 920, 0.09, sr, gain=0.88),
_sil(0.018, sr),
synth_emo_chirp(920, 620, 0.12, sr, gain=0.88),
]),
CHIRP_STARTLED: np.concatenate([
synth_emo_chirp(740, 1780, 0.13, sr, vibrato_hz=42, vibrato_depth=55, gain=0.94),
_sil(0.02, sr),
synth_emo_chirp(1560, 980, 0.12, sr, gain=0.90),
]),
CHIRP_BOOST: np.concatenate([
synth_emo_chirp(660, 1120, 0.08, sr, gain=0.90),
_sil(0.015, sr),
synth_emo_chirp(1100, 1760, 0.16, sr, vibrato_hz=30, vibrato_depth=40, gain=0.94),
]),
CHIRP_BOOKMARK: np.concatenate([
synth_emo_chirp(980, 1440, 0.09, sr, gain=0.92),
_sil(0.02, sr),
synth_emo_chirp(1280, 1820, 0.14, sr, vibrato_hz=28, vibrato_depth=32, gain=0.94),
]),
CHIRP_BLINKER: np.concatenate([
synth_emo_chirp(920, 1260, 0.08, sr, gain=0.80),
_sil(0.015, sr),
synth_emo_chirp(1160, 1420, 0.08, sr, gain=0.80),
]),
}
class RoboticSoundPack:
"""Manages pre-loaded robotic voice/chirp buffers and reactive driving chirps for Soundd."""
def __init__(self, params, sample_rate: int = 48000):
self._params = params
self._sample_rate = sample_rate
self.enabled: bool = self._params.get_bool("MiciRoboticUI")
self.sounds: dict[int, np.ndarray] = {}
# Edge-detection state for reactive chirps
self._prev_set_speed: float = SET_SPEED_NA
self._prev_blinker: bool = False
self._last_chirp_time: float = 0.0
def load(self) -> None:
# Start with guaranteed pure-NumPy procedural chirps so soundd never fails if LFS WAVs are missing
self.sounds = build_procedural_sounds(self._sample_rate)
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
if not os.path.exists(path):
cloudlog.warning(f"Robotic sound file missing, using procedural fallback: {path}")
continue
try:
with wave.open(path, "r") as wavefile:
if (
wavefile.getnchannels() != 1
or wavefile.getsampwidth() != 2
or wavefile.getframerate() != self._sample_rate
):
cloudlog.warning(f"Robotic sound format mismatch, using procedural fallback: {path}")
continue
length = wavefile.getnframes()
if length > 0:
self.sounds[alert_id] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16 / 2)
except Exception as e:
cloudlog.warning(f"Failed to load robotic WAV (possible Git LFS pointer), using procedural fallback: {path} ({e})")
def refresh_param(self) -> bool:
"""Refresh MiciRoboticUI param; returns True if the enabled state changed."""
new_val = self._params.get_bool("MiciRoboticUI")
changed = new_val != self.enabled
self.enabled = new_val
if changed:
cloudlog.info(f"RoboticSoundPack enabled={self.enabled}")
return changed
def get_buffer(self, alert_id: int, default_sounds: dict[int, np.ndarray]) -> np.ndarray:
if self.enabled and alert_id in self.sounds:
return self.sounds[alert_id]
return default_sounds[alert_id]
def detect_reactive_chirp(self, sm, now: float | None = None) -> int | None:
"""Detect driving/user events that should emit a cute one-shot robotic chirp."""
if not self.enabled:
return None
t = time.monotonic() if now is None else now
if t - self._last_chirp_time < CHIRP_COOLDOWN:
return None
chirp: int | None = None
if sm.updated.get("userBookmark") or sm.updated.get("bookmarkButton"):
chirp = CHIRP_BOOKMARK
elif sm.updated.get("carState"):
cs = sm["carState"]
v_cruise = cs.vCruiseCluster
if v_cruise == 0.0 and sm.valid.get("controlsState"):
v_cruise = sm["controlsState"].deprecated.vCruise
cruise_set = 0 < v_cruise < SET_SPEED_NA
if cruise_set and self._prev_set_speed != SET_SPEED_NA and v_cruise != self._prev_set_speed:
chirp = CHIRP_SPEED_UP if v_cruise > self._prev_set_speed else CHIRP_SPEED_DOWN
self._prev_set_speed = v_cruise
blinker = bool(cs.leftBlinker or cs.rightBlinker)
if chirp is None and blinker and not self._prev_blinker:
chirp = CHIRP_BLINKER
self._prev_blinker = blinker
if chirp is None and not cs.standstill:
if cs.aEgo < -3.0:
chirp = CHIRP_STARTLED
elif cs.aEgo > 2.2:
chirp = CHIRP_BOOST
if chirp is not None:
self._last_chirp_time = t
return chirp
@@ -44,6 +44,7 @@ CAPABILITY_FIELDS = (
"device_type",
"subaru_has_sng",
"hyundai_alpha_long_available",
"hyundai_radar_tracks_available",
"toyota_tss2",
"custom_model_active",
)
@@ -68,6 +69,7 @@ CAPABILITY_LABELS: dict[str, str] = {
"device_type": "Device type",
"subaru_has_sng": "Subaru Stop-and-Go available",
"hyundai_alpha_long_available": "Hyundai Alpha Longitudinal available",
"hyundai_radar_tracks_available": "Hyundai radar tracks available",
"toyota_tss2": "Toyota TSS2 platform",
"custom_model_active": "Non-Default model selected",
}
@@ -88,6 +90,7 @@ CAR_CAPABILITY_FIELDS = (
"has_stop_and_go",
"subaru_has_sng",
"hyundai_alpha_long_available",
"hyundai_radar_tracks_available",
"toyota_tss2",
)
@@ -122,6 +125,7 @@ def _resolve_brand_capabilities(caps: dict, bundle_platform: str, CP) -> None:
cloudlog.exception(f"capabilities: unknown hyundai platform {bundle_platform!r}")
elif CP is not None:
caps["hyundai_alpha_long_available"] = bool(CP.alphaLongitudinalAvailable)
caps["hyundai_radar_tracks_available"] = not CP.radarUnavailable
elif brand == "subaru":
if bundle_platform:
+50 -15
View File
@@ -484,6 +484,10 @@
"value": "",
"label": "Default"
},
{
"value": 2.0,
"label": "pidd"
},
{
"value": 1.0,
"label": "v1.0"
@@ -1536,6 +1540,19 @@
"widget": "toggle",
"title": "Tesla Rainbow Mode",
"description": "Display a rainbow effect on the path the model wants to take. It does not affect driving in any way."
},
{
"key": "MiciRoboticUI",
"widget": "toggle",
"title": "Robotic Companion UI",
"description": "Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
"visibility": [
{
"type": "capability",
"field": "device_type",
"equals": "mici"
}
]
}
]
}
@@ -2186,22 +2203,9 @@
"items": [
{
"key": "HyundaiLongitudinalTuning",
"widget": "multiple_button",
"widget": "toggle",
"title": "Custom Longitudinal Tuning",
"options": [
{
"value": 0,
"label": "Off"
},
{
"value": 1,
"label": "Dynamic"
},
{
"value": 2,
"label": "Predictive"
}
],
"description": "Accelerates and brakes the way your car's own cruise control does.",
"visibility": [
{
"type": "capability",
@@ -2219,6 +2223,37 @@
"equals": true
}
]
},
{
"key": "RadarTracks",
"widget": "multiple_button",
"title": "Radar Tracks",
"options": [
{
"value": 0,
"label": "Off"
},
{
"value": 1,
"label": "Lead Only"
},
{
"value": 2,
"label": "Full Radar"
}
],
"visibility": [
{
"type": "capability",
"field": "hyundai_radar_tracks_available",
"equals": true
}
],
"enablement": [
{
"type": "offroad_only"
}
]
}
]
},
@@ -31,6 +31,10 @@ macros:
- type: not
condition: {type: capability, field: device_type, equals: mici}
# Show only on MICI hardware.
mici_only:
- {type: capability, field: device_type, equals: mici}
# Mirrors selfdrive/ui/sunnypilot/layouts/.../mads_settings.py:_mads_limited_settings()
# Rivian + Tesla-without-vehicle-bus get the limited MADS UI (3-toggle subset).
# On those platforms these toggles are disabled — full MADS settings are
@@ -225,6 +225,8 @@ sections:
options:
- value: ''
label: Default
- value: 2.0
label: pidd
- value: 1.0
label: v1.0
- value: 0.0
@@ -11,15 +11,9 @@ sections:
description: ''
items:
- key: HyundaiLongitudinalTuning
widget: multiple_button
widget: toggle
title: Custom Longitudinal Tuning
options:
- value: 0
label: 'Off'
- value: 1
label: Dynamic
- value: 2
label: Predictive
description: Accelerates and brakes the way your car's own cruise control does.
visibility:
- type: capability
field: hyundai_alpha_long_available
@@ -27,6 +21,22 @@ sections:
enablement:
- $ref: '#/macros/offroad'
- $ref: '#/macros/longitudinal'
- key: RadarTracks
widget: multiple_button
title: Radar Tracks
options:
- value: 0
label: 'Off'
- value: 1
label: Lead Only
- value: 2
label: Full Radar
visibility:
- type: capability
field: hyundai_radar_tracks_available
equals: true
enablement:
- $ref: '#/macros/offroad'
- id: subaru
title: Subaru Settings
description: ''
@@ -111,3 +111,9 @@ sections:
widget: toggle
title: Tesla Rainbow Mode
description: Display a rainbow effect on the path the model wants to take. It does not affect driving in any way.
- key: MiciRoboticUI
widget: toggle
title: Robotic Companion UI
description: Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.
visibility:
- $ref: '#/macros/mici_only'
+8 -3
View File
@@ -12,9 +12,6 @@ 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
from openpilot.sunnypilot.models.model_name import DEFAULT_BIG_MODEL, DEFAULT_MODEL
from openpilot.sunnypilot.sunnylink.capabilities import CAPABILITY_LABELS, CAR_CAPABILITY_FIELDS, generate_capabilities
from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import generate_schema
# 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: {}}
@@ -176,6 +173,14 @@ class Rpc:
return {"ok": list(values)}
def _params_metadata(self) -> dict:
from openpilot.sunnypilot.models.model_name import DEFAULT_BIG_MODEL, DEFAULT_MODEL
from openpilot.sunnypilot.sunnylink.capabilities import (
CAPABILITY_LABELS,
CAR_CAPABILITY_FIELDS,
generate_capabilities,
)
from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import generate_schema
try:
schema = generate_schema()
schema["capabilities"] = generate_capabilities(self._params)
+1 -4
View File
@@ -285,10 +285,7 @@ class Engine:
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)
# BlueZ disconnects seconds after the request, by which time the phone may have resumed on this link with another key
acts = self._plain(lk, ERROR, bytes([ERR_UNKNOWN_PHONE]))
self._links[lk.device] = _Link(lk.device, connected=lk.connected, last=now, mtu=lk.mtu, link_id=lk.link_id)
return acts
return self._error(lk, ERR_UNKNOWN_PHONE)
def _touch(self, spki: str):
saved = grants.load(self._params)
@@ -494,21 +494,8 @@ class TestReconnect(OpenpilotTestCase):
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 again.connected
assert again.pop_error() == s.ERR_UNKNOWN_PHONE and not again.connected
assert h.grant_list() == []
h.tick(10.0 + s.IDLE_SECONDS)
assert again.pop_error() == s.ERR_TIMEOUT and not again.connected
def test_unknown_key_then_known_key_on_one_link(self, mocker):
h, phone = self.granted(mocker)
again = h.new_phone(lid=0x4321, device="/again")
again.static = X25519PrivateKey.generate()
again.resume_start(self.comma_static(h), 10.0)
assert again.pop_error() == s.ERR_UNKNOWN_PHONE and again.connected
again.static = phone.static
again.resume_start(self.comma_static(h), 11.0)
assert again.connected and h.engine.connected() == 1
assert len(again.rpc("phones.list", 11.0)["result"]) == 1
def test_remove_drops_a_live_link_at_once(self, mocker):
h, phone = self.granted(mocker)
+3 -1
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import datetime
import os
import platform
import signal
import sys
import time
@@ -221,7 +222,8 @@ def main() -> None:
if __name__ == "__main__":
unblock_stdout()
if platform.system() != "Darwin":
unblock_stdout()
try:
main()
+8 -4
View File
@@ -1,5 +1,6 @@
import importlib
import os
import platform
import signal
import time
import subprocess
@@ -193,10 +194,13 @@ class DaemonProcess(ManagerProcess):
if pid is not None:
try:
os.kill(int(pid), 0)
with open(f'/proc/{pid}/cmdline') as f:
if self.module in f.read():
# daemon is running
return
if platform.system() == 'Darwin':
return
else:
with open(f'/proc/{pid}/cmdline') as f:
if self.module in f.read():
# daemon is running
return
except (OSError, FileNotFoundError):
# process is dead
pass
+45 -12
View File
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
import contextlib
import numpy as np
from functools import cache
import threading
import time
from openpilot.cereal import messaging
from openpilot.common.realtime import Ratekeeper
from openpilot.common.utils import retry
from openpilot.common.swaglog import cloudlog
RATE = 10
@@ -13,6 +14,7 @@ FFT_SAMPLES = 1600 # 100ms
REFERENCE_SPL = 2e-5 # newtons/m^2
SAMPLE_RATE = 16000
SAMPLE_BUFFER = 800 # 50ms
REINIT_RETRY_INTERVAL = 3.0
def patch_sounddevice(sd):
@@ -61,6 +63,9 @@ class Mic:
self.sound_pressure_weighted = 0
self.sound_pressure_level_weighted = 0
self.stream = None
self.last_reinit_time: float | None = None
self.lock = threading.Lock()
def update(self):
@@ -69,7 +74,10 @@ class Mic:
sound_pressure_weighted = self.sound_pressure_weighted
sound_pressure_level_weighted = self.sound_pressure_level_weighted
msg = messaging.new_message('soundPressure', valid=True)
# mark messages invalid while the mic stream is down so consumers know the
# data is stale instead of silently flatlining at zero
stream_ok = self.stream is not None and self.stream.active
msg = messaging.new_message('soundPressure', valid=stream_ok)
msg.soundPressure.soundPressure = float(sound_pressure)
msg.soundPressure.soundPressureWeighted = float(sound_pressure_weighted)
msg.soundPressure.soundPressureWeightedDb = float(sound_pressure_level_weighted)
@@ -77,6 +85,34 @@ class Mic:
self.pm.send('soundPressure', msg)
self.rk.keep_time()
# the stream can go inactive while the process is alive, e.g. if the mic
# device is gone; retry opening it so we self-recover instead of
# permanently broadcasting invalid (stale) data
if not stream_ok:
now = time.monotonic()
if self.last_reinit_time is None or (now - self.last_reinit_time) >= REINIT_RETRY_INTERVAL:
self.last_reinit_time = now
try:
self._reinit_stream()
except Exception:
cloudlog.exception("micd failed to reopen stream")
def _reinit_stream(self):
import sounddevice as sd
if self.stream is not None:
with contextlib.suppress(Exception):
self.stream.close()
self.stream = None
# reload sounddevice to reinitialize portaudio, then open the input stream
sd._terminate()
sd._initialize()
stream = sd.InputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
self.stream = stream
stream.start()
cloudlog.info(f"micd stream reinitialized: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}")
def callback(self, indata, frames, time, status):
"""
Using amplitude measurements, calculate an uncalibrated sound pressure and sound pressure level.
@@ -84,7 +120,7 @@ class Mic:
Logged A-weighted equivalents are rough approximations of the human-perceived loudness.
"""
msg = messaging.new_message('rawAudioData', valid=True)
msg = messaging.new_message('rawAudioData', valid=not status)
audio_data_int_16 = (indata[:, 0] * 32767).astype(np.int16)
msg.rawAudioData.data = audio_data_int_16.tobytes()
msg.rawAudioData.sampleRate = SAMPLE_RATE
@@ -102,22 +138,19 @@ class Mic:
self.measurements = self.measurements[FFT_SAMPLES:]
@retry(attempts=10, delay=3)
def get_stream(self, sd):
# reload sounddevice to reinitialize portaudio
sd._terminate()
sd._initialize()
return sd.InputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER)
def micd_thread(self):
# sounddevice must be imported after forking processes
import sounddevice as sd
patch_sounddevice(sd)
with self.get_stream(sd) as stream:
cloudlog.info(f"micd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}")
try:
while True:
self.update()
finally:
if self.stream is not None:
with contextlib.suppress(Exception):
self.stream.close()
self.stream = None
def main():
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+62
View File
@@ -0,0 +1,62 @@
# Hyundai/Kia/Genesis radar range matrix
This is a forum-ready summary of the routes analyzed for the sunnypilot radar
tracks work. It describes observed protocol families, not guaranteed equipment
for every model year, market, trim, or harness. A range can be present but empty
when the radar is inactive. Raw bus number is also not a layout identifier:
follow the sustained logical A-CAN source and reject brief forwarded copies.
Status terms:
- **Confirmed**: complete range, checksum/cadence, and tracked-object layout
were validated across route data.
- **Observed/optional**: verified on at least one qualifying route, but not
every route or trim carrying the main front-radar family.
- **Candidate**: source association or exact semantics remain incomplete.
- **Not radar**: camera or fused-output traffic overlapping radar-like ranges.
## Platform matrix
| Platform or platform group | Front tracked-object range | Front layout | Additional radar traffic | Camera/fused traffic that is not another radar | Status and notes |
| --- | --- | --- | --- | --- | --- |
| Kia K7 2017; older Hyundai Ioniq; sampled Ioniq PHEV | `0x500–0x53F` | 64 slots, 8 B each, about 20 Hz | `0x4E0`, `0x4E1`, `0x4E3` status/path messages | Legacy `0x238–0x24F` may coexist on applicable cars | **Confirmed** 64-slot legacy/Delphi-ESR dialect. |
| Kia Niro EV first generation; legacy Hyundai Palisade; Sonata; Sonata Hybrid | `0x500–0x51F` | 32 slots, 8 B each, about 20 Hz | `0x4E0–0x4E5` status/build/health/alignment family | Legacy `0x238–0x255` or related camera candidates may coexist by platform | **Confirmed** 32-slot legacy dialect. The upper `0x520–0x53F` bank is absent. |
| Hyundai Kona EV 2022; Kia Ceed PHEV | `0x602–0x617` | Two packed tracks in implemented messages | None established | None established | **Observed/candidate** legacy front family; the relationship between `0x602–0x611` and `0x612–0x617` remains incomplete. |
| Hyundai Elantra HEV 2024 | `0x210–0x21F` | Detailed dialect, 32 tracks in 16 × 32 B messages, 20 Hz | No paired corner family established | Platform-dependent camera traffic | **Confirmed** detailed `210` front radar. |
| Hyundai Ioniq 5; Hyundai Palisade 2023; Kia EV6, older HDA2 samples | `0x210–0x21F` | Detailed dialect, 32 tracks | Right-front candidate: `0x240–0x24F` objects plus `0x270–0x277` compact records. Left-front candidate: `0x278–0x287` objects plus `0x288–0x28F` compact records. | Isolated `0x235` traffic is not a complete camera-object family | **Confirmed** front radar. Paired front corners are **observed/optional** only on qualifying routes; A=right and B=left are strongly inferred but still need physical occlusion confirmation. |
| Hyundai Santa Cruz 2025; Tucson 4th generation; Tucson HEV 2025; Kia Sportage 5th generation | `0x210–0x21F` | Compact dialect, 32 tracks | No corner family established in checked routes | Platform-dependent camera traffic | **Confirmed** compact `210` front radar. Compact and detailed `210` share core kinematics but use different lifecycle fields. |
| Hyundai Ioniq 6 | `0x3A5–0x3C4` | Common 32-track layout, 24 B each, 20 Hz | No independent corner range established | `0x235–0x248` camera objects and `0x360–0x366` camera lane/path may be present | **Confirmed** common `3A5` front radar. |
| Hyundai Kona/Kona HEV/Kona EV 2nd generation; Santa Fe HEV 5th generation; Sonata 2024 | `0x3A5–0x3C4` | Common 32-track layout | No independent corner range established | Platform-dependent `0x235`, `0x360`, and CCNC `0x162` fused traffic | **Confirmed** common `3A5` front radar. CCNC/HDA generation does not imply rich radar extensions. |
| Kia Carnival HEV 2026; EV6 2025; K4 2025; K5 2025; Niro EV/HEV 2nd generation | `0x3A5–0x3C4` | Common 32-track layout | No independent corner range established | Platform-dependent `0x235`, `0x360`, and CCNC `0x162` fused traffic | **Confirmed** common `3A5` front radar. Bus 0/1 varies by architecture; a bus-2 copy can be forwarding. |
| Kia EV9; Hyundai Ioniq 9 | `0x3A5–0x3C4` | Rich 32-track layout with optional width, length, absolute speed, and orientation | `0x3D0–0x3D4` synchronized 32-position auxiliary scan array | `0x235–0x248` camera objects; `0x360–0x366` camera lane/path; CCNC `0x162` fused traffic | **Confirmed** rich `3A5`; `3D0` is **observed/optional** radar auxiliary traffic. Former `3D0` speed/azimuth interpretations were falsified, so it is counted but not projected as geometry. |
| Kia Sportage HEV 2026 forum sample | Overlaps `0x3A5–0x3C4` addresses | Payload is incompatible with the common `3A5` layout | Unknown | Unknown | **Excluded** from the common decoder; address overlap alone is not layout compatibility. |
## Other observed ranges
| Range | Applicable examples | Classification |
| --- | --- | --- |
| `0x235–0x248`, 32 B at about 33 Hz | Newer CAN-FD platforms, including rich EV9/Ioniq 9 captures | **Not radar:** forward-camera object list with class, motion, ID, geometry, velocity, and acceleration. |
| `0x360–0x366`, 32 B | Newer CAN-FD platforms carrying camera lane/path output | **Not radar:** forward-camera lane/path family. |
| `0x180–0x184`, `0x1B6–0x1B9`, `0x2BB–0x2BE` | Sampled Kia Sorento/Sorento HEV and Genesis GV70 candidates | **Not radar:** forward-camera auxiliary lists according to downloaded Hyundai DBCs. |
| `0x238–0x24F`, 8 B | Ioniq PHEV/HEV 2022, legacy Palisade, Niro PHEV candidates | **Not established as radar:** strong legacy forward-camera-perception candidate. |
| `0x238–0x255`, 8 B, often with `0x25A–0x25E` | Custin, Elantra/Elantra HEV 2021, Sonata/Sonata Hybrid candidates | **Not established as radar:** extended legacy forward-camera-perception candidate. |
| `CCNC_0x162` | CCNC platforms | **Not raw radar:** stock fused/cluster lead, side, and rear slots with unknown upstream fusion. |
| Bus-9 `0x300/0x400/0x500/0x600` blocks | Historical EV6 prototype capture | **Historical candidate:** four-corner FL/FR/RL/RR prototype; not reconfirmed in the current production-route corpus. |
## Supported combinations observed in the corpus
| Combination | Front | Corners or radar auxiliary |
| --- | --- | --- |
| Legacy front, 32 slots | `0x500–0x51F` | `0x4E0–0x4E5` companion/status |
| Legacy front, 64 slots | `0x500–0x53F` | `0x4E0`, `0x4E1`, `0x4E3` companion/status |
| Legacy alternate front | `0x602–0x617` | None established |
| CAN-FD detailed front only | `0x210–0x21F` | None established |
| CAN-FD detailed front plus paired front corners | `0x210–0x21F` | A/right candidate `0x240/0x270` families plus B/left candidate `0x278/0x288` families |
| CAN-FD compact front only | `0x210–0x21F` | None established |
| CAN-FD common front | `0x3A5–0x3C4` | Camera/fused families may coexist but are not independent radar tracks |
| CAN-FD rich front plus auxiliary scan | `0x3A5–0x3C4` | Optional `0x3D0–0x3D4` auxiliary radar array |
No checked route proves a combination containing both the paired
`0x240/0x270–0x28F` corner family and `0x3D0–0x3D4`. No distinct production
rear-radar tracked-object range has been confirmed. Rear objects in
`CCNC_0x162` are fused outputs and do not prove a raw rear-radar range.
+228
View File
@@ -0,0 +1,228 @@
# Hyundai/Kia/Genesis radar source inventory
This document separates physical radar sources from camera and fused-object
traffic. Signal-level evidence is in [SIGNALS.md](SIGNALS.md).
The copy-ready vehicle/range summary is in
[PLATFORM_MATRIX.md](PLATFORM_MATRIX.md).
## Confidence and safety rules
- **Confirmed layout** means that bit positions, scales, and behavior agree
across multiple routes. It does not automatically prove the physical ECU.
- **Strong role** means that topology, cadence, geometry, and related messages
support the assignment, but a controlled sensor-occlusion test is still
desirable.
- **Candidate** means useful research data only. Candidate fields must not
affect control or production filtering.
- Identify a source by the complete address set, payload sizes, cadence,
checksum behavior, and logical CAN path. An address or raw bus number alone
is not enough.
- A short copy on another bus is normally a forwarding echo. It is not a
second sensor unless timestamps and payload differences prove independence.
## Current source families
| Source | Layout | Role | Current conclusion |
| --- | --- | --- | --- |
| `0x500–0x51F` or `0x500–0x53F` | 32 or 64 × 8 B at about 20 Hz | Front radar | Shared legacy core with a Delphi ESR extension on the 64-slot dialect. K7, older Ioniq, and Ioniq PHEV samples carry 64 slots; Niro EV, Palisade, Sonata, and Sonata Hybrid samples carry 32. Implemented as standardized `RADAR_500_53F` with an optional upper half, per-source cycle end, and runtime 32-to-64 upgrade. Corrected 0.1-degree geometry is shared; 64-slot-only ESR fields use explicit aliases for 0.05 m/s² acceleration, lateral rate, width, oncoming, grouping, bridge-object, and range mode, while 32-slot acceleration retains 0.02 m/s². |
| `0x4E0–0x4E5` | 8 B at the `500` radar cadence | Front-radar companion/status | Strong source association across every sampled `500` route. Shared `4E0` is decoded as ESR vehicle speed, yaw, curvature, 16-bit scan index, timestamp, counter, and communication health. The 64-slot radar's `4E1` matches ESR Status2; 32-slot `4E1` retains only the shared counter plus unresolved static metadata. `4E3` path IDs are shared and route-validated. The 32-slot-only `4E2`, `4E4`, and `4E5` carry BCD build metadata, protocol-derived raw ADC channels, and factory/vertical alignment status. |
| `0x602–0x617` | 8 B, two packed tracks in the implemented messages | Front radar | Implemented legacy front layout. The relationship between `602–611` and the alternate `612–617` definitions remains incomplete. |
| `0x210–0x21F` | 16 × 32 B at 20 Hz, two tracks per message | Front radar | Confirmed 32-track front layout. Detailed and compact dialects share the same core. |
| `0x3A5–0x3C4` | 32 × 24 B at 20 Hz, one track per message | Front radar | Confirmed front layout. EV9 and Ioniq 9 populate its optional object-size/orientation extension. |
| `0x235–0x248` | 20 × 32 B at about 33 Hz | **Forward-camera objects** | Corrected classification. Its first 124 bits exactly match the downloaded `FR_CMR_Obj` schema and carry camera quality, class, motion, ID, geometry, velocity, and acceleration. It is not corner radar. |
| `0x240–0x24F` + `0x270–0x277` | status + 15 × 24 B objects + 8 × 32 B scan blocks | Candidate right-front corner channel A | Strong two-sensor topology on older HDA2 Ioniq 5, Palisade 2023, and EV6 routes. A=right is route/video-inferred; tracked-object position and velocity are decoded. Compact scan semantics remain unresolved. |
| `0x278–0x28F` | status + 15 × 24 B objects + 8 × 32 B scan blocks | Candidate left-front corner channel B | Symmetric partner to channel A. B=left is route/video-inferred. The compact low field is only a distance candidate; property/auxiliary bits are unresolved. |
| `0x3D0–0x3D4` | 5 × 32 B, seven packed records per message | Front-radar auxiliary scan list | Optional companion to `3A5–3C4` on sampled EV9/Ioniq 9 routes. It has 32 usable record positions and shares the radar cycle counter, but synchronized testing falsified the former radial-speed and azimuth interpretations. The low 12 bits remain only a distance candidate. |
| `0x360–0x366` | 7 × 32 B | **Forward-camera lane/path** | Camera lane/path geometry, not radar. `362` contains lane confidence; `360/361/363/364` are active geometry, while `365/366` are often default-filled optional slots. |
| legacy `0x238–0x24F` or `0x238–0x255` | 24 or 30 × 8 B at about 32 Hz | **Candidate forward-camera perception** | All 13 checked legacy routes carry one of these exact variants. Several carry a simultaneous `500` front radar at a different cadence, arguing strongly against this being a second radar. The 30-message variant also carries synchronized `25A–25E`; exact fields remain unparsed. Do not confuse these 8-byte messages with the CAN-FD `235–248` camera layout or `240/270` corner layout. |
| CAN-FD `0x180–0x184`, `0x1B6–0x1B9`, `0x2BB–0x2BE` | 32 B at about 30 Hz | **Forward-camera auxiliary lists** | Downloaded Hyundai DBCs identify the transmitters/messages as camera traffic, and route payloads have camera-list cadence and slot behavior. Not a radar family. |
| `CCNC_0x162` | fixed lead/left/right/rear slots | Fused/cluster output | Stock ADAS/cluster output with unknown upstream fusion. Do not publish it as independent raw radar. |
| bus 9 `0x300/0x400/0x500/0x600` eight-address blocks | old prototype, eight subtracks per message | Four-corner prototype | Prior EV6 reverse-engineering mapped four blocks to FL/FR/RL/RR, but status and relative speed were unfinished and the family has not been reconfirmed in the current corpus. |
The confirmed `3A5–3C4` layout was checked across 21 compatible forum routes
and 817,852 checksum-valid frames. All 726 advertised segments from the 20
unique `210–21F` routes were scanned: 16 routes had active targets, three had
a complete but empty stream, and one non-HDA2 Telluride route had no 210
range. The 16 active routes split evenly between detailed and compact
dialects, and all 13,210,543 checked 210 frames passed the HKG checksum.
The forum candidates are now classified at the family level. The legacy
`238–24F` and `238–255` variants are strong forward-camera candidates but
remain unparsed. The `180/1B6/2BB` groups are CAN-FD camera auxiliary lists.
The incomplete Ioniq PHEV `500–?` observation is a complete `500–53F`
64-slot front radar. None must be conflated with the CAN-FD `235` camera or
`240/270` corner layouts merely because their addresses overlap.
The `4E0/4E1` 2-bit counters matched in all 2,552 paired frames checked across
seven routes. On the three 64-slot routes, `4E3` matched the same counter in
all 1,133 paired frames. Every one of the 2,369 distinct `4E0` 16-bit
`SCAN_INDEX` steps incremented by one. In a fresh six-route full-segment pass,
decoded `4E0` vehicle speed correlated with `carState.vEgo` at
0.9976–0.99996, with 0.02–0.19 m/s mean absolute error. Both checked 64-slot
routes held `MAXIMUM_TRACKS_ACK=64`; all four 32-slot routes decoded that ESR
field as 1, confirming a different `4E1` dialect. The four sampled 32-slot
variants carried plausible BCD build timestamps in `4E2`; their remaining
`4E1` metadata stayed platform-static. All 7,347 nonzero `4E3` path IDs
referenced active one-based target slots. The 32-slot `4E4/4E5` payloads match
Hyundai-relocated ESR Status5/6 layouts: raw ADC health channels and alignment
status. Across 4,698 `4E5` frames, both factory-alignment fields remained
within the documented 0–3 enum subset; unexercised flags and physical ADC or
misalignment scales remain research-only.
Two other consecutive lookalikes are currently excluded from radar work:
downloaded Hyundai DBCs identify `630–63D` as head-unit/amplifier traffic, and
`5ED–5EF` occurs on routes without `500` tracks and does not follow the
otherwise strong `4E0`/`500` source association.
### Outstanding forum platform queue
| Platform | Remaining candidate |
| --- | --- |
| Hyundai Ioniq PHEV / Ioniq HEV 2022 / Palisade / Kia Niro PHEV 2022 | legacy camera candidate `238–24F`, plus its synchronized `201/20A/266/26D` companion groups |
| Hyundai Custin / Elantra 2021 / Elantra HEV 2021 / Sonata / Sonata Hybrid | extended legacy camera candidate `238–255`, plus `25A–25E` and the same companion groups |
| Kia Sorento / Sorento HEV 4th gen / Genesis GV70 | confirm semantics within the classified CAN-FD camera `180/1B6/2BB` auxiliary groups |
| Legacy `500` front-radar platforms | identify static 32-slot `4E1` metadata and calibrate/actively exercise the decoded `4E4/4E5` health and alignment fields |
The forum also listed Acura MDX and Honda Clarity examples. They remain out of
this Hyundai/Kia/Genesis inventory because the Acura range was unrelated and
the Honda routes did not expose tracks.
## Confirmed and possible vehicle combinations
These are distinct source combinations supported by the corpus. “Possible”
describes protocol combinations, not a promise that every trim exposes them.
| Combination | Front tracked objects | Corner source | Camera/auxiliary source | Known examples or status |
| --- | --- | --- | --- | --- |
| Legacy front only A | `500–51F` or `500–53F` | none observed | `4E0–4E5` radar companion/status | 32- and 64-slot platform variants |
| Legacy front only B | `602–617` | none observed | none established | Kona EV 2022, Ceed PHEV candidates |
| CAN-FD front only A | `210–21F` | none observed | none established | Elantra HEV 2024 and compact-dialect Tucson/Santa Cruz/Sportage routes |
| CAN-FD front + paired front corners | `210–21F` | inferred right A `240–24F` + `270–277`; inferred left B `278–28F` | none required | Older HDA2 Ioniq 5, Palisade 2023, and EV6 observations |
| CAN-FD front only B | `3A5–3C4` | none observed | camera objects/lanes may be absent or not logged | Compatible HDA1 routes |
| CAN-FD front + camera perception | `3A5–3C4` | none established | camera objects `235–248` and lanes `360–366` | Common newer HDA2 pattern; camera traffic is not another radar |
| Rich front + camera perception + auxiliary radar scan | rich `3A5–3C4` | none established | `235–248`, `360–366`, plus radar auxiliary records `3D0–3D4` | EV9 and Ioniq 9 sampled routes |
| Front + four-corner prototype | layout depends on the old EV6 capture | bus-9 FL/FR/RL/RR blocks | unknown | Historical prototype only; not current-production support |
No current evidence proves a combination containing both the paired
`240/270` corner family and the newer `3D0` auxiliary scan family. No distinct
rear-radar tracked-object range has been confirmed in the current routes.
Rear objects shown by `CCNC_0x162` may be fused from other sensors and do not
prove a rear radar source.
## Platform observations
| Platform group | Front | Additional observed traffic |
| --- | --- | --- |
| Ioniq 5 / Palisade 2023 / EV6 older HDA2 samples | detailed `210–21F` | paired `240/270–28F` front corners; A=right and B=left strongly inferred |
| Elantra HEV 2024 | detailed `210–21F` | no corner family established |
| Santa Cruz 2025 / Tucson family / Sportage 5th gen | compact `210–21F` | no corner family established in the checked samples |
| Ioniq 6 / Kona 2 / Kona EV 2 / Santa Fe 5 / Sonata 2024 / Carnival HEV / EV6 2025 / K4 / K5 / Niro 2 | common `3A5–3C4` where compatible | platform-dependent camera `235` and `360` traffic; no decoded corner family established |
| EV9 / Ioniq 9 | rich `3A5–3C4` | camera objects `235`, camera lanes `360`, optional front-radar auxiliary scan `3D0` |
| Sportage HEV 2026 forum sample | overlapping but incompatible `3A5` bytes | excluded from the common-layout decoder |
HDA2 changes where traffic is exposed, but raw bus number is not a reliable
layout discriminator. Follow sustained logical A-CAN and reject short
forwarded copies.
## What remains to prove
1. Confirm the route/video-derived A=right and B=left assignment with a
controlled sensor occlusion or authoritative service mapping.
2. Finish both corner status messages and the remaining 24-byte object
fields: the stable 2-bit unknown category, persistent ID, classification,
dimensions, and sensor-health flags. The former acceleration candidate was
falsified and returned to raw bits. Position and longitudinal/lateral
velocity are resolved, and `0x278` byte 3 is the confirmed pre-truncation
channel-A object count: exported A slots equal `min(count, 15)`.
Preserve all remaining unknown bits until they correlate with the compact
scan bins.
3. Decode the 56 fixed-position `270–277` / `288–28F` scan candidates,
including the low 13-bit distance candidate, seven-bit property, and
nine-bit auxiliary fields. Direct same-cycle range association and a linear
record-index-to-angle map both failed time-shift controls, so do not project
these records as geometry until an independent mapping is found.
4. Decode the `3D0` auxiliary scan array without restoring the falsified
radial-speed or azimuth names. Determine whether the low 12 bits are
distance, identify the role and physical angular ordering of the 32 record
positions, and decode the four flag bits plus both unknown bytes. Two rich
routes confirm exact counter synchronization and the sentinel/zero empty
forms, but reject range-only, candidate-geometry, and direct slot-to-slot
associations with `3A5`. Production RadarData must continue to exclude it.
5. Decode the active polynomial/path fields in `360/361/363/364`. Treat
`365/366` constant payloads as unavailable lane slots, not missing radar.
6. Resolve `235–248` `UNKNOWN_1/2/3`, identify every checksum variant, and
validate native camera classification/motion values against video. Confirm
the camera-source assignment and forwarding path on each platform carrying
the range.
7. Search explicitly for the old four-corner topology and for a distinct rear
tracked-object source. Record verified absence when the correct buses and
maneuvers were covered.
8. Resolve the static 32-slot `4E1` metadata, physically calibrate the
protocol-derived `4E4` ADC channels, and capture alignment events to verify
the inactive `4E5` flags and misalignment scales. Exercise the currently
zero FCW path IDs and low `4E3` status flags on a 32-slot platform. Shared
`4E0` and path IDs are resolved; do not transfer unsupported 64-slot
Status2 fields onto the 32-slot payload.
9. Decode the legacy camera candidates `238–24F` and `238–255`, including
their `201/20A/25A/266/26D` companion groups. Determine whether `250–255`
and `25A–25E` are extra objects, path/lane data, or metadata, and correlate
classification and geometry against video. Keep these out of production
RadarData unless source evidence overturns the current camera assignment.
10. Complete the per-platform combination matrix across HDA1/HDA2 and
CCNC/non-CCNC cars. Record the sustained logical CAN source, forwarded
echoes, empty-but-present ranges, and verified absences rather than relying
on raw bus numbers.
11. Add representative replay fixtures and debugger/on-road UI tests for each
confirmed source combination. Promote candidate names or fields only after
multi-route and controlled-scene validation.
## Useful work that does not require video
1. Cluster every unknown field by platform, object lifecycle, motion class,
address/slot, and empty/default state. Stable cross-platform enums can be
separated from platform configuration bytes.
2. Use consecutive-cycle derivatives and ego-motion compensation to test
velocity, acceleration, yaw, and sensor-frame hypotheses. Always compare
against opposite-channel and time-shifted controls.
3. Search counter phase and bounded latency, not merely nearest timestamps,
when testing associations between tracked objects, compact scan arrays,
camera objects, and status messages.
4. Build transition matrices for the corner unknown category and remaining
flags. The first pass proved the 2-bit category is
stable within a continuous object but is not lifecycle or validity: all four
values occur on active targets, while empty slots use `LONG_DIST=204.7 m`.
Continue searching the remaining fields for birth, coast, replacement, and
deletion behavior without assuming the visual object class.
5. Compare the same physical field across detailed `210`, compact `210`,
`3A5`, corner objects, and legacy `500` tracks after normalizing coordinates
and lifecycle. Shared scaling should survive route and platform changes.
6. Mine downloaded and public DBC/source comments for transmitter identity and
bit boundaries, but require route evidence before adopting physical names or
scales.
7. Measure source dropouts, checksum/counter discontinuities, and status-bit
transitions together. This can identify communication health, blockage,
alignment, and reset fields without video.
8. Generate debugger capture instructions for later physical confirmation:
cover one corner sensor at a time, use a single stationary target at a
measured distance, and record straight approach/recede passes at known
speed. These tests can settle side assignment and physical scan fields with
much less ambiguity than unconstrained road scenes.
## Implementation policy
- Production RadarData contains the confirmed tracked-object layouts only.
- `235–248` remains available through RadarData as a camera-object source for
research, with explicit source labeling and its native object-ID validity.
- The corner and `3D0` generators are research DBCs. Their unresolved fields
are named unknown or candidate in comments and are not used for control.
- `4E0–4E5` status fields are present in the `RADAR_500_53F` DBC for research,
and inventoried by the desktop radar debugger, but are not required for
source detection or production track parsing.
- The on-road UI labels `235–248` as `CAM` and uses triangle markers.
- The desktop radar debugger plots confirmed production tracks, the
debugger-only `612–617` alternate objects, and the decoded `240/278` corner
objects. Its `SIGNALS` table exposes the compact `270/288` records, `3D0`
records, `4E0–4E5` status, `360–366` raw camera payloads, and all six
`CCNC_0x162` fused slots. Compact scans and `3D0` remain table-only and are
never projected as geometry. `0x162` is explicitly labeled fused and is not
published as an independent radar source.
+450
View File
@@ -0,0 +1,450 @@
# Hyundai radar, camera-object, and auxiliary signal notes
This document tracks the evidence behind the 24-byte `RADAR_3A5_3C4` layout
and its shared signal semantics with the 32-byte `RADAR_210_21F` layout.
It also records the now-identified `0x235–0x248` camera objects and the
research-only corner and raw-detection families. It deliberately separates a
signal being active from its meaning being known.
The cross-family and per-platform investigation plan lives in
[RADAR_RESEARCH.md](RADAR_RESEARCH.md).
The forum-ready platform/range summary lives in
[PLATFORM_MATRIX.md](PLATFORM_MATRIX.md).
## Status terms
- **Confirmed core**: populated across compatible platforms and its meaning is
supported by position, motion, or lifecycle behavior.
- **Optional useful**: meaning is supported, but many platforms transmit a
default value instead of the signal.
- **Active unknown**: the field changes consistently, but its meaning is not
established well enough to use.
- **Redundant**: understood, but duplicates a better primary field.
- **Reserved/dead**: remained zero across the tested raw frames.
An optional field that is dead on one platform is not globally dead.
## Evidence corpus
- The original layout was checked against 817,852 frames from 21 forum routes.
- The 3A5 checksum was rechecked on all 817,852 frames and matched the HKG
CAN-FD checksum with the CAN address as data ID, with zero failures.
- All 726 advertised 210-route segments were scanned across 20 unique routes:
16 routes had active targets, three had complete but empty streams, and one
non-HDA2 Telluride route had no 210 stream. The 16 active routes split evenly
between detailed and compact dialects, with no third active layout.
- The 210 HKG checksum matched all 13,210,543 checked frames.
- The documented route corpus was expanded to 107 route/segment entries:
all 36 canonical Hyundai/Kia CAN-FD test routes plus the forum radar and
consecutive-range route lists. A qlog pre-screen identified candidates
carrying 24-byte 3A5 traffic, then full rlogs were used for layout decisions.
- The combined full-rlog pass contains 24 compatible route segments and
492,679 active (`STATE` 3/4) observations. Fourteen segments are HDA2 and ten
are HDA1. The compatible set covers every architecture combination:
HDA1/HDA2 and CCNC/non-CCNC.
- Full geometry/kinematics data was populated only by EV9 and Ioniq 9. Both
are HDA2 + CCNC, but HDA2 + CCNC Kona EV, EV6 2025, and K4 routes left those
fields at their unavailable defaults. A second Ioniq 9 segment independently
reproduced the rich extension.
- The 36 canonical CAN-FD test routes contributed eight compatible 3A5
segments and 150,489 active observations. This independently reproduced the
layout on HDA1 and HDA2 cars.
- An additional eight-segment local recording supplied 89,233 active track
observations. Its replay fingerprint is unavailable, so it is used for
layout/range evidence but not platform attribution.
- The known reserved bits were rechecked across 320,454 additional K5 and
local-recording frames; all remained zero.
- The Sportage HEV 2026 forum route has an incompatible overlapping layout and
is excluded from this matrix.
- A downloaded Hyundai DBC archive supplied two related but non-bit-compatible
object layouts. The BN7 front-radar DBC defines a persistent global object
ID and `0/1/2/3 = unknown/stationary/moving/stopped`; the HMVS4 object DBC
independently defines value 3 as stopped, a 7-bit quality level, and alive
age/lifetime. Neither DBC directly contains the 210 or 3A5 radar layout.
- The same archive's `FR_CMR_Obj` definition matches the first 124 bits of
`0x235–0x248` exactly. Together with its 33 Hz cadence and co-location with
`0x360–0x366`, this corrects the former corner-radar classification:
`0x235–0x248` is a forward-camera object list.
- The repository's Delphi `ESR.dbc` exactly matches the `0x500–0x53F` target
packing and the 64-slot radar's `0x4E0/0x4E1/0x4E3` status packing. A fresh
six-route full-segment check covered two 64-slot and four 32-slot variants.
`0x4E0` radar speed correlated with `carState.vEgo` at 0.9976–0.99996 with
0.02–0.19 m/s mean absolute error. Both 64-slot variants acknowledged 64
tracks in `0x4E1`; the four 32-slot payloads decoded as 1, proving that
their `0x4E1` uses a different dialect.
## 500-53F legacy front-radar layout
Every eight-byte message is one target slot. The lower 32 slots
`0x500–0x51F` are required; some radar variants add an identically packed
upper bank at `0x520–0x53F`. Inter-arrival timing on all six freshly checked
full segments is about 50 ms, confirming the established 20 Hz cadence. A gap
inside these logs makes frame count divided by total segment span misleading.
| Signal | Start bit | Size | Scale / offset | Status |
| --- | ---: | ---: | --- | --- |
| `UNKNOWN_1` | 7 | 8 signed | raw | Preserve on 32-slot variants. Its low bits are active but do not behave like ESR target flags. |
| `ONCOMING_ESR` | 0 | 1 | boolean | 64-slot only. Every flagged target in both full-segment checks had negative ground-frame speed. Clear does not distinguish stationary from same-direction moving. |
| `GROUPING_CHANGED_ESR` | 1 | 1 | boolean | 64-slot ESR identity; exact tracker behavior remains to be correlated. |
| `REL_LAT_SPEED_ESR` | 7 | 6 signed | 0.25 / 0 m/s | 64-slot ESR lateral target rate. It is not published for 32-slot variants. |
| `AZIMUTH` | 12 | 10 signed | 0.1 / 0 deg | Corrected from the former 0.2-degree scale. Lateral projection now uses the angle directly rather than a compensating half-scale. |
| `STATE` | 15 | 3 | enum | Track lifecycle; values 3 and 4 are the measured/coasted valid states used by the parser. |
| `LONG_DIST` | 18 | 11 | 0.1 / 0 m | Target range. |
| `REL_ACCEL` | 33 | 10 signed | 0.02 / 0 m/s² | 32-slot dialect scale retained from route behavior. |
| `REL_ACCEL_ESR` | 33 | 10 signed | 0.05 / 0 m/s² | 64-slot ESR scale. Separate overlapping names prevent applying it to the 32-slot dialect. |
| `WIDTH_ESR` | 37 | 4 | 0.5 / 0 m | 64-slot ESR target width. It was populated on both checked 64-slot routes and identically zero on all four 32-slot routes. |
| `COUNTER` | 38 | 1 | 1 / 0 | Per-target rolling count. |
| `BRIDGE_OBJECT_ESR` | 39 | 1 | boolean | 64-slot ESR identity; exact tracker behavior remains to be correlated. |
| `REL_SPEED` | 53 | 14 signed | 0.01 / 0 m/s | Radial range rate. |
| `MED_RANGE_MODE_ESR` | 55 | 2 | enum | 64-slot ESR medium-range operating-mode field. |
### 4E0-4E5 companion messages
`0x4E0` has the shared ESR status layout on both 32- and 64-slot variants:
| Signal | Start bit | Size | Scale / offset |
| --- | ---: | ---: | --- |
| `DSP_TIMESTAMP` | 5 | 7 | 2 / 0 ms |
| `GROUP_COUNTER` | 6 | 2 | 1 / 0 |
| `COMM_ERROR` | 14 | 1 | boolean |
| `RADIUS_CURVATURE` | 13 | 14 signed | 1 / 0 m |
| `SCAN_INDEX` | 31 | 16 | 1 / 0 |
| `YAW_RATE` | 47 | 12 signed | 0.0625 / 0 deg/s |
| `VEHICLE_SPEED` | 50 | 11 | 0.0625 / 0 m/s |
The 64-slot variant exactly matches ESR Status2 at `0x4E1`. On 32-slot
variants only its low two-bit rolling counter is active; the other 62 bits
are platform-static and do not acknowledge 32 tracks, so the ESR Status2
names remain 64-slot-only. The `0x4E3` in-path path-ID bytes are shared across
both variants, while its low status flags, counter, range mode, and alignment
angle are confirmed only on the 64-slot variant.
| `0x4E1` 64-slot signal | Start bit | Size | Scale / offset |
| --- | ---: | ---: | --- |
| `GROUP_COUNTER` | 1 | 2 | 1 / 0 |
| `MAXIMUM_TRACKS_ACK` | 7 | 6 | 1 / 1 |
| `STEERING_ANGLE_ACK` | 10 | 11 | 1 / 0 deg |
| `RAW_DATA_MODE`, `TRANSCEIVER_OPERATIONAL`, `INTERNAL_ERROR`, `RANGE_PERFORMANCE_ERROR`, `OVERHEAT_ERROR` | 11–15 | 1 each | boolean |
| `TEMPERATURE` | 31 | 8 signed | 1 / 0 °C |
| `GROUPING_MODE` | 33 | 2 | 1 / 0 |
| `VEHICLE_SPEED_COMP_FACTOR` | 39 | 6 signed | 0.00195 / 1 |
| `YAW_RATE_BIAS` | 47 | 8 signed | 0.125 / 0 deg/s |
| `DSP_SOFTWARE_VERSION` | 55 | 16 | 1 / 0 |
| `0x4E3` signal | Start bit | Size | Scale / offset |
| --- | ---: | ---: | --- |
| `GROUP_COUNTER` | 1 | 2 | 1 / 0; 64-slot confirmed |
| `MEDIUM_LONG_RANGE_MODE` | 3 | 2 | 1 / 0; 64-slot confirmed |
| `PARTIAL_BLOCKAGE`, `SIDELOBE_BLOCKAGE`, `LONG_RANGE_GRATING_LOBE_DETECTED`, `TRUCK_TARGET_DETECTED` | 4–7 | 1 each; 64-slot confirmed |
| `ACC_MOVING_PATH_ID` | 15 | 8 | one-based target slot; shared |
| `CMBB_MOVING_PATH_ID`, `CMBB_STATIONARY_PATH_ID` | 23, 31 | 8 each | one-based target slots; shared |
| `FCW_MOVING_PATH_ID`, `FCW_STATIONARY_PATH_ID` | 39, 47 | 8 each | protocol-defined; unexercised on sampled 32-slot routes |
| `AUTO_ALIGN_ANGLE` | 55 | 8 signed | 0.0625 / 0 deg; 64-slot confirmed |
| `ACC_STATIONARY_PATH_ID` | 63 | 8 | one-based target slot; shared |
All 7,347 nonzero `0x4E3` path-ID observations across the four 32-slot routes
referenced an active `0x500–0x51F` target slot. IDs reached 32, proving
one-based indexing. ACC and CMBB moving selectors commonly referenced the
same slot, as did their stationary selectors.
The 32-slot variants additionally send `0x4E2`, `0x4E4`, and `0x4E5`:
- `0x4E2` consistently encodes plausible BCD build timestamps across all four
sampled platforms.
- `0x4E4` matches the byte order and address-shifted envelope of Delphi ESR
Status5: switched-battery, ignition, two temperature, and four supply ADC
channels. The identities are protocol-derived and the raw ADC values are
intentionally uncalibrated; they must not drive a health decision.
- `0x4E5` matches the similarly relocated ESR Status6 alignment payload. In
4,698 checked frames its two factory-alignment fields used only documented
enum values 0–3. The other flags and alignment-value bytes remained zero,
so their identities are protocol-derived but not independently exercised.
Although generic ESR defines eight-byte input messages at `0x4F0/0x4F1`, no
such messages were present on these source buses. The observed Hyundai
`0x4F1` was four bytes on other/forwarded buses and is not assigned the ESR
input schema.
## Signal matrix
| Signal | Status | Availability and evidence |
| --- | --- | --- |
| `CHECKSUM` | Confirmed core | 16-bit HKG CAN-FD checksum using the CAN address as data ID. It matched all 817,852 checked 3A5 frames. |
| `COUNTER` | Confirmed core | Global transmit-cycle counter covering 0-255 and wrapping. |
| `STATE_ALT` | Redundant | Exact compressed mirror in all 325,110 active samples: `STATE=3 -> 2`, `STATE=4 -> 3`. |
| `MOTION_STATE` | Confirmed core | Ground-frame class: unknown, stationary, or moving. Correctly marked observed crossing traffic as moving. Related Hyundai radar data assigns the unused fourth 2-bit value to stopped, not oncoming; that bit remained zero throughout the tested 3A5 corpus. |
| `TRACK_COUNTER` | Confirmed core | Modulo-4 per-track update counter. Separate from the transmit counter. |
| `TRACK_QUALITY` | Confirmed core | Unsigned 7-bit track quality/existence score. Empty and tentative tracks are low, measured tracks are high, and coasted tracks decline with `COAST_AGE`. A related Hyundai object layout describes its 7-bit quality level as reliability, validity, or probability evidence; the radar's raw scale is not confirmed to be a percentage. |
| `AGE` | Confirmed core | Per-track alive age/lifetime count, 0-255. |
| `COAST_AGE` | Confirmed core | Zero for measured tracks and increments while a track is coasted/predicted. |
| `STATE` | Confirmed core | Track lifecycle: empty, tentative, measured, coasted, or unresolved tentative. |
| `RCS` | Confirmed core | Signed radar cross-section/return-strength value. At controlled distances its median consistently increases from small to passenger to large targets. The raw unit is not calibrated. |
| `LONG_DIST` | Confirmed core | Longitudinal target distance in meters. |
| `LAT_DIST` | Confirmed core | Lateral target position relative to the ego axis in meters. |
| `REL_SPEED` | Confirmed core | Longitudinal target speed relative to ego. |
| `NEW_SIGNAL_4` | Active unknown | Category 0-2. Nonzero in about 25% of moving samples, 10% of stationary samples, and 6% of unknown samples; it is related to target state but is not another motion class. |
| `REL_LAT_SPEED` | Confirmed core | Lateral target speed relative to the ego axis. A live crossing target showed `+6.78 m/s` lateral versus `-0.51 m/s` forward. An EV9 route independently supplied hundreds of perpendicular-motion samples. |
| `REL_ACCEL` | Confirmed core | Longitudinal target acceleration relative to ego. |
| `NEW_SIGNAL_18` | Optional active unknown | A lifecycle/measurement-status attribute on rich layouts. In the public EV9/Ioniq 9 data, values 1/2 occur almost exclusively while `STATE=3` is measured and 0 while `STATE=4` is coasted; one anomalous coasted sample retained 2. The distinction between 1 and 2 is unknown. Most platforms always send 0, and a compatible long recording contains the rare value 3. |
| `NEW_SIGNAL_5` | Optional active unknown | Sparse value observed from 0 to 32 on both HDA1 and HDA2 routes, including platforms without rich geometry. No stable correlation is known. |
| `WIDTH` | Optional useful | Target width in 0.1 m units. Populated on EV9/Ioniq 9; passenger-car values cluster around 1.8-2.0 m. Zero means unavailable on other sampled platforms. Every address in 3A5-3C4 can carry it, so it does not identify a separate track bank. |
| `LENGTH` | Optional useful | Target length in 0.1 m units. Passenger cars cluster around 4 m and long vehicles reach roughly 13-15.5 m. It is available on the same target samples as `WIDTH`. |
| `ABS_SPEED` | Optional useful | Absolute target-speed magnitude. On Ioniq 9 it matches `hypot(vEgo + REL_SPEED, REL_LAT_SPEED)` with about 0.08-0.15 m/s median error. It was populated for 28,735/28,860 active Ioniq 9 samples and 23,252/27,339 EV9 samples, including many targets without dimensions. Zero is the platform default when unsupported. |
| `ORIENTATION_ANGLE` | Optional useful | Target orientation relative to the ego axis. Ioniq 9 follows motion heading within roughly 2 degrees median; EV9 crossing traffic rotated from about -45 to -83 degrees. It is associated with dimension-bearing targets. Values near `+/-180` can represent real rearward orientation on rich tracks, while compatible non-rich platforms consistently use +180 as unavailable/default. |
| `NEW_SIGNAL_13` | Optional active unknown | Shape/geometry metadata from 0-10. It was nonzero only on dimension-bearing targets in the EV9/Ioniq 9 routes. Confidence-like behavior is plausible but not established. |
| `NEW_SIGNAL_12` | Optional active unknown | Strong geometry-age/maturity candidate. Two independent Ioniq 9 routes progressed `0 -> 1 -> 2 -> ... -> 10` and saturated at 10. It remains unnamed pending confirmation on another rich platform. |
| `NEW_SIGNAL_14` | Optional active unknown | Shape/geometry category 0-3. It is zero when the associated geometry metadata is unavailable. |
| `NEW_SIGNAL_15` | Optional active unknown | Shape/geometry category 0-2. It is zero when the associated geometry metadata is unavailable. |
| `NEW_SIGNAL_16` | Optional active unknown | Shape/geometry category 0-3. It is zero when the associated geometry metadata is unavailable. |
| `NEW_SIGNAL_17` | Optional active unknown | Shape/geometry category 0-2. It is zero when the associated geometry metadata is unavailable. The most common rich-layout `14/15/16/17` tuple is `2/2/2/1`. |
## Cross-family layout and naming findings
Both families expose 32 tracks at approximately 20 Hz per address:
| Layout | Envelope | Tracks per message | Shared core | Family-specific extension |
| --- | --- | --- | --- | --- |
| 210 detailed | `0x210-0x21F`, 32 bytes | 2 | State, motion, quality, age/coast age, RCS, range, relative velocity/acceleration | Detailed state/RCS/category are populated; compact object-ID bytes are normally zero |
| 210 compact | `0x210-0x21F`, 32 bytes | 2 | Same bit positions and scales except for the documented lateral-speed sign convention | Uses `STATE_ALT`, per-target status and persistent 6-bit `OBJECT_ID`; detailed state/RCS/category remain zero |
| 3A5 common | `0x3A5-0x3C4`, 24 bytes | 1 | Homologous first 16 bytes | Bytes 16-23 carry measurement status and optional dimensions, absolute speed, orientation, and geometry metadata |
The shared signal conclusions are:
- The old signed `NEW_SIGNAL_2` decoding was wrong. Raw values use 0-99 in the
tested corpus, and the signed interpretation created an artificial wrap at
63/64. The standardized name is `TRACK_QUALITY`, unsigned 7-bit.
- Detailed 210 and 3A5 `TRACK_QUALITY` distributions are nearly identical.
Compact 210 uses a higher calibration, commonly around 70 while measured,
that falls toward the low 20s at long coast ages. The semantic name is
shared, but no percentage unit is assigned.
- The old `NEW_SIGNAL_8` is standardized as `RCS`. Detailed 210 and 3A5 have
closely matching distributions, and size ordering is preserved within every
tested distance band. 210 supplies eight signed bits; 3A5 supplies seven
because the remaining bit extends `LONG_DIST` from 12 to 13 bits.
- `NEW_SIGNAL_4` occupies the same physical two bits and has nearly identical
0-2 distributions in detailed 210 and 3A5, but its exact category remains
unknown.
- Compact 210 `OBJECT_ID` remains strongly supported: it held through 99.9%
of consecutive same-track updates and changed when a slot acquired a
replacement target. A related Hyundai BN7 radar DBC independently defines
`ObjectId` as a global ID that remains constant while an object is tracked.
Sparse 3A5 `NEW_SIGNAL_5` does not behave like the same field and remains
unknown.
## Oncoming classification
Oncoming candidates were cross-checked using fresh ego speed and
`vEgo + REL_SPEED < -3 m/s`.
| Layout | Evidence | Conclusion |
| --- | --- | --- |
| 210 compact | Motion code 4 appeared on 4,870 active rows. Synchronized code-4 rows had -13.30 m/s median ground-frame longitudinal speed, with 3,516 strong oncoming candidates. Related Hyundai BN7 radar and HMVS4 object DBCs independently label motion value 3 as stopped. | `MOTION_STATE=3` is stopped and `MOTION_STATE=4` is the compact oncoming class. |
| 210 detailed | Bit 29 never set across 317,965 active rows. Its 4,924 physics-based candidates remained in motion values 0-2. | No dedicated detailed-210 oncoming value. |
| 3A5 common | Bit 29 remained zero in all 817,852 frames. Among 6,104 physics-based candidates across 14 routes, motion was 0 for 5,792, 1 for 312, and never 2. | No dedicated 3A5 oncoming value or flag. |
`NEW_SIGNAL_4` and `NEW_SIGNAL_18` also failed to isolate the 3A5 oncoming
candidates. Do not widen 3A5 `MOTION_STATE` to three bits. If oncoming
classification is needed for 3A5 or detailed 210, derive it from ego-relative
kinematics with persistence, hysteresis, and lane plausibility.
## Platform and cluster conclusions
| Architecture | Compatible examples | Rich geometry |
| --- | --- | --- |
| HDA2 + CCNC | Kona EV 2, EV6 2025, K4, EV9, Ioniq 9 | EV9 and Ioniq 9 only |
| HDA2 + non-CCNC | Ioniq 6, Niro EV 2, Carnival HEV | None observed |
| HDA1 + CCNC | Kona 2/HEV, Sonata/HEV, K4, K5, Santa Fe 5 | None observed |
| HDA1 + non-CCNC | Niro EV 2/HEV | None observed |
- HDA2 changes the normal 3A5 bus from bus 1 to bus 0, but does not imply
rich extension support.
- EV6 2025 carried a complete 3A5 range on buses 0 and 2. The bus-2 subset was
a 99.6% exact byte-for-byte subset of bus 0, consistent with forwarding
rather than a second radar. The runtime selects one active bus per range.
- The optional bytes are attributes on the same 32 addresses, not extra
objects. Dimension-bearing targets appeared throughout 3A5-3C4 rather than
in a dedicated address subset.
- Stock `CCNC_0x162` is a separate fused cluster-object output. Two HDA2 +
CCNC Kona EV routes exercised lead, left/right, and both rear slots while
every 3A5 width/length/absolute-speed/shape field remained unavailable.
Rear-slot distance capped at 20 m and the stock lateral value was fixed at
3.0 m. `LEAD_ALT` remained hidden in both sampled segments.
- Therefore, the additional cluster tofus are real stock CCNC/ADAS outputs,
but they cannot be reconstructed merely by reading the 3A5 rich extension.
Rear tofus in particular need a source beyond the forward 3A5 radar.
## 235-248 forward-camera object layout
Each 32-byte message is one camera-object slot. `OBJECT_ID=0` is unused in the
observed routes. The production parser normalizes the native camera motion
enum to the shared `unknown/stationary/moving` display enum, but preserves the
raw DBC value.
| Signal | Start bit | Size | Scale / offset | Status |
| --- | ---: | ---: | --- | --- |
| `CHECKSUM` | 0 | 16 | 1 / 0 | Checksum field; platform variants exist, so the generator does not force the standard HKG algorithm. |
| `COUNTER` | 16 | 8 | 1 / 0 | Transmit-cycle counter. |
| `QUALITY` | 24 | 7 | 1 / 0 | Camera-object quality/reliability level. |
| `AGE` | 32 | 8 | 1 / 0 | Object alive age. |
| `MOTION_STATE` | 40 | 4 | 1 / 0 | Native camera motion class. |
| `OBJECT_ID` | 44 | 7 | 1 / 0 | Persistent object ID; zero is unused. |
| `WIDTH` | 52 | 7 | 0.05 / 0 m | Estimated width. |
| `CLASSIFICATION` | 60 | 3 | 1 / 0 | Unknown, truck, car, motorcycle, bicycle, pedestrian, undecided. |
| `LONG_DIST` | 64 | 13 | 0.05 / 0 m | Longitudinal relative position. |
| `LAT_DIST` | 78 | 12 | 0.05 / -102.4 m | Lateral relative position. |
| `REL_SPEED` | 91 | 12 | 0.05 / -100 m/s | Longitudinal relative velocity. |
| `REL_LAT_SPEED` | 104 | 10 | 0.05 / -25 m/s | Lateral relative velocity. |
| `REL_ACCEL` | 115 | 9 signed | 0.05 / 0 m/s² | Longitudinal relative acceleration. |
| `UNKNOWN_1` | 125 | 12 | raw | Active extension; semantics unknown. |
| `UNKNOWN_2` | 138 | 12 | raw | Active extension; semantics unknown. |
| `UNKNOWN_3` | 151 | 10 | raw | Active extension; semantics unknown. |
| `AZIMUTH` | 176 | 14 | 360/16384 / -180 deg | Route-validated high-resolution object azimuth. |
Native motion values are: 0 undefined, 1 standing, 2 parked, 3 stopped,
4 unknown movable, 5 moving, 6 stopped oncoming, 7 unknown oncoming,
8 moving oncoming, and 9 crossing bicycle. This is the only newly decoded
family with explicit oncoming moving and stopped-oncoming values.
## 240/270-28F candidate corner-radar layout
The address sizes and symmetry form two complete sensor channels:
| Channel | Inferred physical side | Status | Object slots | Compact scan records |
| --- | --- | --- | --- | --- |
| A | right front | `240`, 16 B | `241–24F`, 15 × 24 B | `270–277`, 8 × 32 B, seven records each |
| B | left front | `278`, 8 B | `279–287`, 15 × 24 B | `288–28F`, 8 × 32 B, seven records each |
Both channels run at about 20 Hz and validate with the HKG CAN-FD checksum in
the sampled Ioniq 5, Palisade 2023, and EV6 data. All 288,021 checked frames
from five complete segment samples passed. A synchronized Palisade
parking-garage sweep strongly assigns A to the right-front sensor and B to
the left-front sensor: A alone retained close objects at large negative
lateral position, while B alone retained the corresponding positive-side
objects. This is strong route/video evidence, but a controlled sensor
occlusion remains the final physical confirmation.
The 24-byte tracked-object record is:
| Signal | Bit | Size | Scale / offset | Status |
| --- | ---: | ---: | --- | --- |
| `UNKNOWN_CATEGORY` | 24 | 2 | raw | Stable within continuous same-slot tracks and changes mainly when a spatially different target replaces the slot. All values 0–3 occur on active objects, so this is not lifecycle or validity. |
| `RCS` | 56 | 7 signed | 1 / 0 | Strong shared-core identification; raw unit uncalibrated. |
| `LONG_DIST` | 63 | 13 | 0.05 / 0 m | Confirmed vehicle-frame longitudinal position. |
| `LAT_DIST` | 76 | 11 signed | 0.05 / 0 m | Confirmed vehicle-frame lateral position. |
| `UNKNOWN_BIT_87` | 87 | 1 | raw | Active unknown. |
| `REL_SPEED` | 88 | 10 signed | 0.2 / 0 m/s | Confirmed longitudinal relative velocity. Four held-out Palisade samples exercised bit 97 independently of bit 96 at 351–357 m; consecutive distance changes matched approximately -52 m/s rather than the false positive speed produced by the former 9-bit decode. |
| `REL_LAT_SPEED` | 98 | 10 signed | 0.05 / 0 m/s | Confirmed lateral relative velocity. |
| `UNKNOWN_BITS_108_117` | 108 | 10 | raw | Former centered acceleration candidate. Its correlations with consecutive `REL_SPEED` derivatives were -0.445, -0.043, -0.009, -0.111, and -0.124 across five Ioniq 5, Palisade, and EV6 samples, so the physical name and scale were falsified. |
Empty object slots use the exact `LONG_DIST=204.7 m` (`0xFFE`) sentinel;
`UNKNOWN_CATEGORY=0` must not be used as an empty test. This correction was
validated on five Ioniq 5, Palisade 2023, and EV6 samples. Including
category-zero objects produced longitudinal position-derivative correlations
of 0.949, 0.603, 0.962, 0.948, and 0.967 across those samples.
The position decode was independently checked against simultaneous
`210–21F` front-radar targets. The 116 unambiguous A matches and 86 B matches
had longitudinal/lateral correlations of 0.999/0.991 and 0.999/0.993,
respectively, with about 0.3 m mean absolute error. Across 14,939 consecutive
same-slot updates, decoded longitudinal and lateral velocity correlated with
position derivatives at 0.964 and 0.944. No lifecycle field has been
identified, and the former acceleration candidate failed derivative checks.
The remaining header, classification, dimension, ID, and health fields stay
bit-preserved rather than borrowing names from the related front-radar core.
The first payload byte after the counter in `0x278` is
`CHANNEL_A_OBJECT_COUNT`. Across 5,999 synchronized cycles on five Ioniq 5,
Palisade, and EV6 samples, the number of non-sentinel `0x241–0x24F` slots equaled
`min(CHANNEL_A_OBJECT_COUNT, 15)` exactly. It ranged from 0–22; values above
15 prove it is the pre-truncation internal candidate count rather than merely
the number of exported slots. The `0x240` status payload remains unresolved;
notably, it was entirely zero after checksum/counter on one Palisade and one
EV6 sample while being active on the other three routes.
The compact arrays are not alternate encodings of that object count. Depending
on route and channel, 11–55 of their 56 bins were non-sentinel in a cycle,
versus at most 15 exported tracked objects; count correlations ranged from
weak to moderate and were never exact.
The compact 32-bit scan record is:
| Record field | Relative bit | Size | Scale | Status |
| --- | ---: | ---: | --- | --- |
| `DISTANCE_CANDIDATE` | 0 | 13 | 0.05 m | Range-like distribution and 400 m endpoint; no synchronized object association, so physical distance is not confirmed. |
| `RESERVED` | 13 | 3 | raw | Preserve. |
| `PROPERTY` | 16 | 7 | raw | Active categorical unknown; sampled values were quantized. |
| `AUX` | 23 | 9 | raw | Active unknown; velocity and split flag/state hypotheses were falsified. |
Record 0 starts at message bit 24, message bit 56 is a frame-status byte, and
records 1–6 start at bits 64, 96, 128, 160, 192, and 224. Unused records
commonly contain `0x010D1F40`, with AUX variants such as `0x018D1F40`; its
low-field component is the 400 m endpoint. Contemporaneous range matching was no
better than the opposite channel or a 500 ms-shifted control. Each of the 56
record positions instead has a characteristic occupancy/range profile, making
this a strong fixed scan/bin-array candidate rather than 56 freely assigned
tracked detections. A direct linear record-index-to-angle search on Ioniq 5
and Palisade data also performed no better than a 500 ms-shifted control.
Decoding the low field, physical ordering, `PROPERTY`, and `AUX` remains open.
## 3D0-3D4 front-radar auxiliary scan records
This optional list accompanies `3A5–3C4` on sampled EV9 and Ioniq 9 routes.
Five 32-byte messages contain seven record positions each; the final three
positions of `3D4` are outside the 32-position list. The repeated
`0xC8782EE0` value and, on EV9, zero are unused records. All 12,090 checked
message frames passed the HKG CAN-FD checksum and carried the same cycle
counter as `3A5–3C4`.
| Record field | Relative bit | Size | Scale / offset | Status |
| --- | ---: | ---: | --- | --- |
| `DISTANCE_CANDIDATE` | 0 | 12 | 0.05 / 0 m | Range-like distribution and endpoint, but no synchronized tracked-object match; not confirmed. |
| `FLAGS_UNKNOWN` | 12 | 4 | raw | Active values 0–2 in the sampled routes; semantics unknown. |
| `UNKNOWN_BYTE_16` | 16 | 8 | raw | Former radial-speed candidate was falsified. |
| `UNKNOWN_BYTE_24` | 24 | 8 | raw | Former azimuth candidate was falsified. |
Packing positions match the corner scan records: record 0 at message bit 24,
one alignment byte at bit 56, then records 1–6 at bits 64 through 224. However,
the exact corner `13/3/7/9` field split is not transferred onto this
`12/4/8/8` layout without evidence.
The stronger synchronized test falsified three tempting interpretations:
- Range-only, candidate polar-geometry, and direct record-index-to-track-index
associations were no better than opposite or 500 ms-shifted controls.
- `UNKNOWN_BYTE_16` had essentially zero correlation with `3A5` longitudinal
or radial relative speed.
- `UNKNOWN_BYTE_24` had essentially zero correlation with `3A5` target angle.
The 32 positions do show stable position-dependent occupancy and low-field
profiles, so a fixed scan/bin or intermediate radar-array role remains
plausible. They are not independent tracked objects, remain excluded from
production RadarData, and are shown only as raw records in the debugger's
`SIGNALS` table, never projected as geometry.
## 360-366 forward-camera lane/path family
These seven 32-byte messages belong to the forward camera. `362` already
contains left/right lane-line confidence. `360`, `361`, `363`, and `364`
carry changing lane/path polynomial-like geometry; their field boundaries are
not yet decoded. `365` and `366` are commonly constant/default-filled,
consistent with unavailable extra lane slots. Their presence or emptiness
must not be interpreted as a radar hardware combination.
## Reserved/dead bits
Bits `26`, `29`, `39`, `55`, `117`, `136-137`, `143`, `171`, and
`188-191` remain zero. No new signal location was found in the follow-up
routes.
## Parser guidance
- Detect support per radar source instead of treating extension defaults as
real measurements.
- Treat zero dimensions as unavailable. Treat +180 as unavailable on non-rich
platforms, but do not discard near-180 rich tracks without checking their
other geometry and lifecycle fields.
- Do not use any `NEW_SIGNAL_*` field for control or filtering until its
meaning is independently validated.
- `TRACK_QUALITY` and `RCS` are decoded for research and diagnostics, but
neither has a calibrated physical/percentage scale suitable for control.
- `REL_LAT_SPEED` is suitable for debugging cross traffic, but a production
cross-traffic filter still needs lane-change validation and track history.
+343
View File
@@ -0,0 +1,343 @@
#!/usr/bin/env python3
import argparse
import concurrent.futures
import os
import signal
import subprocess
import sys
import time
from collections import Counter, defaultdict
import cereal.messaging as messaging
from msgq.ipc_pyx import IpcError
from opendbc.car.tests.routes import CarTestRoute, routes
from openpilot.tools.radar.custom_routes import CUSTOM_ROUTES
from openpilot.tools.radar.radar_helpers import (
build_seen_address_map,
get_radar_spec,
is_exclusive_full_range_match,
)
REPLAY_PATH = os.path.join(os.path.dirname(__file__), "..", "replay", "replay")
REPLAY_PLAYBACK_SPEED = "3.0"
REPLAY_ALLOW_SERVICES = "can"
DETECTION_TIMEOUT_SECONDS = 20.0
DETECTION_MIN_HITS = 10
SOCKET_WAIT_TIMEOUT_SECONDS = 10.0
CAR_MODEL_WIDTH = 38
RADAR_TYPE_WIDTH = 10
ANSI_RESET = "\033[0m"
ANSI_BOLD = "\033[1m"
ANSI_DIM = "\033[2m"
ANSI_RED = "\033[31m"
ANSI_GREEN = "\033[32m"
ANSI_YELLOW = "\033[33m"
ANSI_BLUE = "\033[34m"
ANSI_MAGENTA = "\033[35m"
ANSI_CYAN = "\033[36m"
RADAR_FAMILY_COLORS = {
"RADAR_500_51F": ANSI_CYAN,
"RADAR_210_21F": ANSI_YELLOW,
"RADAR_3A5_3C4": ANSI_GREEN,
"RADAR_602_611": ANSI_BLUE,
}
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Replay Hyundai/Kia/Genesis test routes and auto-detect radar type.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--routes", action="store_true",
help="Use Hyundai/Kia/Genesis routes from opendbc/car/tests/routes.py.")
parser.add_argument("--custom-routes", action="store_true",
help="Use routes from tools/radar/custom_routes.py.")
parser.add_argument("--route", action="append", default=[],
help="Specific route(s) to test. If omitted, use Hyundai/Kia/Genesis routes from opendbc/car/tests/routes.py.")
parser.add_argument("--data-dir", default=None,
help="Optional local directory of route data to pass through to replay.")
parser.add_argument("--timeout", type=float, default=DETECTION_TIMEOUT_SECONDS,
help="Seconds to wait for a radar-family detection before giving up on a route.")
parser.add_argument("--min-hits", type=int, default=DETECTION_MIN_HITS,
help="Minimum CAN hits in a radar-family address range before considering it detected.")
parser.add_argument("--playback", default=REPLAY_PLAYBACK_SPEED,
help="Replay playback speed.")
parser.add_argument("--limit", type=int, default=None,
help="Only process the first N matching routes.")
parser.add_argument("--jobs", type=int, default=1,
help="Number of routes to process in parallel.")
parser.add_argument("--prefix", default="auto-radar-detect",
help="Base OPENPILOT_PREFIX to isolate replay sockets.")
return parser
def get_hkg_routes() -> list[CarTestRoute]:
hkg_prefixes = ("HYUNDAI_", "KIA_", "GENESIS_")
return [
route for route in routes
if route.car_model is not None and getattr(route.car_model, "name", str(route.car_model)).startswith(hkg_prefixes)
]
def get_selected_routes(args: argparse.Namespace) -> list[CarTestRoute]:
selected_sources = int(bool(args.route)) + int(bool(args.routes)) + int(bool(args.custom_routes))
if selected_sources > 1:
raise ValueError("Use only one of --route, --routes, or --custom-routes.")
if args.route:
route_map = {route.route: route for route in get_hkg_routes()}
selected = []
for route_name in args.route:
selected.append(route_map.get(route_name, CarTestRoute(route_name, None)))
return selected[:args.limit] if args.limit is not None else selected
if args.custom_routes:
selected = [CarTestRoute(route.route, route.car_model) for route in CUSTOM_ROUTES]
return selected[:args.limit] if args.limit is not None else selected
selected = get_hkg_routes()
return selected[:args.limit] if args.limit is not None else selected
def terminate_process(proc: subprocess.Popen) -> None:
if proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
def start_replay(route: str, prefix: str, args: argparse.Namespace) -> subprocess.Popen:
cmd = [
REPLAY_PATH,
"--no-vipc",
"--no-loop",
"--playback", args.playback,
"--allow", REPLAY_ALLOW_SERVICES,
"--prefix", prefix,
]
if args.data_dir:
cmd.extend(["--data_dir", args.data_dir])
cmd.append(route)
env = os.environ.copy()
env["OPENPILOT_PREFIX"] = prefix
return subprocess.Popen(
cmd,
cwd=os.path.dirname(REPLAY_PATH),
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setsid if os.name != "nt" else None,
)
def stop_replay(proc: subprocess.Popen) -> None:
if proc.poll() is not None:
return
if os.name != "nt":
try:
os.killpg(proc.pid, signal.SIGTERM)
except ProcessLookupError:
return
else:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
if os.name != "nt":
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
return
else:
proc.kill()
proc.wait(timeout=5)
def wait_for_can_socket(prefix: str, timeout: float) -> messaging.SubSocket:
socket_path = os.path.join("/tmp", f"msgq_{prefix}", "can")
started = time.monotonic()
while True:
if os.path.exists(socket_path):
break
if time.monotonic() - started > timeout:
raise TimeoutError(f"Timed out waiting for CAN socket at {socket_path}")
time.sleep(0.1)
while True:
try:
return messaging.sub_sock("can", conflate=False, timeout=100)
except IpcError:
if time.monotonic() - started > timeout:
raise
time.sleep(0.1)
def detect_radar_family(route: CarTestRoute, route_idx: int, args: argparse.Namespace) -> dict:
prefix = f"{args.prefix}-{os.getpid()}-{route_idx}"
os.environ["OPENPILOT_PREFIX"] = prefix
messaging.reset_context()
proc = start_replay(route.route, prefix, args)
logcan = wait_for_can_socket(prefix, min(args.timeout, SOCKET_WAIT_TIMEOUT_SECONDS))
counts = Counter()
buses = defaultdict(set)
seen_addresses = build_seen_address_map()
started = time.monotonic()
detected = None
try:
while True:
if proc.poll() is not None and (time.monotonic() - started) > 1.0:
break
if time.monotonic() - started > args.timeout:
break
msgs = messaging.drain_sock(logcan, wait_for_one=True)
for msg in msgs:
for can_msg in msg.can:
radar_spec = get_radar_spec(can_msg.address)
if radar_spec is not None:
counts[radar_spec.name] += 1
buses[radar_spec.name].add(can_msg.src)
seen_addresses[radar_spec.name].add(can_msg.address)
if counts[radar_spec.name] >= args.min_hits and is_exclusive_full_range_match(radar_spec, seen_addresses):
detected = radar_spec.name
if detected is not None:
break
if detected is not None:
break
if detected is not None:
break
finally:
stop_replay(proc)
dominant_family = detected
return {
"route": route.route,
"car_model": str(route.car_model) if route.car_model is not None else "UNKNOWN",
"detected": dominant_family or "NONE",
"counts": dict(counts),
"buses": {name: sorted(bus_set) for name, bus_set in buses.items()},
"seen_addresses": {name: sorted(addresses) for name, addresses in seen_addresses.items()},
}
def print_results(results: list[dict]) -> None:
print(f"{'Car Model':<{CAR_MODEL_WIDTH}} {'Detected':<{RADAR_TYPE_WIDTH}} Route")
print("-" * (CAR_MODEL_WIDTH + RADAR_TYPE_WIDTH + 9 + 60))
for result in results:
detected_plain = "" if result["detected"] == "NONE" else result["detected"]
model = format_car_model(result["car_model"])[:CAR_MODEL_WIDTH]
detected = f"{detected_plain:<{RADAR_TYPE_WIDTH}}"
if supports_color() and detected_plain:
detected = f"{colorize_detected(detected_plain)}" + " " * max(0, RADAR_TYPE_WIDTH - len(detected_plain))
print(f"{model:<{CAR_MODEL_WIDTH}} {detected} {result['route']}")
def supports_color() -> bool:
return sys.stdout.isatty() and os.getenv("TERM") not in (None, "dumb")
def format_car_model(car_model: object) -> str:
return str(car_model) if car_model is not None else "UNKNOWN"
def colorize_detected(detected: str) -> str:
if detected == "NONE":
return ""
if not supports_color():
return detected
color = RADAR_FAMILY_COLORS.get(detected, ANSI_MAGENTA)
return f"{color}{detected}{ANSI_RESET}"
def print_progress_line(index: int, total: int, route: CarTestRoute, detected: str) -> None:
left = f"[{index}/{total}]"
model = format_car_model(route.car_model)[:CAR_MODEL_WIDTH]
detected_plain = "" if detected == "NONE" else detected
route_text = route.route
if supports_color():
left = f"{ANSI_DIM}{left}{ANSI_RESET}"
model = f"{ANSI_CYAN}{model:<{CAR_MODEL_WIDTH}}{ANSI_RESET}"
detected_text = colorize_detected(detected_plain).ljust(len(colorize_detected(detected_plain)))
route_text = f"{ANSI_DIM}{route_text}{ANSI_RESET}"
else:
model = f"{model:<{CAR_MODEL_WIDTH}}"
detected_text = detected_plain
detected_text = f"{detected_plain:<{RADAR_TYPE_WIDTH}}" if not supports_color() else (
f"{colorize_detected(detected_plain)}" + " " * max(0, RADAR_TYPE_WIDTH - len(detected_plain))
)
print(f"{left} {model} {detected_text} {route_text}")
def main() -> int:
args = build_arg_parser().parse_args(sys.argv[1:])
try:
selected_routes = get_selected_routes(args)
except ValueError as e:
print(str(e), file=sys.stderr)
return 2
if not selected_routes:
print("No matching routes found.", file=sys.stderr)
return 1
results = []
total = len(selected_routes)
jobs = max(1, min(args.jobs, total))
header_model = "Car Model"
header_detected = "Radar"
if supports_color():
header_model = f"{ANSI_BOLD}{header_model:<{CAR_MODEL_WIDTH}}{ANSI_RESET}"
header_detected = f"{ANSI_BOLD}{header_detected:<{RADAR_TYPE_WIDTH}}{ANSI_RESET}"
else:
header_model = f"{header_model:<{CAR_MODEL_WIDTH}}"
header_detected = f"{header_detected:<{RADAR_TYPE_WIDTH}}"
print(f" {header_model} {header_detected} Route")
if jobs == 1:
for idx, route in enumerate(selected_routes):
result = detect_radar_family(route, idx, args)
print_progress_line(idx + 1, total, route, result['detected'])
results.append((idx, result))
else:
with concurrent.futures.ProcessPoolExecutor(max_workers=jobs) as executor:
future_to_job = {
executor.submit(detect_radar_family, route, idx, args): (idx, route)
for idx, route in enumerate(selected_routes)
}
completed = 0
for future in concurrent.futures.as_completed(future_to_job):
idx, route = future_to_job[future]
result = future.result()
completed += 1
print_progress_line(completed, total, route, result['detected'])
results.append((idx, result))
results = sorted(
(result for _, result in results),
key=lambda result: (result["car_model"], result["route"]),
)
print()
print_results(results)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
from dataclasses import dataclass
@dataclass(frozen=True)
class CustomRoute:
car_model: str
route: str
CUSTOM_ROUTES = [
CustomRoute("HYUNDAI_ELANTRA_HEV_2024", "07a48901db7b2503|0000012d--61aba9f832"),
CustomRoute("HYUNDAI_IONIQ_5", "c5a5f79df9b6a084/0000005d--24c0a7a7ee"),
CustomRoute("HYUNDAI_IONIQ_5", "90950642f47cf05b/00000681--6a904aaa98"),
CustomRoute("HYUNDAI_IONIQ_5", "102161de13e822d1/0000000d--f74a52a624"),
CustomRoute("HYUNDAI_PALISADE_2023", "17ef028fec0ccf81/00000010--dba8455015"),
CustomRoute("HYUNDAI_PALISADE_2023", "6b8052042ba3ee05/00000199--3ed3fb5799"),
CustomRoute("KIA_EV6", "455a0ab75ce5c1e0/000000d1--098f32028c"),
CustomRoute("KIA_EV6", "6d2092783bf67457/0000008c--5caf525813"),
CustomRoute("KIA_EV6", "4961cb0f7bdd77a2/00000105--b636ed2f65"),
CustomRoute("KIA_K8_HEV_1ST_GEN", "78ad5150de133637|2023-09-13--16-15-57"),
CustomRoute("GENESIS_GV60_EV_1ST_GEN", "b1e441e63f1c99dd|0000009d--14cde5aeaf"),
CustomRoute("HYUNDAI_IONIQ_6", "faa815c21279fef7/00000187--ce36ae7c11"),
CustomRoute("HYUNDAI_IONIQ_6", "faa815c21279fef7/00000191--e5c3ffb55b"),
CustomRoute("HYUNDAI_IONIQ_6", "ce8a3764a8bb9141/000000f6--775693a6d6"),
CustomRoute("HYUNDAI_IONIQ_6", "ce8a3764a8bb9141/00000100--ba8bd692f5"),
CustomRoute("HYUNDAI_KONA_2ND_GEN", "32025f26789d8fab/00000022--a499e8ffa3"),
CustomRoute("HYUNDAI_KONA_EV_2ND_GEN", "1618132d68afc876/00000021--bf0f957649"),
CustomRoute("HYUNDAI_KONA_HEV_2ND_GEN", "97ca61196eb73e0d/00000052--4555329470"),
CustomRoute("HYUNDAI_SANTA_FE_HEV_5TH_GEN", "d54302f1d5e7a7cc|00000656--5dae9f54a7"),
CustomRoute("HYUNDAI_SONATA_2024", "4267ea8a353cdb36/00000262--8a427003c7"),
CustomRoute("KIA_CARNIVAL_HEV_4TH_GEN_2026", "7b8cc7bb46000e53/0000000b--2abacaff78"),
CustomRoute("KIA_EV6_2025", "48c27f77f9fd1a9b|00000199--193ee1ba20"),
CustomRoute("KIA_EV9", "ccfd4a1af758ee73/00000091--7fa49719a5"),
CustomRoute("KIA_K4_2025", "baf39eeaba1217ca/00000002--b36e3fa031"),
CustomRoute("KIA_K4_2025", "ac30936e794b297a/00000021--dde25fcfda/24"),
CustomRoute("KIA_K5_2025", "c4a804b067623789/0000007c--163f831540"),
CustomRoute("KIA_NIRO_EV_2ND_GEN", "80b8e9a6ad0acec3/0000032d--8379197bd3"),
CustomRoute("KIA_NIRO_EV_2ND_GEN", "80b8e9a6ad0acec3/0000032c--0055eeee96"),
CustomRoute("KIA_NIRO_EV_2ND_GEN", "cdde60a79a049bf4/00000002--f448ca40b4"),
CustomRoute("KIA_NIRO_HEV_2ND_GEN", "0d4257d1c6741384/00000067--42230e4b8d"),
CustomRoute("HYUNDAI_KONA_EV_2022", "e174e1a0b92263ed/00000003--d0591c14ec"),
CustomRoute("HYUNDAI_KONA_EV_2022", "e174e1a0b92263ed/00000001--18955a967e"),
CustomRoute("KIA_CEED_PHEV", "26064e18b24ae44c/00000000--4eb95fc137"),
CustomRoute("HYUNDAI_IONIQ", "ac27c9808ac91710/00000002--e0aab81e4d"),
CustomRoute("KIA_K7_2017", "74fbff45aa20fe9e/00000010--6f173d5799"),
CustomRoute("KIA_NIRO_EV", "b27d9eafeb61976e/00000233--03a9c0858c"),
CustomRoute("KIA_CARNIVAL_4TH_GEN", "a0cb448c2ffb9383/00000157--ecaf77a801"),
CustomRoute("KIA_CARNIVAL_4TH_GEN", "a0cb448c2ffb9383/00000158--f7e70e1435"),
CustomRoute("KIA_CARNIVAL_4TH_GEN", "a0cb448c2ffb9383/00000154--3471fc4ab3"),
CustomRoute("KIA_SORENTO_4TH_GEN", "bf42073ef09e0af2/00000017--3edc1f8259"),
CustomRoute("KIA_SORENTO_HEV_4TH_GEN", "833262b0c9e4016a/0000004a--0227a058e3"),
CustomRoute("HYUNDAI_PALISADE", "662bedbf8453b81e/00000124--7dc358f20c"),
CustomRoute("HYUNDAI_SONATA", "8f52823c702cb300/00000177--177d1aa6ff"),
CustomRoute("HYUNDAI_SONATA_HYBRID", "e3ae9e987a2a4e57/0000002b--30a6963e88"),
CustomRoute("HYUNDAI_ELANTRA_HEV_2021", "7bc0de9da607c543/00000031--4cb0d8aca5"),
CustomRoute("HYUNDAI_ELANTRA_HEV_2021", "7bc0de9da607c543/00000042--302b371266"),
CustomRoute("HYUNDAI_IONIQ_HEV_2022", "4a975fc1d9e71801/00000005--50d176008a"),
CustomRoute("HYUNDAI_IONIQ_9", "71e4e67d29034771/00000014--25fc6b216f"),
CustomRoute("HYUNDAI_IONIQ_9", "71e4e67d29034771/0000000e--d3b19ad6f6/10"),
CustomRoute("HYUNDAI_SANTA_CRUZ_2025", "6e7904b03a4aafc2/00000010--31034184b6"),
CustomRoute("HYUNDAI_TUCSON_4TH_GEN", "26da1db30eff4fcc/00000061--a60470e363"),
CustomRoute("HYUNDAI_TUCSON_4TH_GEN", "a6d25e95d936fdc4/000002ed--89d7944c52"),
CustomRoute("HYUNDAI_TUCSON_4TH_GEN", "6722665fbbf2a644/00000534--4ab7b733c5"),
CustomRoute("HYUNDAI_TUCSON_HEV_2025", "5868ec006e2bb61e/00000021--7d10df95e8"),
CustomRoute("KIA_SPORTAGE_5TH_GEN", "ce05e32158479f42/000003f4--9543087719"),
CustomRoute("KIA_SPORTAGE_HEV_2026", "343d5e350abaedcf/00000020--1c864750b6"),
]
+329
View File
@@ -0,0 +1,329 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from collections.abc import Iterable, Iterator
from pathlib import Path
import re
import sys
from urllib.parse import unquote
SUNNYPILOT_ROOT = Path(__file__).resolve().parents[4]
if (SUNNYPILOT_ROOT / "tools/lib/logreader.py").exists():
sys.path.insert(0, str(SUNNYPILOT_ROOT))
DEFAULT_ROUTES = """
faa815c21279fef7/00000187--ce36ae7c11
faa815c21279fef7/00000191--e5c3ffb55b
ce8a3764a8bb9141/000000f6--775693a6d6
ce8a3764a8bb9141/00000100--ba8bd692f5
32025f26789d8fab/00000022--a499e8ffa3
1618132d68afc876/00000021--bf0f957649
97ca61196eb73e0d/00000052--4555329470
d54302f1d5e7a7cc/00000656--5dae9f54a7
4267ea8a353cdb36/00000262--8a427003c7
7b8cc7bb46000e53/0000000b--2abacaff78
48c27f77f9fd1a9b/00000199--193ee1ba20
ccfd4a1af758ee73/00000091--7fa49719a5
baf39eeaba1217ca/00000002--b36e3fa031
ac30936e794b297a/00000021--dde25fcfda
c4a804b067623789/0000007c--163f831540
80b8e9a6ad0acec3/0000032d--8379197bd3
80b8e9a6ad0acec3/0000032c--0055eeee96
cdde60a79a049bf4/00000002--f448ca40b4
0d4257d1c6741384/00000067--42230e4b8d
343d5e350abaedcf/00000020--1c864750b6
71e4e67d29034771/00000014--25fc6b216f
71e4e67d29034771/0000000e--d3b19ad6f6
07a48901db7b2503/0000012d--61aba9f832
c5a5f79df9b6a084/0000005d--24c0a7a7ee
90950642f47cf05b/00000681--6a904aaa98
102161de13e822d1/0000000d--f74a52a624
17ef028fec0ccf81/00000010--dba8455015
6b8052042ba3ee05/00000199--3ed3fb5799
464ac801173f6dca/00000382--27ce9e4ade
455a0ab75ce5c1e0/000000d1--098f32028c
6d2092783bf67457/0000008c--5caf525813
4961cb0f7bdd77a2/00000105--b636ed2f65
f9522b6cd6e4e621/00000170--ac6979bdda
ed2717e2c1912f87/00000009--d550f4d5b6
78ad5150de133637/2023-09-13--16-15-57
6e7904b03a4aafc2/00000010--31034184b6
26da1db30eff4fcc/00000061--a60470e363
a6d25e95d936fdc4/000002ed--89d7944c52
6722665fbbf2a644/00000534--4ab7b733c5
477e0b6c352e8bba/0000000e--5e3a5c981c
5868ec006e2bb61e/00000021--7d10df95e8
ce05e32158479f42/000003f4--9543087719
ac27c9808ac91710/00000002--e0aab81e4d
74fbff45aa20fe9e/00000010--6f173d5799
b27d9eafeb61976e/00000233--03a9c0858c
f6324c8fb8b6f68d/00000058--5330471811
e174e1a0b92263ed/00000001--18955a967e
26064e18b24ae44c/00000000--4eb95fc137
4709fe68b0cc9c0a/00000125--ed2a02e7a8
4709fe68b0cc9c0a/0000012b--f29c054b05
ce7eada09318e376/0000000e--0cc3d1c6cc
662bedbf8453b81e/00000124--7dc358f20c
4a975fc1d9e71801/00000005--50d176008a
3e4f79d5bf692518/00000001--f53d01f8e3
3e4f79d5bf692518/00000002--b18171f9a9
810a7ca7cb31ed86/00000001--b6f9cdd134
224d1e774b6acc2e/0000001d--0ae7d5fa70
8f52823c702cb300/00000177--177d1aa6ff
e3ae9e987a2a4e57/0000002b--30a6963e88
7bc0de9da607c543/00000031--4cb0d8aca5
7bc0de9da607c543/00000042--302b371266
bf42073ef09e0af2/00000017--3edc1f8259
833262b0c9e4016a/0000004a--0227a058e3
3cce51ba4cc49950/0000003c--51ebc96f4c
3cce51ba4cc49950/0000003e--d78c337cc5
ad9840558640c31d/0000001a--d6cd4871c2
a468064f19bc0267/00000001--6a0c7d2514
a468064f19bc0267/00000012--1feb5188ec
a468064f19bc0267/00000015--27b5b89e1b
a468064f19bc0267/00000016--31baf70a9f
a468064f19bc0267/00000017--c63c64192b
518f8ad60a03f394/00000016--e0300496c8
"""
def import_logreader():
for mod_name in ("openpilot.tools.lib.logreader", "tools.lib.logreader"):
try:
mod = __import__(mod_name, fromlist=["LogReader"])
return mod.LogReader, mod.ReadMode
except ImportError:
pass
raise SystemExit(
"Could not import LogReader. Run this from an openpilot/comma tooling environment, "
+ "or install the package that provides openpilot.tools.lib.logreader."
)
def normalize_route(route: str) -> str:
return unquote(route.strip()).replace("|", "/")
def add_segment(route: str, segment: int | None) -> str:
if segment is None:
return route
parts = route.split("/")
if len(parts) == 2:
return f"{route}/{segment}"
return route
def parse_routes(text: str, segment: int | None) -> list[str]:
oneboxes = re.findall(r"onebox=([^) \t\n\r]+)", text)
routes = oneboxes if oneboxes else [line for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")]
deduped = dict.fromkeys(add_segment(normalize_route(route), segment) for route in routes)
return list(deduped)
def event_time_s(event, start_time_ns: int) -> float:
return (event.logMonoTime - start_time_ns) / 1e9
def can_messages(event) -> Iterable:
which = event.which()
if which == "can":
return event.can
if which == "sendcan":
return event.sendcan
return ()
def similar_count(count: int, reference: float, tolerance: float) -> bool:
if reference == 0:
return count == 0
return abs(count - reference) / reference <= tolerance
def consecutive_ranges(address_counts: Counter[int], min_len: int, count_tolerance: float) -> Iterator[tuple[int, int]]:
sorted_addresses = sorted(address_counts)
if not sorted_addresses:
return
start = prev = sorted_addresses[0]
run_counts = [address_counts[start]]
for addr in sorted_addresses[1:]:
reference_count = sum(run_counts) / len(run_counts)
if addr == prev + 1 and similar_count(address_counts[addr], reference_count, count_tolerance):
run_counts.append(address_counts[addr])
prev = addr
continue
if prev - start + 1 >= min_len:
yield start, prev
start = prev = addr
run_counts = [address_counts[addr]]
if prev - start + 1 >= min_len:
yield start, prev
def parse_buses(buses: str) -> set[int]:
return {int(bus.strip(), 0) for bus in buses.split(",") if bus.strip()}
def scan_route(LogReader, ReadMode, route: str, skip_s: float, duration_s: float | None,
include_sendcan: bool, buses: set[int]) -> tuple[dict[int, Counter[int]], float]:
counts_by_bus: dict[int, Counter[int]] = defaultdict(Counter)
start_time_ns = None
end_s = None if duration_s is None else skip_s + duration_s
last_scanned_t = skip_s
for event in LogReader(route, default_mode=ReadMode.RLOG):
if start_time_ns is None:
start_time_ns = event.logMonoTime
t = event_time_s(event, start_time_ns)
if t < skip_s:
continue
if end_s is not None and t > end_s:
break
last_scanned_t = t
if event.which() == "sendcan" and not include_sendcan:
continue
for msg in can_messages(event):
if msg.src not in buses:
continue
counts_by_bus[msg.src][msg.address] += 1
return counts_by_bus, max(last_scanned_t - skip_s, 0.0)
def range_freq(counts: Counter[int], start: int, end: int, duration_s: float) -> float:
if duration_s <= 0:
return 0.0
freqs = [counts[addr] / duration_s for addr in range(start, end + 1)]
return sum(freqs) / len(freqs)
def fmt_addr(addr: int) -> str:
return f"0x{addr:X}"
def sorted_range_counts(counts: Counter[tuple[int | None, int, int]]) -> list[tuple[tuple[int | None, int, int], int]]:
return sorted(counts.items(), key=lambda item: (-((item[0][2] - item[0][1]) + 1), -item[1], -1 if item[0][0] is None else item[0][0], item[0][1]))
def print_range(bus: int | None, start: int, end: int, count: int, avg_hz: float, example: str | None = None, bus_label: str | None = None) -> None:
bus_label = bus_label or ("all buses" if bus is None else f"bus {bus}")
example_text = "" if example is None else f" e.g. {example}"
print(f"{count:>4}x {bus_label:>8} {fmt_addr(start)}-{fmt_addr(end)} len={end - start + 1:<3} freq={avg_hz:>6.1f} Hz{example_text}", flush=True)
def main() -> None:
parser = argparse.ArgumentParser(description="Find consecutive CAN address ranges observed after a route warm-up period.")
parser.add_argument("input", nargs="?", help="Optional route, onebox URL, or file containing onebox URLs/routes. Defaults to the pasted side-quest routes.")
parser.add_argument("--segment", type=int, default=1, help="Segment to append to route identifiers that do not already include one. Defaults to 1.")
parser.add_argument("--all-segments", action="store_true", help="Do not append a segment; scan all segments selected by each identifier.")
parser.add_argument("--skip-s", type=float, default=60.0, help="Seconds to skip from the start of each loaded route/segment.")
parser.add_argument("--duration-s", type=float, default=None, help="Optional scan duration after --skip-s. Defaults to the rest of the log.")
parser.add_argument("--min-len", type=int, default=4, help="Minimum consecutive address range length.")
parser.add_argument("--count-tolerance", type=float, default=0.2, help="Maximum relative message-count difference within a range. Defaults to 0.2.")
parser.add_argument("--buses", default="0,1,2", help="Comma-separated CAN buses to scan. Defaults to 0,1,2.")
parser.add_argument("--include-sendcan", action="store_true", help="Include sendcan events in addition to received can events.")
parser.add_argument("--merge-buses", "--no-bus", action="store_true", help="Merge addresses from all CAN buses before finding ranges.")
parser.add_argument("--split-summary-buses", action="store_true", help="Keep aggregate summary counts separate per bus.")
args = parser.parse_args()
if args.input:
input_path = Path(args.input)
text = input_path.read_text() if input_path.exists() else args.input
else:
text = DEFAULT_ROUTES
routes = parse_routes(text, None if args.all_segments else args.segment)
LogReader, ReadMode = import_logreader()
buses = parse_buses(args.buses)
counts: Counter[tuple[int | None, int, int]] = Counter()
freq_sums: Counter[tuple[int | None, int, int]] = Counter()
examples: dict[tuple[int | None, int, int], str] = {}
failed: list[tuple[str, str]] = []
for idx, route in enumerate(routes, 1):
print(f"[{idx:>3}/{len(routes)}] scanning {route}", file=sys.stderr, flush=True)
try:
counts_by_bus, scanned_duration_s = scan_route(LogReader, ReadMode, route, args.skip_s, args.duration_s, args.include_sendcan, buses)
except Exception as e:
failed.append((route, f"{type(e).__name__}: {e}"))
continue
if args.merge_buses:
merged = Counter()
for address_counts in counts_by_bus.values():
merged.update(address_counts)
range_sources = {None: merged}
else:
range_sources = counts_by_bus
route_ranges = set()
route_freqs = {}
for bus, address_counts in range_sources.items():
for start, end in consecutive_ranges(address_counts, args.min_len, args.count_tolerance):
route_ranges.add((bus, start, end))
route_freqs[(bus, start, end)] = range_freq(address_counts, start, end, scanned_duration_s)
per_route_counts: Counter[tuple[int | None, int, int]] = Counter(route_ranges)
print(f"\n{route}", flush=True)
for (bus, start, end), route_count in sorted_range_counts(per_route_counts):
print_range(bus, start, end, route_count, route_freqs[(bus, start, end)])
for range_key in route_ranges:
counts[range_key] += 1
freq_sums[range_key] += route_freqs[range_key]
examples.setdefault(range_key, route)
print(f"\nScanned routes: {len(routes) - len(failed)}/{len(routes)}", flush=True)
print(f"Minimum range length: {args.min_len}", flush=True)
print(f"Count tolerance: {args.count_tolerance:g}", flush=True)
print(f"Skipped first: {args.skip_s:g}s", flush=True)
print(f"Buses: {','.join(str(bus) for bus in sorted(buses))}", flush=True)
if args.duration_s is not None:
print(f"Scan duration: {args.duration_s:g}s", flush=True)
print(flush=True)
if args.split_summary_buses:
for (bus, start, end), count in sorted_range_counts(counts):
avg_hz = freq_sums[(bus, start, end)] / count
print_range(bus, start, end, count, avg_hz, examples[(bus, start, end)])
else:
combined_counts: Counter[tuple[int, int]] = Counter()
combined_freq_sums: Counter[tuple[int, int]] = Counter()
combined_examples: dict[tuple[int, int], str] = {}
combined_buses: dict[tuple[int, int], set[int]] = defaultdict(set)
for (bus, start, end), count in counts.items():
range_key = (start, end)
combined_counts[range_key] += count
combined_freq_sums[range_key] += freq_sums[(bus, start, end)]
combined_examples.setdefault(range_key, examples[(bus, start, end)])
if bus is not None:
combined_buses[range_key].add(bus)
sorted_combined = sorted(combined_counts.items(), key=lambda item: (-((item[0][1] - item[0][0]) + 1), -item[1], item[0][0]))
for (start, end), count in sorted_combined:
avg_hz = combined_freq_sums[(start, end)] / count
buses_label = "buses " + ",".join(str(bus) for bus in sorted(combined_buses[(start, end)]))
print_range(None, start, end, count, avg_hz, combined_examples[(start, end)], bus_label=buses_label)
if failed:
print("\nFailed routes:", file=sys.stderr)
for route, error in failed:
print(f" {route}: {error}", file=sys.stderr)
if __name__ == "__main__":
main()
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
import math
import os
import tempfile
from dataclasses import dataclass
from opendbc.can.parser import CANParser
from opendbc.dbc.generator.hyundai.hyundai_radar_3a5_3c4 import RADAR_3A5_3C4_MESSAGE_COMMENT, RADAR_3A5_3C4_SIGNAL_COMMENTS
RADAR_500_51F_DBC_TEMPLATE = """
BO_ {addr_dec} RADAR_TRACK_{addr_hex}: 8 RADAR
SG_ UNKNOWN_1 : 7|8@0- (1,0) [-128|127] "" XXX
SG_ AZIMUTH : 12|10@0- (0.2,0) [-102.4|102.2] "" XXX
SG_ STATE : 15|3@0+ (1,0) [0|7] "" XXX
SG_ LONG_DIST : 18|11@0+ (0.1,0) [0|204.7] "" XXX
SG_ REL_ACCEL : 33|10@0- (0.02,0) [-10.24|10.22] "" XXX
SG_ ZEROS : 37|4@0+ (1,0) [0|255] "" XXX
SG_ COUNTER : 38|1@0+ (1,0) [0|1] "" XXX
SG_ STATE_3 : 39|1@0+ (1,0) [0|1] "" XXX
SG_ REL_SPEED : 53|14@0- (0.01,0) [-81.92|81.92] "" XXX
SG_ STATE_2 : 55|2@0+ (1,0) [0|3] "" XXX
"""
RADAR_3A5_3C4_DBC_TEMPLATE = """
BO_ {addr_dec} RADAR_TRACK_{addr_hex}: 24 RADAR
SG_ CHECKSUM : 0|16@1+ (1,0) [0|65535] "" XXX
SG_ COUNTER : 16|8@1+ (1,0) [0|255] "" XXX
SG_ STATE_ALT : 25|2@0+ (1,0) [0|3] "" XXX
SG_ MOTION_STATE : 28|2@0+ (1,0) [0|2] "" XXX
SG_ TRACK_COUNTER : 31|2@0+ (1,0) [0|3] "" XXX
SG_ TRACK_QUALITY : 38|7@0+ (1,0) [0|127] "" XXX
SG_ AGE : 47|8@0+ (1,0) [0|255] "" XXX
SG_ COAST_AGE : 51|4@0+ (1,0) [0|15] "" XXX
SG_ STATE : 54|3@0+ (1,0) [0|7] "" XXX
SG_ RCS : 62|7@0- (1,0) [-64|63] "" XXX
SG_ LONG_DIST : 63|13@1+ (0.05,0) [0|409.55] "m" XXX
SG_ LAT_DIST : 76|12@1- (0.05,0) [-102.4|102.35] "m" XXX
SG_ REL_SPEED : 88|14@1- (0.01,0) [-81.92|81.91] "m/s" XXX
SG_ NEW_SIGNAL_4 : 103|2@0+ (1,0) [0|2] "" XXX
SG_ REL_LAT_SPEED : 104|13@1- (0.01,0) [-40.96|40.95] "m/s" XXX
SG_ REL_ACCEL : 118|10@1- (0.02,0) [-10.24|10.22] "m/s^2" XXX
SG_ NEW_SIGNAL_18 : 129|2@0+ (1,0) [0|2] "" XXX
SG_ NEW_SIGNAL_5 : 135|6@0+ (1,0) [0|32] "" XXX
SG_ WIDTH : 138|5@1+ (0.1,0) [0|3.1] "m" XXX
SG_ LENGTH : 151|8@0+ (0.1,0) [0|25.5] "m" XXX
SG_ ABS_SPEED : 152|10@1+ (0.1,0) [0|102.3] "m/s" XXX
SG_ ORIENTATION_ANGLE : 162|9@1- (1,0) [-180|180] "deg" XXX
SG_ NEW_SIGNAL_13 : 175|4@0+ (1,0) [0|10] "" XXX
SG_ NEW_SIGNAL_12 : 179|4@0+ (1,0) [0|10] "" XXX
SG_ NEW_SIGNAL_14 : 181|2@0+ (1,0) [0|3] "" XXX
SG_ NEW_SIGNAL_15 : 183|2@0+ (1,0) [0|2] "" XXX
SG_ NEW_SIGNAL_16 : 185|2@0+ (1,0) [0|3] "" XXX
SG_ NEW_SIGNAL_17 : 187|2@0+ (1,0) [0|2] "" XXX
VAL_ {addr_dec} STATE_ALT 0 "EMPTY" 1 "TENTATIVE" 2 "MEASURED" 3 "COASTED" ;
VAL_ {addr_dec} MOTION_STATE 0 "UNKNOWN" 1 "STATIONARY" 2 "MOVING" ;
VAL_ {addr_dec} STATE 0 "EMPTY" 1 "TENTATIVE_1" 2 "TENTATIVE_2" 3 "MEASURED" 4 "COASTED" 7 "UNRESOLVED_TENTATIVE" ;
"""
RADAR_3A5_3C4_DBC_TEMPLATE += "\n".join((
'CM_ BO_ {addr_dec} "' + RADAR_3A5_3C4_MESSAGE_COMMENT + '";',
*(f'CM_ SG_ {{addr_dec}} {signal} "{comment}";' for signal, comment in RADAR_3A5_3C4_SIGNAL_COMMENTS),
)) + "\n"
RADAR_210_21F_DBC_TEMPLATE = """
BO_ {addr_dec} RADAR_TRACK_{addr_hex}: 32 RADAR
SG_ CHECKSUM : 0|16@1+ (1,0) [0|65535] "" XXX
SG_ COUNTER : 16|8@1+ (1,0) [0|255] "" XXX
SG_ 1_AGE : 47|8@0+ (1,0) [0|255] "" XXX
SG_ 1_STATE_ALT : 51|4@0+ (1,0) [0|15] "" XXX
SG_ 1_STATE : 55|4@0+ (1,0) [0|15] "" XXX
SG_ 1_NEW_SIGNAL_3 : 63|8@0- (1,0) [0|255] "" XXX
SG_ 1_LONG_DIST : 64|12@1+ (0.05,0) [0|4095] "" XXX
SG_ 1_LAT_DIST : 76|12@1- (0.05,0) [0|4095] "" XXX
SG_ 1_REL_SPEED : 88|14@1- (0.01,0) [0|16383] "" XXX
SG_ 1_NEW_SIGNAL_1 : 102|2@1+ (1,0) [0|3] "" XXX
SG_ 1_LAT_ACCEL : 104|13@1- (1,0) [0|8191] "" XXX
SG_ 1_REL_ACCEL : 118|10@1- (1,0) [0|1023] "" XXX
SG_ 2_AGE : 175|8@0+ (1,0) [0|255] "" XXX
SG_ 2_STATE_ALT : 179|4@0+ (1,0) [0|15] "" XXX
SG_ 2_STATE : 183|4@0+ (1,0) [0|15] "" XXX
SG_ 2_NEW_SIGNAL_3 : 191|8@0- (1,0) [0|255] "" XXX
SG_ 2_LONG_DIST : 192|12@1+ (0.05,0) [0|4095] "" XXX
SG_ 2_LAT_DIST : 204|12@1- (0.05,0) [0|4095] "" XXX
SG_ 2_REL_SPEED : 216|14@1- (0.01,0) [0|65535] "" XXX
SG_ 2_NEW_SIGNAL_1 : 230|2@1+ (1,0) [0|3] "" XXX
SG_ 2_LAT_ACCEL : 232|13@1- (1,0) [0|8191] "" XXX
SG_ 2_REL_ACCEL : 246|10@1- (1,0) [0|1023] "" XXX
"""
RADAR_602_611_DBC_TEMPLATE = """
BO_ {addr_dec} RADAR_TRACK_{addr_hex}: 8 RADAR
SG_ 1_DISTANCE : 0|10@1+ (0.25,0) [0|255.75] "" XXX
SG_ 1_LATERAL : 10|11@1+ (0.03,-30.705) [-30.705|30.705] "" XXX
SG_ 1_SPEED : 21|10@1+ (0.25,-128) [-128|127.75] "" XXX
SG_ 2_DISTANCE : 31|10@1+ (0.25,0) [0|255.75] "" XXX
SG_ 2_LATERAL : 41|11@1+ (0.03,-30.705) [-30.705|30.705] "" XXX
SG_ 2_SPEED : 52|8@1- (0.25,0) [-32|31.75] "" XXX
SG_ UNKNOWN_2 : 60|2@1+ (1,0) [0|3] "" XXX
SG_ COUNTER : 62|2@1+ (1,0) [0|3] "" XXX
"""
@dataclass(frozen=True)
class RadarSpec:
name: str
start_addr: int
msg_count: int
dbc_template: str
track_prefixes: tuple[str, ...]
frequency: int
@property
def end_addr(self) -> int:
return self.start_addr + self.msg_count - 1
def contains(self, address: int) -> bool:
return self.start_addr <= address <= self.end_addr
RADAR_SPECS = (
RadarSpec("RADAR_500_51F", 0x500, 32, RADAR_500_51F_DBC_TEMPLATE, ("",), frequency=20),
RadarSpec("RADAR_210_21F", 0x210, 16, RADAR_210_21F_DBC_TEMPLATE, ("1_", "2_"), frequency=20),
RadarSpec("RADAR_3A5_3C4", 0x3A5, 32, RADAR_3A5_3C4_DBC_TEMPLATE, ("",), frequency=20),
RadarSpec("RADAR_602_611", 0x602, 16, RADAR_602_611_DBC_TEMPLATE, ("1_", "2_"), frequency=10),
)
def build_seen_address_map() -> dict[str, set[int]]:
return {radar_spec.name: set() for radar_spec in RADAR_SPECS}
def get_radar_spec(address: int) -> RadarSpec | None:
for radar_spec in RADAR_SPECS:
if radar_spec.contains(address):
return radar_spec
return None
def is_exclusive_full_range_match(radar_spec: RadarSpec, seen_addresses: dict[str, set[int]]) -> bool:
expected_addresses = set(range(radar_spec.start_addr, radar_spec.end_addr + 1))
if seen_addresses[radar_spec.name] != expected_addresses:
return False
for other_spec in RADAR_SPECS:
if other_spec.name == radar_spec.name:
continue
other_expected_addresses = set(range(other_spec.start_addr, other_spec.end_addr + 1))
if seen_addresses[other_spec.name] == other_expected_addresses:
return False
return True
def get_radar_dbc_path(radar_spec: RadarSpec) -> str:
dbc_path = os.path.join(tempfile.gettempdir(), f"{radar_spec.name.lower()}_radar_ui.dbc")
dbc_content = "\n".join(
radar_spec.dbc_template.format(addr_dec=addr, addr_hex=f"{addr:x}")
for addr in range(radar_spec.start_addr, radar_spec.end_addr + 1)
)
if not os.path.exists(dbc_path) or open(dbc_path).read() != dbc_content:
with open(dbc_path, "w") as f:
f.write(dbc_content)
return dbc_path
def get_radar_can_parser(radar_spec: RadarSpec, bus: int) -> CANParser:
messages = [(f"RADAR_TRACK_{addr:x}", radar_spec.frequency) for addr in range(radar_spec.start_addr, radar_spec.end_addr + 1)]
return CANParser(get_radar_dbc_path(radar_spec), messages, bus)
def get_track_storage_key(radar_spec: RadarSpec, bus: int, addr: int, track_prefix: str) -> tuple[str, int, int]:
if radar_spec.name in ("RADAR_500_51F", "RADAR_3A5_3C4"):
return (radar_spec.name, bus, addr)
track_index = int(track_prefix[0]) - 1
return (radar_spec.name, bus, addr * 2 + track_index)
def get_track_ts_nanos(parser: CANParser, msg_name: str, radar_spec: RadarSpec, track_prefix: str) -> int:
if radar_spec.name == "RADAR_602_611":
return parser.ts_nanos[msg_name][f"{track_prefix}DISTANCE"]
if radar_spec.name == "RADAR_210_21F":
return parser.ts_nanos[msg_name][f"{track_prefix}LONG_DIST"]
return parser.ts_nanos[msg_name]["LONG_DIST"]
def decode_radar_track(radar_spec: RadarSpec, track_msg, track_prefix: str) -> tuple[float, float, float, float]:
if radar_spec.name == "RADAR_602_611":
return (
track_msg[f"{track_prefix}DISTANCE"],
track_msg[f"{track_prefix}LATERAL"],
track_msg[f"{track_prefix}SPEED"],
float("nan"),
)
if radar_spec.name == "RADAR_210_21F":
return (
track_msg[f"{track_prefix}LONG_DIST"],
track_msg[f"{track_prefix}LAT_DIST"],
track_msg[f"{track_prefix}REL_SPEED"],
float("nan"),
)
if radar_spec.name == "RADAR_500_51F":
azimuth = math.radians(track_msg["AZIMUTH"])
long_dist = track_msg["LONG_DIST"]
return (
math.cos(azimuth) * long_dist,
0.5 * -math.sin(azimuth) * long_dist,
track_msg["REL_SPEED"],
track_msg["REL_ACCEL"],
)
return (
track_msg["LONG_DIST"],
track_msg["LAT_DIST"],
track_msg["REL_SPEED"],
track_msg["REL_ACCEL"],
)
def is_radar_track_valid(radar_spec: RadarSpec, track_msg, track_prefix: str) -> bool:
if radar_spec.name == "RADAR_602_611":
return 0 < track_msg[f"{track_prefix}DISTANCE"] < 255.75
if radar_spec.name == "RADAR_210_21F":
return track_msg[f"{track_prefix}STATE"] in (3, 4)
return track_msg["STATE"] in (3, 4)
+912
View File
@@ -0,0 +1,912 @@
#!/usr/bin/env python3
import argparse
import os
import signal
import subprocess
import sys
import time
from dataclasses import dataclass
import cv2
import numpy as np
import pyray as rl
import cereal.messaging as messaging
from opendbc.car.tests.routes import routes
from openpilot.common.basedir import BASEDIR
from openpilot.common.transformations.camera import DEVICE_CAMERAS
from openpilot.tools.radar.custom_routes import CUSTOM_ROUTES
from openpilot.tools.replay.lib.ui_helpers import (
UP,
BLACK,
GREEN,
Calibration,
get_blank_lid_overlay,
init_plots,
plot_lead,
plot_model,
to_topdown_pt,
)
from openpilot.tools.radar.radar_helpers import (
RADAR_SPECS,
build_seen_address_map,
decode_radar_track,
get_radar_can_parser,
get_radar_spec,
get_track_storage_key,
get_track_ts_nanos,
is_exclusive_full_range_match,
is_radar_track_valid,
)
from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA
from msgq.visionipc import VisionIpcClient, VisionStreamType
os.environ['BASEDIR'] = BASEDIR
ANGLE_SCALE = 5.0
RADAR_TRACK_TIMEOUT_FRAMES = 10
RADAR_FORMAT_SWITCH_MISS_FRAMES = 30
RADAR_TRACK_RADIUS = 4
CAMERA_RADAR_Y_OFFSET = 25
RADAR_HEATMAP_DECAY = 0.975
RADAR_HEATMAP_ALPHA = 0.65
CAMERA_RADAR_HEATMAP_ALPHA = 0.45
REPLAY_PATH = os.path.join(os.path.dirname(__file__), "..", "replay", "replay")
REPLAY_SOCKET_WAIT_TIMEOUT_SECONDS = 10.0
REPLAY_SPEEDS = (0.2, 0.5, 1.0, 2.0, 4.0, 8.0)
CAMERA_DRAW_WIDTH = 640
CAMERA_DRAW_HEIGHT = 480
TOP_DOWN_DRAW_WIDTH = 384
PLOT_DRAW_WIDTH = 480
PLOT_DRAW_HEIGHT = 480
RADAR_HEATMAP_MODES = ("OFF", "TOP", "CAMERA", "BOTH")
CYAN = (90, 235, 255)
AMBER = (255, 210, 90)
SOFT_WHITE = (235, 235, 235)
SLATE = (140, 180, 210)
@dataclass
class RadarTrackPoint:
trackId: int
measured: bool = True
dRel: float = 0.0
yRel: float = 0.0
vRel: float = 0.0
aRel: float = 0.0
yvRel: float = float("nan")
def draw_radar_points(tracks, lid_overlay):
for track in tracks:
px, py = to_topdown_pt(track.dRel, -track.yRel)
if px != -1:
cv2.circle(lid_overlay, (py, px), RADAR_TRACK_RADIUS, 255, thickness=-1, lineType=cv2.LINE_AA)
def update_radar_heatmap(tracks, radar_heatmap):
radar_heatmap *= RADAR_HEATMAP_DECAY
for track in tracks:
px, py = to_topdown_pt(track.dRel, -track.yRel)
if px != -1:
cv2.circle(radar_heatmap, (py, px), RADAR_TRACK_RADIUS + 2, 255.0, thickness=-1, lineType=cv2.LINE_AA)
def update_radar_camera_heatmap(tracks, radar_heatmap, calibration, shape):
radar_heatmap *= RADAR_HEATMAP_DECAY
if calibration is None:
return
height, width = shape[:2]
for track in tracks:
if track.dRel <= 0.0:
continue
pt = calibration.car_space_to_bb(
np.asarray([track.dRel - RADAR_TO_CAMERA]),
np.asarray([-track.yRel]),
np.asarray([1.0]),
)
x, y = np.round(pt[0]).astype(int)
y += CAMERA_RADAR_Y_OFFSET
if 0 <= x < width and 0 <= y < height:
cv2.circle(radar_heatmap, (x, y), RADAR_TRACK_RADIUS + 3, 255.0, thickness=-1, lineType=cv2.LINE_AA)
def overlay_heatmap(img, radar_heatmap, alpha_scale):
radar_heat_uint8 = np.ascontiguousarray(np.clip(radar_heatmap, 0, 255).astype(np.uint8))
radar_heat_mask = radar_heat_uint8 > 0
if not np.any(radar_heat_mask):
return
heat_rgb = cv2.cvtColor(cv2.applyColorMap(radar_heat_uint8, cv2.COLORMAP_TURBO), cv2.COLOR_BGR2RGB).astype(np.float32)
img_rgb = img.astype(np.float32)
alpha = ((radar_heat_uint8.astype(np.float32) / 255.0) * alpha_scale)[..., None]
img[:] = np.where(
radar_heat_mask[..., None],
np.clip(img_rgb * (1.0 - alpha) + heat_rgb * alpha, 0, 255).astype(np.uint8),
img,
)
def draw_radar_points_camera(tracks, img, calibration):
if calibration is None:
return
for track in tracks:
if track.dRel <= 0.0:
continue
# Match the road-space projection convention used by other UI overlays.
pt = calibration.car_space_to_bb(
np.asarray([track.dRel - RADAR_TO_CAMERA]),
np.asarray([-track.yRel]),
np.asarray([1.0]),
)
x, y = np.round(pt[0]).astype(int)
y += CAMERA_RADAR_Y_OFFSET
if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
cv2.circle(img, (x, y), RADAR_TRACK_RADIUS, (255, 255, 255), thickness=-1, lineType=cv2.LINE_AA)
def draw_loading_overlay(font, lines, camera_texture, top_down_texture, hor_mode, panel_x, panel_y):
rl.draw_texture_pro(
camera_texture,
rl.Rectangle(0, 0, camera_texture.width, camera_texture.height),
rl.Rectangle(0, 0, CAMERA_DRAW_WIDTH, CAMERA_DRAW_HEIGHT),
rl.Vector2(0, 0),
0.0,
rl.WHITE,
)
rl.draw_texture(top_down_texture, CAMERA_DRAW_WIDTH, 0, rl.WHITE) # noqa: TID251
if hor_mode:
panel_width = 620
panel_height = 300
else:
panel_width = 700
panel_height = 320
rl.draw_rectangle(panel_x - 20, panel_y - 30, panel_width, panel_height, rl.Color(0, 0, 0, 140))
rl.draw_rectangle_lines(panel_x - 20, panel_y - 30, panel_width, panel_height, rl.Color(255, 255, 255, 90))
for i, line in enumerate(lines):
if line:
rl.draw_text_ex(font, line, rl.Vector2(panel_x, panel_y + i * 40), 28 if i == 0 else 20, 0, rl.WHITE)
def start_replay(route: str, prefix: str, playback: str, data_dir: str | None, start_seconds: int) -> subprocess.Popen:
cmd = [
REPLAY_PATH,
"--playback", playback,
"--prefix", prefix,
]
if start_seconds > 0:
cmd.extend(["--start", str(start_seconds)])
if data_dir:
cmd.extend(["--data_dir", data_dir])
cmd.append(route)
env = os.environ.copy()
env["OPENPILOT_PREFIX"] = prefix
return subprocess.Popen(
cmd,
cwd=os.path.dirname(REPLAY_PATH),
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setsid if os.name != "nt" else None,
)
def stop_replay(proc: subprocess.Popen | None) -> None:
if proc is not None and proc.poll() is None:
if os.name != "nt":
try:
os.killpg(proc.pid, signal.SIGTERM)
except ProcessLookupError:
pass
else:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
if os.name != "nt":
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
else:
proc.kill()
proc.wait(timeout=5)
# `replay` can leave helper processes like `replayd` behind, so do one
# targeted cleanup pass on shutdown as well.
for pattern in ("/tools/replay/replay", "replayd"):
try:
subprocess.run(
["pkill", "-f", pattern],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except FileNotFoundError:
pass
def wait_for_can_socket(prefix: str, timeout: float) -> None:
socket_path = os.path.join("/tmp", f"msgq_{prefix}", "can")
started = time.monotonic()
while not os.path.exists(socket_path):
if time.monotonic() - started > timeout:
raise TimeoutError(f"Timed out waiting for CAN socket at {socket_path}")
time.sleep(0.1)
def get_hkg_routes() -> list[tuple[str, str]]:
hkg_prefixes = ("HYUNDAI_", "KIA_", "GENESIS_")
return [
(route.route, getattr(route.car_model, "name", str(route.car_model)))
for route in routes
if route.car_model is not None and getattr(route.car_model, "name", str(route.car_model)).startswith(hkg_prefixes)
]
def get_custom_routes() -> list[tuple[str, str]]:
return [(route.route, route.car_model) for route in CUSTOM_ROUTES]
def make_submaster(addr):
return messaging.SubMaster(
[
'carState',
'longitudinalPlan',
'carControl',
'radarState',
'liveCalibration',
'controlsState',
'selfdriveState',
'liveTracks',
'modelV2',
'liveParameters',
'roadCameraState',
],
addr=addr,
)
def reset_radar_state():
return (
0,
None,
0,
{radar_spec.name: 0 for radar_spec in RADAR_SPECS},
build_seen_address_map(),
{},
0,
{},
{},
{},
)
def ui_thread(addr, route_entries=None, playback="1.0", data_dir=None, prefix="ui-replay", start_route_idx=0):
cv2.setNumThreads(1)
# Get monitor info before creating window
rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT)
rl.init_window(1, 1, "")
max_height = rl.get_monitor_height(0)
rl.close_window()
hor_mode = os.getenv("HORIZONTAL") is not None
hor_mode = True if max_height < 960 + 300 else hor_mode
if hor_mode:
size = (CAMERA_DRAW_WIDTH + TOP_DOWN_DRAW_WIDTH + PLOT_DRAW_WIDTH, 960)
write_x = 5
write_y = 480
else:
size = (CAMERA_DRAW_WIDTH + TOP_DOWN_DRAW_WIDTH, 960 + 300)
write_x = CAMERA_DRAW_WIDTH + 5
write_y = 970
rl.set_trace_log_level(rl.TraceLogLevel.LOG_ERROR)
rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT)
rl.init_window(size[0], size[1], "openpilot debug UI")
rl.set_target_fps(60)
# Load font
font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts/JetBrainsMono-Medium.ttf")
font = rl.load_font_ex(font_path, 32, None, 0)
# Create textures for camera and top-down view
camera_image = rl.gen_image_color(640, 480, rl.BLACK)
camera_texture = rl.load_texture_from_image(camera_image)
rl.unload_image(camera_image)
# lid_overlay array is (lidar_x, lidar_y) = (384, 960)
# pygame treats first axis as width, so texture is 384 wide x 960 tall
# For raylib, we need to transpose to get (height, width) = (960, 384) for the RGBA array
top_down_image = rl.gen_image_color(UP.lidar_x, UP.lidar_y, rl.BLACK)
top_down_texture = rl.load_texture_from_image(top_down_image)
rl.unload_image(top_down_image)
current_route_idx = start_route_idx
current_route_name = None
current_route_model = None
replay_proc = None
current_start_seconds = 0
paused = False
state_checks_enabled = False
radar_heatmap_mode_idx = 0
current_playback = min(REPLAY_SPEEDS, key=lambda speed: abs(speed - float(playback)))
last_replay_started_at = time.monotonic()
playback_ready = False
loading_status = "Initializing UI"
def current_offset_seconds() -> int:
if paused or not playback_ready or replay_proc is None or replay_proc.poll() is not None:
return current_start_seconds
return max(0, int(current_start_seconds + (time.monotonic() - last_replay_started_at) * current_playback))
def connect_streams():
nonlocal replay_proc, current_route_name, current_route_model, current_route_idx, current_start_seconds, loading_status, paused, \
last_replay_started_at, current_playback, playback_ready
if route_entries:
current_route_name, current_route_model = route_entries[current_route_idx]
loading_status = f"Starting replay for route {current_route_idx + 1}/{len(route_entries)} at {current_start_seconds}s ({current_playback:.1f}x)"
stop_replay(replay_proc)
os.environ["OPENPILOT_PREFIX"] = prefix
messaging.reset_context()
replay_proc = start_replay(current_route_name, prefix, f"{current_playback:.1f}", data_dir, current_start_seconds)
paused = False
playback_ready = False
loading_status = "Waiting for CAN socket"
wait_for_can_socket(prefix, REPLAY_SOCKET_WAIT_TIMEOUT_SECONDS)
loading_status = "Connecting to messaging streams"
sm_local = make_submaster(addr)
logcan_local = messaging.sub_sock("can", addr=addr, conflate=False, timeout=100)
loading_status = "Waiting for road camera frames"
return sm_local, logcan_local
sm, logcan = connect_streams()
img = np.zeros((480, 640, 3), dtype='uint8')
imgff = None
num_px = 0
calibration = None
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
lid_overlay_blank = get_blank_lid_overlay(UP)
radar_heatmap = np.zeros_like(lid_overlay_blank, dtype=np.float32)
camera_radar_heatmap = np.zeros(img.shape[:2], dtype=np.float32)
# plots
name_to_arr_idx = {
"gas": 0,
"computer_gas": 1,
"user_brake": 2,
"computer_brake": 3,
"v_ego": 4,
"v_pid": 5,
"angle_steers_des": 6,
"angle_steers": 7,
"angle_steers_k": 8,
"steer_torque": 9,
"v_override": 10,
"v_cruise": 11,
"a_ego": 12,
"a_target": 13,
}
plot_arr = np.zeros((100, len(name_to_arr_idx.values())))
plot_xlims = [(0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0])]
plot_ylims = [(-0.1, 1.1), (-ANGLE_SCALE, ANGLE_SCALE), (0.0, 75.0), (-3.0, 2.0)]
plot_names = [
["gas", "computer_gas", "user_brake", "computer_brake"],
["angle_steers", "angle_steers_des", "angle_steers_k", "steer_torque"],
["v_ego", "v_override", "v_pid", "v_cruise"],
["a_ego", "a_target"],
]
plot_colors = [["b", "b", "g", "r", "y"], ["b", "g", "y", "r"], ["b", "g", "r", "y"], ["b", "r"]]
plot_styles = [["-", "-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-"]]
draw_plots = init_plots(plot_arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles)
# Palette for converting lid_overlay grayscale indices to RGBA colors
palette = np.zeros((256, 4), dtype=np.uint8)
palette[:, 3] = 255 # alpha
palette[1] = [255, 0, 0, 255] # RED
palette[2] = [0, 255, 0, 255] # GREEN
palette[3] = [0, 0, 255, 255] # BLUE
palette[4] = [255, 255, 0, 255] # YELLOW
palette[110] = [110, 110, 110, 255] # car_color (gray)
palette[255] = [255, 255, 255, 255] # WHITE
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
while not rl.window_should_close():
# ***** frame *****
if not vipc_client.is_connected():
vipc_client.connect(False)
rl.begin_drawing()
rl.clear_background(rl.Color(64, 64, 64, 255))
if rl.is_key_released(rl.KeyboardKey.KEY_Q):
rl.end_drawing()
stop_replay(replay_proc)
replay_proc = None
break
shift_down = rl.is_key_down(rl.KeyboardKey.KEY_LEFT_SHIFT) or rl.is_key_down(rl.KeyboardKey.KEY_RIGHT_SHIFT)
if route_entries and rl.is_key_released(rl.KeyboardKey.KEY_SPACE):
if paused:
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
else:
current_start_seconds = current_offset_seconds()
paused = True
loading_status = "Paused"
stop_replay(replay_proc)
replay_proc = None
if route_entries and rl.is_key_released(rl.KeyboardKey.KEY_RIGHT):
current_route_idx = (current_route_idx + 1) % len(route_entries)
current_start_seconds = 0
paused = False
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if route_entries and rl.is_key_released(rl.KeyboardKey.KEY_LEFT):
current_route_idx = (current_route_idx - 1) % len(route_entries)
current_start_seconds = 0
paused = False
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if route_entries and rl.is_key_released(rl.KeyboardKey.KEY_M):
current_start_seconds = max(0, current_offset_seconds() + (-60 if shift_down else 60))
paused = False
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if route_entries and rl.is_key_released(rl.KeyboardKey.KEY_S):
current_start_seconds = max(0, current_offset_seconds() + (-10 if shift_down else 10))
paused = False
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if route_entries and (rl.is_key_released(rl.KeyboardKey.KEY_EQUAL) or rl.is_key_released(rl.KeyboardKey.KEY_KP_ADD)):
for speed in REPLAY_SPEEDS:
if speed > current_playback:
current_playback = speed
break
if not paused:
current_start_seconds = current_offset_seconds()
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if route_entries and (rl.is_key_released(rl.KeyboardKey.KEY_MINUS) or rl.is_key_released(rl.KeyboardKey.KEY_KP_SUBTRACT)):
for speed in reversed(REPLAY_SPEEDS):
if speed < current_playback:
current_playback = speed
break
if not paused:
current_start_seconds = current_offset_seconds()
(can_range_msg_count,
active_radar_format_name,
active_radar_format_miss_count,
radar_format_total_counts,
radar_format_seen_addresses,
radar_track_ids,
next_radar_track_id,
radar_tracks,
radar_track_last_seen,
radar_parsers) = reset_radar_state()
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
sm, logcan = connect_streams()
vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True)
if rl.is_key_released(rl.KeyboardKey.KEY_C):
state_checks_enabled = not state_checks_enabled
if rl.is_key_released(rl.KeyboardKey.KEY_H):
radar_heatmap_mode_idx = (radar_heatmap_mode_idx + 1) % len(RADAR_HEATMAP_MODES)
if RADAR_HEATMAP_MODES[radar_heatmap_mode_idx] == "OFF":
radar_heatmap.fill(0)
camera_radar_heatmap.fill(0)
yuv_img_raw = vipc_client.recv()
if yuv_img_raw is None or not yuv_img_raw.data.any():
if replay_proc is not None and replay_proc.poll() is not None:
loading_status = f"Replay exited with code {replay_proc.poll()}"
loading_lines = [
f"{loading_status}{' (paused)' if paused else ''}",
f"Route {current_route_idx + 1}/{len(route_entries)}" if route_entries else "Connected to external replay",
f"Platform: {current_route_model}" if current_route_model is not None else "",
f"Route: {current_route_name}" if current_route_name is not None else "",
f"Offset: {current_offset_seconds()}s" if route_entries else "",
f"Playback: {current_playback:.1f}x" if route_entries else "",
f"Radar state checks: {'ON' if state_checks_enabled else 'OFF'}",
f"Radar heatmap: {RADAR_HEATMAP_MODES[radar_heatmap_mode_idx]}",
"Keys: SPACE play/pause, RIGHT next, LEFT prev, M +/-60s, S +/-10s, +/- speed, C checks, H heatmap, Q quit" \
if route_entries else "Keys: C checks, H heatmap, Q quit",
]
draw_loading_overlay(font, loading_lines, camera_texture, top_down_texture, hor_mode, 80, 160)
rl.end_drawing()
continue
if not playback_ready:
playback_ready = True
last_replay_started_at = time.monotonic()
loading_status = "Streaming"
lid_overlay = lid_overlay_blank.copy()
top_down = top_down_texture, lid_overlay
sm.update(0)
camera = DEVICE_CAMERAS[("tici", str(sm['roadCameraState'].sensor))]
# Use received buffer dimensions (full HEVC can have stride != buffer_len/rows due to VENUS padding)
h, w, stride = yuv_img_raw.height, yuv_img_raw.width, yuv_img_raw.stride
nv12_size = h * 3 // 2 * stride
imgff = np.frombuffer(yuv_img_raw.data, dtype=np.uint8, count=nv12_size).reshape((h * 3 // 2, stride))
num_px = w * h
rgb = cv2.cvtColor(imgff[: h * 3 // 2, : w], cv2.COLOR_YUV2RGB_NV12)
qcam = "QCAM" in os.environ
bb_scale = 0.825 if qcam else 0.8
calib_scale = camera.fcam.width / 640.0
zoom_matrix = np.asarray([[bb_scale, 0.0, 0.0], [0.0, bb_scale, 0.0], [0.0, 0.0, 1.0]])
cv2.warpAffine(rgb, zoom_matrix[:2], (img.shape[1], img.shape[0]), dst=img, flags=cv2.WARP_INVERSE_MAP)
intrinsic_matrix = camera.fcam.intrinsics
w = sm['controlsState'].lateralControlState.which()
if w == 'lqrStateDEPRECATED':
angle_steers_k = sm['controlsState'].lateralControlState.lqrStateDEPRECATED.steeringAngleDeg
elif w == 'indiState':
angle_steers_k = sm['controlsState'].lateralControlState.indiState.steeringAngleDeg
else:
angle_steers_k = np.inf
plot_arr[:-1] = plot_arr[1:]
plot_arr[-1, name_to_arr_idx['angle_steers']] = sm['carState'].steeringAngleDeg
plot_arr[-1, name_to_arr_idx['angle_steers_des']] = sm['carControl'].actuators.steeringAngleDeg
plot_arr[-1, name_to_arr_idx['angle_steers_k']] = angle_steers_k
plot_arr[-1, name_to_arr_idx['gas']] = sm['carState'].gasDEPRECATED
# TODO gas is deprecated
plot_arr[-1, name_to_arr_idx['computer_gas']] = np.clip(sm['carControl'].actuators.accel / 4.0, 0.0, 1.0)
plot_arr[-1, name_to_arr_idx['user_brake']] = sm['carState'].brake
plot_arr[-1, name_to_arr_idx['steer_torque']] = sm['carControl'].actuators.torque * ANGLE_SCALE
# TODO brake is deprecated
plot_arr[-1, name_to_arr_idx['computer_brake']] = np.clip(-sm['carControl'].actuators.accel / 4.0, 0.0, 1.0)
plot_arr[-1, name_to_arr_idx['v_ego']] = sm['carState'].vEgo
plot_arr[-1, name_to_arr_idx['v_cruise']] = sm['carState'].cruiseState.speed
plot_arr[-1, name_to_arr_idx['a_ego']] = sm['carState'].aEgo
if len(sm['longitudinalPlan'].accels):
plot_arr[-1, name_to_arr_idx['a_target']] = sm['longitudinalPlan'].accels[0]
if sm.recv_frame['modelV2']:
plot_model(sm['modelV2'], img, calibration, top_down)
if sm.recv_frame['radarState']:
plot_lead(sm['radarState'], top_down)
if sm.updated['liveCalibration'] and num_px:
rpyCalib = np.asarray(sm['liveCalibration'].rpyCalib)
calibration = Calibration(num_px, rpyCalib, intrinsic_matrix, calib_scale)
can_packets = messaging.drain_sock(logcan)
if can_packets:
can_strings = [
(can_packet.logMonoTime, [(msg.address, msg.dat, msg.src) for msg in can_packet.can])
for can_packet in can_packets
]
detected_format_counts = {radar_spec.name: 0 for radar_spec in RADAR_SPECS}
for can_packet in can_packets:
for msg in can_packet.can:
radar_spec = get_radar_spec(msg.address)
if radar_spec is not None:
can_range_msg_count += 1
detected_format_counts[radar_spec.name] += 1
radar_format_total_counts[radar_spec.name] += 1
radar_format_seen_addresses[radar_spec.name].add(msg.address)
if radar_spec.name not in radar_parsers:
radar_parsers[radar_spec.name] = {}
if msg.src not in radar_parsers[radar_spec.name]:
radar_parsers[radar_spec.name][msg.src] = get_radar_can_parser(radar_spec, msg.src)
matching_formats = [
radar_spec.name
for radar_spec in RADAR_SPECS
if is_exclusive_full_range_match(radar_spec, radar_format_seen_addresses)
]
if len(matching_formats) == 1:
if active_radar_format_name == matching_formats[0]:
active_radar_format_miss_count = 0
elif active_radar_format_name is None:
active_radar_format_name = matching_formats[0]
active_radar_format_miss_count = 0
else:
active_radar_format_miss_count += 1
if active_radar_format_miss_count >= RADAR_FORMAT_SWITCH_MISS_FRAMES:
active_radar_format_name = matching_formats[0]
active_radar_format_miss_count = 0
elif len(matching_formats) == 0 and active_radar_format_name is not None:
active_radar_format_miss_count += 1
if active_radar_format_miss_count >= RADAR_FORMAT_SWITCH_MISS_FRAMES:
active_radar_format_name = None
active_radar_format_miss_count = 0
active_radar_spec = next((spec for spec in RADAR_SPECS if spec.name == active_radar_format_name), None)
if active_radar_spec is not None:
for bus, parser in radar_parsers.get(active_radar_spec.name, {}).items():
updated_addrs = parser.update(can_strings)
relevant_updated_addrs = {
track_addr for track_addr in updated_addrs
if active_radar_spec.start_addr <= track_addr <= active_radar_spec.end_addr
}
if not relevant_updated_addrs:
continue
for track_addr in relevant_updated_addrs:
msg_name = f"RADAR_TRACK_{track_addr:x}"
track_msg = parser.vl[msg_name]
for track_prefix in active_radar_spec.track_prefixes:
track_key = get_track_storage_key(active_radar_spec, bus, track_addr, track_prefix)
ts_nanos = get_track_ts_nanos(parser, msg_name, active_radar_spec, track_prefix)
if ts_nanos == 0:
continue
if state_checks_enabled and not is_radar_track_valid(active_radar_spec, track_msg, track_prefix):
radar_tracks.pop(track_key, None)
radar_track_last_seen.pop(track_key, None)
continue
d_rel, y_rel, v_rel, a_rel = decode_radar_track(active_radar_spec, track_msg, track_prefix)
if track_key not in radar_track_ids:
radar_track_ids[track_key] = next_radar_track_id
next_radar_track_id += 1
radar_tracks[track_key] = RadarTrackPoint(
trackId=radar_track_ids[track_key],
dRel=d_rel,
yRel=y_rel,
vRel=v_rel,
aRel=a_rel,
)
radar_track_last_seen[track_key] = sm.frame
stale_tracks = [
track_key for track_key, last_seen in radar_track_last_seen.items()
if (sm.frame - last_seen) > RADAR_TRACK_TIMEOUT_FRAMES
]
for track_key in stale_tracks:
radar_track_last_seen.pop(track_key, None)
radar_tracks.pop(track_key, None)
active_radar_tracks = [
track for track_key, track in radar_tracks.items()
if active_radar_format_name is not None and track_key[0] == active_radar_format_name
]
active_radar_buses = sorted({
track_key[1] for track_key in radar_tracks
if active_radar_format_name is not None and track_key[0] == active_radar_format_name
})
if len(active_radar_tracks) == 0:
active_radar_tracks = sm['liveTracks'].points
active_radar_buses = []
radar_heatmap_mode = RADAR_HEATMAP_MODES[radar_heatmap_mode_idx]
if radar_heatmap_mode in ("TOP", "BOTH"):
update_radar_heatmap(active_radar_tracks, radar_heatmap)
if radar_heatmap_mode in ("CAMERA", "BOTH"):
update_radar_camera_heatmap(active_radar_tracks, camera_radar_heatmap, calibration, img.shape)
overlay_heatmap(img, camera_radar_heatmap, CAMERA_RADAR_HEATMAP_ALPHA)
# draw decoded radar tracks when present, otherwise fall back to liveTracks
draw_radar_points(active_radar_tracks, top_down[1])
draw_radar_points_camera(active_radar_tracks, img, calibration)
# *** blits ***
# Update camera texture from numpy array
img_rgba = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)
rl.update_texture(camera_texture, rl.ffi.cast("void *", img_rgba.ctypes.data))
rl.draw_texture_pro(
camera_texture,
rl.Rectangle(0, 0, camera_texture.width, camera_texture.height),
rl.Rectangle(0, 0, CAMERA_DRAW_WIDTH, CAMERA_DRAW_HEIGHT),
rl.Vector2(0, 0),
0.0,
rl.WHITE,
)
# display alerts
rl.draw_text_ex(font, sm['selfdriveState'].alertText1, rl.Vector2(180, 150), 30, 0, rl.RED)
rl.draw_text_ex(font, sm['selfdriveState'].alertText2, rl.Vector2(180, 190), 20, 0, rl.RED)
# draw plots (texture is reused internally)
plot_texture = draw_plots(plot_arr)
if hor_mode:
rl.draw_texture_pro(
plot_texture,
rl.Rectangle(0, 0, plot_texture.width, plot_texture.height),
rl.Rectangle(CAMERA_DRAW_WIDTH + TOP_DOWN_DRAW_WIDTH, 0, PLOT_DRAW_WIDTH, PLOT_DRAW_HEIGHT),
rl.Vector2(0, 0),
0.0,
rl.WHITE,
)
else:
rl.draw_texture(plot_texture, 0, 300, rl.WHITE) # noqa: TID251
# Convert lid_overlay to RGBA and update top_down texture
# lid_overlay is (384, 960), need to transpose to (960, 384) for row-major RGBA buffer
lid_rgba = palette[lid_overlay.T]
if radar_heatmap_mode in ("TOP", "BOTH"):
overlay_heatmap(lid_rgba[..., :3], radar_heatmap.T, RADAR_HEATMAP_ALPHA)
rl.update_texture(top_down_texture, rl.ffi.cast("void *", np.ascontiguousarray(lid_rgba).ctypes.data))
rl.draw_texture(top_down_texture, CAMERA_DRAW_WIDTH, 0, rl.WHITE) # noqa: TID251
SPACING = 20
lines = [
("ENABLED", GREEN if sm['selfdriveState'].enabled else BLACK),
("SPEED: " + str(round(sm['carState'].vEgo, 1)) + " m/s", CYAN),
("LONG CONTROL STATE: " + str(sm['controlsState'].longControlState), CYAN),
("LONG MPC SOURCE: " + str(sm['longitudinalPlan'].longitudinalPlanSource), CYAN),
(f"RADAR FORMAT: {active_radar_format_name or 'NONE'}", AMBER),
(f"RADAR CAN MSGS: {can_range_msg_count}", AMBER),
(f"RADAR TRACKS: {len(active_radar_tracks)}"
+ (f" (BUS {','.join(str(bus) for bus in active_radar_buses)})" if active_radar_buses else ""),
AMBER),
(f"RADAR STATE CHECKS: {'ON' if state_checks_enabled else 'OFF'}", AMBER),
(f"RADAR HEATMAP: {RADAR_HEATMAP_MODES[radar_heatmap_mode_idx]}", AMBER),
(f"ROUTE: {current_route_name}" if current_route_name is not None else "", SLATE),
(f"PLATFORM: {current_route_model}" if current_route_model is not None else "", SLATE),
(f"OFFSET: {current_offset_seconds()}s" if route_entries else "", SOFT_WHITE),
(f"PLAYBACK: {current_playback:.1f}x" if route_entries else "", SOFT_WHITE),
(f"STATUS: {'PAUSED' if paused else 'PLAYING'}" if route_entries else "", SOFT_WHITE),
("ANGLE OFFSET (AVG): " + str(round(sm['liveParameters'].angleOffsetAverageDeg, 2)) + " deg", SOFT_WHITE),
("ANGLE OFFSET (INSTANT): " + str(round(sm['liveParameters'].angleOffsetDeg, 2)) + " deg", SOFT_WHITE),
("STIFFNESS: " + str(round(sm['liveParameters'].stiffnessFactor * 100.0, 2)) + " %", SOFT_WHITE),
("STEER RATIO: " + str(round(sm['liveParameters'].steerRatio, 2)), SOFT_WHITE),
]
hud_height = len(lines) * SPACING + 18
rl.draw_rectangle(write_x - 10, write_y - 12, 560, hud_height, rl.Color(8, 12, 18, 155))
rl.draw_rectangle(write_x - 10, write_y - 12, 4, hud_height, rl.Color(90, 235, 255, 255))
rl.draw_rectangle_lines(write_x - 10, write_y - 12, 560, hud_height, rl.Color(90, 235, 255, 80))
for i, line in enumerate(lines):
if line is not None:
color = rl.Color(line[1][0], line[1][1], line[1][2], 255)
rl.draw_text_ex(font, line[0], rl.Vector2(write_x, write_y + i * SPACING), 20, 0, color)
rl.end_drawing()
rl.unload_texture(camera_texture)
rl.unload_texture(top_down_texture)
rl.unload_font(font)
rl.close_window()
stop_replay(replay_proc)
def get_arg_parser():
parser = argparse.ArgumentParser(description="Show replay data in a UI.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("ip_address", nargs="?", default="127.0.0.1", help="The ip address on which to receive zmq messages.")
parser.add_argument("--route", default=None, help="Route to replay locally before opening the UI.")
parser.add_argument("--routes", action="store_true", help="Cycle Hyundai/Kia/Genesis routes from opendbc/car/tests/routes.py.")
parser.add_argument("--custom-routes", nargs="?", type=int, const=1, default=None,
help="Cycle routes from tools/radar/custom_routes.py, optionally starting from a 1-based route index.")
parser.add_argument("--data-dir", default=None, help="Optional local route data directory to pass to replay.")
parser.add_argument("--playback", default="1.0", help="Replay playback speed when using --route.")
parser.add_argument("--prefix", default="ui-replay", help="OPENPILOT_PREFIX to use when launching replay from the UI.")
parser.add_argument("--frame-address", default=None, help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.")
return parser
if __name__ == "__main__":
args = get_arg_parser().parse_args(sys.argv[1:])
selected_sources = int(args.route is not None) + int(args.routes) + int(args.custom_routes is not None)
if selected_sources > 1:
raise SystemExit("Use only one of --route, --routes, or --custom-routes.")
route_entries = None
start_route_idx = 0
if args.route is not None:
route_entries = [(args.route, "MANUAL_ROUTE")]
elif args.routes:
route_entries = get_hkg_routes()
elif args.custom_routes is not None:
route_entries = get_custom_routes()
start_route_idx = max(0, min(len(route_entries) - 1, args.custom_routes - 1))
if route_entries:
os.environ["OPENPILOT_PREFIX"] = args.prefix
messaging.reset_context()
elif args.ip_address != "127.0.0.1":
os.environ["ZMQ"] = "1"
messaging.reset_context()
ui_thread(args.ip_address, route_entries=route_entries, playback=args.playback, data_dir=args.data_dir, prefix=args.prefix, start_route_idx=start_route_idx)
+3192
View File
File diff suppressed because it is too large Load Diff