mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-30 00:33:41 +08:00
Keep live steering settings reads out of the control cycle
This commit is contained in:
@@ -51,6 +51,7 @@ from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePo
|
||||
from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate
|
||||
from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns
|
||||
from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported
|
||||
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
|
||||
from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled
|
||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
||||
from openpilot.starpilot.lateral.controller_selection import learning_allowed, read_selection
|
||||
@@ -131,12 +132,19 @@ class Controls:
|
||||
)
|
||||
self.highway_correction_gain = HighwayCorrectionGain()
|
||||
self.highway_smoothing_supported = lateral_supported(self.CP)
|
||||
self.highway_gain = read_gain(self.params) if self.highway_smoothing_supported else 1.0
|
||||
self.live_steering_preferences = (
|
||||
LiveSteeringPreferences(self.params) if self.highway_smoothing_supported and os.getenv("REPLAY") != "1" else None)
|
||||
preferences = self.live_steering_preferences
|
||||
self.highway_gain = (preferences.current.highway_gain if preferences is not None else read_gain(self.params)) if self.highway_smoothing_supported else 1.0
|
||||
self.lateral_pause = LateralPause(read_lateral_pause(self.params), self.params)
|
||||
self.lane_change_preferences = LiveLaneChangePolicy(self.params, now_ns=0 if os.getenv('REPLAY') == '1' else time.monotonic_ns())
|
||||
self.lane_change_preferences = LiveLaneChangePolicy(
|
||||
self.params, now_ns=0 if os.getenv('REPLAY') == '1' else time.monotonic_ns(),
|
||||
settings_reader=(lambda: preferences.current.lane_change) if preferences is not None else None)
|
||||
self.lane_change_policy = self.lane_change_preferences.applied
|
||||
self.lane_change_smoother = LaneChangeSmoother()
|
||||
self.lane_centering_host = LaneCenteringHost(self.params) if lane_runtime_supported(self.CP) else None
|
||||
self.lane_centering_host = LaneCenteringHost(
|
||||
self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None,
|
||||
) if lane_runtime_supported(self.CP) else None
|
||||
self.torque_host = (
|
||||
TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None))
|
||||
if torque_runtime_enabled(self.CP, self.params)
|
||||
@@ -511,7 +519,10 @@ class Controls:
|
||||
self.model_turn_assist.reset()
|
||||
self.model_turn_assist.twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
|
||||
if self.highway_smoothing_supported:
|
||||
if self.sm.frame % 100 == 0:
|
||||
preferences = getattr(self, "live_steering_preferences", None)
|
||||
if preferences is not None:
|
||||
self.highway_gain = preferences.current.highway_gain
|
||||
elif self.sm.frame % 100 == 0:
|
||||
self.highway_gain = read_gain(self.params)
|
||||
predicted = None
|
||||
if self.sm.all_checks(['modelV2']):
|
||||
@@ -929,7 +940,14 @@ def main():
|
||||
cloudlog.warning("Controls normal scheduling preference unavailable")
|
||||
else:
|
||||
set_core_affinity([4, 5])
|
||||
controls.run()
|
||||
preferences = controls.live_steering_preferences
|
||||
if preferences is not None:
|
||||
preferences.start()
|
||||
try:
|
||||
controls.run()
|
||||
finally:
|
||||
if preferences is not None:
|
||||
preferences.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -188,9 +188,11 @@ class LiveLaneChangePolicy:
|
||||
"""
|
||||
REFRESH_NS = 1_000_000_000
|
||||
|
||||
def __init__(self, params, *, now_ns=0):
|
||||
def __init__(self, params, *, now_ns=0, settings_reader=None):
|
||||
self.params = params
|
||||
saved = read_saved(params)
|
||||
self.settings_reader = settings_reader
|
||||
saved = read_saved(params) if settings_reader is None else settings_reader()
|
||||
self.saved = saved
|
||||
self.requested = effective(saved) if saved.readable and saved.valid else self._disabled()
|
||||
self.applied = self.requested
|
||||
self.last_read_ns = now_ns if type(now_ns) is int and now_ns > 0 else 0
|
||||
@@ -204,8 +206,14 @@ class LiveLaneChangePolicy:
|
||||
self.last_read_ns = 0
|
||||
self.requested = self.applied = self._disabled()
|
||||
return self.applied
|
||||
if not self.last_read_ns or now_ns - self.last_read_ns >= self.REFRESH_NS:
|
||||
saved = read_saved(self.params)
|
||||
if self.settings_reader is not None:
|
||||
saved = self.settings_reader()
|
||||
refresh = not self.last_read_ns or saved is not self.saved
|
||||
else:
|
||||
refresh = not self.last_read_ns or now_ns - self.last_read_ns >= self.REFRESH_NS
|
||||
saved = read_saved(self.params) if refresh else self.saved
|
||||
if refresh:
|
||||
self.saved = saved
|
||||
self.requested = effective(saved) if saved.readable and saved.valid else self._disabled()
|
||||
self.last_read_ns = now_ns
|
||||
if not self.requested.enabled:
|
||||
|
||||
@@ -2,21 +2,21 @@
|
||||
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from openpilot.cereal.services import SERVICE_LIST
|
||||
from openpilot.common.realtime import DT_CTRL
|
||||
from openpilot.common.params import UnknownKeyName
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.lateral.lane_centering import ControlMode, LaneCenteringRequest, LaneCenteringSettings, STRENGTH_BASELINE, STRENGTH_MAX
|
||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
||||
|
||||
|
||||
def read_settings(params) -> LaneCenteringSettings:
|
||||
def raw(key, default):
|
||||
try:
|
||||
return Path(params.get_param_path(key)).read_bytes()
|
||||
except FileNotFoundError:
|
||||
return default
|
||||
value, readable = read_saved(params, key, 64)
|
||||
if not readable:
|
||||
raise ValueError('Invalid lane preference')
|
||||
return default if value is None else value
|
||||
|
||||
def boolean(key, default):
|
||||
value = raw(key, default)
|
||||
@@ -53,8 +53,9 @@ class LaneCenteringHost:
|
||||
REQUIRED = ('carState', 'selfdriveState', 'modelV2', 'vehicleParameters')
|
||||
FREQUENCY_CHECKED = ('carState', 'modelV2', 'vehicleParameters')
|
||||
|
||||
def __init__(self, params):
|
||||
def __init__(self, params, *, settings_reader=None):
|
||||
self.params = params
|
||||
self.settings_reader = settings_reader
|
||||
self.settings = LaneCenteringSettings()
|
||||
self.last_refresh_ns: int | None = None
|
||||
self.last_tick_ns: int | None = None
|
||||
@@ -76,7 +77,12 @@ class LaneCenteringHost:
|
||||
self.last_refresh_ns = None
|
||||
self.last_refusal = 'host_clock'
|
||||
return None
|
||||
if self.last_refresh_ns is None or now_ns < self.last_refresh_ns or now_ns - self.last_refresh_ns >= self.REFRESH_NS:
|
||||
if self.settings_reader is not None:
|
||||
settings = self.settings_reader()
|
||||
if settings is not self.settings:
|
||||
self.settings = settings
|
||||
self.last_refresh_ns = now_ns
|
||||
elif self.last_refresh_ns is None or now_ns < self.last_refresh_ns or now_ns - self.last_refresh_ns >= self.REFRESH_NS:
|
||||
self.settings = read_settings(self.params)
|
||||
self.last_refresh_ns = now_ns
|
||||
if not self.settings.enabled:
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Read live steering preferences without putting disk waits on the control loop."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import threading
|
||||
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import read_gain
|
||||
from openpilot.starpilot.lateral.lane_runtime import read_settings
|
||||
from openpilot.starpilot.lateral.lane_centering import LaneCenteringSettings
|
||||
from openpilot.starpilot.lateral.lane_change_preferences import read_saved, SavedLaneChange
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SteeringPreferences:
|
||||
highway_gain: float
|
||||
lane_centering: LaneCenteringSettings
|
||||
lane_change: SavedLaneChange
|
||||
|
||||
|
||||
class LiveSteeringPreferences:
|
||||
INTERVAL = 1.0
|
||||
|
||||
def __init__(self, params):
|
||||
self.params = params
|
||||
self.current = self._read()
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
def _read(self):
|
||||
return SteeringPreferences(read_gain(self.params), read_settings(self.params), read_saved(self.params))
|
||||
|
||||
def start(self):
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, name="steering-settings", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _run(self):
|
||||
while not self._stop.wait(self.INTERVAL):
|
||||
current = self._read()
|
||||
if not self._stop.is_set():
|
||||
self.current = current
|
||||
|
||||
def close(self):
|
||||
self._stop.set()
|
||||
@@ -0,0 +1,169 @@
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.honda.values import CAR
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.selfdrive.controls.controlsd import Controls
|
||||
from openpilot.starpilot.lateral import lane_change_preferences, lane_runtime
|
||||
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
|
||||
from openpilot.starpilot.lateral.tests.test_lane_runtime import Frame, feed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['highway', 'centering', 'lane_change'])
|
||||
def test_actual_control_cycle_does_not_wait_for_live_settings_disk(reader):
|
||||
with OpenpilotPrefix(), mock.patch.dict(os.environ, {'SIMULATION': '1', 'REPLAY': '0', 'AOL_REPLAY_RUNTIME': '0'}), \
|
||||
mock.patch('openpilot.selfdrive.controls.controlsd.messaging.PubMaster'):
|
||||
params = Params()
|
||||
cp = interfaces[CAR.HONDA_CIVIC].get_non_essential_params(CAR.HONDA_CIVIC)
|
||||
params.put('CarParams', cp.to_bytes(), block=True)
|
||||
actual, reference = Controls(), Controls()
|
||||
origin = time.monotonic_ns()
|
||||
expected = []
|
||||
for tick in range(110):
|
||||
now = origin + tick * 10_000_000
|
||||
with mock.patch('openpilot.selfdrive.controls.controlsd.time.monotonic_ns', return_value=now):
|
||||
feed(reference, now, tick)
|
||||
command, _ = reference.state_control()
|
||||
expected.append(command.to_dict())
|
||||
targets = {
|
||||
'highway': 'openpilot.selfdrive.controls.controlsd.read_gain',
|
||||
'centering': 'openpilot.starpilot.lateral.lane_runtime.read_settings',
|
||||
'lane_change': 'openpilot.starpilot.lateral.lane_change_preferences.read_saved',
|
||||
}
|
||||
actual.lane_change_preferences.last_read_ns = 0
|
||||
with mock.patch(targets[reader], side_effect=AssertionError('control thread waited for disk')):
|
||||
for tick in range(110):
|
||||
now = origin + tick * 10_000_000
|
||||
with mock.patch('openpilot.selfdrive.controls.controlsd.time.monotonic_ns', return_value=now):
|
||||
feed(actual, now, tick)
|
||||
command, _ = actual.state_control()
|
||||
assert command.to_dict() == expected[tick]
|
||||
now = origin + 110 * 10_000_000
|
||||
with mock.patch('openpilot.selfdrive.controls.controlsd.time.monotonic_ns', return_value=now):
|
||||
feed(actual, now, 110, fault=True)
|
||||
command, _ = actual.state_control()
|
||||
assert not command.latActive
|
||||
|
||||
|
||||
def test_blocked_reader_keeps_complete_snapshot_and_does_not_delay_stop():
|
||||
with OpenpilotPrefix():
|
||||
params = Params()
|
||||
params.put('HighwaySmoothingLevel', 5., block=True)
|
||||
reader = LiveSteeringPreferences(params)
|
||||
before = reader.current
|
||||
assert before.highway_gain == .5
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
next_snapshot = replace(before, highway_gain=.8)
|
||||
|
||||
def blocked_read():
|
||||
entered.set()
|
||||
assert release.wait(2.)
|
||||
return next_snapshot
|
||||
|
||||
with mock.patch.object(reader, 'INTERVAL', .001), mock.patch.object(reader, '_read', side_effect=blocked_read):
|
||||
reader.start()
|
||||
try:
|
||||
assert entered.wait(2.)
|
||||
thread = reader._thread
|
||||
reader.start()
|
||||
assert reader._thread is thread
|
||||
for _ in range(1000):
|
||||
assert reader.current is before
|
||||
reader.close()
|
||||
assert not release.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
reader.close()
|
||||
assert reader._thread is not None
|
||||
reader._thread.join(2.)
|
||||
assert not reader._thread.is_alive()
|
||||
assert reader.current is before
|
||||
|
||||
|
||||
def test_cached_preferences_reach_existing_owners_without_revalidation_each_tick():
|
||||
with OpenpilotPrefix():
|
||||
params = Params()
|
||||
reader = LiveSteeringPreferences(params)
|
||||
centering = lane_runtime.LaneCenteringHost(params, settings_reader=lambda: reader.current.lane_centering)
|
||||
policy = lane_change_preferences.LiveLaneChangePolicy(params, now_ns=1_000_000_000,
|
||||
settings_reader=lambda: reader.current.lane_change)
|
||||
with mock.patch.object(lane_change_preferences, 'effective', wraps=lane_change_preferences.effective) as validate:
|
||||
for tick in range(200):
|
||||
now = 1_000_000_001 + tick * 10_000_000
|
||||
centering.sample(Frame(now), now_ns=now, lateral_active=True, longitudinal_active=False)
|
||||
policy.sample(now)
|
||||
assert validate.call_count == 0
|
||||
changed = replace(reader.current.lane_change, policy=replace(policy.applied, auto_lane_change=True))
|
||||
reader.current = replace(reader.current, lane_change=changed)
|
||||
assert policy.sample(4_000_000_000).auto_lane_change
|
||||
assert validate.call_count == 1
|
||||
reader.current = replace(reader.current, lane_change=replace(changed, readable=False))
|
||||
assert not policy.sample(4_000_000_001, signaling=True, maneuver_active=True).auto_lane_change
|
||||
assert validate.call_count == 1
|
||||
assert not policy.sample(0).enabled
|
||||
reader.current = replace(reader.current, lane_change=changed)
|
||||
assert policy.sample(5_000_000_000).auto_lane_change
|
||||
|
||||
|
||||
def test_live_reader_uses_existing_validation_for_each_completed_refresh():
|
||||
with OpenpilotPrefix():
|
||||
params = Params()
|
||||
reader = LiveSteeringPreferences(params)
|
||||
params.put('HighwaySmoothingLevel', 3., block=True)
|
||||
params.put_bool('LaneCentering', True, block=True)
|
||||
params.put('LaneCenterOffset', .1, block=True)
|
||||
Path(params.get_param_path('LaneChangePreferences')).write_bytes(b'not-json')
|
||||
refreshed = reader._read()
|
||||
assert refreshed.highway_gain == .3
|
||||
assert refreshed.lane_centering.enabled
|
||||
assert refreshed.lane_centering.offset_m == .1
|
||||
assert not refreshed.lane_change.valid
|
||||
Path(params.get_param_path('HighwaySmoothingLevel')).write_bytes(b'nan')
|
||||
Path(params.get_param_path('LaneCentering')).write_bytes(b'bad')
|
||||
invalid = reader._read()
|
||||
assert invalid.highway_gain == 1.
|
||||
assert not invalid.lane_centering.enabled
|
||||
|
||||
|
||||
def test_control_main_starts_reader_after_scheduling_and_closes_on_exit():
|
||||
from openpilot.selfdrive.controls import controlsd
|
||||
|
||||
events = []
|
||||
preferences = mock.Mock()
|
||||
preferences.start.side_effect = lambda: events.append('start')
|
||||
preferences.close.side_effect = lambda: events.append('close')
|
||||
controls = mock.Mock(live_steering_preferences=preferences)
|
||||
controls.run.side_effect = KeyboardInterrupt
|
||||
with mock.patch.object(controlsd, 'config_realtime_process'), mock.patch.object(controlsd, 'Controls', return_value=controls), \
|
||||
mock.patch.object(controlsd.HARDWARE, 'get_device_type', return_value='pc'), \
|
||||
mock.patch.object(controlsd, 'set_core_affinity', side_effect=lambda cpus: events.append('affinity')):
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
controlsd.main()
|
||||
assert events == ['affinity', 'start', 'close']
|
||||
|
||||
|
||||
def test_completed_background_refresh_reaches_the_control_snapshot():
|
||||
with OpenpilotPrefix():
|
||||
reader = LiveSteeringPreferences(Params())
|
||||
refreshed = replace(reader.current, highway_gain=.7)
|
||||
pause = threading.Event()
|
||||
with mock.patch.object(reader, 'INTERVAL', .001), mock.patch.object(reader, '_read', return_value=refreshed):
|
||||
reader.start()
|
||||
try:
|
||||
deadline = time.monotonic() + 2.
|
||||
while reader.current is not refreshed and time.monotonic() < deadline:
|
||||
pause.wait(.001)
|
||||
assert reader.current is refreshed
|
||||
finally:
|
||||
reader.close()
|
||||
assert reader._thread is not None
|
||||
reader._thread.join(2.)
|
||||
assert not reader._thread.is_alive()
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "fdacc6bb8551f060aba4ace2018146ac03ecf2cc2fdf5afff14fe626a5d9aa63", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "da0f2e36a330c0f967081f44ebd4c78e32444aa3aa386bb9cad8435e2f470cd7", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user