Add Coast Downhills to Long Planner

This commit is contained in:
firestar5683
2026-11-23 12:33:37 -06:00
parent 777df8f6d8
commit 3fa425f769
13 changed files with 222 additions and 10 deletions
Binary file not shown.
Binary file not shown.
+2
View File
@@ -90,6 +90,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"ForceStopDistanceOffset", {PERSISTENT, INT, "0"}},
{"LeadApproachBuffer", {PERSISTENT, BOOL, "0"}},
{"FasterLeadTakeoff", {PERSISTENT, BOOL, "0"}},
{"CoastDownhills", {PERSISTENT, BOOL, "0"}},
{"DownhillSpeedSurplus", {PERSISTENT, FLOAT, "0.0"}},
{"SwitchbackModeCooldown", {PERSISTENT, FLOAT, "5.0"}},
{"CustomCruise", {PERSISTENT, FLOAT, "1.0"}},
{"CustomCruiseLong", {PERSISTENT, FLOAT, "5.0"}},
@@ -29,6 +29,8 @@ from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling, Curve
from openpilot.starpilot.longitudinal.profile_runtime import (AppliedProfile, ProfileSmoother, ProfileTuning, SelectedProfileTuning,
TRAFFIC_CRUISE_BRAKE_MAGNITUDE)
from openpilot.starpilot.longitudinal.slc_coast import braking_lead_relevant
from openpilot.starpilot.longitudinal.downhill_coast import speed_error as downhill_speed_error
from openpilot.starpilot.conditional_mode.ui_action import current_authority, fresh_service
from openpilot.starpilot.longitudinal.throttle_gate import ModelThrottleGate
from openpilot.starpilot.longitudinal.ioniq6_start import eligible as ioniq6_long_eligible
from openpilot.starpilot.longitudinal.lane_change_gap import LaneChangeGap, project as project_lane_gap
@@ -78,7 +80,7 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
profile: AppliedProfile | None = None,
base_brake_floor: float = A_CRUISE_MIN, selected_acceleration_max: float | None = None, faster_takeoffs: bool = False,
*, a_target_prev: float | None = None, ease_slc_braking: bool = False,
speed_step: bool = False):
speed_step: bool = False, downhill_error: float | None = None):
ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX
max_accel = ceiling if e2e else get_max_accel(v_ego, faster_takeoffs)
if selected_acceleration_max is not None and not e2e:
@@ -101,6 +103,9 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
cruise_min = max(ACCEL_MIN, -profile.cruise_brake_magnitude) if profile is not None else max(ACCEL_MIN, base_brake_floor)
speed_error = v_cruise - v_ego
if downhill_error is not None:
speed_error = downhill_error
max_accel = min(max_accel, 0.)
if not e2e and not faster_takeoffs and v_ego >= MIN_ALLOW_THROTTLE_SPEED and speed_error > 0.:
speed_error /= CRUISE_ACCEL_RESPONSE_TIME
elif ease_slc_braking and speed_error < 0.:
@@ -116,15 +121,16 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
lower = max(lower, min(decel_start, 0.) - SLC_BRAKE_ONSET_JERK * dt)
target_accel = float(np.clip(target_accel, lower, a_cruise_prev + j_cruise * dt))
return float(min(target_accel, max_accel)) if speed_step else target_accel
return float(min(target_accel, max_accel)) if speed_step or downhill_error is not None else target_accel
class LongitudinalPlanner:
def __init__(self, CP, init_v=0.0, init_a=0.0, dt=DT_MDL, clock_ns: Callable[[], int] = time.monotonic_ns, *,
developer_tuning=None, navigation_slowdown_percent: int = DEFAULT_SLOWDOWN_PERCENT):
developer_tuning=None, navigation_slowdown_percent: int = DEFAULT_SLOWDOWN_PERCENT, downhill_surplus_mps: float = 0.):
self.CP = CP
tuning = developer_tuning or {}
self.navigation_slowdown_percent = navigation_slowdown_percent
self.downhill_surplus_mps = downhill_surplus_mps
self.action_delay_override = tuning.get("delay")
self.stop_speed = tuning.get("stop_speed", .3)
self.max_accel_override = tuning.get("max_accel")
@@ -437,6 +443,24 @@ class LongitudinalPlanner:
if preap_acceleration_cap is not None:
selected_acceleration = (preap_acceleration_cap if selected_acceleration is None else
min(selected_acceleration, preap_acceleration_cap))
downhill_error = None
if (self.downhill_surplus_mps > 0. and profile_eligible and not reset_state and self.allow_throttle and
v_cruise == v_cruise_kph * CV.KPH_TO_MS and v_ego >= v_cruise >= 5. and traffic_mode is False and
cruise_ceiling is None and curve_ceiling is None and navigation_target is None and
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting)) and
(wheel_coast is None or not wheel_coast[0].conditional_stop) and
not self.fcw and not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
self.force_stop_plan.approach_distance_m == 0. and not output_should_stop_mpc and not output_should_stop_e2e and
self.mpc.solution_status == 0 and not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))):
cs, orientation = sm['carState'], sm['carControl'].orientationNED
if (len(orientation) == 3 and not (cs.standstill or cs.gasPressed or cs.brakePressed) and
current_authority(sm, self.CP, drive_id, sample_now_ns) and
all(fresh_service(sm, name, drive_id, sample_now_ns) for name in ('radarState', 'modelV2', 'controlsState', 'deviceMotion'))):
limit = min(v_cruise + self.downhill_surplus_mps, V_CRUISE_MAX * CV.KPH_TO_MS)
downhill_error = downhill_speed_error(v_cruise, v_ego, cs.aEgo, orientation[1], limit=limit, delay=action_t)
if downhill_error is not None and navigation_ceiling(
sm, self.CP, sample_now_ns, limit + .25, slowdown_percent=self.navigation_slowdown_percent) is not None:
downhill_error = None
speed_step = False
if self.CP.carFingerprint == 'TESLA_MODEL_Y':
cs = sm['carState']
@@ -467,7 +491,8 @@ class LongitudinalPlanner:
accel_coast, self.allow_throttle, cruise_profile,
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
a_target_prev=self.output_a_target,
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead, speed_step=speed_step)
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead, speed_step=speed_step,
downhill_error=downhill_error)
if self.button_cruise is not None:
button_target = self.button_cruise.sample(
sm, now_ns=sample_now_ns, drive_id=drive_id, target_speed=v_cruise,
@@ -475,7 +500,7 @@ class LongitudinalPlanner:
speed=self.v_desired_filter.x, previous_accel=self.output_a_target, reference=self.mpc,
blocked=bool(reset_state or not profile_eligible or not self.allow_throttle or traffic_mode is not False or self.fcw or
self.force_stop_plan.forcing or self.force_stop_plan.should_stop or output_should_stop_mpc or
sm['modelV2'].action.shouldStop or wheel_coast is not None or
sm['modelV2'].action.shouldStop or wheel_coast is not None or downhill_error is not None or
any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))))
if button_target is not None:
self.a_cruise = button_target
@@ -561,7 +586,7 @@ class LongitudinalPlanner:
output_a_target, self.output_should_stop = self.ford_stop_approach.sample(
sm, now_ns=sample_now_ns, drive_id=drive_id, target=float(output_a_target),
stopping=self.output_should_stop, accel_min=ACCEL_MIN, active=profile_eligible and not reset_state)
self.output_a_target = np.clip(output_a_target, ACCEL_MIN, accel_ceiling)
self.output_a_target = np.clip(output_a_target, ACCEL_MIN, 0. if downhill_error is not None else accel_ceiling)
self.v_desired_filter.x = self.v_desired_filter.x + self.dt * (self.output_a_target + a_prev) / 2.0
+6 -1
View File
@@ -325,6 +325,7 @@ def starpilot_main():
ldw = LaneDepartureWarning()
from openpilot.starpilot.longitudinal.developer_tuning import read_tuning
from openpilot.starpilot.longitudinal.downhill_coast import read_surplus
from openpilot.starpilot.navigation.slowdown import DEFAULT_SLOWDOWN_PERCENT
navigation_slowdown_percent = DEFAULT_SLOWDOWN_PERCENT
if CP.openpilotLongitudinalControl and not CP.passive and not CP.dashcamOnly:
@@ -334,7 +335,8 @@ def starpilot_main():
except (OSError, ValueError):
pass
longitudinal_planner = LongitudinalPlanner(CP, developer_tuning=read_tuning(params, CP),
navigation_slowdown_percent=navigation_slowdown_percent)
navigation_slowdown_percent=navigation_slowdown_percent,
downhill_surplus_mps=read_surplus(params))
nudge_preferences = NudgePreferences(params)
# Saved-on features start only for a finalized, supported driving owner. Their
# current-source and longitudinal authority checks still run every frame.
@@ -398,6 +400,9 @@ def starpilot_main():
subscribed_services.extend(optional_slc)
subscribed_services.append('starpilotNavigation')
optional_conditional = ['starpilotNavigation'] + (['starpilotRadarState'] if conditional_host is not None else []) + optional_slc
if longitudinal_planner.downhill_surplus_mps > 0.:
subscribed_services.append('deviceMotion')
optional_conditional.append('deviceMotion')
sm = messaging.SubMaster(subscribed_services, poll='modelV2',
ignore_alive=optional_conditional, ignore_valid=optional_conditional,
ignore_avg_freq=optional_conditional)
@@ -0,0 +1,29 @@
import math
from openpilot.common.constants import CV
from openpilot.starpilot.saved_source import read_saved
KEY = 'CoastDownhills'
SURPLUS_KEY = 'DownhillSpeedSurplus'
MAX_SURPLUS_MPH = 25
def read_surplus(params) -> float:
try:
if read_saved(params, KEY, 8) != (b'1', True) or read_saved(params, 'SafeMode', 8) not in ((None, True), (b'0', True)):
return 0.
raw, readable = read_saved(params, SURPLUS_KEY, 32)
surplus = float(raw) if raw is not None else 0.
if readable and 0. <= surplus <= MAX_SURPLUS_MPH:
return surplus * CV.MPH_TO_MS
except (OSError, RuntimeError, TypeError, ValueError):
pass
return 0.
def speed_error(set_speed: float, speed: float, accel: float, pitch: float, *, limit: float, delay: float) -> float | None:
if (not all(map(math.isfinite, (set_speed, speed, accel, pitch, limit, delay))) or
not 0. < set_speed < limit or speed < set_speed or not -math.radians(20.) <= pitch <= -math.atan(.02)):
return None
# Only delay cruise braking. Never create positive speed error or chase the allowance.
return min(0., limit - (speed + max(0., accel) * max(0., delay)))
@@ -0,0 +1,107 @@
from pathlib import Path
from types import SimpleNamespace
import math
import pytest
from openpilot.common.constants import CV
from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner
from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling, CurveCeiling
from openpilot.starpilot.longitudinal.downhill_coast import KEY, SURPLUS_KEY, read_surplus, speed_error
from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import ACTIVE, messages, snapshot
from opendbc.car.honda.interface import CarInterface
from opendbc.car.honda.values import CAR
SET_SPEED = 30 * CV.MPH_TO_MS
LIMIT = 35 * CV.MPH_TO_MS
NOW = 5_000_000_000
DRIVE = 1_000_000_000
def test_saved_defaults_and_invalid_values(tmp_path: Path):
params = SimpleNamespace(get_param_path=lambda key: tmp_path / key)
assert read_surplus(params) == 0.
(tmp_path / KEY).write_bytes(b'1')
for raw, expected in ((b'25.000000', 25 * CV.MPH_TO_MS), (b'0', 0.), (b'-1', 0.),
(b'25.1', 0.), (b'nan', 0.), (b'inf', 0.), (b'bad', 0.)):
(tmp_path / SURPLUS_KEY).write_bytes(raw)
assert read_surplus(params) == expected
(tmp_path / SURPLUS_KEY).write_bytes(b'5')
(tmp_path / 'SafeMode').write_bytes(b'1')
assert read_surplus(params) == 0.
(tmp_path / 'SafeMode').unlink()
(tmp_path / KEY).write_bytes(b'0')
assert read_surplus(params) == 0.
def test_gravity_only_allowance_and_approach_to_limit():
def error(speed, pitch=-.05, accel=.3, limit=LIMIT):
return speed_error(SET_SPEED, speed, accel, pitch, limit=limit, delay=.25)
assert error(SET_SPEED - .1) is None
assert error(SET_SPEED + 1) == 0.
assert error(LIMIT) == pytest.approx(-.075)
assert error(LIMIT + 1) == pytest.approx(-1.075)
assert error(SET_SPEED + 1, pitch=.05) is None
assert error(SET_SPEED + 1, pitch=0.) is None
assert error(SET_SPEED + 1, pitch=math.nan) is None
assert error(SET_SPEED + 1, limit=SET_SPEED) is None
class Frame(dict):
def __init__(self, **kwargs):
data, _ = messages(**kwargs)
super().__init__(data, deviceState=SimpleNamespace(started=True, startedMonoTime=DRIVE), deviceMotion=SimpleNamespace())
self['carState'].vCruise = SET_SPEED / CV.KPH_TO_MS
self['carState'].vEgo = SET_SPEED + 1.
self['carState'].canValid = True
self['carControl'].enabled = True
self['carControl'].longActive = True
self['carControl'].orientationNED = [0., -.05, 0.]
self.seen = dict.fromkeys(self, True)
self.alive = self.seen.copy()
self.valid = self.seen.copy()
self.logMonoTime = dict.fromkeys(self, NOW - 20_000_000)
self.recv_time = dict.fromkeys(self, (NOW - 20_000_000) / 1e9)
@pytest.mark.parametrize('case', ['clear', 'above-limit', 'lead', 'stop', 'force', 'slc', 'curve', 'navigation',
'stale', 'flat', 'driver', 'below-set'])
def test_planner_only_relaxes_ordinary_cruise_braking(case, monkeypatch):
cp = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC)
frame = Frame(lead=case == 'lead', e2e=case == 'stop', force=case == 'force')
options = {}
if case == 'above-limit':
frame['carState'].vEgo = LIMIT + 1.
elif case == 'slc':
options['cruise_ceiling'] = CruiseCeiling(SET_SPEED + .5, ACTIVE)
elif case == 'curve':
options['curve_ceiling'] = CurveCeiling(SET_SPEED + .5, frame.logMonoTime['modelV2'])
elif case == 'navigation':
from openpilot.selfdrive.controls.lib import longitudinal_planner
# A navigation approach can be above SET but below the downhill allowance.
monkeypatch.setattr(longitudinal_planner, 'navigation_ceiling',
lambda *args, **kwargs: SET_SPEED + .5 if args[3] > SET_SPEED + .75 else None)
elif case == 'stale':
frame.logMonoTime['deviceMotion'] = NOW - 500_000_000
elif case == 'flat':
frame['carControl'].orientationNED = [0., 0., 0.]
elif case == 'driver':
frame['carState'].gasPressed = True
elif case == 'below-set':
frame['carState'].vEgo = SET_SPEED - 1.
speed = float(frame['carState'].vEgo)
normal = LongitudinalPlanner(cp, init_v=speed, init_a=.7)
coast = LongitudinalPlanner(cp, init_v=speed, init_a=.7, downhill_surplus_mps=5 * CV.MPH_TO_MS)
for _ in range(30):
normal.update(frame, now_ns=NOW, drive_id=DRIVE, **options)
coast.update(frame, now_ns=NOW, drive_id=DRIVE, **options)
assert coast.mpc.solution_status == normal.mpc.solution_status == 0
if case in ('clear', 'above-limit'):
assert coast.a_cruise <= 0.
assert coast.output_a_target <= 0.
else:
assert snapshot(coast) == snapshot(normal)
if case == 'clear':
assert normal.a_cruise < coast.a_cruise == 0.
elif case == 'above-limit':
assert coast.output_a_target < 0.
@@ -27,6 +27,7 @@ from openpilot.starpilot.longitudinal.profile_runtime import TRAFFIC_CRUISE_BRAK
from openpilot.starpilot.longitudinal.lead_approach_runtime import KEY as LEAD_APPROACH_KEY
from openpilot.starpilot.longitudinal.lead_takeoff_preferences import KEY as LEAD_TAKEOFF_KEY
from openpilot.starpilot.longitudinal.encouragement import KEY as NUDGE_KEY
from openpilot.starpilot.longitudinal.downhill_coast import KEY as DOWNHILL_KEY, SURPLUS_KEY, MAX_SURPLUS_MPH
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET
from openpilot.starpilot.longitudinal.planner_selection import KEY as PLANNER_SELECTION_KEY, save_selection
@@ -116,6 +117,7 @@ BOOL_DEFAULTS = {
"CustomPersonalities": False, PLANNER_SELECTION_KEY: True,
LEAD_APPROACH_KEY: False,
LEAD_TAKEOFF_KEY: False,
DOWNHILL_KEY: False,
NUDGE_KEY: True,
LOW_SPEED_CRUISE_ON_SET: False,
"DisengageOnAccelerator": False,
@@ -125,6 +127,7 @@ BOOL_DEFAULTS = {
"ForceAutoTuneOff": False, "AlwaysOnLateral": True, "NostalgiaMode": False,
}
FLOAT_SPECS = {
SURPLUS_KEY: (0, MAX_SURPLUS_MPH, 1, "mph"),
"ForceStopDistanceOffset": (-20, 20, 1, "ft"),
"LaneCenterOffset": (-0.3, 0.3, 0.01, "m"),
"LaneCenteringE2EAuthority": (0.0, 1.0, 0.05, "fraction"),
@@ -1288,6 +1291,12 @@ class FeatureSettingsOwner:
rows.append(self._bool_row(NUDGE_KEY, "Experimental Speed Nudge", self.authority("preferences"),
reason="Gently recovers toward set speed when Experimental mode hesitates on a clear road. " +
"Leads, stops, curve limits and driver overrides retain priority."))
downhill_allowed = allowed and self.authority("long") and self._value(PLANNER_SELECTION_KEY)[0] == "1"
downhill = self._bool_row(DOWNHILL_KEY, "Coast Downhills", downhill_allowed,
"Lets gravity carry the car above set speed without targeting a higher speed. Applies next drive.")
rows.append(downhill)
if downhill.value == "On":
rows.append(self._number_row(SURPLUS_KEY, "Maximum Speed Above Set Speed", downhill_allowed))
rows.append(self._bool_row(LOW_SPEED_CRUISE_ON_SET, "Low-Speed Cruise Start", self.authority("preferences"),
reason="Lets StarPilot SET at your current speed down to the vehicle’s minimum engagement speed. " +
"Factory cruise still uses the car’s minimum speed."))
@@ -1601,8 +1610,8 @@ class FeatureSettingsOwner:
group = "long"
elif key in BOOL_DEFAULTS or key in FLOAT_SPECS or key in (*SOURCE_PRIORITY_KEYS, *ADVANCE_KEYS, 'SLCConfirmation', PEDAL_OVERRIDE_KEY):
source_key = key
long_key = (key in ("CustomPersonalities", "ForceStops", "ForceStopDistanceOffset", *DRIVE_MODE_KEYS) or "Personality" in key or
key.endswith(("Follow", "FollowHigh")) or "Jerk" in key)
long_key = (key in ("CustomPersonalities", "ForceStops", "ForceStopDistanceOffset", DOWNHILL_KEY, SURPLUS_KEY, *DRIVE_MODE_KEYS) or
"Personality" in key or key.endswith(("Follow", "FollowHigh")) or "Jerk" in key)
if key in ("ShowSpeedLimits", "AlwaysAllowUploads", *SOURCE_PRIORITY_KEYS) or (key == "ForceStops" and request.value == "Off"):
group = "preferences"
elif key in LANE_LIVE_KEYS and not self.authority("lane"):
@@ -1650,6 +1659,9 @@ class FeatureSettingsOwner:
return False
if key == "ForceStopDistanceOffset" and self._value("ForceStops")[0] != "1" and not (reset_default and float(request.value) == float(self._default(key))):
return False
if key in (DOWNHILL_KEY, SURPLUS_KEY) and (self._value(PLANNER_SELECTION_KEY)[0] != "1" or
key == SURPLUS_KEY and self._value(DOWNHILL_KEY)[0] != "1"):
return False
if key == "reset_profiles":
if not request.confirmation or self._document()[2]:
return False
@@ -0,0 +1,32 @@
from openpilot.common.params import Params
from openpilot.starpilot.longitudinal.downhill_coast import KEY, SURPLUS_KEY, read_surplus
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest, row_change
def test_downhill_toggle_and_slider_share_the_planner_settings(tmp_path):
params = Params(str(tmp_path))
owner = FeatureSettingsOwner(params, lambda group: group in ('long', 'parked_preferences', 'preferences'),
vehicle_fingerprint=lambda: 'TEST_CAR')
def rows():
state = owner.snapshot('profiles', parked=True, system_long=True, lateral_context=False, metric=False)
return {row.key: row for row in state.rows}
initial = rows()
assert initial[KEY].value == 'Off'
assert SURPLUS_KEY not in initial
enable = row_change(initial[KEY])
assert enable is not None and owner.apply(enable)
slider = rows()[SURPLUS_KEY]
assert (float(slider.value), slider.minimum, slider.maximum, slider.step, slider.unit) == (0., 0., 25., 1., 'mph')
assert read_surplus(params) == 0.
assert not owner.apply(FeatureSettingsRequest(SURPLUS_KEY, slider.source, '26', vehicle_fingerprint='TEST_CAR'))
assert owner.apply(FeatureSettingsRequest(SURPLUS_KEY, slider.source, '5', vehicle_fingerprint='TEST_CAR'))
assert read_surplus(params) > 0.
active = rows()
disable = row_change(active[KEY])
assert disable is not None and owner.apply(disable)
assert SURPLUS_KEY not in rows()
assert read_surplus(params) == 0.
assert params.get(SURPLUS_KEY) == 5.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "16907edcddd43ac743045571076e36cf3011e8d04592a0bcf4aba480448bd631", "schema_version": 1}
{"protected_inventory_sha256": "303d07a9384228fed1af4c6bdec713de09b947ca3c594beba35885470061f08f", "schema_version": 1}