diff --git a/openpilot/common/libcommon.a b/openpilot/common/libcommon.a index d8987c54cb..de778a2215 100644 Binary files a/openpilot/common/libcommon.a and b/openpilot/common/libcommon.a differ diff --git a/openpilot/common/libparams_c.so b/openpilot/common/libparams_c.so index e79473cf1b..ecef29dc41 100755 Binary files a/openpilot/common/libparams_c.so and b/openpilot/common/libparams_c.so differ diff --git a/openpilot/common/params_keys.h b/openpilot/common/params_keys.h index e723854345..26797a53bc 100644 --- a/openpilot/common/params_keys.h +++ b/openpilot/common/params_keys.h @@ -381,6 +381,7 @@ inline static std::unordered_map keys = { {"SafeMode", {PERSISTENT, BOOL, "0"}}, {"CurveSpeedController", {PERSISTENT | DONT_LOG, BOOL, "0"}}, {"CurveSpeedControllerNoLead", {PERSISTENT | DONT_LOG, BOOL, "0"}}, + {"GentleCurveSlowdown", {PERSISTENT | DONT_LOG, BOOL, "1"}}, {"ShowCSCStatus", {PERSISTENT | DONT_LOG, BOOL, "0"}}, {"CurvatureData", {PERSISTENT | DONT_LOG, JSON}}, {"CurveComfortData", {PERSISTENT | DONT_LOG, JSON}}, diff --git a/openpilot/selfdrive/controls/lib/curve_speed.py b/openpilot/selfdrive/controls/lib/curve_speed.py new file mode 100644 index 0000000000..99099a7bdb --- /dev/null +++ b/openpilot/selfdrive/controls/lib/curve_speed.py @@ -0,0 +1,29 @@ +import numpy as np + +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY + +MAX_LAT_ACCEL = 2.8 +MAX_ACCEL_OFFSET = 0.5 +MAX_OFFSET_JERK = 0.5 +LOOKAHEAD_TIME = 6.0 + + +class CurveSpeed: + def __init__(self, dt): + self.dt = dt + self.accel_offset = 0.0 + + def reset(self): + self.accel_offset = 0.0 + + def update(self, model, roll): + target = 0.0 + for t, v, yaw_rate in zip(model.position.t, model.velocity.x, model.orientationRate.z, strict=False): + # lat_accel = v * yaw_rate - ACCELERATION_DUE_TO_GRAVITY * (roll + predicted_roll) + lat_accel = v * yaw_rate - ACCELERATION_DUE_TO_GRAVITY * roll + if t < LOOKAHEAD_TIME and abs(lat_accel) >= MAX_LAT_ACCEL: + target = -MAX_ACCEL_OFFSET + break + max_step = MAX_OFFSET_JERK * self.dt + self.accel_offset = float(np.clip(target, self.accel_offset - max_step, self.accel_offset + max_step)) + return self.accel_offset diff --git a/openpilot/selfdrive/controls/lib/longitudinal_planner.py b/openpilot/selfdrive/controls/lib/longitudinal_planner.py index dfac9c368b..d02b823d42 100755 --- a/openpilot/selfdrive/controls/lib/longitudinal_planner.py +++ b/openpilot/selfdrive/controls/lib/longitudinal_planner.py @@ -14,6 +14,7 @@ from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.realtime import DT_MDL from openpilot.selfdrive.modeld.constants import ModelConstants from openpilot.selfdrive.controls.lib.accel_boost import AccelBoost +from openpilot.selfdrive.controls.lib.curve_speed import CurveSpeed from openpilot.selfdrive.controls.lib.personality_accel_boost import PersonalityAccelBoost from openpilot.starpilot.longitudinal.encouragement import Encouragement from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState @@ -150,6 +151,8 @@ class LongitudinalPlanner: self.clock_ns = clock_ns self.allow_throttle = True self.accel_boost = AccelBoost() + self.curve_speed = CurveSpeed(dt) + self.gentle_curve_slowdown = True self.personality_accel_boost = PersonalityAccelBoost(dt) self.personality_boost_scale = 1.0 self.encouragement = Encouragement() @@ -206,6 +209,7 @@ class LongitudinalPlanner: self.previous_manual_cruise_kph = None self.manual_cruise_step_until_ns = 0 self.model_lead_history.clear() + self.curve_speed.reset() self.plan_drive_id = drive_id model_y_no_lead_takeoff = (faster_lead_takeoff and self.CP.carFingerprint == 'TESLA_MODEL_Y' and not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))) @@ -561,10 +565,22 @@ class LongitudinalPlanner: e2e_active = sm['selfdriveState'].experimentalMode personality = sm['selfdriveState'].personality relaxed = personality == log.LongitudinalPersonality.relaxed + curve_offset = 0.0 + roll = sm['vehicleParameters'].roll + if (self.gentle_curve_slowdown and e2e_active and self.CP.openpilotLongitudinalControl and not reset_state and + sm['selfdriveState'].enabled and sm['carControl'].longActive and curve.effective_mps is None and not sm['controlsState'].forceDecel and + not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and + not (output_should_stop_mpc or output_should_stop_e2e or cruise_should_stop) and + cs.canValid and not cs.canTimeout and not cs.gasPressed and not cs.brakePressed and math.isfinite(roll) and + all(fresh_service(sm, name, drive_id, sample_now_ns) for name in ('modelV2', 'vehicleParameters'))): + curve_offset = self.curve_speed.update(sm['modelV2'], roll) + else: + self.curve_speed.reset() + boost_blocked = ( not e2e_active or not profile_eligible or reset_state or self.fcw or not self.allow_throttle or self.force_stop_plan.forcing or output_should_stop_mpc or output_should_stop_e2e or cruise_should_stop or self.mpc.solution_status != 0 or - curve.effective_mps is not None or traffic_mode is None or sm['controlsState'].forceDecel or + curve.effective_mps is not None or curve_offset < 0.0 or traffic_mode is None or sm['controlsState'].forceDecel or not cs.canValid or cs.canTimeout or cs.gasPressed or cs.brakePressed or not all(getattr(sm, health, {}).get(service, False) for health in ('alive', 'valid', 'freq_ok') for service in ('modelV2', 'carState', 'radarState')) @@ -584,7 +600,7 @@ class LongitudinalPlanner: scale = self.personality_boost_scale if output_a_target_e2e > 0.0 else min(self.personality_boost_scale, 1.0) encouraged_model = output_a_target_e2e + scale * (boosted_model - output_a_target_e2e) manual_model = self.accel_boost.update(sm, output_a_target_e2e, output_a_target_mpc, self.a_cruise) - output_a_target_e2e = max(manual_model, encouraged_model) + output_a_target_e2e = output_a_target_e2e + curve_offset if curve_offset < 0.0 else max(manual_model, encouraged_model) candidates = [(output_a_target_mpc, self.mpc.source, output_should_stop_mpc), (self.a_cruise, LongitudinalPlanSource.cruise, cruise_should_stop)] @@ -634,7 +650,7 @@ class LongitudinalPlanner: takeoff_frame = project_takeoff( sm, self.CP, now_ns=sample_now_ns, drive_id=takeoff_drive_id, stop_plan=self.force_stop_plan, acceleration_max=takeoff_max, mpc_accel=output_a_target_mpc, follow_seconds=float(self.mpc.params[0, 4]), - blocked=bool(reset_state or self.fcw or not self.allow_throttle or traffic_mode is not False or + blocked=bool(reset_state or self.fcw or not self.allow_throttle or traffic_mode is not False or curve_offset < 0.0 or self.mpc.solution_status != 0)) output_a_target, self.output_should_stop = self.lead_takeoff.step( True, takeoff_frame, output_a_target, self.output_should_stop) diff --git a/openpilot/selfdrive/controls/plannerd.py b/openpilot/selfdrive/controls/plannerd.py index 7c96f982c8..772f219cfb 100755 --- a/openpilot/selfdrive/controls/plannerd.py +++ b/openpilot/selfdrive/controls/plannerd.py @@ -558,6 +558,7 @@ def starpilot_main(): drive_id=current_start_ns, follow_seconds=follow_seconds, traffic_mode=traffic_mode, takeoff_enabled=faster_lead_takeoff) speed_nudge = nudge_preferences.sample(now_ns) + longitudinal_planner.gentle_curve_slowdown = nudge_preferences.gentle_curve_slowdown personality = "traffic" if traffic_mode is True else str(sm["selfdriveState"].personality) longitudinal_planner.personality_boost_scale = nudge_preferences.boost_scales.get(personality, 1.0) curve_result = update_curve_frame(longitudinal_planner, sm, CP, now_ns, host=curve_host, diff --git a/openpilot/starpilot/curve_speed/preferences.py b/openpilot/starpilot/curve_speed/preferences.py index 4d3ba538d0..3d5f690fdb 100644 --- a/openpilot/starpilot/curve_speed/preferences.py +++ b/openpilot/starpilot/curve_speed/preferences.py @@ -18,6 +18,7 @@ DOCUMENT_KEY = 'CurveComfortData' LEGACY_KEY = 'CurvatureData' MASTER_KEY = 'CurveSpeedController' NO_LEAD_KEY = 'CurveSpeedControllerNoLead' +GENTLE_KEY = 'GentleCurveSlowdown' DOCUMENT_LIMIT = 32768 REFRESH_NS = 1_000_000_000 diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index 14134543d2..516c114ba4 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -85,6 +85,7 @@ DESCRIPTIONS = { 'profile:global_braking': 'Chooses the braking response used by personalities set to Use global preset.', 'reset_profiles': 'Restores the default acceleration, braking and following curves and presets.', 'CurveSpeedController': 'Adjusts cruise speed for curves ahead using available learned cornering preferences.', + 'GentleCurveSlowdown': 'Gently slows for curves in End to End when Curve Speed Controller has no speed target.', 'CurveSpeedControllerNoLead': 'Pauses curve-speed adjustments while following a lead vehicle.', 'ShowCSCStatus': 'Shows when Curve Speed Controller is adjusting speed on the driving screen.', 'curve_reset': 'Deletes saved cornering learning so Curve Speed Controller can learn your preferences again.', diff --git a/openpilot/starpilot/galaxy/tests/description-key-inventory.json b/openpilot/starpilot/galaxy/tests/description-key-inventory.json index 1b4ec12f42..7d59adb5cd 100644 --- a/openpilot/starpilot/galaxy/tests/description-key-inventory.json +++ b/openpilot/starpilot/galaxy/tests/description-key-inventory.json @@ -38,6 +38,7 @@ "ForceAutoTuneOff", "ForceStopDistanceOffset", "ForceStops", + "GentleCurveSlowdown", "FordHighSpeedDampening_ang", "FordHighSpeedFactor_ang", "FordLowSpeedFactor_ang", diff --git a/openpilot/starpilot/galaxy/tests/test_settings.py b/openpilot/starpilot/galaxy/tests/test_settings.py index 283d2eb24f..d0f4c38471 100644 --- a/openpilot/starpilot/galaxy/tests/test_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_settings.py @@ -843,6 +843,15 @@ class SettingsGatewayTest(SettingsGatewayFixture): self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation)) self.assertEqual(decode(manual.read_bytes()), SavedCodes()) + def test_gentle_curve_defaults_on_independently_of_the_learned_controller(self): + page = self.page("curve") + index = next(i for i, row in enumerate(page["rows"]) if row["label"] == "Gentle Curve Slowdown") + self.assertEqual(page["rows"][index]["value"], "On") + self.assertFalse(self.params.get_bool("CurveSpeedController")) + intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value="Off") + self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation)) + self.assertFalse(self.params.get_bool("GentleCurveSlowdown")) + def test_curve_page_uses_one_use_source_bound_long_intent(self): page = self.page("curve") index = next(i for i, row in enumerate(page["rows"]) if row["label"] == "Curve Speed Controller") diff --git a/openpilot/starpilot/longitudinal/encouragement.py b/openpilot/starpilot/longitudinal/encouragement.py index 81d92cd5b6..9c2cbcca35 100644 --- a/openpilot/starpilot/longitudinal/encouragement.py +++ b/openpilot/starpilot/longitudinal/encouragement.py @@ -2,6 +2,7 @@ import math +from openpilot.starpilot.curve_speed.preferences import GENTLE_KEY from openpilot.starpilot.saved_source import read_saved KEY = "ExperimentalSpeedNudge" @@ -82,6 +83,7 @@ class NudgePreferences: def __init__(self, params): self.params = params self.enabled = False + self.gentle_curve_slowdown = True self.boost_scales = dict.fromkeys(BOOST_KEYS, 1.0) self.next_ns = 0 self.last_ns = 0 @@ -97,6 +99,11 @@ class NudgePreferences: self.enabled = readable and raw == b'1' except (OSError, RuntimeError, TypeError, ValueError): self.enabled = False + try: + raw, readable = read_saved(self.params, GENTLE_KEY, 8) + self.gentle_curve_slowdown = readable and raw in (None, b'1') + except (OSError, RuntimeError, TypeError, ValueError): + self.gentle_curve_slowdown = False for name, key in BOOST_KEYS.items(): try: raw, readable = read_saved(self.params, key, 16) diff --git a/openpilot/starpilot/longitudinal/tests/test_encouragement.py b/openpilot/starpilot/longitudinal/tests/test_encouragement.py index 2c957197d8..eb4a676aa0 100644 --- a/openpilot/starpilot/longitudinal/tests/test_encouragement.py +++ b/openpilot/starpilot/longitudinal/tests/test_encouragement.py @@ -425,13 +425,16 @@ def test_speed_nudge_preference_defaults_off_and_rejects_invalid_sources(raw, re preferences = NudgePreferences(Mock(get_default_value=lambda _: 100.)) assert preferences.sample(1_000_000_000) is enabled assert preferences.sample(1_500_000_000) is enabled - assert read.call_count == 5 + assert read.call_count == 6 + assert preferences.gentle_curve_slowdown is (readable and raw in (None, b"1")) read.return_value = (b'0', True) assert not preferences.sample(2_000_000_000) - assert read.call_count == 10 + assert read.call_count == 12 + assert not preferences.gentle_curve_slowdown read.return_value = (b'1', True) assert preferences.sample(500_000_000) - assert read.call_count == 15 + assert read.call_count == 18 + assert preferences.gentle_curve_slowdown @pytest.mark.parametrize('factory,car', [(HondaInterface, HONDA.HONDA_CIVIC), diff --git a/openpilot/starpilot/longitudinal/tests/test_model_lead_trajectory.py b/openpilot/starpilot/longitudinal/tests/test_model_lead_trajectory.py index 244aa5507e..c52504ba1d 100644 --- a/openpilot/starpilot/longitudinal/tests/test_model_lead_trajectory.py +++ b/openpilot/starpilot/longitudinal/tests/test_model_lead_trajectory.py @@ -6,6 +6,7 @@ from opendbc.car.honda.interface import CarInterface from opendbc.car.honda.values import CAR from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib import long_mpc as m +from openpilot.starpilot.longitudinal.cruise_ceiling import CurveCeiling from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import messages NOW = 100_000_000_000 @@ -16,6 +17,7 @@ class Inputs(dict): super().__init__(data) self.valid = dict.fromkeys(data, True) self.alive = dict(self.valid) + self.seen = dict(self.valid) self.freq_ok = dict(self.valid) self.logMonoTime = dict.fromkeys(data, NOW) self.recv_time = dict.fromkeys(data, NOW / 1e9) @@ -162,6 +164,37 @@ class TestModelLeadTrajectory(unittest.TestCase): self.assertFalse(boost.called) self.assertEqual(planner.personality_accel_boost.bias_filter.x, 0.0) + def test_gentle_curve_slowdown_without_star_pilot_target(self): + sm, _ = inputs() + sm['radarState'].leadOne.present = sm['radarState'].leadTwo.present = False + sm['selfdriveState'].experimentalMode = True + sm['modelV2'].action.desiredAcceleration = .1 + sm['modelV2'].position.t = [0., 10.] + sm['modelV2'].position.x = [0., 250.] + sm['modelV2'].orientationRate.z = [.2] + planner = self.planner() + planner.personality_boost_scale = 2.0 + for frame in range(21): + now = NOW + frame * 50_000_000 + sm.logMonoTime.update(dict.fromkeys(sm, now)) + sm.recv_time.update(dict.fromkeys(sm, now / 1e9)) + planner.update(sm, now_ns=now, drive_id=NOW - 1_000_000_000) + if frame == 0: + self.assertAlmostEqual(planner.curve_speed.accel_offset, -.025) + self.assertAlmostEqual(planner.curve_speed.accel_offset, -.5) + self.assertAlmostEqual(planner.output_a_target, -.4) + planner.update(sm, now_ns=now, drive_id=NOW - 1_000_000_000, curve_ceiling=CurveCeiling(19., now)) + self.assertEqual(planner.last_curve_ceiling_status, "selected") + self.assertEqual(planner.curve_speed.accel_offset, 0.) + sm.seen['vehicleParameters'] = False + planner.update(sm, now_ns=now, drive_id=NOW - 1_000_000_000) + self.assertEqual(planner.curve_speed.accel_offset, 0.) + sm.seen['vehicleParameters'] = True + planner.gentle_curve_slowdown = False + planner.update(sm, now_ns=now, drive_id=NOW - 1_000_000_000) + self.assertEqual(planner.curve_speed.accel_offset, 0.) + self.assertGreater(planner.output_a_target, -.4) + def test_actual_planner_scales_only_the_automatic_extra_acceleration(self): for personality in ('standard', 'aggressive'): outputs = [] diff --git a/openpilot/starpilot/ui/feature_defaults.py b/openpilot/starpilot/ui/feature_defaults.py index 21763d7887..b351764c43 100644 --- a/openpilot/starpilot/ui/feature_defaults.py +++ b/openpilot/starpilot/ui/feature_defaults.py @@ -1,7 +1,7 @@ """Default values and numeric bounds for saved driving settings.""" from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET -from openpilot.starpilot.curve_speed.preferences import MASTER_KEY as CURVE_MASTER_KEY, NO_LEAD_KEY as CURVE_NO_LEAD_KEY +from openpilot.starpilot.curve_speed.preferences import GENTLE_KEY, MASTER_KEY as CURVE_MASTER_KEY, NO_LEAD_KEY as CURVE_NO_LEAD_KEY from openpilot.starpilot.lateral.lane_centering import STRENGTH_MAX from openpilot.starpilot.longitudinal.downhill_coast import KEY as DOWNHILL_KEY, SURPLUS_KEY, MAX_SURPLUS_MPH from openpilot.starpilot.longitudinal.encouragement import BOOST_KEYS, MAX_BOOST_PERCENT, KEY as NUDGE_KEY @@ -38,7 +38,7 @@ BOOL_DEFAULTS = { LOW_SPEED_CRUISE_ON_SET: False, "DisengageOnAccelerator": False, AGGRESSIVE_COOLING_KEY: False, - CURVE_MASTER_KEY: False, CURVE_NO_LEAD_KEY: False, + CURVE_MASTER_KEY: False, CURVE_NO_LEAD_KEY: False, GENTLE_KEY: True, "ShowCSCStatus": False, "ForceAutoTuneOff": False, "AlwaysOnLateral": True, "NostalgiaMode": False, } diff --git a/openpilot/starpilot/ui/feature_settings_owner.py b/openpilot/starpilot/ui/feature_settings_owner.py index d78bfc9207..f536c68d51 100644 --- a/openpilot/starpilot/ui/feature_settings_owner.py +++ b/openpilot/starpilot/ui/feature_settings_owner.py @@ -83,7 +83,7 @@ from openpilot.starpilot.panda_wake import KEYS as PANDA_WAKE_KEYS from openpilot.starpilot.saved_document import commit_exact from openpilot.starpilot.curve_speed.preferences import ( DOCUMENT_KEY as CURVE_DOCUMENT_KEY, LEGACY_KEY as CURVE_LEGACY_KEY, - MASTER_KEY as CURVE_MASTER_KEY, NO_LEAD_KEY as CURVE_NO_LEAD_KEY, + MASTER_KEY as CURVE_MASTER_KEY, NO_LEAD_KEY as CURVE_NO_LEAD_KEY, GENTLE_KEY, DOCUMENT_LIMIT as CURVE_DOCUMENT_LIMIT, read_learning, ) from openpilot.starpilot.curve_speed.actions import ACTION_KEYS as CURVE_ACTION_KEYS, apply_learning, learning_snapshot @@ -114,7 +114,7 @@ TORQUE_NUMBERS = LEGACY_KEYS LANE_LIVE_KEYS = frozenset(("LaneCentering", "LaneCenteringPauseOnSignal", "LaneCenterOffset", "LaneCenteringE2EAuthority", "LaneCenteringStrength")) CURVE_KEYS = frozenset((CURVE_MASTER_KEY, CURVE_NO_LEAD_KEY)) -CURVE_PAGE_KEYS = CURVE_KEYS | {"ShowCSCStatus"} +CURVE_PAGE_KEYS = CURVE_KEYS | {"ShowCSCStatus", GENTLE_KEY} class FeatureSettingsOwner: @@ -1021,6 +1021,8 @@ class FeatureSettingsOwner: "Invalid saved learning" if not learning.valid else "Pauses curve speed adjustments while following a lead vehicle" if allowed else "Unavailable with the current vehicle or feature settings")) + rows.append(self._bool_row(GENTLE_KEY, "Gentle Curve Slowdown", allowed, + reason="Gently slows for curves in End to End when Curve Speed Controller has no speed target")) rows.append(self._bool_row("ShowCSCStatus", "Show Curve status", allowed, reason="Display preference only; it does not enable control")) rows.append(FeatureRow("", "Saved learning", "Valid" if learning.valid else "Unavailable", diff --git a/prebuilt.json b/prebuilt.json index a8c3fa6b9a..50f0f4779d 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "340895f2a58fca3ddac4c6dc616b865ffb6b99b20863299982f9266dc8b95bfd", "schema_version": 1} +{"protected_inventory_sha256": "07c51e7bd1d8042b6c270c807d112794fbbd93261ba17c82fa9a02cefd262e8c", "schema_version": 1}