Compare commits

...

3 Commits

Author SHA1 Message Date
firestarsdog d2f1afc5e8 Build device artifacts for e8ed60f652
Record fresh outputs from the full ARM64 ./build for the SLC and Dom source
commits, including native libraries, generated C/C++, Panda firmware, and
the updated prebuilt receipt.

Validation:
- AArch64 and QCOM artifact structure checks passed.
- Native Params registry validated all 386 keys.
- The build receipt matches the generated working-tree inventory.

Build completed with non-fatal CasADi version and firmware linker warnings.
Runtime inference and on-road behavior were not tested.
2026-11-10 15:48:14 -05:00
whoisdomi e8ed60f652 Stabilize low-speed steering and force-stop behavior
Consolidates commits authored by whoisdomi:

- 64df004be1 No twitch test?
- 3426045d1e twitch 2
- 2a4676dfca Force Stop fix
- 233a386ab4 twitch 2 fix
- f831010290 force stop edge case
- 00d46b482d Force Stop: use Vision Stop distance
- ec0221c16f twitch 3
- c86a4ac8d6 Force Stop Signs behind leads
- d7d1fa02a1 Twitch 5
- 7e72a4bd8e Force stop fix 2

Keep the model action curvature floor at 2.5 m/s, matching bluescreensonly4.
2026-11-10 13:55:41 -05:00
firestarsdog b90bf86386 Rework speed-limit control, integration, and HUD
Consolidates source, test, documentation, and UI asset changes authored by firestarsdog:

- 5f3ea81785 SLC Squish
- e54b3f9e36 Normalize stopped speeds to preserve SLC overrides
- fc981552b3 Clarify SLC targets and confirmation prompts
- 891454e47c Align speed HUD for clearer SLC prompts
- 4e4d258ad3 Visual Polish + Suppress "LAST" in UI
- 5b896476d6 rm historic adopted speed on engage

Generated device build outputs are recorded separately after the source commits.
2026-11-10 12:02:44 -05:00
240 changed files with 9592 additions and 7574 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5 -1
View File
@@ -360,6 +360,7 @@ class CarController(CarControllerBase):
self.volt_cc_cancel_pending = False self.volt_cc_cancel_pending = False
self.volt_cc_last_cancel_frame = 0 self.volt_cc_last_cancel_frame = 0
self.volt_cc_metric = False self.volt_cc_metric = False
self.volt_cc_speed_ceiling_mps = None
self.volt_cc_last_button_frame = 0 self.volt_cc_last_button_frame = 0
self.volt_cc_last_direction_frame = None self.volt_cc_last_direction_frame = None
self.volt_cc_consumed_source_ns = 0 self.volt_cc_consumed_source_ns = 0
@@ -1396,7 +1397,10 @@ class CarController(CarControllerBase):
self.volt_cc_consumed_source_ns = source_ns self.volt_cc_consumed_source_ns = source_ns
can_sends.append(gmcan.create_buttons(self.packer_pt, CanBus.POWERTRAIN, (CS.buttons_counter + 1) % 4, button)) can_sends.append(gmcan.create_buttons(self.packer_pt, CanBus.POWERTRAIN, (CS.buttons_counter + 1) % 4, button))
elif self.frame % 4 == 0: elif self.frame % 4 == 0:
button, rate = button_request(CS.out.vEgo, CS.out.cruiseState.speed, actuators.accel, CS.out.vCruise, cruise_kph = CS.out.vCruise
if self.volt_cc_speed_ceiling_mps is not None:
cruise_kph = min(cruise_kph, self.volt_cc_speed_ceiling_mps * CV.MS_TO_KPH)
button, rate = button_request(CS.out.vEgo, CS.out.cruiseState.speed, actuators.accel, cruise_kph,
bool(CC.hudControl.leadVisible), self.volt_cc_metric) bool(CC.hudControl.leadVisible), self.volt_cc_metric)
source_ns = physical.button_credit_ns source_ns = physical.button_credit_ns
if ((self.frame - self.volt_cc_last_button_frame) * DT_CTRL > rate and if ((self.frame - self.volt_cc_last_button_frame) * DT_CTRL > rate and
@@ -335,8 +335,8 @@ def test_actual_card_active_observation_requires_fresh_selfdrive_state(monkeypat
host.observe_ioniq6_long_authority = lambda *args: None host.observe_ioniq6_long_authority = lambda *args: None
host.update_vehicle_state_context = lambda *args: None host.update_vehicle_state_context = lambda *args: None
def update_cruise_speed(_state, _pending, *, approved=None): def update_cruise_speed(_state, _pending, *, wheel_context=None):
assert approved is None assert wheel_context is None
host.update_cruise_speed = update_cruise_speed host.update_cruise_speed = update_cruise_speed
host.v_cruise_helper = SimpleNamespace(slc_consumed_button=None, toyota=None) host.v_cruise_helper = SimpleNamespace(slc_consumed_button=None, toyota=None)
host.startup_panda_configured = lambda: True host.startup_panda_configured = lambda: True
@@ -870,7 +870,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
card_owner.is_metric = True card_owner.is_metric = True
card_owner.experimental_mode = False card_owner.experimental_mode = False
card_owner.initial_cruise_speed = 40 card_owner.initial_cruise_speed = 40
card_owner.v_cruise_helper = SimpleNamespace(update_v_cruise=lambda *_, slc_enabled=False, slc_approved=None: None, card_owner.v_cruise_helper = SimpleNamespace(update_v_cruise=lambda *_, slc_enabled=False, wheel_context=None: None,
initialize_v_cruise=lambda *_, **kwargs: None, slc_consumed_button=None, toyota=None, initialize_v_cruise=lambda *_, **kwargs: None, slc_consumed_button=None, toyota=None,
slc_cruise_change=None, v_cruise_kph=60.0, v_cruise_cluster_kph=60.0) slc_cruise_change=None, v_cruise_kph=60.0, v_cruise_cluster_kph=60.0)
card_owner.RI = SimpleNamespace(update=lambda _: None) card_owner.RI = SimpleNamespace(update=lambda _: None)
+7 -1
View File
@@ -339,7 +339,7 @@ struct SlcState @0xa1680744031fdb2d {
hasPendingAdjustedLimit @45 :Bool; hasPendingAdjustedLimit @45 :Bool;
presentationAdjustedLimit @46 :Float32; presentationAdjustedLimit @46 :Float32;
hasPresentationAdjustedLimit @47 :Bool; hasPresentationAdjustedLimit @47 :Bool;
overrideBasis @48 :Text; # none/pedal/persistent; qualified contribution only overrideBasis @48 :Text; # none/pedal/persistent/wheel; qualified contribution only
retainedOverride @49 :Bool; retainedOverride @49 :Bool;
commandActionSequenceId @50 :UInt64; # UI sequence that issued this command commandActionSequenceId @50 :UInt64; # UI sequence that issued this command
automaticAdoptionPending @51 :Bool; automaticAdoptionPending @51 :Bool;
@@ -352,6 +352,10 @@ struct SlcState @0xa1680744031fdb2d {
# Qualified adoption proposal; the current displayed observation stays above. # Qualified adoption proposal; the current displayed observation stays above.
upcomingSpeedLimit @57 :Float32; upcomingSpeedLimit @57 :Float32;
upcomingBoundaryId @58 :Text; upcomingBoundaryId @58 :Text;
acceptedIsPreview @59 :Bool; # a temporary ceiling, ineligible for initializing SET
wheelOverrideSince @60 :UInt64; # nonzero while a wheel tap may cross the current adjusted limit
wheelAdoptMonoTime @61 :UInt64; # Card's original wheel event timestamp, only on the approval frame
wheelAdoptTargetMps @62 :Float32; # exact adjusted SET approved for that event
struct SourceReading { struct SourceReading {
source @0 :Text; source @0 :Text;
enabled @1 :Bool; enabled @1 :Bool;
@@ -453,6 +457,7 @@ struct SlcAction @0x9ccdc8676701b412 {
conditionalManual @5 :ConditionalManualAction; conditionalManual @5 :ConditionalManualAction;
controllerCruise @6 :ControllerCruiseAction; controllerCruise @6 :ControllerCruiseAction;
controllerMode @7 :ControllerCruiseAction; controllerMode @7 :ControllerCruiseAction;
wheelAdoptMonoTime @8 :UInt64; # original timestamp of a qualified Adopt Speed Limit wheel event
struct ControllerCruiseAction { struct ControllerCruiseAction {
version @0 :UInt16; version @0 :UInt16;
@@ -520,6 +525,7 @@ struct SlcCruiseEvent @0xcd96dafb67a082d0 {
trafficMode @13 :TrafficModeGesture; trafficMode @13 :TrafficModeGesture;
wheelAction @14 :SlcAction.ControllerCruiseAction; wheelAction @14 :SlcAction.ControllerCruiseAction;
teslaStockCruise @15 :TeslaStockCruise; teslaStockCruise @15 :TeslaStockCruise;
wheelOverrideSince @16 :UInt64; # SLC eligibility captured by a physical + tap; zero for ordinary SET changes
struct TeslaStockCruise { struct TeslaStockCruise {
version @0 :UInt16; version @0 :UInt16;
File diff suppressed because it is too large Load Diff
+117 -3
View File
@@ -749,7 +749,7 @@ struct SlcState {
struct ConditionalModeState; struct ConditionalModeState;
struct _capnpPrivate { struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(a1680744031fdb2d, 18, 22) CAPNP_DECLARE_STRUCT_HEADER(a1680744031fdb2d, 21, 22)
#if !CAPNP_LITE #if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE #endif // !CAPNP_LITE
@@ -845,7 +845,7 @@ struct SlcAction {
struct _capnpPrivate { struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(9ccdc8676701b412, 4, 4) CAPNP_DECLARE_STRUCT_HEADER(9ccdc8676701b412, 5, 4)
#if !CAPNP_LITE #if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE #endif // !CAPNP_LITE
@@ -897,7 +897,7 @@ struct SlcCruiseEvent {
struct ManualModeGesture; struct ManualModeGesture;
struct _capnpPrivate { struct _capnpPrivate {
CAPNP_DECLARE_STRUCT_HEADER(cd96dafb67a082d0, 7, 6) CAPNP_DECLARE_STRUCT_HEADER(cd96dafb67a082d0, 8, 6)
#if !CAPNP_LITE #if !CAPNP_LITE
static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; } static constexpr ::capnp::_::RawBrandedSchema const* brand() { return &schema->defaultBrand; }
#endif // !CAPNP_LITE #endif // !CAPNP_LITE
@@ -4524,6 +4524,14 @@ public:
inline bool hasUpcomingBoundaryId() const; inline bool hasUpcomingBoundaryId() const;
inline ::capnp::Text::Reader getUpcomingBoundaryId() const; inline ::capnp::Text::Reader getUpcomingBoundaryId() const;
inline bool getAcceptedIsPreview() const;
inline ::uint64_t getWheelOverrideSince() const;
inline ::uint64_t getWheelAdoptMonoTime() const;
inline float getWheelAdoptTargetMps() const;
private: private:
::capnp::_::StructReader _reader; ::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -4817,6 +4825,18 @@ public:
inline void adoptUpcomingBoundaryId(::capnp::Orphan< ::capnp::Text>&& value); inline void adoptUpcomingBoundaryId(::capnp::Orphan< ::capnp::Text>&& value);
inline ::capnp::Orphan< ::capnp::Text> disownUpcomingBoundaryId(); inline ::capnp::Orphan< ::capnp::Text> disownUpcomingBoundaryId();
inline bool getAcceptedIsPreview();
inline void setAcceptedIsPreview(bool value);
inline ::uint64_t getWheelOverrideSince();
inline void setWheelOverrideSince( ::uint64_t value);
inline ::uint64_t getWheelAdoptMonoTime();
inline void setWheelAdoptMonoTime( ::uint64_t value);
inline float getWheelAdoptTargetMps();
inline void setWheelAdoptTargetMps(float value);
private: private:
::capnp::_::StructBuilder _builder; ::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -5669,6 +5689,8 @@ public:
inline bool hasControllerMode() const; inline bool hasControllerMode() const;
inline ::cereal::SlcAction::ControllerCruiseAction::Reader getControllerMode() const; inline ::cereal::SlcAction::ControllerCruiseAction::Reader getControllerMode() const;
inline ::uint64_t getWheelAdoptMonoTime() const;
private: private:
::capnp::_::StructReader _reader; ::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -5737,6 +5759,9 @@ public:
inline void adoptControllerMode(::capnp::Orphan< ::cereal::SlcAction::ControllerCruiseAction>&& value); inline void adoptControllerMode(::capnp::Orphan< ::cereal::SlcAction::ControllerCruiseAction>&& value);
inline ::capnp::Orphan< ::cereal::SlcAction::ControllerCruiseAction> disownControllerMode(); inline ::capnp::Orphan< ::cereal::SlcAction::ControllerCruiseAction> disownControllerMode();
inline ::uint64_t getWheelAdoptMonoTime();
inline void setWheelAdoptMonoTime( ::uint64_t value);
private: private:
::capnp::_::StructBuilder _builder; ::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -6128,6 +6153,8 @@ public:
inline bool hasTeslaStockCruise() const; inline bool hasTeslaStockCruise() const;
inline ::cereal::SlcCruiseEvent::TeslaStockCruise::Reader getTeslaStockCruise() const; inline ::cereal::SlcCruiseEvent::TeslaStockCruise::Reader getTeslaStockCruise() const;
inline ::uint64_t getWheelOverrideSince() const;
private: private:
::capnp::_::StructReader _reader; ::capnp::_::StructReader _reader;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -6228,6 +6255,9 @@ public:
inline void adoptTeslaStockCruise(::capnp::Orphan< ::cereal::SlcCruiseEvent::TeslaStockCruise>&& value); inline void adoptTeslaStockCruise(::capnp::Orphan< ::cereal::SlcCruiseEvent::TeslaStockCruise>&& value);
inline ::capnp::Orphan< ::cereal::SlcCruiseEvent::TeslaStockCruise> disownTeslaStockCruise(); inline ::capnp::Orphan< ::cereal::SlcCruiseEvent::TeslaStockCruise> disownTeslaStockCruise();
inline ::uint64_t getWheelOverrideSince();
inline void setWheelOverrideSince( ::uint64_t value);
private: private:
::capnp::_::StructBuilder _builder; ::capnp::_::StructBuilder _builder;
template <typename, ::capnp::Kind> template <typename, ::capnp::Kind>
@@ -20214,6 +20244,62 @@ inline ::capnp::Orphan< ::capnp::Text> SlcState::Builder::disownUpcomingBoundary
::capnp::bounded<21>() * ::capnp::POINTERS)); ::capnp::bounded<21>() * ::capnp::POINTERS));
} }
inline bool SlcState::Reader::getAcceptedIsPreview() const {
return _reader.getDataField<bool>(
::capnp::bounded<141>() * ::capnp::ELEMENTS);
}
inline bool SlcState::Builder::getAcceptedIsPreview() {
return _builder.getDataField<bool>(
::capnp::bounded<141>() * ::capnp::ELEMENTS);
}
inline void SlcState::Builder::setAcceptedIsPreview(bool value) {
_builder.setDataField<bool>(
::capnp::bounded<141>() * ::capnp::ELEMENTS, value);
}
inline ::uint64_t SlcState::Reader::getWheelOverrideSince() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<18>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcState::Builder::getWheelOverrideSince() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<18>() * ::capnp::ELEMENTS);
}
inline void SlcState::Builder::setWheelOverrideSince( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<18>() * ::capnp::ELEMENTS, value);
}
inline ::uint64_t SlcState::Reader::getWheelAdoptMonoTime() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<19>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcState::Builder::getWheelAdoptMonoTime() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<19>() * ::capnp::ELEMENTS);
}
inline void SlcState::Builder::setWheelAdoptMonoTime( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<19>() * ::capnp::ELEMENTS, value);
}
inline float SlcState::Reader::getWheelAdoptTargetMps() const {
return _reader.getDataField<float>(
::capnp::bounded<40>() * ::capnp::ELEMENTS);
}
inline float SlcState::Builder::getWheelAdoptTargetMps() {
return _builder.getDataField<float>(
::capnp::bounded<40>() * ::capnp::ELEMENTS);
}
inline void SlcState::Builder::setWheelAdoptTargetMps(float value) {
_builder.setDataField<float>(
::capnp::bounded<40>() * ::capnp::ELEMENTS, value);
}
inline bool SlcState::SourceReading::Reader::hasSource() const { inline bool SlcState::SourceReading::Reader::hasSource() const {
return !_reader.getPointerField( return !_reader.getPointerField(
::capnp::bounded<0>() * ::capnp::POINTERS).isNull(); ::capnp::bounded<0>() * ::capnp::POINTERS).isNull();
@@ -21721,6 +21807,20 @@ inline ::capnp::Orphan< ::cereal::SlcAction::ControllerCruiseAction> SlcAction::
::capnp::bounded<3>() * ::capnp::POINTERS)); ::capnp::bounded<3>() * ::capnp::POINTERS));
} }
inline ::uint64_t SlcAction::Reader::getWheelAdoptMonoTime() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<4>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcAction::Builder::getWheelAdoptMonoTime() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<4>() * ::capnp::ELEMENTS);
}
inline void SlcAction::Builder::setWheelAdoptMonoTime( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<4>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t SlcAction::ControllerCruiseAction::Reader::getVersion() const { inline ::uint16_t SlcAction::ControllerCruiseAction::Reader::getVersion() const {
return _reader.getDataField< ::uint16_t>( return _reader.getDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS); ::capnp::bounded<0>() * ::capnp::ELEMENTS);
@@ -22589,6 +22689,20 @@ inline ::capnp::Orphan< ::cereal::SlcCruiseEvent::TeslaStockCruise> SlcCruiseEve
::capnp::bounded<5>() * ::capnp::POINTERS)); ::capnp::bounded<5>() * ::capnp::POINTERS));
} }
inline ::uint64_t SlcCruiseEvent::Reader::getWheelOverrideSince() const {
return _reader.getDataField< ::uint64_t>(
::capnp::bounded<7>() * ::capnp::ELEMENTS);
}
inline ::uint64_t SlcCruiseEvent::Builder::getWheelOverrideSince() {
return _builder.getDataField< ::uint64_t>(
::capnp::bounded<7>() * ::capnp::ELEMENTS);
}
inline void SlcCruiseEvent::Builder::setWheelOverrideSince( ::uint64_t value) {
_builder.setDataField< ::uint64_t>(
::capnp::bounded<7>() * ::capnp::ELEMENTS, value);
}
inline ::uint16_t SlcCruiseEvent::TeslaStockCruise::Reader::getVersion() const { inline ::uint16_t SlcCruiseEvent::TeslaStockCruise::Reader::getVersion() const {
return _reader.getDataField< ::uint16_t>( return _reader.getDataField< ::uint16_t>(
::capnp::bounded<0>() * ::capnp::ELEMENTS); ::capnp::bounded<0>() * ::capnp::ELEMENTS);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+8 -7
View File
@@ -327,12 +327,12 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"HideDMIcon", {PERSISTENT, BOOL, "0"}}, {"HideDMIcon", {PERSISTENT, BOOL, "0"}},
{"HidePersonalityAlerts", {PERSISTENT, BOOL, "0"}}, {"HidePersonalityAlerts", {PERSISTENT, BOOL, "0"}},
{"ShowSpeedLimits", {PERSISTENT, BOOL, "1"}}, {"ShowSpeedLimits", {PERSISTENT, BOOL, "1"}},
{"SLCConfirmation", {PERSISTENT, BOOL, "0"}}, {"SLCOnEngage", {PERSISTENT, BOOL, "0"}},
{"SLCAdvanceSeconds", {PERSISTENT, INT, "0"}}, {"SLCConfirmation", {PERSISTENT, INT, "0"}},
{"SLCConfirmationHigher", {PERSISTENT, BOOL, "0"}}, {"SLCAdvanceHigherSeconds", {PERSISTENT, INT, "0"}},
{"SLCConfirmationLower", {PERSISTENT, BOOL, "0"}}, {"SLCAdvanceLowerSeconds", {PERSISTENT, INT, "0"}},
{"SLCFallback", {PERSISTENT, INT}}, // Retired; preserve saved bytes for older versions. {"SLCOverrideMode", {PERSISTENT, INT, "1"}},
{"SLCOverride", {PERSISTENT, INT, "1"}}, {"SLCWheelOverride", {PERSISTENT, BOOL, "0"}},
{"SLCQualifiedHistory", {PERSISTENT, JSON}}, {"SLCQualifiedHistory", {PERSISTENT, JSON}},
{"ConditionalModeConfig", {PERSISTENT | DONT_LOG, JSON}}, {"ConditionalModeConfig", {PERSISTENT | DONT_LOG, JSON}},
{"ConditionalManualState", {PERSISTENT | DONT_LOG, JSON}}, {"ConditionalManualState", {PERSISTENT | DONT_LOG, JSON}},
@@ -361,7 +361,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"VASMPreferences", {PERSISTENT | DONT_LOG, JSON}}, {"VASMPreferences", {PERSISTENT | DONT_LOG, JSON}},
{"LaneChangePreferences", {PERSISTENT | DONT_LOG, JSON}}, {"LaneChangePreferences", {PERSISTENT | DONT_LOG, JSON}},
{"SLCPriority1", {PERSISTENT, STRING, "Vision"}}, {"SLCPriority1", {PERSISTENT, STRING, "Vision"}},
{"SLCPriority2", {PERSISTENT, STRING, "Dashboard"}}, {"SLCPriority2", {PERSISTENT, STRING, "Map Data"}},
{"SLCPriority3", {PERSISTENT, STRING, "Off"}},
{"SpeedLimitController", {PERSISTENT, BOOL, "0"}}, {"SpeedLimitController", {PERSISTENT, BOOL, "0"}},
{"RouteCount", {PERSISTENT, INT, "0"}}, {"RouteCount", {PERSISTENT, INT, "0"}},
{"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, {"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
+70 -92
View File
@@ -4,7 +4,6 @@ import os
import time import time
import threading import threading
import uuid import uuid
from collections import deque
from typing import cast from typing import cast
import openpilot.cereal.messaging as messaging import openpilot.cereal.messaging as messaging
@@ -32,7 +31,7 @@ from opendbc.car.hyundai.ioniq6_media import Ioniq6MediaButtons
from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR
from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase
from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
from openpilot.selfdrive.car.cruise import VCruiseHelper, SlcPendingConfirmation from openpilot.selfdrive.car.cruise import SlcWheelContext, VCruiseHelper
from openpilot.starpilot.speed_limits import physical_actions as slc_physical from openpilot.starpilot.speed_limits import physical_actions as slc_physical
from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity
@@ -94,7 +93,7 @@ from openpilot.starpilot.vehicle_selection import startup_candidate
from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences
from openpilot.starpilot.controller_extensions import configure_controller, observe_controller_can, order_controller_can from openpilot.starpilot.controller_extensions import configure_controller, observe_controller_can, order_controller_can
from openpilot.starpilot.vehicle_startup import VehicleStartupOwner from openpilot.starpilot.vehicle_startup import VehicleStartupOwner
from openpilot.starpilot.controllers.wheel_actions import WheelPublisher, key_for from openpilot.starpilot.controllers.wheel_actions import LIFETIME_NS as WHEEL_ACTION_MAX_AGE_NS, WheelPublisher, key_for
from openpilot.starpilot.controllers.cruise_action import CruiseActionConsumer, eligible as cruise_action_eligible from openpilot.starpilot.controllers.cruise_action import CruiseActionConsumer, eligible as cruise_action_eligible
from openpilot.starpilot.schema_cache import get_cache, prewarm_cache_contracts, put_cache from openpilot.starpilot.schema_cache import get_cache, prewarm_cache_contracts, put_cache
@@ -140,15 +139,15 @@ def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket
def curve_press_receipt(CS: car.CarState, helper: VCruiseHelper, sm, *, curve_replay: bool, def curve_press_receipt(CS: car.CarState, helper: VCruiseHelper, sm, *, curve_replay: bool,
slc_replay: bool, host_long_active: bool, observed_ns: int): slc_replay: bool, host_long_active: bool, observed_ns: int):
"""Reserve SLC presentation presses even when their command is stale or rejected.""" """A confirmation or native standstill RES must not also override Curve control."""
accelerate = frozenset((car.CarState.ButtonEvent.Type.accelCruise, accelerate = frozenset((car.CarState.ButtonEvent.Type.accelCruise,
car.CarState.ButtonEvent.Type.resumeCruise)) car.CarState.ButtonEvent.Type.resumeCruise))
pressed = {b.type.raw for b in CS.buttonEvents if b.pressed and b.type.raw in accelerate} pressed = {b.type.raw for b in CS.buttonEvents if b.pressed and b.type.raw in accelerate}
if (not curve_replay or not host_long_active or not CS.canValid or CS.canTimeout or not CS.cruiseState.available or if (not curve_replay or not host_long_active or not CS.canValid or CS.canTimeout or not CS.cruiseState.available or
not pressed): CS.standstill or CS.cruiseState.standstill or not pressed):
return None return None
if slc_replay and (helper.slc_consumed_button is not None or bool(pressed & helper.slc_suppressed_buttons) or if (helper.slc_consumed_button is not None or bool(pressed & helper.slc_suppressed_buttons) or
bool(sm['slcState'].hasPending)): slc_replay and bool(sm['slcState'].hasPending)):
return None return None
return ('curveAccelPress', None, float(helper.v_cruise_kph_last / 3.6), return ('curveAccelPress', None, float(helper.v_cruise_kph_last / 3.6),
float(helper.v_cruise_kph / 3.6), observed_ns) float(helper.v_cruise_kph / 3.6), observed_ns)
@@ -188,10 +187,6 @@ class Car:
ignore_valid=['autoSteeringLearning'], ignore_avg_freq=['autoSteeringLearning']) ignore_valid=['autoSteeringLearning'], ignore_avg_freq=['autoSteeringLearning'])
self.slc_cruise_event_id = 0 self.slc_cruise_event_id = 0
self.slc_producer_session = uuid.uuid4().hex self.slc_producer_session = uuid.uuid4().hex
self.slc_command_sock = messaging.sub_sock('slcCruiseCommand', conflate=False) if self.slc_replay else None
self.slc_commands = deque(maxlen=8)
self.slc_last_command_id = 0
self.slc_command_session = ''
self.slc_receipts: list[tuple[str, object, float, float, int]] = [] self.slc_receipts: list[tuple[str, object, float, float, int]] = []
self.manual_receipt = None self.manual_receipt = None
self.manual_event_sequence = 0 self.manual_event_sequence = 0
@@ -428,14 +423,13 @@ class Car:
for ignored in (self.sm.ignore_alive, self.sm.ignore_valid, self.sm.ignore_average_freq): for ignored in (self.sm.ignore_alive, self.sm.ignore_valid, self.sm.ignore_average_freq):
if 'slcState' not in ignored: if 'slcState' not in ignored:
ignored.append('slcState') ignored.append('slcState')
if self.slc_command_sock is None:
self.slc_command_sock = messaging.sub_sock('slcCruiseCommand', conflate=False)
if 'slcDashboardObservation' not in self.pm.sock: if 'slcDashboardObservation' not in self.pm.sock:
self.pm.sock['slcDashboardObservation'] = messaging.pub_sock('slcDashboardObservation') self.pm.sock['slcDashboardObservation'] = messaging.pub_sock('slcDashboardObservation')
self.slc_requested_configuration = self.read_slc_configuration() self.slc_requested_configuration = self.read_slc_configuration()
self.slc_configuration = self.slc_requested_configuration self.slc_configuration = self.slc_requested_configuration
self.slc_replay = self.slc_configuration[0] self.slc_replay = self.slc_configuration[0]
self.slc_control_enabled = self.slc_replay and self.slc_configuration[1].enabled self.slc_control_enabled = self.slc_replay and self.slc_configuration[1].enabled
self.slc_match_on_engage = self.slc_transport_available and self.read_slc_match_on_engage()
self.slc_source_floor_ns = 0 self.slc_source_floor_ns = 0
# Write previous route's CarParams # Write previous route's CarParams
@@ -476,6 +470,9 @@ class Car:
feature_enabled(self.params, self.CP, 'slc', os.environ)) feature_enabled(self.params, self.CP, 'slc', os.environ))
return bool(admitted), settings return bool(admitted), settings
def read_slc_match_on_engage(self) -> bool:
return read_saved(self.params, 'SLCOnEngage', 1) == (b'1', True)
def refresh_slc_configuration(self, now_ns: int) -> None: def refresh_slc_configuration(self, now_ns: int) -> None:
configuration = getattr(self, 'slc_requested_configuration', None) configuration = getattr(self, 'slc_requested_configuration', None)
if configuration is None or configuration == getattr(self, 'slc_configuration', None): if configuration is None or configuration == getattr(self, 'slc_configuration', None):
@@ -483,12 +480,8 @@ class Car:
self.slc_configuration = configuration self.slc_configuration = configuration
self.slc_replay = configuration[0] self.slc_replay = configuration[0]
self.slc_control_enabled = self.slc_replay and configuration[1].enabled self.slc_control_enabled = self.slc_replay and configuration[1].enabled
# Invalidate old SLC choices while keeping consumed buttons latched until release.
self.slc_source_floor_ns = max(getattr(self, 'slc_source_floor_ns', 0), now_ns) self.slc_source_floor_ns = max(getattr(self, 'slc_source_floor_ns', 0), now_ns)
self.slc_commands.clear()
self.slc_command_session = ''
self.slc_last_command_id = 0
# Keep the shared event producer and held suppression until physical release.
# Only SLC's sourced/issued work predating this admission is retired.
def observe_distance_personality(self, CS: car.CarState, now_ns: int) -> None: def observe_distance_personality(self, CS: car.CarState, now_ns: int) -> None:
tracker = getattr(self, 'distance_personality_tracker', None) tracker = getattr(self, 'distance_personality_tracker', None)
@@ -581,18 +574,22 @@ class Car:
0 < control_log_ns <= now_ns and now_ns - control_log_ns <= slc_physical.STATE_MAX_AGE_NS and 0 < control_log_ns <= now_ns and now_ns - control_log_ns <= slc_physical.STATE_MAX_AGE_NS and
self.sm['carControl'].enabled) self.sm['carControl'].enabled)
host_control_enabled = bool(self.CP.openpilotLongitudinalControl and not self.CP.pcmCruise and host_enabled) host_control_enabled = bool(self.CP.openpilotLongitudinalControl and not self.CP.pcmCruise and host_enabled)
host_long_active = host_control_enabled and self.sm['carControl'].longActive host_long_active = bool(self.CP.openpilotLongitudinalControl and host_enabled and self.sm['carControl'].longActive)
slc_long_active = bool(getattr(self, 'slc_control_enabled', self.slc_replay) and self.CP.openpilotLongitudinalControl and slc_long_active = bool(getattr(self, 'slc_control_enabled', self.slc_replay) and self.CP.openpilotLongitudinalControl and
host_enabled and (self.sm['carControl'].longActive or CS.gasPressed)) host_enabled and (self.sm['carControl'].longActive or CS.gasPressed))
pending = None pending = None
if self.slc_replay: if self.slc_replay:
pending = slc_physical.pending_confirmation( pending = slc_physical.pending_confirmation(
self.sm, now_ns, long_active=slc_long_active, after_ns=floor_ns) self.sm, now_ns, long_active=slc_long_active, after_ns=floor_ns)
approved = (slc_physical.state_current(self.sm, observation, self.slc_producer_session, now_ns) wheel_context = None
if self.v_cruise_helper.toyota is not None and self.slc_control_enabled else None) slc_settings = getattr(self, 'slc_configuration', (False, None))[1]
if approved is not None and int(approved.frameMonoTime) <= floor_ns: cruise_helper = self.v_cruise_helper
approved = None if (self.slc_replay and getattr(slc_settings, 'wheel_override', False) and host_long_active and can_rcv_valid and
self.update_cruise_speed(CS, pending, approved=approved) not self.CP.pcmCruise and pending is None and (cruise_helper.slc_wheel_press is not None or len(CS.buttonEvents) > 0) and
not (CS.brakePressed or CS.gasPressed or CS.standstill or CS.cruiseState.standstill)):
wheel_context = slc_physical.wheel_override_context(self.sm, now_ns, after_ns=floor_ns,
selected_kph=cruise_helper.v_cruise_kph, is_metric=self.is_metric)
self.update_cruise_speed(CS, pending, wheel_context=wheel_context)
if self.controller_cruise_sock is not None: if self.controller_cruise_sock is not None:
for _ in range(8): for _ in range(8):
request = messaging.recv_one_or_none(self.controller_cruise_sock) request = messaging.recv_one_or_none(self.controller_cruise_sock)
@@ -601,6 +598,8 @@ class Car:
self.controller_cruise_consumer.apply(request, self.CP, CS, self.sm, self.v_cruise_helper, self.controller_cruise_consumer.apply(request, self.CP, CS, self.sm, self.v_cruise_helper,
now_ns=now_ns, is_metric=self.is_metric, now_ns=now_ns, is_metric=self.is_metric,
enabled=bool(host_control_enabled and can_rcv_valid and not self.params.get_bool("SafeMode"))) enabled=bool(host_control_enabled and can_rcv_valid and not self.params.get_bool("SafeMode")))
if self.slc_replay:
self.apply_slc_adopt(now_ns, host_control_enabled=host_control_enabled, after_ns=floor_ns)
consumed = self.v_cruise_helper.slc_consumed_button consumed = self.v_cruise_helper.slc_consumed_button
if self.aol_card_intent is not None: if self.aol_card_intent is not None:
if self.aol_process_fault_context is None: if self.aol_process_fault_context is None:
@@ -798,52 +797,6 @@ class Car:
slc_replay=self.slc_replay, host_long_active=host_long_active, observed_ns=now_ns) slc_replay=self.slc_replay, host_long_active=host_long_active, observed_ns=now_ns)
if curve_receipt is not None: if curve_receipt is not None:
self.slc_receipts.append(curve_receipt) self.slc_receipts.append(curve_receipt)
if self.slc_command_sock is not None:
for _ in range(8):
command_message = messaging.recv_one_or_none(self.slc_command_sock)
if command_message is None:
break
if self.slc_replay and command_message.valid:
self.slc_commands.append(command_message)
for _ in range(len(self.slc_commands)):
command_message = self.slc_commands.popleft()
command = command_message.slcCruiseCommand
if int(command.issuedMonoTime) <= floor_ns:
continue
if now_ns < int(command.issuedMonoTime):
if now_ns <= int(command.expiresMonoTime):
self.slc_commands.append(command_message)
continue
state = slc_physical.state_current(self.sm, observation, self.slc_producer_session, now_ns)
if (state is None or int(self.sm.logMonoTime['slcState']) < int(command.issuedMonoTime)) and now_ns < int(command.expiresMonoTime):
self.slc_commands.append(command_message)
continue
if state is not None and str(state.sessionId) != self.slc_command_session:
self.slc_command_session = str(state.sessionId)
self.slc_last_command_id = 0
if not self.slc_command_session:
self.slc_command_session = str(command.sessionId)
if str(command.sessionId) != self.slc_command_session or int(command.commandId) <= self.slc_last_command_id:
continue
self.slc_last_command_id = int(command.commandId)
previous_mps = float(self.v_cruise_helper.v_cruise_kph / 3.6)
origin = SlcPendingConfirmation(str(command.sessionId), int(command.decisionId), int(command.presentationId))
owners = {**self.v_cruise_helper.slc_suppression_owner, **self.v_cruise_helper.slc_released_owner}
allowed_buttons = {button for button, owner in owners.items() if owner == origin} if int(command.decisionId) > 0 else set()
intervening_button = (bool(self.v_cruise_helper.slc_cruise_change) or
any(b.type.raw not in allowed_buttons for b in CS.buttonEvents) or
any(timer > 0 and button not in allowed_buttons
for button, timer in self.v_cruise_helper.button_timers.items()))
applicable = slc_physical.command_applicable(
command, state, observation, self.slc_producer_session, now_ns, previous_mps,
long_active=slc_long_active,
button_event=intervening_button)
if self.v_cruise_helper.toyota is not None:
applicable = applicable and self.v_cruise_helper.toyota.can_apply(float(command.targetMps))
if applicable:
self.v_cruise_helper.apply_slc_target(float(command.targetMps), self.is_metric)
self.slc_receipts.append(('commandApplied' if applicable else 'commandRejected', command,
previous_mps, float(self.v_cruise_helper.v_cruise_kph / 3.6), now_ns))
blocked_keys = set() blocked_keys = set()
if self.manual_receipt is not None: if self.manual_receipt is not None:
blocked_keys.add(key_for(self.manual_receipt[0])) blocked_keys.add(key_for(self.manual_receipt[0]))
@@ -859,28 +812,49 @@ class Car:
return CS, RD return CS, RD
def update_cruise_speed(self, CS, pending=None, *, approved=None): def apply_slc_adopt(self, now_ns: int, *, host_control_enabled: bool, after_ns: int = 0) -> None:
pending = getattr(self, 'slc_wheel_adopt', None)
if pending is None:
return
wheel_ns, selected_kph = pending
helper = self.v_cruise_helper
if (not after_ns < wheel_ns <= now_ns <= wheel_ns + WHEEL_ACTION_MAX_AGE_NS or
not host_control_enabled or not self.slc_control_enabled or
not helper.v_cruise_initialized or helper.v_cruise_kph != selected_kph or any(helper.button_timers.values())):
self.slc_wheel_adopt = None
return
target = slc_physical.adopted_target(self.sm, now_ns, wheel_ns=wheel_ns)
if target is not None:
self.slc_wheel_adopt = None
helper.apply_slc_target(target, self.is_metric)
def update_cruise_speed(self, CS, pending=None, *, wheel_context: SlcWheelContext | None = None):
self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric, pending, self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric, pending,
slc_enabled=getattr(self, 'slc_control_enabled', getattr(self, 'slc_replay', False)), slc_enabled=getattr(self, 'slc_control_enabled', getattr(self, 'slc_replay', False)),
slc_approved=approved) wheel_context=wheel_context)
if self.sm['carControl'].enabled and not self.CC_prev.enabled: if self.sm['carControl'].enabled and not self.CC_prev.enabled:
initial = None target, initial = None, None
now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns() now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns()
if (getattr(self, 'slc_control_enabled', False) and self.CP.openpilotLongitudinalControl and if (getattr(self, 'slc_match_on_engage', False) and getattr(self, 'slc_control_enabled', False) and
not self.CP.pcmCruise and self.CP.openpilotLongitudinalControl and
CS.canValid and not CS.canTimeout and CS.cruiseState.available and CS.canValid and not CS.canTimeout and CS.cruiseState.available and
self.sm.valid['carControl'] and self.sm.alive['carControl'] and self.sm.valid['carControl'] and self.sm.alive['carControl'] and
0 < int(self.sm.logMonoTime['carControl']) <= now_ns and 0 < int(self.sm.logMonoTime['carControl']) <= now_ns and
now_ns - int(self.sm.logMonoTime['carControl']) <= slc_physical.STATE_MAX_AGE_NS and now_ns - int(self.sm.logMonoTime['carControl']) <= slc_physical.STATE_MAX_AGE_NS):
(self.sm['carControl'].longActive or CS.gasPressed)): long_requested = self.sm['carControl'].longActive or CS.gasPressed
evidence = getattr(self.CI.CS, 'dashboard_limit', None) if not long_requested and 'aolAxisState' in self.sm.logMonoTime:
initial = slc_physical.engagement_state( # AOL can acknowledge the request before longitudinal actuators become active.
self.sm, evidence.observation if evidence is not None else None, self.slc_producer_session, axis = current_axis(self.sm, now_ns=now_ns)
now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0)) long_requested = axis is not None and axis.nativeAcknowledged and axis.desiredLongitudinal
# Initialization owns this edge; evaluate commands against its final speed. if long_requested:
evidence = getattr(self.CI.CS, 'dashboard_limit', None)
target, initial = slc_physical.engagement_target(
self.sm, evidence.observation if evidence is not None else None, self.slc_producer_session,
now_ns, after_ns=getattr(self, 'slc_source_floor_ns', 0))
adopted = self.v_cruise_helper.initialize_v_cruise( adopted = self.v_cruise_helper.initialize_v_cruise(
self.CS_prev, self.experimental_mode, resume=self.vehicle_startup.consume_cruise_resume(), initial_speed=self.initial_cruise_speed, self.CS_prev, self.experimental_mode, resume=self.vehicle_startup.consume_cruise_resume(), initial_speed=self.initial_cruise_speed,
slc_target_mps=float(initial.presentationAdjustedLimit) if initial is not None else None, is_metric=self.is_metric) slc_target_mps=target, is_metric=self.is_metric)
if adopted: if adopted and initial is not None:
self.slc_receipts.append(('engagementAdopt', initial, 0.0, float(self.v_cruise_helper.v_cruise_kph / 3.6), now_ns)) self.slc_receipts.append(('engagementAdopt', initial, 0.0, float(self.v_cruise_helper.v_cruise_kph / 3.6), now_ns))
def aol_cancel_source(self, CS, now_ns: int) -> int: def aol_cancel_source(self, CS, now_ns: int) -> int:
@@ -1149,11 +1123,6 @@ class Car:
elif self.CP.brand == 'hyundai': elif self.CP.brand == 'hyundai':
from openpilot.starpilot.car.hyundai.dashboard import compose as hyundai_compose from openpilot.starpilot.car.hyundai.dashboard import compose as hyundai_compose
companion = hyundai_compose(self.CP, self.CI.CS, CS, companion, car_state_stamp=int(cs_send.logMonoTime)) companion = hyundai_compose(self.CP, self.CI.CS, CS, companion, car_state_stamp=int(cs_send.logMonoTime))
if self.v_cruise_helper.toyota is not None:
if companion is None:
companion = messaging.new_message('starpilotCarState', valid=bool(cs_send.valid), logMonoTime=int(cs_send.logMonoTime))
companion.starpilotCarState.sourceCarStateMonoTime = int(cs_send.logMonoTime)
self.v_cruise_helper.toyota.publish(companion.starpilotCarState.toyotaCruise)
self.car_gps_publisher.update(self.CI.CS, self.pm, companion) self.car_gps_publisher.update(self.CI.CS, self.pm, companion)
self.pm.send('carState', cs_send) self.pm.send('carState', cs_send)
if getattr(self, 'learning_stamp_observer', None) is not None: if getattr(self, 'learning_stamp_observer', None) is not None:
@@ -1161,6 +1130,9 @@ class Car:
wheel = getattr(self, 'wheel_publisher', None) wheel = getattr(self, 'wheel_publisher', None)
if wheel is not None: if wheel is not None:
if (getattr(self, 'slc_control_enabled', False) and self.CC_prev.enabled and self.sm['carControl'].enabled and
any(action == 10 for _, action in self.wheel_commands)):
self.slc_wheel_adopt = (int(cs_send.logMonoTime), self.v_cruise_helper.v_cruise_kph)
wheel.publish(self.wheel_commands, self.CP, self.pm, now_ns=int(cs_send.logMonoTime), wheel.publish(self.wheel_commands, self.CP, self.pm, now_ns=int(cs_send.logMonoTime),
drive_id=int(self.sm['deviceState'].startedMonoTime), source_car_ns=int(cs_send.logMonoTime), drive_id=int(self.sm['deviceState'].startedMonoTime), source_car_ns=int(cs_send.logMonoTime),
source_control_ns=int(self.sm.logMonoTime['carControl'])) source_control_ns=int(self.sm.logMonoTime['carControl']))
@@ -1200,6 +1172,8 @@ class Car:
if kind == 'driverChange': if kind == 'driverChange':
assert isinstance(detail, tuple) and len(detail) == 4 assert isinstance(detail, tuple) and len(detail) == 4
record.button, record.longPress = detail[2], detail[3] record.button, record.longPress = detail[2], detail[3]
if self.v_cruise_helper.slc_wheel_tap is not None:
record.sessionId, record.wheelOverrideSince = self.v_cruise_helper.slc_wheel_tap
elif kind in ('confirmationAccept', 'confirmationReject'): elif kind in ('confirmationAccept', 'confirmationReject'):
record.button = detail.button record.button = detail.button
record.sessionId = detail.pending.session_id record.sessionId = detail.pending.session_id
@@ -1207,13 +1181,11 @@ class Car:
record.presentationId = detail.pending.presentation_id record.presentationId = detail.pending.presentation_id
elif kind == 'curveAccelPress': elif kind == 'curveAccelPress':
record.button = 'accel' record.button = 'accel'
else: elif kind == 'engagementAdopt':
record.sessionId = str(detail.sessionId) record.sessionId = str(detail.sessionId)
record.commandId = 0 if kind == 'engagementAdopt' else int(detail.commandId)
record.decisionId = int(detail.decisionId) record.decisionId = int(detail.decisionId)
record.presentationId = int(detail.presentationId) record.presentationId = int(detail.presentationId)
if kind == 'engagementAdopt': record.button = 'decel'
record.button = 'decel'
self.pm.send('slcCruiseEvent', event) self.pm.send('slcCruiseEvent', event)
if getattr(self, 'conditional_replay', False) and self.manual_receipt is not None: if getattr(self, 'conditional_replay', False) and self.manual_receipt is not None:
@@ -1635,6 +1607,10 @@ class Car:
if physical.button_credit_ns - self.volt_cc_boot_offset_ns <= max(self.volt_cc_drive_id, self.volt_cc_source_floor_ns): if physical.button_credit_ns - self.volt_cc_boot_offset_ns <= max(self.volt_cc_drive_id, self.volt_cc_source_floor_ns):
self.CI.CC.volt_cc_consumed_source_ns = physical.button_credit_ns self.CI.CC.volt_cc_consumed_source_ns = physical.button_credit_ns
self.CI.CC.volt_cc_metric = self.is_metric self.CI.CC.volt_cc_metric = self.is_metric
self.CI.CC.volt_cc_speed_ceiling_mps = (slc_physical.active_ceiling(
self.sm, self.volt_cc_now_mono_ns,
after_ns=max(self.volt_cc_drive_id, self.volt_cc_source_floor_ns, getattr(self, 'slc_source_floor_ns', 0)))
if getattr(self, 'slc_control_enabled', False) else None)
if getattr(self.CI.CC, "bolt_cc_profile", False): if getattr(self.CI.CC, "bolt_cc_profile", False):
self.CI.CC.bolt_cc_metric = self.is_metric self.CI.CC.bolt_cc_metric = self.is_metric
@@ -1896,6 +1872,8 @@ class Car:
now = time.monotonic() now = time.monotonic()
if now >= next_cruise_read: if now >= next_cruise_read:
self.slc_requested_configuration = self.read_slc_configuration() self.slc_requested_configuration = self.read_slc_configuration()
if getattr(self, 'slc_transport_available', False):
self.slc_match_on_engage = self.read_slc_match_on_engage()
self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP) self.v_cruise_helper.intervals = read_cruise_intervals(self.params, self.CP)
pitch_input = getattr(self.CI.CC, 'long_pitch_input', None) pitch_input = getattr(self.CI.CC, 'long_pitch_input', None)
if pitch_input is not None: if pitch_input is not None:
+40 -59
View File
@@ -43,6 +43,9 @@ class SlcConsumedButton:
button: str button: str
SlcWheelContext = tuple[str, int]
def validated_initial_cruise_speed(value: object) -> int: def validated_initial_cruise_speed(value: object) -> int:
if type(value) is int and V_CRUISE_INITIAL <= value <= V_CRUISE_MAX: if type(value) is int and V_CRUISE_INITIAL <= value <= V_CRUISE_MAX:
return value return value
@@ -66,35 +69,27 @@ class VCruiseHelper:
self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers} self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers}
self.pcm_slc_sample: tuple[float, int] | None = None self.pcm_slc_sample: tuple[float, int] | None = None
self.pcm_slc_button = ButtonType.unknown self.pcm_slc_button = ButtonType.unknown
# Set by software cruise steps or a checked Toyota PCM physical +/- change.
self.slc_cruise_change: tuple[float, float, str, bool] | None = None self.slc_cruise_change: tuple[float, float, str, bool] | None = None
self.slc_consumed_button: SlcConsumedButton | None = None self.slc_consumed_button: SlcConsumedButton | None = None
self.slc_suppressed_buttons: set[ButtonType] = set() self.slc_suppressed_buttons: set[ButtonType] = set()
self.slc_suppression_owner: dict[ButtonType, SlcPendingConfirmation] = {}
self.slc_released_owner: dict[ButtonType, SlcPendingConfirmation] = {}
self.slc_released_suppressed = False self.slc_released_suppressed = False
self.slc_pcm = False self.slc_wheel_press: SlcWheelContext | None = None
from openpilot.starpilot.speed_limits.toyota import eligible, ToyotaCruise self.slc_wheel_tap: SlcWheelContext | None = None
self.toyota = ToyotaCruise() if eligible(CP) else None
@property @property
def v_cruise_initialized(self): def v_cruise_initialized(self):
return self.v_cruise_kph != V_CRUISE_UNSET return self.v_cruise_kph != V_CRUISE_UNSET
def update_v_cruise(self, CS, enabled, is_metric, slc_pending: SlcPendingConfirmation | None = None, *, slc_enabled: bool = False, def update_v_cruise(self, CS, enabled, is_metric, slc_pending: SlcPendingConfirmation | None = None, *,
slc_approved=None): slc_enabled: bool = False, wheel_context: SlcWheelContext | None = None):
self.slc_pcm = bool(slc_enabled and self.CP.pcmCruise and self.CP.openpilotLongitudinalControl)
from opendbc.car.subaru.software_cruise import selected as subaru_software_selected from opendbc.car.subaru.software_cruise import selected as subaru_software_selected
subaru_software = subaru_software_selected(self.CP) subaru_software = subaru_software_selected(self.CP)
software_cruise = not self.CP.pcmCruise or self.slc_pcm or subaru_software software_cruise = not self.CP.pcmCruise or subaru_software
self.slc_cruise_change = None self.slc_cruise_change = None
self.slc_consumed_button = None self.slc_consumed_button = None
self.slc_released_suppressed = False self.slc_released_suppressed = False
self.slc_released_owner = {} self.slc_wheel_tap = None
self.v_cruise_kph_last = self.v_cruise_kph self.v_cruise_kph_last = self.v_cruise_kph
if self.toyota is not None:
self.slc_pcm = self.toyota.update(self, CS, enabled, slc_enabled, slc_approved, is_metric)
software_cruise = self.slc_pcm
now_ns = monotonic_ns() now_ns = monotonic_ns()
if not CS.cruiseState.available or now_ns - self.pending_resume_ns > 500_000_000: if not CS.cruiseState.available or now_ns - self.pending_resume_ns > 500_000_000:
self.pending_resume_ns = 0 self.pending_resume_ns = 0
@@ -106,21 +101,26 @@ class VCruiseHelper:
button.type in (ButtonType.accelCruise, ButtonType.resumeCruise) and self.v_cruise_initialized): button.type in (ButtonType.accelCruise, ButtonType.resumeCruise) and self.v_cruise_initialized):
self.pending_resume_ns = now_ns self.pending_resume_ns = now_ns
if software_cruise or self.slc_suppressed_buttons: if software_cruise or slc_enabled and self.CP.openpilotLongitudinalControl or self.slc_suppressed_buttons:
self._update_slc_button_latches(CS, enabled, slc_pending) self._update_slc_button_latches(CS, enabled, slc_pending)
if (not slc_enabled or not enabled or self.CP.pcmCruise or slc_pending is not None or
not CS.cruiseState.available or ButtonType.accelCruise in self.slc_suppressed_buttons):
wheel_context = None
if wheel_context != self.slc_wheel_press:
self.slc_wheel_press = None
if wheel_context is not None and self.button_timers[ButtonType.accelCruise] == 0:
pressed = {b.type.raw for b in CS.buttonEvents if b.pressed}
if ButtonType.accelCruise in pressed and ButtonType.resumeCruise not in pressed:
self.slc_wheel_press = wheel_context
if CS.cruiseState.available: if CS.cruiseState.available:
if software_cruise: if software_cruise:
if self.toyota is None and (self.slc_pcm or subaru_software) and (not enabled or not self.v_cruise_initialized): if subaru_software and (not enabled or not self.v_cruise_initialized):
# PCM still owns engagement; SLC owns the software set speed while system long is selected.
stock_kph = CS.cruiseState.speed * CV.MS_TO_KPH stock_kph = CS.cruiseState.speed * CV.MS_TO_KPH
self.v_cruise_kph = stock_kph if 0 < stock_kph < V_CRUISE_UNSET else V_CRUISE_UNSET self.v_cruise_kph = stock_kph if 0 < stock_kph < V_CRUISE_UNSET else V_CRUISE_UNSET
# if stock cruise is completely disabled, then we can use our own set speed logic
self._update_v_cruise_non_pcm(CS, enabled, is_metric) self._update_v_cruise_non_pcm(CS, enabled, is_metric)
if self.toyota is None: self.v_cruise_cluster_kph = self.v_cruise_kph
self.v_cruise_cluster_kph = self.v_cruise_kph
if self.toyota is not None:
self.toyota.constrain(self)
self.update_button_timers(CS, enabled) self.update_button_timers(CS, enabled)
else: else:
self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH
@@ -139,6 +139,8 @@ class VCruiseHelper:
self.pcm_slc_button = ButtonType.unknown self.pcm_slc_button = ButtonType.unknown
if software_cruise: if software_cruise:
self.update_button_timers(CS, enabled) self.update_button_timers(CS, enabled)
if self.button_timers[ButtonType.accelCruise] == 0:
self.slc_wheel_press = None
def _update_toyota_pcm_slc_change(self, CS, enabled: bool, now_ns: int) -> None: def _update_toyota_pcm_slc_change(self, CS, enabled: bool, now_ns: int) -> None:
"""Observe a physical PCM speed change without writing stock selected speed.""" """Observe a physical PCM speed change without writing stock selected speed."""
@@ -165,8 +167,9 @@ class VCruiseHelper:
held = ButtonType.unknown held = ButtonType.unknown
if continuous: if continuous:
delta = self.v_cruise_kph - previous[0] delta = self.v_cruise_kph - previous[0]
if ((button == ButtonType.accelCruise and delta > 0.) or if (not self.slc_suppressed_buttons and not self.slc_released_suppressed and
(button == ButtonType.decelCruise and delta < 0.)): ((button == ButtonType.accelCruise and delta > 0.) or
(button == ButtonType.decelCruise and delta < 0.))):
self.slc_cruise_change = (previous[0] / 3.6, self.v_cruise_kph / 3.6, self.slc_cruise_change = (previous[0] / 3.6, self.v_cruise_kph / 3.6,
'accel' if delta > 0. else 'decel', False) 'accel' if delta > 0. else 'decel', False)
self.pcm_slc_button = held self.pcm_slc_button = held
@@ -179,17 +182,13 @@ class VCruiseHelper:
continue continue
if not b.pressed and button in self.slc_suppressed_buttons: if not b.pressed and button in self.slc_suppressed_buttons:
self.slc_suppressed_buttons.remove(button) self.slc_suppressed_buttons.remove(button)
prior_owner = self.slc_suppression_owner.pop(button, None)
if prior_owner is not None:
self.slc_released_owner[button] = prior_owner
self.slc_released_suppressed = True self.slc_released_suppressed = True
self.button_timers[button] = 0 self.button_timers[button] = 0
elif (b.pressed and enabled and CS.cruiseState.available and slc_pending is not None and elif (b.pressed and enabled and CS.cruiseState.available and slc_pending is not None and
not (self.toyota is not None and button == ButtonType.accelCruise and not (self.CP.pcmCruise and button == ButtonType.accelCruise and
(CS.standstill or CS.cruiseState.standstill or not CS.cruiseState.enabled)) and (CS.standstill or CS.cruiseState.standstill or not CS.cruiseState.enabled)) and
button not in self.slc_suppressed_buttons): button not in self.slc_suppressed_buttons):
self.slc_suppressed_buttons.add(button) self.slc_suppressed_buttons.add(button)
self.slc_suppression_owner[button] = slc_pending
self.slc_consumed_button = SlcConsumedButton(slc_pending, 'accel' if button == ButtonType.accelCruise else 'decel') self.slc_consumed_button = SlcConsumedButton(slc_pending, 'accel' if button == ButtonType.accelCruise else 'decel')
def _update_v_cruise_non_pcm(self, CS, enabled, is_metric): def _update_v_cruise_non_pcm(self, CS, enabled, is_metric):
@@ -231,26 +230,20 @@ class VCruiseHelper:
if not self.button_change_states[button_type]["enabled"]: if not self.button_change_states[button_type]["enabled"]:
return return
self.adjust_v_cruise(button_type, CS, is_metric, long_press=long_press) changed = self.adjust_v_cruise(button_type, CS, is_metric, long_press=long_press)
if changed and button_type == ButtonType.accelCruise and not long_press and self.button_timers[button_type] > 0:
self.slc_wheel_tap = self.slc_wheel_press
def adjust_v_cruise(self, button_type, CS, is_metric: bool, *, long_press: bool = False) -> bool: def adjust_v_cruise(self, button_type, CS, is_metric: bool, *, long_press: bool = False) -> bool:
"""Apply the normal software cruise step without synthesizing button events.""" """Apply the normal software cruise step without synthesizing button events."""
from opendbc.car.subaru.software_cruise import selected as subaru_software_selected from opendbc.car.subaru.software_cruise import selected as subaru_software_selected
subaru_software = subaru_software_selected(self.CP) subaru_software = subaru_software_selected(self.CP)
if ((self.CP.pcmCruise and not self.slc_pcm and not subaru_software) or button_type not in (ButtonType.accelCruise, ButtonType.decelCruise) or if ((self.CP.pcmCruise and not subaru_software) or button_type not in (ButtonType.accelCruise, ButtonType.decelCruise) or
not 0 < self.v_cruise_kph < V_CRUISE_UNSET or not 0 < self.v_cruise_kph < V_CRUISE_UNSET or
(button_type == ButtonType.accelCruise and CS.cruiseState.standstill)): (button_type == ButtonType.accelCruise and CS.cruiseState.standstill)):
return False return False
v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT
previous_kph = self.v_cruise_kph previous_kph = self.v_cruise_kph
toyota = self.toyota if self.slc_pcm else None
previous_cluster_kph = self.v_cruise_cluster_kph
if toyota is not None:
if toyota.requested is None:
return False
if button_type == ButtonType.decelCruise:
previous_kph = toyota.requested[0]
self.v_cruise_kph = toyota.requested[1]
interval = self.intervals.held if long_press else self.intervals.short interval = self.intervals.held if long_press else self.intervals.short
v_cruise_delta = v_cruise_delta * interval v_cruise_delta = v_cruise_delta * interval
display_speed = round(self.v_cruise_kph if is_metric else self.v_cruise_kph * CV.KPH_TO_MPH) display_speed = round(self.v_cruise_kph if is_metric else self.v_cruise_kph * CV.KPH_TO_MPH)
@@ -266,11 +259,6 @@ class VCruiseHelper:
self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX)
self.v_cruise_cluster_kph = self.v_cruise_kph self.v_cruise_cluster_kph = self.v_cruise_kph
if toyota is not None:
toyota.requested = (float(self.v_cruise_kph), float(self.v_cruise_cluster_kph))
toyota.manual_step = (previous_kph, previous_cluster_kph, 'accel' if button_type == ButtonType.accelCruise else 'decel', long_press)
toyota.constrain(self)
return self.v_cruise_kph != previous_kph
if 0 < previous_kph < V_CRUISE_UNSET and self.v_cruise_kph != previous_kph: if 0 < previous_kph < V_CRUISE_UNSET and self.v_cruise_kph != previous_kph:
button = "accel" if button_type == ButtonType.accelCruise else "decel" button = "accel" if button_type == ButtonType.accelCruise else "decel"
self.slc_cruise_change = (float(previous_kph / 3.6), float(self.v_cruise_kph / 3.6), button, long_press) self.slc_cruise_change = (float(previous_kph / 3.6), float(self.v_cruise_kph / 3.6), button, long_press)
@@ -291,23 +279,19 @@ class VCruiseHelper:
self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled} self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled}
def apply_slc_target(self, target_mps: float, is_metric: bool) -> None: def apply_slc_target(self, target_mps: float, is_metric: bool) -> None:
"""Apply a qualified planner command to the card-owned software set speed.""" """Set the software cruise ceiling for engagement or a qualified driver request."""
# Match ordinary button precision so stepping away and back restores this target. # Match ordinary button precision so stepping away and back restores this target.
self.v_cruise_kph = slc_target_kph(target_mps, is_metric) self.v_cruise_kph = slc_target_kph(target_mps, is_metric)
self.v_cruise_cluster_kph = self.v_cruise_kph self.v_cruise_cluster_kph = self.v_cruise_kph
if self.toyota is not None:
self.toyota.manual_step = None
self.toyota.constrain(self)
self.toyota.requested = (self.v_cruise_kph, self.v_cruise_cluster_kph)
def initialize_v_cruise(self, CS, experimental_mode: bool, *, resume: bool | None = None, def initialize_v_cruise(self, CS, experimental_mode: bool, *, resume: bool | None = None,
initial_speed: object = V_CRUISE_INITIAL, slc_target_mps: float | None = None, is_metric: bool = False) -> bool: initial_speed: object = V_CRUISE_INITIAL, slc_target_mps: float | None = None, is_metric: bool = False) -> bool:
"""Return whether engagement adopts the qualified current SLC limit.""" """Return whether engagement used the supplied SLC target."""
if (not self.CP.openpilotLongitudinalControl or slc_target_mps is None or type(slc_target_mps) not in (int, float) or if (not self.CP.openpilotLongitudinalControl or slc_target_mps is None or type(slc_target_mps) not in (int, float) or
not math.isfinite(slc_target_mps) or not V_CRUISE_MIN / 3.6 - 1e-5 <= slc_target_mps <= V_CRUISE_MAX / 3.6 + 1e-5): not math.isfinite(slc_target_mps) or not V_CRUISE_MIN / 3.6 - 1e-5 <= slc_target_mps <= V_CRUISE_MAX / 3.6 + 1e-5):
slc_target_mps = None slc_target_mps = None
# PCM initializes when SLC does not own SET. # Native cruise owns PCM SET, including when SLC supplies a planner cap.
if self.CP.pcmCruise and (not self.slc_pcm or slc_target_mps is None): if self.CP.pcmCruise:
return False return False
# A car-owned acknowledgment can outlive the physical button event. # A car-owned acknowledgment can outlive the physical button event.
if resume is None: if resume is None:
@@ -315,15 +299,12 @@ class VCruiseHelper:
resume = (0 < self.pending_resume_ns and 0 <= age <= 500_000_000) or any( resume = (0 < self.pending_resume_ns and 0 <= age <= 500_000_000) or any(
b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents)
self.pending_resume_ns = 0 self.pending_resume_ns = 0
if slc_target_mps is None and resume and self.v_cruise_initialized: if resume and self.v_cruise_initialized:
if not self.CP.pcmCruise: self.v_cruise_kph = self.v_cruise_kph_last
self.v_cruise_kph = self.v_cruise_kph_last self.v_cruise_cluster_kph = self.v_cruise_kph
self.v_cruise_cluster_kph = self.v_cruise_kph
return False return False
elif slc_target_mps is not None: elif slc_target_mps is not None:
# Toyota still needs its native capacity/release approval before application. self.apply_slc_target(slc_target_mps, is_metric)
if self.toyota is None:
self.apply_slc_target(slc_target_mps, is_metric)
return True return True
else: else:
self.v_cruise_kph = int(round(np.clip(max(CS.vEgo * CV.MS_TO_KPH, validated_initial_cruise_speed(initial_speed)), V_CRUISE_INITIAL, V_CRUISE_MAX))) self.v_cruise_kph = int(round(np.clip(max(CS.vEgo * CV.MS_TO_KPH, validated_initial_cruise_speed(initial_speed)), V_CRUISE_INITIAL, V_CRUISE_MAX)))
@@ -52,7 +52,7 @@ class TestCruiseIntervals(unittest.TestCase):
Path(self.params.get_param_path("CustomCruiseLong")).write_bytes(b"200") Path(self.params.get_param_path("CustomCruiseLong")).write_bytes(b"200")
self.assertEqual(read_cruise_intervals(self.params, self.cp), CruiseIntervals()) self.assertEqual(read_cruise_intervals(self.params, self.cp), CruiseIntervals())
def test_slc_uses_saved_intervals_for_every_other_make_and_pcm_mode(self): def test_slc_preserves_software_intervals_and_native_pcm_set(self):
brands = [brand.__module__.split('.')[-2] for brand in BRANDS if brand.__module__.split('.')[-2] != 'toyota'] + ['future'] brands = [brand.__module__.split('.')[-2] for brand in BRANDS if brand.__module__.split('.')[-2] != 'toyota'] + ['future']
self.params.put("CustomCruise", 3.0, block=True) self.params.put("CustomCruise", 3.0, block=True)
self.params.put("CustomCruiseLong", 7.0, block=True) self.params.put("CustomCruiseLong", 7.0, block=True)
@@ -67,6 +67,11 @@ class TestCruiseIntervals(unittest.TestCase):
helper.v_cruise_kph = helper.v_cruise_cluster_kph = initial helper.v_cruise_kph = helper.v_cruise_cluster_kph = initial
helper.intervals = read_cruise_intervals(self.params, cp) helper.intervals = read_cruise_intervals(self.params, cp)
helper.update_v_cruise(state(button, True, native=140.), True, metric, slc_enabled=True) helper.update_v_cruise(state(button, True, native=140.), True, metric, slc_enabled=True)
if pcm:
helper.update_v_cruise(state(button, False, native=140.), True, metric, slc_enabled=True)
self.assertAlmostEqual(helper.v_cruise_kph, 140., places=4)
self.assertIsNone(helper.slc_cruise_change)
continue
if held: if held:
for _ in range(CRUISE_LONG_PRESS): for _ in range(CRUISE_LONG_PRESS):
helper.update_v_cruise(state(native=140.), True, metric, slc_enabled=True) helper.update_v_cruise(state(native=140.), True, metric, slc_enabled=True)
+9 -6
View File
@@ -478,22 +478,25 @@ class Controls:
new_desired_curvature = model_v2.action.desiredCurvature if CC.latActive else self.curvature new_desired_curvature = model_v2.action.desiredCurvature if CC.latActive else self.curvature
assist = self.turn_assist_enabled() assist = self.turn_assist_enabled()
rolling = math.isfinite(CS.vEgo) and CS.vEgo > max(0.1 * CV.MPH_TO_MS, self.CP.minSteerSpeed) rolling = math.isfinite(CS.vEgo) and CS.vEgo > max(0.1 * CV.MPH_TO_MS, self.CP.minSteerSpeed)
if ( assist_ready = (
assist assist
and rolling
and self.sm.all_checks(['modelV2']) and self.sm.all_checks(['modelV2'])
and CC.latActive and CC.latActive
and not CS.standstill
and not CS.steerFaultTemporary and not CS.steerFaultTemporary
and not CS.steerFaultPermanent and not CS.steerFaultPermanent
and CS.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low) and CS.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low)
): )
if assist_ready and rolling and not CS.standstill:
self.model_turn_assist.curvature = self.curvature self.model_turn_assist.curvature = self.curvature
self.model_turn_assist.twitch_guard_remaining = update_twitch_guard(self.model_turn_assist.twitch_guard_remaining, CS.vEgo, CS.standstill) self.model_turn_assist.twitch_guard_armed = update_twitch_guard(self.model_turn_assist.twitch_guard_armed, CS.vEgo, CS.standstill)
new_desired_curvature = self.model_turn_assist.update(CS, model_v2, CC, new_desired_curvature) new_desired_curvature = self.model_turn_assist.update(CS, model_v2, CC, new_desired_curvature)
elif assist_ready:
self.model_turn_assist.curvature = self.curvature
new_desired_curvature = self.model_turn_assist.update_stopped(CS, new_desired_curvature)
self.model_turn_assist.twitch_guard_armed = update_twitch_guard(self.model_turn_assist.twitch_guard_armed, CS.vEgo, CS.standstill)
elif getattr(self, 'model_turn_assist', None) is not None: elif getattr(self, 'model_turn_assist', None) is not None:
self.model_turn_assist.reset() self.model_turn_assist.reset()
self.model_turn_assist.twitch_guard_remaining = update_twitch_guard(0.0, CS.vEgo, CS.standstill) self.model_turn_assist.twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
lane_base_curvature = new_desired_curvature lane_base_curvature = new_desired_curvature
self.lane_centering_applied = 0.0 self.lane_centering_applied = 0.0
self.lane_centering_inactive_reason = 'inactive' self.lane_centering_inactive_reason = 'inactive'
File diff suppressed because one or more lines are too long
@@ -373,12 +373,11 @@ class LongitudinalPlanner:
cruise_profile = replace(cruise_profile, cruise_brake_magnitude=global_magnitude) cruise_profile = replace(cruise_profile, cruise_brake_magnitude=global_magnitude)
if sm['controlsState'].forceDecel: if sm['controlsState'].forceDecel:
cruise_profile = None cruise_profile = None
elif (ceiling.effective_mps is not None or curve.effective_mps is not None) and cruise_profile is not None: elif curve.effective_mps is not None and cruise_profile is not None:
# An eligible lower ceiling must retain at least native approach # Curve approach retains native braking when the saved cruise response is softer.
# braking even when the saved profile requests a softer cruise response.
cruise_profile = replace(cruise_profile, cruise_brake_magnitude=max(cruise_profile.cruise_brake_magnitude, cruise_profile = replace(cruise_profile, cruise_brake_magnitude=max(cruise_profile.cruise_brake_magnitude,
abs(A_CRUISE_MIN))) abs(A_CRUISE_MIN)))
if ceiling.effective_mps is not None or curve.effective_mps is not None: if curve.effective_mps is not None:
global_floor = min(global_floor, A_CRUISE_MIN) global_floor = min(global_floor, A_CRUISE_MIN)
if selected_acceleration is not None and cruise_profile is not None: if selected_acceleration is not None and cruise_profile is not None:
# The selected curve owns acceleration; following/jerks retain their owner. # The selected curve owns acceleration; following/jerks retain their owner.
+37 -116
View File
@@ -1,8 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import json
from collections import deque from collections import deque
from dataclasses import replace
from opendbc.car.structs import car from opendbc.car.structs import car
from openpilot.common.params import Params from openpilot.common.params import Params
@@ -12,8 +10,9 @@ from openpilot.selfdrive.controls.lib.ldw import LaneDepartureWarning
from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner, NATIVE_PLAN_INPUTS from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner, NATIVE_PLAN_INPUTS
import openpilot.cereal.messaging as messaging import openpilot.cereal.messaging as messaging
from openpilot.cereal.services import SERVICE_LIST from openpilot.cereal.services import SERVICE_LIST
from openpilot.starpilot.speed_limits import history as slc_history from openpilot.starpilot.speed_limits.planner_host import (
from openpilot.starpilot.speed_limits.runtime import Action as SlcAction, CruiseEvent as SlcCruiseEvent, Runtime as SlcRuntime SLC_ACTIONS, SavedSlcLifecycle, action_from_message, cruise_event_from_message, current_cruise_event, receive_slc_events,
)
from openpilot.starpilot.longitudinal.profile_runtime import ProfileHost from openpilot.starpilot.longitudinal.profile_runtime import ProfileHost
from openpilot.starpilot.longitudinal.lane_change_gap import LaneGapPreferences from openpilot.starpilot.longitudinal.lane_change_gap import LaneGapPreferences
from openpilot.starpilot.longitudinal.experimental_release import ConditionalHandoff from openpilot.starpilot.longitudinal.experimental_release import ConditionalHandoff
@@ -40,62 +39,8 @@ from openpilot.starpilot.feature_capabilities import longitudinal_supported
from openpilot.starpilot.conditional_mode.projection import paired_clocks_ns from openpilot.starpilot.conditional_mode.projection import paired_clocks_ns
from openpilot.starpilot.conditional_mode.ui_action import observation as ui_manual_observation from openpilot.starpilot.conditional_mode.ui_action import observation as ui_manual_observation
from openpilot.starpilot.longitudinal.cruise_ceiling import CurveCeiling from openpilot.starpilot.longitudinal.cruise_ceiling import CurveCeiling
from openpilot.starpilot.feature_runtime import (enabled as feature_enabled, requested as feature_requested, from openpilot.starpilot.feature_runtime import enabled as feature_enabled, requested as feature_requested, slc_transport_capable
slc_runtime_settings, slc_transport_capable, vision_control_enabled)
import time import time
from openpilot.starpilot.speed_limits.runtime_settings import read_params as read_slc_settings
class SavedSlcLifecycle:
"""Refresh saved admission; offsets and display units preserve driver choices."""
def __init__(self, params, cp, environment):
self.params, self.cp, self.environment = params, cp, dict(environment)
self.runtime = None
self.configuration = None
self.last_refresh_ns = None
def refresh(self, now_ns: int, *, pending_actions=None, pending_cruise=None):
if self.last_refresh_ns is not None and 0 <= now_ns - self.last_refresh_ns < 1_000_000_000:
return self.runtime, False
self.last_refresh_ns = now_ns
# One immutable parsed snapshot owns this refresh. Repeated qualification
# used to reopen the same saved keys five times in a due model iteration.
saved_slc = read_slc_settings(self.params)
admitted = feature_enabled(self.params, self.cp, 'slc', self.environment, saved_slc=saved_slc)
settings = slc_runtime_settings(self.params, self.cp, self.environment, saved_slc=saved_slc)
vision = admitted and feature_enabled(self.params, self.cp, 'vision', self.environment, saved_slc=saved_slc)
configuration = (admitted and not settings.errors, settings, vision,
vision_control_enabled(self.params, self.cp, saved_slc=saved_slc),
feature_enabled(self.params, self.cp, 'vision', {}, saved_slc=saved_slc),
self.params.get_bool('IsMetric'))
if configuration == self.configuration:
return self.runtime, False
previous_runtime = self.runtime
if (self.runtime is not None and self.configuration is not None and
configuration[:-1] == (self.configuration[0], replace(self.runtime.settings, offsets=settings.offsets,
advance_seconds=settings.advance_seconds),
*self.configuration[2:-1])):
if settings.offsets != self.runtime.settings.offsets or configuration[5] != self.configuration[5]:
self.runtime.update_offsets(settings.offsets, is_metric=configuration[5])
if settings.advance_seconds != self.runtime.settings.advance_seconds:
self.runtime.update_advance(settings.advance_seconds)
else:
set_speed_after_ns = self.runtime.set_speed_after_ns if self.runtime is not None else 0
if self.runtime is not None:
self.runtime.reset()
self.runtime = (SlcRuntime(settings, vision_enabled=vision,
vision_control_qualified=configuration[3],
vision_display_qualified=configuration[4], is_metric=configuration[5])
if configuration[0] else None)
if self.runtime is not None:
self.runtime.set_speed_after_ns = set_speed_after_ns
self.configuration = configuration
if pending_actions is not None:
pending_actions.clear()
if pending_cruise is not None and (self.runtime is None or self.runtime is not previous_runtime):
pending_cruise.clear()
return self.runtime, True
def profile_for_frame(host: ProfileHost | None, sm, CP, now_ns: int, *, traffic_mode: bool | None = False): def profile_for_frame(host: ProfileHost | None, sm, CP, now_ns: int, *, traffic_mode: bool | None = False):
@@ -159,11 +104,13 @@ def traffic_profile_status(mode: bool | None, target, applied, settings) -> tupl
def curve_for_frame(host: CurveHost | None, sm, CP, now_ns: int, *, drive_id: int = 0, def curve_for_frame(host: CurveHost | None, sm, CP, now_ns: int, *, drive_id: int = 0,
event: CurveDriverEvent | None = None, follow_time_s: float | None = None): event: CurveDriverEvent | None = None, follow_time_s: float | None = None,
cruise_ceiling_mps: float | None = None):
"""A diagnostic runtime result is not planner authority by itself.""" """A diagnostic runtime result is not planner authority by itself."""
if host is None: if host is None:
return None, None return None, None
result = host.sample(sm, CP, now_ns, drive_id=drive_id, event=event, follow_time_s=follow_time_s) result = host.sample(sm, CP, now_ns, drive_id=drive_id, event=event, follow_time_s=follow_time_s,
cruise_ceiling_mps=cruise_ceiling_mps)
if result.ceiling_mps is None: if result.ceiling_mps is None:
return None, result return None, result
model_ns = sm.logMonoTime.get('modelV2', 0) model_ns = sm.logMonoTime.get('modelV2', 0)
@@ -177,6 +124,12 @@ def confirm_curve_frame(host: CurveHost | None, planner: LongitudinalPlanner, no
host.runtime.confirm_applied(now_ns, applied=bool(planner.last_curve_ceiling_applied)) host.runtime.confirm_applied(now_ns, applied=bool(planner.last_curve_ceiling_applied))
def wheel_override_blocked(force_stop: ForceStopRuntime | None, curve_host: CurveHost | None, *, curve_backlog: bool = False) -> bool:
# Force Stop can consume RES on the tick it commits, before a forcing plan is published.
return ((force_stop is not None and (force_stop.policy.can_commit_next_frame or force_stop.plan.speed_ceiling_mps is not None)) or
(curve_host is not None and (curve_backlog or curve_host.runtime.was_controlling)))
def conditional_handoff_for_frame(host: ConditionalPlannerHost | None, sm, CP, now_ns: int, def conditional_handoff_for_frame(host: ConditionalPlannerHost | None, sm, CP, now_ns: int,
drive_id: int) -> ConditionalHandoff | None: drive_id: int) -> ConditionalHandoff | None:
if host is None or not CP.openpilotLongitudinalControl or CP.passive or CP.dashcamOnly: if host is None or not CP.openpilotLongitudinalControl or CP.passive or CP.dashcamOnly:
@@ -290,7 +243,8 @@ def update_curve_frame(planner: LongitudinalPlanner, sm, CP, now_ns: int, *, hos
results = [] results = []
def provider(follow_time_s: float | None): def provider(follow_time_s: float | None):
ceiling, result = curve_for_frame(host, sm, CP, now_ns, drive_id=drive_id, ceiling, result = curve_for_frame(host, sm, CP, now_ns, drive_id=drive_id,
event=event, follow_time_s=follow_time_s) event=event, follow_time_s=follow_time_s,
cruise_ceiling_mps=cruise_ceiling.speed_mps if cruise_ceiling is not None else None)
results.append(result) results.append(result)
return ceiling return ceiling
planner.update(sm, cruise_ceiling=cruise_ceiling, profile_tuning=profile_tuning, planner.update(sm, cruise_ceiling=cruise_ceiling, profile_tuning=profile_tuning,
@@ -320,18 +274,7 @@ def queue_cruise_event(event, slc_events, curve_events, conditional_events=None,
curve_events.append(CurveDriverEvent(str(cruise.producerSessionId), int(cruise.eventId), curve_events.append(CurveDriverEvent(str(cruise.producerSessionId), int(cruise.eventId),
int(cruise.observedMonoTime), kind, str(cruise.button), int(event.logMonoTime))) int(cruise.observedMonoTime), kind, str(cruise.button), int(event.logMonoTime)))
else: else:
slc_events.append(SlcCruiseEvent(int(cruise.eventId), int(cruise.observedMonoTime), slc_events.append(cruise_event_from_message(event))
float(cruise.previousMps), float(cruise.selectedMps), str(cruise.button),
str(cruise.producerSessionId), int(event.logMonoTime), kind,
str(cruise.sessionId), int(cruise.decisionId),
int(cruise.presentationId), int(cruise.commandId)))
def current_cruise_event(events, now_ns: int):
max_event_age_ns = int(2e9 / SERVICE_LIST['modelV2'].frequency)
while events and now_ns - events[0].observed_ns > max_event_age_ns:
events.popleft()
return events.popleft() if events and events[0].observed_ns <= now_ns else None
def queue_ui_action(event, slc_actions, conditional_actions, mode_actions=None) -> None: def queue_ui_action(event, slc_actions, conditional_actions, mode_actions=None) -> None:
@@ -343,9 +286,8 @@ def queue_ui_action(event, slc_actions, conditional_actions, mode_actions=None)
mode_actions.append(event) mode_actions.append(event)
elif kind == 'conditionalModeCycle': elif kind == 'conditionalModeCycle':
conditional_actions.append(event) conditional_actions.append(event)
elif kind in ('accept', 'reject', 'adopt'): elif kind in SLC_ACTIONS:
slc_actions.append((int(event.logMonoTime), SlcAction(str(request.sessionId), int(request.sequenceId), slc_actions.append(action_from_message(event))
int(request.decisionId), int(request.presentationId), kind)))
def current_ui_manual_event(events, now_ns: int): def current_ui_manual_event(events, now_ns: int):
@@ -417,7 +359,7 @@ def starpilot_main():
pending_switchback = deque(maxlen=8) pending_switchback = deque(maxlen=8)
mode_settings = ConditionalSettingsOwner(params) if mode_owner is not None else None mode_settings = ConditionalSettingsOwner(params) if mode_owner is not None else None
slc_lifecycle = SavedSlcLifecycle(params, CP, os.environ) slc_lifecycle = SavedSlcLifecycle(params, CP, os.environ)
slc_runtime, _ = slc_lifecycle.refresh(0) slc_lifecycle.refresh(0)
slc_action_sock = (messaging.sub_sock("slcAction", conflate=False) slc_action_sock = (messaging.sub_sock("slcAction", conflate=False)
if slc_available or conditional_host is not None or mode_owner is not None else None) if slc_available or conditional_host is not None or mode_owner is not None else None)
slc_cruise_sock = messaging.sub_sock("slcCruiseEvent", conflate=False) slc_cruise_sock = messaging.sub_sock("slcCruiseEvent", conflate=False)
@@ -431,18 +373,14 @@ def starpilot_main():
publish_services = ['longitudinalPlan', 'starpilotLongitudinalPlan', 'driverAssistance'] publish_services = ['longitudinalPlan', 'starpilotLongitudinalPlan', 'driverAssistance']
if slc_available or curve_host is not None or conditional_host is not None or traffic_owner is not None or mode_owner is not None: if slc_available or curve_host is not None or conditional_host is not None or traffic_owner is not None or mode_owner is not None:
publish_services.append('slcState') publish_services.append('slcState')
if slc_available:
publish_services.append('slcCruiseCommand')
pm = messaging.PubMaster(publish_services) pm = messaging.PubMaster(publish_services)
native_plan_checks = list(NATIVE_PLAN_INPUTS) native_plan_checks = list(NATIVE_PLAN_INPUTS)
subscribed_services = list(NATIVE_PLAN_INPUTS) subscribed_services = list(NATIVE_PLAN_INPUTS)
subscribed_services.append('deviceState') subscribed_services.append('deviceState')
if conditional_host is not None: if conditional_host is not None:
subscribed_services.append('starpilotRadarState') subscribed_services.append('starpilotRadarState')
optional_slc = ['slcDashboardObservation', 'slcVisionObservation', 'mapdOut', 'starpilotCarState'] if slc_available else [] optional_slc = slc_lifecycle.source_services() if slc_available else []
if slc_available and feature_enabled(params, CP, 'aol', os.environ): if force_stop_owner is not None:
optional_slc.append('aolAxisState')
if force_stop_owner is not None and 'starpilotCarState' not in optional_slc:
optional_slc.append('starpilotCarState') optional_slc.append('starpilotCarState')
if force_stop_owner is not None and 'slcVisionObservation' not in optional_slc: if force_stop_owner is not None and 'slcVisionObservation' not in optional_slc:
optional_slc.append('slcVisionObservation') optional_slc.append('slcVisionObservation')
@@ -461,16 +399,14 @@ def starpilot_main():
# Due saved-setting verification can block on Params. Complete it # Due saved-setting verification can block on Params. Complete it
# before acquiring the model and fast-source batch, not after that # before acquiring the model and fast-source batch, not after that
# batch has already begun aging toward the CEM freshness deadline. # batch has already begun aging toward the CEM freshness deadline.
slc_runtime, _ = slc_lifecycle.refresh(time.monotonic_ns(), pending_actions=pending_slc_actions, slc_lifecycle.refresh(time.monotonic_ns(), pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
pending_cruise=pending_slc_cruise)
sm.update() sm.update()
if sm.updated['modelV2']: if sm.updated['modelV2']:
# Only explicit replay uses the recorded model timeline. In a live host, # Only explicit replay uses the recorded model timeline. In a live host,
# modelV2 may lag newer inputs in the same SubMaster update. # modelV2 may lag newer inputs in the same SubMaster update.
now_ns = int(sm.logMonoTime['modelV2']) if 'REPLAY' in os.environ else time.monotonic_ns() now_ns = int(sm.logMonoTime['modelV2']) if 'REPLAY' in os.environ else time.monotonic_ns()
if 'REPLAY' in os.environ: if 'REPLAY' in os.environ:
slc_runtime, _ = slc_lifecycle.refresh(now_ns, pending_actions=pending_slc_actions, slc_lifecycle.refresh(now_ns, pending_actions=pending_slc_actions, pending_cruise=pending_slc_cruise)
pending_cruise=pending_slc_cruise)
current_start_ns = (int(sm['deviceState'].startedMonoTime) current_start_ns = (int(sm['deviceState'].startedMonoTime)
if 'deviceState' in subscribed_services and sm.valid['deviceState'] and if 'deviceState' in subscribed_services and sm.valid['deviceState'] and
sm.alive['deviceState'] and 0 < sm.logMonoTime['deviceState'] <= now_ns else 0) sm.alive['deviceState'] and 0 < sm.logMonoTime['deviceState'] <= now_ns else 0)
@@ -481,10 +417,7 @@ def starpilot_main():
planner_status = None planner_status = None
drive_changed = current_start_ns > 0 and drive_start_ns > 0 and current_start_ns != drive_start_ns drive_changed = current_start_ns > 0 and drive_start_ns > 0 and current_start_ns != drive_start_ns
if slc_cruise_sock is not None: if slc_cruise_sock is not None:
for _ in range(8): for event in receive_slc_events(slc_cruise_sock):
event = messaging.recv_one_or_none(slc_cruise_sock)
if event is None:
break
if str(event.slcCruiseEvent.kind) == 'wheelAction' and event.valid: if str(event.slcCruiseEvent.kind) == 'wheelAction' and event.valid:
pending_wheel.append(event) pending_wheel.append(event)
continue continue
@@ -507,10 +440,7 @@ def starpilot_main():
if traffic_owner is not None: if traffic_owner is not None:
traffic_owner.reset() traffic_owner.reset()
if slc_action_sock is not None: if slc_action_sock is not None:
for _ in range(8): for event in receive_slc_events(slc_action_sock):
event = messaging.recv_one_or_none(slc_action_sock)
if event is None:
break
queue_ui_action(event, pending_slc_actions, pending_conditional_ui, pending_modes) queue_ui_action(event, pending_slc_actions, pending_conditional_ui, pending_modes)
waiting_wheel = deque(maxlen=32) waiting_wheel = deque(maxlen=32)
while pending_wheel: while pending_wheel:
@@ -522,25 +452,13 @@ def starpilot_main():
else: else:
wheel_coast.receive(event, params, CP, sm, now_ns=now_ns) wheel_coast.receive(event, params, CP, sm, now_ns=now_ns)
pending_wheel = waiting_wheel pending_wheel = waiting_wheel
if slc_runtime is not None: # Curve observes the press before SLC sees the release. A queued Curve press can still own the tap.
if drive_changed or slc_runtime.state.reset_required or slc_runtime.ledger.reset_required: curve_event = current_cruise_event(pending_curve_events, now_ns)
slc_runtime.reset() slc_output = slc_lifecycle.step(sm, now_ns, pending_slc_actions, pending_slc_cruise, drive_changed=drive_changed,
pending_slc_actions.clear() wheel_override_blocked=wheel_override_blocked(force_stop_owner, curve_host, curve_backlog=bool(pending_curve_events)))
pending_slc_cruise.clear() cruise_ceiling = slc_output.result.ceiling if slc_output is not None else None
max_event_age_ns = int(2e9 / SERVICE_LIST['modelV2'].frequency) if slc_output is not None:
while pending_slc_actions and now_ns - pending_slc_actions[0][0] > max_event_age_ns: planner_status = slc_output.message
pending_slc_actions.popleft()
cruise_event = current_cruise_event(pending_slc_cruise, now_ns)
request = (pending_slc_actions.popleft()[1] if cruise_event is None and pending_slc_actions and
pending_slc_actions[0][0] <= now_ns else None)
output = slc_runtime.step(sm, CP, now_ns=now_ns, request=request, cruise_event=cruise_event)
planner_status = output.message
if output.command is not None:
pm.send('slcCruiseCommand', output.command)
history_write = output.result.acceptance.history_write if output.result.acceptance is not None else None
# A camera episode has no road-location identity for a later drive.
if history_write is not None and history_write.candidate.source != 'vision':
params.put("SLCQualifiedHistory", json.loads(slc_history.encode(history_write, time.time_ns())))
needs_clock = conditional_host is not None or traffic_owner is not None or force_stop_owner is not None or mode_owner is not None needs_clock = conditional_host is not None or traffic_owner is not None or force_stop_owner is not None or mode_owner is not None
clock_pair = paired_clocks_ns() if needs_clock and 'REPLAY' not in os.environ else None clock_pair = paired_clocks_ns() if needs_clock and 'REPLAY' not in os.environ else None
controller_traffic_toggle = bool(wheel_coast.traffic_toggles % 2) controller_traffic_toggle = bool(wheel_coast.traffic_toggles % 2)
@@ -600,7 +518,6 @@ def starpilot_main():
lead_approach_key = lead_approach_for_frame(approach_preferences, sm, CP, now_ns) lead_approach_key = lead_approach_for_frame(approach_preferences, sm, CP, now_ns)
if curve_preferences is not None and curve_host is not None: if curve_preferences is not None and curve_host is not None:
curve_preferences.refresh(curve_host, now_ns) curve_preferences.refresh(curve_host, now_ns)
curve_event = current_cruise_event(pending_curve_events, now_ns)
conditional_handoff = (conditional_handoff_for_frame(conditional_host, sm, CP, clock_pair[0], current_start_ns) conditional_handoff = (conditional_handoff_for_frame(conditional_host, sm, CP, clock_pair[0], current_start_ns)
if clock_pair is not None else None) if clock_pair is not None else None)
wheel_coast.conditional_stop = bool(conditional_handoff is not None and conditional_host is not None and wheel_coast.conditional_stop = bool(conditional_handoff is not None and conditional_host is not None and
@@ -617,6 +534,7 @@ def starpilot_main():
drive_id=current_start_ns, follow_seconds=follow_seconds, drive_id=current_start_ns, follow_seconds=follow_seconds,
traffic_mode=traffic_mode, takeoff_enabled=faster_lead_takeoff) traffic_mode=traffic_mode, takeoff_enabled=faster_lead_takeoff)
curve_result = update_curve_frame(longitudinal_planner, sm, CP, now_ns, host=curve_host, curve_result = update_curve_frame(longitudinal_planner, sm, CP, now_ns, host=curve_host,
cruise_ceiling=cruise_ceiling,
profile_tuning=profile_tuning, profile_tuning=profile_tuning,
traffic_mode=traffic_mode, lane_change_policy=lane_change_policy, traffic_mode=traffic_mode, lane_change_policy=lane_change_policy,
global_braking_response=global_braking_response, selected_profiles=selected_profiles, global_braking_response=global_braking_response, selected_profiles=selected_profiles,
@@ -643,6 +561,7 @@ def starpilot_main():
proposal, snapshot = conditional_host.sample( proposal, snapshot = conditional_host.sample(
sm, CP, longitudinal_planner, now_mono_ns=conditional_now_ns, now_boot_ns=conditional_boot_ns, sm, CP, longitudinal_planner, now_mono_ns=conditional_now_ns, now_boot_ns=conditional_boot_ns,
sample_skew_ns=conditional_skew_ns, drive_id=current_start_ns, sample_skew_ns=conditional_skew_ns, drive_id=current_start_ns,
cruise_ceiling_mps=cruise_ceiling.speed_mps if cruise_ceiling is not None else None,
owner_context=ConditionalOwnerContext( owner_context=ConditionalOwnerContext(
traffic_mode=traffic_observation(traffic_verdict, model_ns=int(sm.logMonoTime['modelV2']), traffic_mode=traffic_observation(traffic_verdict, model_ns=int(sm.logMonoTime['modelV2']),
owner_present=traffic_owner is not None), owner_present=traffic_owner is not None),
@@ -677,6 +596,8 @@ def starpilot_main():
mode_owner.sample('switchback', sm, CP, now_ns=now_ns), session=mode_session, mode_owner.sample('switchback', sm, CP, now_ns=now_ns), session=mode_session,
sequence=mode_sequence, now_ns=now_ns, source_car_control_ns=int(sm.logMonoTime['carControl'])) sequence=mode_sequence, now_ns=now_ns, source_car_control_ns=int(sm.logMonoTime['carControl']))
if planner_status is not None: if planner_status is not None:
if planner_status.slcState.wheelOverrideSince and wheel_override_blocked(force_stop_owner, curve_host):
planner_status.slcState.wheelOverrideSince = 0
pm.send('slcState', planner_status) pm.send('slcState', planner_status)
if current_start_ns > 0: if current_start_ns > 0:
drive_start_ns = current_start_ns drive_start_ns = current_start_ns
@@ -9,6 +9,7 @@ import unittest
from openpilot.cereal import messaging from openpilot.cereal import messaging
from openpilot.common.params import Params from openpilot.common.params import Params
from openpilot.starpilot import feature_runtime from openpilot.starpilot import feature_runtime
from openpilot.starpilot.speed_limits import planner_host as slc_host
from openpilot.starpilot.speed_limits.runtime_settings import read_params as read_slc_settings from openpilot.starpilot.speed_limits.runtime_settings import read_params as read_slc_settings
from openpilot.selfdrive.controls import plannerd from openpilot.selfdrive.controls import plannerd
from openpilot.starpilot.conditional_mode.tests import test_status_consumer as transport from openpilot.starpilot.conditional_mode.tests import test_status_consumer as transport
@@ -98,7 +99,7 @@ class TestCemInputAcquisitionOrder(unittest.TestCase):
def read(params): def read(params):
reads.append(True) reads.append(True)
return read_slc_settings(params) return read_slc_settings(params)
with patch.object(plannerd, 'read_slc_settings', side_effect=read, create=True), \ with patch.object(slc_host, 'read_slc_settings', side_effect=read), \
patch.object(feature_runtime, 'read_slc_settings', side_effect=read): patch.object(feature_runtime, 'read_slc_settings', side_effect=read):
runtime, changed = owner.refresh(MONO) runtime, changed = owner.refresh(MONO)
self.assertTrue(changed) self.assertTrue(changed)
@@ -23,21 +23,21 @@ from openpilot.starpilot.conditional_mode.projection import ConditionalOwnerCont
from openpilot.starpilot.conditional_mode.runtime_settings import DOCUMENT_KEY from openpilot.starpilot.conditional_mode.runtime_settings import DOCUMENT_KEY
from openpilot.starpilot.conditional_mode.status import settings_fingerprint from openpilot.starpilot.conditional_mode.status import settings_fingerprint
from openpilot.starpilot.conditional_mode.tests.test_projection import BOOT, MONO, FakeSubMaster, serialized_scene from openpilot.starpilot.conditional_mode.tests.test_projection import BOOT, MONO, FakeSubMaster, serialized_scene
from openpilot.starpilot.speed_limits.runtime import Action as SlcAction, CruiseEvent as SlcCruiseEvent
class TestConditionalRuntimeLoop(unittest.TestCase): class TestConditionalRuntimeLoop(unittest.TestCase):
def test_slc_unit_change_keeps_receipts_for_the_current_command(self): def test_slc_unit_change_preserves_cap_and_queued_driver_event(self):
from openpilot.selfdrive.car.cruise import slc_target_kph
from openpilot.starpilot.speed_limits import offset_document as od from openpilot.starpilot.speed_limits import offset_document as od
from openpilot.starpilot.speed_limits.runtime import Action, CruiseEvent from openpilot.starpilot.speed_limits.runtime import Action, CruiseEvent
from openpilot.starpilot.speed_limits.tests.test_runtime_replay import RuntimeReplayTests from openpilot.starpilot.speed_limits.tests import test_runtime_replay as replay
fixture = RuntimeReplayTests() fixture = replay.RuntimeReplayTests()
fixture.setUp() fixture.setUp()
sm, cp = fixture.sm, fixture.cp sm, cp = fixture.sm, fixture.cp
with tempfile.TemporaryDirectory() as directory: with tempfile.TemporaryDirectory() as directory:
params = Params(directory) params = Params(directory)
params.put_bool('SpeedLimitController', True, block=True) params.put_bool('SpeedLimitController', True, block=True)
params.put_bool('SLCConfirmation', True, block=True) params.put('SLCConfirmation', 1, block=True)
params.put('SLCPriority1', 'Dashboard', block=True) params.put('SLCPriority1', 'Dashboard', block=True)
params.put('SLCOffsetSchedule', od.to_value(od.default_document(False)), block=True) params.put('SLCOffsetSchedule', od.to_value(od.default_document(False)), block=True)
owner = plannerd.SavedSlcLifecycle(params, cp, {}) owner = plannerd.SavedSlcLifecycle(params, cp, {})
@@ -46,20 +46,19 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
sm.advance(2_900_000_000) sm.advance(2_900_000_000)
pending = runtime.step(sm, cp, now_ns=2_900_000_000).message.slcState pending = runtime.step(sm, cp, now_ns=2_900_000_000).message.slcState
sm.advance(2_950_000_000) sm.advance(2_950_000_000)
issued = runtime.step(sm, cp, now_ns=2_950_000_000, accepted = runtime.step(sm, cp, now_ns=2_950_000_000,
request=Action(runtime.session_id, 1, pending.decisionId, pending.presentationId, 'accept')) request=Action(runtime.session_id, 1, pending.decisionId, pending.presentationId, 'accept'))
command = issued.command.slcCruiseCommand self.assertEqual(accepted.result.ceiling.speed_mps, 25.)
selected = slc_target_kph(command.targetMps, False) events = deque([CruiseEvent(1, 2_990_000_000, 60/3.6, 65/3.6, 'accel', 'card-producer', 2_990_000_000)])
receipts = deque([CruiseEvent(1, 2_990_000_000, 60 / 3.6, selected / 3.6, '', 'card-producer',
2_990_000_000, 'commandApplied', runtime.session_id, command.decisionId, command.presentationId, command.commandId)])
params.put_bool('IsMetric', True, block=True) params.put_bool('IsMetric', True, block=True)
metric, _ = owner.refresh(3_000_000_000, pending_cruise=receipts) metric, _ = owner.refresh(3_000_000_000, pending_cruise=events)
self.assertEqual(len(receipts), 1) self.assertIs(metric, runtime)
sm['carState'].vCruise = sm['carState'].vCruiseCluster = selected self.assertEqual(len(events), 1)
sm['carState'].vCruise = sm['carState'].vCruiseCluster = 65.
sm.advance(3_000_000_000) sm.advance(3_000_000_000)
applied = metric.step(sm, cp, now_ns=3_000_000_000, cruise_event=receipts.popleft()) output = metric.step(sm, cp, now_ns=3_000_000_000, cruise_event=events.popleft())
self.assertEqual(applied.message.slcState.commandStatus, 'applied') self.assertEqual(output.result.ceiling.speed_mps, 25.)
self.assertIsNone(applied.command) self.assertEqual(sm['carState'].vCruise, 65.)
def test_slc_unit_changes_preserve_set_speed_and_driver_choices(self): def test_slc_unit_changes_preserve_set_speed_and_driver_choices(self):
from openpilot.common.constants import CV from openpilot.common.constants import CV
@@ -68,14 +67,14 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
from openpilot.starpilot.speed_limits.runtime import Action, CruiseEvent from openpilot.starpilot.speed_limits.runtime import Action, CruiseEvent
from openpilot.starpilot.speed_limits.tests.test_runtime_replay import RuntimeReplayTests from openpilot.starpilot.speed_limits.tests.test_runtime_replay import RuntimeReplayTests
now = 2_000_000_000 now = 2_000_000_000
for confirmation, choice in ((False, 'applied'), (True, 'applied'), (False, 'override'), (True, 'decline')): for confirmation, choice in ((False, 'applied'), (True, 'applied'), (False, 'ceiling'), (True, 'decline')):
with self.subTest(confirmation=confirmation, choice=choice), tempfile.TemporaryDirectory() as directory: with self.subTest(confirmation=confirmation, choice=choice), tempfile.TemporaryDirectory() as directory:
fixture = RuntimeReplayTests() fixture = RuntimeReplayTests()
fixture.setUp() fixture.setUp()
sm, cp = fixture.sm, fixture.cp sm, cp = fixture.sm, fixture.cp
params = Params(directory) params = Params(directory)
params.put_bool('SpeedLimitController', True, block=True) params.put_bool('SpeedLimitController', True, block=True)
params.put_bool('SLCConfirmation', confirmation, block=True) params.put('SLCConfirmation', int(confirmation), block=True)
params.put('SLCPriority1', 'Dashboard', block=True) params.put('SLCPriority1', 'Dashboard', block=True)
params.put('SLCOffsetSchedule', od.to_value(od.default_document(False)), block=True) params.put('SLCOffsetSchedule', od.to_value(od.default_document(False)), block=True)
owner = plannerd.SavedSlcLifecycle(params, cp, {}) owner = plannerd.SavedSlcLifecycle(params, cp, {})
@@ -84,14 +83,14 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
baseline = slc_target_kph(65 * CV.MPH_TO_MS, False) baseline = slc_target_kph(65 * CV.MPH_TO_MS, False)
sm['carState'].vCruise = sm['carState'].vCruiseCluster = baseline sm['carState'].vCruise = sm['carState'].vCruiseCluster = baseline
aligned = original.step(sm, cp, now_ns=now) aligned = original.step(sm, cp, now_ns=now)
self.assertIsNone(aligned.command) self.assertTrue(aligned.message.slcState.hasAccepted)
if choice == 'override': if choice == 'ceiling':
selected = slc_target_kph(70 * CV.MPH_TO_MS, False) selected = slc_target_kph(70 * CV.MPH_TO_MS, False)
sm['carState'].vCruise = sm['carState'].vCruiseCluster = selected sm['carState'].vCruise = sm['carState'].vCruiseCluster = selected
sm.advance(now + 50_000_000) sm.advance(now + 50_000_000)
chosen = original.step(sm, cp, now_ns=now + 50_000_000, cruise_event=CruiseEvent( chosen = original.step(sm, cp, now_ns=now + 50_000_000, cruise_event=CruiseEvent(
1, now + 50_000_000, baseline / 3.6, selected / 3.6, 'accel', 'card-producer', now + 50_000_000)) 1, now + 50_000_000, baseline / 3.6, selected / 3.6, 'accel', 'card-producer', now + 50_000_000))
self.assertTrue(chosen.message.slcState.driverOverrideActive) self.assertFalse(chosen.message.slcState.driverOverrideActive)
elif choice == 'decline': elif choice == 'decline':
sm['slcDashboardObservation'].speedMps = 55 * CV.MPH_TO_MS sm['slcDashboardObservation'].speedMps = 55 * CV.MPH_TO_MS
sm.advance(now + 50_000_000) sm.advance(now + 50_000_000)
@@ -105,11 +104,10 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
self.assertTrue(changed) self.assertTrue(changed)
sm.advance(now + 1_000_000_000) sm.advance(now + 1_000_000_000)
output = metric.step(sm, cp, now_ns=now + 1_000_000_000) output = metric.step(sm, cp, now_ns=now + 1_000_000_000)
self.assertIsNone(output.command)
self.assertFalse(output.message.slcState.hasPending) self.assertFalse(output.message.slcState.hasPending)
self.assertTrue(output.message.slcState.hasAccepted) self.assertTrue(output.message.slcState.hasAccepted)
self.assertEqual(sm['carState'].vCruise, selected) self.assertEqual(sm['carState'].vCruise, selected)
self.assertEqual(output.message.slcState.driverOverrideActive, choice == 'override') self.assertFalse(output.message.slcState.driverOverrideActive)
if choice == 'decline': if choice == 'decline':
self.assertEqual(output.result.acceptance.basis, 'rejected') self.assertEqual(output.result.acceptance.basis, 'rejected')
@@ -122,13 +120,11 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
owner = plannerd.SavedSlcLifecycle(params, cp, {}) owner = plannerd.SavedSlcLifecycle(params, cp, {})
imperial, _ = owner.refresh(MONO) imperial, _ = owner.refresh(MONO)
self.assertFalse(imperial.is_metric) self.assertFalse(imperial.is_metric)
imperial.set_speed_after_ns = MONO + 1_050_000_000
actions, cruise = deque([object()]), deque([object()]) actions, cruise = deque([object()]), deque([object()])
params.put_bool('IsMetric', True, block=True) params.put_bool('IsMetric', True, block=True)
metric, changed = owner.refresh(MONO + 1_000_000_000, pending_actions=actions, pending_cruise=cruise) metric, changed = owner.refresh(MONO + 1_000_000_000, pending_actions=actions, pending_cruise=cruise)
self.assertTrue(changed) self.assertTrue(changed)
self.assertTrue(metric.is_metric) self.assertTrue(metric.is_metric)
self.assertEqual(metric.set_speed_after_ns, MONO + 1_050_000_000)
self.assertIs(metric, imperial) self.assertIs(metric, imperial)
self.assertFalse(actions) self.assertFalse(actions)
self.assertEqual(len(cruise), 1) self.assertEqual(len(cruise), 1)
@@ -168,7 +164,7 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
# Status and transport are reserved independently of saved SLC/CEM # Status and transport are reserved independently of saved SLC/CEM
# admission, so a later saved change can attach without restarting. # admission, so a later saved change can attach without restarting.
self.assertEqual(publisher.call_args.args[0], ['longitudinalPlan', 'starpilotLongitudinalPlan', self.assertEqual(publisher.call_args.args[0], ['longitudinalPlan', 'starpilotLongitudinalPlan',
'driverAssistance', 'slcState', 'slcCruiseCommand']) 'driverAssistance', 'slcState'])
self.assertEqual(conditional_ctor.call_count, int(enabled)) self.assertEqual(conditional_ctor.call_count, int(enabled))
if enabled: if enabled:
self.assertIs(conditional_ctor.call_args.args[0], params) self.assertIs(conditional_ctor.call_args.args[0], params)
@@ -200,8 +196,8 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
self.assertFalse(vision.vision_control_qualified) self.assertFalse(vision.vision_control_qualified)
self.assertEqual(vision.settings.selection.slots[0], Source.VISION) self.assertEqual(vision.settings.selection.slots[0], Source.VISION)
session = vision.session_id session = vision.session_id
pending_actions = deque([(3_000_000_000, plannerd.SlcAction(session, 1, 1, 1, 'accept'))]) pending_actions = deque([(3_000_000_000, SlcAction(session, 1, 1, 1, 'accept'))])
pending_cruise = deque([plannerd.SlcCruiseEvent(1, 3_000_000_000, 20., 21., 'set', session_id=session)]) pending_cruise = deque([SlcCruiseEvent(1, 3_000_000_000, 20., 21., 'set', session_id=session)])
self.assertEqual(owner.refresh(3_050_000_000, pending_actions=pending_actions, self.assertEqual(owner.refresh(3_050_000_000, pending_actions=pending_actions,
pending_cruise=pending_cruise), (vision, False)) pending_cruise=pending_cruise), (vision, False))
self.assertEqual(len(pending_actions), 1) self.assertEqual(len(pending_actions), 1)
@@ -217,8 +213,8 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
self.assertNotEqual(vision.session_id, session) # Retired session was reset. self.assertNotEqual(vision.session_id, session) # Retired session was reset.
params.put_bool('ShowSpeedLimits', False, block=True) params.put_bool('ShowSpeedLimits', False, block=True)
params.put_bool('SpeedLimitController', False, block=True) params.put_bool('SpeedLimitController', False, block=True)
pending_actions.append((4_050_000_000, plannerd.SlcAction(control.session_id, 1, 1, 1, 'accept'))) pending_actions.append((4_050_000_000, SlcAction(control.session_id, 1, 1, 1, 'accept')))
pending_cruise.append(plannerd.SlcCruiseEvent(2, 4_050_000_000, 20., 21., 'set', session_id=control.session_id)) pending_cruise.append(SlcCruiseEvent(2, 4_050_000_000, 20., 21., 'set', session_id=control.session_id))
self.assertEqual(owner.refresh(5_000_000_000, pending_actions=pending_actions, self.assertEqual(owner.refresh(5_000_000_000, pending_actions=pending_actions,
pending_cruise=pending_cruise), (None, True)) pending_cruise=pending_cruise), (None, True))
self.assertFalse(pending_actions) self.assertFalse(pending_actions)
@@ -251,7 +247,7 @@ class TestConditionalRuntimeLoop(unittest.TestCase):
patch.object(messaging, 'SubMaster', return_value=sm) as subscriber, patch.object(messaging, 'sub_sock'): patch.object(messaging, 'SubMaster', return_value=sm) as subscriber, patch.object(messaging, 'sub_sock'):
with self.assertRaises(EndLoop): with self.assertRaises(EndLoop):
plannerd.starpilot_main() plannerd.starpilot_main()
self.assertIn('slcCruiseCommand', publisher.call_args.args[0]) self.assertNotIn('slcCruiseCommand', publisher.call_args.args[0])
for service in ('slcDashboardObservation', 'slcVisionObservation'): for service in ('slcDashboardObservation', 'slcVisionObservation'):
self.assertIn(service, subscriber.call_args.args[0]) self.assertIn(service, subscriber.call_args.args[0])
for check in ('ignore_alive', 'ignore_valid', 'ignore_avg_freq'): for check in ('ignore_alive', 'ignore_valid', 'ignore_avg_freq'):
@@ -156,7 +156,7 @@ class CurveLoopTests(unittest.TestCase):
stamp = NOW + n * 50_000_000 stamp = NOW + n * 50_000_000
sm = bus(stamp) sm = bus(stamp)
result = update_curve_frame(planner, sm, cp, stamp, host=host, cruise_ceiling=slc) result = update_curve_frame(planner, sm, cp, stamp, host=host, cruise_ceiling=slc)
self.assertIsNotNone(result.ceiling_mps) self.assertIsNone(result.ceiling_mps)
self.assertFalse(planner.last_curve_ceiling_applied) self.assertFalse(planner.last_curve_ceiling_applied)
self.assertFalse(host.runtime.was_controlling) self.assertFalse(host.runtime.was_controlling)
self.assertEqual(host.runtime.curve.revision, 0) self.assertEqual(host.runtime.curve.revision, 0)
@@ -45,326 +45,326 @@ const static double MAHA_THRESH_31 = 3.8414588206941227;
* * * *
* This file is part of 'ekf' * * This file is part of 'ekf' *
******************************************************************************/ ******************************************************************************/
void err_fun(double *nom_x, double *delta_x, double *out_999653426340036453) { void err_fun(double *nom_x, double *delta_x, double *out_4741931869403660740) {
out_999653426340036453[0] = delta_x[0] + nom_x[0]; out_4741931869403660740[0] = delta_x[0] + nom_x[0];
out_999653426340036453[1] = delta_x[1] + nom_x[1]; out_4741931869403660740[1] = delta_x[1] + nom_x[1];
out_999653426340036453[2] = delta_x[2] + nom_x[2]; out_4741931869403660740[2] = delta_x[2] + nom_x[2];
out_999653426340036453[3] = delta_x[3] + nom_x[3]; out_4741931869403660740[3] = delta_x[3] + nom_x[3];
out_999653426340036453[4] = delta_x[4] + nom_x[4]; out_4741931869403660740[4] = delta_x[4] + nom_x[4];
out_999653426340036453[5] = delta_x[5] + nom_x[5]; out_4741931869403660740[5] = delta_x[5] + nom_x[5];
out_999653426340036453[6] = delta_x[6] + nom_x[6]; out_4741931869403660740[6] = delta_x[6] + nom_x[6];
out_999653426340036453[7] = delta_x[7] + nom_x[7]; out_4741931869403660740[7] = delta_x[7] + nom_x[7];
out_999653426340036453[8] = delta_x[8] + nom_x[8]; out_4741931869403660740[8] = delta_x[8] + nom_x[8];
} }
void inv_err_fun(double *nom_x, double *true_x, double *out_4610969769563887824) { void inv_err_fun(double *nom_x, double *true_x, double *out_2026357602489443023) {
out_4610969769563887824[0] = -nom_x[0] + true_x[0]; out_2026357602489443023[0] = -nom_x[0] + true_x[0];
out_4610969769563887824[1] = -nom_x[1] + true_x[1]; out_2026357602489443023[1] = -nom_x[1] + true_x[1];
out_4610969769563887824[2] = -nom_x[2] + true_x[2]; out_2026357602489443023[2] = -nom_x[2] + true_x[2];
out_4610969769563887824[3] = -nom_x[3] + true_x[3]; out_2026357602489443023[3] = -nom_x[3] + true_x[3];
out_4610969769563887824[4] = -nom_x[4] + true_x[4]; out_2026357602489443023[4] = -nom_x[4] + true_x[4];
out_4610969769563887824[5] = -nom_x[5] + true_x[5]; out_2026357602489443023[5] = -nom_x[5] + true_x[5];
out_4610969769563887824[6] = -nom_x[6] + true_x[6]; out_2026357602489443023[6] = -nom_x[6] + true_x[6];
out_4610969769563887824[7] = -nom_x[7] + true_x[7]; out_2026357602489443023[7] = -nom_x[7] + true_x[7];
out_4610969769563887824[8] = -nom_x[8] + true_x[8]; out_2026357602489443023[8] = -nom_x[8] + true_x[8];
} }
void H_mod_fun(double *state, double *out_1018390387391438144) { void H_mod_fun(double *state, double *out_1259167760902589274) {
out_1018390387391438144[0] = 1.0; out_1259167760902589274[0] = 1.0;
out_1018390387391438144[1] = 0.0; out_1259167760902589274[1] = 0.0;
out_1018390387391438144[2] = 0.0; out_1259167760902589274[2] = 0.0;
out_1018390387391438144[3] = 0.0; out_1259167760902589274[3] = 0.0;
out_1018390387391438144[4] = 0.0; out_1259167760902589274[4] = 0.0;
out_1018390387391438144[5] = 0.0; out_1259167760902589274[5] = 0.0;
out_1018390387391438144[6] = 0.0; out_1259167760902589274[6] = 0.0;
out_1018390387391438144[7] = 0.0; out_1259167760902589274[7] = 0.0;
out_1018390387391438144[8] = 0.0; out_1259167760902589274[8] = 0.0;
out_1018390387391438144[9] = 0.0; out_1259167760902589274[9] = 0.0;
out_1018390387391438144[10] = 1.0; out_1259167760902589274[10] = 1.0;
out_1018390387391438144[11] = 0.0; out_1259167760902589274[11] = 0.0;
out_1018390387391438144[12] = 0.0; out_1259167760902589274[12] = 0.0;
out_1018390387391438144[13] = 0.0; out_1259167760902589274[13] = 0.0;
out_1018390387391438144[14] = 0.0; out_1259167760902589274[14] = 0.0;
out_1018390387391438144[15] = 0.0; out_1259167760902589274[15] = 0.0;
out_1018390387391438144[16] = 0.0; out_1259167760902589274[16] = 0.0;
out_1018390387391438144[17] = 0.0; out_1259167760902589274[17] = 0.0;
out_1018390387391438144[18] = 0.0; out_1259167760902589274[18] = 0.0;
out_1018390387391438144[19] = 0.0; out_1259167760902589274[19] = 0.0;
out_1018390387391438144[20] = 1.0; out_1259167760902589274[20] = 1.0;
out_1018390387391438144[21] = 0.0; out_1259167760902589274[21] = 0.0;
out_1018390387391438144[22] = 0.0; out_1259167760902589274[22] = 0.0;
out_1018390387391438144[23] = 0.0; out_1259167760902589274[23] = 0.0;
out_1018390387391438144[24] = 0.0; out_1259167760902589274[24] = 0.0;
out_1018390387391438144[25] = 0.0; out_1259167760902589274[25] = 0.0;
out_1018390387391438144[26] = 0.0; out_1259167760902589274[26] = 0.0;
out_1018390387391438144[27] = 0.0; out_1259167760902589274[27] = 0.0;
out_1018390387391438144[28] = 0.0; out_1259167760902589274[28] = 0.0;
out_1018390387391438144[29] = 0.0; out_1259167760902589274[29] = 0.0;
out_1018390387391438144[30] = 1.0; out_1259167760902589274[30] = 1.0;
out_1018390387391438144[31] = 0.0; out_1259167760902589274[31] = 0.0;
out_1018390387391438144[32] = 0.0; out_1259167760902589274[32] = 0.0;
out_1018390387391438144[33] = 0.0; out_1259167760902589274[33] = 0.0;
out_1018390387391438144[34] = 0.0; out_1259167760902589274[34] = 0.0;
out_1018390387391438144[35] = 0.0; out_1259167760902589274[35] = 0.0;
out_1018390387391438144[36] = 0.0; out_1259167760902589274[36] = 0.0;
out_1018390387391438144[37] = 0.0; out_1259167760902589274[37] = 0.0;
out_1018390387391438144[38] = 0.0; out_1259167760902589274[38] = 0.0;
out_1018390387391438144[39] = 0.0; out_1259167760902589274[39] = 0.0;
out_1018390387391438144[40] = 1.0; out_1259167760902589274[40] = 1.0;
out_1018390387391438144[41] = 0.0; out_1259167760902589274[41] = 0.0;
out_1018390387391438144[42] = 0.0; out_1259167760902589274[42] = 0.0;
out_1018390387391438144[43] = 0.0; out_1259167760902589274[43] = 0.0;
out_1018390387391438144[44] = 0.0; out_1259167760902589274[44] = 0.0;
out_1018390387391438144[45] = 0.0; out_1259167760902589274[45] = 0.0;
out_1018390387391438144[46] = 0.0; out_1259167760902589274[46] = 0.0;
out_1018390387391438144[47] = 0.0; out_1259167760902589274[47] = 0.0;
out_1018390387391438144[48] = 0.0; out_1259167760902589274[48] = 0.0;
out_1018390387391438144[49] = 0.0; out_1259167760902589274[49] = 0.0;
out_1018390387391438144[50] = 1.0; out_1259167760902589274[50] = 1.0;
out_1018390387391438144[51] = 0.0; out_1259167760902589274[51] = 0.0;
out_1018390387391438144[52] = 0.0; out_1259167760902589274[52] = 0.0;
out_1018390387391438144[53] = 0.0; out_1259167760902589274[53] = 0.0;
out_1018390387391438144[54] = 0.0; out_1259167760902589274[54] = 0.0;
out_1018390387391438144[55] = 0.0; out_1259167760902589274[55] = 0.0;
out_1018390387391438144[56] = 0.0; out_1259167760902589274[56] = 0.0;
out_1018390387391438144[57] = 0.0; out_1259167760902589274[57] = 0.0;
out_1018390387391438144[58] = 0.0; out_1259167760902589274[58] = 0.0;
out_1018390387391438144[59] = 0.0; out_1259167760902589274[59] = 0.0;
out_1018390387391438144[60] = 1.0; out_1259167760902589274[60] = 1.0;
out_1018390387391438144[61] = 0.0; out_1259167760902589274[61] = 0.0;
out_1018390387391438144[62] = 0.0; out_1259167760902589274[62] = 0.0;
out_1018390387391438144[63] = 0.0; out_1259167760902589274[63] = 0.0;
out_1018390387391438144[64] = 0.0; out_1259167760902589274[64] = 0.0;
out_1018390387391438144[65] = 0.0; out_1259167760902589274[65] = 0.0;
out_1018390387391438144[66] = 0.0; out_1259167760902589274[66] = 0.0;
out_1018390387391438144[67] = 0.0; out_1259167760902589274[67] = 0.0;
out_1018390387391438144[68] = 0.0; out_1259167760902589274[68] = 0.0;
out_1018390387391438144[69] = 0.0; out_1259167760902589274[69] = 0.0;
out_1018390387391438144[70] = 1.0; out_1259167760902589274[70] = 1.0;
out_1018390387391438144[71] = 0.0; out_1259167760902589274[71] = 0.0;
out_1018390387391438144[72] = 0.0; out_1259167760902589274[72] = 0.0;
out_1018390387391438144[73] = 0.0; out_1259167760902589274[73] = 0.0;
out_1018390387391438144[74] = 0.0; out_1259167760902589274[74] = 0.0;
out_1018390387391438144[75] = 0.0; out_1259167760902589274[75] = 0.0;
out_1018390387391438144[76] = 0.0; out_1259167760902589274[76] = 0.0;
out_1018390387391438144[77] = 0.0; out_1259167760902589274[77] = 0.0;
out_1018390387391438144[78] = 0.0; out_1259167760902589274[78] = 0.0;
out_1018390387391438144[79] = 0.0; out_1259167760902589274[79] = 0.0;
out_1018390387391438144[80] = 1.0; out_1259167760902589274[80] = 1.0;
} }
void f_fun(double *state, double dt, double *out_8437871470129484601) { void f_fun(double *state, double dt, double *out_7988689886054324519) {
out_8437871470129484601[0] = state[0]; out_7988689886054324519[0] = state[0];
out_8437871470129484601[1] = state[1]; out_7988689886054324519[1] = state[1];
out_8437871470129484601[2] = state[2]; out_7988689886054324519[2] = state[2];
out_8437871470129484601[3] = state[3]; out_7988689886054324519[3] = state[3];
out_8437871470129484601[4] = state[4]; out_7988689886054324519[4] = state[4];
out_8437871470129484601[5] = dt*((-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]))*state[6] - 9.8100000000000005*state[8] + stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*state[1]) + (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*state[4])) + state[5]; out_7988689886054324519[5] = dt*((-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]))*state[6] - 9.8100000000000005*state[8] + stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*state[1]) + (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*state[4])) + state[5];
out_8437871470129484601[6] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*state[4])) + state[6]; out_7988689886054324519[6] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*state[4])) + state[6];
out_8437871470129484601[7] = state[7]; out_7988689886054324519[7] = state[7];
out_8437871470129484601[8] = state[8]; out_7988689886054324519[8] = state[8];
} }
void F_fun(double *state, double dt, double *out_7222922179546997313) { void F_fun(double *state, double dt, double *out_1354407396311610150) {
out_7222922179546997313[0] = 1; out_1354407396311610150[0] = 1;
out_7222922179546997313[1] = 0; out_1354407396311610150[1] = 0;
out_7222922179546997313[2] = 0; out_1354407396311610150[2] = 0;
out_7222922179546997313[3] = 0; out_1354407396311610150[3] = 0;
out_7222922179546997313[4] = 0; out_1354407396311610150[4] = 0;
out_7222922179546997313[5] = 0; out_1354407396311610150[5] = 0;
out_7222922179546997313[6] = 0; out_1354407396311610150[6] = 0;
out_7222922179546997313[7] = 0; out_1354407396311610150[7] = 0;
out_7222922179546997313[8] = 0; out_1354407396311610150[8] = 0;
out_7222922179546997313[9] = 0; out_1354407396311610150[9] = 0;
out_7222922179546997313[10] = 1; out_1354407396311610150[10] = 1;
out_7222922179546997313[11] = 0; out_1354407396311610150[11] = 0;
out_7222922179546997313[12] = 0; out_1354407396311610150[12] = 0;
out_7222922179546997313[13] = 0; out_1354407396311610150[13] = 0;
out_7222922179546997313[14] = 0; out_1354407396311610150[14] = 0;
out_7222922179546997313[15] = 0; out_1354407396311610150[15] = 0;
out_7222922179546997313[16] = 0; out_1354407396311610150[16] = 0;
out_7222922179546997313[17] = 0; out_1354407396311610150[17] = 0;
out_7222922179546997313[18] = 0; out_1354407396311610150[18] = 0;
out_7222922179546997313[19] = 0; out_1354407396311610150[19] = 0;
out_7222922179546997313[20] = 1; out_1354407396311610150[20] = 1;
out_7222922179546997313[21] = 0; out_1354407396311610150[21] = 0;
out_7222922179546997313[22] = 0; out_1354407396311610150[22] = 0;
out_7222922179546997313[23] = 0; out_1354407396311610150[23] = 0;
out_7222922179546997313[24] = 0; out_1354407396311610150[24] = 0;
out_7222922179546997313[25] = 0; out_1354407396311610150[25] = 0;
out_7222922179546997313[26] = 0; out_1354407396311610150[26] = 0;
out_7222922179546997313[27] = 0; out_1354407396311610150[27] = 0;
out_7222922179546997313[28] = 0; out_1354407396311610150[28] = 0;
out_7222922179546997313[29] = 0; out_1354407396311610150[29] = 0;
out_7222922179546997313[30] = 1; out_1354407396311610150[30] = 1;
out_7222922179546997313[31] = 0; out_1354407396311610150[31] = 0;
out_7222922179546997313[32] = 0; out_1354407396311610150[32] = 0;
out_7222922179546997313[33] = 0; out_1354407396311610150[33] = 0;
out_7222922179546997313[34] = 0; out_1354407396311610150[34] = 0;
out_7222922179546997313[35] = 0; out_1354407396311610150[35] = 0;
out_7222922179546997313[36] = 0; out_1354407396311610150[36] = 0;
out_7222922179546997313[37] = 0; out_1354407396311610150[37] = 0;
out_7222922179546997313[38] = 0; out_1354407396311610150[38] = 0;
out_7222922179546997313[39] = 0; out_1354407396311610150[39] = 0;
out_7222922179546997313[40] = 1; out_1354407396311610150[40] = 1;
out_7222922179546997313[41] = 0; out_1354407396311610150[41] = 0;
out_7222922179546997313[42] = 0; out_1354407396311610150[42] = 0;
out_7222922179546997313[43] = 0; out_1354407396311610150[43] = 0;
out_7222922179546997313[44] = 0; out_1354407396311610150[44] = 0;
out_7222922179546997313[45] = dt*(stiffness_front*(-state[2] - state[3] + state[7])/(mass*state[1]) + (-stiffness_front - stiffness_rear)*state[5]/(mass*state[4]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[6]/(mass*state[4])); out_1354407396311610150[45] = dt*(stiffness_front*(-state[2] - state[3] + state[7])/(mass*state[1]) + (-stiffness_front - stiffness_rear)*state[5]/(mass*state[4]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[6]/(mass*state[4]));
out_7222922179546997313[46] = -dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*pow(state[1], 2)); out_1354407396311610150[46] = -dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*pow(state[1], 2));
out_7222922179546997313[47] = -dt*stiffness_front*state[0]/(mass*state[1]); out_1354407396311610150[47] = -dt*stiffness_front*state[0]/(mass*state[1]);
out_7222922179546997313[48] = -dt*stiffness_front*state[0]/(mass*state[1]); out_1354407396311610150[48] = -dt*stiffness_front*state[0]/(mass*state[1]);
out_7222922179546997313[49] = dt*((-1 - (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*pow(state[4], 2)))*state[6] - (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*pow(state[4], 2))); out_1354407396311610150[49] = dt*((-1 - (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*pow(state[4], 2)))*state[6] - (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*pow(state[4], 2)));
out_7222922179546997313[50] = dt*(-stiffness_front*state[0] - stiffness_rear*state[0])/(mass*state[4]) + 1; out_1354407396311610150[50] = dt*(-stiffness_front*state[0] - stiffness_rear*state[0])/(mass*state[4]) + 1;
out_7222922179546997313[51] = dt*(-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4])); out_1354407396311610150[51] = dt*(-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]));
out_7222922179546997313[52] = dt*stiffness_front*state[0]/(mass*state[1]); out_1354407396311610150[52] = dt*stiffness_front*state[0]/(mass*state[1]);
out_7222922179546997313[53] = -9.8100000000000005*dt; out_1354407396311610150[53] = -9.8100000000000005*dt;
out_7222922179546997313[54] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front - pow(center_to_rear, 2)*stiffness_rear)*state[6]/(rotational_inertia*state[4])); out_1354407396311610150[54] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front - pow(center_to_rear, 2)*stiffness_rear)*state[6]/(rotational_inertia*state[4]));
out_7222922179546997313[55] = -center_to_front*dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*pow(state[1], 2)); out_1354407396311610150[55] = -center_to_front*dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*pow(state[1], 2));
out_7222922179546997313[56] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]); out_1354407396311610150[56] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
out_7222922179546997313[57] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]); out_1354407396311610150[57] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
out_7222922179546997313[58] = dt*(-(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*pow(state[4], 2)) - (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*pow(state[4], 2))); out_1354407396311610150[58] = dt*(-(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*pow(state[4], 2)) - (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*pow(state[4], 2)));
out_7222922179546997313[59] = dt*(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(rotational_inertia*state[4]); out_1354407396311610150[59] = dt*(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(rotational_inertia*state[4]);
out_7222922179546997313[60] = dt*(-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])/(rotational_inertia*state[4]) + 1; out_1354407396311610150[60] = dt*(-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])/(rotational_inertia*state[4]) + 1;
out_7222922179546997313[61] = center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]); out_1354407396311610150[61] = center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
out_7222922179546997313[62] = 0; out_1354407396311610150[62] = 0;
out_7222922179546997313[63] = 0; out_1354407396311610150[63] = 0;
out_7222922179546997313[64] = 0; out_1354407396311610150[64] = 0;
out_7222922179546997313[65] = 0; out_1354407396311610150[65] = 0;
out_7222922179546997313[66] = 0; out_1354407396311610150[66] = 0;
out_7222922179546997313[67] = 0; out_1354407396311610150[67] = 0;
out_7222922179546997313[68] = 0; out_1354407396311610150[68] = 0;
out_7222922179546997313[69] = 0; out_1354407396311610150[69] = 0;
out_7222922179546997313[70] = 1; out_1354407396311610150[70] = 1;
out_7222922179546997313[71] = 0; out_1354407396311610150[71] = 0;
out_7222922179546997313[72] = 0; out_1354407396311610150[72] = 0;
out_7222922179546997313[73] = 0; out_1354407396311610150[73] = 0;
out_7222922179546997313[74] = 0; out_1354407396311610150[74] = 0;
out_7222922179546997313[75] = 0; out_1354407396311610150[75] = 0;
out_7222922179546997313[76] = 0; out_1354407396311610150[76] = 0;
out_7222922179546997313[77] = 0; out_1354407396311610150[77] = 0;
out_7222922179546997313[78] = 0; out_1354407396311610150[78] = 0;
out_7222922179546997313[79] = 0; out_1354407396311610150[79] = 0;
out_7222922179546997313[80] = 1; out_1354407396311610150[80] = 1;
} }
void h_25(double *state, double *unused, double *out_5845994727189855200) { void h_25(double *state, double *unused, double *out_3766785436680432794) {
out_5845994727189855200[0] = state[6]; out_3766785436680432794[0] = state[6];
} }
void H_25(double *state, double *unused, double *out_1618166537623988050) { void H_25(double *state, double *unused, double *out_1377389164112836920) {
out_1618166537623988050[0] = 0; out_1377389164112836920[0] = 0;
out_1618166537623988050[1] = 0; out_1377389164112836920[1] = 0;
out_1618166537623988050[2] = 0; out_1377389164112836920[2] = 0;
out_1618166537623988050[3] = 0; out_1377389164112836920[3] = 0;
out_1618166537623988050[4] = 0; out_1377389164112836920[4] = 0;
out_1618166537623988050[5] = 0; out_1377389164112836920[5] = 0;
out_1618166537623988050[6] = 1; out_1377389164112836920[6] = 1;
out_1618166537623988050[7] = 0; out_1377389164112836920[7] = 0;
out_1618166537623988050[8] = 0; out_1377389164112836920[8] = 0;
} }
void h_24(double *state, double *unused, double *out_2733857150290724482) { void h_24(double *state, double *unused, double *out_7833154037772829772) {
out_2733857150290724482[0] = state[4]; out_7833154037772829772[0] = state[4];
out_2733857150290724482[1] = state[5]; out_7833154037772829772[1] = state[5];
} }
void H_24(double *state, double *unused, double *out_3790816136629487616) { void H_24(double *state, double *unused, double *out_5708312681030779401) {
out_3790816136629487616[0] = 0; out_5708312681030779401[0] = 0;
out_3790816136629487616[1] = 0; out_5708312681030779401[1] = 0;
out_3790816136629487616[2] = 0; out_5708312681030779401[2] = 0;
out_3790816136629487616[3] = 0; out_5708312681030779401[3] = 0;
out_3790816136629487616[4] = 1; out_5708312681030779401[4] = 1;
out_3790816136629487616[5] = 0; out_5708312681030779401[5] = 0;
out_3790816136629487616[6] = 0; out_5708312681030779401[6] = 0;
out_3790816136629487616[7] = 0; out_5708312681030779401[7] = 0;
out_3790816136629487616[8] = 0; out_5708312681030779401[8] = 0;
out_3790816136629487616[9] = 0; out_5708312681030779401[9] = 0;
out_3790816136629487616[10] = 0; out_5708312681030779401[10] = 0;
out_3790816136629487616[11] = 0; out_5708312681030779401[11] = 0;
out_3790816136629487616[12] = 0; out_5708312681030779401[12] = 0;
out_3790816136629487616[13] = 0; out_5708312681030779401[13] = 0;
out_3790816136629487616[14] = 1; out_5708312681030779401[14] = 1;
out_3790816136629487616[15] = 0; out_5708312681030779401[15] = 0;
out_3790816136629487616[16] = 0; out_5708312681030779401[16] = 0;
out_3790816136629487616[17] = 0; out_5708312681030779401[17] = 0;
} }
void h_30(double *state, double *unused, double *out_2208545198935832850) { void h_30(double *state, double *unused, double *out_7765906615223965994) {
out_2208545198935832850[0] = state[4]; out_7765906615223965994[0] = state[4];
} }
void H_30(double *state, double *unused, double *out_6145862867751596248) { void H_30(double *state, double *unused, double *out_5539301177378779835) {
out_6145862867751596248[0] = 0; out_5539301177378779835[0] = 0;
out_6145862867751596248[1] = 0; out_5539301177378779835[1] = 0;
out_6145862867751596248[2] = 0; out_5539301177378779835[2] = 0;
out_6145862867751596248[3] = 0; out_5539301177378779835[3] = 0;
out_6145862867751596248[4] = 1; out_5539301177378779835[4] = 1;
out_6145862867751596248[5] = 0; out_5539301177378779835[5] = 0;
out_6145862867751596248[6] = 0; out_5539301177378779835[6] = 0;
out_6145862867751596248[7] = 0; out_5539301177378779835[7] = 0;
out_6145862867751596248[8] = 0; out_5539301177378779835[8] = 0;
} }
void h_26(double *state, double *unused, double *out_604006904334020533) { void h_26(double *state, double *unused, double *out_2764233347563120349) {
out_604006904334020533[0] = state[7]; out_2764233347563120349[0] = state[7];
} }
void H_26(double *state, double *unused, double *out_5359669856498044274) { void H_26(double *state, double *unused, double *out_5118892482986893144) {
out_5359669856498044274[0] = 0; out_5118892482986893144[0] = 0;
out_5359669856498044274[1] = 0; out_5118892482986893144[1] = 0;
out_5359669856498044274[2] = 0; out_5118892482986893144[2] = 0;
out_5359669856498044274[3] = 0; out_5118892482986893144[3] = 0;
out_5359669856498044274[4] = 0; out_5118892482986893144[4] = 0;
out_5359669856498044274[5] = 0; out_5118892482986893144[5] = 0;
out_5359669856498044274[6] = 0; out_5118892482986893144[6] = 0;
out_5359669856498044274[7] = 1; out_5118892482986893144[7] = 1;
out_5359669856498044274[8] = 0; out_5118892482986893144[8] = 0;
} }
void h_27(double *state, double *unused, double *out_844321459529009555) { void h_27(double *state, double *unused, double *out_6547202700037797670) {
out_844321459529009555[0] = state[3]; out_6547202700037797670[0] = state[3];
} }
void H_27(double *state, double *unused, double *out_8320626179552021159) { void H_27(double *state, double *unused, double *out_3681491423056501901) {
out_8320626179552021159[0] = 0; out_3681491423056501901[0] = 0;
out_8320626179552021159[1] = 0; out_3681491423056501901[1] = 0;
out_8320626179552021159[2] = 0; out_3681491423056501901[2] = 0;
out_8320626179552021159[3] = 1; out_3681491423056501901[3] = 1;
out_8320626179552021159[4] = 0; out_3681491423056501901[4] = 0;
out_8320626179552021159[5] = 0; out_3681491423056501901[5] = 0;
out_8320626179552021159[6] = 0; out_3681491423056501901[6] = 0;
out_8320626179552021159[7] = 0; out_3681491423056501901[7] = 0;
out_8320626179552021159[8] = 0; out_3681491423056501901[8] = 0;
} }
void h_29(double *state, double *unused, double *out_2793128068725012795) { void h_29(double *state, double *unused, double *out_5614419939767242899) {
out_2793128068725012795[0] = state[1]; out_5614419939767242899[0] = state[1];
} }
void H_29(double *state, double *unused, double *out_5635631523437204064) { void H_29(double *state, double *unused, double *out_5394854149926052934) {
out_5635631523437204064[0] = 0; out_5394854149926052934[0] = 0;
out_5635631523437204064[1] = 1; out_5394854149926052934[1] = 1;
out_5635631523437204064[2] = 0; out_5394854149926052934[2] = 0;
out_5635631523437204064[3] = 0; out_5394854149926052934[3] = 0;
out_5635631523437204064[4] = 0; out_5394854149926052934[4] = 0;
out_5635631523437204064[5] = 0; out_5394854149926052934[5] = 0;
out_5635631523437204064[6] = 0; out_5394854149926052934[6] = 0;
out_5635631523437204064[7] = 0; out_5394854149926052934[7] = 0;
out_5635631523437204064[8] = 0; out_5394854149926052934[8] = 0;
} }
void h_28(double *state, double *unused, double *out_4484828697352558873) { void h_28(double *state, double *unused, double *out_455560003755268109) {
out_4484828697352558873[0] = state[0]; out_455560003755268109[0] = state[0];
} }
void H_28(double *state, double *unused, double *out_3672001251871877813) { void H_28(double *state, double *unused, double *out_3431223878360726683) {
out_3672001251871877813[0] = 1; out_3431223878360726683[0] = 1;
out_3672001251871877813[1] = 0; out_3431223878360726683[1] = 0;
out_3672001251871877813[2] = 0; out_3431223878360726683[2] = 0;
out_3672001251871877813[3] = 0; out_3431223878360726683[3] = 0;
out_3672001251871877813[4] = 0; out_3431223878360726683[4] = 0;
out_3672001251871877813[5] = 0; out_3431223878360726683[5] = 0;
out_3672001251871877813[6] = 0; out_3431223878360726683[6] = 0;
out_3672001251871877813[7] = 0; out_3431223878360726683[7] = 0;
out_3672001251871877813[8] = 0; out_3431223878360726683[8] = 0;
} }
void h_31(double *state, double *unused, double *out_2046944767694668159) { void h_31(double *state, double *unused, double *out_2316154044051549627) {
out_2046944767694668159[0] = state[8]; out_2316154044051549627[0] = state[8];
} }
void H_31(double *state, double *unused, double *out_5985877958731395750) { void H_31(double *state, double *unused, double *out_1346743202235876492) {
out_5985877958731395750[0] = 0; out_1346743202235876492[0] = 0;
out_5985877958731395750[1] = 0; out_1346743202235876492[1] = 0;
out_5985877958731395750[2] = 0; out_1346743202235876492[2] = 0;
out_5985877958731395750[3] = 0; out_1346743202235876492[3] = 0;
out_5985877958731395750[4] = 0; out_1346743202235876492[4] = 0;
out_5985877958731395750[5] = 0; out_1346743202235876492[5] = 0;
out_5985877958731395750[6] = 0; out_1346743202235876492[6] = 0;
out_5985877958731395750[7] = 0; out_1346743202235876492[7] = 0;
out_5985877958731395750[8] = 1; out_1346743202235876492[8] = 1;
} }
#include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Dense>
#include <iostream> #include <iostream>
@@ -518,68 +518,68 @@ void car_update_28(double *in_x, double *in_P, double *in_z, double *in_R, doubl
void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) { void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
update<1, 3, 0>(in_x, in_P, h_31, H_31, NULL, in_z, in_R, in_ea, MAHA_THRESH_31); update<1, 3, 0>(in_x, in_P, h_31, H_31, NULL, in_z, in_R, in_ea, MAHA_THRESH_31);
} }
void car_err_fun(double *nom_x, double *delta_x, double *out_999653426340036453) { void car_err_fun(double *nom_x, double *delta_x, double *out_4741931869403660740) {
err_fun(nom_x, delta_x, out_999653426340036453); err_fun(nom_x, delta_x, out_4741931869403660740);
} }
void car_inv_err_fun(double *nom_x, double *true_x, double *out_4610969769563887824) { void car_inv_err_fun(double *nom_x, double *true_x, double *out_2026357602489443023) {
inv_err_fun(nom_x, true_x, out_4610969769563887824); inv_err_fun(nom_x, true_x, out_2026357602489443023);
} }
void car_H_mod_fun(double *state, double *out_1018390387391438144) { void car_H_mod_fun(double *state, double *out_1259167760902589274) {
H_mod_fun(state, out_1018390387391438144); H_mod_fun(state, out_1259167760902589274);
} }
void car_f_fun(double *state, double dt, double *out_8437871470129484601) { void car_f_fun(double *state, double dt, double *out_7988689886054324519) {
f_fun(state, dt, out_8437871470129484601); f_fun(state, dt, out_7988689886054324519);
} }
void car_F_fun(double *state, double dt, double *out_7222922179546997313) { void car_F_fun(double *state, double dt, double *out_1354407396311610150) {
F_fun(state, dt, out_7222922179546997313); F_fun(state, dt, out_1354407396311610150);
} }
void car_h_25(double *state, double *unused, double *out_5845994727189855200) { void car_h_25(double *state, double *unused, double *out_3766785436680432794) {
h_25(state, unused, out_5845994727189855200); h_25(state, unused, out_3766785436680432794);
} }
void car_H_25(double *state, double *unused, double *out_1618166537623988050) { void car_H_25(double *state, double *unused, double *out_1377389164112836920) {
H_25(state, unused, out_1618166537623988050); H_25(state, unused, out_1377389164112836920);
} }
void car_h_24(double *state, double *unused, double *out_2733857150290724482) { void car_h_24(double *state, double *unused, double *out_7833154037772829772) {
h_24(state, unused, out_2733857150290724482); h_24(state, unused, out_7833154037772829772);
} }
void car_H_24(double *state, double *unused, double *out_3790816136629487616) { void car_H_24(double *state, double *unused, double *out_5708312681030779401) {
H_24(state, unused, out_3790816136629487616); H_24(state, unused, out_5708312681030779401);
} }
void car_h_30(double *state, double *unused, double *out_2208545198935832850) { void car_h_30(double *state, double *unused, double *out_7765906615223965994) {
h_30(state, unused, out_2208545198935832850); h_30(state, unused, out_7765906615223965994);
} }
void car_H_30(double *state, double *unused, double *out_6145862867751596248) { void car_H_30(double *state, double *unused, double *out_5539301177378779835) {
H_30(state, unused, out_6145862867751596248); H_30(state, unused, out_5539301177378779835);
} }
void car_h_26(double *state, double *unused, double *out_604006904334020533) { void car_h_26(double *state, double *unused, double *out_2764233347563120349) {
h_26(state, unused, out_604006904334020533); h_26(state, unused, out_2764233347563120349);
} }
void car_H_26(double *state, double *unused, double *out_5359669856498044274) { void car_H_26(double *state, double *unused, double *out_5118892482986893144) {
H_26(state, unused, out_5359669856498044274); H_26(state, unused, out_5118892482986893144);
} }
void car_h_27(double *state, double *unused, double *out_844321459529009555) { void car_h_27(double *state, double *unused, double *out_6547202700037797670) {
h_27(state, unused, out_844321459529009555); h_27(state, unused, out_6547202700037797670);
} }
void car_H_27(double *state, double *unused, double *out_8320626179552021159) { void car_H_27(double *state, double *unused, double *out_3681491423056501901) {
H_27(state, unused, out_8320626179552021159); H_27(state, unused, out_3681491423056501901);
} }
void car_h_29(double *state, double *unused, double *out_2793128068725012795) { void car_h_29(double *state, double *unused, double *out_5614419939767242899) {
h_29(state, unused, out_2793128068725012795); h_29(state, unused, out_5614419939767242899);
} }
void car_H_29(double *state, double *unused, double *out_5635631523437204064) { void car_H_29(double *state, double *unused, double *out_5394854149926052934) {
H_29(state, unused, out_5635631523437204064); H_29(state, unused, out_5394854149926052934);
} }
void car_h_28(double *state, double *unused, double *out_4484828697352558873) { void car_h_28(double *state, double *unused, double *out_455560003755268109) {
h_28(state, unused, out_4484828697352558873); h_28(state, unused, out_455560003755268109);
} }
void car_H_28(double *state, double *unused, double *out_3672001251871877813) { void car_H_28(double *state, double *unused, double *out_3431223878360726683) {
H_28(state, unused, out_3672001251871877813); H_28(state, unused, out_3431223878360726683);
} }
void car_h_31(double *state, double *unused, double *out_2046944767694668159) { void car_h_31(double *state, double *unused, double *out_2316154044051549627) {
h_31(state, unused, out_2046944767694668159); h_31(state, unused, out_2316154044051549627);
} }
void car_H_31(double *state, double *unused, double *out_5985877958731395750) { void car_H_31(double *state, double *unused, double *out_1346743202235876492) {
H_31(state, unused, out_5985877958731395750); H_31(state, unused, out_1346743202235876492);
} }
void car_predict(double *in_x, double *in_P, double *in_Q, double dt) { void car_predict(double *in_x, double *in_P, double *in_Q, double dt) {
predict(in_x, in_P, in_Q, dt); predict(in_x, in_P, in_Q, dt);
@@ -9,27 +9,27 @@ void car_update_27(double *in_x, double *in_P, double *in_z, double *in_R, doubl
void car_update_29(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void car_update_29(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void car_update_28(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void car_update_28(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void car_err_fun(double *nom_x, double *delta_x, double *out_999653426340036453); void car_err_fun(double *nom_x, double *delta_x, double *out_4741931869403660740);
void car_inv_err_fun(double *nom_x, double *true_x, double *out_4610969769563887824); void car_inv_err_fun(double *nom_x, double *true_x, double *out_2026357602489443023);
void car_H_mod_fun(double *state, double *out_1018390387391438144); void car_H_mod_fun(double *state, double *out_1259167760902589274);
void car_f_fun(double *state, double dt, double *out_8437871470129484601); void car_f_fun(double *state, double dt, double *out_7988689886054324519);
void car_F_fun(double *state, double dt, double *out_7222922179546997313); void car_F_fun(double *state, double dt, double *out_1354407396311610150);
void car_h_25(double *state, double *unused, double *out_5845994727189855200); void car_h_25(double *state, double *unused, double *out_3766785436680432794);
void car_H_25(double *state, double *unused, double *out_1618166537623988050); void car_H_25(double *state, double *unused, double *out_1377389164112836920);
void car_h_24(double *state, double *unused, double *out_2733857150290724482); void car_h_24(double *state, double *unused, double *out_7833154037772829772);
void car_H_24(double *state, double *unused, double *out_3790816136629487616); void car_H_24(double *state, double *unused, double *out_5708312681030779401);
void car_h_30(double *state, double *unused, double *out_2208545198935832850); void car_h_30(double *state, double *unused, double *out_7765906615223965994);
void car_H_30(double *state, double *unused, double *out_6145862867751596248); void car_H_30(double *state, double *unused, double *out_5539301177378779835);
void car_h_26(double *state, double *unused, double *out_604006904334020533); void car_h_26(double *state, double *unused, double *out_2764233347563120349);
void car_H_26(double *state, double *unused, double *out_5359669856498044274); void car_H_26(double *state, double *unused, double *out_5118892482986893144);
void car_h_27(double *state, double *unused, double *out_844321459529009555); void car_h_27(double *state, double *unused, double *out_6547202700037797670);
void car_H_27(double *state, double *unused, double *out_8320626179552021159); void car_H_27(double *state, double *unused, double *out_3681491423056501901);
void car_h_29(double *state, double *unused, double *out_2793128068725012795); void car_h_29(double *state, double *unused, double *out_5614419939767242899);
void car_H_29(double *state, double *unused, double *out_5635631523437204064); void car_H_29(double *state, double *unused, double *out_5394854149926052934);
void car_h_28(double *state, double *unused, double *out_4484828697352558873); void car_h_28(double *state, double *unused, double *out_455560003755268109);
void car_H_28(double *state, double *unused, double *out_3672001251871877813); void car_H_28(double *state, double *unused, double *out_3431223878360726683);
void car_h_31(double *state, double *unused, double *out_2046944767694668159); void car_h_31(double *state, double *unused, double *out_2316154044051549627);
void car_H_31(double *state, double *unused, double *out_5985877958731395750); void car_H_31(double *state, double *unused, double *out_1346743202235876492);
void car_predict(double *in_x, double *in_P, double *in_Q, double dt); void car_predict(double *in_x, double *in_P, double *in_Q, double dt);
void car_set_mass(double x); void car_set_mass(double x);
void car_set_rotational_inertia(double x); void car_set_rotational_inertia(double x);
File diff suppressed because it is too large Load Diff
@@ -5,18 +5,18 @@ void pose_update_4(double *in_x, double *in_P, double *in_z, double *in_R, doubl
void pose_update_10(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void pose_update_10(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void pose_update_13(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void pose_update_13(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void pose_update_14(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea); void pose_update_14(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
void pose_err_fun(double *nom_x, double *delta_x, double *out_8942860553158829980); void pose_err_fun(double *nom_x, double *delta_x, double *out_8357459543021008699);
void pose_inv_err_fun(double *nom_x, double *true_x, double *out_2254641408306223903); void pose_inv_err_fun(double *nom_x, double *true_x, double *out_3253386232645254795);
void pose_H_mod_fun(double *state, double *out_76292315910108330); void pose_H_mod_fun(double *state, double *out_3551210960619195093);
void pose_f_fun(double *state, double dt, double *out_1412378285720339068); void pose_f_fun(double *state, double dt, double *out_3486488515702872216);
void pose_F_fun(double *state, double dt, double *out_5059879879978958987); void pose_F_fun(double *state, double dt, double *out_6504624075581041956);
void pose_h_4(double *state, double *unused, double *out_8306941651867152905); void pose_h_4(double *state, double *unused, double *out_7873091896089738414);
void pose_H_4(double *state, double *unused, double *out_41214293034027689); void pose_H_4(double *state, double *unused, double *out_8703729345658275828);
void pose_h_10(double *state, double *unused, double *out_4127406154043783729); void pose_h_10(double *state, double *unused, double *out_8481552048721867035);
void pose_H_10(double *state, double *unused, double *out_7440694459650338948); void pose_H_10(double *state, double *unused, double *out_9046581129967679223);
void pose_h_13(double *state, double *unused, double *out_2904306600296367164); void pose_h_13(double *state, double *unused, double *out_2079745877024079652);
void pose_H_13(double *state, double *unused, double *out_3171059532298305112); void pose_H_13(double *state, double *unused, double *out_6530740902718942987);
void pose_h_14(double *state, double *unused, double *out_6520989930447577741); void pose_h_14(double *state, double *unused, double *out_5967769102958667382);
void pose_H_14(double *state, double *unused, double *out_3922026563305456840); void pose_H_14(double *state, double *unused, double *out_5779773871711791259);
void pose_predict(double *in_x, double *in_P, double *in_Q, double dt); void pose_predict(double *in_x, double *in_P, double *in_Q, double dt);
} }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6 -1
View File
@@ -16,6 +16,8 @@ GearShifter = car.CarState.GearShifter
AOL_TOGGLE = 9 AOL_TOGGLE = 9
PAUSE_LATERAL = 3 PAUSE_LATERAL = 3
PAUSE_LONGITUDINAL = 4 PAUSE_LONGITUDINAL = 4
# The only wheel action WheelPublisher delivers from cruise MAIN.
ADOPT_SPEED_LIMIT = 10
@dataclass(frozen=True) @dataclass(frozen=True)
class AolSettings: class AolSettings:
@@ -28,6 +30,7 @@ class AolSettings:
mode_actions: tuple[int, int, int] = (0, 0, 0) mode_actions: tuple[int, int, int] = (0, 0, 0)
custom_actions: tuple[int, int, int] = (0, 0, 0) custom_actions: tuple[int, int, int] = (0, 0, 0)
default_physical_buttons: bool = True default_physical_buttons: bool = True
main_wheel_action: bool = False
def _button_value(params, key: str) -> int | None: def _button_value(params, key: str) -> int | None:
@@ -64,6 +67,7 @@ def read_settings(params) -> AolSettings:
enabled=params.get_bool('AlwaysOnLateral') and valid_pause, pause_brake_mps=pause_mps if valid_pause else 0.0, enabled=params.get_bool('AlwaysOnLateral') and valid_pause, pause_brake_mps=pause_mps if valid_pause else 0.0,
lkas_action=_axis_action(lkas), main_action=_axis_action(main), lkas_action=_axis_action(lkas), main_action=_axis_action(main),
default_physical_buttons=lkas == 0 and main == 0, default_physical_buttons=lkas == 0 and main == 0,
main_wheel_action=main == ADOPT_SPEED_LIMIT,
distance_actions=(_button_action(params, 'DistanceButtonControl'), distance_actions=(_button_action(params, 'DistanceButtonControl'),
_button_action(params, 'LongDistanceButtonControl'), _button_action(params, 'LongDistanceButtonControl'),
_button_action(params, 'VeryLongDistanceButtonControl')), _button_action(params, 'VeryLongDistanceButtonControl')),
@@ -319,7 +323,8 @@ class AolCardIntent:
independent_buttons = self.independent_cruise_buttons and (main_managed or lkas_managed) independent_buttons = self.independent_cruise_buttons and (main_managed or lkas_managed)
# The opt-in is bound to existing HKG torque owners. Other physical # The opt-in is bound to existing HKG torque owners. Other physical
# owners keep their current event and native contracts. # owners keep their current event and native contracts.
main_toggle = not independent_buttons or main_managed main_toggle = (not independent_buttons or main_managed) and not (
self.independent_cruise_buttons and self.settings.main_wheel_action)
lkas_toggle = not independent_buttons or lkas_managed lkas_toggle = not independent_buttons or lkas_managed
previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle) previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle)
cancel_pressed = False cancel_pressed = False
@@ -0,0 +1,73 @@
"""Cruise MAIN assigned to Adopt speed limit is not also the Hyundai physical lateral toggle."""
import pytest
from opendbc.car import structs
from openpilot.starpilot.aol.intent import AolCardIntent, AolSettings, read_settings
from openpilot.starpilot.aol.tests.test_ioniq6_stock_repair import stock
from openpilot.starpilot.car.hyundai.aol import create_intent, qualified_ioniq6
def long_cp():
cp = stock(False)
cp.pcmCruise = False
cp.openpilotLongitudinalControl = True
cp.safetyConfigs[0].safetyParam = 0x8815
assert qualified_ioniq6(cp)
return cp
def press(owner, cs, button, now_ns, *, engaged=False):
cs.buttonEvents = [structs.CarState.ButtonEvent(type=button, pressed=True)]
owner.update(cs, now_ns=now_ns, fault_active=False, standard_enabled=engaged)
cs.buttonEvents = [structs.CarState.ButtonEvent(type=button, pressed=False)]
owner.update(cs, now_ns=now_ns + 1, fault_active=False, standard_enabled=engaged)
def lateral(owner):
return owner.allowed_latch and not owner.pause_lateral
def armed(owner):
cs = structs.CarState(canValid=True, gearShifter='drive')
cs.cruiseState.available = True
owner.update(cs, now_ns=1, fault_active=False)
press(owner, cs, 'lkas', 2)
assert lateral(owner)
return cs
@pytest.mark.parametrize('main_wheel_action', [False, True])
def test_ioniq6_main_assigned_to_adopt_keeps_lkas_armed_lateral(main_wheel_action):
owner = create_intent(long_cp(), AolSettings(True, 0., 0, 0, (0, 0, 0), (0, 0, 0), main_wheel_action=main_wheel_action))
assert owner.independent_cruise_buttons
cs = armed(owner)
press(owner, cs, 'mainCruise', 10, engaged=True)
assert lateral(owner) == main_wheel_action
press(owner, cs, 'lkas', 20, engaged=True)
assert lateral(owner) != main_wheel_action
def test_main_toggle_is_unchanged_without_independent_cruise_buttons():
owner = AolCardIntent(AolSettings(True, 0., 0, 0, (0, 0, 0), (0, 0, 0), main_wheel_action=True), explicit_latch=True)
cs = armed(owner)
press(owner, cs, 'mainCruise', 10, engaged=True)
assert not lateral(owner)
class SavedParams:
def __init__(self, values):
self.values = values
def get(self, key, return_default=False):
return self.values.get(key)
def get_bool(self, key):
return self.values.get(key) == b'1'
def get_param_path(self, key):
return f'/nonexistent/{key}'
@pytest.mark.parametrize('lkas,main,main_wheel', [(b'0', b'10', True), (b'0', b'9', False), (b'10', b'0', False), (b'0', b'8', False)])
def test_only_main_adopt_is_marked_as_a_main_wheel_action(lkas, main, main_wheel):
settings = read_settings(SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': lkas, 'MainCruiseButtonControl': main}))
assert settings.main_wheel_action == main_wheel
Binary file not shown.
@@ -101,7 +101,7 @@
"discriminantOffset": 0 "discriminantOffset": 0
}, },
"new_storage": { "new_storage": {
"dataWordCount": 18, "dataWordCount": 21,
"pointerCount": 22, "pointerCount": 22,
"preferredListEncoding": "inlineComposite", "preferredListEncoding": "inlineComposite",
"isGroup": false, "isGroup": false,
@@ -252,6 +252,78 @@
"ordinal": { "ordinal": {
"explicit": 58 "explicit": 58
} }
},
{
"slot": {
"offset": 141,
"type": {
"bool": null
},
"defaultValue": {
"bool": false
},
"hadExplicitDefault": false
},
"name": "acceptedIsPreview",
"codeOrder": 59,
"discriminantValue": 65535,
"ordinal": {
"explicit": 59
}
},
{
"slot": {
"offset": 18,
"type": {
"uint64": null
},
"defaultValue": {
"uint64": 0
},
"hadExplicitDefault": false
},
"name": "wheelOverrideSince",
"codeOrder": 60,
"discriminantValue": 65535,
"ordinal": {
"explicit": 60
}
},
{
"slot": {
"offset": 19,
"type": {
"uint64": null
},
"defaultValue": {
"uint64": 0
},
"hadExplicitDefault": false
},
"name": "wheelAdoptMonoTime",
"codeOrder": 61,
"discriminantValue": 65535,
"ordinal": {
"explicit": 61
}
},
{
"slot": {
"offset": 40,
"type": {
"float32": null
},
"defaultValue": {
"float32": 0.0
},
"hadExplicitDefault": false
},
"name": "wheelAdoptTargetMps",
"codeOrder": 62,
"discriminantValue": 65535,
"ordinal": {
"explicit": 62
}
} }
] ]
}, },
@@ -764,6 +836,90 @@
} }
} }
] ]
},
"0x9ccdc8676701b412": {
"kind": "struct",
"before_name": "SlcAction",
"after_name": "SlcAction",
"old_field_count": 8,
"old_storage": {
"dataWordCount": 4,
"pointerCount": 4,
"preferredListEncoding": "inlineComposite",
"isGroup": false,
"discriminantCount": 0,
"discriminantOffset": 0
},
"new_storage": {
"dataWordCount": 5,
"pointerCount": 4,
"preferredListEncoding": "inlineComposite",
"isGroup": false,
"discriminantCount": 0,
"discriminantOffset": 0
},
"added_fields": [
{
"slot": {
"offset": 4,
"type": {
"uint64": null
},
"defaultValue": {
"uint64": 0
},
"hadExplicitDefault": false
},
"name": "wheelAdoptMonoTime",
"codeOrder": 8,
"discriminantValue": 65535,
"ordinal": {
"explicit": 8
}
}
]
},
"0xcd96dafb67a082d0": {
"kind": "struct",
"before_name": "SlcCruiseEvent",
"after_name": "SlcCruiseEvent",
"old_field_count": 16,
"old_storage": {
"dataWordCount": 7,
"pointerCount": 6,
"preferredListEncoding": "inlineComposite",
"isGroup": false,
"discriminantCount": 0,
"discriminantOffset": 0
},
"new_storage": {
"dataWordCount": 8,
"pointerCount": 6,
"preferredListEncoding": "inlineComposite",
"isGroup": false,
"discriminantCount": 0,
"discriminantOffset": 0
},
"added_fields": [
{
"slot": {
"offset": 7,
"type": {
"uint64": null
},
"defaultValue": {
"uint64": 0
},
"hadExplicitDefault": false
},
"name": "wheelOverrideSince",
"codeOrder": 16,
"discriminantValue": 65535,
"ordinal": {
"explicit": 16
}
}
]
} }
}, },
"published_addition_commits": { "published_addition_commits": {
@@ -6,9 +6,8 @@ CEM selects Experimental mode for configured speed, road, signal, curve, lead, s
`ConditionalPlannerHost` joins the current native MPC result, current model/car/radar observations, saved preferences, and qualified wheel-button events. It produces a short-lived proposal on `slcState.conditionalMode`; it does not own the effective driving mode. `selfdrived` independently checks the current vehicle capability, longitudinal axis, drive, saved configuration, and input freshness before accepting that proposal. Its ordinary `ExperimentalMode` request remains the fallback. The UI displays an active conditional reason only from a fresh selfdrived acknowledgment matching the exact current `selfdriveState` frame and active longitudinal axis; the saved family is displayed separately. `ConditionalPlannerHost` joins the current native MPC result, current model/car/radar observations, saved preferences, and qualified wheel-button events. It produces a short-lived proposal on `slcState.conditionalMode`; it does not own the effective driving mode. `selfdrived` independently checks the current vehicle capability, longitudinal axis, drive, saved configuration, and input freshness before accepting that proposal. Its ordinary `ExperimentalMode` request remains the fallback. The UI displays an active conditional reason only from a fresh selfdrived acknowledgment matching the exact current `selfdriveState` frame and active longitudinal axis; the saved family is displayed separately.
Speed-limit availability is independent of mode selection. The retired `SLCFallback=1` Speed-limit availability is independent of mode selection. A missing or stale Maps or Vision limit does
preference cannot request Experimental or veto Chill, including when Maps or Vision not request Experimental or veto Chill. Other scene triggers, manual mode choices and committed
becomes unknown or stale. Other scene triggers, manual mode choices and committed
stop handling retain their existing behavior. Historical speed-limit reason labels stop handling retain their existing behavior. Historical speed-limit reason labels
remain readable in recorded routes. remain readable in recorded routes.
@@ -49,6 +48,6 @@ Traffic assignment does not suppress ordinary profile tuning.
Scene inputs distinguish false from unknown. Model filters advance once per original model tick; the oldest required source bounds freshness separately, so a slower fresh radar cannot stall a model filter or renew stale data. Startup, clock discontinuities, and drive changes require fresh observations. Conditional Chill requires every applicable veto to be known false. Disabled build features can be known absent; an enabled producer without a qualified observation remains unknown. Scene inputs distinguish false from unknown. Model filters advance once per original model tick; the oldest required source bounds freshness separately, so a slower fresh radar cannot stall a model filter or renew stale data. Startup, clock discontinuities, and drive changes require fresh observations. Conditional Chill requires every applicable veto to be known false. Disabled build features can be known absent; an enabled producer without a qualified observation remains unknown.
Current producers cover native MPC follow time and stop/throttle intent, model lane geometry, qualified adjacent radar, SLC attribution, pedal override, and the effective mode reported by selfdrived. The exact Ioniq media path supplies source-stamped Traffic Mode to CEM and a bounded Traffic follow/jerk, acceleration and cruise-braking profile. The shared committed-turn evaluator feeds both the stop detector and slower-lead retuning from original car/model stamps. Traffic retains the existing 0.75-second effective headway floor; saved values below it remain unsupported and intact. The native planner shapes the cruise-only floor for a qualified SLC cap, a validated named Eco/Sport braking personality, or the explicit global Braking response. A saved Traffic braking category reverts to its 0.42 m/s² cruise baseline for a present radar lead or standstill, then recovers through the existing profile smoother; MPC and model braking retain priority. The saved lane-change close-gap preference and current lateral minimum-speed policy are separate from conditional scene selection. Frozen weather and other hazard-context braking inputs remain absent. Stop-sign, forced-stop, and dashboard stop-sign producers remain absent. The historical red-light name is already represented by the current stop-light observation, so it does not need a duplicate owner. Current producers cover native MPC follow time and stop/throttle intent, model lane geometry, qualified adjacent radar, SLC attribution, pedal override, and the effective mode reported by selfdrived. The exact Ioniq media path supplies source-stamped Traffic Mode to CEM and a bounded Traffic follow/jerk, acceleration and cruise-braking profile. The shared committed-turn evaluator feeds both the stop detector and slower-lead retuning from original car/model stamps. Traffic retains the existing 0.75-second effective headway floor; saved values below it remain unsupported and intact. The native planner retains the selected cruise-braking response for an SLC cap. Conditional speed comparisons and curve control receive the same-cycle SLC-capped cruise target while the driver's SET remains unchanged. A saved Traffic braking category reverts to its 0.42 m/s² cruise baseline for a present radar lead or standstill, then recovers through the existing profile smoother; MPC and model braking retain priority. The saved lane-change close-gap preference and current lateral minimum-speed policy are separate from conditional scene selection. Frozen weather and other hazard-context braking inputs remain absent. Stop-sign, forced-stop, and dashboard stop-sign producers remain absent. The historical red-light name is already represented by the current stop-light observation, so it does not need a duplicate owner.
The source contract includes frozen `starpilot/controls/lib/conditional_experimental_mode.py`, `conditional_chill_mode.py`, `starpilot/common/experimental_state.py`, and the planner's mode selection. Tests compare executable frozen policy/detector traces and exercise current serialized messages, native MPC/radar joins, lifecycle boundaries, manual controls, and settings concurrency. These are integration evidence, not vehicle qualification. Normal availability is limited to the exact tagged Ioniq 6 LONG profile; the separate ECU handoff and native safety acknowledgment must succeed first. Missing scene producers and road behavior still require evaluation. The source contract includes frozen `starpilot/controls/lib/conditional_experimental_mode.py`, `conditional_chill_mode.py`, `starpilot/common/experimental_state.py`, and the planner's mode selection. Tests compare executable frozen policy/detector traces and exercise current serialized messages, native MPC/radar joins, lifecycle boundaries, manual controls, and settings concurrency. These are integration evidence, not vehicle qualification. Normal availability is limited to the exact tagged Ioniq 6 LONG profile; the separate ECU handoff and native safety acknowledgment must succeed first. Missing scene producers and road behavior still require evaluation.
@@ -59,6 +59,7 @@ class ConditionalModeHost:
selected_t_follow_s: float | None = None, selected_t_follow_s: float | None = None,
selected_t_follow_observed_mono_ns: int | None = None, selected_t_follow_observed_mono_ns: int | None = None,
settings_owner: ConditionalSettingsOwner | None = None, settings_owner: ConditionalSettingsOwner | None = None,
cruise_ceiling_mps: float | None = None,
) -> HostProposal: ) -> HostProposal:
signal_options = None signal_options = None
settings_revision = None settings_revision = None
@@ -120,6 +121,7 @@ class ConditionalModeHost:
selected_t_follow_observed_mono_ns=selected_t_follow_observed_mono_ns, selected_t_follow_observed_mono_ns=selected_t_follow_observed_mono_ns,
owner_context=owner_context, owner_context=owner_context,
signal_options=signal_options, signal_options=signal_options,
cruise_ceiling_mps=cruise_ceiling_mps,
) )
authority = projected.authority authority = projected.authority
if authority is not None and authority.fresh and (not authority.system_long_capable or authority.safe_mode or if authority is not None and authority.fresh and (not authority.system_long_capable or authority.safe_mode or
@@ -180,6 +180,7 @@ class ConditionalPlannerHost:
drive_id: int, manual: ManualState | None = None, drive_id: int, manual: ManualState | None = None,
owner_context: ConditionalOwnerContext | None = None, owner_context: ConditionalOwnerContext | None = None,
native_plan_valid: bool = False, native_plan_valid: bool = False,
cruise_ceiling_mps: float | None = None,
manual_event=None, manual_event=None,
ui_event=None, ui_event=None,
) -> tuple[HostProposal, SettingsSnapshot | None]: ) -> tuple[HostProposal, SettingsSnapshot | None]:
@@ -289,6 +290,7 @@ class ConditionalPlannerHost:
manual=self.manual_state if manual is None else manual, owner_context=context, manual=self.manual_state if manual is None else manual, owner_context=context,
selected_t_follow_s=selected_follow_time(planner), selected_t_follow_s=selected_follow_time(planner),
selected_t_follow_observed_mono_ns=sm.logMonoTime.get('modelV2'), selected_t_follow_observed_mono_ns=sm.logMonoTime.get('modelV2'),
cruise_ceiling_mps=cruise_ceiling_mps,
settings_owner=self.settings, settings_owner=self.settings,
) )
snapshot = self.settings.current snapshot = self.settings.current
@@ -406,6 +406,7 @@ class SceneProjector:
selected_t_follow_observed_mono_ns: int | None = None, selected_t_follow_observed_mono_ns: int | None = None,
owner_context: ConditionalOwnerContext | None = None, owner_context: ConditionalOwnerContext | None = None,
signal_options: CEMOptions | None = None, signal_options: CEMOptions | None = None,
cruise_ceiling_mps: float | None = None,
) -> ProjectedScene: ) -> ProjectedScene:
if ( if (
type(now_mono_ns) is not int type(now_mono_ns) is not int
@@ -441,6 +442,9 @@ class SceneProjector:
speed = _ego_speed(car) if car is not None and _field(car, 'canValid') is True and _field(car, 'canTimeout') is False else None speed = _ego_speed(car) if car is not None and _field(car, 'canValid') is True and _field(car, 'canTimeout') is False else None
cruise_kph = _number(_field(car, 'vCruise'), high=V_CRUISE_UNSET_KPH) if speed is not None else None cruise_kph = _number(_field(car, 'vCruise'), high=V_CRUISE_UNSET_KPH) if speed is not None else None
cruise = cruise_kph * KPH_TO_MPS if cruise_kph is not None and 0 < cruise_kph < V_CRUISE_UNSET_KPH else None cruise = cruise_kph * KPH_TO_MPS if cruise_kph is not None and 0 < cruise_kph < V_CRUISE_UNSET_KPH else None
if cruise_ceiling_mps is not None:
cap = _number(cruise_ceiling_mps, high=V_CRUISE_UNSET_KPH * KPH_TO_MPS)
cruise = min(cruise, cap) if cruise is not None and cap is not None and cap > 0 else None
curvature = _number(_field(controls, 'curvature'), low=-1.0, high=1.0) if controls is not None else None curvature = _number(_field(controls, 'curvature'), low=-1.0, high=1.0) if controls is not None else None
raw_curve = abs(speed * speed * curvature) >= FROZEN_CURVE_ACCEL_MPS2 if speed is not None and curvature is not None else None raw_curve = abs(speed * speed * curvature) >= FROZEN_CURVE_ACCEL_MPS2 if speed is not None and curvature is not None else None
horizon = None horizon = None
@@ -114,6 +114,20 @@ def owner_context(stamp: int, *, stop_time=8.0, slower=True, stopped=False):
class TestSceneProjector(unittest.TestCase): class TestSceneProjector(unittest.TestCase):
def test_conditional_speed_comparisons_use_the_slc_cap_without_mutating_set(self):
for cap, expected in ((None, 20.), (15., 15.), (25., 20.), (float('nan'), None)):
with self.subTest(cap=cap):
projector = SceneProjector()
sm = FakeSubMaster(serialized_scene(), MONO-5_000_000)
projector.project(sm, CP, now_mono_ns=MONO, now_boot_ns=BOOT, sample_skew_ns=1000)
now = MONO+50_000_000
sm.stamp(now)
sm.payloads.update(serialized_scene(stamp=BOOT+50_000_000))
result = projector.project(sm, CP, now_mono_ns=now, now_boot_ns=BOOT+50_000_000,
sample_skew_ns=1000, safe_mode=False, owner_context=owner_context(now), cruise_ceiling_mps=cap)
self.assertEqual(result.scene.set_speed_mps, expected)
self.assertEqual(sm['carState'].vCruise, 72.)
def test_standstill_filter_undershoot_requires_fresh_physical_zero_speed(self): def test_standstill_filter_undershoot_requires_fresh_physical_zero_speed(self):
cases = ((-1.401298464324817e-45, True, 0., True), cases = ((-1.401298464324817e-45, True, 0., True),
(-0.0008391447481699288, True, 0., True), (-0.0008391447481699288, True, 0., True),
+7 -1
View File
@@ -80,8 +80,14 @@ class CurveHost:
self.previous_long_active = False self.previous_long_active = False
self.previous_active_headway = None self.previous_active_headway = None
def sample(self, sm, CP, now_ns: int, *, drive_id: int = 0, event=None, follow_time_s: float | None = None): def sample(self, sm, CP, now_ns: int, *, drive_id: int = 0, event=None, follow_time_s: float | None = None,
cruise_ceiling_mps: float | None = None):
frame = frame_from_submaster(sm, CP, now_ns, drive_id=drive_id) frame = frame_from_submaster(sm, CP, now_ns, drive_id=drive_id)
if cruise_ceiling_mps is not None:
if not math.isfinite(cruise_ceiling_mps) or cruise_ceiling_mps <= 0:
frame = replace(frame, inputs_fresh=False)
else:
frame = replace(frame, cruise_mps=min(frame.cruise_mps, cruise_ceiling_mps))
if drive_id and self.lead_drive_id and drive_id != self.lead_drive_id: if drive_id and self.lead_drive_id and drive_id != self.lead_drive_id:
self._reset_leads() self._reset_leads()
if drive_id: if drive_id:
@@ -44,6 +44,12 @@ class TestCurveHost(unittest.TestCase):
self.sm.logMonoTime['radarState'] = NOW - 1_000_000_000 self.sm.logMonoTime['radarState'] = NOW - 1_000_000_000
self.assertIsNone(self.host.sample(self.sm, self.cp, NOW + 50_000_000).ceiling_mps) self.assertIsNone(self.host.sample(self.sm, self.cp, NOW + 50_000_000).ceiling_mps)
def test_curve_uses_same_cycle_slc_capped_cruise_without_mutating_set(self):
with patch.object(self.host.runtime, 'step', wraps=self.host.runtime.step) as step:
self.host.sample(self.sm, self.cp, NOW, follow_time_s=1.45, cruise_ceiling_mps=20.)
self.assertEqual(step.call_args.args[0].cruise_mps, 20.)
self.assertEqual(self.sm['carState'].vCruise, 108.)
def test_stock_owner_and_malformed_field_fail_closed(self): def test_stock_owner_and_malformed_field_fail_closed(self):
self.cp.openpilotLongitudinalControl = False self.cp.openpilotLongitudinalControl = False
self.assertIsNone(self.host.sample(self.sm, self.cp, NOW).ceiling_mps) self.assertIsNone(self.host.sample(self.sm, self.cp, NOW).ceiling_mps)
+1 -1
View File
@@ -21,7 +21,7 @@ CYCLE_PERSONALITY = "__starpilot_controller_action__:cycle_driving_personality"
# Saved preference shortcuts retain the current owner's authority and dependencies. # Saved preference shortcuts retain the current owner's authority and dependencies.
FEATURE_KEYS = { FEATURE_KEYS = {
"slc": ("SpeedLimitController", "ShowSpeedLimits", "SLCConfirmation", "SLCConfirmationHigher", "SLCConfirmationLower"), "slc": ("SpeedLimitController", "ShowSpeedLimits", "SLCConfirmation"),
"lane": ("LaneCentering", "LaneCenteringPauseOnSignal"), "lane": ("LaneCentering", "LaneCenteringPauseOnSignal"),
"curve": ("CurveSpeedController", "CurveSpeedControllerNoLead", "ShowCSCStatus"), "curve": ("CurveSpeedController", "CurveSpeedControllerNoLead", "ShowCSCStatus"),
"aol": ("AlwaysOnLateral", "NostalgiaMode"), "aol": ("AlwaysOnLateral", "NostalgiaMode"),
@@ -1 +1 @@
{"abi":{"SOABI":"cpython-312-aarch64-linux-gnu","cache_tag":"cpython-312","implementation":"cpython","machine":"aarch64","platform":"linux","pointer_bits":64,"python":[3,12]},"artifact_sha256":"1406542a4442c87106e579efbb8acd4aae4fb4ae17c91e0f2ce79cc0bc1c52d6","revision":"flm-exact-primitives-v1","schema":1,"sources":{"SConscript":"8e7589098349bc9400c9b99578fcdf661db204578762b2121ce9d2a1d34b90bd","SConstruct":"c4ae8224009dc8cba061b2304f7b4ea0ed570e6cbc3dde19f43a3eaf0c251a54","_primitive_walk.pyx":"564a8f5d0d0d1ac3af6cc873d7502440000a17e8609a1c900d0f90b09fb86a03","native_primitives.py":"1f197b261dde6219735d2d832ef7129c6f9fe8b9e415498115d722c74649acbf"}} {"abi":{"SOABI":"cpython-312-aarch64-linux-gnu","cache_tag":"cpython-312","implementation":"cpython","machine":"aarch64","platform":"linux","pointer_bits":64,"python":[3,12]},"artifact_sha256":"784d1e4627399be5e2b4953c8d406331f534a902dfce01904a17981980de6b5f","revision":"flm-exact-primitives-v1","schema":1,"sources":{"SConscript":"8e7589098349bc9400c9b99578fcdf661db204578762b2121ce9d2a1d34b90bd","SConstruct":"c4ae8224009dc8cba061b2304f7b4ea0ed570e6cbc3dde19f43a3eaf0c251a54","_primitive_walk.pyx":"564a8f5d0d0d1ac3af6cc873d7502440000a17e8609a1c900d0f90b09fb86a03","native_primitives.py":"1f197b261dde6219735d2d832ef7129c6f9fe8b9e415498115d722c74649acbf"}}
Binary file not shown.
@@ -62,12 +62,23 @@ DESCRIPTIONS = {
'CurveSpeedControllerNoLead': 'Pauses curve-speed adjustments while following a lead vehicle.', 'CurveSpeedControllerNoLead': 'Pauses curve-speed adjustments while following a lead vehicle.',
'ShowCSCStatus': 'Shows when Curve Speed Controller is adjusting speed on the driving screen.', '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.', 'curve_reset': 'Deletes saved cornering learning so Curve Speed Controller can learn your preferences again.',
'SpeedLimitController': 'Adjusts the set speed to accepted speed limits using your source priority and offsets.', 'SpeedLimitController': 'Follows accepted limits plus offsets up to SET speed. Missing data uses the previous accepted limit.',
'SLCOnEngage': ('Starts software cruise SET at the SLC limit plus offset. ' +
'A limit accepted this session remains available during data gaps. Previous-drive history does not initialize SET. ' +
'RES restores the previous SET.'),
'SLCOverrideMode': ('Cruise uses this target when you lift off the accelerator. ' +
'Holding your speed uses the highest speed you reached, up to SET.'),
'SLCWheelOverride': 'Press + to raise SET past the adjusted limit and use your new SET speed.',
'ShowSpeedLimits': 'Shows recognized speed-limit signs on the driving screen.', 'ShowSpeedLimits': 'Shows recognized speed-limit signs on the driving screen.',
'SLCConfirmation': 'Auto adopts new limits immediately. With Automatic adoption off, + accepts and − declines within 10 seconds.', 'SLCConfirmation': ('Off adopts new limits automatically. Both, Higher only, and Lower only prompt relative to the last accepted limit. ' +
'SLCAdvanceSeconds': 'Offers mapped limits early using road distance and current speed. Existing adoption and confirmation settings still apply.', '+ accepts and − declines within 30 seconds.'),
'SLCAdvanceHigherSeconds': ('Offers higher mapped limits early using road distance and current speed. ' +
'Existing adoption and confirmation settings still apply.'),
'SLCAdvanceLowerSeconds': ('Offers lower mapped limits early using road distance and current speed. ' +
'Existing adoption and confirmation settings still apply.'),
'SLCPriority1': 'Chooses the first source checked for a fresh speed limit.', 'SLCPriority1': 'Chooses the first source checked for a fresh speed limit.',
'SLCPriority2': 'Chooses the source used when the primary source has no fresh speed limit.', 'SLCPriority2': 'Chooses the source used when the primary source has no fresh speed limit.',
'SLCPriority3': 'Chooses an optional third source when neither earlier source has a fresh speed limit.',
'slc_reset': 'Resets saved speed-limit offsets while retaining valid configured speed ranges.', 'slc_reset': 'Resets saved speed-limit offsets while retaining valid configured speed ranges.',
'reset_calibration': 'Clears saved camera and steering calibration. The device recalibrates on the next drive.', 'reset_calibration': 'Clears saved camera and steering calibration. The device recalibrates on the next drive.',
'reset_driver_monitoring': 'Clear saved wheel-side detection. Automatic detection restarts on the next drive.', 'reset_driver_monitoring': 'Clear saved wheel-side detection. Automatic detection restarts on the next drive.',
@@ -77,10 +77,15 @@
"RelaxedJerkSpeedDecrease", "RelaxedJerkSpeedDecrease",
"RemoteStartBootsComma", "RemoteStartBootsComma",
"ReverseCruise", "ReverseCruise",
"SLCAdvanceSeconds", "SLCAdvanceHigherSeconds",
"SLCAdvanceLowerSeconds",
"SLCConfirmation", "SLCConfirmation",
"SLCOnEngage",
"SLCOverrideMode",
"SLCPriority1", "SLCPriority1",
"SLCPriority2", "SLCPriority2",
"SLCPriority3",
"SLCWheelOverride",
"ScreenBrightness", "ScreenBrightness",
"ScreenBrightnessOnroad", "ScreenBrightnessOnroad",
"ScreenTimeout", "ScreenTimeout",
@@ -63,40 +63,23 @@ class TestCanonicalRecovery(TestCase):
self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved']) self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved'])
self.assertEqual(recovery.snapshot(self.session, self.generation)['count'], 0) self.assertEqual(recovery.snapshot(self.session, self.generation)['count'], 0)
def test_legacy_confirmation_flags_do_not_create_hidden_customization(self): def test_directional_confirmation_resets_to_off(self):
self.params.put_bool('SLCConfirmation', False, block=True) self.params.put('SLCConfirmation', 4, block=True)
self.params.put_bool('SLCConfirmationLower', True, block=True)
self.params.put_bool('SLCConfirmationHigher', True, block=True)
recovery = self.recovery() recovery = self.recovery()
view = recovery.snapshot(self.session, self.generation) view = recovery.snapshot(self.session, self.generation)
children = [row for row in view['rows'] if row['label'] in ('Confirm lower limits', 'Confirm higher limits')] row = next(row for row in view['rows'] if row['label'] == 'Confirm limits')
self.assertEqual(children, []) pending = recovery.preview(view['view'], [row['id']], self.session, self.generation)
self.assertFalse(self.params.get_bool('SLCConfirmation'))
self.assertTrue(self.params.get_bool('SLCConfirmationLower'))
self.assertTrue(self.params.get_bool('SLCConfirmationHigher'))
def test_reset_confirmation_master_preserves_ignored_legacy_bytes(self):
for key in ('SLCConfirmation', 'SLCConfirmationLower', 'SLCConfirmationHigher'):
self.params.put_bool(key, True, block=True)
recovery = self.recovery()
view = recovery.snapshot(self.session, self.generation)
selected = [row['id'] for row in view['rows'] if row['label'] in
('Automatic adoption', 'Confirm lower limits', 'Confirm higher limits')]
self.assertEqual(len(selected), 1)
pending = recovery.preview(view['view'], selected, self.session, self.generation)
self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved']) self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved'])
self.assertFalse(self.params.get_bool('SLCConfirmation')) self.assertFalse(self.params.get('SLCConfirmation'))
for key in ('SLCConfirmationLower', 'SLCConfirmationHigher'):
self.assertTrue(self.params.get_bool(key))
def test_unsupported_rows_remain_visible_but_cannot_block_available_reset_all(self): def test_unsupported_rows_remain_visible_but_cannot_block_available_reset_all(self):
from dataclasses import replace from dataclasses import replace
self.params.put_bool('SLCConfirmation', True, block=True) self.params.put('SLCConfirmation', 1, block=True)
self.params.put_bool('ShowBrakeStatus', True, block=True) self.params.put_bool('ShowBrakeStatus', True, block=True)
self.context.value = replace(self.context.value, cp=None, cp_raw=None) self.context.value = replace(self.context.value, cp=None, cp_raw=None)
recovery = self.recovery() recovery = self.recovery()
view = recovery.snapshot(self.session, self.generation) view = recovery.snapshot(self.session, self.generation)
unsupported = next(row for row in view['rows'] if row['label'] == 'Automatic adoption') unsupported = next(row for row in view['rows'] if row['label'] == 'Confirm limits')
self.assertFalse(unsupported['resetAvailable']) self.assertFalse(unsupported['resetAvailable'])
with self.assertRaises(SettingsChanged): with self.assertRaises(SettingsChanged):
recovery.preview(view['view'], [unsupported['id']], self.session, self.generation) recovery.preview(view['view'], [unsupported['id']], self.session, self.generation)
@@ -104,7 +87,7 @@ class TestCanonicalRecovery(TestCase):
self.assertTrue(selected) self.assertTrue(selected)
pending = recovery.preview(view['view'], selected, self.session, self.generation) pending = recovery.preview(view['view'], selected, self.session, self.generation)
self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved']) self.assertTrue(recovery.confirm(pending['intent'], self.session, self.generation)['saved'])
self.assertTrue(self.params.get_bool('SLCConfirmation')) self.assertTrue(self.params.get('SLCConfirmation'))
self.assertFalse(self.params.get_bool('ShowBrakeStatus')) self.assertFalse(self.params.get_bool('ShowBrakeStatus'))
def test_other_canonical_inactive_children_reset_without_turning_their_masters_on(self): def test_other_canonical_inactive_children_reset_without_turning_their_masters_on(self):
@@ -44,20 +44,17 @@ class TestRecoveryHttp(TestCase):
rows = self.request('/api/settings/non-defaults', cookie=cookie)[1]['rows'] rows = self.request('/api/settings/non-defaults', cookie=cookie)[1]['rows']
self.assertNotIn('Wheel brake and acceleration colors', [row['label'] for row in rows]) self.assertNotIn('Wheel brake and acceleration colors', [row['label'] for row in rows])
def test_confirmation_reset_uses_only_master_and_preserves_legacy_flags(self): def test_confirmation_reset_restores_off(self):
for key in ('SLCConfirmation', 'SLCConfirmationLower', 'SLCConfirmationHigher'): self.params.put('SLCConfirmation', 1, block=True)
self.params.put_bool(key, True, block=True)
cookie = self.login() cookie = self.login()
payload = self.selection(cookie, ['Automatic adoption']) payload = self.selection(cookie, ['Confirm limits'])
status, pending, _ = self.request('/api/settings/recovery/preview', cookie=cookie, payload=payload) status, pending, _ = self.request('/api/settings/recovery/preview', cookie=cookie, payload=payload)
self.assertEqual(status, 200) self.assertEqual(status, 200)
result = self.request('/api/settings/recovery/confirm', cookie=cookie, result = self.request('/api/settings/recovery/confirm', cookie=cookie,
payload={'intent': pending['intent'], 'confirmed': True}) payload={'intent': pending['intent'], 'confirmed': True})
self.assertEqual(result[0], 200) self.assertEqual(result[0], 200)
self.assertTrue(result[1]['saved']) self.assertTrue(result[1]['saved'])
self.assertFalse(self.params.get_bool('SLCConfirmation')) self.assertFalse(self.params.get('SLCConfirmation'))
for key in ('SLCConfirmationLower', 'SLCConfirmationHigher'):
self.assertTrue(self.params.get_bool(key))
def test_wrong_selection_and_unconfirmed_requests_are_rejected(self): def test_wrong_selection_and_unconfirmed_requests_are_rejected(self):
self.params.put_bool('ShowBrakeStatus', True, block=True) self.params.put_bool('ShowBrakeStatus', True, block=True)
@@ -81,13 +78,13 @@ class TestRecoveryHttp(TestCase):
self.assertTrue(self.params.get_bool('ShowBrakeStatus')) self.assertTrue(self.params.get_bool('ShowBrakeStatus'))
def test_unsupported_rows_are_reported_and_available_reset_all_does_not_touch_them(self): def test_unsupported_rows_are_reported_and_available_reset_all_does_not_touch_them(self):
self.params.put_bool('SLCConfirmation', True, block=True) self.params.put('SLCConfirmation', 1, block=True)
self.params.put_bool('ShowBrakeStatus', True, block=True) self.params.put_bool('ShowBrakeStatus', True, block=True)
self.context.value = replace(self.context.value, cp=None, cp_raw=None) self.context.value = replace(self.context.value, cp=None, cp_raw=None)
cookie = self.login() cookie = self.login()
status, view, _ = self.request('/api/settings/non-defaults', cookie=cookie) status, view, _ = self.request('/api/settings/non-defaults', cookie=cookie)
self.assertEqual(status, 200) self.assertEqual(status, 200)
unsupported = next(row for row in view['rows'] if row['label'] == 'Automatic adoption') unsupported = next(row for row in view['rows'] if row['label'] == 'Confirm limits')
self.assertFalse(unsupported['resetAvailable']) self.assertFalse(unsupported['resetAvailable'])
self.assertEqual(self.request('/api/settings/recovery/preview', cookie=cookie, self.assertEqual(self.request('/api/settings/recovery/preview', cookie=cookie,
payload={'view': view['view'], 'selected': [unsupported['id']]})[0], 409) payload={'view': view['view'], 'selected': [unsupported['id']]})[0], 409)
@@ -99,4 +96,4 @@ class TestRecoveryHttp(TestCase):
self.assertEqual(result[0], 200) self.assertEqual(result[0], 200)
self.assertTrue(result[1]['saved']) self.assertTrue(result[1]['saved'])
self.assertFalse(self.params.get_bool('ShowBrakeStatus')) self.assertFalse(self.params.get_bool('ShowBrakeStatus'))
self.assertTrue(self.params.get_bool('SLCConfirmation')) self.assertTrue(self.params.get('SLCConfirmation'))
@@ -47,6 +47,25 @@ try {
assert.equal(starport.previewHidden("car_exit"), false) assert.equal(starport.previewHidden("car_exit"), false)
assert.deepEqual([...saved], before) assert.deepEqual([...saved], before)
for (const projection of [false, true]) {
const vm = editor(projection)
vm.state.scene = 'slc_pending'
vm.state.profile = 'large'
vm.layout = {clock:{enabled:true}}
vm.state.art = {status:'ready', scene:'slc_pending', profile:projection ? 'projection' : 'large',
sprites:{sprites:{clock:{visible:false}}}}
assert.equal(vm.sceneHidden('clock'), true, 'Native prompt occlusion hides the preview and its eye control')
vm.layout.clock.enabled = false
assert.equal(vm.sceneHidden('clock'), false, 'A disabled clock can still be added from the tray')
vm.layout.clock.enabled = true
for (const change of [{status:'updating'}, {scene:'engaged'}, {profile:'compact'}]) {
const native = vm.state.art
vm.state.art = {...native, ...change}
assert.equal(vm.sceneHidden('clock'), false, 'Retained artwork cannot apply stale visibility')
vm.state.art = native
}
}
saved.delete('gx-layout-preview-visibility-v2:comma') saved.delete('gx-layout-preview-visibility-v2:comma')
saved.set('gx-layout-preview-visibility-v1:comma', JSON.stringify({ large: { current_speed: true }, compact: { stopped_timer: true } })) saved.set('gx-layout-preview-visibility-v1:comma', JSON.stringify({ large: { current_speed: true }, compact: { stopped_timer: true } }))
const migrated = editor(false) const migrated = editor(false)
@@ -10,11 +10,11 @@ print(json.dumps(dict(document=default_document(), defaults=default_document(),
revision="native", editable=True, valid=True, activeProfile="large", supportedProfiles=["large"]))) revision="native", editable=True, valid=True, activeProfile="large", supportedProfiles=["large"])))
`], { encoding: "utf8" })) `], { encoding: "utf8" }))
assert.equal(validSnapshot(data), true) assert.equal(validSnapshot(data), true)
for (const version of [11, 12]) { for (const version of [11, 12, 13, 14]) {
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), true) assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), true)
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), true) assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), true)
} }
for (const version of [9, 10, 13]) { for (const version of [9, 10, 15]) {
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false) assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false)
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false) assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false)
} }
@@ -92,25 +92,26 @@ assert.equal(vm.layout.nav_map.opacity, 35)
assert.equal(validSnapshot({ ...data, document: vm.state.draft }), true) assert.equal(validSnapshot({ ...data, document: vm.state.draft }), true)
// Use actual native geometry for source attachment, bounds, and the transient timer. // Use actual native geometry for source attachment, bounds, and the transient timer.
assert.deepEqual(data.metadata.profiles.large.widgets.cruise_limits.sourcesExtent, {inline:108, card:116, actionGap:8}) assert.deepEqual(data.metadata.profiles.large.widgets.cruise_limits.sourcesExtent, {inline:104, card:112, actionGap:8})
vm.state.draft = structuredClone(data.document) vm.state.draft = structuredClone(data.document)
vm.state.selected = "cruise_limits" vm.state.selected = "cruise_limits"
vm.setSpeedSources("speedSources", true) vm.setSpeedSources("speedSources", true)
assert.equal(vm.layout.speed_limit_actions.y, 359) assert.equal(vm.layout.speed_limit_actions.y, 381)
vm.setSpeedSources("speedSourcesCard", true) vm.setSpeedSources("speedSourcesCard", true)
assert.equal(vm.layout.speed_limit_actions.y, 367) assert.equal(vm.layout.speed_limit_actions.y, 389)
vm.setSpeedSources("speedSources", false) vm.setSpeedSources("speedSources", false)
assert.equal(vm.layout.speed_limit_actions.y, 267) assert.equal(vm.layout.speed_limit_actions.y, 267)
const overlapping = structuredClone(data.document) const overlapping = structuredClone(data.document)
overlapping.layouts.large.cruise_limits.y = 550 overlapping.layouts.large.cruise_limits.y = 550
assert.equal(validDocument(overlapping, data.metadata), false) assert.equal(validDocument(overlapping, data.metadata), false)
// Keep the expanded confirmation clear of the torque arc while testing the bottom edge. // Disable torque while testing source attachment at the lower screen edge.
vm.layout.cruise_limits.x = 1520 vm.layout.torque_bar.enabled = false
vm.layout.speed_limit_actions.x = 1544 vm.layout.cruise_limits.x = 1430
vm.layout.speed_limit_actions.x = 1454
vm.layout.cruise_limits.y = 690 vm.layout.cruise_limits.y = 690
vm.layout.speed_limit_actions.y = 882 vm.layout.speed_limit_actions.y = 882
vm.setSpeedSources("speedSources", true) vm.setSpeedSources("speedSources", true)
assert.equal(vm.layout.cruise_limits.y, 590) assert.equal(vm.layout.cruise_limits.y, 568)
assert.equal(vm.layout.speed_limit_actions.y, 882) assert.equal(vm.layout.speed_limit_actions.y, 882)
assert.equal(validDocument(vm.state.draft, data.metadata), true) assert.equal(validDocument(vm.state.draft, data.metadata), true)
Object.assign(vm.layout.speed_limit_actions, {x:600, y:500}) Object.assign(vm.layout.speed_limit_actions, {x:600, y:500})
@@ -107,7 +107,7 @@ class TestOffroadConfigurationPages(unittest.TestCase):
'conditional': ('Saved driving mode',), 'conditional': ('Saved driving mode',),
'conditional/cem': ('Speed threshold', 'Speed with lead', 'Stop lights'), 'conditional/cem': ('Speed threshold', 'Speed with lead', 'Stop lights'),
'lane_change': ('Allow lane changes', 'Minimum lane-change speed', 'Automatic Lane Changes', 'Lane Change Speed'), 'lane_change': ('Allow lane changes', 'Minimum lane-change speed', 'Automatic Lane Changes', 'Lane Change Speed'),
'slc': ('Speed Limit Controller', 'Automatic adoption'), 'slc': ('Speed Limit Controller', 'Confirm limits'),
'profiles': ('Force Stop', 'Selected Acceleration Profile', 'Selected Deceleration Profile'), 'profiles': ('Force Stop', 'Selected Acceleration Profile', 'Selected Deceleration Profile'),
'torque': ('Steering Controller', 'Turn Assist', 'Lat Accel', 'Friction'), 'torque': ('Steering Controller', 'Turn Assist', 'Lat Accel', 'Friction'),
'wheel': ('Short press', 'Hold', 'Distance long press', 'MODE press', 'Star button'), 'wheel': ('Short press', 'Hold', 'Distance long press', 'MODE press', 'Star button'),
@@ -531,13 +531,12 @@ assert.match(OnroadLayoutPage.template, /state\.profile === 'compact'" class="gx
// One scene dropdown, grouped, with every scene exactly once. // One scene dropdown, grouped, with every scene exactly once.
assert.deepEqual(vm.sceneGroups.map(group => group.label), ["Editing", "Driving", "Conditional experimental", "Speed limit"]) assert.deepEqual(vm.sceneGroups.map(group => group.label), ["Editing", "Driving", "Conditional experimental", "Speed limit"])
assert.deepEqual(vm.sceneGroups.flatMap(group => group.scenes.map(scene => scene.id)).sort(), vm.scenes.map(scene => scene.id).sort()) assert.deepEqual(vm.sceneGroups.flatMap(group => group.scenes.map(scene => scene.id)).sort(), vm.scenes.map(scene => scene.id).sort())
// The Small screen only offers scenes that look different there; a hidden pick falls back to General edit. // Compact exposes its pedal and display-only states just like the large screen.
vm.state.scene = "slc_display" vm.state.scene = "slc_display"
vm.selectProfile("compact") vm.selectProfile("compact")
assert.equal(vm.state.scene, "general") assert.equal(vm.state.scene, "slc_display")
const smallScenes = vm.sceneGroups.flatMap(group => group.scenes.map(scene => scene.id)) const smallScenes = vm.sceneGroups.flatMap(group => group.scenes.map(scene => scene.id))
for (const id of ["slc_pedal", "slc_display"]) assert.ok(!smallScenes.includes(id), id) for (const id of ["slc_pedal", "slc_display", "slc_retained"]) assert.ok(smallScenes.includes(id), id)
assert.ok(smallScenes.includes('slc_retained')) // The override X is visible on the Small screen too.
assert.ok(smallScenes.includes("slc_unavailable") && smallScenes.includes("slc_disengaged")) assert.ok(smallScenes.includes("slc_unavailable") && smallScenes.includes("slc_disengaged"))
vm.selectProfile("large") vm.selectProfile("large")
assert.equal(vm.sceneGroups.flatMap(group => group.scenes).length, vm.scenes.length) assert.equal(vm.sceneGroups.flatMap(group => group.scenes).length, vm.scenes.length)
@@ -1211,12 +1210,28 @@ console.log('Display options, target switching and reload during polling passed'
// A closed developer sidebar makes the torque arc taller than its narrow-road box. // A closed developer sidebar makes the torque arc taller than its narrow-road box.
{ {
const sample = snapshot(), profile = sample.metadata.profiles.large const sample = snapshot(), profile = sample.metadata.profiles.large
profile.widgets.cruise_limits.height = 168 profile.widgets.cruise_limits.height = 194
profile.widgets.cruise_limits.confirmation = { x: 172, y: -12, width: 419, height: 204 } profile.widgets.cruise_limits.confirmation = { x: 172, y: -12, width: 388 * Math.hypot(2160,1080) / 1800, height: 168 * Math.hypot(2160,1080) / 1800 }
profile.widgets.torque_bar.confirmationObstacle = { x: 0, y: -48, width: 1250, height: 289 } profile.widgets.torque_bar.confirmationObstacle = { x: 0, y: -48, width: 1250, height: 289 }
assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 550, sample.document.layouts.large), true) assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 535, sample.document.layouts.large), true)
delete profile.widgets.torque_bar.confirmationObstacle delete profile.widgets.torque_bar.confirmationObstacle
assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 550, sample.document.layouts.large), false) assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 535, sample.document.layouts.large), false)
profile.widgets.cruise_limits.height = 276 profile.widgets.cruise_limits.height = 276
assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 500, sample.document.layouts.large), true) assert.equal(documentHelpers.overlapsReserved(profile, 'cruise_limits', 88, 500, sample.document.layouts.large), true)
} }
// Reserve the taller notice while keeping the opened buttons at their existing size.
{
const sample = snapshot(), profile = sample.metadata.profiles.compact
profile.widgets.max_speed.width = 146
profile.widgets.speed_limit = { ...profile.widgets.speed_limit, width: 128, height: 144,
confirmation: { x: -172, y: -8, width: 328, height: 159 } }
sample.document.version = 14
sample.document.layouts.compact.speed_limit = { x: 320, y: 16, enabled: true }
assert.equal(documentHelpers.overlapsReserved(profile, 'speed_limit', 320, 16, sample.document.layouts.compact), false)
assert.equal(validDocument(sample.document, sample.metadata), true)
assert.equal(documentHelpers.overlapsReserved(profile, 'speed_limit', 320, 20, sample.document.layouts.compact), true)
assert.equal(documentHelpers.overlapsReserved(profile, 'speed_limit', 320, 24, sample.document.layouts.compact), true)
assert.equal(documentHelpers.overlapsReserved(profile, 'speed_limit', 317, 16, sample.document.layouts.compact), true)
assert.equal(clampPlacement(profile, 'speed_limit', 330, 16, sample.document.layouts.compact).x, 320)
}
@@ -25,15 +25,15 @@ metadata.widgets.jetlink_status = { label: "Jetlink status", kind: "jetlink_stat
metadata.widgetOrder = [...(metadata.widgetOrder || Object.keys(native.metadata.profiles.large.widgets)), "jetlink_status", "car_exit"] metadata.widgetOrder = [...(metadata.widgetOrder || Object.keys(native.metadata.profiles.large.widgets)), "jetlink_status", "car_exit"]
const widgets = Object.fromEntries(Object.entries(metadata.widgets).map(([id, widget]) => [id, const widgets = Object.fromEntries(Object.entries(metadata.widgets).map(([id, widget]) => [id,
{ ...widget.default, ...(widget.resizable ? { size: widget.resizable.default } : {}) }])) { ...widget.default, ...(widget.resizable ? { size: widget.resizable.default } : {}) }]))
const doc = { version: 5, clock24Hour: false, largeUiGammaTrial: false, blindSpotBorder: false, signalBorder: false, blindSpotCamera: false, hidePersonalityAlerts: false, wheelPedalFeedback: false, leadIndicator: false, leadInfo: "Off", speedSources: false, speedSourcesCard: false, speedAlign: "center", canvas: { width: 2880, height: 1080 }, widgets } const doc = { version: 6, clock24Hour: false, largeUiGammaTrial: false, blindSpotBorder: false, signalBorder: false, blindSpotCamera: false, hidePersonalityAlerts: false, wheelPedalFeedback: false, leadIndicator: false, leadInfo: "Off", speedSources: false, speedSourcesCard: false, speedAlign: "center", canvas: { width: 2880, height: 1080 }, widgets }
const raw = { version: 1, document: doc, defaults: copy(doc), metadata, const raw = { version: 1, document: doc, defaults: copy(doc), metadata,
screen: { width: 1280, height: 720, margin_width: 0, margin_height: 240 }, screen: { width: 1280, height: 720, margin_width: 0, margin_height: 240 },
revision: "aa-screen-and-layout", editable: true, valid: true, revision: "aa-screen-and-layout", editable: true, valid: true,
colors: { palette: native.document.palette, widgetColors: native.document.widgetColors.large, roadColors: {} } } colors: { palette: native.document.palette, widgetColors: native.document.widgetColors.large, roadColors: {} } }
const data = editorSnapshot(raw) const data = editorSnapshot(raw)
assert.deepEqual(editorSnapshot({ ...raw, document: { ...doc, version: 4 }, defaults: { ...doc, version: 4 } }).document, assert.deepEqual(editorSnapshot({ ...raw, document: { ...doc, version: 4 }, defaults: { ...doc, version: 4 } }).document,
data.document, "version 4 layouts remain readable alongside the backend's version 5") data.document, "version 4 layouts remain readable alongside the backend's version 6")
for (const bad of [{ version: 6 }, { version: "5" }, { canvas: { width: 1920, height: 1080 } }]) for (const bad of [{ version: 7 }, { version: "5" }, { canvas: { width: 1920, height: 1080 } }])
assert.throws(() => editorSnapshot({ ...raw, document: { ...doc, ...bad } }), /does not match/) assert.throws(() => editorSnapshot({ ...raw, document: { ...doc, ...bad } }), /does not match/)
assert.equal(validSnapshot(data), true) assert.equal(validSnapshot(data), true)
@@ -260,7 +260,7 @@ const draft = copy(feed.data.document)
draft.layouts.large.current_speed.x += 20 draft.layouts.large.current_speed.x += 20
assert.equal(await feed.save(draft), true) assert.equal(await feed.save(draft), true)
assert.equal(requests[0].url, "./api/starport/layout") assert.equal(requests[0].url, "./api/starport/layout")
assert.equal(requests[1].body.document.version, 5) assert.equal(requests[1].body.document.version, 6)
assert.deepEqual(Object.keys(requests[1].body.document).sort(), ["blindSpotBorder", "blindSpotCamera", "canvas", "clock24Hour", "hidePersonalityAlerts", "largeUiGammaTrial", "leadIndicator", "leadInfo", "signalBorder", "speedAlign", "speedSources", "speedSourcesCard", "version", "wheelPedalFeedback", "widgets"]) assert.deepEqual(Object.keys(requests[1].body.document).sort(), ["blindSpotBorder", "blindSpotCamera", "canvas", "clock24Hour", "hidePersonalityAlerts", "largeUiGammaTrial", "leadIndicator", "leadInfo", "signalBorder", "speedAlign", "speedSources", "speedSourcesCard", "version", "wheelPedalFeedback", "widgets"])
assert.equal(requests[1].body.document.widgets.current_speed.x, 1170) assert.equal(requests[1].body.document.widgets.current_speed.x, 1170)
assert.equal(requests[1].body.document.speedAlign, "center") assert.equal(requests[1].body.document.speedAlign, "center")
@@ -76,7 +76,7 @@ class TestSavedTorquePage(unittest.TestCase):
self.assertTrue(self.gateway._context('torque').editing_saved_vehicle) self.assertTrue(self.gateway._context('torque').editing_saved_vehicle)
self.assertEqual(self.context.sample().cp.carFingerprint, 'HYUNDAI_IONIQ_6') self.assertEqual(self.context.sample().cp.carFingerprint, 'HYUNDAI_IONIQ_6')
self.assertEqual(self.gateway._context('slc').cp.carFingerprint, 'HYUNDAI_IONIQ_6') self.assertEqual(self.gateway._context('slc').cp.carFingerprint, 'HYUNDAI_IONIQ_6')
slc = next(row for row in self.page('slc')['rows'] if row['label'] == 'Automatic adoption') slc = next(row for row in self.page('slc')['rows'] if row['label'] == 'Confirm limits')
self.assertTrue(slc['available']) self.assertTrue(slc['available'])
self.offroad.return_value = False self.offroad.return_value = False
with patch.object(self.context, 'configuration_allowed', return_value=True): with patch.object(self.context, 'configuration_allowed', return_value=True):
@@ -461,9 +461,9 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertIn("Vision", primary["choices"]) self.assertIn("Vision", primary["choices"])
self.assertIn("Vision", secondary["choices"]) self.assertIn("Vision", secondary["choices"])
self.assertNotIn("require your confirmation", primary["reason"]) self.assertNotIn("require your confirmation", primary["reason"])
confirmation = next(row for row in rows if row["label"] == "Automatic adoption") confirmation = next(row for row in rows if row["label"] == "Confirm limits")
self.assertEqual(confirmation["value"], "On") self.assertEqual(confirmation["value"], "Off")
self.assertIn("immediately", confirmation["reason"]) self.assertIn("automatically", confirmation["reason"])
self.assertIn("accepts", confirmation["reason"]) self.assertIn("accepts", confirmation["reason"])
with mock.patch.dict(os.environ, {"SLC_REPLAY_RUNTIME": "0", "SLC_VISION_DEVELOPMENT": "0"}): with mock.patch.dict(os.environ, {"SLC_REPLAY_RUNTIME": "0", "SLC_VISION_DEVELOPMENT": "0"}):
@@ -27,10 +27,22 @@ const withHeader={...meta,sprites:{speed_limit_actions:{x:0,y:0,width:2,height:1
assert.deepEqual(await widgetArtMetadata(image(withHeader)),withHeader,'Native action sprites include the heading above the buttons') assert.deepEqual(await widgetArtMetadata(image(withHeader)),withHeader,'Native action sprites include the heading above the buttons')
for(const bad of [{...meta,width:3},{...meta,sprites:{conditional_mode:{x:1,y:0,width:2,height:1}}}, for(const bad of [{...meta,width:3},{...meta,sprites:{conditional_mode:{x:1,y:0,width:2,height:1}}},
{...meta,sprites:{conditional_mode:{x:0,y:0,width:NaN,height:1}}}, {...meta,sprites:{conditional_mode:{x:0,y:0,width:NaN,height:1}}},
{...meta,sprites:{speed_limit_actions:{x:0,y:0,width:2,height:1,offsetY:-33}}}, {...meta,sprites:{speed_limit_actions:{x:0,y:0,width:2,height:1,offsetY:-34}}},
{...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetY:-32}}}, {...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetY:-32}}},
{...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetX:1}}}])await assert.rejects(widgetArtMetadata(image(bad))) {...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetX:1}}}])await assert.rejects(widgetArtMetadata(image(bad)))
await assert.rejects(widgetArtMetadata(new Blob(['not PNG']))) await assert.rejects(widgetArtMetadata(new Blob(['not PNG'])))
for (const [id, offsetX, offsetY] of [['speed_limit', -182.5, -12.5], ['speed_limit', -2, 0], ['cruise_limits', 0, -12.5]]) {
const native = {...meta, sprites: {[id]: {x:0,y:0,width:2,height:1,offsetX,offsetY,visible:false}}}
assert.deepEqual(await widgetArtMetadata(image(native)), native)
}
for (const rect of [{offsetX:-193}, {offsetY:-14}, {visible:'false'}]) {
await assert.rejects(widgetArtMetadata(image({...meta,sprites:{speed_limit:{x:0,y:0,width:2,height:1,...rect}}})))
}
const compactIds=['weather','max_speed','speed_limit','steering_wheel','conditional_mode','following_distance','model_confidence',
'driver_monitor','speed_limit_actions','driving_mode_descriptions','clock']
const complete={...meta,sprites:Object.fromEntries(compactIds.map(id=>[id,{x:0,y:0,width:2,height:1,visible:true}]))}
assert.deepEqual(await widgetArtMetadata(image(complete)),complete)
await assert.rejects(widgetArtMetadata(image({...complete,sprites:{...complete.sprites,extra:{x:0,y:0,width:2,height:1}}})))
const flush=async()=>{for(let i=0;i<20;i++)await Promise.resolve()} const flush=async()=>{for(let i=0;i<20;i++)await Promise.resolve()}
function fixture() { function fixture() {
const updates=[],requests=[],timers=new Map(),revoked=[];let next=0,url=0,unauthorized=0 const updates=[],requests=[],timers=new Map(),revoked=[];let next=0,url=0,unauthorized=0
@@ -59,6 +71,7 @@ tick();await answer(1);assert.equal(requests.length,3);await answer(2);assert.eq
feed.update(document,'compact','engaged') feed.update(document,'compact','engaged')
assert.equal(feed.currentUrl,'blob:1','Returning to a profile restores its artwork immediately') assert.equal(feed.currentUrl,'blob:1','Returning to a profile restores its artwork immediately')
assert.equal(updates.at(-1).status,'ready');assert.equal(timers.size,0,'Unchanged cached artwork needs no request') assert.equal(updates.at(-1).status,'ready');assert.equal(timers.size,0,'Unchanged cached artwork needs no request')
assert.equal(updates.findLast(update=>'profile' in update).profile,'compact','Cached artwork retains its screen identity')
assert.deepEqual(revoked,[],'Switching profiles keeps both mounted sheets alive') assert.deepEqual(revoked,[],'Switching profiles keeps both mounted sheets alive')
feed.update(document,'large','braking');tick();await answer(3,503) feed.update(document,'large','braking');tick();await answer(3,503)
assert.equal(feed.currentUrl,'blob:2','A transient failure retains visible artwork') assert.equal(feed.currentUrl,'blob:2','A transient failure retains visible artwork')
@@ -1,7 +1,5 @@
import { widgetArtMetadata } from "./widget-art.js" import { widgetArtMetadata } from "./widget-art.js"
import { widgetSize } from "./onroad-layout-document.js" import { widgetSize } from "./onroad-layout-document.js"
// hiddenOn: screens where the scene looks exactly like another one. The Small screen has no text for these
// speed-limit states, so they match Engaged there.
export const PREVIEW_SCENES = [ export const PREVIEW_SCENES = [
{ id: "general", label: "General edit" }, { id: "general", label: "General edit" },
{ id: "engaged", label: "Engaged" }, { id: "engaged", label: "Engaged" },
@@ -17,11 +15,11 @@ export const PREVIEW_SCENES = [
{ id: "slc_pending", label: "Confirmation choices" }, { id: "slc_pending", label: "Confirmation choices" },
{ id: "slc_max", label: "Using set speed" }, { id: "slc_max", label: "Using set speed" },
{ id: "slc_equal", label: "Equal speed limits" }, { id: "slc_equal", label: "Equal speed limits" },
{ id: "slc_pedal", label: "Using accelerator", hiddenOn: ["compact"] }, { id: "slc_pedal", label: "Using accelerator" },
{ id: "slc_retained", label: "Set-speed override" }, { id: "slc_retained", label: "Set-speed override" },
{ id: "slc_disengaged", label: "Cruise off" }, { id: "slc_disengaged", label: "Cruise off" },
{ id: "slc_unavailable", label: "Unavailable speed limit" }, { id: "slc_unavailable", label: "Unavailable speed limit" },
{ id: "slc_display", label: "Display-only speed limit", hiddenOn: ["compact"] }, { id: "slc_display", label: "Display-only speed limit" },
] ]
const SCENES = PREVIEW_SCENES.map(({ id }) => id) const SCENES = PREVIEW_SCENES.map(({ id }) => id)
@@ -36,8 +34,9 @@ export function previewScene(scene) {
mode: off ? "Disengaged" : scene === "slc_pedal" ? "ACC - Override" : !longitudinal ? "Always On Lateral" : experimental ? "ACC - Experimental" : "ACC - Chill" } mode: off ? "Disengaged" : scene === "slc_pedal" ? "ACC - Override" : !longitudinal ? "Always On Lateral" : experimental ? "ACC - Experimental" : "ACC - Chill" }
} }
export function sceneHidesWidget(scene, profile, id, layout = {}, widgets = {}) { export function sceneHidesWidget(scene, profile, id, layout = {}, widgets = {}, sprites = {}) {
if (scene === "general") return false if (scene === "general") return false
if (layout?.[id]?.enabled && typeof sprites[id]?.visible === "boolean") return !sprites[id].visible
const { lateral, longitudinal } = previewScene(scene) const { lateral, longitudinal } = previewScene(scene)
if (id === "stopped_timer") return scene !== "stopped" if (id === "stopped_timer") return scene !== "stopped"
if (id === "cem_gauge") return !scene.startsWith("cem_") if (id === "cem_gauge") return !scene.startsWith("cem_")
@@ -159,7 +158,7 @@ export class LayoutPreviewFeed {
if (cached) this.latestArt.set(profile, cacheKey) if (cached) this.latestArt.set(profile, cacheKey)
const shown = cached || this.artCache.get(this.latestArt.get(profile)) const shown = cached || this.artCache.get(this.latestArt.get(profile))
this.currentUrl = shown?.url || null this.currentUrl = shown?.url || null
this.publish({ url: this.currentUrl, sprites: shown?.sprites || null, scene: shown?.scene || null }) this.publish({ url: this.currentUrl, sprites: shown?.sprites || null, scene: shown?.scene || null, profile })
if (cached?.key === renderKey) { if (cached?.key === renderKey) {
this.publish({ status: "ready", error: "" }) this.publish({ status: "ready", error: "" })
return return
@@ -140,7 +140,7 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
export function validDocument(document, metadata) { export function validDocument(document, metadata) {
if (!object(document)) return false if (!object(document)) return false
const profiles = metadata?.projection === true ? ["large"] : PROFILES const profiles = metadata?.projection === true ? ["large"] : PROFILES
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : ![11, 12].includes(document.version)) || if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : ![11, 12, 13, 14].includes(document.version)) ||
(Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") || (Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") ||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") || (Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) || (Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
@@ -606,7 +606,12 @@ export const OnroadLayoutPage = {
this.state.showEditingAids = !this.state.showEditingAids this.state.showEditingAids = !this.state.showEditingAids
try { localStorage.setItem(aidsPreferenceKey, this.state.showEditingAids ? "1" : "0") } catch { } try { localStorage.setItem(aidsPreferenceKey, this.state.showEditingAids ? "1" : "0") } catch { }
}, },
sceneHidden(id) { return sceneHidesWidget(this.state.scene, this.state.profile, id, this.layout, this.profile?.widgets) }, sceneHidden(id) {
const { scene, profile, art } = this.state
const sprites = art?.status === "ready" && art.scene === scene && art.profile === (this.projection ? "projection" : profile) ?
art.sprites?.sprites : undefined
return sceneHidesWidget(scene, profile, id, this.layout, this.profile?.widgets, sprites)
},
previewHidden(id) { previewHidden(id) {
if (this.projection && id === "car_exit") return false if (this.projection && id === "car_exit") return false
if (this.sceneHidden(id)) return true if (this.sceneHidden(id)) return true
@@ -25,7 +25,7 @@ export function editorSnapshot(raw) {
throw new Error(raw?.reason || "Connect Android Auto once to obtain the actual screen.") throw new Error(raw?.reason || "Connect Android Auto once to obtain the actual screen.")
const colors = raw.colors const colors = raw.colors
const document = (value) => { const document = (value) => {
if (![4, 5].includes(value.version) || value.canvas?.width !== raw.metadata.width || value.canvas?.height !== raw.metadata.height) if (![4, 5, 6].includes(value.version) || value.canvas?.width !== raw.metadata.width || value.canvas?.height !== raw.metadata.height)
throw new Error("The saved StarPort layout does not match its screen. Reload before editing.") throw new Error("The saved StarPort layout does not match its screen. Reload before editing.")
return { version: 8, clock24Hour: value.clock24Hour === true, largeUiGammaTrial: value.largeUiGammaTrial === true, blindSpotBorder: value.blindSpotBorder === true, signalBorder: value.signalBorder === true, blindSpotCamera: value.blindSpotCamera === true, hidePersonalityAlerts: value.hidePersonalityAlerts === true, wheelPedalFeedback: value.wheelPedalFeedback === true, leadIndicator: value.leadIndicator === true, leadInfo: LEAD_INFO.includes(value.leadInfo) ? value.leadInfo : "Off", speedSources: value.speedSources === true, speedSourcesCard: value.speedSourcesCard === true, speedAlign: ["center", "right"].includes(value.speedAlign) ? value.speedAlign : "left", ...(value.widgetOrder ? { widgetOrder: { large: clone(value.widgetOrder) } } : {}), palette: clone(colors.palette), layouts: { large: clone(value.widgets) }, return { version: 8, clock24Hour: value.clock24Hour === true, largeUiGammaTrial: value.largeUiGammaTrial === true, blindSpotBorder: value.blindSpotBorder === true, signalBorder: value.signalBorder === true, blindSpotCamera: value.blindSpotCamera === true, hidePersonalityAlerts: value.hidePersonalityAlerts === true, wheelPedalFeedback: value.wheelPedalFeedback === true, leadIndicator: value.leadIndicator === true, leadInfo: LEAD_INFO.includes(value.leadInfo) ? value.leadInfo : "Off", speedSources: value.speedSources === true, speedSourcesCard: value.speedSourcesCard === true, speedAlign: ["center", "right"].includes(value.speedAlign) ? value.speedAlign : "left", ...(value.widgetOrder ? { widgetOrder: { large: clone(value.widgetOrder) } } : {}), palette: clone(colors.palette), layouts: { large: clone(value.widgets) },
widgetColors: { large: clone(colors.widgetColors) }, roadColors: { large: clone(colors.roadColors) } } widgetColors: { large: clone(colors.widgetColors) }, roadColors: { large: clone(colors.roadColors) } }
@@ -38,7 +38,7 @@ export function editorSnapshot(raw) {
} }
export function projectionPayload(body, metadata) { export function projectionPayload(body, metadata) {
return { revision: body.revision, document: { version: 5, return { revision: body.revision, document: { version: 6,
canvas: { width: metadata.profiles.large.width, height: metadata.profiles.large.height }, canvas: { width: metadata.profiles.large.width, height: metadata.profiles.large.height },
clock24Hour: body.document.clock24Hour === true, clock24Hour: body.document.clock24Hour === true,
largeUiGammaTrial: body.document.largeUiGammaTrial === true, largeUiGammaTrial: body.document.largeUiGammaTrial === true,
@@ -32,14 +32,16 @@ export async function widgetArtMetadata(blob, header = null) {
metadata.width < 1 || metadata.width > 1024 || metadata.height < 1 || metadata.height > 1440 || metadata.width < 1 || metadata.width > 1024 || metadata.height < 1 || metadata.height > 1440 ||
metadata.width !== view.getUint32(16) || metadata.height !== view.getUint32(20) || metadata.width !== view.getUint32(16) || metadata.height !== view.getUint32(20) ||
!metadata.sprites || typeof metadata.sprites !== "object" || Array.isArray(metadata.sprites) || !metadata.sprites || typeof metadata.sprites !== "object" || Array.isArray(metadata.sprites) ||
Object.keys(metadata.sprites).length > 10) throw new Error("Invalid widget art metadata") Object.keys(metadata.sprites).length > 11) throw new Error("Invalid widget art metadata")
for (const [id, rect] of Object.entries(metadata.sprites)) { for (const [id, rect] of Object.entries(metadata.sprites)) {
const minX = id === "speed_limit" ? -192 : -2
const minY = id === "speed_limit_actions" ? -33 : ["cruise_limits", "speed_limit"].includes(id) ? -13 : -1
if (!/^[a-z_]+$/.test(id) || !rect || ![rect.x,rect.y,rect.width,rect.height].every(Number.isInteger) || if (!/^[a-z_]+$/.test(id) || !rect || ![rect.x,rect.y,rect.width,rect.height].every(Number.isInteger) ||
rect.x < 0 || rect.y < 0 || rect.width < 1 || rect.height < 1 || rect.x < 0 || rect.y < 0 || rect.width < 1 || rect.height < 1 ||
rect.x + rect.width > metadata.width || rect.y + rect.height > metadata.height || rect.x + rect.width > metadata.width || rect.y + rect.height > metadata.height ||
!Number.isFinite(rect.offsetX ?? 0) || (rect.offsetX ?? 0) <= -1 || (rect.offsetX ?? 0) > 0 || !Number.isFinite(rect.offsetX ?? 0) || (rect.offsetX ?? 0) < minX || (rect.offsetX ?? 0) > 0 ||
!Number.isFinite(rect.offsetY ?? 0) || (rect.offsetY ?? 0) <= (id === 'speed_limit_actions' ? -33 : -1) || !Number.isFinite(rect.offsetY ?? 0) || (rect.offsetY ?? 0) < minY || (rect.offsetY ?? 0) > 0 ||
(rect.offsetY ?? 0) > 0) throw new Error("Invalid widget art rectangle") (rect.visible !== undefined && typeof rect.visible !== "boolean")) throw new Error("Invalid widget art rectangle")
} }
return metadata return metadata
} }
@@ -28,12 +28,17 @@ CURVATURE_HOLD_CONFIRM_MIN = 0.003
CURVATURE_HOLD_CONFIRM_SWEPT = 0.6 CURVATURE_HOLD_CONFIRM_SWEPT = 0.6
TWITCH_GUARD_MAX_SPEED = 4.0 TWITCH_GUARD_MAX_SPEED = 4.0
TWITCH_GUARD_FADE_SPEED = 3.0 TWITCH_GUARD_FADE_SPEED = 3.0
TWITCH_GUARD_DURATION = 1.5
TWITCH_GUARD_PLAN_RATIO = 4.0 TWITCH_GUARD_PLAN_RATIO = 4.0
TWITCH_GUARD_FLOOR = 0.002 TWITCH_GUARD_FLOOR = 0.002
TWITCH_GUARD_STRAIGHT_LO = 0.005 TWITCH_GUARD_STRAIGHT_LO = 0.005
TWITCH_GUARD_STRAIGHT_HI = 0.014 TWITCH_GUARD_STRAIGHT_HI = 0.014
TWITCH_GUARD_MIN_REACH = 12.0 TWITCH_GUARD_MIN_REACH = 12.0
STOP_HOLD_MAX_SPEED = 2.5
STOP_HOLD_DIST = 1.5
STOP_HOLD_RELEASE_DIST = 3.0
STOP_HOLD_MIN_DECEL = 0.3
STOP_HOLD_MAX_CURVATURE = 0.01
STOP_GUARD_DIST = 5.0
def _plan_circle_curvature(xs, ys, lookahead: float) -> float: def _plan_circle_curvature(xs, ys, lookahead: float) -> float:
@@ -118,12 +123,18 @@ def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float) -> float:
return curvature + (math.copysign(limit, curvature) - curvature) * fade return curvature + (math.copysign(limit, curvature) - curvature) * fade
def update_twitch_guard(remaining: float, v_ego: float, standstill: bool) -> float: def update_twitch_guard(armed: bool, v_ego: float, standstill: bool) -> bool:
if not (math.isfinite(remaining) and math.isfinite(v_ego)): if not math.isfinite(v_ego):
return 0.0 return False
if standstill or abs(v_ego) <= 0.3: if standstill or abs(v_ego) <= 0.3:
return TWITCH_GUARD_DURATION return True
return max(remaining - DT_CTRL, 0.0) return armed and v_ego < TWITCH_GUARD_MAX_SPEED
def stopping_distance(v_ego: float, a_ego: float, max_speed: float = STOP_HOLD_MAX_SPEED) -> float:
if not (math.isfinite(v_ego) and math.isfinite(a_ego)) or v_ego >= max_speed:
return math.inf
return v_ego ** 2 / (2.0 * max(-a_ego, 0.01))
TURN_LEAD_T = 1.3 TURN_LEAD_T = 1.3
TURN_LEAD_MIN_M = 4.0 TURN_LEAD_MIN_M = 4.0
TURN_LEAD_MAX_M = 14.0 TURN_LEAD_MAX_M = 14.0
@@ -149,14 +160,46 @@ class ModelTurnAssist:
self.turn_hold_swept = 0.0 self.turn_hold_swept = 0.0
self.turn_hold_handoff_t = 0.0 self.turn_hold_handoff_t = 0.0
self.turn_blinker_swept = 0.0 self.turn_blinker_swept = 0.0
self.twitch_guard_remaining = 0.0 self.twitch_guard_armed = False
self.stop_hold_curvature = None
self.output_curvature = None
self.curvature = 0.0 self.curvature = 0.0
self.turn_hold_done = False self.turn_hold_done = False
def update_stopped(self, CS, new_desired_curvature):
if CS.leftBlinker or CS.rightBlinker or self.output_curvature is None:
self.reset()
return new_desired_curvature
if CS.steeringPressed:
self.output_curvature = self.curvature
return self.output_curvature
def update(self, CS, model_v2, CC, new_desired_curvature): def update(self, CS, model_v2, CC, new_desired_curvature):
blinker_dir = float(CS.rightBlinker) - float(CS.leftBlinker) blinker_dir = float(CS.rightBlinker) - float(CS.leftBlinker)
if CC.latActive and self.twitch_guard_remaining > 0.0 and (blinker_dir == 0.0) and (self.turn_hold_curvature == 0.0): stop_dist = stopping_distance(CS.vEgo, CS.aEgo)
new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo) entering = CS.aEgo < -STOP_HOLD_MIN_DECEL and stop_dist < STOP_HOLD_DIST and abs(self.curvature) < STOP_HOLD_MAX_CURVATURE
holding = self.stop_hold_curvature is not None and stop_dist < STOP_HOLD_RELEASE_DIST
if blinker_dir != 0.0:
self.twitch_guard_armed = False
elif (CS.aEgo < -STOP_HOLD_MIN_DECEL and abs(self.curvature) < TWITCH_GUARD_STRAIGHT_LO and
stopping_distance(CS.vEgo, CS.aEgo, TWITCH_GUARD_MAX_SPEED) < STOP_GUARD_DIST):
self.twitch_guard_armed = True
if CC.latActive and blinker_dir == 0.0 and self.turn_hold_curvature == 0.0 and (entering or holding):
if CS.steeringPressed:
self.stop_hold_curvature = self.curvature
elif self.stop_hold_curvature is None:
if self.output_curvature is not None:
self.stop_hold_curvature = self.output_curvature
elif self.twitch_guard_armed:
self.stop_hold_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo)
else:
self.stop_hold_curvature = new_desired_curvature
new_desired_curvature = self.stop_hold_curvature
self.twitch_guard_armed = True
else:
self.stop_hold_curvature = None
if CC.latActive and self.twitch_guard_armed and (blinker_dir == 0.0) and (self.turn_hold_curvature == 0.0):
new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo)
if blinker_dir == 0.0: if blinker_dir == 0.0:
self.turn_blinker_swept = 0.0 self.turn_blinker_swept = 0.0
else: else:
@@ -250,6 +293,7 @@ class ModelTurnAssist:
if CS.vEgo < CURVATURE_HOLD_RELEASE_SPEED and (not self.turn_hold_done) and (lead_curvature * blinker_dir > abs(self.turn_hold_curvature)): if CS.vEgo < CURVATURE_HOLD_RELEASE_SPEED and (not self.turn_hold_done) and (lead_curvature * blinker_dir > abs(self.turn_hold_curvature)):
held_mag = min(lead_curvature * blinker_dir, abs(self.turn_hold_curvature) + CURVATURE_HOLD_RATCHET_RATE * DT_CTRL) held_mag = min(lead_curvature * blinker_dir, abs(self.turn_hold_curvature) + CURVATURE_HOLD_RATCHET_RATE * DT_CTRL)
self.turn_hold_curvature = math.copysign(held_mag, lead_curvature) self.turn_hold_curvature = math.copysign(held_mag, lead_curvature)
self.output_curvature = new_desired_curvature
return new_desired_curvature return new_desired_curvature
@@ -0,0 +1,129 @@
import unittest
from types import SimpleNamespace
from openpilot.starpilot.lateral.model_turn_assist import (
STOP_HOLD_MAX_SPEED, TWITCH_GUARD_FLOOR, TWITCH_GUARD_MAX_SPEED, ModelTurnAssist, update_twitch_guard,
)
STRAIGHT = SimpleNamespace(position=SimpleNamespace(x=[0., 1., 2., 3.], y=[0., 0., 0., 0.]),
meta=SimpleNamespace(laneChangeState=0))
LONG_STRAIGHT = SimpleNamespace(position=SimpleNamespace(x=[float(x) for x in range(0, 80, 4)], y=[0.] * 20),
meta=SimpleNamespace(laneChangeState=0))
def car(speed, accel, blinker=0, pressed=False):
return SimpleNamespace(vEgo=speed, aEgo=accel, rightBlinker=blinker == 1, leftBlinker=blinker == -1,
steeringPressed=pressed, steeringTorque=0.)
def step(assist, speed, accel, desired, active=True, model=STRAIGHT, **kwargs):
return assist.update(car(speed, accel, **kwargs), model, SimpleNamespace(latActive=active), desired)
class TestStopHold(unittest.TestCase):
def test_holds_command_through_final_metre_of_stop(self):
assist = ModelTurnAssist()
self.assertEqual(step(assist, 2.0, -2.0, .002), .002)
for speed, desired in ((1.5, .004), (1.0, .010), (.6, .014)):
self.assertEqual(step(assist, speed, -2.0, desired), .002)
def test_releases_when_car_stops_slowing(self):
assist = ModelTurnAssist()
step(assist, 1.0, -2.0, .001)
self.assertEqual(step(assist, 1.0, -.5, .01), .001)
self.assertEqual(step(assist, 1.0, 0., .01), .01)
self.assertIsNone(assist.stop_hold_curvature)
def test_does_not_engage_far_from_stop_or_above_speed(self):
for speed, accel in ((2.0, -.5), (1.0, -.2), (STOP_HOLD_MAX_SPEED, -5.), (1.0, 1.)):
with self.subTest(speed=speed, accel=accel):
assist = ModelTurnAssist()
self.assertEqual(step(assist, speed, accel, .01), .01)
self.assertIsNone(assist.stop_hold_curvature)
def test_blinker_or_inactive_never_holds(self):
for direction in (-1, 1):
assist = ModelTurnAssist()
step(assist, 1.0, -2.0, .001)
self.assertNotEqual(step(assist, 1.0, -2.0, direction * .02, blinker=direction), .001)
self.assertIsNone(assist.stop_hold_curvature)
assist = ModelTurnAssist()
self.assertEqual(step(assist, 1.0, -2.0, .01, active=False), .01)
self.assertIsNone(assist.stop_hold_curvature)
def test_driver_steering_moves_hold_to_measured_curvature(self):
assist = ModelTurnAssist()
step(assist, 1.0, -2.0, .001)
assist.curvature = -.003
self.assertEqual(step(assist, .8, -2.0, .015, pressed=True), -.003)
assist.curvature = .009
self.assertEqual(step(assist, .6, -2.0, .015), -.003)
def test_latches_guarded_command_not_raw_model(self):
assist = ModelTurnAssist()
assist.twitch_guard_armed = True
self.assertEqual(step(assist, 1.0, 0., .012, model=LONG_STRAIGHT), TWITCH_GUARD_FLOOR)
self.assertEqual(step(assist, .6, -2.0, .012, model=LONG_STRAIGHT), TWITCH_GUARD_FLOOR)
def test_does_not_freeze_a_turn_in_progress(self):
assist = ModelTurnAssist()
assist.curvature = .02
self.assertEqual(step(assist, 1.0, -2.0, .04), .04)
self.assertIsNone(assist.stop_hold_curvature)
class TestTwitchGuardArming(unittest.TestCase):
def test_armed_from_standstill_until_max_speed(self):
self.assertTrue(update_twitch_guard(False, 0., True))
self.assertTrue(update_twitch_guard(False, .3, False))
self.assertFalse(update_twitch_guard(False, 1., False))
for speed in (.5, 2., TWITCH_GUARD_MAX_SPEED - .01):
self.assertTrue(update_twitch_guard(True, speed, False))
self.assertFalse(update_twitch_guard(True, TWITCH_GUARD_MAX_SPEED, False))
self.assertFalse(update_twitch_guard(True, float('nan'), False))
def test_released_stop_hold_hands_off_to_guard(self):
assist = ModelTurnAssist()
step(assist, 1.0, -2.0, .001, model=LONG_STRAIGHT)
self.assertTrue(assist.twitch_guard_armed)
self.assertEqual(step(assist, 1.0, 0., .012, model=LONG_STRAIGHT), TWITCH_GUARD_FLOOR)
def test_unarmed_guard_leaves_creep_command(self):
assist = ModelTurnAssist()
self.assertEqual(step(assist, 1.0, 0., .012, model=LONG_STRAIGHT), .012)
def test_stop_approach_arms_guard_only_with_straight_wheel(self):
assist = ModelTurnAssist()
self.assertEqual(step(assist, 3.0, -1.5, .012, model=LONG_STRAIGHT), TWITCH_GUARD_FLOOR)
assist = ModelTurnAssist()
assist.curvature = .006
self.assertEqual(step(assist, 3.0, -1.5, .012, model=LONG_STRAIGHT), .012)
assist = ModelTurnAssist()
self.assertEqual(step(assist, 3.0, -.2, .012, model=LONG_STRAIGHT), .012)
def test_standstill_keeps_last_command_instead_of_raw_model(self):
assist = ModelTurnAssist()
assist.twitch_guard_armed = True
self.assertEqual(step(assist, 1.0, 0., .012, model=LONG_STRAIGHT), TWITCH_GUARD_FLOOR)
self.assertEqual(assist.update_stopped(car(0., 0.), .012), TWITCH_GUARD_FLOOR)
assist.curvature = -.004
self.assertEqual(assist.update_stopped(car(0., 0., pressed=True), .012), -.004)
self.assertEqual(assist.update_stopped(car(0., 0.), .012), -.004)
def test_standstill_passes_raw_model_with_blinker_or_no_history(self):
self.assertEqual(ModelTurnAssist().update_stopped(car(0., 0.), .012), .012)
assist = ModelTurnAssist()
step(assist, 1.0, 0., .003)
self.assertEqual(assist.update_stopped(car(0., 0., blinker=1), .012), .012)
self.assertIsNone(assist.output_curvature)
def test_blinker_disarms_guard(self):
assist = ModelTurnAssist()
assist.twitch_guard_armed = True
step(assist, 2.0, 0., .012, model=LONG_STRAIGHT, blinker=1)
self.assertFalse(assist.twitch_guard_armed)
self.assertEqual(step(assist, 2.0, 0., .012, model=LONG_STRAIGHT), .012)
if __name__ == '__main__':
unittest.main()
+8 -9
View File
@@ -12,15 +12,14 @@ Policy order matters. Target shaping precedes PID preparation; vehicle output sh
`LongitudinalPlanner.update(sm, *, cruise_ceiling=None, profile_tuning=None)` accepts an optional `LongitudinalPlanner.update(sm, *, cruise_ceiling=None, profile_tuning=None)` accepts an optional
`CruiseCeiling(speed_mps, authority)` in addition to the existing driver cruise `CruiseCeiling(speed_mps, authority)` in addition to the existing driver cruise
message. The live caller supplies no ceiling. The planner still reads message. The live [SLC](../speed_limits/README.md) caller supplies a qualified cap.
`carState.vCruise` for the driver's selected ceiling and leaves every supplied The planner still reads `carState.vCruise` as the driver's selected ceiling and
Cap'n Proto message unchanged. [SLC](../speed_limits/README.md) adopts accepted leaves supplied messages unchanged. Accepted limits affect the planner cap, not SET.
limits into Card's ordinary cruise SET; it supplies no additional planner ceiling.
The optional input remains available to explicit callers and replay tests.
The `CruiseCeiling` dataclass validates no source or acceptance history by The `CruiseCeiling` dataclass validates no source or acceptance history by
construction. Its caller must first establish a fresh, accepted, normalized construction. Its caller must establish an accepted, normalized m/s ceiling in
m/s ceiling in the correct speed coordinate. The planner validates its numeric the correct speed coordinate, including the fixed previous-accepted-limit fallback.
Vehicle coordinates and authority remain fresh. The planner validates its numeric
shape and the shared four-mode `Authority` contract. It applies the lower of shape and the shared four-mode `Authority` contract. It applies the lower of
the supplied ceiling and the existing driver ceiling only when native system the supplied ceiling and the existing driver ceiling only when native system
longitudinal control is available, the supplied authority grants active system longitudinal control is available, the supplied authority grants active system
@@ -33,7 +32,7 @@ publish that diagnostic or alter the longitudinal plan schema.
This optional input changes only the cruise candidate before the planner's This optional input changes only the cruise candidate before the planner's
existing jerk limiting. SLC uses the ordinary cruise braking response and selected existing jerk limiting. SLC uses the ordinary cruise braking response and selected
profile after its SET adoption. Lead-relevance checks still prevent cruise comfort profile for its capped target; a cap does not strengthen a softer cruise profile. Lead-relevance checks still prevent cruise comfort
tuning from weakening braking for a close, slow or braking lead; malformed lead tuning from weakening braking for a close, slow or braking lead; malformed lead
evidence also vetoes that tuning. The native MPC, lead, e2e, stop and acceleration evidence also vetoes that tuning. The native MPC, lead, e2e, stop and acceleration
arbitration remain in place. An inactive planner may still compute a nonzero arbitration remain in place. An inactive planner may still compute a nonzero
@@ -111,7 +110,7 @@ different historical scales:
| Sport (`sport`) | 2.4 m/s² | 2.0 m/s² | | Sport (`sport`) | 2.4 m/s² | 2.0 m/s² |
These are positive deceleration magnitudes for ordinary cruise braking, These are positive deceleration magnitudes for ordinary cruise braking,
including an SLC change to cruise SET. Global values preserve the historical including a changed SLC cap. Global values preserve the historical
1.2 m/s² baseline with half/normal/double responses; explicit personality 1.2 m/s² baseline with half/normal/double responses; explicit personality
presets retain their original physical values. The distinction preserves presets retain their original physical values. The distinction preserves
existing tuning and saved-document compatibility. existing tuning and saved-document compatibility.
+87 -17
View File
@@ -7,11 +7,23 @@ from openpilot.common.realtime import DT_MDL
STANDSTILL_HOLD_NS = 2_000_000_000 STANDSTILL_HOLD_NS = 2_000_000_000
STANDSTILL_CLEAR_NS = 750_000_000 STANDSTILL_CLEAR_NS = 750_000_000
STOP_COMMIT_TIME_S = .5
SIGN_CONFIRM_STEP_S = 2 * DT_MDL
SIGN_MAX_SPEED_MPS = 17.88 SIGN_MAX_SPEED_MPS = 17.88
SIGN_MODEL_AGREE_M = 50.0 SIGN_MODEL_AGREE_M = 50.0
SIGN_SEED_M = 27.0 SIGN_SEED_M = 27.0
SIGN_ESTIMATE_HOLD_NS = 2_000_000_000
# Over a long model path a sign is only believed if stopping at its estimate would be a normal stop.
SIGN_LONG_PATH_MAX_DECEL = 2.5
SIGN_APPROACH_DECEL = 1.0 SIGN_APPROACH_DECEL = 1.0
MODEL_APPROACH_DECEL = .65 MODEL_APPROACH_DECEL = .65
# Stopped behind a car at a sign: the line is assumed one car length past that car's rear.
QUEUE_LEAD_MAX_M = 8.0
QUEUE_LEAD_LENGTH_M = 4.5
# A car still inside this margin past the line may just be moving up the queue, not through the intersection.
QUEUE_CLEAR_M = 5.0
QUEUE_SIGN_RECENT_NS = 10_000_000_000
QUEUE_MAX_SPEED_MPS = 6.0
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -56,6 +68,8 @@ class StopFrame:
resume_requested: bool = False resume_requested: bool = False
perception_available: bool = True perception_available: bool = True
sign: bool = False sign: bool = False
dashboard_sign: bool = False
vision_distance_m: float | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -96,12 +110,58 @@ class ForceStop:
self.previously_enabled = False self.previously_enabled = False
self.distance = 0.0 self.distance = 0.0
self.distance_cap = 0.0 self.distance_cap = 0.0
self.queue_sign_ns = 0
self.queue_line = None
self._clear_sign_estimate()
def _clear_sign_estimate(self):
self.dash_distance = None
self.vision_distance = None
self.vision_samples = 0
self.sign_evidence_ns = 0
def _sign_estimate(self, frame: StopFrame, now: int, travel: float) -> float | None:
if self.sign_evidence_ns and now - self.sign_evidence_ns > SIGN_ESTIMATE_HOLD_NS:
self._clear_sign_estimate()
if self.dash_distance is not None:
self.dash_distance = max(0.0, self.dash_distance - travel)
if self.vision_distance is not None:
self.vision_distance = max(0.0, self.vision_distance - travel)
vision = frame.vision_distance_m
if vision is not None and math.isfinite(vision) and vision >= 0:
self.vision_samples += 1
self.vision_distance = vision if self.vision_distance is None else (
self.vision_distance + (vision - self.vision_distance) / self.vision_samples)
if frame.dashboard_sign or frame.sign and self.vision_distance is None:
self.dash_distance = SIGN_SEED_M if self.dash_distance is None else min(self.dash_distance, SIGN_SEED_M)
if frame.sign or vision is not None:
self.sign_evidence_ns = now
estimates = [value for value in (self.dash_distance, self.vision_distance) if value is not None]
return sum(estimates) / len(estimates) if estimates else None
def _queue_step(self, frame: StopFrame, now: int, travel: float, lead_blocked: bool):
if frame.sign and lead_blocked:
self.queue_sign_ns = now
queued_lead = frame.lead_present and frame.lead_speed_mps < 1.0 and frame.lead_distance_m < QUEUE_LEAD_MAX_M
arm = frame.standstill and self.queue_sign_ns and now - self.queue_sign_ns <= QUEUE_SIGN_RECENT_NS
if queued_lead and (arm or self.queue_line is not None):
self.queue_line = frame.lead_distance_m + QUEUE_LEAD_LENGTH_M
elif self.queue_line is not None:
self.queue_line -= travel
if self.queue_line is not None and (frame.pedal_override or frame.resume_requested or self.queue_line <= 0 or
frame.speed_mps > QUEUE_MAX_SPEED_MPS):
self.queue_line = None
self.queue_sign_ns = 0
def _clear_standstill(self): def _clear_standstill(self):
self.standstill_since_ns = 0 self.standstill_since_ns = 0
self.standstill_clear_ns = 0 self.standstill_clear_ns = 0
self.standstill_reason = None self.standstill_reason = None
@property
def can_commit_next_frame(self) -> bool:
return self.timer + SIGN_CONFIRM_STEP_S >= STOP_COMMIT_TIME_S
def step(self, frame: StopFrame, tune: StopTune, offset_ft: int = 0) -> StopPlan: def step(self, frame: StopFrame, tune: StopTune, offset_ft: int = 0) -> StopPlan:
now = frame.model_ns now = frame.model_ns
if (type(now) is not int or now <= 0 or now <= self.last_model_ns or if (type(now) is not int or now <= 0 or now <= self.last_model_ns or
@@ -121,7 +181,10 @@ class ForceStop:
self.reset() self.reset()
return StopPlan() return StopPlan()
available = frame.perception_available available = frame.perception_available
if available and (frame.light or frame.raw_model_stopped) or frame.sign: sign_estimate = self._sign_estimate(frame, now, max(0.0, speed) * dt)
lead = (frame.lead_present and frame.lead_distance_m < tune.lead_veto_m and frame.lead_speed_mps < speed + 2)
self._queue_step(frame, now, max(0.0, speed) * dt, lead or frame.tracking_lead)
if available and (frame.light or frame.raw_model_stopped) or frame.sign or self.queue_line is not None:
if not frame.standstill: if not frame.standstill:
self.stop_seen_ns = now self.stop_seen_ns = now
if frame.standstill: if frame.standstill:
@@ -129,16 +192,21 @@ class ForceStop:
stop_then_turn = bool(self.stop_seen_ns and now - self.stop_seen_ns < 4_000_000_000) stop_then_turn = bool(self.stop_seen_ns and now - self.stop_seen_ns < 4_000_000_000)
turn = speed <= 18 * 0.44704 and frame.blinker and abs(frame.steering_angle_deg) >= 25 and not stop_then_turn turn = speed <= 18 * 0.44704 and frame.blinker and abs(frame.steering_angle_deg) >= 25 and not stop_then_turn
curved = available and abs(curvature) >= .003 and not stop_then_turn curved = available and abs(curvature) >= .003 and not stop_then_turn
lead = (frame.lead_present and frame.lead_distance_m < tune.lead_veto_m and frame.lead_speed_mps < speed + 2)
model_active = available and horizon < (108.0 if self.activation_gate and frame.light else 100.0) model_active = available and horizon < (108.0 if self.activation_gate and frame.light else 100.0)
self.activation_gate = model_active and frame.light self.activation_gate = model_active and frame.light
permitted = (available and now >= self.override_until_ns and not frame.driving_in_curve and not turn and permitted = (available and now >= self.override_until_ns and not frame.driving_in_curve and not turn and
not frame.tracking_lead and not lead) not frame.tracking_lead and not lead)
model_path = frame.light and model_active and permitted and not curved model_path = frame.light and model_active and permitted and not curved
sign_path = frame.sign and permitted and speed < SIGN_MAX_SPEED_MPS and horizon < SIGN_MODEL_AGREE_M plausible = sign_estimate is None or speed * speed <= 2 * SIGN_LONG_PATH_MAX_DECEL * max(sign_estimate, 1.0)
if sign_path: sign_path = (frame.sign and permitted and speed < SIGN_MAX_SPEED_MPS and
(horizon < SIGN_MODEL_AGREE_M or self.forcing and plausible))
line_blocked = (self.queue_line is not None and frame.lead_present and
frame.lead_distance_m < self.queue_line + QUEUE_CLEAR_M)
queue_path = (self.queue_line is not None and not line_blocked and not frame.standstill and available and
now >= self.override_until_ns and not frame.driving_in_curve and not turn)
if sign_path or queue_path:
self.sign_confirmed = True self.sign_confirmed = True
active = model_path or sign_path active = model_path or sign_path or queue_path
if model_path: if model_path:
self.from_light = True self.from_light = True
self.light_clear_ns = 0 self.light_clear_ns = 0
@@ -177,17 +245,17 @@ class ForceStop:
if not available and not self.forcing: if not available and not self.forcing:
self.timer = 0 self.timer = 0
elif active and not frame.standstill: elif active and not frame.standstill:
self.timer = min(2.0, self.timer + DT_MDL * (2 if frame.sign else 1)) self.timer = min(2.0, self.timer + (SIGN_CONFIRM_STEP_S if frame.sign or queue_path else DT_MDL))
elif turn and not self.forcing and not frame.standstill: elif turn and not self.forcing and not frame.standstill:
self.timer = 0 self.timer = 0
elif held: elif held:
self.timer = max(self.timer, .5) self.timer = max(self.timer, STOP_COMMIT_TIME_S)
elif self.forcing and frame.standstill and not frame.sign and not frame.light and not frame.raw_model_stopped: elif self.forcing and frame.standstill and not frame.sign and not frame.light and not frame.raw_model_stopped:
self.timer = 0 self.timer = 0
else: else:
self.timer = max(0, self.timer - DT_MDL * .25) self.timer = max(0, self.timer - DT_MDL * .25)
force = self.timer >= .5 or self.forcing and not frame.standstill or held force = self.timer >= STOP_COMMIT_TIME_S or self.forcing and not frame.standstill or held
light_cleared = (not held and self.forcing and self.from_light and not frame.standstill and light_cleared = (not held and self.forcing and self.from_light and not frame.standstill and not self.sign_confirmed and
available and not frame.light and not frame.sign and go_scene) available and not frame.light and not frame.sign and go_scene)
low_speed_hold = (light_cleared and tune.low_speed_hold_mps is not None and self.entry_speed is not None and low_speed_hold = (light_cleared and tune.low_speed_hold_mps is not None and self.entry_speed is not None and
speed <= tune.low_speed_hold_mps and speed < self.entry_speed - .25) speed <= tune.low_speed_hold_mps and speed < self.entry_speed - .25)
@@ -224,12 +292,12 @@ class ForceStop:
elif available: elif available:
self.distance = min(self.distance, horizon) self.distance = min(self.distance, horizon)
self.distance_cap = max(0.0, self.distance_cap - speed * dt) self.distance_cap = max(0.0, self.distance_cap - speed * dt)
self.distance = min(self.distance, self.distance_cap + 15 * min(self.distance_cap / 60, 1)) cap = self.distance_cap + 15 * min(self.distance_cap / 60, 1)
if frame.sign and available: self.distance = min(self.distance, cap)
if horizon < SIGN_MODEL_AGREE_M: if sign_estimate is not None and (self.sign_confirmed or frame.sign and available and horizon < SIGN_MODEL_AGREE_M):
self.distance = min(self.distance, SIGN_SEED_M) self.distance = min(sign_estimate, cap)
if horizon < SIGN_SEED_M: if self.queue_line is not None and self.sign_confirmed:
self.distance = horizon self.distance = self.queue_line
effective = self.distance + offset + tune.distance_bias_m effective = self.distance + offset + tune.distance_bias_m
decel = SIGN_APPROACH_DECEL if frame.sign else MODEL_APPROACH_DECEL decel = SIGN_APPROACH_DECEL if frame.sign else MODEL_APPROACH_DECEL
ceiling = math.sqrt(2 * decel * max(0, effective - tune.handoff_m)) ceiling = math.sqrt(2 * decel * max(0, effective - tune.handoff_m))
@@ -245,10 +313,12 @@ class ForceStop:
if effective > tune.handoff_m: if effective > tune.handoff_m:
ceiling = math.sqrt(2 * MODEL_APPROACH_DECEL * (effective - tune.handoff_m)) ceiling = math.sqrt(2 * MODEL_APPROACH_DECEL * (effective - tune.handoff_m))
self.previously_enabled = frame.enabled self.previously_enabled = frame.enabled
stop_length = self.distance if self.forcing and self.distance > tune.handoff_m else approach stop_length = self.distance if self.forcing else approach
# The MPC obstacle includes its standing-distance term; adding it at the # The MPC obstacle includes its standing-distance term; adding it at the
# native boundary avoids moving the actual stop line by that buffer. # native boundary avoids moving the actual stop line by that buffer.
obstacle = stop_length * .93 + offset + tune.distance_bias_m if stop_length > tune.handoff_m else None # The offset moves the handoff with the ceiling; otherwise a positive offset creeps with no stop target.
obstacle = (stop_length * .93 + offset + tune.distance_bias_m
if stop_length > 0 and stop_length + offset > tune.handoff_m else None)
return StopPlan(now, ceiling, obstacle, self.forcing, bool(self.forcing and ceiling is not None and ceiling <= .5), return StopPlan(now, ceiling, obstacle, self.forcing, bool(self.forcing and ceiling is not None and ceiling <= .5),
self.distance if self.forcing else 0.0, approach, self.distance if self.forcing else 0.0, approach,
tune.jerk_scale if self.forcing or approach > 0 else 1.0, bool(held and self.forcing and not overridden), tune.jerk_scale if self.forcing or approach > 0 else 1.0, bool(held and self.forcing and not overridden),
@@ -51,6 +51,7 @@ class ForceStopRuntime:
self.policy = ForceStop() self.policy = ForceStop()
self.resume = StopResume() self.resume = StopResume()
self.vision_stop = StopConfirmation() self.vision_stop = StopConfirmation()
self.vision_ranged_ns = 0
self.light = StopLightDetector() self.light = StopLightDetector()
self.lead = LeadDetector() self.lead = LeadDetector()
self.plan = StopPlan() self.plan = StopPlan()
@@ -66,6 +67,7 @@ class ForceStopRuntime:
def reset(self): def reset(self):
self.vision_stop.reset() self.vision_stop.reset()
self.vision_ranged_ns = 0
self.resume.reset() self.resume.reset()
self.policy.reset() self.policy.reset()
self.light.reset() self.light.reset()
@@ -184,14 +186,19 @@ class ForceStopRuntime:
return self.plan return self.plan
vision_sign = self.vision_stop.observe( vision_sign = self.vision_stop.observe(
read_stop_evidence(sm, now_ns=now_ns, now_boot_ns=now_boot_ns, drive_id=drive_id), now_ns=now_ns) read_stop_evidence(sm, now_ns=now_ns, now_boot_ns=now_boot_ns, drive_id=drive_id), now_ns=now_ns)
vision_fresh = bool(vision_sign and 0 <= now_ns - vision_sign <= CONTROL_STOP_MAX_AGE_NS)
vision_distance = None
if vision_fresh and vision_sign != self.vision_ranged_ns and self.vision_stop.distance_m is not None:
self.vision_ranged_ns = vision_sign
vision_distance = self.vision_stop.distance_m - float(car.vEgo) * (stamp - vision_sign) / 1e9
dashboard_sign = dashboard_stop_sign(sm, now_ns=now_ns, drive_id=drive_id)
frame = StopFrame(stamp, float(car.vEgo), horizon, light_context, horizon is not None and horizon < 50, frame = StopFrame(stamp, float(car.vEgo), horizon, light_context, horizon is not None and horizon < 50,
bool(model.action.shouldStop), bool(car.standstill), True, bool(car.gasPressed), bool(model.action.shouldStop), bool(car.standstill), True, bool(car.gasPressed),
tracked is not None and tracked.tracked is True, bool(lead.present), float(lead.dRel), float(lead.vLead), tracked is not None and tracked.tracked is True, bool(lead.present), float(lead.dRel), float(lead.vLead),
raw_curve[1] if raw_curve is not None else False, curvature[0] if curvature is not None else None, raw_curve[1] if raw_curve is not None else False, curvature[0] if curvature is not None else None,
bool(car.leftBlinker or car.rightBlinker), float(car.steeringAngleDeg), resume_requested=resume_requested, bool(car.leftBlinker or car.rightBlinker), float(car.steeringAngleDeg), resume_requested=resume_requested,
perception_available=perception_available, perception_available=perception_available, sign=dashboard_sign or vision_fresh,
sign=dashboard_stop_sign(sm, now_ns=now_ns, drive_id=drive_id) or dashboard_sign=dashboard_sign, vision_distance_m=vision_distance)
bool(vision_sign and 0 <= now_ns - vision_sign <= CONTROL_STOP_MAX_AGE_NS))
self.plan = self.policy.step(frame, vehicle_tune(str(cp.carFingerprint)), self.offset) self.plan = self.policy.step(frame, vehicle_tune(str(cp.carFingerprint)), self.offset)
if takeoff_enabled: if takeoff_enabled:
self.plan = replace(self.plan, takeoff_light_observed=takeoff_observed, takeoff_light=takeoff_light) self.plan = replace(self.plan, takeoff_light_observed=takeoff_observed, takeoff_light=takeoff_light)
@@ -229,6 +229,138 @@ class ForceStopTests(unittest.TestCase):
plan = self.owner.step(frame(tick, speed_mps=0., horizon_m=190., light=False, standstill=True), self.tune) plan = self.owner.step(frame(tick, speed_mps=0., horizon_m=190., light=False, standstill=True), self.tune)
self.assertFalse(plan.forcing) self.assertFalse(plan.forcing)
def test_latched_sign_survives_light_and_sign_dropout(self):
for tick in range(15):
self.owner.step(frame(tick, speed_mps=8., horizon_m=45., sign=True), self.tune)
self.assertTrue(self.owner.sign_confirmed)
for tick in range(15, 45):
plan = self.owner.step(frame(tick, speed_mps=1., horizon_m=190., light=False), self.tune)
self.assertTrue(plan.forcing)
def test_sign_seed_never_moves_the_stop_farther(self):
for tick in range(50):
previous = self.owner.step(frame(tick, speed_mps=8., horizon_m=45., sign=True), self.tune)
self.assertLess(previous.tracked_distance_m, 20.)
plan = self.owner.step(frame(50, speed_mps=8., horizon_m=20., sign=True), self.tune)
self.assertLessEqual(plan.tracked_distance_m, previous.tracked_distance_m)
def test_sign_latches_and_seeds_over_long_path_once_light_committed(self):
for tick in range(15):
plan = self.owner.step(frame(tick, horizon_m=60.), self.tune)
self.assertTrue(plan.forcing)
self.assertGreater(plan.tracked_distance_m, 50.)
plan = self.owner.step(frame(15, horizon_m=60., sign=True), self.tune)
self.assertTrue(self.owner.sign_confirmed)
self.assertLessEqual(plan.tracked_distance_m, 27.)
plan = self.owner.step(frame(16, horizon_m=60., light=False), self.tune)
self.assertLess(plan.tracked_distance_m, 27.)
def test_long_path_sign_needing_a_hard_stop_is_ignored(self):
for tick in range(15):
plan = self.owner.step(frame(tick, speed_mps=13., horizon_m=90.), self.tune)
self.assertTrue(plan.forcing)
for tick in range(15, 55):
plan = self.owner.step(frame(tick, speed_mps=13., horizon_m=90., sign=True, dashboard_sign=True), self.tune)
self.assertFalse(self.owner.sign_confirmed)
self.assertGreater(plan.tracked_distance_m, 50.)
def test_long_path_sign_alone_does_not_commit(self):
for tick in range(20):
plan = self.owner.step(frame(tick, horizon_m=60., light=False, sign=True), self.tune)
self.assertFalse(plan.forcing)
self.assertFalse(self.owner.sign_confirmed)
def test_vision_distance_replaces_assumed_sign_distance(self):
for tick in range(15):
plan = self.owner.step(frame(tick, horizon_m=60.), self.tune)
plan = self.owner.step(frame(15, horizon_m=60., sign=True, vision_distance_m=35.), self.tune)
self.assertTrue(self.owner.sign_confirmed)
self.assertAlmostEqual(plan.tracked_distance_m, 35.)
plan = self.owner.step(frame(16, horizon_m=60., sign=True), self.tune)
self.assertAlmostEqual(plan.tracked_distance_m, 34.5)
plan = self.owner.step(frame(17, horizon_m=60., sign=True, vision_distance_m=31.), self.tune)
self.assertAlmostEqual(plan.tracked_distance_m, 32.5)
def test_dashboard_and_vision_distances_are_averaged(self):
for tick in range(15):
self.owner.step(frame(tick, horizon_m=60.), self.tune)
plan = self.owner.step(frame(15, horizon_m=60., sign=True, dashboard_sign=True), self.tune)
self.assertAlmostEqual(plan.tracked_distance_m, 27.)
plan = self.owner.step(frame(16, horizon_m=60., sign=True, dashboard_sign=True, vision_distance_m=35.), self.tune)
self.assertAlmostEqual(plan.tracked_distance_m, (26.5 + 35.) / 2)
def test_sign_distance_expires_without_evidence_and_never_jumps_back(self):
for tick in range(15):
self.owner.step(frame(tick, horizon_m=60.), self.tune)
self.owner.step(frame(15, horizon_m=60., sign=True, vision_distance_m=30.), self.tune)
for tick in range(16, 70):
plan = self.owner.step(frame(tick, speed_mps=4., horizon_m=60., light=True), self.tune)
self.assertLess(plan.tracked_distance_m, 30.)
self.assertIsNone(self.owner.vision_distance)
def queue_behind_lead(self, sign=True):
for tick in range(10):
plan = self.owner.step(frame(tick, speed_mps=8., horizon_m=45., light=False, sign=sign, lead_present=True,
lead_distance_m=20., lead_speed_mps=0.), self.tune)
self.assertFalse(plan.forcing)
for tick in range(10, 30):
plan = self.owner.step(frame(tick, speed_mps=0., horizon_m=5., light=False, standstill=True, lead_present=True,
lead_distance_m=5., lead_speed_mps=0.), self.tune)
self.assertFalse(plan.forcing)
def test_sign_behind_stopped_lead_stops_at_line_after_lead_leaves(self):
self.queue_behind_lead()
self.assertAlmostEqual(self.owner.queue_line, 9.5)
for tick in range(30, 35):
plan = self.owner.step(frame(tick, speed_mps=0., horizon_m=12., light=False, standstill=True, lead_present=True,
lead_distance_m=7., lead_speed_mps=3.), self.tune)
self.assertFalse(plan.forcing)
for tick in range(35, 45):
plan = self.owner.step(frame(tick, speed_mps=1., horizon_m=15., light=False), self.tune)
self.assertTrue(plan.forcing)
self.assertTrue(self.owner.sign_confirmed)
self.assertAlmostEqual(plan.tracked_distance_m, 9.5 - 10 * .05)
for tick in range(45, 100):
plan = self.owner.step(frame(tick, speed_mps=0., horizon_m=15., light=False, standstill=True), self.tune)
self.assertTrue(plan.manual_hold)
released = self.owner.step(frame(100, speed_mps=0., horizon_m=15., light=False, standstill=True,
pedal_override=True), self.tune)
self.assertFalse(released.manual_hold)
self.assertIsNone(self.owner.queue_line)
def test_lead_stop_without_sign_is_not_remembered(self):
self.queue_behind_lead(sign=False)
self.assertIsNone(self.owner.queue_line)
for tick in range(30, 50):
plan = self.owner.step(frame(tick, speed_mps=1., horizon_m=15., light=False), self.tune)
self.assertFalse(plan.forcing)
def test_lead_moving_up_the_queue_is_followed_not_stopped_for(self):
self.queue_behind_lead()
for tick in range(30, 60):
plan = self.owner.step(frame(tick, speed_mps=1., horizon_m=15., light=False, lead_present=True,
lead_distance_m=6., lead_speed_mps=1.5), self.tune)
self.assertFalse(plan.forcing)
plan = self.owner.step(frame(60, speed_mps=0., horizon_m=5., light=False, standstill=True, lead_present=True,
lead_distance_m=4., lead_speed_mps=0.), self.tune)
self.assertFalse(plan.forcing)
self.assertAlmostEqual(self.owner.queue_line, 8.5)
def test_driver_gas_while_queued_forgets_the_sign(self):
self.queue_behind_lead()
self.owner.step(frame(30, speed_mps=0., horizon_m=5., light=False, standstill=True, pedal_override=True), self.tune)
self.assertIsNone(self.owner.queue_line)
for tick in range(31, 50):
plan = self.owner.step(frame(tick, speed_mps=1., horizon_m=15., light=False), self.tune)
self.assertFalse(plan.forcing)
def test_positive_offset_keeps_stop_target_until_native_stop(self):
for tick in range(40):
plan = self.owner.step(frame(tick, horizon_m=12.), self.tune, 8)
if plan.forcing:
self.assertTrue(plan.should_stop or plan.obstacle_m is not None)
self.assertTrue(plan.should_stop)
def test_odometry_ceiling_bounds_reopened_model(self): def test_odometry_ceiling_bounds_reopened_model(self):
for tick in range(15): for tick in range(15):
self.owner.step(frame(tick), self.tune) self.owner.step(frame(tick), self.tune)
@@ -7,11 +7,12 @@ from opendbc.car.honda.interface import CarInterface
from opendbc.car.honda.values import CAR from opendbc.car.honda.values import CAR
from openpilot.common.params import Params from openpilot.common.params import Params
from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner
from openpilot.selfdrive.controls.plannerd import update_curve_frame from openpilot.selfdrive.controls.plannerd import update_curve_frame, wheel_override_blocked
from openpilot.starpilot.curve_speed.host import CurveHost from openpilot.starpilot.curve_speed.host import CurveHost
from openpilot.starpilot.longitudinal.force_stop import StopPlan from openpilot.starpilot.longitudinal.force_stop import StopPlan, vehicle_tune
from openpilot.starpilot.longitudinal.force_stop_runtime import ForceStopRuntime, dashboard_stop_sign from openpilot.starpilot.longitudinal.force_stop_runtime import ForceStopRuntime, dashboard_stop_sign
from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import messages, snapshot from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import messages, snapshot
from openpilot.starpilot.longitudinal.tests.test_force_stop import frame as stop_frame
from openpilot.starpilot.longitudinal.tests.test_stop_resume import event as button_event from openpilot.starpilot.longitudinal.tests.test_stop_resume import event as button_event
BASE = 100_000_000_000 BASE = 100_000_000_000
@@ -61,6 +62,31 @@ class ForceStopRuntimeTests(unittest.TestCase):
self.assertTrue(output.forcing) self.assertTrue(output.forcing)
return output return output
def test_wheel_priority_requires_a_stop_cap_or_possible_commit_next_frame(self):
tune = vehicle_tune(str(self.cp.carFingerprint))
sign = {'light': False, 'sign': True, 'horizon_m': 40.}
self.owner.plan = self.owner.policy.step(stop_frame(0, **sign), tune)
self.assertIsNone(self.owner.plan.speed_ceiling_mps)
self.assertFalse(wheel_override_blocked(self.owner, None))
self.owner.plan = self.owner.policy.step(stop_frame(1, light=False, resume_requested=True), tune)
self.assertGreater(self.owner.policy.timer, 0.)
self.assertEqual(self.owner.policy.override_until_ns, 0)
self.assertFalse(wheel_override_blocked(self.owner, None))
self.owner.reset()
for tick in range(4):
self.owner.plan = self.owner.policy.step(stop_frame(tick, **sign), tune)
self.assertIsNone(self.owner.plan.speed_ceiling_mps)
self.assertTrue(wheel_override_blocked(self.owner, None))
self.owner.policy.step(stop_frame(4, resume_requested=True, **sign), tune)
self.assertGreater(self.owner.policy.override_until_ns, 0)
self.owner.reset()
self.owner.plan = self.owner.policy.step(stop_frame(0), tune)
self.assertFalse(self.owner.policy.can_commit_next_frame)
self.assertIsNotNone(self.owner.plan.speed_ceiling_mps)
self.assertTrue(wheel_override_blocked(self.owner, None))
def test_committed_stop_survives_valid_mode_settings_and_traffic_changes(self): def test_committed_stop_survives_valid_mode_settings_and_traffic_changes(self):
import json import json
from openpilot.starpilot.conditional_mode.policy import ModeChoice from openpilot.starpilot.conditional_mode.policy import ModeChoice
@@ -245,6 +245,48 @@ class TestVoltCc(unittest.TestCase):
self.assertFalse(any(msg[0] in (0x2cb, 0x315, 0x200, 0x3d1) for msg in sent[-1][0])) self.assertFalse(any(msg[0] in (0x2cb, 0x315, 0x200, 0x3d1) for msg in sent[-1][0]))
def test_slc_cap_reaches_cruise_down_without_changing_driver_set(self):
for metric in (False, True):
with self.subTest(metric=metric):
controls, card, ci, packer, sent, base, offset = fixture()
card.is_metric, card.slc_control_enabled, card.slc_source_floor_ns = metric, True, 0
state = messaging.new_message('slcState').slcState
state.enabled, state.sessionId, state.hasCeiling, state.effectiveCap = True, 'drive', True, 45 * .44704
controls.sm.data['slcState'] = state
for flags in (controls.sm.seen, controls.sm.valid, controls.sm.alive):
flags['slcState'] = True
flags['carControl'] = True
command = structs.CarControl(enabled=True, latActive=True, longActive=True)
command.actuators.accel = -1.
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
command.hudControl.setSpeed = 70 * .44704
controls.sm.data['carControl'] = command
controls.sm.logMonoTime['carControl'] = base
by_phase = []
for phase in ('active', 'stale'):
directions = []
for tick in range(100):
now = base + (len(by_phase) * 100 + tick) * 10_000_000
out = ci.update([(now + offset - 2_000_000,
physical_frames(packer, speed=55 * .44704, target_speed=70 * .44704, counter=(tick // 3) % 4))])
self.assertTrue(out.canValid)
out.vCruise = out.vCruiseCluster = 70 * .44704 * 3.6
for name in controls.sm.logMonoTime:
controls.sm.logMonoTime[name] = now - 2_000_000
controls.sm.recv_time[name] = (now - 1_000_000) / 1e9
controls.sm.logMonoTime['slcState'] = state.frameMonoTime = now - (2_000_000 if phase == 'active' else 200_000_000)
with patch('openpilot.selfdrive.car.card.clock_pair_ns', return_value=(now, now + offset)), \
patch('openpilot.selfdrive.car.card.time.monotonic_ns', return_value=now), \
patch('openpilot.selfdrive.car.card.REPLAY', False):
card.controls_update(out, command.as_reader())
directions.extend((data[5] >> 4) & 7 for address, data, _ in sent[-1][0] if address == 0x1e1)
self.assertAlmostEqual(out.vCruise, 70 * .44704 * 3.6, places=4)
self.assertAlmostEqual(command.hudControl.setSpeed, 70 * .44704, places=4)
by_phase.append(directions)
self.assertIn(3, by_phase[0])
self.assertEqual(by_phase[1], [])
self.assertIsNone(ci.CC.volt_cc_speed_ceiling_mps)
def test_actual_card_constructor_subscribes_selected_consumer(self): def test_actual_card_constructor_subscribes_selected_consumer(self):
class Registered(Exception): class Registered(Exception):
pass pass
@@ -86,8 +86,9 @@ class TestPlannerSelection(unittest.TestCase):
imports = [node.module for node in planner.body if isinstance(node, ast.ImportFrom)] imports = [node.module for node in planner.body if isinstance(node, ast.ImportFrom)]
self.assertIn('openpilot.starpilot.longitudinal.upstream.mpc', imports) self.assertIn('openpilot.starpilot.longitudinal.upstream.mpc', imports)
self.assertNotIn('openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc', imports) self.assertNotIn('openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc', imports)
self.assertFalse(any(value and value.startswith('openpilot.starpilot.') and value != self.assertEqual({value for value in imports if value and value.startswith('openpilot.starpilot.')}, {
'openpilot.starpilot.longitudinal.upstream.mpc' for value in imports)) 'openpilot.starpilot.longitudinal.upstream.mpc', 'openpilot.starpilot.longitudinal.cruise_ceiling',
})
if __name__ == '__main__': if __name__ == '__main__':
@@ -60,7 +60,7 @@ class TrafficAccelerationPlannerTests(unittest.TestCase):
self.assertLessEqual(traffic.output_a_target, 0.44 + 1e-8) self.assertLessEqual(traffic.output_a_target, 0.44 + 1e-8)
self.assertLess(traffic.a_cruise, baseline.a_cruise) self.assertLess(traffic.a_cruise, baseline.a_cruise)
def test_soft_saved_traffic_keeps_slc_and_force_decel_braking(self): def test_slc_cap_preserves_soft_traffic_response_and_native_force_decel(self):
target = self.tuning(acceleration=0.6, braking=0.35) target = self.tuning(acceleration=0.6, braking=0.35)
self.assertAlmostEqual(target.acceleration_max, 0.6) self.assertAlmostEqual(target.acceleration_max, 0.6)
self.assertAlmostEqual(target.cruise_brake_magnitude, 0.35) self.assertAlmostEqual(target.cruise_brake_magnitude, 0.35)
@@ -72,14 +72,15 @@ class TrafficAccelerationPlannerTests(unittest.TestCase):
for _ in range(60): for _ in range(60):
sm, _ = messages(force=force) sm, _ = messages(force=force)
sm['carControl'].longActive = True sm['carControl'].longActive = True
baseline.update(sm, cruise_ceiling=ceiling)
traffic.update(sm, cruise_ceiling=ceiling, profile_tuning=target, traffic_mode=True) traffic.update(sm, cruise_ceiling=ceiling, profile_tuning=target, traffic_mode=True)
sm['carState'].vCruise = 15.0 * 3.6
baseline.update(sm, profile_tuning=target, traffic_mode=True)
self.assertEqual(traffic.mpc.solution_status, 0) self.assertEqual(traffic.mpc.solution_status, 0)
self.assertLessEqual(traffic.a_cruise, baseline.a_cruise + 1e-8) self.assertLessEqual(traffic.a_cruise, baseline.a_cruise + 1e-8)
self.assertEqual(traffic.last_cruise_ceiling_status, 'force_decel' if force else 'applied') self.assertEqual(traffic.last_cruise_ceiling_status, 'force_decel' if force else 'applied')
self.assertIsNotNone(traffic.last_profile) self.assertIsNotNone(traffic.last_profile)
self.assertAlmostEqual(traffic.last_profile.cruise_brake_magnitude, 0.35) self.assertAlmostEqual(traffic.last_profile.cruise_brake_magnitude, 0.35)
self.assertLessEqual(traffic.a_cruise, -0.5 + 1e-8) self.assertLessEqual(traffic.a_cruise, (-0.5 if force else -0.35) + 1e-8)
def test_soft_saved_traffic_preserves_lead_and_model_stop_candidates(self): def test_soft_saved_traffic_preserves_lead_and_model_stop_candidates(self):
target = self.tuning(acceleration=0.6, braking=0.5) target = self.tuning(acceleration=0.6, braking=0.5)
@@ -215,8 +216,10 @@ class TrafficAccelerationPlannerTests(unittest.TestCase):
cruise_ceiling=cruise_ceiling, curve_ceiling=curve_ceiling) cruise_ceiling=cruise_ceiling, curve_ceiling=curve_ceiling)
self.assertEqual(planner.mpc.solution_status, 0) self.assertEqual(planner.mpc.solution_status, 0)
self.assertAlmostEqual(planner.output_a_target, baseline.output_a_target, places=5) self.assertAlmostEqual(planner.output_a_target, baseline.output_a_target, places=5)
if case in ('slc', 'curve'): if case == 'curve':
self.assertLessEqual(planner.a_cruise, -0.5 + 1e-8) self.assertLessEqual(planner.a_cruise, -0.5 + 1e-8)
elif case == 'slc':
self.assertLessEqual(planner.a_cruise, -0.42 + 1e-8)
elif case == 'force_decel': elif case == 'force_decel':
self.assertLessEqual(planner.a_cruise, -0.5 + 1e-8) self.assertLessEqual(planner.a_cruise, -0.5 + 1e-8)
elif case == 'model_stop': elif case == 'model_stop':
@@ -23,7 +23,7 @@ class EndLoop(Exception):
class TestUpstreamConditional(unittest.TestCase): class TestUpstreamConditional(unittest.TestCase):
def run_loop(self, *, safe=False, stale=False, clocks=True, replay=False): def run_loop(self, *, safe=False, stale=False, clocks=True, replay=False, show_speed_limits=False):
directory = self.enterContext(tempfile.TemporaryDirectory()) directory = self.enterContext(tempfile.TemporaryDirectory())
params = Params(directory) params = Params(directory)
cp = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC_BOSCH) cp = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC_BOSCH)
@@ -32,6 +32,9 @@ class TestUpstreamConditional(unittest.TestCase):
params.put_bool('UseStarPilotLongitudinalPlanner', False, block=True) params.put_bool('UseStarPilotLongitudinalPlanner', False, block=True)
params.put_bool('SafeMode', safe, block=True) params.put_bool('SafeMode', safe, block=True)
params.put_bool('ExperimentalMode', False, block=True) params.put_bool('ExperimentalMode', False, block=True)
params.put_bool('ShowSpeedLimits', show_speed_limits, block=True)
if show_speed_limits:
params.put('SLCPriority1', 'Dashboard', block=True)
params.put('ConditionalModeConfig', json.loads(encode_preferences(SavedPreferences( params.put('ConditionalModeConfig', json.loads(encode_preferences(SavedPreferences(
mode=ModeChoice.CEM, cem=CEMOptions(speed_mps=20., stop_lights=False, lead=False, slower_lead=False)))), block=True) mode=ModeChoice.CEM, cem=CEMOptions(speed_mps=20., stop_lights=False, lead=False, slower_lead=False)))), block=True)
settings = ConditionalSettingsOwner(params) settings = ConditionalSettingsOwner(params)
@@ -82,6 +85,15 @@ class TestUpstreamConditional(unittest.TestCase):
self.payloads[name] = getattr(messaging.log_from_bytes(event.to_bytes()), name) self.payloads[name] = getattr(messaging.log_from_bytes(event.to_bytes()), name)
if stale: if stale:
self.logMonoTime['modelV2'] -= 1_000_000_000 self.logMonoTime['modelV2'] -= 1_000_000_000
if show_speed_limits:
dashboard = messaging.new_message('slcDashboardObservation', valid=True).slcDashboardObservation
dashboard.carStateLogMonoTime = dashboard.observedMonoTime = stamp
dashboard.validUntilMonoTime = stamp + 100_000_000
dashboard.status, dashboard.speedMps, dashboard.episode = 'valid', 15., 1
dashboard.producerSessionId = 'card'
self.payloads['slcDashboardObservation'] = dashboard
self.logMonoTime['slcDashboardObservation'] = stamp
self.valid['slcDashboardObservation'] = self.alive['slcDashboardObservation'] = True
sm = Scene() sm = Scene()
@@ -133,10 +145,19 @@ class TestUpstreamConditional(unittest.TestCase):
self.assertFalse(any(result.accepted for _, result in results)) self.assertFalse(any(result.accepted for _, result in results))
self.assertFalse(any(str(plan.longitudinalPlanSource) == 'e2e' for plan in plans)) self.assertFalse(any(str(plan.longitudinalPlanSource) == 'e2e' for plan in plans))
def test_cem_and_speed_limit_share_one_status_per_model_frame(self):
results, statuses, plans, subscriptions = self.run_loop(show_speed_limits=True)
self.assertEqual(subscriptions.count('deviceState'), 1)
self.assertEqual(len(statuses), len(plans))
self.assertTrue(any(result.accepted and result.experimental for _, result in results))
self.assertTrue(all(status.slcState.displayOnly and status.slcState.speedLimit == 15. and
status.slcState.conditionalMode.version == 1 for status in statuses))
def test_safe_mode_retains_upstream_without_conditional_transport(self): def test_safe_mode_retains_upstream_without_conditional_transport(self):
results, statuses, plans, subscriptions = self.run_loop(safe=True) results, statuses, plans, subscriptions = self.run_loop(safe=True)
self.assertFalse(results or statuses) self.assertFalse(results or statuses)
self.assertNotIn('deviceState', subscriptions) self.assertNotIn('starpilotRadarState', subscriptions)
self.assertNotIn('starpilotNavigation', subscriptions)
self.assertEqual(len(plans), 100) self.assertEqual(len(plans), 100)
def test_missing_live_clock_does_not_publish_conditional_proposals(self): def test_missing_live_clock_does_not_publish_conditional_proposals(self):
@@ -2,11 +2,15 @@
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
import unittest import unittest
from unittest.mock import patch from unittest.mock import Mock, patch
import numpy as np import numpy as np
from openpilot.cereal import log import pytest
from openpilot.cereal import log, messaging
from openpilot.common.params import Params
from openpilot.selfdrive.controls import plannerd as starpilot_plannerd
from openpilot.starpilot.longitudinal.upstream import mpc, planner, plannerd from openpilot.starpilot.longitudinal.upstream import mpc, planner, plannerd
from openpilot.starpilot.speed_limits.tests import test_runtime_replay as replay
class Solver: class Solver:
@@ -51,9 +55,9 @@ class TestUpstreamPlanner(unittest.TestCase):
self.assertEqual(vars(cp), before) self.assertEqual(vars(cp), before)
self.assertFalse(hasattr(stock, 'profile_tuning')) self.assertFalse(hasattr(stock, 'profile_tuning'))
def test_upstream_process_constructs_only_native_publishers_and_planner(self): def test_upstream_process_without_slc_transport_uses_only_native_services(self):
calls = [] calls = []
cp = SimpleNamespace(brand='honda', openpilotLongitudinalControl=True) cp = SimpleNamespace(brand='honda', openpilotLongitudinalControl=True, passive=True)
class SM: class SM:
def update(self): def update(self):
raise InterruptedError('bounded end of mocked loop') raise InterruptedError('bounded end of mocked loop')
@@ -61,7 +65,8 @@ class TestUpstreamPlanner(unittest.TestCase):
calls.append(('subscribe', services, kwargs)) calls.append(('subscribe', services, kwargs))
return SM() return SM()
fake_params = SimpleNamespace(get=lambda key, **kwargs: b'CP') fake_params = SimpleNamespace(get=lambda key, **kwargs: b'CP')
with patch.object(plannerd, 'config_realtime_process'), patch.object(plannerd, 'Params', return_value=fake_params), \ with patch.dict('os.environ', {}, clear=True), patch.object(plannerd, 'config_realtime_process'), \
patch.object(plannerd, 'Params', return_value=fake_params), \
patch.object(plannerd.messaging, 'log_from_bytes', return_value=cp), \ patch.object(plannerd.messaging, 'log_from_bytes', return_value=cp), \
patch.object(plannerd, 'LongitudinalPlanner', side_effect=lambda cp: calls.append(('planner', cp))), \ patch.object(plannerd, 'LongitudinalPlanner', side_effect=lambda cp: calls.append(('planner', cp))), \
patch.object(plannerd, 'LaneDepartureWarning', return_value=object()), \ patch.object(plannerd, 'LaneDepartureWarning', return_value=object()), \
@@ -77,5 +82,87 @@ class TestUpstreamPlanner(unittest.TestCase):
self.assertEqual(Path(plannerd.__file__).resolve(), (root / 'plannerd.py').resolve()) self.assertEqual(Path(plannerd.__file__).resolve(), (root / 'plannerd.py').resolve())
@pytest.mark.parametrize('choice', ['wheel', 'screen', 'stock_cruise'])
def test_upstream_planner_applies_confirmed_slc_with_op_long(tmp_path, monkeypatch, choice):
fixture = replay.RuntimeReplayTests()
fixture.setUp()
cp, sm = fixture.cp, fixture.sm
cp.openpilotLongitudinalControl = choice != 'stock_cruise'
sm['slcDashboardObservation'].speedMps = 15.
sm.data['deviceState'] = messaging.new_message('deviceState').deviceState
sm.valid['deviceState'] = sm.alive['deviceState'] = False
params = Params(str(tmp_path))
params.put('CarParams', cp.to_bytes(), block=True)
params.put_bool('UseStarPilotLongitudinalPlanner', False, block=True)
params.put_bool('SpeedLimitController', True, block=True)
params.put('SLCPriority1', 'Dashboard', block=True)
params.put('SLCConfirmation', 1, block=True)
publisher = Mock()
subscriber = Mock(return_value=sm)
outputs = []
events = {}
start = 2_000_000_000
class EndLoop(Exception):
pass
def update():
sm.frame = len(outputs) + 1
if sm.frame == 3:
raise EndLoop
sm.advance(start + (sm.frame - 1) * 50_000_000)
if sm.frame != 2 or choice == 'stock_cruise':
return
shown = outputs[0].slcState
assert shown.hasPending and not shown.hasCeiling
service = 'slcCruiseEvent' if choice == 'wheel' else 'slcAction'
event = messaging.new_message(service, valid=True)
event.logMonoTime = sm.logMonoTime['modelV2']
action = getattr(event, service)
action.sessionId, action.decisionId, action.presentationId = shown.sessionId, shown.decisionId, shown.presentationId
if choice == 'wheel':
action.kind, action.button = 'confirmationAccept', 'accel'
action.eventId, action.producerSessionId, action.observedMonoTime = 1, 'card-producer', event.logMonoTime
else:
action.kind, action.sequenceId = 'accept', 1
events[service] = event
def send(service, message):
if service == 'slcState':
outputs.append(message)
sm.all_checks = lambda services=None: True
monkeypatch.setattr(sm, 'update', update)
monkeypatch.setenv('REPLAY', '1')
monkeypatch.delenv('SLC_REPLAY_RUNTIME', raising=False)
monkeypatch.setattr(starpilot_plannerd, 'Params', lambda: params)
monkeypatch.setattr(plannerd, 'Params', lambda: params)
monkeypatch.setattr(plannerd, 'config_realtime_process', Mock())
monkeypatch.setattr(plannerd, 'LaneDepartureWarning', Mock(return_value=Mock(left=False, right=False)))
monkeypatch.setattr(messaging, 'SubMaster', subscriber)
monkeypatch.setattr(messaging, 'PubMaster', Mock(return_value=publisher))
monkeypatch.setattr(messaging, 'sub_sock', lambda service, **kwargs: service)
monkeypatch.setattr(messaging, 'recv_one_or_none', lambda service: events.pop(service, None))
publisher.send.side_effect = send
cruise = Mock(wraps=planner.get_cruise_accel)
monkeypatch.setattr(planner, 'get_cruise_accel', cruise)
with pytest.raises(EndLoop):
starpilot_plannerd.main()
assert 'slcDashboardObservation' in subscriber.call_args.kwargs['ignore_valid']
assert cruise.call_args_list[0].args[1] == pytest.approx(100. / 3.6)
assert sm['carState'].vCruise == 100.
state = outputs[1].slcState
if choice == 'stock_cruise':
assert state.displayOnly and not state.hasPending and not state.hasCeiling
assert cruise.call_args.args[1] == pytest.approx(100. / 3.6)
else:
assert state.hasCeiling and state.actionStatus == 'accept'
assert cruise.call_args.args[1] == 15.
assert params.get('SLCQualifiedHistory')['speed_mps'] == 15.
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
@@ -14,6 +14,7 @@ from openpilot.starpilot.longitudinal.upstream.mpc import T_IDXS as T_IDXS_MPC
from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan, should_stop from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan, should_stop
from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET
from openpilot.common.swaglog import cloudlog from openpilot.common.swaglog import cloudlog
from openpilot.starpilot.longitudinal.cruise_ceiling import select_cruise_ceiling
A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6] A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6]
A_CRUISE_MAX_BP = [0., 10.0, 25., 40.] A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
@@ -70,7 +71,7 @@ class LongitudinalPlanner:
self.a_desired_trajectory = np.zeros(CONTROL_N) self.a_desired_trajectory = np.zeros(CONTROL_N)
self.j_desired_trajectory = np.zeros(CONTROL_N) self.j_desired_trajectory = np.zeros(CONTROL_N)
def update(self, sm): def update(self, sm, *, cruise_ceiling=None):
if len(sm['carControl'].orientationNED) == 3: if len(sm['carControl'].orientationNED) == 3:
accel_coast = get_coast_accel(sm['carControl'].orientationNED[1]) accel_coast = get_coast_accel(sm['carControl'].orientationNED[1])
else: else:
@@ -79,11 +80,17 @@ class LongitudinalPlanner:
v_ego = sm['carState'].vEgo v_ego = sm['carState'].vEgo
v_cruise_kph = min(sm['carState'].vCruise, V_CRUISE_MAX) v_cruise_kph = min(sm['carState'].vCruise, V_CRUISE_MAX)
v_cruise = v_cruise_kph * CV.KPH_TO_MS v_cruise = v_cruise_kph * CV.KPH_TO_MS
long_control_off = sm['controlsState'].longControlState == LongCtrlState.off
ceiling = select_cruise_ceiling(
cruise_ceiling, driver_v_cruise_kph=sm['carState'].vCruise, driver_cruise_mps=v_cruise,
system_long_available=self.CP.openpilotLongitudinalControl, long_control_active=not long_control_off,
selfdrive_enabled=sm['selfdriveState'].enabled, force_decel=sm['controlsState'].forceDecel,
)
if ceiling.effective_mps is not None:
v_cruise = ceiling.effective_mps
if sm['controlsState'].forceDecel: if sm['controlsState'].forceDecel:
v_cruise = 0.0 v_cruise = 0.0
long_control_off = sm['controlsState'].longControlState == LongCtrlState.off
# Reset current state when not engaged, or user is controlling the speed # Reset current state when not engaged, or user is controlling the speed
reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['selfdriveState'].enabled reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['selfdriveState'].enabled
# PCM cruise speed may be updated a few cycles later, check if initialized # PCM cruise speed may be updated a few cycles later, check if initialized
@@ -1,5 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import time
from collections import deque from collections import deque
from opendbc.car.structs import car from opendbc.car.structs import car
@@ -11,7 +12,11 @@ from openpilot.selfdrive.controls.plannerd import current_manual_event, current_
from openpilot.starpilot.conditional_mode.planner_host import ConditionalPlannerHost from openpilot.starpilot.conditional_mode.planner_host import ConditionalPlannerHost
from openpilot.starpilot.conditional_mode.projection import paired_clocks_ns from openpilot.starpilot.conditional_mode.projection import paired_clocks_ns
from openpilot.starpilot.feature_runtime import enabled as feature_enabled from openpilot.starpilot.feature_runtime import enabled as feature_enabled
from openpilot.starpilot.feature_runtime import slc_transport_capable
from openpilot.starpilot.longitudinal.upstream.planner import LongitudinalPlanner from openpilot.starpilot.longitudinal.upstream.planner import LongitudinalPlanner
from openpilot.starpilot.speed_limits.planner_host import (
SLC_ACTIONS, SLC_CRUISE_EVENTS, SavedSlcLifecycle, action_from_message, cruise_event_from_message, receive_slc_events,
)
import openpilot.cereal.messaging as messaging import openpilot.cereal.messaging as messaging
@@ -25,50 +30,76 @@ def main():
ldw = LaneDepartureWarning() ldw = LaneDepartureWarning()
longitudinal_planner = LongitudinalPlanner(CP) longitudinal_planner = LongitudinalPlanner(CP)
replay = 'REPLAY' in os.environ
conditional = ConditionalPlannerHost(params) if feature_enabled(params, CP, 'conditional', os.environ) else None conditional = ConditionalPlannerHost(params) if feature_enabled(params, CP, 'conditional', os.environ) else None
slc = SavedSlcLifecycle(params, CP, os.environ) if slc_transport_capable(CP, os.environ) else None
native_inputs = ['carControl', 'carState', 'controlsState', 'vehicleParameters', 'radarState', 'modelV2', 'selfdriveState'] native_inputs = ['carControl', 'carState', 'controlsState', 'vehicleParameters', 'radarState', 'modelV2', 'selfdriveState']
optional = ['deviceState', 'longitudinalPlan', 'starpilotRadarState', 'starpilotNavigation'] if conditional is not None else [] optional = ['deviceState'] if slc is not None or conditional is not None else []
pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance'] + (['slcState'] if conditional is not None else [])) if slc is not None:
slc.refresh(0)
optional.extend(slc.source_services())
if conditional is not None:
optional.extend(['longitudinalPlan', 'starpilotRadarState', 'starpilotNavigation'])
pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance'] + (['slcState'] if optional else []))
sm = messaging.SubMaster(native_inputs + optional, poll='modelV2', sm = messaging.SubMaster(native_inputs + optional, poll='modelV2',
ignore_alive=optional, ignore_valid=optional, ignore_avg_freq=optional) ignore_alive=optional, ignore_valid=optional, ignore_avg_freq=optional)
cruise_sock = messaging.sub_sock('slcCruiseEvent', conflate=False) if conditional is not None else None cruise_sock = messaging.sub_sock('slcCruiseEvent', conflate=False) if optional else None
action_sock = messaging.sub_sock('slcAction', conflate=False) if conditional is not None else None action_sock = messaging.sub_sock('slcAction', conflate=False) if optional else None
pending_actions, pending_cruise = deque(maxlen=64), deque(maxlen=64)
pending_manual, pending_ui = deque(maxlen=64), deque(maxlen=64) pending_manual, pending_ui = deque(maxlen=64), deque(maxlen=64)
drive_start_ns = 0 drive_start_ns = 0
try: try:
while True: while True:
if slc is not None and not replay:
slc.refresh(time.monotonic_ns(), pending_actions=pending_actions, pending_cruise=pending_cruise)
sm.update() sm.update()
if sm.updated['modelV2']: if sm.updated['modelV2']:
longitudinal_planner.update(sm) clocks = paired_clocks_ns() if conditional is not None and not replay else None
if conditional is not None and 'REPLAY' not in os.environ: now_ns = int(sm.logMonoTime['modelV2']) if replay else clocks[0] if clocks is not None else time.monotonic_ns()
clocks = paired_clocks_ns() drive_id = (int(sm['deviceState'].startedMonoTime) if optional and sm.valid['deviceState'] and sm.alive['deviceState'] and
if clocks is not None: 0 < sm.logMonoTime['deviceState'] <= now_ns else 0)
now_ns, boot_ns, skew_ns = clocks drive_changed = drive_id > 0 and drive_start_ns > 0 and drive_id != drive_start_ns
drive_id = (int(sm['deviceState'].startedMonoTime) if sm.valid['deviceState'] and sm.alive['deviceState'] and if drive_changed and conditional is not None and not replay:
0 < sm.logMonoTime['deviceState'] <= now_ns else 0) conditional.reset()
if drive_id > 0 and drive_start_ns > 0 and drive_id != drive_start_ns: pending_manual.clear()
conditional.reset() pending_ui.clear()
pending_manual.clear()
pending_ui.clear() if slc is not None or clocks is not None:
for sock, service, kind, pending in ((cruise_sock, 'slcCruiseEvent', 'conditionalMode', pending_manual), if slc is not None and replay:
(action_sock, 'slcAction', 'conditionalModeCycle', pending_ui)): slc.refresh(now_ns, pending_actions=pending_actions, pending_cruise=pending_cruise)
for _ in range(8): for event in receive_slc_events(cruise_sock):
event = messaging.recv_one_or_none(sock) if event.valid:
if event is None: kind = str(event.slcCruiseEvent.kind)
break if slc is not None and kind in SLC_CRUISE_EVENTS:
if event.valid and str(getattr(event, service).kind) == kind: pending_cruise.append(cruise_event_from_message(event))
pending.append(event) elif clocks is not None and kind == 'conditionalMode':
proposal, snapshot = conditional.sample( pending_manual.append(event)
sm, CP, longitudinal_planner, now_mono_ns=now_ns, now_boot_ns=boot_ns, sample_skew_ns=skew_ns, for event in receive_slc_events(action_sock):
drive_id=drive_id, native_plan_valid=bool(sm.all_checks(native_inputs)), if event.valid:
manual_event=current_manual_event(pending_manual, now_ns, int(sm.logMonoTime['carState'])), kind = str(event.slcAction.kind)
ui_event=current_ui_manual_event(pending_ui, now_ns)) if slc is not None and kind in SLC_ACTIONS:
status = conditional.status.attach(None, proposal, snapshot, now_ns=now_ns, drive_id=drive_id, pending_actions.append(action_from_message(event))
model_ns=int(sm.logMonoTime['modelV2']), car_state_ns=int(sm.logMonoTime['carState'])) elif clocks is not None and kind == 'conditionalModeCycle':
pm.send('slcState', status) pending_ui.append(event)
if drive_id > 0:
drive_start_ns = drive_id output = slc.step(sm, now_ns, pending_actions, pending_cruise, drive_changed=drive_changed) if slc is not None else None
ceiling = output.result.ceiling if output is not None else None
status = output.message if output is not None else None
longitudinal_planner.update(sm, cruise_ceiling=ceiling)
if conditional is not None and clocks is not None:
_, boot_ns, skew_ns = clocks
proposal, snapshot = conditional.sample(
sm, CP, longitudinal_planner, now_mono_ns=now_ns, now_boot_ns=boot_ns, sample_skew_ns=skew_ns,
drive_id=drive_id, native_plan_valid=bool(sm.all_checks(native_inputs)),
cruise_ceiling_mps=ceiling.speed_mps if ceiling is not None else None,
manual_event=current_manual_event(pending_manual, now_ns, int(sm.logMonoTime['carState'])),
ui_event=current_ui_manual_event(pending_ui, now_ns))
status = conditional.status.attach(status, proposal, snapshot, now_ns=now_ns, drive_id=drive_id,
model_ns=int(sm.logMonoTime['modelV2']), car_state_ns=int(sm.logMonoTime['carState']))
if status is not None:
pm.send('slcState', status)
drive_start_ns = drive_id or drive_start_ns
longitudinal_planner.publish(sm, pm) longitudinal_planner.publish(sm, pm)
ldw.update(sm.frame, sm['modelV2'], sm['carState'], sm['carControl']) ldw.update(sm.frame, sm['modelV2'], sm['carState'], sm['carControl'])
@@ -7,14 +7,14 @@
"plannerd.py": { "plannerd.py": {
"upstream_path": "openpilot/selfdrive/controls/plannerd.py", "upstream_path": "openpilot/selfdrive/controls/plannerd.py",
"upstream_sha256": "9c1591c78522e0f89794eb7301113fc616ec6ac079e576a3c9f9ebec64bcbfde", "upstream_sha256": "9c1591c78522e0f89794eb7301113fc616ec6ac079e576a3c9f9ebec64bcbfde",
"adapted_sha256": "0af78b0030a2219f3224e28592715a50bc5620a1e644b75c13eeb0cbeeb2afd5", "adapted_sha256": "c0a305cd934673706aa29166ba3b08ae82894b1d7ee41e5348c4b995ee9a4db2",
"adaptation": "Planner/MPC imports redirected; independent existing conditional-mode owner and bounded transport connected outside unchanged upstream planner/MPC arithmetic" "adaptation": "Redirected planner imports and connected independent conditional mode and shared SLC through bounded event transport and a shared status publisher"
}, },
"planner.py": { "planner.py": {
"upstream_path": "openpilot/selfdrive/controls/lib/longitudinal_planner.py", "upstream_path": "openpilot/selfdrive/controls/lib/longitudinal_planner.py",
"upstream_sha256": "d81425700cf7152ef4f617ec1517fb4137fc5af9188047f48b31aff62dc652f4", "upstream_sha256": "d81425700cf7152ef4f617ec1517fb4137fc5af9188047f48b31aff62dc652f4",
"adapted_sha256": "7f79b61e095928100cb1d1d0b5e5e6ee66676d461c2274fc5a542cec2c841e8f", "adapted_sha256": "47967154441baa073e777e9664f3383705ddeaa779da8dc31c3b2909b9ad49b0",
"adaptation": "Only planner/MPC import paths redirected; no arithmetic/state/publisher changes" "adaptation": "Redirected MPC imports and applied the optional, authority-checked SLC cap to the cruise target"
}, },
"mpc.py": { "mpc.py": {
"upstream_path": "openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py", "upstream_path": "openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py",
+4 -5
View File
@@ -218,18 +218,17 @@ def enabled(started: bool, params: Params, CP: car.CarParams) -> bool:
# Selecting Maps owns producer demand directly. Do not rewrite the separate # Selecting Maps owns producer demand directly. Do not rewrite the separate
# diagnostic opt-in, and do not start control inside the Go shadow provider. # diagnostic opt-in, and do not start control inside the Go shadow provider.
from openpilot.starpilot.saved_source import read_saved from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.speed_limits.runtime_settings import LABELS, read_params from openpilot.starpilot.speed_limits.runtime_settings import LABELS, SOURCE_PRIORITY_DEFAULTS, SOURCE_PRIORITY_KEYS, SOURCE_PRIORITY_MAX_BYTES, read_params
from openpilot.starpilot.speed_limits.selection import SelectionMode, Source from openpilot.starpilot.speed_limits.selection import SelectionMode, Source
# Default Vision/Dashboard needs no Maps producer or full settings scan.
# These bounded reads are demand hints only; canonical parsing below owns # These bounded reads are demand hints only; canonical parsing below owns
# the enabled/display state and rejects malformed complete preferences. # the enabled/display state and rejects malformed complete preferences.
labels = [] labels = []
for key in ('SLCPriority1', 'SLCPriority2'): for key, default in zip(SOURCE_PRIORITY_KEYS, SOURCE_PRIORITY_DEFAULTS, strict=True):
raw, readable = read_saved(params, key, 32) raw, readable = read_saved(params, key, SOURCE_PRIORITY_MAX_BYTES)
if not readable: if not readable:
return False return False
try: try:
labels.append(raw.decode('utf-8') if raw is not None else None) labels.append(raw.decode('utf-8') if raw is not None else default)
except UnicodeError: except UnicodeError:
return False return False
if not any(LABELS.get(label) is Source.MAP for label in labels) and labels[0] not in ('Highest', 'Lowest'): if not any(LABELS.get(label) is Source.MAP for label in labels) and labels[0] not in ('Highest', 'Lowest'):
@@ -16,6 +16,7 @@ from openpilot.common.params import Params
from openpilot.starpilot.maps.artifact import elf_arm64_static, source_digest from openpilot.starpilot.maps.artifact import elf_arm64_static, source_digest
from openpilot.starpilot.maps import shadow_lifecycle as shadow from openpilot.starpilot.maps import shadow_lifecycle as shadow
from openpilot.starpilot.maps import package_shadow from openpilot.starpilot.maps import package_shadow
from openpilot.starpilot.speed_limits.runtime_settings import SOURCE_PRIORITY_KEYS
def fake_static_elf() -> bytes: def fake_static_elf() -> bytes:
@@ -35,7 +36,7 @@ class FakeParams(Params):
self.path = path self.path = path
def get_param_path(self, key: str = '') -> str: def get_param_path(self, key: str = '') -> str:
assert key in (shadow.OPT_IN_KEY, 'SLCPriority1', 'SLCPriority2') assert key in (shadow.OPT_IN_KEY, *SOURCE_PRIORITY_KEYS)
return str(self.path if key == shadow.OPT_IN_KEY else self.path.parent / key) return str(self.path if key == shadow.OPT_IN_KEY else self.path.parent / key)
@@ -173,6 +174,7 @@ class TestShadowLifecycle(unittest.TestCase):
path = self.base / 'MapdShadowEnabled' path = self.base / 'MapdShadowEnabled'
params = FakeParams(path) params = FakeParams(path)
cp = FakeCar() cp = FakeCar()
(self.base / 'SLCPriority2').write_bytes(b'Dashboard')
self.assertFalse(shadow.enabled(True, params, cp)) self.assertFalse(shadow.enabled(True, params, cp))
path.write_bytes(b'1') path.write_bytes(b'1')
self.assertTrue(shadow.enabled(True, params, cp)) self.assertTrue(shadow.enabled(True, params, cp))
@@ -196,6 +198,7 @@ class TestShadowLifecycle(unittest.TestCase):
with mock.patch.dict(os.environ, {'PARAMS_ROOT': str(self.base / 'params')}): with mock.patch.dict(os.environ, {'PARAMS_ROOT': str(self.base / 'params')}):
params = Params() params = Params()
self.assertFalse(params.get_default_value(shadow.OPT_IN_KEY)) self.assertFalse(params.get_default_value(shadow.OPT_IN_KEY))
params.put('SLCPriority2', 'Dashboard', block=True)
self.assertFalse(shadow.enabled(True, params, FakeCar())) self.assertFalse(shadow.enabled(True, params, FakeCar()))
params.put_bool(shadow.OPT_IN_KEY, True, block=True) params.put_bool(shadow.OPT_IN_KEY, True, block=True)
self.assertTrue(shadow.enabled(True, params, FakeCar())) self.assertTrue(shadow.enabled(True, params, FakeCar()))
+11 -11
View File
@@ -1,15 +1,15 @@
# Speed-limit composition # Speed-limit composition
`composition.step` joins current source selection, adoption decisions, configured `composition.step` joins source selection, acceptance, offsets and qualified raw/cluster
offsets, selected cruise coordinates and qualified driver intent. It preserves speed pairs into `Result.ceiling`. The planner caps the driver's SET with this value;
validation of sessions, clocks, source observations, current authority and the causal SLC never writes SET. Source, action, session, clock and authority validation remain
action ledger. Malformed or contradictory input cannot authorize a command. at their existing boundaries. Ordinary driver SET changes do not create an SLC bypass.
The resulting accepted adjusted limit is adoption data. Runtime sends it to card The previous accepted limit plus the current offset remains the cap through source
as a bounded set-speed command, retrying a failed application only while the same gaps and later engagements. Validated saved history supplies the same fallback
adoption and expected set speed remain current. `Result.ceiling` is always `None`; SLC does after a restart. It never creates a fresh source observation or accepts a pending
not compose another speed ceiling with the driver's set speed. The planner uses proposal. Current vehicle coordinates and system-longitudinal authority remain
card's published set speed and its ordinary selected braking profile. required. There is no separate SLC override reducer or retained pedal target.
Lead following, curves, stopping and actuator restrictions retain their independent planner paths. Lead following, curves, stopping, cruise profiles and actuator restrictions retain
See the [current controller contract](README.md). their existing owners. See the [controller contract](README.md).
+7 -16
View File
@@ -1,18 +1,9 @@
# Set-speed override # Driver inputs
Only a qualified driver set-speed change can create an SLC override. Either an Ordinary cruise +/- changes the driver's SET ceiling. With **Override speed limit
increase or decrease qualifies when the resulting speed differs from the most with +** enabled, a qualifying physical tap past the adjusted limit also lets cruise
recently applied set speed. Card's qualified application receipt records the use SET. The accelerator override has its own policy. See [SET speed and accelerator](README.md#set-speed-and-accelerator).
rounded value; only a 0.001 m/s transport tolerance applies. The causal ledger
excludes automatic changes, consumed
confirmation presses, duplicated effects and foreign or obsolete contexts.
Override is presentation state; it never adds another planner target. Card's set Source loss uses the previous accepted limit plus the current offset, up to SET.
speed remains the sole cruise target. The widget crosses out its latest source That remembered limit survives re-engagement and restarts; applying it still needs
limit while override is active. A new limit is adopted immediately in automatic mode current vehicle coordinates and system-longitudinal authority. See [README](README.md).
or follows the ten-second manual confirmation policy. Acceptance clears the old override. Returning
the selected speed to the adopted adjusted limit also clears it.
Accelerator use neither creates an override nor cancels a preexisting set-speed
choice. Authority transitions still suppress commands and invalidate action origins;
reversed clocks and malformed evidence remain fail-closed. See [README](README.md).
+246 -135
View File
@@ -1,62 +1,83 @@
# Speed Limit Controller # Speed Limit Controller
SLC uses the ordinary cruise set speed as its only vehicle-speed target. A qualified SLC supplies a speed-limit cap beneath the driver's cruise SET. The planner uses
limit from the selected Dashboard, Maps, or Vision source is an input to adoption. the lower of SET and the accepted limit plus its configured offset, converted into
Acceptance applies the configured offset within the existing 8–145 km/h cruise physical-speed coordinates once. Accepting a limit never rewrites SET. Native PCM
bounds and sends a qualified command to card, cruise owns its setpoint; non-PCM software cruise and the dedicated Subaru software
which owns `vCruise` and `vCruiseCluster`. SLC supplies no separate planner ceiling. cruise mode retain their existing owners. Automatic SLC requires system longitudinal
Lead, curve, stop and actuator safety constraints retain their existing owners. control. Lead, curve, stop and actuator safety constraints retain their existing owners.
SLC works with either the StarPilot or upstream longitudinal planner.
## New limits and adoption ## New limits and adoption
On SET or RES engagement, a currently qualified limit from the selected source **Match Speed Limit on Engage** is Off by default. When enabled, a new software SET
initializes SET with its existing offset and mph/km/h rounding, even with Automatic engagement uses the SLC limit plus its offset. A limit accepted in this runtime
adoption off. Sources keep updating while disengaged. This explicit adoption clears session remains available during a source gap. Restored history from a previous
the matching prompt, decline or set-speed override; later limits keep the normal drive or runtime restart never initializes SET; without an eligible limit, ordinary
confirmation policy. Without a qualified current limit, RESUME restores the previous SET initialization uses current vehicle speed or the configured initial minimum,
SET and normal SET initialization applies. An early Maps proposal does not replace whichever is higher. A fresh SET can adopt the qualified current limit over one accepted
the current road's limit at engagement. Toyota still requires native cruise capacity earlier in this drive when both the posted limit and the offset-adjusted target
and release approval before applying the target. are lower. This applies after an earlier timeout or explicit decline. Otherwise,
a different reading leaves the same-drive accepted limit as the SET target.
An accepted early Maps preview applies to the SLC ceiling only. In that case,
a new SET uses the qualified current road limit when available, or ordinary
SET initialization if only the preview is available.
RES restores the previous SET when one exists. Factory cruise keeps its own SET.
A different numeric limit from the selected source starts a new decision, including A different numeric limit from the selected source can start a new decision, including
while a set-speed override is active. A source/road identity change at the same after the driver changes SET. A source or road identity change at the same numeric
numeric limit does not start another decision. A decline remains effective across limit does not start another decision. The most recent decline survives source
a source gap or same-value provider change; a later different limit starts a new gaps and other readings until a different limit is adopted or another limit is
window, including when an earlier numeric limit returns. declined. The sign continues to show the road reading.
A different provider proposing a different numeric limit must remain the proposed A qualified limit from a different provider enters the same confirmation or automatic
replacement for two seconds before confirmation or automatic adoption. A competing adoption flow immediately, without an extra source-switch delay.
qualified reading cancels that check; missing readings do not restart it. Adoption
still requires fresh evidence at the end. Same-provider limit changes, explicit
driver adoption and latched early Maps proposals keep their existing timing.
While StarPilot owns speed control, a proposed limit whose adjusted, rounded target A proposed adjusted limit matching both displayed SET values is recorded without
already matches both current SET values is recorded without another confirmation another confirmation. The comparison uses the existing mph/km/h display rounding,
or cruise command. The comparison uses the same mph/km/h rounding as Card, not not actual traveling speed. A presented Accept or Decline takes priority. An
actual traveling speed. A presented Accept or Decline takes priority, and a decline expired confirmation remains declined during ordinary SET adjustments. Unit
remains effective for that proposal. If SET reaches the target during a prompt, changes renew pending actions while preserving accepted limits, declines, SET
the prompt closes without changing speed. An earlier command must first settle, and the active physical-speed cap.
and SET must be observed after its receipt or expiry, before alignment is trusted.
Received-limit memory still manages proposal changes and declined choices.
An expired confirmation stays declined even if SET now matches. Changing only
display units renews pending actions while preserving accepted limits, declines, manual
overrides and the already applied SET.
With Automatic adoption on, qualified new limits are adopted immediately. With **Confirm limits** set to **Off**, qualified new limits are adopted immediately.
With it off, the stationary confirmation card gives two gentle purple pulses **Both**, **Higher only**, and **Lower only** ask relative to the previous
accepted posted limit. An unselected direction is automatic.
Without a previous limit, any manual policy asks for the first one unless it
already matches SET.
The stationary New Limit caption gives two gentle pulses
(700 ms each, separated by 200 ms), then rests until the 3.2-second cycle repeats. (700 ms each, separated by 200 ms), then rests until the 3.2-second cycle repeats.
Only the lower part of the card pulses; the speed and source remain steady. Only the caption changes color; the speed and source remain steady.
The arrow remains relative to vehicle speed. The arrow remains relative to vehicle speed.
Outside manual confirmation, large UI uses the same US or Vienna sign at 1.25× Outside manual confirmation, large UI uses the same US or Vienna sign at 1.25×
scale beside SET speed. scale beside SET speed.
US signs share a cached antialiased white outline with a transparent interior; Signs and confirmation choices have transparent interiors. Cached sign outlines and
the offset fits inside the fixed sign height on both screens. tight dark glyph edges keep the camera visible without sampling its brightness.
SET keeps its label and value in both profiles. When the displayed road limit
matches the fresh accepted cap actually limiting SET, it gets an IN USE label;
the rectangular sign also turns green.
An applied offset target uses a large LIMIT value with the source reading below.
A held override uses the same rectangular readout labeled OVERRIDE, including in
Vienna mode; the road limit remains readable below it. While the accelerator is
pressed, PEDAL identifies the temporary driver input without claiming a held speed.
Both sign styles identify the displayed source: DASH for Dashboard, OSM for offline Both sign styles identify the displayed source: DASH for Dashboard, OSM for offline
Maps, and VISION for the vision model. Explicit Mapbox readings in historical Maps, and VISION for the vision model. Explicit Mapbox readings in historical
replay use NAV; unidentified sources keep SPEED. Retained readings keep their replay use NAV; unidentified live sources show SPEED. A retained road reading
original source label. shows LAST alongside its source when known. For the same source and speed, the
Both styles place only this source above the number, beside any pending arrow. label clears after 150 ms of live updates. Vision keeps a confirmed sign current
The source and arrow share a centered row; all sign contents use the same geometry after it leaves view while the camera pipeline stays healthy. DASH follows the
current OEM reading, and Maps keeps the current road limit separate from its
upcoming preview. Retained and recovering readings never claim IN USE.
During a new-limit confirmation the applied LIMIT or OVERRIDE stays below SET;
if SET is hidden, that status appears in the confirmation header with a `Now:`
label. The expanded Accept button contains the proposed limit including its offset
and unit; Reject says `new limit`. Source readings and offset arithmetic stay in
the collapsed notice, outside the expanded decision. Accept and Reject retain their original touch
areas and action validation. Green Accept and red Reject outlines contain each
button without filling its interior; pressing strengthens the outline and colors
the label. Disabled choices use muted ink.
Ordinary signs keep the source above the number, beside any pending arrow.
The source and arrow share a centered row; sign contents use the same geometry
on both screens. Small arrows are baked at double resolution and text is aligned on both screens. Small arrows are baked at double resolution and text is aligned
to final pixels for clear native rendering. to final pixels for clear native rendering.
Steering-wheel + accepts and − declines. Tapping the sign opens the same Steering-wheel + accepts and − declines. Tapping the sign opens the same
@@ -65,25 +86,29 @@ while system longitudinal control is engaged, including a temporary accelerator
override. Disengaged and AOL lateral-only modes keep displaying limits without override. Disengaged and AOL lateral-only modes keep displaying limits without
prompting. Losing longitudinal engagement cancels the pending choice without prompting. Losing longitudinal engagement cancels the pending choice without
declining it; re-engaging starts a fresh choice if needed. A pending manual choice declining it; re-engaging starts a fresh choice if needed. A pending manual choice
expires after ten monotonic seconds while engaged, including source gaps. The same expires after thirty monotonic seconds while engaged, including source gaps. The same
decision, card and expanded controls remain during a gap, with Accept disabled and decision, presentation, card and expanded controls remain actionable during a gap.
an unavailable label. Reject still dismisses that decision. Recovery renews the Accept applies that remembered proposal and Reject dismisses it. Recovery of the
action presentation without restarting the decision, deadline or attention cycle. same proposal preserves the interaction, deadline and attention cycle.
Wheel confirmation presses remain consumed during a gap, so they cannot become Wheel confirmation presses remain consumed during a gap, so they cannot become
ordinary SET adjustments. An unavailable Accept is never queued for recovery. ordinary SET adjustments. Acceptance takes effect immediately and is never queued.
Decline and timeout leave set speed unchanged. An action at the exact deadline Decline and timeout leave set speed unchanged. An action captured by the deadline
can still complete its presented decision; a later action cannot accept it. can complete its presented decision within the input freshness window. The prompt
closes at expiry, and an action captured after the deadline cannot accept it.
The existing saved `SLCConfirmation` bit is retained: `0` means Automatic adoption The saved `SLCConfirmation` mode is `0` for Off, `1` for Both, `3` for Higher
on and `1` means off. Both native settings layouts show the inverse as Automatic only, or `4` for Lower only.
adoption. Legacy directional confirmation and override preferences do not change
this confirmation policy.
## Optional early adoption ## Optional early adoption
The existing SLC settings page adds **Adopt limits early**: Off by default, or The existing SLC settings page offers **Adopt higher limits early** and
1–10 whole seconds (`SLCAdvanceSeconds`). It applies to both increases and **Adopt lower limits early**: each is Off by default, or 1–10 whole seconds
decreases from offline Maps. Other sources keep their current-limit behavior. (`SLCAdvanceHigherSeconds` and `SLCAdvanceLowerSeconds`). Direction follows the
posted upcoming limit relative to the current mapped limit, before offsets.
Other sources keep their current-limit behavior.
An ordered source list without Maps ignores map readings and previews. Removing
Maps retires an in-progress preview and returns to the selected sources' normal
adoption and previous-limit fallback rules.
The upcoming Map proposal must win the configured source-selection policy. The upcoming Map proposal must win the configured source-selection policy.
There is no new onroad widget, caption, or countdown. The existing New Limit There is no new onroad widget, caption, or countdown. The existing New Limit
confirmation presents the proposed limit and its own offset; the ordinary sign confirmation presents the proposed limit and its own offset; the ordinary sign
@@ -96,47 +121,69 @@ estimate arrival. A first offer requires motion and active system speed control.
This is approximate timing, not a promise to reach the target speed at the sign. This is approximate timing, not a promise to reach the target speed at the sign.
The first offer latches one boundary encounter. Slowing or stopping does not The first offer latches one boundary encounter. Slowing or stopping does not
retract it or restart the existing ten-second confirmation deadline. Source loss retract it or restart the existing thirty-second confirmation deadline. Source loss
removes authority and retains the pending choice; fresh recovery of the same retains the pending choice and its Accept / Reject interaction; recovery of the same
boundary uses the original deadline and a current presentation. Losing longitudinal boundary uses the original deadline and presentation. Losing longitudinal
engagement cancels an unanswered choice; re-engaging starts a fresh deadline. engagement cancels an unanswered choice; re-engaging starts a fresh deadline.
Decline, expiry, manual override and completed application survive the boundary A fresh preview with a different destination way or limit closes an unanswered
becoming current. prompt, even before the replacement is close enough to offer. Closing a prompt
preserves the rollback point for an earlier applied preview.
Decline, expiry and the matching decision survive the previewed limit becoming current.
An older preview cap ends at arrival if the selected current reading differs.
Changing the driver's SET does not withdraw an accepted early limit.
An unchanged approach limit cannot be offered again solely because the preview An unchanged approach limit cannot be offered again solely because the preview
is lost or disabled. Current-source evidence, command freshness, expected SET, is lost or disabled. Current-source evidence, active system-longitudinal authority and driver-button checks still apply.
driver-button checks and Toyota's native capacity/release checks still apply. A fresh road match that contradicts the preview retires the encounter, even if
Maps knows the road but has no posted speed for it.
A newly selected current Maps limit gets its own decision before the next exit
can be offered, including the first Maps reading of a drive.
The same source-selection policy used to offer a preview can retire it when another
qualified source wins. That approach cannot re-offer the same destination and
limit solely because the winning source disappears or a tile refresh changes the ID.
If the preferred live source matches the accepted preview speed, the cap continues.
Otherwise the previous acceptance is restored and the selected source follows normal
confirmation rules.
The configured adopt wheel action continues to adopt the displayed current limit The configured adopt wheel action continues to adopt the displayed current limit
when no confirmation is pending. when no confirmation is pending.
Timing-only edits preserve the runtime session and driver decisions. Off cancels Timing-only edits preserve the runtime session and driver decisions. Off cancels
unapplied advance work and leaves an applied SET intact; normal current-limit unapplied advance work only for that direction and leaves an applied SLC cap
behavior resumes at the boundary. Offset and unit edits retain their existing intact; normal current-limit behavior resumes at the boundary. Offset and unit edits retain their existing
meaning. A short lower-limit zone can immediately qualify its exit increase; meaning. A short lower-limit zone can immediately qualify its exit increase;
there is no hidden minimum dwell time. GPS uncertainty, missing map data and an there is no hidden minimum dwell time. GPS uncertainty, missing map data and an
unresolved continuation can prevent advance adoption; ordinary current-limit SLC unresolved continuation can prevent advance adoption; ordinary current-limit SLC
remains the fallback. No accepted SET is rolled back just because data vanishes. remains the fallback. An applied cap is retained when source data vanishes during the engagement.
On the wire, `slcState.speedLimit` remains the current selected observation. On the wire, `slcState.speedLimit` remains the current selected observation.
`upcomingSpeedLimit` and `upcomingBoundaryId` identify a qualified early proposal; `upcomingSpeedLimit` and `upcomingBoundaryId` identify a qualified early proposal;
an early `slcCruiseCommand` must carry the same boundary ID. The boundary record early acceptance remains bound to that encounter. The boundary record
is in memory for this runtime session, not a saved decision database. is in memory for this runtime session, not a saved decision database.
Only a finite positive source observation can propose a limit. Missing, stale and Only a finite positive qualified observation can propose a new limit. Missing,
unknown observations stay distinct. Source loss retains an engaged manual choice stale and unknown observations remain distinct. Source loss retains an engaged
until its original deadline and creates no authority to change set speed. Automatic manual choice and its interaction until the original deadline. Only an explicit
adoption retains accepted history and does not reapply an unchanged limit on Accept can adopt that remembered proposal. Missing data uses the previous accepted limit plus the current offset,
recovery. While the publisher remains fresh, the widget retains the latest bounded by SET. A pending or declined new limit cannot replace that remembered value.
received limit, offset and original source with an unavailable status, independently Without a previous accepted limit, ordinary SET remains the target.
of accepted history. Cruise continues using its current SET, including a driver's
manual adjustment. Source loss creates no speed target and cannot select a
different Conditional Experimental or Conditional Chill mode. Normal mode triggers
and live braking safeguards remain with their existing owners.
Previous accepted limit and its legacy Experimental fallback are retired. The previous accepted limit survives disengagement and runtime restarts. The
`SLCFallback` remains registered without a default solely to preserve existing existing `SLCQualifiedHistory` record stores it with format and schema validation;
saved bytes for older versions; current code neither reads nor writes it. restoration retains only the value and source label, never an old source episode
Missing, 0, 1, 2 and malformed old values all use the same behavior above. as fresh evidence. An early preview can cap speed during the drive, but only a
Old Quick Select assignments remain saved but unavailable. qualified current reading can confirm that preview for history. This remembered
value may describe a different road. Current
vehicle coordinates and active system-longitudinal authority are still required
to apply its cap. Disabled SLC and stock longitudinal control apply no cap.
Returning to the already accepted numeric limit clears an obsolete confirmation.
The widget retains the latest received limit, offset and source with an unavailable
status. If the active SLC target differs from the displayed limit with its visible
offset, the steady sign shows both values and labels the active target SLC.
Normal conditional-mode triggers and live braking safeguards retain their
owners; missing limit data cannot select an Experimental or Chill fallback mode.
Previous accepted limit is the fixed fallback. There is no fallback selector or
Experimental fallback. Old Quick Select assignments remain saved but unavailable.
Offsets use only the saved `SLCOffsetSchedule`, with fixed physical speed ranges Offsets use only the saved `SLCOffsetSchedule`, with fixed physical speed ranges
and adjustments. Without a saved schedule, all seven ranges start at zero and and adjustments. Without a saved schedule, all seven ranges start at zero and
@@ -147,42 +194,50 @@ unit changes. There is no separate offset-adoption step.
Converted offsets display as whole mph or km/h, and edits use whole units. Converted offsets display as whole mph or km/h, and edits use whole units.
Unit switches retain the saved precision so repeated conversions do not drift. Unit switches retain the saved precision so repeated conversions do not drift.
Offset-only edits preserve accepted and Offset-only edits preserve accepted and rejected state and renew action identities.
rejected state and renew action identities. A changed offset can update the set A changed offset updates the previous accepted SLC cap, including during source loss.
speed of the accepted current limit; source loss defers this command until that Valid source and confirmation edits also preserve the accepted limit and applied
limit is qualified again. cap while renewing pending actions. Disabling SLC still clears that constraint.
## Set speed and accelerator ## SET speed and accelerator
A qualified manual change to a different set speed marks an override, for increases Cruise + and − change SET. Confirmation presses remain consumed through hold and
and decreases. An X crosses the sign while override is active. Returning to the release and do not also apply a software cruise step. Native PCM button effects remain native;
applied set speed clears it, using card's receipt to account for whole-unit rounding. Adopting StarPilot does not pretend it can suppress the vehicle's own SET adjustment.
a new limit also clears it. Adoption retains the ordinary buttons' 0.1 km/h internal Native standstill RES takes precedence over confirmation.
precision, including for mph targets. New-limit decisions continue during override.
Ordinary software SET adjustments use the saved short-press and held-press intervals Software cruise keeps its saved short/held intervals. PCM vehicles retain their
on every make, including PCM vehicles while SLC owns SET. Toyota uses Swap Toyota native steps, including the Toyota Swap Cruise Steps preference. The dedicated
Cruise Steps for both native cruise and software SET: off selects short 1 / hold 5, Subaru software-cruise mode remains independent of SLC.
and on selects short 5 / hold 1. Other makes use CustomCruise and CustomCruiseLong. The Volt conventional-cruise controller uses the fresh SLC cap beneath SET for its
Confirmation presses and native resume keep their existing meanings; they do not cruise-button speed boundary, with its existing physical-source and timing checks.
also apply an interval step. Toyota's native cruise ceiling still limits software SET.
The accelerator temporarily allows higher vehicle speed without changing set speed **After an accelerator override** defaults to **Hold the speed you reached**. Pressing
or creating an SLC override. Adoption and confirmation can update software set the gas above the accepted limit plus offset lets cruise hold the fastest speed you
speed while accelerator override temporarily suspends actuator output. On release the ordinary planner approaches set speed reach, up to SET. **Use your SET speed** targets SET. **Resume the adjusted limit**
using the currently selected braking profile. Existing lead and stopping constraints returns to the accepted limit plus offset on release. The override clears when cruise disengages,
continue to apply. the adjusted limit catches up, or the driver explicitly accepts or adopts a limit.
Stopping while cruise stays engaged preserves the override.
After an explicit choice, the current accelerator press cannot start another
override. Releasing and pressing again can start one.
SET and the accepted limit are separate from the override. Lead, curve and
stopping constraints still apply.
The onroad screen does not offer a separate button to reapply the displayed limit. **Override speed limit with +** defaults to Off and is available when StarPilot
The configured wheel action to adopt a limit remains available, as do the normal owns SET. A tap must move the displayed SET from at or below the adjusted limit
set-speed buttons and confirmation for a different limit. to above it. Cruise then uses SET until it returns to the adjusted limit, a different
limit is accepted, or engagement ends. A display-unit change or a stop while
cruise stays engaged preserves an active override. Confirmation, Curve Speed and
Force Stop take priority over this gesture.
With SLC enabled and system longitudinal control available, card owns software set The configured wheel action can explicitly adopt the displayed current limit. Once
speed even on PCM vehicles; PCM still owns engagement. Native PCM setpoint changes the planner approves that specific press, card moves software SET to the approved
cannot overwrite an adopted software set speed. When SLC is off, the original PCM adjusted limit while cruise is engaged. A newer SET change cancels the write. If
set-speed path is restored. Stock longitudinal control never gains SLC commands. card misses the approval frame, only SLC acceptance applies. On Hyundai
independent-button cars, cruise MAIN assigned to adopt is no longer also the
physical AOL lateral toggle. The onroad screen adds no new control.
## Source and command qualification ## Source and action qualification
Source selection, registered vehicle capabilities, strict saved-setting decoding, Source selection, registered vehicle capabilities, strict saved-setting decoding,
Dashboard parser freshness, Maps road qualification, and Vision clock/inference Dashboard parser freshness, Maps road qualification, and Vision clock/inference
@@ -192,33 +247,89 @@ sources. See [selection](SELECTION.md), [Maps](MAP_SOURCE.md), and the pinned ca
[model provenance](vision/assets/PROVENANCE.md). [model provenance](vision/assets/PROVENANCE.md).
Vision interprets sign numerals using the existing Metric setting: km/h when on, Vision interprets sign numerals using the existing Metric setting: km/h when on,
mph when off. The producer converts once to m/s for both UI layouts and cruise SET. mph when off. The producer converts once to m/s for both UI layouts and the SLC cap.
Changing Metric clears Vision's retained sign and supporting reads, including Changing Metric clears Vision's retained sign and supporting reads, including
in-flight results and cached heartbeats; fresh evidence must confirm the next limit. in-flight results and cached heartbeats; fresh evidence must confirm the next limit.
The current applied SET remains unchanged by this reset. SET and the current engagement's applied cap remain unchanged by this reset.
Every action binds the current session, decision and presentation. The causal ledger Every action binds the current session, decision and presentation. The causal ledger
keeps consumed confirmation presses out of the ordinary cruise-button path, through keeps consumed confirmation presses out of ordinary software cruise, through held
held repeats and release. Accept and Reject cannot follow a replaced source repeats and release. Accept and Reject cannot follow a replaced source candidate.
candidate, including a replacement at the same numeric speed in the action's Source recovery keeps the presentation for an unchanged proposal and its original deadline.
planner cycle. Such a replacement preserves the decision and its deadline but The planner independently checks longitudinal authority, a valid initialized SET
renews its presentation. Card checks active system-longitudinal authority, command and the numeric cap before applying the lower speed.
and state age, matching presentation and source, expected current set speed, legal
speed bounds, and intervening buttons before applying a command once. Dashboard
commands also match the local OEM episode. Maps and Vision commands bind the fresh
qualified planner presentation. A command receipt distinguishes application from
limit acceptance. Rejected or expired commands may retry with current evidence
while the accepted limit and expected set speed remain current, with no pending
decision or manual override. Applied commands are not repeated.
Declining or timing out a returned limit never revives an earlier adoption command;
the historical adoption remains recorded independently of the new rejection.
Transport changes append to reserved custom messages. `SlcState` retains automatic `SlcState.hasCeiling` and `effectiveCap` report the active physical-speed constraint;
pending metadata at ordinals 51–52 and latest-received display metadata at 53–55. `isLimitingMaxSet` identifies when it is below the driver's ceiling. Observations,
`SlcCruiseCommand` appends its source at 14 and accepted limits and the effective constraint remain separate. The existing custom
a bidirectional adoption kind; historical fields and enum ordinals remain reserved. wire layout and historical command fields remain reserved for compatibility; live
Official vehicle schemas are unchanged. Historical SLC ceiling fields stay empty. SLC no longer publishes or consumes `slcCruiseCommand`. Official vehicle schemas
are unchanged. Shared curve, conditional-mode and controller messages remain intact.
Host tests cover decisions, source validation, commands, cruise buttons, profile ## Numeric comparison investigation
Native replay confirms a source-conversion cause of repeated confirmations. This
is a synthetic reproduction through real cereal packets, source qualification and
the runtime, not a diagnosis of a particular recorded drive.
The offline generator's [`maps.ParseMaxSpeed`](../../../mapd_repo/maps/generate_offline.go)
uses `0.277778 * posted_kph`, while Dashboard decoding and Vision use
`posted_kph * (1 / 3.6)`. The generated tile stores this result as Float64.
`CurrentWay.EffectiveMaxSpeed` reaches `State.MatchedLimitMps` and `mapdOut` as
Float32; the discrepancy survives that conversion. Dashboard and Vision also
publish Float32, so ordinary equivalent floating-point arithmetic often collapses
to an identical wire value instead of causing a new decision.
For the same posted **50 km/h**:
| Reading | Float32 m/s seen by SLC |
| --- | --- |
| Dashboard using `1 / 3.6` | `13.88888931274414` |
| Map using `0.277778` | `13.888899803161621` |
| Difference | `0.00001049041748046875` |
Both display as 50 km/h or 31 mph. Before the repair, switching between these
readings could open another confirmation even though the displayed number agreed.
StarPilot now checks current and upcoming Maps readings and restored Maps history
for the exact legacy Float32 encoding of a whole km/h limit through 250 km/h.
Matches are converted to the standard Float32 value before SLC uses them.
[`test_numeric_decisions.py`](tests/test_numeric_decisions.py) records the
following controls against the actual runtime:
- For 30, 50, 80, 100, 130 and 250 km/h, a switch to the legacy Maps value keeps
the accepted cap without another confirmation in either display-unit mode.
- Over 40 seconds at 20 Hz, switching Dashboard availability every half-second
with the two 50 km/h encodings now preserves one decision and its original
timeout. The same replay created 81 decisions before the repair.
- Equivalent mph arithmetic and a Float64 `nextafter` difference disappear at
the shared Float32 wire boundary and cause no new numerical decision.
- A same-number producer restart renews the presentation and retires an old
press, while keeping the decision and deadline. A plain source gap preserves
the presentation as well and counts toward the original deadline.
- Genuine 1 km/h and 1 mph changes remain decisions. In particular, both 40 and
41 km/h display as 25 mph, so current display rounding is insufficient to
establish that two limits mean the same thing.
A separate arithmetic sweep of integer 4–250 km/h found distinct Float32 values
for every shortened conversion; the largest difference was
`0.00006103515625 m/s`. This measures the current converter formula, not installed
map coverage or onroad prompt frequency. Conditional speed rules call the same
Maps parser. The separate `main.ParseMaxSpeed` helper in `speed_limit.go` has no
callers in the reviewed tree and is not the live producer path identified here.
The reference FrogPilot revision checked on 2026-11-03 was
[`98ac7448`](https://github.com/FrogAi/FrogPilot/blob/98ac7448ab542e9fdff72d1ec4d7de2cd31460be/frogpilot/controls/lib/speed_limit_controller.py).
Its controller and reviewed callers matched the earlier `bb8ffa7` source bytes.
Running its actual decision methods with provider/network work isolated confirmed
that its `< 1 m/s` rule updates the target for conversion noise, real 1 km/h and
real 1–2 mph changes without another confirmation; a 3 mph change asks. At 20 Hz,
the alternating-noise scenario retains its nominal timeout instead of restarting
it. These were decision-function checks, not a complete FrogPilot runtime test.
Repairing the value at SLC input covers existing tiles and saved Maps history.
Source identity and driver-action guards still apply after numeric repair.
Host tests cover decisions, source validation, planner caps, cruise buttons, profile
selection and both UI layouts. Synthetic captures and host tests do not establish selection and both UI layouts. Synthetic captures and host tests do not establish
camera accuracy, device timing under load, or onroad behavior. camera accuracy, device timing under load, or onroad behavior.
@@ -15,15 +15,16 @@ Geographic, producer-episode and session-value identities pass through unchanged
Selection checks their structure but owns no drive session; the acceptance reducer Selection checks their structure but owns no drive session; the acceptance reducer
must verify session-value applicability against its current session before use. must verify session-value applicability against its current session before use.
`SelectionPolicy` has an explicit mode, exactly two primary source slots and an `SelectionPolicy` has an explicit mode, up to three primary source slots and an
online-fallback Boolean. A slot may be empty or repeat another slot. Online is online-fallback Boolean. The default order is Vision, Maps, then Off. The saved
second and third slots can be Off. A slot may repeat another slot. Online is
never a primary slot. This module does not activate or translate preferences. never a primary slot. This module does not activate or translate preferences.
| Mode | Primary candidates | Choice | | Mode | Primary candidates | Choice |
| --- | --- | --- | | --- | --- | --- |
| Ordered | Only the configured slots | First eligible valid observation | | Ordered | Only the configured slots | First eligible valid observation |
| Highest | Dashboard and map; vision only if present in either slot | Highest eligible value | | Highest | Dashboard and map, plus vision if present in a slot | Highest eligible value |
| Lowest | Dashboard and map; vision only if present in either slot | Lowest eligible value | | Lowest | Dashboard and map, plus vision if present in a slot | Lowest eligible value |
Equal extrema choose dashboard, then map, then vision, independent of input map Equal extrema choose dashboard, then map, then vision, independent of input map
iteration order. The minimum eligible limit is explicitly 1 m/s, inclusive. iteration order. The minimum eligible limit is explicitly 1 m/s, inclusive.
@@ -42,14 +43,14 @@ If no eligible alternative exists, the result retains unknown or stale state.
Unknown takes precedence over stale, which takes precedence over absence; the Unknown takes precedence over stale, which takes precedence over absence; the
full per-source statuses remain available. Explicit absence, exclusion below the full per-source statuses remain available. Explicit absence, exclusion below the
minimum or an empty configured source set produces an absent result. Acceptance minimum or an empty configured source set produces an absent result. Acceptance
keeps accepted history but supplies no control target during source loss. uses the previous accepted limit during source loss, without inventing a current observation.
Malformed input produces `invalid_input`, errors and Malformed input produces `invalid_input`, errors and
an unknown observation without selecting a source. an unknown observation without selecting a source.
The tests include composition through the acceptance reducer: accepted 65 mph, The tests include composition through the acceptance reducer: accepted 65 mph,
proposed 45, driver rejection, then source loss and reconnect. Last accepted proposed 45, driver rejection, then source loss and reconnect. Last accepted
history remains 65 for both longitudinal-only and combined authority. Source loss history remains 65 for both longitudinal-only and combined authority. Source loss
does not change the already applied cruise SET or authorize a new command. does not change the driver's cruise SET or accept the rejected proposal.
Lateral-only or stock ownership cannot turn a selected Lateral-only or stock ownership cannot turn a selected
speed into a system longitudinal target. These are speed into a system longitudinal target. These are
deterministic policy tests, not native producer, planner, CAN or vehicle evidence. deterministic policy tests, not native producer, planner, CAN or vehicle evidence.
@@ -9,34 +9,30 @@ contains explicit half-open bands with signed m/s offsets;
it supplies no settings defaults or source freshness policy. A missing band or it supplies no settings defaults or source freshness policy. A missing band or
unavailable target/pair produces `UNAVAILABLE`; malformed values produce unavailable target/pair produces `UNAVAILABLE`; malformed values produce
`INVALID`. `SpeedPair` contains measured cluster speed, which may be below raw `INVALID`. `SpeedPair` contains measured cluster speed, which may be below raw
speed; resolution clamps each delta to `max(cluster - raw, 0)`. A nonvalid speed; resolution clamps each delta to `max(cluster - raw, 0)`. Only a `VALID`
resolution with a context is malformed and triggers the override session-reset resolution supplies a planner coordinate.
contract. Only a `VALID` context may enter `overrides.step(domain=...)`.
Before entering this domain, the runtime floors finite negative ego-speed estimates
to zero when fresh `carState` evidence reports standstill. The speed filter can
undershoot zero after the wheels stop. Negative estimates while moving, nonfinite
values and stale vehicle data remain unavailable; the original messages are unchanged.
A finite negative offset that would make the target nonpositive in cluster or A finite negative offset that would make the target nonpositive in cluster or
planner coordinates is ignored for that limit. The unadjusted accepted limit planner coordinates is ignored for that limit. The unadjusted accepted limit
is used instead; the result stays within the ordinary cruise-speed bounds. is used instead; the result stays within the ordinary cruise-speed bounds.
Malformed schedules still fail validation. Malformed schedules still fail validation.
Call order is acceptance, domain resolution, override reduction, then Call order is acceptance, domain resolution, then
`to_planner_coordinate(context, contribution_raw_mps, basis)`. The reducer `to_planner_coordinate(context)`. The accepted limit plus offset is
compares current selected and retained intent against `accepted raw + offset` in cluster coordinates; subtracting the current ego cluster delta once produces
in cluster coordinates. It keeps retained intent in raw selected-speed units, the planner cap. A nonpositive result supplies no coordinate. The planner compares
even when the current selected value later changes for an unrelated reason. this cap with the independent driver's SET and applies the lower target.
The conversion adds the *current qualified selected cluster delta* to that
retained raw speed. A current pedal contribution uses the current ego cluster
delta. The larger of limit plus offset and override is converted to planner
coordinates by subtracting the ego cluster delta exactly once. A nonpositive
result gives no coordinate. The coordinate validates the composition; it is not
a separate live planner ceiling. Runtime commands use the accepted adjusted
cluster target to update Card's SET speed. See the [controller contract](README.md).
These helpers are pure; the live composition supplies the qualified inputs. Ordinary SET changes do not supply an override contribution. During source loss,
They have no Params access, source freshness policy or vehicle output. Current the previous accepted limit uses the current offset and fresh vehicle coordinates.
SLC overrides come from qualified SET changes. Accelerator use does not create It can be restored from validated saved history, without representing its old
an SLC override; ordinary actuator gating owns the temporary pedal override. source identity as current evidence. Pending and declined proposals cannot replace it.
The tests compose actual acceptance and causal override decisions, including These helpers remain pure and have no Params, source-freshness or vehicle-output
retained raw intent with a changed current selected value, offset changes, ownership. Tests cover units, signed offsets, malformed and missing coordinates,
negative offsets, missing coordinates, and one native planner/MPC case. These source-gap continuation, unchanged SET, authority and the native planner.
are deterministic software contracts, not on-road qualification.
+63 -82
View File
@@ -6,9 +6,7 @@ import math
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from enum import Enum from enum import Enum
CONFIRMATION_NS = 10_000_000_000 CONFIRMATION_NS = 30_000_000_000
SOURCE_SWITCH_NS = 2_000_000_000
MAX_REJECTIONS = 256
class ObservationKind(Enum): class ObservationKind(Enum):
@@ -69,7 +67,7 @@ class Authority:
@property @property
def can_control(self) -> bool: def can_control(self) -> bool:
"""Permission to adopt a software set speed, including accelerator override.""" """Permission to adopt an SLC limit during a system-longitudinal engagement."""
return (self.mode in (Mode.LONGITUDINAL_ONLY, Mode.COMBINED) and return (self.mode in (Mode.LONGITUDINAL_ONLY, Mode.COMBINED) and
self.owner is LongitudinalOwner.SYSTEM and (self.longitudinal_active or self.accelerator_override)) self.owner is LongitudinalOwner.SYSTEM and (self.longitudinal_active or self.accelerator_override))
@@ -92,6 +90,7 @@ class DriverAction:
sequence_id: int sequence_id: int
decision_id: int decision_id: int
kind: ActionKind kind: ActionKind
observed_ns: int | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -131,16 +130,6 @@ class Presentation:
candidate: Candidate candidate: Candidate
@dataclass(frozen=True)
class AdoptionProposal:
session_id: str
action_sequence_id: int
presentation_id: int
accepted: AcceptedLimit
reconciliation_speed_mps: float
clear_override: bool = True
@dataclass(frozen=True) @dataclass(frozen=True)
class State: class State:
session_id: str session_id: str
@@ -148,18 +137,14 @@ class State:
# A historical adoption may match a returned proposal the driver now declines. # A historical adoption may match a returned proposal the driver now declines.
accepted: AcceptedLimit | None = None accepted: AcceptedLimit | None = None
pending: PendingDecision | None = None pending: PendingDecision | None = None
rejected: frozenset[Candidate] = frozenset() rejected: Candidate | None = None
last_timestamp_ns: int | None = None last_timestamp_ns: int | None = None
timer_running: bool = False timer_running: bool = False
last_action_sequence: int = -1 last_action_sequence: int = -1
next_decision_id: int = 1 next_decision_id: int = 1
rejection_capacity_exhausted: bool = False
presentation: Presentation | None = None presentation: Presentation | None = None
next_presentation_id: int = 1 next_presentation_id: int = 1
received_speed_mps: float | None = None received_speed_mps: float | None = None
received_source: str | None = None
switch_candidate: Candidate | None = None
switch_started_ns: int | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -172,7 +157,6 @@ class Decision:
action_receipt: ActionReceipt | None = None action_receipt: ActionReceipt | None = None
errors: tuple[str, ...] = () errors: tuple[str, ...] = ()
adoption_receipt: ActionReceipt | None = None adoption_receipt: ActionReceipt | None = None
adoption: AdoptionProposal | None = None
authority: Authority | None = None authority: Authority | None = None
policy: Policy | None = None policy: Policy | None = None
@@ -260,21 +244,12 @@ def _state_errors(state: State) -> list[str]:
errors.append("invalid state clock") errors.append("invalid state clock")
if state.received_speed_mps is not None and not _speed_valid(state.received_speed_mps): if state.received_speed_mps is not None and not _speed_valid(state.received_speed_mps):
errors.append("invalid received speed") errors.append("invalid received speed")
if state.received_source is not None and not _token(state.received_source):
errors.append("invalid received source")
if state.switch_candidate is not None:
if (not _candidate_valid(state.switch_candidate, state.session_id) or state.switch_started_ns is None or not _integer(state.switch_started_ns) or
state.last_timestamp_ns is None or state.switch_started_ns > state.last_timestamp_ns):
errors.append("invalid source switch")
elif state.switch_started_ns is not None:
errors.append("source switch lacks candidate")
if not _integer(state.last_action_sequence, -1) or not _integer(state.next_decision_id, 1) or not _integer(state.next_presentation_id, 1): if not _integer(state.last_action_sequence, -1) or not _integer(state.next_decision_id, 1) or not _integer(state.next_presentation_id, 1):
errors.append("invalid state sequence") errors.append("invalid state sequence")
if type(state.timer_running) is not bool or type(state.rejection_capacity_exhausted) is not bool: if type(state.timer_running) is not bool:
errors.append("invalid state flags") errors.append("invalid state flags")
rejections_valid = (type(state.rejected) is frozenset and len(state.rejected) <= MAX_REJECTIONS and rejection_valid = state.rejected is None or _candidate_valid(state.rejected, state.session_id)
all(_candidate_valid(c, state.session_id) for c in state.rejected)) if not rejection_valid:
if not rejections_valid:
errors.append("invalid rejection history") errors.append("invalid rejection history")
if state.pending is not None: if state.pending is not None:
pending = state.pending pending = state.pending
@@ -284,7 +259,7 @@ def _state_errors(state: State) -> list[str]:
pending.candidate.speed_mps != state.received_speed_mps or pending.candidate.speed_mps != state.received_speed_mps or
pending.automatic and state.observation != Observation(ObservationKind.VALID, pending.candidate)): pending.automatic and state.observation != Observation(ObservationKind.VALID, pending.candidate)):
errors.append("invalid pending decision") errors.append("invalid pending decision")
elif rejections_valid and pending.candidate in state.rejected: elif rejection_valid and state.rejected is not None and pending.candidate.speed_mps == state.rejected.speed_mps:
errors.append("pending candidate is already rejected") errors.append("pending candidate is already rejected")
if state.timer_running and (state.pending is None or state.last_timestamp_ns is None): if state.timer_running and (state.pending is None or state.last_timestamp_ns is None):
errors.append("timer lacks pending decision or clock") errors.append("timer lacks pending decision or clock")
@@ -293,7 +268,10 @@ def _state_errors(state: State) -> list[str]:
if (not isinstance(shown, Presentation) or not _integer(shown.presentation_id, 1) or if (not isinstance(shown, Presentation) or not _integer(shown.presentation_id, 1) or
not _integer(state.next_presentation_id, 1) or shown.presentation_id >= state.next_presentation_id or not _integer(state.next_presentation_id, 1) or shown.presentation_id >= state.next_presentation_id or
not _candidate_valid(shown.candidate, state.session_id) or state.last_timestamp_ns is None or not _candidate_valid(shown.candidate, state.session_id) or state.last_timestamp_ns is None or
state.observation != Observation(ObservationKind.VALID, shown.candidate)): state.observation != Observation(ObservationKind.VALID, shown.candidate) and not (
isinstance(state.pending, PendingDecision) and not state.pending.automatic and
state.pending.candidate == shown.candidate and isinstance(state.observation, Observation) and
state.observation.kind is not ObservationKind.VALID)):
errors.append("invalid presentation context") errors.append("invalid presentation context")
elif isinstance(state.observation, Observation) and state.observation.kind is ObservationKind.VALID: elif isinstance(state.observation, Observation) and state.observation.kind is ObservationKind.VALID:
errors.append("valid observation lacks presentation context") errors.append("valid observation lacks presentation context")
@@ -311,7 +289,13 @@ def new_session(session_id: str, accepted: AcceptedLimit | None = None) -> State
def _action_valid(action: object) -> bool: def _action_valid(action: object) -> bool:
return (isinstance(action, DriverAction) and _token(action.session_id) and _integer(action.sequence_id) and return (isinstance(action, DriverAction) and _token(action.session_id) and _integer(action.sequence_id) and
_integer(action.decision_id, 1) and isinstance(action.kind, ActionKind)) _integer(action.decision_id, 1) and isinstance(action.kind, ActionKind) and
(action.observed_ns is None or _integer(action.observed_ns, 1)))
def _timely(action: DriverAction, pending: PendingDecision, now_ns: int) -> bool:
observed_ns = now_ns if action.observed_ns is None else action.observed_ns
return 0 <= pending.active_elapsed_ns - (now_ns - observed_ns) <= CONFIRMATION_NS
def _adopt_valid(adopt: object) -> bool: def _adopt_valid(adopt: object) -> bool:
@@ -330,6 +314,9 @@ def _acknowledge(state: State, action: DriverAction | AdoptRequest | None) -> tu
def _accept(state: State, candidate: Candidate, now_ns: int) -> tuple[State, AcceptedLimit | None]: def _accept(state: State, candidate: Candidate, now_ns: int) -> tuple[State, AcceptedLimit | None]:
if state.rejected is not None and (state.accepted is None or state.accepted.candidate.speed_mps != candidate.speed_mps or
state.rejected.speed_mps == candidate.speed_mps):
state = replace(state, rejected=None)
if state.accepted is not None and state.accepted.candidate == candidate and state.pending is None: if state.accepted is not None and state.accepted.candidate == candidate and state.pending is None:
return replace(state, pending=None, timer_running=False), None return replace(state, pending=None, timer_running=False), None
accepted = AcceptedLimit(candidate, state.session_id, now_ns) accepted = AcceptedLimit(candidate, state.session_id, now_ns)
@@ -337,14 +324,12 @@ def _accept(state: State, candidate: Candidate, now_ns: int) -> tuple[State, Acc
def _reject(state: State, candidate: Candidate) -> State: def _reject(state: State, candidate: Candidate) -> State:
if candidate not in state.rejected and len(state.rejected) == MAX_REJECTIONS: return replace(state, rejected=candidate, pending=None, timer_running=False)
return replace(state, pending=None, timer_running=False, rejection_capacity_exhausted=True)
return replace(state, rejected=state.rejected | {candidate}, pending=None, timer_running=False)
def step(state: State, observation: Observation, authority: Authority, policy: Policy, *, now_ns: int, def step(state: State, observation: Observation, authority: Authority, policy: Policy, *, now_ns: int,
action: DriverAction | None = None, adopt: AdoptRequest | None = None, set_speed_matches: bool = False, action: DriverAction | None = None, adopt: AdoptRequest | None = None, set_speed_matches: bool = False,
confirmation_started_ns: int | None = None) -> Decision: confirmation_started_ns: int | None = None, confirmation_grace_ns: int = 0) -> Decision:
"""Return a decision, never a cruise command. Invalid input produces no control target.""" """Return a decision, never a cruise command. Invalid input produces no control target."""
state_errors = _state_errors(state) state_errors = _state_errors(state)
if state_errors: if state_errors:
@@ -357,7 +342,7 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
errors.append("invalid policy") errors.append("invalid policy")
if not _integer(now_ns) or (state.last_timestamp_ns is not None and now_ns < state.last_timestamp_ns): if not _integer(now_ns) or (state.last_timestamp_ns is not None and now_ns < state.last_timestamp_ns):
errors.append("invalid or reversed monotonic clock") errors.append("invalid or reversed monotonic clock")
if action is not None and not _action_valid(action): if action is not None and (not _action_valid(action) or action.observed_ns is not None and action.observed_ns > now_ns):
errors.append("invalid driver action") errors.append("invalid driver action")
if adopt is not None and not _adopt_valid(adopt): if adopt is not None and not _adopt_valid(adopt):
errors.append("invalid adopt request") errors.append("invalid adopt request")
@@ -365,6 +350,8 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
errors.append("ambiguous action and adopt request") errors.append("ambiguous action and adopt request")
if type(set_speed_matches) is not bool: if type(set_speed_matches) is not bool:
errors.append("invalid SET alignment") errors.append("invalid SET alignment")
if not _integer(confirmation_grace_ns):
errors.append("invalid confirmation grace")
if confirmation_started_ns is not None and (not _integer(confirmation_started_ns) or not _integer(now_ns) or confirmation_started_ns > now_ns): if confirmation_started_ns is not None and (not _integer(confirmation_started_ns) or not _integer(now_ns) or confirmation_started_ns > now_ns):
errors.append('invalid confirmation start') errors.append('invalid confirmation start')
if errors: if errors:
@@ -387,43 +374,47 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
state = replace(state, pending=replace(old.pending, state = replace(state, pending=replace(old.pending,
active_elapsed_ns=old.pending.active_elapsed_ns + now_ns - old.last_timestamp_ns)) active_elapsed_ns=old.pending.active_elapsed_ns + now_ns - old.last_timestamp_ns))
candidate = observation.candidate candidate = observation.candidate
if candidate is None: if candidate is None and (state.pending is None or state.pending.automatic):
state = replace(state, presentation=None) state = replace(state, presentation=None)
elif old.presentation is None or old.presentation.candidate != candidate: elif candidate is not None and (old.presentation is None or old.presentation.candidate != candidate):
state = replace(state, presentation=Presentation(state.next_presentation_id, candidate), next_presentation_id=state.next_presentation_id + 1) state = replace(state, presentation=Presentation(state.next_presentation_id, candidate), next_presentation_id=state.next_presentation_id + 1)
def finish(basis: str, *, target: float | None = None, history: AcceptedLimit | None = None, def finish(basis: str, *, target: float | None = None, history: AcceptedLimit | None = None) -> Decision:
adoption: AdoptionProposal | None = None) -> Decision: nonlocal state
if observation.kind is not ObservationKind.VALID and state.pending is None:
state = replace(state, presentation=None)
final_receipt = replace(receipt, status=basis) if receipt is not None and receipt.status == "seen" else receipt final_receipt = replace(receipt, status=basis) if receipt is not None and receipt.status == "seen" else receipt
final_adopt_receipt = replace(adopt_receipt, status=basis) if adopt_receipt is not None and adopt_receipt.status == "seen" else adopt_receipt final_adopt_receipt = replace(adopt_receipt, status=basis) if adopt_receipt is not None and adopt_receipt.status == "seen" else adopt_receipt
return Decision(state, candidate, target, basis, history, final_receipt, adoption_receipt=final_adopt_receipt, return Decision(state, candidate, target, basis, history, final_receipt, adoption_receipt=final_adopt_receipt,
adoption=adoption, authority=authority, policy=policy) authority=authority, policy=policy)
def previous_target() -> float | None: def previous_target() -> float | None:
return state.accepted.candidate.speed_mps if state.accepted is not None and authority.can_control else None return state.accepted.candidate.speed_mps if state.accepted is not None and authority.can_control else None
def unavailable(basis: str) -> Decision: def unavailable(basis: str) -> Decision:
nonlocal state, receipt nonlocal state, receipt, candidate
pending = state.pending pending = state.pending
if (pending is None or pending.automatic or not authority.can_control or if (pending is None or pending.automatic or not authority.can_control or
not (policy.confirm_lower or policy.confirm_higher)): not (policy.confirm_lower or policy.confirm_higher)):
state = replace(state, pending=None, timer_running=False) state = replace(state, pending=None, timer_running=False)
return finish(basis) return finish(basis, target=previous_target())
# The driver's choice survives missing evidence; its authority does not. candidate = pending.candidate
# A presented manual choice stays actionable until its original deadline.
if (receipt is not None and receipt.status == 'seen' and action is not None and if (receipt is not None and receipt.status == 'seen' and action is not None and
action.kind is ActionKind.REJECT and action.decision_id == pending.decision_id and action.decision_id == pending.decision_id and old.presentation is not None and
pending.active_elapsed_ns <= CONFIRMATION_NS): old.presentation.candidate == pending.candidate and
receipt = replace(receipt, consumed=True, status='reject') _timely(action, pending, now_ns)):
receipt = replace(receipt, consumed=True, status=action.kind.value)
if action.kind is ActionKind.ACCEPT:
state, history = _accept(state, pending.candidate, now_ns)
return finish('driver_accept', target=pending.candidate.speed_mps, history=history)
state = _reject(state, pending.candidate) state = _reject(state, pending.candidate)
return finish('driver_reject') return finish('driver_reject', target=previous_target())
if pending.active_elapsed_ns >= CONFIRMATION_NS: if pending.active_elapsed_ns >= CONFIRMATION_NS + confirmation_grace_ns:
state = _reject(state, pending.candidate) state = _reject(state, pending.candidate)
return finish('timeout_reject') return finish('timeout_reject', target=previous_target())
return finish(basis) return finish(basis, target=previous_target())
if state.rejection_capacity_exhausted:
state = replace(state, pending=None, timer_running=False)
return finish("session_reset_required")
if policy.display_only: if policy.display_only:
state = replace(state, pending=None, timer_running=False) state = replace(state, pending=None, timer_running=False)
return finish("display_only") return finish("display_only")
@@ -435,41 +426,32 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
explicit_adopt = (adopt is not None and adopt_receipt is not None and adopt_receipt.status == 'seen' and explicit_adopt = (adopt is not None and adopt_receipt is not None and adopt_receipt.status == 'seen' and
old.presentation is not None and old.presentation.presentation_id == adopt.presentation_id and old.presentation is not None and old.presentation.presentation_id == adopt.presentation_id and
old.presentation.candidate == candidate == adopt.candidate) old.presentation.candidate == candidate == adopt.candidate)
if (new_limit and state.received_source is not None and candidate.source != state.received_source and
authority.can_control and not explicit_adopt and confirmation_started_ns is None):
switching = state.switch_candidate
if switching is None or (switching.source, switching.speed_mps) != (candidate.source, candidate.speed_mps):
state = replace(state, switch_candidate=candidate, switch_started_ns=now_ns)
assert state.switch_started_ns is not None
if now_ns - state.switch_started_ns < SOURCE_SWITCH_NS:
return unavailable('source_switch_pending')
state = replace(state, received_source=candidate.source, switch_candidate=None, switch_started_ns=None)
if new_limit: if new_limit:
state = replace(state, received_speed_mps=candidate.speed_mps, pending=None, rejected=frozenset(), timer_running=False) state = replace(state, received_speed_mps=candidate.speed_mps, pending=None, timer_running=False)
if adopt_receipt is not None and adopt_receipt.status == "seen": if adopt_receipt is not None and adopt_receipt.status == "seen":
assert adopt is not None assert adopt is not None
if not explicit_adopt: if not explicit_adopt:
adopt_receipt = replace(adopt_receipt, status="different_presentation") adopt_receipt = replace(adopt_receipt, status="different_presentation")
else: else:
# Recorded for any authority; only an owner of longitudinal control commands a target. # Remember explicit adoption even when longitudinal control is inactive.
state, history = _accept(replace(state, rejected=frozenset(c for c in state.rejected if c.speed_mps != candidate.speed_mps)), candidate, now_ns) state, history = _accept(state, candidate, now_ns)
assert state.accepted is not None assert state.accepted is not None
adopt_receipt = replace(adopt_receipt, consumed=True, status="adopt") adopt_receipt = replace(adopt_receipt, consumed=True, status="adopt")
if not authority.can_control: if not authority.can_control:
return finish("driver_adopt", history=history) return finish("driver_adopt", history=history)
proposal = AdoptionProposal(state.session_id, adopt.sequence_id, adopt.presentation_id, state.accepted, candidate.speed_mps) return finish("driver_adopt", target=candidate.speed_mps, history=history)
return finish("driver_adopt", target=candidate.speed_mps, history=history, adoption=proposal)
if any(rejected.speed_mps == candidate.speed_mps for rejected in state.rejected): if state.rejected is not None and state.rejected.speed_mps == candidate.speed_mps:
state = replace(state, pending=None, timer_running=False) state = replace(state, pending=None, timer_running=False)
return finish("rejected", target=previous_target()) return finish("rejected", target=previous_target())
previous_speed = state.accepted.candidate.speed_mps if state.accepted is not None else None previous_speed = state.accepted.candidate.speed_mps if state.accepted is not None else None
if not new_limit and old.pending is None and candidate.speed_mps == previous_speed: if candidate.speed_mps == previous_speed:
state = replace(state, pending=None, timer_running=False) state = replace(state, pending=None, timer_running=False)
return finish("accepted", target=previous_target()) return finish("accepted", target=previous_target())
confirmation = policy.confirm_higher if previous_speed is None or candidate.speed_mps > previous_speed else ( confirmation = policy.confirm_lower or policy.confirm_higher
policy.confirm_lower if candidate.speed_mps < previous_speed else policy.confirm_lower or policy.confirm_higher) if previous_speed is not None:
confirmation = policy.confirm_higher if candidate.speed_mps > previous_speed else policy.confirm_lower
if confirmation and not authority.can_control: if confirmation and not authority.can_control:
state = replace(state, pending=None, timer_running=False) state = replace(state, pending=None, timer_running=False)
return finish("inactive") return finish("inactive")
@@ -490,8 +472,7 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
target=candidate.speed_mps if authority.can_control else None, history=history) target=candidate.speed_mps if authority.can_control else None, history=history)
return finish("automatic_pending", target=previous_target()) return finish("automatic_pending", target=previous_target())
if receipt is not None and receipt.status == "seen" and pending.active_elapsed_ns <= CONFIRMATION_NS: if receipt is not None and receipt.status == "seen" and action is not None and _timely(action, pending, now_ns):
assert action is not None
if action.decision_id != pending.decision_id: if action.decision_id != pending.decision_id:
receipt = replace(receipt, status="different_decision") receipt = replace(receipt, status="different_decision")
elif old.pending is None or old.pending.decision_id != pending.decision_id: elif old.pending is None or old.pending.decision_id != pending.decision_id:
@@ -506,14 +487,14 @@ def step(state: State, observation: Observation, authority: Authority, policy: P
state, history = _accept(state, candidate, now_ns) state, history = _accept(state, candidate, now_ns)
return finish("driver_accept", target=candidate.speed_mps if authority.can_control else None, history=history) return finish("driver_accept", target=candidate.speed_mps if authority.can_control else None, history=history)
state = _reject(state, candidate) state = _reject(state, candidate)
return finish("driver_reject", target=None if state.rejection_capacity_exhausted else previous_target()) return finish("driver_reject", target=previous_target())
if pending.active_elapsed_ns >= CONFIRMATION_NS: if pending.active_elapsed_ns >= CONFIRMATION_NS + confirmation_grace_ns:
state = _reject(state, candidate) state = _reject(state, candidate)
return finish("timeout_reject", target=None if state.rejection_capacity_exhausted else previous_target()) return finish("timeout_reject", target=previous_target())
# An explicit choice above wins; alignment is approval only while we own speed control. # An explicit choice above wins; alignment is approval only while we own speed control.
if set_speed_matches and authority.can_control: if set_speed_matches and authority.can_control and pending.active_elapsed_ns < CONFIRMATION_NS:
state, history = _accept(state, candidate, now_ns) state, history = _accept(state, candidate, now_ns)
return finish("accepted", target=candidate.speed_mps, history=history) return finish("accepted", target=candidate.speed_mps, history=history)
+109 -20
View File
@@ -13,11 +13,14 @@ class Encounter:
speed_mps: float speed_mps: float
way_id: int way_id: int
started_ns: int | None started_ns: int | None
approach_way_id: int
crossed: bool = False crossed: bool = False
declined: bool = False declined: bool = False
withdrawn: bool = False withdrawn: bool = False
disabled: bool = False disabled: bool = False
accepted_ns: int | None = None accepted_ns: int | None = None
applied_preview: acc.AcceptedLimit | None = None
retired: bool = False
class Advance: class Advance:
@@ -25,6 +28,8 @@ class Advance:
self.encounter: Encounter | None = None self.encounter: Encounter | None = None
self.boundary_id = '' self.boundary_id = ''
self.started_ns: int | None = None self.started_ns: int | None = None
self.retired_cap: acc.AcceptedLimit | None = None
self.retired_pending_speed_mps: float | None = None
def disable(self): def disable(self):
if self.encounter is not None and not self.encounter.crossed: if self.encounter is not None and not self.encounter.crossed:
@@ -32,6 +37,8 @@ class Advance:
def use_current(self, candidate): def use_current(self, candidate):
self.boundary_id, self.started_ns = '', None self.boundary_id, self.started_ns = '', None
self.retired_cap = None
self.retired_pending_speed_mps = None
if self.encounter is not None: if self.encounter is not None:
self.encounter.disabled = True self.encounter.disabled = True
self.encounter.withdrawn = False self.encounter.withdrawn = False
@@ -40,41 +47,114 @@ class Advance:
self.encounter.accepted_ns = None self.encounter.accepted_ns = None
def propose(self, observations, policy, upcoming: Upcoming | None, *, current_way_id: int, def propose(self, observations, policy, upcoming: Upcoming | None, *, current_way_id: int,
seconds: int, speed_mps: float | None, standstill: bool, can_offer: bool, higher_seconds: int, lower_seconds: int, speed_mps: float | None, standstill: bool, can_offer: bool,
confirmation_active: bool, now_ns: int): confirmation_active: bool, now_ns: int, pending: acc.PendingDecision | None, live: acc.Candidate | None,
current_unresolved: bool):
self.boundary_id, self.started_ns = '', None self.boundary_id, self.started_ns = '', None
self.retired_cap = None
self.retired_pending_speed_mps = None
current = observations[sel.Source.MAP].candidate current = observations[sel.Source.MAP].candidate
encounter = self.encounter encounter = self.encounter
pending_preview = (pending is not None and encounter is not None and pending.candidate.source == 'map' and
pending.candidate.speed_mps == encounter.speed_mps)
if encounter is not None and current_way_id:
if not encounter.crossed and current_way_id == encounter.way_id and current is not None:
self.retired_cap = encounter.applied_preview
if encounter.retired or current.speed_mps != encounter.speed_mps:
if pending_preview:
self.retired_pending_speed_mps = encounter.speed_mps
self.encounter = None
return None
encounter.crossed = True
elif not encounter.crossed and (
current_way_id not in (encounter.approach_way_id, encounter.way_id) or
current is not None and not encounter.retired and current.speed_mps not in (encounter.from_mps, encounter.speed_mps)):
if (current is not None and upcoming is not None and upcoming.way_id == encounter.way_id and
upcoming.observation.candidate.speed_mps == encounter.speed_mps and current.speed_mps == encounter.from_mps):
encounter.approach_way_id = current_way_id
else:
self.retired_cap = encounter.applied_preview
if pending_preview:
self.retired_pending_speed_mps = encounter.speed_mps
if current_way_id == encounter.approach_way_id:
encounter.applied_preview = None
encounter.retired = True
else:
self.encounter = None
return None
elif encounter.crossed and current is not None and current.speed_mps != encounter.speed_mps:
self.encounter = encounter = None
held_wins = False
if encounter is not None and not encounter.crossed and (not encounter.retired or encounter.applied_preview is not None):
held = (encounter.applied_preview.candidate if encounter.applied_preview is not None else
pending.candidate if pending_preview and not encounter.retired else None)
if held is not None:
# Compare projected Maps candidates without publishing them as fresh observations.
comparison = dict(observations)
comparison[sel.Source.MAP] = acc.Observation(acc.ObservationKind.VALID, held)
fallback = current is None and live is not None and live.speed_mps != encounter.from_mps
held_wins = not fallback and sel.select_limit(comparison, policy).selected_source is sel.Source.MAP
pending_wins = held_wins
if pending_preview and pending.candidate != held:
comparison[sel.Source.MAP] = acc.Observation(acc.ObservationKind.VALID, pending.candidate)
pending_wins = not fallback and sel.select_limit(comparison, policy).selected_source is sel.Source.MAP
if not held_wins:
self.retired_cap = encounter.applied_preview
encounter.applied_preview = None
if not pending_wins:
encounter.retired = True
if pending_preview and (live is None or live.speed_mps != encounter.speed_mps or held_wins):
self.retired_pending_speed_mps = encounter.speed_mps
if encounter.retired and not held_wins:
return None
if encounter is not None and not encounter.declined and encounter.accepted_ns is None: if encounter is not None and not encounter.declined and encounter.accepted_ns is None:
if not confirmation_active: if not confirmation_active:
encounter.started_ns = None encounter.started_ns = None
elif encounter.started_ns is None: elif encounter.started_ns is None:
encounter.started_ns = now_ns encounter.started_ns = now_ns
if current is None: if current is None:
if encounter is not None and not encounter.crossed: if encounter is not None and not encounter.crossed and (not encounter.retired or held_wins):
return {source: acc.Observation(acc.ObservationKind.UNKNOWN) return {source: acc.Observation(acc.ObservationKind.UNKNOWN)
if observation.candidate is not None and observation.candidate.speed_mps == encounter.from_mps if observation.candidate is not None and observation.candidate.speed_mps == encounter.from_mps
else observation for source, observation in observations.items()} else observation for source, observation in observations.items()}
return None return None
if encounter is not None: # A tile refresh can change the boundary ID for the same road and limit.
if current.speed_mps == encounter.speed_mps and (encounter.crossed or current_way_id == encounter.way_id): replaced = (encounter is not None and upcoming is not None and
encounter.crossed = True (upcoming.way_id != encounter.way_id or upcoming.observation.candidate.speed_mps != encounter.speed_mps))
elif current.speed_mps not in (encounter.from_mps, encounter.speed_mps): previous = encounter if replaced and not encounter.crossed else None
if replaced and not (encounter.crossed or encounter.declined or encounter.disabled or encounter.retired) and encounter.accepted_ns is None:
if pending_preview:
self.retired_pending_speed_mps = encounter.speed_mps
if encounter.applied_preview is None:
self.encounter = encounter = None self.encounter = encounter = None
else:
encounter.started_ns = None
seconds = (higher_seconds if upcoming is not None and upcoming.observation.candidate.speed_mps > current.speed_mps
else lower_seconds)
pending_current = (pending is not None and live is not None and
pending.candidate.source == live.source and pending.candidate.speed_mps == live.speed_mps)
# shortcut: use fresh GPS distance without propagation; revisit only if replay shows material timing error. # shortcut: use fresh GPS distance without propagation; revisit only if replay shows material timing error.
eligible = (can_offer and type(seconds) is int and 0 < seconds <= 10 and not standstill and current_first = current_unresolved and (encounter is None or encounter.crossed)
eligible = (can_offer and not (pending_current or current_first) and type(seconds) is int and 0 < seconds <= 10 and not standstill and
speed_mps is not None and type(speed_mps) in (int, float) and math.isfinite(speed_mps) and speed_mps > 0 and speed_mps is not None and type(speed_mps) in (int, float) and math.isfinite(speed_mps) and speed_mps > 0 and
upcoming is not None and upcoming.distance_m <= speed_mps * seconds) upcoming is not None and upcoming.distance_m <= speed_mps * seconds)
if eligible and (encounter is None or upcoming.boundary_id != encounter.boundary_id): if eligible:
proposed = dict(observations) if encounter is None or replaced and not (encounter.crossed and pending_preview):
proposed[sel.Source.MAP] = upcoming.observation proposed = dict(observations)
if sel.select_limit(proposed, policy).selected_source is sel.Source.MAP: proposed[sel.Source.MAP] = upcoming.observation
assert upcoming.observation.candidate is not None if sel.select_limit(proposed, policy).selected_source is sel.Source.MAP:
encounter = self.encounter = Encounter(upcoming.boundary_id, current.speed_mps, assert upcoming.observation.candidate is not None
upcoming.observation.candidate.speed_mps, upcoming.way_id, now_ns) encounter = self.encounter = Encounter(upcoming.boundary_id, current.speed_mps,
upcoming.observation.candidate.speed_mps, upcoming.way_id, now_ns, current_way_id,
applied_preview=previous.applied_preview if previous is not None else None)
elif not encounter.crossed:
encounter.boundary_id = upcoming.boundary_id
if encounter is None: if encounter is None:
return None return None
if encounter.retired:
return dict.fromkeys(sel.Source, acc.Observation(acc.ObservationKind.UNKNOWN)) if held_wins else None
proposed = dict(observations) proposed = dict(observations)
blocked = encounter.declined or encounter.withdrawn blocked = encounter.declined or encounter.withdrawn
@@ -87,15 +167,20 @@ class Advance:
if not encounter.disabled and sel.select_limit(observations, policy).selected_source is sel.Source.MAP: if not encounter.disabled and sel.select_limit(observations, policy).selected_source is sel.Source.MAP:
self.started_ns = encounter.started_ns self.started_ns = encounter.started_ns
return None return None
elif (seconds > 0 and not blocked and not encounter.disabled and upcoming is not None and elif (not blocked and not encounter.disabled and upcoming is not None and
not (replaced and encounter is previous) and
upcoming.boundary_id == encounter.boundary_id and upcoming.boundary_id == encounter.boundary_id and
upcoming.observation.candidate.speed_mps == encounter.speed_mps): upcoming.observation.candidate.speed_mps == encounter.speed_mps):
proposed[sel.Source.MAP] = upcoming.observation proposed[sel.Source.MAP] = upcoming.observation
if sel.select_limit(proposed, policy).selected_source is sel.Source.MAP: if sel.select_limit(proposed, policy).selected_source is sel.Source.MAP:
self.boundary_id, self.started_ns = encounter.boundary_id, encounter.started_ns self.boundary_id, self.started_ns = encounter.boundary_id, encounter.started_ns
return proposed
else: else:
# Losing a preview must not offer the still-current approach limit again. # Losing a preview must not offer the still-current approach limit again.
proposed[sel.Source.MAP] = acc.Observation(acc.ObservationKind.UNKNOWN) proposed[sel.Source.MAP] = acc.Observation(acc.ObservationKind.UNKNOWN)
if held_wins:
# A losing rival is neither an adoption candidate nor fresh evidence for a held preview.
return dict.fromkeys(sel.Source, acc.Observation(acc.ObservationKind.UNKNOWN))
chosen = sel.select_limit(proposed, policy).observation.candidate chosen = sel.select_limit(proposed, policy).observation.candidate
if not encounter.crossed and chosen is not None and chosen.speed_mps == encounter.from_mps: if not encounter.crossed and chosen is not None and chosen.speed_mps == encounter.from_mps:
encounter.withdrawn = True encounter.withdrawn = True
@@ -110,18 +195,22 @@ class Advance:
if encounter is None or result.acceptance is None: if encounter is None or result.acceptance is None:
return return
decision = result.acceptance decision = result.acceptance
accepted = decision.state.accepted
if encounter.crossed or accepted != encounter.applied_preview:
encounter.applied_preview = None
if encounter.retired:
return
selected = result.selection.observation.candidate if result.selection is not None else None selected = result.selection.observation.candidate if result.selection is not None else None
selected = selected or decision.display_candidate
if selected is not None and selected.speed_mps == encounter.speed_mps and selected.source == 'map': if selected is not None and selected.speed_mps == encounter.speed_mps and selected.source == 'map':
if decision.basis in ('driver_reject', 'timeout_reject', 'rejected'): if decision.basis in ('driver_reject', 'timeout_reject', 'rejected'):
encounter.declined = True encounter.declined = True
accepted = decision.state.accepted
if accepted is not None and accepted.candidate.speed_mps == encounter.speed_mps and decision.state.pending is None: if accepted is not None and accepted.candidate.speed_mps == encounter.speed_mps and decision.state.pending is None:
if encounter.accepted_ns is None: if encounter.accepted_ns is None:
encounter.accepted_ns = accepted.accepted_at_ns encounter.accepted_ns = accepted.accepted_at_ns
if (not encounter.crossed and decision.history_write == accepted and decision.basis != 'driver_adopt'):
encounter.applied_preview = accepted
elif selected is not None and not encounter.crossed and not encounter.disabled: elif selected is not None and not encounter.crossed and not encounter.disabled:
encounter.withdrawn = True encounter.withdrawn = True
if encounter.accepted_ns is not None and result.state.override.persistent_selected_mps is not None:
encounter.withdrawn = True
accepted = decision.state.accepted
if not encounter.disabled and encounter.accepted_ns is not None and accepted is not None and accepted.accepted_at_ns != encounter.accepted_ns: if not encounter.disabled and encounter.accepted_ns is not None and accepted is not None and accepted.accepted_at_ns != encounter.accepted_ns:
encounter.withdrawn = True encounter.withdrawn = True
+95 -64
View File
@@ -1,4 +1,4 @@
"""Pure source, adoption, offset and driver-intent decisions for card's set speed.""" """Qualified SLC decisions supply a planner cap beneath the driver's SET."""
import math import math
from collections.abc import Mapping from collections.abc import Mapping
@@ -7,9 +7,9 @@ from dataclasses import dataclass, replace
from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling
from openpilot.starpilot.speed_limits import acceptance as acc from openpilot.starpilot.speed_limits import acceptance as acc
from openpilot.starpilot.speed_limits import action_arbitration as arb from openpilot.starpilot.speed_limits import action_arbitration as arb
from openpilot.starpilot.speed_limits import overrides as ov
from openpilot.starpilot.speed_limits import selection as sel from openpilot.starpilot.speed_limits import selection as sel
from openpilot.starpilot.speed_limits import speed_domain as sd from openpilot.starpilot.speed_limits import speed_domain as sd
from openpilot.starpilot.speed_limits.runtime_settings import PedalOverride
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -18,7 +18,6 @@ class HostState:
long_control_active: bool long_control_active: bool
selfdrive_enabled: bool selfdrive_enabled: bool
force_decel: bool force_decel: bool
force_stop_active: bool
driver_v_cruise_kph: float driver_v_cruise_kph: float
selected_cluster_kph: float | None selected_cluster_kph: float | None
@@ -39,22 +38,26 @@ class Frame:
adopt: acc.AdoptRequest | None = None adopt: acc.AdoptRequest | None = None
classified_cruise: arb.Result | None = None classified_cruise: arb.Result | None = None
is_metric: bool | None = None is_metric: bool | None = None
set_speed_ready: bool = True
adoption_observations: Mapping[sel.Source, acc.Observation] | None = None adoption_observations: Mapping[sel.Source, acc.Observation] | None = None
confirmation_started_ns: int | None = None confirmation_started_ns: int | None = None
pedal_override: PedalOverride = PedalOverride.OFF
preview_reverted: bool = False
confirmation_grace_ns: int = 0
wheel_override_enabled: bool = False
wheel_override_blocked: bool = False
wheel_override_since_ns: int = 0
@dataclass(frozen=True) @dataclass(frozen=True)
class State: class State:
session_id: str session_id: str
acceptance: acc.State acceptance: acc.State
override: ov.State
control_generation: int = 0
last_now_ns: int | None = None last_now_ns: int | None = None
previous_mode: acc.Mode | None = None
previous_owner: acc.LongitudinalOwner | None = None
was_active_path: bool = False
reset_required: bool = False reset_required: bool = False
pedal_target_mps: float = 0.
pedal_blocked_until_release: bool = False
wheel_override_metric: bool | None = None
wheel_override_since_ns: int = 0
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -63,7 +66,6 @@ class Result:
selection: sel.Selection | None = None selection: sel.Selection | None = None
acceptance: acc.Decision | None = None acceptance: acc.Decision | None = None
domain: sd.DomainResolution | None = None domain: sd.DomainResolution | None = None
override: ov.Decision | None = None
coordinate: sd.PlannerCoordinate | None = None coordinate: sd.PlannerCoordinate | None = None
ceiling: CruiseCeiling | None = None ceiling: CruiseCeiling | None = None
status: str = "none" status: str = "none"
@@ -85,36 +87,33 @@ def _number(value: object, *, positive: bool = False) -> bool:
def _state_valid(state: object) -> bool: def _state_valid(state: object) -> bool:
if not isinstance(state, State) or not isinstance(state.acceptance, acc.State) or not isinstance(state.override, ov.State): if not isinstance(state, State) or not isinstance(state.acceptance, acc.State):
return False return False
if (type(state.session_id) is not str or not state.session_id or state.acceptance.session_id != state.session_id or return (type(state.session_id) is str and bool(state.session_id) and state.acceptance.session_id == state.session_id and
state.override.session_id != state.session_id or not _integer(state.control_generation) or _number(state.pedal_target_mps) and (state.last_now_ns is None or _integer(state.last_now_ns)) and
(state.last_now_ns is not None and not _integer(state.last_now_ns)) or type(state.reset_required) is bool and type(state.pedal_blocked_until_release) is bool and
type(state.was_active_path) is not bool or type(state.reset_required) is not bool): (state.wheel_override_metric is None or type(state.wheel_override_metric) is bool) and
return False _integer(state.wheel_override_since_ns))
if ((state.previous_mode is None) != (state.previous_owner is None) or
(state.previous_mode is not None and not isinstance(state.previous_mode, acc.Mode)) or
(state.previous_owner is not None and not isinstance(state.previous_owner, acc.LongitudinalOwner))):
return False
return True
def _host_valid(host: object) -> bool: def _host_valid(host: object) -> bool:
return (isinstance(host, HostState) and return (isinstance(host, HostState) and
all(type(value) is bool for value in (host.system_long_available, host.long_control_active, all(type(value) is bool for value in (host.system_long_available, host.long_control_active,
host.selfdrive_enabled, host.force_decel, host.force_stop_active)) and host.selfdrive_enabled, host.force_decel)) and
_number(host.driver_v_cruise_kph) and _number(host.driver_v_cruise_kph) and
(host.selected_cluster_kph is None or _number(host.selected_cluster_kph))) (host.selected_cluster_kph is None or _number(host.selected_cluster_kph)))
def _override_evidence(kind: sd.DomainStatus) -> ov.EvidenceKind: def new_session(session_id: str, previous_limit: acc.AcceptedLimit | None = None) -> State:
return {sd.DomainStatus.VALID: ov.EvidenceKind.VALID, if previous_limit is not None:
sd.DomainStatus.ABSENT: ov.EvidenceKind.ABSENT, if not isinstance(previous_limit, acc.AcceptedLimit):
sd.DomainStatus.STALE: ov.EvidenceKind.STALE}.get(kind, ov.EvidenceKind.UNKNOWN) raise ValueError('invalid previous speed limit')
acc.new_session(previous_limit.session_id, previous_limit)
# Remember the value without carrying an old source episode into this session.
def new_session(session_id: str, qualified_history: acc.AcceptedLimit | None = None) -> State: candidate = replace(previous_limit.candidate,
return State(session_id, acc.new_session(session_id, qualified_history), ov.new_session(session_id)) observation_identity=acc.ObservationIdentity(acc.IdentityKind.SESSION_VALUE, session_id=session_id))
previous_limit = acc.AcceptedLimit(candidate, session_id, 0)
return State(session_id, acc.new_session(session_id, previous_limit))
def step(state: State, frame: Frame) -> Result: def step(state: State, frame: Frame) -> Result:
@@ -126,11 +125,14 @@ def step(state: State, frame: Frame) -> Result:
(state.last_now_ns is not None and frame.now_ns < state.last_now_ns) or (state.last_now_ns is not None and frame.now_ns < state.last_now_ns) or
not _host_valid(frame.host) or not acc.authority_is_valid(frame.authority) or not _host_valid(frame.host) or not acc.authority_is_valid(frame.authority) or
not isinstance(frame.acceptance_policy, acc.Policy) or not isinstance(frame.acceptance_policy, acc.Policy) or
not isinstance(frame.pedal_override, PedalOverride) or
not _integer(frame.wheel_override_since_ns) or
any(type(value) is not bool for value in (frame.acceptance_policy.confirm_lower, any(type(value) is not bool for value in (frame.acceptance_policy.confirm_lower,
frame.acceptance_policy.confirm_higher, frame.acceptance_policy.confirm_higher,
frame.acceptance_policy.display_only)) or frame.acceptance_policy.display_only,
frame.wheel_override_enabled, frame.wheel_override_blocked)) or
not isinstance(frame.selected_kind, sd.DomainStatus) or not isinstance(frame.ego_pair, sd.SpeedPair) or not isinstance(frame.selected_kind, sd.DomainStatus) or not isinstance(frame.ego_pair, sd.SpeedPair) or
(frame.is_metric is not None and type(frame.is_metric) is not bool) or type(frame.set_speed_ready) is not bool): (frame.is_metric is not None and type(frame.is_metric) is not bool)):
return Result(replace(state, reset_required=True), status="invalid_frame", errors=("invalid frame or clock",)) return Result(replace(state, reset_required=True), status="invalid_frame", errors=("invalid frame or clock",))
host = frame.host host = frame.host
selected_initialized = host.driver_v_cruise_kph > 0 and host.driver_v_cruise_kph != 255.0 selected_initialized = host.driver_v_cruise_kph > 0 and host.driver_v_cruise_kph != 255.0
@@ -140,13 +142,10 @@ def step(state: State, frame: Frame) -> Result:
frame.authority.accelerator_override and not (host.system_long_available and host.selfdrive_enabled and frame.pedal_pressed is True)): frame.authority.accelerator_override and not (host.system_long_available and host.selfdrive_enabled and frame.pedal_pressed is True)):
return Result(replace(state, last_now_ns=frame.now_ns, reset_required=True), return Result(replace(state, last_now_ns=frame.now_ns, reset_required=True),
status="host_authority_disagreement", errors=("host and system-long authority disagree",)) status="host_authority_disagreement", errors=("host and system-long authority disagree",))
active_path = (frame.authority.can_control and (host_long or frame.authority.accelerator_override) and selected_initialized and engaged_path = (frame.authority.can_control and (host_long or frame.authority.accelerator_override) and
not host.force_decel and not host.force_stop_active and not frame.acceptance_policy.display_only) selected_initialized and not frame.acceptance_policy.display_only)
mode_changed = state.previous_mode is not None and (state.previous_mode != frame.authority.mode or active_path = engaged_path and not host.force_decel
state.previous_owner != frame.authority.owner) base = replace(state, last_now_ns=frame.now_ns, pedal_target_mps=0., wheel_override_metric=None, wheel_override_since_ns=0)
generation = state.control_generation + int(active_path and (not state.was_active_path or mode_changed))
base = replace(state, control_generation=generation, last_now_ns=frame.now_ns,
previous_mode=frame.authority.mode, previous_owner=frame.authority.owner, was_active_path=active_path)
if frame.classified_cruise is not None: if frame.classified_cruise is not None:
classified = frame.classified_cruise classified = frame.classified_cruise
@@ -166,7 +165,7 @@ def step(state: State, frame: Frame) -> Result:
ego = frame.ego_pair ego = frame.ego_pair
candidate = selected.observation.candidate candidate = selected.observation.candidate
matches_set = False matches_set = False
if (active_path and frame.set_speed_ready and candidate is not None and frame.selected_kind is sd.DomainStatus.VALID and if (active_path and candidate is not None and frame.selected_kind is sd.DomainStatus.VALID and
ego.status is sd.DomainStatus.VALID and ego.session_id == state.session_id and ego.timestamp_ns == frame.now_ns and ego.status is sd.DomainStatus.VALID and ego.session_id == state.session_id and ego.timestamp_ns == frame.now_ns and
_number(ego.raw_mps) and _number(ego.cluster_mps)): _number(ego.raw_mps) and _number(ego.cluster_mps)):
assert ego.raw_mps is not None and ego.cluster_mps is not None assert ego.raw_mps is not None and ego.cluster_mps is not None
@@ -176,13 +175,13 @@ def step(state: State, frame: Frame) -> Result:
target, host.driver_v_cruise_kph, host.selected_cluster_kph, frame.is_metric) target, host.driver_v_cruise_kph, host.selected_cluster_kph, frame.is_metric)
acceptance = acc.step(base.acceptance, selected.observation, frame.authority, frame.acceptance_policy, acceptance = acc.step(base.acceptance, selected.observation, frame.authority, frame.acceptance_policy,
now_ns=frame.now_ns, action=frame.action, adopt=frame.adopt, set_speed_matches=matches_set, now_ns=frame.now_ns, action=frame.action, adopt=frame.adopt, set_speed_matches=matches_set,
confirmation_started_ns=frame.confirmation_started_ns) confirmation_started_ns=frame.confirmation_started_ns,
confirmation_grace_ns=frame.confirmation_grace_ns)
base = replace(base, acceptance=acceptance.state) base = replace(base, acceptance=acceptance.state)
if acceptance.errors: if acceptance.errors:
return Result(replace(base, reset_required=True), selected, acceptance, return Result(replace(base, reset_required=True), selected, acceptance,
status="invalid_acceptance", errors=acceptance.errors) status="invalid_acceptance", errors=acceptance.errors)
# The raw selected set speed is derived solely from the actual driver vCruise kph.
if frame.selected_kind is sd.DomainStatus.VALID and selected_initialized and host.selected_cluster_kph is not None: if frame.selected_kind is sd.DomainStatus.VALID and selected_initialized and host.selected_cluster_kph is not None:
pair = sd.selected_pair_from_kph(host.driver_v_cruise_kph / 3.6, host.selected_cluster_kph, pair = sd.selected_pair_from_kph(host.driver_v_cruise_kph / 3.6, host.selected_cluster_kph,
session_id=state.session_id, timestamp_ns=frame.now_ns) session_id=state.session_id, timestamp_ns=frame.now_ns)
@@ -191,30 +190,62 @@ def step(state: State, frame: Frame) -> Result:
else: else:
pair = sd.SpeedPair(sd.DomainStatus.ABSENT) pair = sd.SpeedPair(sd.DomainStatus.ABSENT)
domain = sd.resolve(acceptance, frame.offset_schedule, pair, frame.ego_pair) domain = sd.resolve(acceptance, frame.offset_schedule, pair, frame.ego_pair)
selected_evidence = ov.SelectedEvidence(_override_evidence(pair.status), pair.raw_mps if pair.status is sd.DomainStatus.VALID else None) if domain.status is sd.DomainStatus.INVALID:
pedal_evidence = ov.PedalEvidence(_override_evidence(frame.ego_pair.status), return Result(replace(base, reset_required=True), selected, acceptance, domain,
frame.pedal_pressed if frame.ego_pair.status is sd.DomainStatus.VALID else None, status="invalid_domain", errors=(domain.reason,))
frame.ego_pair.raw_mps if frame.ego_pair.status is sd.DomainStatus.VALID else None) clear_override = frame.preview_reverted or acceptance.basis in ('driver_accept', 'driver_adopt')
change = frame.classified_cruise.change if frame.classified_cruise is not None else None clear_wheel = clear_override or state.acceptance.accepted != acceptance.state.accepted
override = ov.step(base.override, acceptance, frame.authority, frame.acceptance_policy, wheel_metric = state.wheel_override_metric if frame.wheel_override_enabled and not clear_wheel else None
selected_evidence, pedal_evidence, now_ns=frame.now_ns, change=change, domain=domain) previous = 0. if clear_override else state.pedal_target_mps
base = replace(base, override=override.state) pedal_blocked = (state.pedal_blocked_until_release or clear_override) and (
if override.errors or domain.status is sd.DomainStatus.INVALID: frame.pedal_pressed is not False or ego.status is not sd.DomainStatus.VALID)
return Result(replace(base, reset_required=True), selected, acceptance, domain, override, base = replace(base, pedal_blocked_until_release=pedal_blocked)
status="invalid_domain_or_override", errors=override.errors or (domain.reason,))
if not active_path or domain.status is not sd.DomainStatus.VALID: if not active_path or domain.status is not sd.DomainStatus.VALID:
return Result(base, selected, acceptance, domain, override, # Longitudinal output can resume one frame after the driver releases the pedal.
status=acceptance.basis if acceptance.basis == 'source_switch_pending' else 'inactive_or_unavailable') if (system_mode and host.selfdrive_enabled and not engaged_path and selected_initialized and
not (host.force_decel or frame.acceptance_policy.display_only) and
ego.status is sd.DomainStatus.VALID and pair.status is sd.DomainStatus.VALID):
base = replace(base, pedal_target_mps=previous if frame.pedal_override is not PedalOverride.OFF else 0.,
wheel_override_metric=wheel_metric)
return Result(base, selected, acceptance, domain, status='inactive_or_unavailable')
context = domain.context context = domain.context
if (not isinstance(context, sd.DomainContext) or override.state.session_id != state.session_id or assert context is not None
override.state.last_timestamp_ns != frame.now_ns or override.state.accepted_mps != context.accepted_raw_mps or selected_cluster = context.selected_raw_mps + context.selected_delta_mps
override.state.effective_target_mps != context.effective_cluster_mps): if frame.wheel_override_enabled and frame.is_metric is not None:
return Result(replace(base, reset_required=True), selected, acceptance, domain, override, since = 0 if clear_wheel else state.wheel_override_since_ns
status="invalid_join", errors=("override and speed domain mismatch",)) pending = acceptance.state.pending
coordinate = sd.to_planner_coordinate(context, override.contribution_mps, override.basis) ready = (host_long and not frame.pedal_pressed and not frame.wheel_override_blocked and
(pending is None or pending.automatic))
adjusted_limit = context.effective_cluster_mps
change = frame.classified_cruise.change if frame.classified_cruise is not None else None
# A tap belongs to the eligibility interval at button-down, even if SET changes later.
if (wheel_metric is None and ready and since > 0 and frame.wheel_override_since_ns == since and change is not None and
change.disposition is arb.Disposition.DRIVER_INTENT and change.previous_mps is not None and
not sd.set_above_limit(change.previous_mps, adjusted_limit, frame.is_metric)):
wheel_metric = frame.is_metric
# A display-unit edit can round two different speeds to the same number.
if wheel_metric is not None and not sd.set_above_limit(selected_cluster, adjusted_limit, wheel_metric):
wheel_metric = None
base = replace(base, wheel_override_metric=wheel_metric,
wheel_override_since_ns=(since or frame.now_ns) if ready else 0)
if wheel_metric is not None:
coordinate = sd.PlannerCoordinate(None, 'wheel', selected_cluster, context.ego_delta_mps)
return Result(base, selected, acceptance, domain, coordinate, status=acceptance.basis)
pedal_target = 0.
if frame.pedal_override is not PedalOverride.OFF:
ego_cluster = context.ego_raw_mps + context.ego_delta_mps
gas_above_limit = not pedal_blocked and frame.authority.accelerator_override and ego_cluster > context.effective_cluster_mps
if gas_above_limit or previous > context.effective_cluster_mps:
pedal_target = (selected_cluster if frame.pedal_override is PedalOverride.SET_SPEED else
min(selected_cluster, max(previous, ego_cluster if gas_above_limit else 0.)))
if pedal_target <= context.effective_cluster_mps:
pedal_target = 0.
base = replace(base, pedal_target_mps=pedal_target)
coordinate = sd.to_planner_coordinate(context, override_mps=pedal_target)
if coordinate.cap_mps is None: if coordinate.cap_mps is None:
return Result(replace(base, reset_required=True), selected, acceptance, domain, override, coordinate, return Result(replace(base, reset_required=True), selected, acceptance, domain, coordinate,
status="invalid_coordinate", errors=("planner coordinate unavailable",)) status="invalid_coordinate", errors=("planner coordinate unavailable",))
# Adoption changes card's set speed; SLC never supplies a second planner ceiling. return Result(base, selected, acceptance, domain, coordinate,
return Result(base, selected, acceptance, domain, override, coordinate, ceiling=CruiseCeiling(coordinate.cap_mps, frame.authority),
status=acceptance.basis) status=acceptance.basis)
+17 -22
View File
@@ -1,4 +1,4 @@
"""Versioned accepted-limit persistence with explicit identity applicability.""" """Remember the last accepted limit as a fallback, never as fresh source evidence."""
import json import json
import math import math
@@ -6,9 +6,11 @@ import math
from openpilot.cereal import custom from openpilot.cereal import custom
from openpilot.starpilot.schema_cache import schema_fingerprint from openpilot.starpilot.schema_cache import schema_fingerprint
from openpilot.starpilot.speed_limits import acceptance as acc from openpilot.starpilot.speed_limits import acceptance as acc
from openpilot.starpilot.speed_limits.map_observation import repair_legacy_map_speed
FORMAT = "starpilot-slc-accepted" FORMAT = "starpilot-slc-accepted"
VERSION = 1 VERSION = 1
MAX_BYTES = 16_384
def encode(accepted: acc.AcceptedLimit, saved_wall_ns: int) -> str: def encode(accepted: acc.AcceptedLimit, saved_wall_ns: int) -> str:
@@ -24,16 +26,8 @@ def encode(accepted: acc.AcceptedLimit, saved_wall_ns: int) -> str:
"origin_session": accepted.session_id}, sort_keys=True, separators=(",", ":")) "origin_session": accepted.session_id}, sort_keys=True, separators=(",", ":"))
def decode(raw: str | bytes | dict | None, *, session_id: str, current: acc.Observation, def decode(raw: str | bytes | dict | None, *, session_id: str) -> acc.AcceptedLimit | None:
now_wall_ns: int, max_age_ns: int) -> acc.AcceptedLimit | None: if raw is None or type(session_id) is not str or not session_id:
"""Only durable geographic identity can be carried into a new drive.
The caller sets an applicability age from its source contract. Dashboard TSR
producer episodes are drive-local and cannot be restored across a new session.
"""
if raw is None or type(session_id) is not str or not session_id or type(now_wall_ns) is not int or type(max_age_ns) is not int:
return None
if max_age_ns < 0 or now_wall_ns <= 0:
return None return None
try: try:
value = raw if isinstance(raw, dict) else json.loads(raw) value = raw if isinstance(raw, dict) else json.loads(raw)
@@ -41,18 +35,19 @@ def decode(raw: str | bytes | dict | None, *, session_id: str, current: acc.Obse
"speed_mps", "identity_kind", "identity_value", "origin_session"} or "speed_mps", "identity_kind", "identity_value", "origin_session"} or
value["format"] != FORMAT or type(value["version"]) is not int or value["version"] != VERSION or value["format"] != FORMAT or type(value["version"]) is not int or value["version"] != VERSION or
value["source_schema"] != schema_fingerprint(custom.SlcDashboardObservation.schema) or value["source_schema"] != schema_fingerprint(custom.SlcDashboardObservation.schema) or
type(value["saved_wall_ns"]) is not int or value["saved_wall_ns"] > now_wall_ns or type(value["saved_wall_ns"]) is not int or value["saved_wall_ns"] <= 0 or
now_wall_ns - value["saved_wall_ns"] > max_age_ns or value['source'] not in ('dashboard', 'map', 'vision') or
value["identity_kind"] != acc.IdentityKind.GEOGRAPHIC.value or
not isinstance(value["identity_value"], str) or not value["identity_value"] or
not isinstance(value["origin_session"], str) or not value["origin_session"] or not isinstance(value["origin_session"], str) or not value["origin_session"] or
type(value["speed_mps"]) not in (int, float) or not math.isfinite(value["speed_mps"])): type(value["speed_mps"]) not in (int, float) or not math.isfinite(value["speed_mps"])):
return None return None
candidate = acc.Candidate(value["source"], acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value["identity_value"]), kind = acc.IdentityKind(value['identity_kind'])
float(value["speed_mps"])) identity = acc.ObservationIdentity(kind, value['identity_value'],
if (not acc.observation_is_valid(acc.Observation(acc.ObservationKind.VALID, candidate), session_id=session_id) or value['origin_session'] if kind is acc.IdentityKind.SESSION_VALUE else None)
current != acc.Observation(acc.ObservationKind.VALID, candidate)): candidate = acc.Candidate(value['source'], identity, float(value['speed_mps']))
return None acc.new_session(value['origin_session'], acc.AcceptedLimit(candidate, value['origin_session'], 0))
return acc.AcceptedLimit(candidate, session_id, 0) speed = repair_legacy_map_speed(candidate.speed_mps) if candidate.source == 'map' else candidate.speed_mps
except (TypeError, ValueError, OverflowError): remembered = acc.Candidate(candidate.source,
acc.ObservationIdentity(acc.IdentityKind.SESSION_VALUE, session_id=session_id), speed)
return acc.new_session(session_id, acc.AcceptedLimit(remembered, session_id, 0)).accepted
except (TypeError, ValueError, OverflowError, RecursionError):
return None return None
@@ -2,6 +2,7 @@
import hashlib import hashlib
import json import json
import math import math
import struct
from dataclasses import dataclass from dataclasses import dataclass
from openpilot.starpilot.speed_limits import acceptance as acc from openpilot.starpilot.speed_limits import acceptance as acc
@@ -9,6 +10,26 @@ from openpilot.starpilot.speed_limits import map_source as ms
from openpilot.starpilot.speed_limits.map_source import copy_frame as copy_frame from openpilot.starpilot.speed_limits.map_source import copy_frame as copy_frame
_LEGACY_KPH_TO_MPS = .277778
def _float32(value: float) -> float:
return struct.unpack('f', struct.pack('f', value))[0]
_MAX_LEGACY_SPEED = _float32(250 * _LEGACY_KPH_TO_MPS)
def repair_legacy_map_speed(speed_mps: float) -> float:
# shortcut: match the legacy converter through 250 km/h, revisit if higher posted limits need repair.
if not 1 <= speed_mps <= _MAX_LEGACY_SPEED:
return speed_mps
posted_kph = round(speed_mps / _LEGACY_KPH_TO_MPS)
if speed_mps == _float32(posted_kph * _LEGACY_KPH_TO_MPS):
return _float32(posted_kph / 3.6)
return speed_mps
@dataclass(frozen=True) @dataclass(frozen=True)
class Upcoming: class Upcoming:
observation: acc.Observation observation: acc.Observation
@@ -39,25 +60,28 @@ class MapSource:
if evidence.observation.kind is acc.ObservationKind.STALE: if evidence.observation.kind is acc.ObservationKind.STALE:
return evidence.observation return evidence.observation
accepted = self.tracker.diagnostic(now_boot_ns=now_boot_ns).frame accepted = self.tracker.diagnostic(now_boot_ns=now_boot_ns).frame
if (evidence.kind != 'matched_limit_unqualified' or accepted is None or if (evidence.kind not in ('matched_limit_unqualified', 'matched_no_limit_unqualified') or accepted is None or
accepted.way_selection != 'current' or accepted.way_selection != 'current' or
any(type(value) is not str or not 0 < len(value) <= 256 or not value.strip() or any(type(value) is not str or not 0 < len(value) <= 256 or not value.strip() or
any(ord(c) < 32 for c in value) for value in (drive_session, car_fingerprint))): any(ord(c) < 32 for c in value) for value in (drive_session, car_fingerprint))):
# Missing speed metadata, coverage/GPS loss and ambiguous/lookahead ways # Missing speed metadata, coverage/GPS loss and ambiguous/lookahead ways
# are incomplete evidence, not a new limit or regulatory absence. # are incomplete evidence, not a new limit or regulatory absence.
return acc.Observation(acc.ObservationKind.UNKNOWN) return acc.Observation(acc.ObservationKind.UNKNOWN)
self.way_id = accepted.way_id
if evidence.kind == 'matched_no_limit_unqualified':
return evidence.observation
identity = hashlib.sha256(json.dumps((drive_session, car_fingerprint, accepted.producer_session, identity = hashlib.sha256(json.dumps((drive_session, car_fingerprint, accepted.producer_session,
accepted.generation, accepted.source, accepted.way_id), separators=(',', ':')).encode()).hexdigest() accepted.generation, accepted.source, accepted.way_id), separators=(',', ':')).encode()).hexdigest()
self.way_id = accepted.way_id
boundary = accepted.preview_boundary_id boundary = accepted.preview_boundary_id
speed = repair_legacy_map_speed(accepted.speed_mps)
preview_speed = repair_legacy_map_speed(accepted.preview_speed_mps) if type(accepted.preview_speed_mps) is float else 0.
if (type(boundary) is str and len(boundary) == 64 and all(c in '0123456789abcdef' for c in boundary) and if (type(boundary) is str and len(boundary) == 64 and all(c in '0123456789abcdef' for c in boundary) and
type(accepted.preview_speed_mps) is float and math.isfinite(accepted.preview_speed_mps) and math.isfinite(preview_speed) and preview_speed >= 1.0 and abs(preview_speed - speed) > .02 and
accepted.preview_speed_mps >= 1.0 and abs(accepted.preview_speed_mps - accepted.speed_mps) > .02 and
type(accepted.preview_distance_m) is float and math.isfinite(accepted.preview_distance_m) and type(accepted.preview_distance_m) is float and math.isfinite(accepted.preview_distance_m) and
0 < accepted.preview_distance_m <= 500 and type(accepted.preview_way_id) is int and accepted.preview_way_id > 0): 0 < accepted.preview_distance_m <= 500 and type(accepted.preview_way_id) is int and accepted.preview_way_id > 0):
preview_identity = hashlib.sha256(f'{identity}:{boundary}'.encode()).hexdigest() preview_identity = hashlib.sha256(f'{identity}:{boundary}'.encode()).hexdigest()
observation = acc.Observation(acc.ObservationKind.VALID, acc.Candidate('map', observation = acc.Observation(acc.ObservationKind.VALID, acc.Candidate('map',
acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value=preview_identity), accepted.preview_speed_mps)) acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value=preview_identity), preview_speed))
self.upcoming = Upcoming(observation, accepted.preview_distance_m, boundary, accepted.preview_way_id) self.upcoming = Upcoming(observation, accepted.preview_distance_m, boundary, accepted.preview_way_id)
return acc.Observation(acc.ObservationKind.VALID, acc.Candidate('map', return acc.Observation(acc.ObservationKind.VALID, acc.Candidate('map',
acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value=identity), accepted.speed_mps)) acc.ObservationIdentity(acc.IdentityKind.GEOGRAPHIC, value=identity), speed))

Some files were not shown because too many files have changed in this diff Show More