Engine Sounds Wheel Controls

This commit is contained in:
whoisdomi
2026-11-18 13:59:45 -06:00
parent e55dbfb5ed
commit 689eaf7d55
10 changed files with 157 additions and 15 deletions
@@ -4,7 +4,7 @@ from dataclasses import dataclass
from opendbc.car.gm.profiles import profiles_supported as gm_profiles_supported
import hashlib
from openpilot.starpilot.conditional_mode.manual import EXPERIMENTAL_MODE_ACTION, TRAFFIC_MODE_ACTION, ioniq6_media_eligible
from openpilot.starpilot.conditional_mode.manual import ACTION_COUNT, EXPERIMENTAL_MODE_ACTION, TRAFFIC_MODE_ACTION, ioniq6_media_eligible
from openpilot.starpilot.conditional_mode.preferences import MAX_DOCUMENT_BYTES, PreferenceError, decode_preferences
from openpilot.starpilot.saved_document import WriteResult, commit_exact
from openpilot.starpilot.saved_source import read_saved
@@ -22,7 +22,7 @@ SAFE_KEY = "SafeMode"
MAX_SCALAR_BYTES = 8
CHOICES = {"Off": b"0", "Cycle conditional mode": str(EXPERIMENTAL_MODE_ACTION).encode(),
"Toggle traffic mode": str(TRAFFIC_MODE_ACTION).encode(), "Switchback Mode": b"7"}
_CANONICAL_ACTIONS = frozenset(str(value).encode() for value in range(15))
_CANONICAL_ACTIONS = frozenset(str(value).encode() for value in range(ACTION_COUNT))
@dataclass(frozen=True)
@@ -23,6 +23,7 @@ from openpilot.starpilot.saved_source import read_saved
EXPERIMENTAL_MODE_ACTION = 5
TRAFFIC_MODE_ACTION = 6
ACTION_COUNT = 17
VERY_LONG_PRESS = 5 * CRUISE_LONG_PRESS
MEDIA_LONG_NS = CRUISE_LONG_PRESS * 10_000_000 # Convert 100 Hz ticks to source-packet nanoseconds.
MEDIA_VERY_LONG_NS = VERY_LONG_PRESS * 10_000_000
@@ -106,7 +107,7 @@ def _action(params, key: str) -> int | None:
if raw is None:
return 0
# Registered INT defaults and Params::put values are canonical decimal.
if raw not in tuple(str(value).encode() for value in range(15)):
if raw not in tuple(str(value).encode() for value in range(ACTION_COUNT)):
return None
return int(raw)
@@ -53,7 +53,7 @@ def context(tmp_path):
def test_exact_catalog_and_missing_vs_saved_off(context):
params, _ = context
assert sorted(ACTIONS.values()) == list(range(15))
assert sorted(ACTIONS.values()) == list(range(17))
assert len(KEYS) == 15
assert capture(params)['DistanceButtonControl'] == 1
assert capture(params)['LongDistanceButtonControl'] == 5
@@ -62,7 +62,7 @@ def test_exact_catalog_and_missing_vs_saved_off(context):
assert capture(params)['DistanceButtonControl'] == 0
@pytest.mark.parametrize('key,code', [('DistanceButtonControl', code) for code in (1, 2, 5, 6, 7, 8, 11, 12, 13, 14)])
@pytest.mark.parametrize('key,code', [('DistanceButtonControl', code) for code in (1, 2, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16)])
def test_real_distance_short_delivers_once_and_claims_serialized_release(context, key, code):
params, cp = context
params.put(key, code, block=True)
@@ -5,7 +5,7 @@ from dataclasses import dataclass
from functools import lru_cache
from opendbc.car import structs
from openpilot.starpilot.conditional_mode.manual import Button, ButtonTracker, Press, ioniq6_media_eligible
from openpilot.starpilot.conditional_mode.manual import ACTION_COUNT, Button, ButtonTracker, Press, ioniq6_media_eligible
from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.conditional_mode.ui_action import fresh_service
@@ -14,8 +14,9 @@ ACTIONS = {
"Off": 0, "Cycle personality": 1, "Force coast": 2, "Pause steering": 3, "Pause longitudinal": 4,
"Experimental override": 5, "Traffic mode": 6, "Switchback Mode": 7, "Bookmark": 8,
"Toggle AOL": 9, "Adopt speed limit": 10, "Quick Select 1": 11, "Quick Select 2": 12,
"Quick Select 3": 13, "Pulse and glide": 14,
"Quick Select 3": 13, "Pulse and glide": 14, "Toggle Engine Sounds": 15, "Next Engine Sound": 16,
}
ENGINE_SOUND_ACTIONS = (15, 16)
KEYS = ("LKASButtonControl", "MainCruiseButtonControl", "DistanceButtonControl", "LongDistanceButtonControl",
"VeryLongDistanceButtonControl", "CancelButtonControl", "LongCancelButtonControl", "VeryLongCancelButtonControl",
"ModeButtonControl", "LongModeButtonControl", "VeryLongModeButtonControl", "StarButtonControl",
@@ -23,7 +24,7 @@ KEYS = ("LKASButtonControl", "MainCruiseButtonControl", "DistanceButtonControl",
PADDLE_KEY = "LeftPaddleButtonControl"
LIFETIME_NS = 250_000_000
SESSION = re.compile(r"[0-9a-f]{32}\Z")
DELIVERED_ACTIONS = frozenset((1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14))
DELIVERED_ACTIONS = frozenset((1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14, *ENGINE_SOUND_ACTIONS))
DEFAULTS = {"DistanceButtonControl": 1, "LongDistanceButtonControl": 5, "VeryLongDistanceButtonControl": 6}
BUTTON_KEYS = {
Button.LKAS: (KEYS[0],), Button.DISTANCE: KEYS[2:5], Button.MODE: KEYS[8:11], Button.CUSTOM: KEYS[11:14],
@@ -117,7 +118,7 @@ def capture(params):
result = {}
for key in KEYS:
raw, readable = read_saved(params, key, 8)
if not readable or raw is not None and raw not in tuple(str(value).encode() for value in range(15)):
if not readable or raw is not None and raw not in tuple(str(value).encode() for value in range(ACTION_COUNT)):
return None
result[key] = int(raw) if raw is not None else DEFAULTS.get(key, 0)
return result
@@ -17,6 +17,35 @@ def profile_name(params) -> str:
return name if name in PROFILES else DEFAULT_PROFILE
def _commit(params, key: str, raw: bytes, expected: bytes | None) -> bool:
from openpilot.starpilot.saved_document import commit_exact
result = commit_exact(params, key=key, max_bytes=64, raw=raw, expected=expected, authorized=lambda: True,
temp_prefix=".engine-sound-")
return result.committed and result.verified
def toggle(params) -> bool | None:
"""Flip Engine Sounds; returns the new state, or None if the saved value could not be replaced."""
from openpilot.starpilot.saved_source import read_saved
raw, readable = read_saved(params, ENABLED_KEY, 8)
if not readable or raw not in (None, b"0", b"1"):
return None
on = raw != b"1"
return on if _commit(params, ENABLED_KEY, b"1" if on else b"0", raw) else None
def next_profile(params) -> str | None:
"""Select the profile after the current one, wrapping; returns its name."""
from openpilot.starpilot.saved_source import read_saved
raw, readable = read_saved(params, PROFILE_KEY, 64)
if not readable:
return None
names = list(PROFILES)
current = raw.decode(errors="replace") if raw is not None else DEFAULT_PROFILE
name = names[(names.index(current) + 1) % len(names)] if current in PROFILES else DEFAULT_PROFILE
return name if _commit(params, PROFILE_KEY, name.encode(), raw) else None
def volume(params) -> float:
try:
return min(max(int(params.get(VOLUME_KEY)), 0), 100) / 100.0
@@ -0,0 +1,62 @@
from openpilot.common.params import Params
from openpilot.starpilot.engine_sound import settings
from openpilot.starpilot.engine_sound.profiles import DEFAULT_PROFILE, PROFILES
from openpilot.starpilot.ui.engine_sound_notice import NOTICE_NS, EngineSoundNotice
from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert
NOW = 5_000_000_000
def test_toggle_flips_saved_state(tmp_path):
params = Params(str(tmp_path))
assert settings.toggle(params) is True
assert params.get_bool('EngineSound')
assert settings.toggle(params) is False
assert not params.get_bool('EngineSound')
def test_toggle_leaves_an_unreadable_value(tmp_path):
params = Params(str(tmp_path))
path = params.get_param_path('EngineSound')
with open(path, 'wb') as f:
f.write(b'7')
assert settings.toggle(params) is None
with open(path, 'rb') as f:
assert f.read() == b'7'
def test_next_profile_cycles_every_car_and_wraps(tmp_path):
params = Params(str(tmp_path))
names = list(PROFILES)
start = names.index(DEFAULT_PROFILE)
seen = [settings.next_profile(params) for _ in names]
assert seen == [names[(start + i + 1) % len(names)] for i in range(len(names))]
assert settings.profile_name(params) == DEFAULT_PROFILE
def test_next_profile_recovers_an_unknown_saved_car(tmp_path):
params = Params(str(tmp_path))
params.put('EngineSoundProfile', 'tractor', block=True)
assert settings.next_profile(params) == DEFAULT_PROFILE
def test_notice_shows_the_car_then_yields():
notice = EngineSoundNotice()
assert notice.update(OnroadAlert(), NOW) == OnroadAlert()
notice.show(False, True, 'jaguar_ftype', NOW)
alert = notice.update(OnroadAlert(), NOW + 1)
assert (alert.size, alert.text1, alert.text2) == (AlertSize.MID, 'Jaguar F-Type', 'Engine Sound')
native = OnroadAlert(AlertSize.FULL, 'TAKE CONTROL')
assert notice.update(native, NOW + 1) is native
assert notice.update(OnroadAlert(), NOW + NOTICE_NS) == OnroadAlert()
def test_notice_toggle_text():
notice = EngineSoundNotice()
notice.show(True, True, 'lfa', NOW)
assert (notice.update(OnroadAlert(), NOW).text1, notice.update(OnroadAlert(), NOW).text2) == ('Engine Sounds On', 'LFA')
notice.show(True, False, 'lfa', NOW)
alert = notice.update(OnroadAlert(), NOW)
assert (alert.size, alert.text1) == (AlertSize.SMALL, 'Engine Sounds Off')
notice.show(False, False, 'lfa', NOW)
assert notice.update(OnroadAlert(), NOW).text2 == 'Engine Sounds Off'
@@ -0,0 +1,29 @@
"""Short onroad notice after a wheel button toggles or changes the engine sound."""
from openpilot.starpilot.engine_sound.profiles import PROFILES
from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert
NOTICE_NS = 1_500_000_000
ALERT_TYPE = "engineSoundChanged/warning"
def notice_text(toggled: bool, enabled: bool, profile: str) -> tuple[str, str]:
label = PROFILES[profile].label if profile in PROFILES else profile
if toggled:
return ("Engine Sounds On", label) if enabled else ("Engine Sounds Off", "")
return label, "Engine Sound" if enabled else "Engine Sounds Off"
class EngineSoundNotice:
def __init__(self) -> None:
self._until_ns = 0
self._text = ("", "")
def show(self, toggled: bool, enabled: bool, profile: str, now_ns: int) -> None:
self._text = notice_text(toggled, enabled, profile)
self._until_ns = now_ns + NOTICE_NS
def update(self, native_alert: OnroadAlert, now_ns: int) -> OnroadAlert:
if native_alert.size != AlertSize.NONE or not 0 < self._until_ns - now_ns <= NOTICE_NS:
return native_alert
return OnroadAlert(AlertSize.MID if self._text[1] else AlertSize.SMALL, self._text[0], self._text[1], alert_type=ALERT_TYPE)
+18 -3
View File
@@ -81,7 +81,7 @@ from openpilot.starpilot.ui.onroad_favorites import OnroadFavorites
from openpilot.starpilot.ui.onroad_dm import DriverMonitorLayer
from openpilot.starpilot.favorites.owner import FavoritesOwner
from openpilot.starpilot.controllers.cruise_action import CruiseActionPublisher, ui_authority as cruise_action_authority
from openpilot.starpilot.controllers.wheel_actions import WheelConsumer
from openpilot.starpilot.controllers.wheel_actions import ENGINE_SOUND_ACTIONS, WheelConsumer
from openpilot.starpilot.ui.wheel_input import onroad_action_context
from openpilot.starpilot.system.starport.projection_bookmark import BookmarkReceiver
from openpilot.starpilot.system.starport.projection_slc_action import SlcActionReceiver
@@ -575,12 +575,15 @@ class StarShellSession:
command = self._wheel_consumer.accept(event, ui_state.params, ui_state.CP, ui_state.sm, now_ns=now_ns)
if command is None or command.action == 0:
continue
authorized = (self._bookmark_authority() if command.action == 8 else
authorized = (self._bookmark_authority() if command.action in (8, *ENGINE_SOUND_ACTIONS) else
self._favorite_authority(allow_personality_notice=command.action == 1))
if not authorized:
continue
actions = self._native_favorite_actions()
try:
if command.action in ENGINE_SOUND_ACTIONS:
self._engine_sound_action(command.action == ENGINE_SOUND_ACTIONS[0], now_ns)
continue
actions = self._native_favorite_actions()
if command.action == 1:
if self._wheel_personality is not None:
self._wheel_personality()
@@ -603,6 +606,18 @@ class StarShellSession:
except (OSError, RuntimeError, ValueError, TypeError):
pass
def _engine_sound_action(self, toggle: bool, now_ns: int) -> None:
from openpilot.starpilot.engine_sound import settings as engine_sound
params = ui_state.params
if toggle:
enabled = engine_sound.toggle(params)
profile = engine_sound.profile_name(params)
else:
profile = engine_sound.next_profile(params)
enabled = engine_sound.enabled(params)
if enabled is not None and profile is not None:
self.adapter.engine_sound_notice.show(toggle, enabled, profile, now_ns)
def _conditional_action_owner(self):
if self.conditional_actions is None:
self.conditional_actions = ConditionalUiActionOwner(ui_state.params)
@@ -30,6 +30,7 @@ from openpilot.starpilot.parked_evidence import ParkedEvidence, RESUME_SKEW_NS,
from openpilot.starpilot.ui.conditional_status import ConditionalDisplayProjector, ConditionalPerceptionProjector, configured_choice
from openpilot.starpilot.ui.traffic_status import TrafficDisplayProjector
from openpilot.starpilot.ui.drive_mode_notice import DriveModeNotice
from openpilot.starpilot.ui.engine_sound_notice import EngineSoundNotice
from openpilot.starpilot.controllers.mode_actions import SwitchbackStatusOwner
from openpilot.starpilot.ui.wheel_feedback import observe_wheel_acceleration
from openpilot.starpilot.ui.torque_feedback import observe_torque_feedback
@@ -338,6 +339,7 @@ class RuntimeSnapshotAdapter:
self._traffic_profile_valid = False
self._personality_notice = PersonalityNotice()
self._drive_mode_notice = DriveModeNotice(ui_state.params)
self.engine_sound_notice = EngineSoundNotice()
self._stopped_timer = StoppedTimer()
self._replay_stopped_history = False
self._developer_metrics = DeveloperMetrics()
@@ -735,6 +737,7 @@ class RuntimeSnapshotAdapter:
drive_mode_source, display_car, cp=cp, drive_frame=after,
event_ns=int(sm.logMonoTime['starpilotCarState']) if drive_mode_source is not None else 0, now_ns=now_ns,
native_alert=alert, traffic_active=bool(traffic is not None and traffic.state == 'active'))
alert = self.engine_sound_notice.update(alert, now_ns)
onroad = OnroadState(weather_location=weather_location, developer_metrics=developer_metrics, stop_sign_observed_ns=stop_observed_ns,
engaged=display_lat_active or display_long_active or longitudinal_overridden, camera_available=started,
speed_mps=raw_speed, cruise_kph=cruise, speed_limit=observation,
+5 -3
View File
@@ -3,7 +3,9 @@ import hashlib
from openpilot.starpilot.aol.vehicle import policy_for
from openpilot.starpilot.conditional_mode.manual import ioniq6_media_eligible
from openpilot.starpilot.feature_capabilities import lateral_supported
from openpilot.starpilot.controllers.wheel_actions import ACTIONS, DEFAULTS, KEYS, PADDLE_KEY, button_reported, eligible, paddle_bookmark_available
from openpilot.starpilot.conditional_mode.manual import ACTION_COUNT
from openpilot.starpilot.controllers.wheel_actions import (ACTIONS, DEFAULTS, ENGINE_SOUND_ACTIONS, KEYS, PADDLE_KEY, button_reported, eligible,
paddle_bookmark_available)
from openpilot.starpilot.saved_document import commit_exact
from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
@@ -79,7 +81,7 @@ class WheelFeature:
return ()
if key in KEYS[8:] and not media:
return ()
codes = {0, 8, 11, 12, 13}
codes = {0, 8, 11, 12, 13, *ENGINE_SOUND_ACTIONS}
if self.owner.longitudinal_available():
codes.update((1, 2, 5, 10, 14))
codes.add(6)
@@ -115,7 +117,7 @@ class WheelFeature:
if not choices:
continue
raw, readable = read_saved(self.owner.params, key, 8)
number = DEFAULTS.get(key, 0) if raw is None else int(raw) if raw in tuple(str(i).encode() for i in range(15)) else -1
number = DEFAULTS.get(key, 0) if raw is None else int(raw) if raw in tuple(str(i).encode() for i in range(ACTION_COUNT)) else -1
selected = next((name for name, code in ACTIONS.items() if code == number), None)
implicit_toggle = False
if cp.brand == 'hyundai' and policy.explicit_latch and key in KEYS[:2]: