mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-29 16:23:55 +08:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a150727244 | |||
| 90b216c9e6 | |||
| afe4548c20 | |||
| 48d9831662 | |||
| 17e5e97241 | |||
| bb62ff7f66 | |||
| f4873d928d | |||
| 15278f7164 | |||
| 238257ad24 | |||
| 30eea20ee4 | |||
| 3d57f1fc8e | |||
| 5ef7a8d977 | |||
| 4bf641aab0 | |||
| 7b80004af7 | |||
| a2b38e9b66 | |||
| ef39779669 | |||
| 77338898f2 |
@@ -90,7 +90,7 @@ class MessageState:
|
||||
self.counter = cur_count
|
||||
return self.counter_fail < MAX_BAD_COUNTER
|
||||
|
||||
def valid(self, current_nanos: int) -> bool:
|
||||
def valid(self, current_nanos: int, bus_timeout: bool) -> bool:
|
||||
if self.ignore_alive:
|
||||
return True
|
||||
if not self.timestamps:
|
||||
@@ -201,12 +201,13 @@ class CANParser:
|
||||
def can_valid(self) -> bool:
|
||||
valid = True
|
||||
counters_valid = True
|
||||
bus_timeout = self.bus_timeout
|
||||
invalid_messages = set()
|
||||
for state in self.message_states.values():
|
||||
if state.counter_fail >= MAX_BAD_COUNTER:
|
||||
counters_valid = False
|
||||
state.rate_limited_log(self._last_update_nanos, f"counter invalid, {state.counter_fail=} {MAX_BAD_COUNTER=}")
|
||||
if not state.valid(self._last_update_nanos):
|
||||
if not state.valid(self._last_update_nanos, bus_timeout):
|
||||
valid = False
|
||||
invalid_messages.add(state.address)
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ def camera_current(parser):
|
||||
source = parser.message_states.get(0x2A4)
|
||||
now = parser._last_update_nanos
|
||||
bus_timeout = parser.bus_timeout
|
||||
healthy = all(state.valid(now) and state.counter_fail < MAX_BAD_COUNTER for state in parser.message_states.values())
|
||||
healthy = all(state.valid(now, bus_timeout) and state.counter_fail < MAX_BAD_COUNTER for state in parser.message_states.values())
|
||||
return bool(healthy and not bus_timeout and source is not None and source.timestamps
|
||||
and source.counter_fail < MAX_BAD_COUNTER and 0 < int(source.timestamps[-1]) <= now
|
||||
and now - int(source.timestamps[-1]) <= source.timeout_threshold)
|
||||
|
||||
@@ -375,7 +375,7 @@ class CarState(CarStateBase):
|
||||
bus_timeout = cp.bus_timeout
|
||||
self.ev6_aol_source_healthy = bool(
|
||||
not bus_timeout and source is not None and source.timestamps
|
||||
and source.valid(now) and source.counter_fail < MAX_BAD_COUNTER
|
||||
and source.valid(now, bus_timeout) and source.counter_fail < MAX_BAD_COUNTER
|
||||
and 0 < self.ev6_aol_sample_stamp_ns <= now
|
||||
and now - self.ev6_aol_sample_stamp_ns <= source.timeout_threshold)
|
||||
values = cp.vl_all['CLU11']
|
||||
@@ -578,7 +578,7 @@ class CarState(CarStateBase):
|
||||
bus_timeout = cp.bus_timeout
|
||||
self.ev6_aol_source_healthy = bool(
|
||||
not bus_timeout and source is not None and source.timestamps
|
||||
and source.valid(now) and source.counter_fail < MAX_BAD_COUNTER
|
||||
and source.valid(now, bus_timeout) and source.counter_fail < MAX_BAD_COUNTER
|
||||
and 0 < self.ev6_aol_sample_stamp_ns <= now
|
||||
and now - self.ev6_aol_sample_stamp_ns <= source.timeout_threshold)
|
||||
values = cp.vl_all[self.cruise_btns_msg_canfd]
|
||||
@@ -777,30 +777,8 @@ class CarState(CarStateBase):
|
||||
msgs.extend((name, 0) for name in {available_msg, enabled_msg, speed_msg})
|
||||
if not CP.flags & HyundaiFlags.NON_SCC_NO_FCA:
|
||||
(msgs if CP.flags & HyundaiFlags.NON_SCC_RADAR_FCA else cam_msgs).append(("FCA11", math.nan))
|
||||
pt_signals = None
|
||||
if (CP.carFingerprint == CAR.HYUNDAI_SONATA_HYBRID and CP.pcmCruise and not CP.openpilotLongitudinalControl and
|
||||
not CP.flags & (HyundaiFlags.CAMERA_SCC | HyundaiFlags.NON_SCC)):
|
||||
pt_signals = {
|
||||
"BCM_PO_11": ("LDA_BTN",),
|
||||
"CGW1": ("CF_Gway_DrvDrSw", "CF_Gway_AstDrSw", "CF_Gway_DrvSeatBeltSw", "CF_Gway_TurnSigLh", "CF_Gway_TurnSigRh"),
|
||||
"CGW2": ("CF_Gway_RLDrSw", "CF_Gway_RRDrSw"),
|
||||
"CLU15": ("CF_Clu_VehicleSpeed",),
|
||||
"ELECT_GEAR": ("Elect_Gear_Shifter",),
|
||||
"E_EMS11": ("CR_Vcu_AccPedDep_Pos",),
|
||||
"FCA11": ("CF_VSM_Warn", "CF_VSM_DecCmdAct", "FCA_CmdAct"),
|
||||
"LCA11": ("CF_Lca_IndLeft", "CF_Lca_IndRight"),
|
||||
"MDPS12": ("CR_Mdps_StrColTq", "CR_Mdps_OutTq", "CF_Mdps_ToiUnavail", "CF_Mdps_ToiFlt", "CF_Mdps_ToiActive"),
|
||||
"SAS11": ("SAS_Angle", "SAS_Speed"),
|
||||
"SCC11": ("MainMode_ACC", "SCCInfoDisplay", "VSetDis"),
|
||||
"SCC12": ("ACCMode", "TakeOverReq", "CF_VSM_Warn", "CF_VSM_DecCmdAct", "AEB_CmdAct"),
|
||||
"TCS11": ("TCS_PAS", "ABS_ACT"),
|
||||
"TCS13": ("DriverOverride", "PBRAKE_ACT", "ACCEnable"),
|
||||
"TCS15": ("AVH_LAMP",),
|
||||
"WHL_SPD11": ("WHL_SPD_FL", "WHL_SPD_FR", "WHL_SPD_RL", "WHL_SPD_RR"),
|
||||
}
|
||||
|
||||
parsers = {
|
||||
Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], msgs, 0, signals=pt_signals),
|
||||
Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], msgs, 0),
|
||||
Bus.cam: CANParser(DBC[CP.carFingerprint][Bus.pt], cam_msgs, 2),
|
||||
}
|
||||
|
||||
|
||||
@@ -5,18 +5,6 @@ from opendbc.car.hyundai.classic_scc_aol import CLASSIC_SCC_IDS, stock_word
|
||||
AOL_MARKER = 0x0400
|
||||
AOL_EXPERIENCE = 32
|
||||
_EXCLUDED = int(HyundaiFlags.LEGACY | HyundaiFlags.UNSUPPORTED_LONGITUDINAL | HyundaiFlags.ALT_LIMITS_2 | HyundaiFlags.CAMERA_SCC | HyundaiFlags.FCEV)
|
||||
_DYNAMIC_FLAGS = int(HyundaiFlags.HAS_LDA_BUTTON | HyundaiFlags.USE_FCA | HyundaiFlags.SEND_LFA)
|
||||
_IDENTITY_MASK = int(
|
||||
HyundaiFlags.CANFD
|
||||
| HyundaiFlags.NON_SCC
|
||||
| HyundaiFlags.FCEV
|
||||
| HyundaiFlags.LEGACY
|
||||
| HyundaiFlags.EV
|
||||
| HyundaiFlags.HYBRID
|
||||
| HyundaiFlags.ALT_LIMITS
|
||||
| HyundaiFlags.ALT_LIMITS_2
|
||||
| HyundaiFlags.CAMERA_SCC
|
||||
)
|
||||
CLASSIC_LONG_IDS = frozenset(identity for identity in CLASSIC_SCC_IDS if not int(identity.config.flags) & _EXCLUDED)
|
||||
LONG_AOL_WORDS = frozenset(AOL_MARKER | 4 | gas | limits | lda for gas in (0, 1, 2) for limits in (0, 64) for lda in (0, 2048))
|
||||
|
||||
@@ -36,22 +24,33 @@ def aol_word(cp):
|
||||
|
||||
|
||||
def qualified(cp, *, marked_only=False):
|
||||
if not cp.openpilotLongitudinalControl or cp.pcmCruise:
|
||||
return False
|
||||
from opendbc.car.hyundai.legacy_long_aol import CARS, qualified as legacy_qualified
|
||||
if cp.carFingerprint in CARS:
|
||||
return legacy_qualified(cp, marked_only=marked_only)
|
||||
if cp.brand != 'hyundai' or cp.carFingerprint not in CLASSIC_LONG_IDS:
|
||||
return False
|
||||
declared = int(CAR[cp.carFingerprint].config.flags)
|
||||
allowed = declared | _DYNAMIC_FLAGS
|
||||
allowed = declared | int(HyundaiFlags.HAS_LDA_BUTTON | HyundaiFlags.USE_FCA | HyundaiFlags.SEND_LFA)
|
||||
identity_mask = int(
|
||||
HyundaiFlags.CANFD
|
||||
| HyundaiFlags.NON_SCC
|
||||
| HyundaiFlags.FCEV
|
||||
| HyundaiFlags.LEGACY
|
||||
| HyundaiFlags.EV
|
||||
| HyundaiFlags.HYBRID
|
||||
| HyundaiFlags.ALT_LIMITS
|
||||
| HyundaiFlags.ALT_LIMITS_2
|
||||
| HyundaiFlags.CAMERA_SCC
|
||||
)
|
||||
if (
|
||||
int(cp.flags) & _IDENTITY_MASK != declared & _IDENTITY_MASK
|
||||
int(cp.flags) & identity_mask != declared & identity_mask
|
||||
or int(cp.flags) & ~allowed
|
||||
or is_blended(cp)
|
||||
or cp.passive
|
||||
or cp.notCar
|
||||
or cp.dashcamOnly
|
||||
or not cp.openpilotLongitudinalControl
|
||||
or cp.pcmCruise
|
||||
or cp.steerControlType != structs.CarParams.SteerControlType.torque
|
||||
or not cp.alphaLongitudinalAvailable
|
||||
or cp.alternativeExperience not in (0, AOL_EXPERIENCE)
|
||||
|
||||
@@ -12,21 +12,9 @@ from opendbc.car.hyundai.values import CAR, HyundaiFlags, HyundaiSafetyFlags, is
|
||||
AOL_MARKER = 0x0400
|
||||
AOL_EXPERIENCE = 32
|
||||
_EXCLUDED = int(HyundaiFlags.CANFD | HyundaiFlags.NON_SCC | HyundaiFlags.FCEV)
|
||||
_DYNAMIC_FLAGS = int(HyundaiFlags.HAS_LDA_BUTTON | HyundaiFlags.USE_FCA | HyundaiFlags.SEND_LFA)
|
||||
_IDENTITY_MASK = _EXCLUDED | int(
|
||||
HyundaiFlags.EV | HyundaiFlags.HYBRID | HyundaiFlags.ALT_LIMITS | HyundaiFlags.ALT_LIMITS_2 | HyundaiFlags.CAMERA_SCC | HyundaiFlags.LEGACY
|
||||
)
|
||||
CLASSIC_SCC_IDS = frozenset(identity for identity in CAR if not int(identity.config.flags) & _EXCLUDED and identity != CAR.HYUNDAI_PALISADE_2023) | frozenset(
|
||||
(CAR.HYUNDAI_NEXO_1ST_GEN,)
|
||||
)
|
||||
_STOCK_FLAGS = tuple((int(flag), int(safety)) for flag, safety in (
|
||||
(HyundaiFlags.FCEV, HyundaiSafetyFlags.FCEV_GAS),
|
||||
(HyundaiFlags.EV, HyundaiSafetyFlags.EV_GAS),
|
||||
(HyundaiFlags.HYBRID, HyundaiSafetyFlags.HYBRID_GAS),
|
||||
(HyundaiFlags.ALT_LIMITS, HyundaiSafetyFlags.ALT_LIMITS),
|
||||
(HyundaiFlags.ALT_LIMITS_2, HyundaiSafetyFlags.ALT_LIMITS_2),
|
||||
(HyundaiFlags.CAMERA_SCC, HyundaiSafetyFlags.CAMERA_SCC),
|
||||
))
|
||||
_MODELS = (structs.CarParams.SafetyModel.hyundai, structs.CarParams.SafetyModel.hyundaiLegacy)
|
||||
FCEV_AOL_WORDS = frozenset((0x0500, 0x0D00))
|
||||
NORMAL_AOL_WORDS = (
|
||||
@@ -43,10 +31,16 @@ def native_profile_supported(model, param):
|
||||
|
||||
def stock_word(cp):
|
||||
word = int(HyundaiSafetyFlags.CAN_REFRESH_MSGS) if cp.carFingerprint in (CAR.HYUNDAI_ELANTRA_2024, CAR.HYUNDAI_ELANTRA_HEV_2024) else 0
|
||||
flags = int(cp.flags)
|
||||
for flag, safety in _STOCK_FLAGS:
|
||||
if flags & flag:
|
||||
word |= safety
|
||||
for flag, safety in (
|
||||
(HyundaiFlags.FCEV, HyundaiSafetyFlags.FCEV_GAS),
|
||||
(HyundaiFlags.EV, HyundaiSafetyFlags.EV_GAS),
|
||||
(HyundaiFlags.HYBRID, HyundaiSafetyFlags.HYBRID_GAS),
|
||||
(HyundaiFlags.ALT_LIMITS, HyundaiSafetyFlags.ALT_LIMITS),
|
||||
(HyundaiFlags.ALT_LIMITS_2, HyundaiSafetyFlags.ALT_LIMITS_2),
|
||||
(HyundaiFlags.CAMERA_SCC, HyundaiSafetyFlags.CAMERA_SCC),
|
||||
):
|
||||
if int(cp.flags) & int(flag):
|
||||
word |= int(safety)
|
||||
return word
|
||||
|
||||
|
||||
@@ -58,9 +52,12 @@ def qualified(cp, *, marked_only=False):
|
||||
if cp.brand != "hyundai" or cp.carFingerprint not in CLASSIC_SCC_IDS:
|
||||
return False
|
||||
declared = int(CAR[cp.carFingerprint].config.flags)
|
||||
allowed = declared | _DYNAMIC_FLAGS
|
||||
allowed = declared | int(HyundaiFlags.HAS_LDA_BUTTON | HyundaiFlags.USE_FCA | HyundaiFlags.SEND_LFA)
|
||||
identity_mask = _EXCLUDED | int(
|
||||
HyundaiFlags.EV | HyundaiFlags.HYBRID | HyundaiFlags.ALT_LIMITS | HyundaiFlags.ALT_LIMITS_2 | HyundaiFlags.CAMERA_SCC | HyundaiFlags.LEGACY
|
||||
)
|
||||
if (
|
||||
int(cp.flags) & _IDENTITY_MASK != declared & _IDENTITY_MASK
|
||||
int(cp.flags) & identity_mask != declared & identity_mask
|
||||
or int(cp.flags) & ~allowed
|
||||
or is_blended(cp)
|
||||
or cp.passive
|
||||
|
||||
@@ -161,8 +161,6 @@ def get_radar_can_parser(CP):
|
||||
# MRR35 publishes many unused/unknown fields in each object packet. Decode
|
||||
# the four consumed track fields, retaining parser integrity fields automatically.
|
||||
selected = ({name: ('STATE', 'LONG_DIST', 'LAT_DIST', 'REL_SPEED') for name, _ in messages} if mrr35 else None)
|
||||
if radar_dbc(CP) == "hyundai_kia_mando_front_radar_generated":
|
||||
selected = {name: ('STATE', 'AZIMUTH', 'LONG_DIST', 'REL_SPEED') for name, _ in messages}
|
||||
return CANParser(radar_dbc(CP), messages, radar_bus(CP) if mrr35 or mrr30 or gv70 else 1, signals=selected)
|
||||
|
||||
|
||||
|
||||
@@ -329,7 +329,7 @@ class TestBlendedLifecycle(unittest.TestCase):
|
||||
car._deferred_radar_can = None
|
||||
vars(car)['RI'] = SimpleNamespace(update=lambda can_list: None)
|
||||
vars(car)['state_publish'] = lambda *args: calls.append('state')
|
||||
car.CP = SimpleNamespace(brand='hyundai', passive=False)
|
||||
car.CP = SimpleNamespace(passive=False)
|
||||
car.ci_initialized = False
|
||||
|
||||
class SM(dict):
|
||||
|
||||
@@ -216,7 +216,7 @@ def test_actual_classic_family_cancel_and_manual_withdrawal(identity, monkeypatc
|
||||
config = card.CP.safetyConfigs[0]
|
||||
model, word = int(config.safetyModel.raw), int(config.safetyParam)
|
||||
configured = [False]
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car._step))).body[0].body
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car.step))).body[0].body
|
||||
assignments = [node for node in dispatch_tree if isinstance(node, ast.Assign) and
|
||||
any(isinstance(t, ast.Name) and t.id == 'initialized' for t in node.targets)]
|
||||
decisions = [node for node in dispatch_tree if isinstance(node, ast.If) and ast.unparse(node.test) == 'not self.CP.passive and initialized']
|
||||
|
||||
@@ -243,7 +243,7 @@ def test_classic_family_actual_startup_cancel_and_manual_withdrawal(identity, mo
|
||||
config = card.CP.safetyConfigs[0]
|
||||
model, word = int(config.safetyModel.raw), int(config.safetyParam)
|
||||
configured = [False]
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car._step))).body[0].body
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car.step))).body[0].body
|
||||
assignments = [
|
||||
node for node in dispatch_tree if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'initialized' for t in node.targets)
|
||||
]
|
||||
|
||||
@@ -13,7 +13,6 @@ from opendbc.car.hyundai.radar_interface import RadarInterface
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
from openpilot.starpilot.aol.card_native import aol_configuration
|
||||
from openpilot.starpilot.aol.intent import AOL_TOGGLE
|
||||
from openpilot.starpilot.car.hyundai.aol import policy_for, native_accepts_cp
|
||||
|
||||
@@ -103,8 +102,7 @@ class TestEV9CombinedPending(EV9StartupFixture):
|
||||
self.assertEqual(self.sent, [])
|
||||
with structs.CarParams.from_bytes(saved.get('CarParams')) as published:
|
||||
self.assertEqual(published.to_dict(), card.CP.to_dict())
|
||||
_, owners, _ = aol_configuration(card)
|
||||
self.assertEqual(owners[0], aol)
|
||||
self.assertEqual(card.aol_permission_owners()[0], aol)
|
||||
owner.close()
|
||||
|
||||
def test_marker_finalization_cannot_relabel_other_cp_fields_or_follow_publication(self):
|
||||
|
||||
@@ -116,16 +116,16 @@ class TestNonSccStartup(unittest.TestCase):
|
||||
message = parser.message_states[parser.dbc.name_to_msg[name].address]
|
||||
self.assertFalse(message.ignore_alive, (identity, name))
|
||||
self.assertFalse(message.timestamps, (identity, name))
|
||||
self.assertFalse(message.valid(1_000_000_000), (identity, name, 'never received'))
|
||||
self.assertFalse(message.valid(1_000_000_000, False), (identity, name, 'never received'))
|
||||
packer = CANPacker(DBC[identity][Bus.pt])
|
||||
packet = packer.make_can_msg(name, 0, {})
|
||||
if name == 'EMS16':
|
||||
packet = checksum(packet)
|
||||
ci.update([(1_000_000_000, [packet])])
|
||||
self.assertTrue(message.timestamps, (identity, name, 'packed arrival'))
|
||||
self.assertTrue(message.valid(1_000_000_000), (identity, name, 'arrived'))
|
||||
self.assertTrue(message.valid(1_000_000_000, False), (identity, name, 'arrived'))
|
||||
expired = 1_000_000_000 + int(message.timeout_threshold) + 1
|
||||
self.assertFalse(message.valid(expired), (identity, name, 'expired'))
|
||||
self.assertFalse(message.valid(expired, False), (identity, name, 'expired'))
|
||||
self.assertFalse(ci.update([(expired, [])]).canValid, (identity, name, 'incomplete stream'))
|
||||
|
||||
def test_required_sources_loss_wrong_bus_and_recovery(self):
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_prepublication_classic_owner_preserves_real_boot_and_independent_axes(i
|
||||
config = card.CP.safetyConfigs[0]
|
||||
model, word = int(config.safetyModel.raw), int(config.safetyParam)
|
||||
configured = [False]
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car._step))).body[0].body
|
||||
dispatch_tree = ast.parse(textwrap.dedent(inspect.getsource(card_module.Car.step))).body[0].body
|
||||
assignments = [
|
||||
node for node in dispatch_tree if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'initialized' for t in node.targets)
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ from opendbc.car.hyundai import radar_interface
|
||||
from opendbc.car.hyundai.tests.test_dom_radar_complete_paths import CASES, bank, factory
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,dbc,bus,start,count,length,lka', [case for case in CASES if any(layout in case[1] for layout in ('mrr35', 'mando_front'))])
|
||||
@pytest.mark.parametrize('name,dbc,bus,start,count,length,lka', [case for case in CASES if 'mrr35' in case[1]])
|
||||
def test_projected_radar_matches_complete_decoder(monkeypatch, name, dbc, bus, start, count, length, lka):
|
||||
cp = factory(name, bus, start, count, length, lka)
|
||||
projected = radar_interface.RadarInterface(cp)
|
||||
|
||||
@@ -110,6 +110,7 @@ class CarController(CarControllerBase):
|
||||
|
||||
self.accel = 0
|
||||
self.prev_accel = 0
|
||||
self.corolla_launch = CP.carFingerprint == CAR.TOYOTA_COROLLA_TSS2 and not CP.flags & (ToyotaFlags.HYBRID | ToyotaFlags.GAS_INTERCEPTOR)
|
||||
# *** end long control state ***
|
||||
|
||||
self.packer = CANPacker(dbc_names[Bus.pt])
|
||||
@@ -392,6 +393,11 @@ class CarController(CarControllerBase):
|
||||
pcm_accel_cmd = actuators.accel if filter_allowed else 0.
|
||||
if (bypass_long or self.prius_longitudinal or rav4h_long or advert_long) and not long_active:
|
||||
pcm_accel_cmd = 0.
|
||||
standstill_launch = (self.corolla_launch and long_active and CS.out.standstill and not stopping and actuators.accel > 0 and
|
||||
not (bypass_long or self.prius_longitudinal or rav4h_long or advert_long or pedal_owner))
|
||||
if standstill_launch:
|
||||
self.prev_accel = max(self.prev_accel, 0.)
|
||||
self.long_pid.i = max(self.long_pid.i, 0.)
|
||||
if long_active:
|
||||
pcm_accel_cmd = rate_limit(pcm_accel_cmd, self.prev_accel, ACCEL_WINDDOWN_LIMIT, ACCEL_WINDUP_LIMIT)
|
||||
self.prev_accel = pcm_accel_cmd
|
||||
@@ -532,7 +538,7 @@ class CarController(CarControllerBase):
|
||||
can_sends.append(make_tester_present_msg(0x750, 0, 0xF))
|
||||
|
||||
if self.bsm_poller is not None:
|
||||
can_sends.extend(self.bsm_poller.update(CS.out, self.frame))
|
||||
can_sends.extend(self.bsm_poller.update(CS.out, self.frame, factory_bsm=CS.factory_bsm))
|
||||
|
||||
door_command = self.door_locks.update(CS.out)
|
||||
if door_command is not None:
|
||||
|
||||
@@ -40,6 +40,7 @@ def has_optional_prius_gap_button(CP):
|
||||
class CarState(CarStateBase):
|
||||
def __init__(self, CP):
|
||||
super().__init__(CP)
|
||||
self.factory_bsm = False
|
||||
can_define = CANDefine(DBC[CP.carFingerprint][Bus.pt])
|
||||
original_prius = prius_sdsu.configured(CP) or prius_advert_filter.configured(CP)
|
||||
self.eps_torque_scale = ((CP.safetyConfigs[0].safetyParam & 0xFF) / 100. if prius_advert_filter.configured(CP) else
|
||||
@@ -235,12 +236,13 @@ class CarState(CarStateBase):
|
||||
ret.genericToggle = bool(cp.vl["LIGHT_STALK"]["AUTO_HIGH_BEAM"])
|
||||
ret.espDisabled = cp.vl["ESP_CONTROL"]["TC_DISABLED"] != 0
|
||||
|
||||
if self.CP.flags & ToyotaFlags.HAS_BSM or isinstance(cp, enhanced_bsm.BsmCANParser) and cp.factory_bsm:
|
||||
self.factory_bsm = isinstance(cp, enhanced_bsm.BsmCANParser) and cp.factory_bsm
|
||||
if self.CP.flags & ToyotaFlags.HAS_BSM or self.factory_bsm:
|
||||
ret.leftBlindspot = (cp.vl["BSM"]["L_ADJACENT"] == 1) or (cp.vl["BSM"]["L_APPROACHING"] == 1)
|
||||
ret.rightBlindspot = (cp.vl["BSM"]["R_ADJACENT"] == 1) or (cp.vl["BSM"]["R_APPROACHING"] == 1)
|
||||
if isinstance(cp, enhanced_bsm.BsmCANParser) and ret.vEgo > 6.0:
|
||||
ret.leftBlindspot |= cp.occupied(enhanced_bsm.SIDES[0])
|
||||
ret.rightBlindspot |= cp.occupied(enhanced_bsm.SIDES[1])
|
||||
elif isinstance(cp, enhanced_bsm.BsmCANParser) and ret.vEgo > 6.0:
|
||||
ret.leftBlindspot = cp.occupied(enhanced_bsm.SIDES[0])
|
||||
ret.rightBlindspot = cp.occupied(enhanced_bsm.SIDES[1])
|
||||
|
||||
if self.CP.carFingerprint != CAR.TOYOTA_PRIUS_V:
|
||||
self.lkas_hud = copy.copy(cp_cam.vl["LKAS_HUD"])
|
||||
@@ -415,7 +417,7 @@ class CarState(CarStateBase):
|
||||
Rav4hCANParser if rav4h_filter_configured(CP) else CANParser)
|
||||
if enhanced_bsm.configured(CP):
|
||||
pt_parser = enhanced_bsm.BsmCANParser
|
||||
pt_messages.append(("BSM", 0 if CP.flags & ToyotaFlags.HAS_BSM else math.nan))
|
||||
pt_messages.append(("BSM", math.nan))
|
||||
parsers = {
|
||||
Bus.pt: pt_parser(DBC[CP.carFingerprint][Bus.pt], pt_messages, 0, **({"stock_word": CP.safetyConfigs[0].safetyParam} if stock else
|
||||
{"alternate_main": alternate_sdsu_main} if legacy_advert else {})),
|
||||
|
||||
@@ -16,7 +16,7 @@ REPLY_MAX_AGE_NS = 500_000_000
|
||||
|
||||
def supported(cp):
|
||||
required = ToyotaFlags.TSS2 | ToyotaFlags.NO_DSU | ToyotaFlags.RAISED_ACCEL_LIMIT | ToyotaFlags.HYBRID
|
||||
allowed = required | ToyotaFlags.AUTO_BRAKE_HOLD | ToyotaFlags.HAS_BSM
|
||||
allowed = required | ToyotaFlags.AUTO_BRAKE_HOLD
|
||||
return (cp.carFingerprint == CAR.TOYOTA_PRIUS_TSS2 and cp.brand == 'toyota' and
|
||||
cp.pcmCruise and cp.openpilotLongitudinalControl and not (cp.passive or cp.dashcamOnly or cp.notCar or cp.secOcRequired) and
|
||||
cp.steerControlType == structs.CarParams.SteerControlType.torque and cp.flags & required == required and
|
||||
@@ -55,7 +55,8 @@ class BsmCANParser(CANParser):
|
||||
for address, data, bus in frames:
|
||||
if bus == self.bus and address == 0x3F6 and len(data) == 8:
|
||||
self.factory_bsm = True
|
||||
if (bus == self.bus and address == 0x758 and len(data) == 8 and
|
||||
self.blindspots.clear()
|
||||
if (not self.factory_bsm and bus == self.bus and address == 0x758 and len(data) == 8 and
|
||||
data[0] in SIDES and data[1:4] == b'\x06\x61\x69'):
|
||||
self.blindspots[data[0]] = (timestamp, max(data[5:7]) > 35)
|
||||
return super().update(strings, sendcan)
|
||||
@@ -70,8 +71,8 @@ class BsmPoller:
|
||||
self.active = False
|
||||
self.started = 0
|
||||
|
||||
def update(self, state, frame):
|
||||
ready = (frame > 200 and state.canValid and not state.canTimeout and
|
||||
def update(self, state, frame, *, factory_bsm=False):
|
||||
ready = (not factory_bsm and frame > 200 and state.canValid and not state.canTimeout and
|
||||
state.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport) and
|
||||
state.vEgo > (6.0 if self.active else 7.0))
|
||||
if ready != self.active:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.toyota.carcontroller import CarController
|
||||
from opendbc.car.toyota.tests.test_auto_hold import setup_hold, tick_acc
|
||||
from opendbc.car.toyota.values import CAR, DBC, ToyotaFlags
|
||||
|
||||
LONG_STATE = structs.CarControl.Actuators.LongControlState
|
||||
|
||||
|
||||
def launch(car=CAR.TOYOTA_COROLLA_TSS2, *, standstill=True, accel=0.2, state=LONG_STATE.pid):
|
||||
cp, controller, command, cs = setup_hold(car, False)
|
||||
cs.out.brakePressed = False
|
||||
cs.out.standstill = standstill
|
||||
cs.out.vEgo = 0. if standstill else 1.
|
||||
cs.out.cruiseState.enabled = True
|
||||
cs.out.cruiseState.standstill = standstill
|
||||
cs.pcm_acc_status = 8
|
||||
cs.gvc = 0.
|
||||
command.enabled = command.longActive = True
|
||||
command.actuators.accel = accel
|
||||
command.actuators.longControlState = state
|
||||
controller.prev_accel = -2.0
|
||||
controller.long_pid.i = -0.3
|
||||
return cp, controller, command, cs
|
||||
|
||||
|
||||
def test_corolla_standstill_launch_skips_brake_unwind():
|
||||
cp, controller, command, cs = launch()
|
||||
assert tick_acc(cp, controller, command, cs)['ACCEL_CMD'] >= 0.
|
||||
assert controller.long_pid.i >= 0.
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ('moving', 'stopping', 'braking', 'camry'))
|
||||
def test_launch_keeps_unwind_elsewhere(case):
|
||||
kwargs = {'moving': {'standstill': False}, 'stopping': {'state': LONG_STATE.stopping},
|
||||
'braking': {'accel': -0.5}, 'camry': {'car': CAR.TOYOTA_CAMRY_TSS2}}[case]
|
||||
cp, controller, command, cs = launch(**kwargs)
|
||||
assert tick_acc(cp, controller, command, cs)['ACCEL_CMD'] < -1.
|
||||
|
||||
|
||||
def test_hybrid_corolla_keeps_unwind():
|
||||
cp, _, _, _ = launch()
|
||||
cp.flags |= int(ToyotaFlags.HYBRID)
|
||||
assert not CarController(DBC[cp.carFingerprint], cp).corolla_launch
|
||||
@@ -21,12 +21,11 @@ def params(car=CAR.TOYOTA_PRIUS_TSS2, *, factory=False, requested=True):
|
||||
|
||||
@pytest.mark.parametrize('car,factory,requested,configured', (
|
||||
(CAR.TOYOTA_PRIUS_TSS2, False, True, True),
|
||||
(CAR.TOYOTA_PRIUS_TSS2, True, True, True),
|
||||
(CAR.TOYOTA_PRIUS_TSS2, True, False, False),
|
||||
(CAR.TOYOTA_PRIUS_TSS2, True, True, False),
|
||||
(CAR.TOYOTA_PRIUS_TSS2, False, False, False),
|
||||
(CAR.TOYOTA_COROLLA_TSS2, False, True, False),
|
||||
))
|
||||
def test_polling_admission(car, factory, requested, configured):
|
||||
def test_fallback_admission(car, factory, requested, configured):
|
||||
cp = params(car, factory=factory, requested=requested)
|
||||
ci = CarInterface(cp)
|
||||
assert isinstance(ci.can_parsers[Bus.pt], enhanced_bsm.BsmCANParser) == configured
|
||||
@@ -54,20 +53,15 @@ def test_fresh_bsm_replies_are_independent_and_use_recorded_idle_format():
|
||||
assert not parser.occupied(0x42)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('factory_at_startup', (False, True))
|
||||
def test_factory_and_diagnostic_detections_are_combined(factory_at_startup):
|
||||
cp = params(factory=factory_at_startup)
|
||||
def test_late_factory_broadcast_takes_priority():
|
||||
cp = params()
|
||||
ci = CarInterface(cp)
|
||||
packer = CANPacker(DBC[CAR.TOYOTA_PRIUS_TSS2][Bus.pt])
|
||||
wheel = packer.make_can_msg('WHEEL_SPEEDS', 0, {f'WHEEL_SPEED_{side}': 36 for side in ('FL', 'FR', 'RL', 'RR')})
|
||||
left_factory = packer.make_can_msg('BSM', 0, {'L_APPROACHING': 1})
|
||||
left_idle = (0x758, bytes.fromhex('4106616900000089'), 0)
|
||||
right_active = (0x758, bytes.fromhex('4206616900390089'), 0)
|
||||
ci.update([(990_000_000, [])]) # The wheel message is registered on first access.
|
||||
state = ci.update([(1_000_000_000, [wheel, left_factory, left_idle, right_active])])
|
||||
assert state.leftBlindspot and state.rightBlindspot
|
||||
state = ci.update([(1_500_000_001, [wheel, left_factory])])
|
||||
factory = packer.make_can_msg('BSM', 0, {'L_APPROACHING': 1})
|
||||
right = (0x758, bytes.fromhex('4206616900390089'), 0)
|
||||
state = ci.update([(1_000_000_000, [factory, right])])
|
||||
assert state.leftBlindspot and not state.rightBlindspot
|
||||
assert ci.CS.factory_bsm
|
||||
|
||||
|
||||
def test_poll_cadence_and_cleanup():
|
||||
@@ -138,12 +132,8 @@ def test_native_diagnostics_are_scoped_and_require_a_paced_moving_session(tmp_pa
|
||||
assert tx(end)
|
||||
assert not tx(end)
|
||||
wheel(8.)
|
||||
rx('BSM', {'L_ADJACENT': 1})
|
||||
assert tx(enable)
|
||||
safety.set_timer(1_141_000)
|
||||
rx('BSM', {'L_ADJACENT': 1})
|
||||
assert tx(poll)
|
||||
wheel(0.)
|
||||
rx('BSM', {})
|
||||
assert not tx(poll)
|
||||
assert tx(end)
|
||||
assert not tx(enable)
|
||||
|
||||
@@ -34,7 +34,7 @@ def test_prius_gap_button_requires_the_source_only_during_a_press(stock_aol):
|
||||
gap_message = parsers[Bus.pt].message_states[0x343]
|
||||
assert not gap_message.ignore_alive
|
||||
assert edges(12_000_000_000) == []
|
||||
assert not gap_message.valid(12_000_000_000)
|
||||
assert not gap_message.valid(12_000_000_000, False)
|
||||
assert edges(12_030_000_000, 0) == [False]
|
||||
assert gap_message.ignore_alive
|
||||
assert gap_message.valid(23_000_000_000)
|
||||
assert gap_message.valid(23_000_000_000, False)
|
||||
|
||||
@@ -69,6 +69,7 @@ static bool toyota_stock_longitudinal = false;
|
||||
static bool toyota_lta = false;
|
||||
static bool toyota_radar_diagnostics_allowed = false;
|
||||
static bool toyota_enhanced_bsm = false;
|
||||
static bool toyota_factory_bsm_seen = false;
|
||||
static uint32_t toyota_bsm_tx_ts[2] = {0U, 0U};
|
||||
static bool toyota_bsm_session[2] = {false, false};
|
||||
static int toyota_dbc_eps_torque_factor = 100; // conversion factor for STEER_TORQUE_EPS in %: see dbc file
|
||||
@@ -223,6 +224,9 @@ static void toyota_hold_observe(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
static void toyota_optional_rx_hook(const CANPacket_t *msg) {
|
||||
if (toyota_enhanced_bsm && msg_matches(msg, 0x3F6U, 0U) && (GET_LEN(msg) == 8U)) {
|
||||
toyota_factory_bsm_seen = true;
|
||||
}
|
||||
// Only bus0 pedal RX belongs to the required catalog. A CRC-valid camera
|
||||
// copy must neither invalidate its parent nor refresh the primary lease.
|
||||
const bool camera_copy = toyota_pedal && msg_matches(msg, 0x201U, 2U) && (GET_LEN(msg) == 6U) &&
|
||||
@@ -623,7 +627,7 @@ static bool toyota_tx_hook(const CANPacket_t *msg) {
|
||||
const bool paced = safety_get_ts_elapsed(now, toyota_bsm_tx_ts[side]) >= 40000U;
|
||||
const bool enable = start && !session && (vehicle_speed.values[0] > (7 * VEHICLE_SPEED_FACTOR));
|
||||
const bool poll_allowed = poll && session && paced && (vehicle_speed.values[0] > (6 * VEHICLE_SPEED_FACTOR));
|
||||
tx &= (stop_polling && session) || (ready && (enable || poll_allowed));
|
||||
tx &= (stop_polling && session) || (!toyota_factory_bsm_seen && ready && (enable || poll_allowed));
|
||||
if (tx) {
|
||||
toyota_bsm_session[side] = !stop_polling;
|
||||
toyota_bsm_tx_ts[side] = now;
|
||||
@@ -642,6 +646,7 @@ static bool toyota_tx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
static safety_config toyota_init(uint16_t param) {
|
||||
toyota_factory_bsm_seen = false;
|
||||
toyota_enhanced_bsm = (param == 73U) && ((alternative_experience & ALT_EXP_TOYOTA_ENHANCED_BSM) != 0);
|
||||
for (unsigned int i = 0U; i < 2U; i++) {
|
||||
toyota_bsm_tx_ts[i] = 0U;
|
||||
|
||||
@@ -603,12 +603,7 @@ class TestToyotaHighlanderAol(unittest.TestCase):
|
||||
self.assertTrue(send(right, start))
|
||||
self.rx(0x3F6, bytes(8))
|
||||
self.safety.set_timer(1_080_000)
|
||||
self.assertTrue(send(left, poll))
|
||||
self.assertTrue(send(right, poll))
|
||||
stopped = dict.fromkeys(speed, 0)
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.packer.make_can_msg_safety("WHEEL_SPEEDS", 0, stopped)))
|
||||
self.assertFalse(send(left, poll))
|
||||
self.assertFalse(send(right, poll))
|
||||
self.assertTrue(send(left, stop))
|
||||
self.assertTrue(send(right, stop))
|
||||
self.assertFalse(send(left, start))
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -137,6 +137,9 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"LaneCentering", {PERSISTENT, BOOL, "0"}},
|
||||
{"LaneCenteringPauseOnSignal", {PERSISTENT, BOOL, "1"}},
|
||||
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
|
||||
{"ParkedClearance", {PERSISTENT, BOOL, "0"}},
|
||||
{"ParkedClearanceGap", {PERSISTENT, FLOAT, "1.5"}},
|
||||
{"ParkedClearanceShift", {PERSISTENT, FLOAT, "0.3"}},
|
||||
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
|
||||
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
|
||||
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
|
||||
|
||||
@@ -39,10 +39,16 @@ from openpilot.starpilot.aol.intent import AolProcessFaultContext, claim_remappe
|
||||
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity
|
||||
from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol, native_observation as honda_native_observation
|
||||
from opendbc.car.volkswagen.stock_aol import safety_config as volkswagen_aol_safety_config
|
||||
from openpilot.starpilot.car.volkswagen.aol import qualified as qualified_volkswagen_aol
|
||||
from openpilot.starpilot.car.rivian.aol import retained_brake_lateral_intent as rivian_brake_intent_retained
|
||||
from opendbc.car.rivian.stock_aol import qualified as qualified_rivian_aol
|
||||
from opendbc.car.mazda.stock_aol import qualified as qualified_mazda_aol
|
||||
from opendbc.car.tesla.preap.aol import qualified as qualified_tesla_preap
|
||||
from opendbc.car.hyundai.canfd_angle_aol import qualified as qualified_angle_aol
|
||||
from opendbc.car.hyundai.canfd_owner import config_index as hyundai_canfd_config_index
|
||||
from opendbc.car.hyundai.captured_adrv_startup import CapturedADRVStartup
|
||||
from openpilot.starpilot.car.nissan.aol import qualified as qualified_nissan_aol
|
||||
from openpilot.starpilot.car.volvo.aol import qualified as qualified_volvo_aol
|
||||
from openpilot.starpilot.car.hyundai.aol import aol_safety_config as hyundai_aol_safety_config, pending_stock_angle_arm
|
||||
from openpilot.starpilot.car.hyundai.aol import retained_shared_long_cancel_intent as hkg_cancel_intent_retained
|
||||
from openpilot.starpilot.car.ford.aol import (brake_pause_active as ford_brake_pause_active,
|
||||
@@ -50,7 +56,7 @@ from openpilot.starpilot.car.ford.aol import (brake_pause_active as ford_brake_p
|
||||
qualification_cycle as ford_qualification_cycle,
|
||||
qualified as qualified_ford_aol)
|
||||
from openpilot.starpilot.car.subaru import aol as subaru_aol
|
||||
from openpilot.starpilot.aol.card_native import aol_configuration
|
||||
from openpilot.starpilot.aol.card_native import native_handlers
|
||||
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, current_axis, current_native
|
||||
from openpilot.starpilot.aol.vehicle import create_intent as create_aol_intent, native_latch_rejected, policy_for as aol_policy_for
|
||||
from openpilot.starpilot.aol.wire import IntentState, encode_intent
|
||||
@@ -382,8 +388,6 @@ class Car:
|
||||
self._prepare_feedback_capture()
|
||||
except Exception:
|
||||
pass # Optional learning setup cannot stop native startup.
|
||||
if self.aol_card_intent is not None:
|
||||
aol_configuration(self)
|
||||
self.aol_transport_feedback = TransportPauseFeedback(self.CP) if self.aol_replay else None
|
||||
if isinstance(self.CI, GMInterface) and self.CI.CC is not None and self.CI.CC.volt_sng_plan_input is not None:
|
||||
self.CI.CC.volt_sng_plan_input.boottime = self.volt_startup_keepalive()
|
||||
@@ -484,11 +488,7 @@ class Car:
|
||||
|
||||
can_strs = messaging.drain_sock_raw(self.can_sock, wait_for_one=True)
|
||||
can_received_ns = time.monotonic_ns()
|
||||
if (self.CP.carFingerprint == HYUNDAI_CAR.HYUNDAI_SONATA_HYBRID and self.CP.pcmCruise and
|
||||
not self.CP.openpilotLongitudinalControl):
|
||||
can_list = can_capnp_to_list(can_strs, include_tx_receipts=False)
|
||||
else:
|
||||
can_list = can_capnp_to_list(can_strs)
|
||||
can_list = can_capnp_to_list(can_strs)
|
||||
|
||||
observe_controller_can(self.CI, can_list)
|
||||
CS = self.CI.update(can_list)
|
||||
@@ -644,9 +644,11 @@ class Car:
|
||||
not any(e.immediateDisable or e.softDisable or e.userDisable for e in self.sm['onroadEvents']))
|
||||
fault_active = transport_reset or self.aol_disarming_fault(CS, event_ns, now_ns,
|
||||
transport_observed_healthy=reuse_transport or angle_arm_pending or ford_initial_wait or volkswagen_initial_wait)
|
||||
_, owners, handlers = aol_configuration(self)
|
||||
angle_aol, ford_aol, honda_aol, mazda_aol, preap_aol, volkswagen_aol, rivian_aol = owners
|
||||
permission_owner = handlers is not None
|
||||
angle_aol, ford_aol, honda_aol, mazda_aol, preap_aol, volkswagen_aol = self.aol_permission_owners()
|
||||
nissan_aol = qualified_nissan_aol(self.CP, marked_only=True)
|
||||
rivian_aol = qualified_rivian_aol(self.CP, marked_only=True)
|
||||
volvo_aol = qualified_volvo_aol(self.CP, marked_only=True)
|
||||
permission_owner = angle_aol or ford_aol or honda_aol or mazda_aol or preap_aol or nissan_aol or volkswagen_aol or rivian_aol or volvo_aol
|
||||
angle_panda_ready = not permission_owner or self.startup_panda_configured()
|
||||
native = (
|
||||
current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_axis_session() if permission_owner else None)
|
||||
@@ -656,8 +658,11 @@ class Car:
|
||||
honda_eps_pending = bool(honda_aol and not transport_reset and native is not None and
|
||||
getattr(self.aol_transport_feedback, 'honda_eps_retained_native_ns', 0) == int(native.observedMonoTime))
|
||||
native_reset = False
|
||||
if handlers is not None:
|
||||
observe, restrict = handlers
|
||||
if permission_owner:
|
||||
observe, restrict = native_handlers(
|
||||
self, volvo_aol=volvo_aol, rivian_aol=rivian_aol, volkswagen_aol=volkswagen_aol, nissan_aol=nissan_aol,
|
||||
preap_aol=preap_aol, mazda_aol=mazda_aol, honda_aol=honda_aol, ford_aol=ford_aol,
|
||||
)
|
||||
preap_observation = {}
|
||||
if preap_aol:
|
||||
cancel_stamp = int(self.CI.CS.preap.cancel_echo_stamp_ns)
|
||||
@@ -933,31 +938,29 @@ class Car:
|
||||
getattr(self, '_aol_can_observation', None), now_ns)
|
||||
|
||||
def aol_disarming_fault(self, CS, event_ns: int, now_ns: int, *, transport_observed_healthy=False) -> bool:
|
||||
if not aol_configuration(self)[0].intent_supported:
|
||||
if not aol_policy_for(self.CP).intent_supported:
|
||||
return True
|
||||
from openpilot.starpilot.aol.vehicle import intent_disarming_fault
|
||||
feedback = getattr(self, 'aol_transport_feedback', None)
|
||||
if feedback is None:
|
||||
feedback = self.aol_transport_feedback = TransportPauseFeedback(self.CP)
|
||||
if not transport_observed_healthy:
|
||||
cancel_source_ns = self.aol_cancel_source(CS, now_ns)
|
||||
hkg_cancel_retained = hkg_cancel_intent_retained(self.CP, CS, self.sm, feedback,
|
||||
self.aol_card_intent, cancel_source_ns=cancel_source_ns, now_ns=now_ns,
|
||||
producer=getattr(self, 'slc_producer_session', ''))
|
||||
if not hkg_cancel_retained and feedback.observe(self.sm, self.CP, CS, now_ns,
|
||||
latched=getattr(getattr(self, 'aol_card_intent', None), 'allowed_latch', True),
|
||||
cancel_source_ns=cancel_source_ns, brake_source_ns=self.aol_honda_brake_source(CS, now_ns),
|
||||
gm_withdrawal_source_ns=self.aol_gm_withdrawal_source(CS, now_ns),
|
||||
intent_producer_session=getattr(self, 'slc_producer_session', ''),
|
||||
main_arm_ns=(getattr(self.aol_card_intent, 'main_arm_ns', 0) or
|
||||
getattr(self.aol_card_intent, 'physical_arm_ns', 0)),
|
||||
startup_calibration_pending=getattr(self.aol_card_intent, 'startup_calibration_pending', False),
|
||||
intent_paused=(getattr(self.aol_card_intent, 'pause_lateral', False) or
|
||||
ford_brake_pause_active(self.CP, CS, self.aol_settings) or
|
||||
self.CP.brand == 'volkswagen' and CS.canValid and not CS.canTimeout and
|
||||
not CS.steerFaultPermanent and (CS.gearShifter == car.CarState.GearShifter.reverse or
|
||||
getattr(self.aol_card_intent, 'reverse_pause', False)))):
|
||||
return True
|
||||
hkg_cancel_retained = hkg_cancel_intent_retained(self.CP, CS, self.sm, feedback,
|
||||
self.aol_card_intent, cancel_source_ns=self.aol_cancel_source(CS, now_ns), now_ns=now_ns,
|
||||
producer=getattr(self, 'slc_producer_session', ''))
|
||||
if not transport_observed_healthy and not hkg_cancel_retained and feedback.observe(self.sm, self.CP, CS, now_ns,
|
||||
latched=getattr(getattr(self, 'aol_card_intent', None), 'allowed_latch', True),
|
||||
cancel_source_ns=self.aol_cancel_source(CS, now_ns), brake_source_ns=self.aol_honda_brake_source(CS, now_ns),
|
||||
gm_withdrawal_source_ns=self.aol_gm_withdrawal_source(CS, now_ns),
|
||||
intent_producer_session=getattr(self, 'slc_producer_session', ''),
|
||||
main_arm_ns=(getattr(self.aol_card_intent, 'main_arm_ns', 0) or
|
||||
getattr(self.aol_card_intent, 'physical_arm_ns', 0)),
|
||||
startup_calibration_pending=getattr(self.aol_card_intent, 'startup_calibration_pending', False),
|
||||
intent_paused=(getattr(self.aol_card_intent, 'pause_lateral', False) or
|
||||
ford_brake_pause_active(self.CP, CS, self.aol_settings) or
|
||||
self.CP.brand == 'volkswagen' and CS.canValid and not CS.canTimeout and
|
||||
not CS.steerFaultPermanent and (CS.gearShifter == car.CarState.GearShifter.reverse or
|
||||
getattr(self.aol_card_intent, 'reverse_pause', False)))):
|
||||
return True
|
||||
events = self.sm['onroadEvents']
|
||||
if feedback.retention_qualified or feedback.retention_pending:
|
||||
from openpilot.starpilot.aol.transport_pause import AVAILABILITY_EVENTS
|
||||
@@ -973,9 +976,19 @@ class Car:
|
||||
startup_calibration_pending=bool(intent is not None and getattr(intent, 'startup_calibration_pending', False) and
|
||||
intent.settings.enabled and intent.main_action != 9),
|
||||
temporary_ui_process_failure=fault_context is not None and fault_context.temporary_ui_failure(event_ns, now_ns),
|
||||
temporary_selfdrive_lagging=True,
|
||||
temporary_selfdrive_lagging=(qualified_gm(self.CP) or aol_policy_for(self.CP).intent_supported),
|
||||
temporary_source_pause=(feedback.qualified or feedback.awaiting))
|
||||
|
||||
def aol_permission_owners(self) -> tuple[bool, bool, bool, bool, bool, bool]:
|
||||
# CP is fixed once the drive starts; these checks ran five times per 100 Hz frame.
|
||||
cached = getattr(self, '_aol_owner_cache', None)
|
||||
if cached is None or cached[0] is not self.CP:
|
||||
owners = (bool(qualified_angle_aol(self.CP, marked_only=True)), bool(qualified_ford_aol(self.CP, marked_only=True)),
|
||||
bool(qualified_honda_stock_aol(self.CP, marked_only=True)), bool(qualified_mazda_aol(self.CP, marked_only=True)),
|
||||
bool(qualified_tesla_preap(self.CP, marked_only=True)), bool(qualified_volkswagen_aol(self.CP, marked_only=True)))
|
||||
cached = self._aol_owner_cache = (self.CP, owners)
|
||||
return cached[1]
|
||||
|
||||
def aol_honda_native_observation(self, native, *, latched, panda_ready, restricted, now_ns, pending_since_ns):
|
||||
acknowledged = getattr(self, '_honda_aol_acknowledgment', None)
|
||||
key = None
|
||||
|
||||
@@ -22,7 +22,7 @@ from opendbc.car.toyota.values import CAR as TOYOTA_CAR, ToyotaFlags
|
||||
from opendbc.car.subaru.values import CAR as SUBARU_CAR, FROGGER_ANGLE_SIBLINGS
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, read_gain
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, predicted_lateral_accels, read_gain
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque
|
||||
from openpilot.selfdrive.controls.lib.lateral_controller_factory import create_lateral_controller
|
||||
@@ -62,6 +62,7 @@ from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePo
|
||||
from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate
|
||||
from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns
|
||||
from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported
|
||||
from openpilot.starpilot.lateral.parked_runtime import ParkedClearanceHost, runtime_supported as parked_runtime_supported
|
||||
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
|
||||
from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled
|
||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
||||
@@ -147,6 +148,7 @@ class Controls:
|
||||
optional = list(
|
||||
dict.fromkeys(
|
||||
self.longitudinal_inputs.optional_services + ['starpilotCarState', 'deviceState', 'autoSteeringLearning', 'starpilotSteeringTracking', 'pandaStates']
|
||||
+ (['radarTracks'] if parked_runtime_supported(self.CP) else [])
|
||||
)
|
||||
)
|
||||
if optional:
|
||||
@@ -198,6 +200,9 @@ class Controls:
|
||||
self.lane_centering_host = LaneCenteringHost(
|
||||
self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None,
|
||||
) if lane_runtime_supported(self.CP) else None
|
||||
self.parked_clearance_host = ParkedClearanceHost(
|
||||
self.params, settings_reader=(lambda: preferences.current.parked) if preferences is not None else None,
|
||||
) if parked_runtime_supported(self.CP) else None
|
||||
self.torque_host = (
|
||||
TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None))
|
||||
if torque_runtime_enabled(self.CP, self.params)
|
||||
@@ -661,7 +666,7 @@ class Controls:
|
||||
self.highway_gain = read_gain(self.params)
|
||||
predicted = None
|
||||
if self.sm.all_checks(['modelV2']):
|
||||
predicted = self.highway_correction_gain.predict(model_v2)
|
||||
predicted = predicted_lateral_accels(model_v2.position.t, model_v2.velocity.x, model_v2.orientationRate.z)
|
||||
# before lane centering so its guard measures only its own correction against the smoothed base
|
||||
new_desired_curvature = self.highway_correction_gain.update(
|
||||
new_desired_curvature,
|
||||
@@ -679,6 +684,11 @@ class Controls:
|
||||
steering_limited=self.steer_limited_by_safety,
|
||||
actuator_delay_s=lat_delay,
|
||||
)
|
||||
parked_clearance = getattr(self, 'parked_clearance_host', None)
|
||||
if parked_clearance is not None:
|
||||
new_desired_curvature += parked_clearance.update(
|
||||
self.sm, now_ns=int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns(),
|
||||
lateral_active=bool(CC.latActive), maneuver=bool(self.sm.valid['lateralManeuverPlan']))
|
||||
lane_base_curvature = new_desired_curvature
|
||||
self.lane_centering_applied = 0.0
|
||||
self.lane_centering_inactive_reason = 'inactive'
|
||||
@@ -715,6 +725,7 @@ class Controls:
|
||||
time_discontinuity=lane_centering.time_discontinuity,
|
||||
measured_curvature=self.curvature,
|
||||
lateral_delay_s=lane_delay,
|
||||
hold=bool(parked_clearance is not None and parked_clearance.shift > 0.0),
|
||||
)
|
||||
)
|
||||
self.last_lane_centering_result = result
|
||||
|
||||
@@ -75,17 +75,8 @@ class HighwayCorrectionGain:
|
||||
def __init__(self):
|
||||
self.alpha = DT_CTRL / (BASELINE_TAU + DT_CTRL)
|
||||
self.alpha_curve = DT_CTRL / (CURVE_LEVEL_TAU + DT_CTRL)
|
||||
self._prediction_model = None
|
||||
self._prediction = None
|
||||
self.reset()
|
||||
|
||||
def predict(self, model) -> tuple[float, ...] | None:
|
||||
# SubMaster retains the same immutable reader until another packet arrives.
|
||||
if model is not self._prediction_model:
|
||||
self._prediction = predicted_lateral_accels(model.position.t, model.velocity.x, model.orientationRate.z)
|
||||
self._prediction_model = model
|
||||
return self._prediction
|
||||
|
||||
def reset(self, curvature: float = 0.0) -> None:
|
||||
self.baseline = curvature
|
||||
self.curve_level = curvature
|
||||
|
||||
@@ -118,10 +118,13 @@ class Track:
|
||||
"radarTrackId": self.identifier,
|
||||
}
|
||||
|
||||
def potential_low_speed_lead(self, v_ego: float):
|
||||
def potential_low_speed_lead(self, v_ego: float, path: tuple[np.ndarray, np.ndarray] | None = None):
|
||||
# stop for stuff in front of you and low speed, even without model confirmation
|
||||
# Radar points closer than 0.75, are almost always glitches on toyota radars
|
||||
return abs(self.yRel) < 1.0 and (v_ego < V_EGO_STATIONARY) and (0.75 < self.dRel < 25)
|
||||
y_rel = self.yRel
|
||||
if path is not None and len(path[0]) and path[0][-1] >= self.dRel + RADAR_TO_CAMERA:
|
||||
y_rel += float(np.interp(self.dRel + RADAR_TO_CAMERA, path[0], path[1]))
|
||||
return abs(y_rel) < 1.0 and (v_ego < V_EGO_STATIONARY) and (0.75 < self.dRel < 25)
|
||||
|
||||
def __str__(self):
|
||||
ret = f"x: {self.dRel:4.1f} y: {self.yRel:4.1f} v: {self.vRel:4.1f} a: {self.aLeadK:4.1f}"
|
||||
@@ -174,7 +177,8 @@ def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: floa
|
||||
|
||||
|
||||
def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader,
|
||||
model_v_ego: float, lead_prob: float, low_speed_override: bool = True) -> dict[str, Any]:
|
||||
model_v_ego: float, lead_prob: float, low_speed_override: bool = True,
|
||||
path: tuple[np.ndarray, np.ndarray] | None = None) -> dict[str, Any]:
|
||||
# Determine leads, this is where the essential logic happens
|
||||
if len(tracks) > 0 and ready and lead_prob > .5:
|
||||
track = match_vision_to_track(v_ego, lead_msg, tracks)
|
||||
@@ -188,7 +192,7 @@ def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capn
|
||||
lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego, lead_prob)
|
||||
|
||||
if low_speed_override:
|
||||
low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego)]
|
||||
low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego, path)]
|
||||
if len(low_speed_tracks) > 0:
|
||||
closest_track = min(low_speed_tracks, key=lambda c: c.dRel)
|
||||
|
||||
@@ -199,6 +203,23 @@ def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capn
|
||||
return lead_dict
|
||||
|
||||
|
||||
def _has(message, field: str) -> bool:
|
||||
has = getattr(message, '_has', None)
|
||||
return has is None or bool(has(field))
|
||||
|
||||
|
||||
def model_path(model) -> tuple[np.ndarray, np.ndarray] | None:
|
||||
if not _has(model, 'position'):
|
||||
return None
|
||||
position = model.position
|
||||
if not _has(position, 'x') or not _has(position, 'y'):
|
||||
return None
|
||||
x, y = np.asarray(position.x, dtype=float), np.asarray(position.y, dtype=float)
|
||||
if len(x) < 2 or len(x) != len(y) or not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)) or np.any(np.diff(x) < 0):
|
||||
return None
|
||||
return x, y
|
||||
|
||||
|
||||
class RadarD:
|
||||
def __init__(self, delay: float = 0.0, *, adjacent_enabled: bool = False, radar_available: bool = False,
|
||||
clock_pair_fn=None, honda_bosch_a_radar: bool = False, use_voacc: bool = False):
|
||||
@@ -359,7 +380,8 @@ class RadarD:
|
||||
elif self.honda_bosch_a is not None:
|
||||
self.radar_state.leadOne, self.radar_state.leadTwo = self.honda_bosch_a.leads(sm, self, model_v_ego)
|
||||
else:
|
||||
self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.lead_prob_filters[0].x, low_speed_override=True)
|
||||
self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.lead_prob_filters[0].x,
|
||||
low_speed_override=True, path=model_path(sm['modelV2']))
|
||||
self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego,
|
||||
self.lead_prob_filters[1].x, low_speed_override=False)
|
||||
if self.adjacent_enabled:
|
||||
|
||||
@@ -2,7 +2,6 @@ import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.realtime import DT_CTRL
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import KEY, HighwayCorrectionGain, predicted_lateral_accels, read_gain
|
||||
|
||||
@@ -169,26 +168,6 @@ def test_gain_is_clamped():
|
||||
np.testing.assert_allclose(low, floor, rtol=0, atol=1e-15)
|
||||
|
||||
|
||||
def test_prediction_reuses_only_the_same_model_packet():
|
||||
hcg = HighwayCorrectionGain()
|
||||
|
||||
def packet(yaw_rate):
|
||||
msg = messaging.new_message('modelV2')
|
||||
msg.modelV2.position.t = [0., 2.]
|
||||
msg.modelV2.velocity.x = [30., 30.]
|
||||
msg.modelV2.orientationRate.z = [yaw_rate, yaw_rate]
|
||||
return msg.as_reader().modelV2
|
||||
|
||||
first = packet(0.03125)
|
||||
second = packet(0.0625)
|
||||
predicted = hcg.predict(first)
|
||||
assert predicted == (0.9375, 0.9375)
|
||||
hcg.reset()
|
||||
assert hcg.predict(first) is predicted
|
||||
assert hcg.predict(second) == (1.875, 1.875)
|
||||
assert hcg.predict(messaging.new_message('modelV2').as_reader().modelV2) is None
|
||||
|
||||
|
||||
def test_predicted_lateral_accels():
|
||||
t = 10.0 * (np.arange(33) / 32) ** 2
|
||||
assert predicted_lateral_accels(t, np.full(33, 30.0), np.full(33, 0.02)) == (0.6, 0.6)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import numpy as np
|
||||
from types import SimpleNamespace as NS
|
||||
|
||||
from openpilot.selfdrive.controls.radard import KalmanParams, Track, get_lead, model_path
|
||||
|
||||
XS = np.linspace(0., 30., 33)
|
||||
|
||||
|
||||
def stopped(d=8., y=0.):
|
||||
track = Track(1, 0., KalmanParams(.05))
|
||||
track.update(d, y, -2., 0.)
|
||||
return track
|
||||
|
||||
|
||||
def lead(path, track=None):
|
||||
model = NS(x=[0.] * 6, y=[0.] * 6, v=[0.] * 6, a=[0.] * 6, xStd=[1.] * 6, yStd=[1.] * 6, vStd=[1.] * 6, aStd=[1.] * 6)
|
||||
return get_lead(2., True, {1: track or stopped()}, model, 2., 0., low_speed_override=True, path=path)
|
||||
|
||||
|
||||
def test_low_speed_override_follows_a_turning_path():
|
||||
assert not lead((XS, -XS ** 2 / 12.))['present']
|
||||
|
||||
|
||||
def test_low_speed_override_keeps_objects_in_path():
|
||||
assert lead((XS, np.zeros_like(XS)))['present']
|
||||
assert lead((XS, -XS ** 2 / 12.), stopped(8., 9.52 ** 2 / 12.))['present']
|
||||
assert lead(None)['present']
|
||||
|
||||
|
||||
def test_short_or_invalid_path_falls_back_to_straight_ahead():
|
||||
assert lead((np.linspace(0., 2., 33), np.linspace(0., -5., 33)))['present']
|
||||
assert model_path(NS(position=NS(x=[0., 1.], y=[0., float('nan')]))) is None
|
||||
assert model_path(NS(position=NS(x=[1., 0.], y=[0., 0.]))) is None
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -32,7 +32,6 @@ def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True, *, source_observe
|
||||
Args:
|
||||
can_msgs: List of tuples [(address, data_bytes, src), ...]
|
||||
msgtype: 'can' or 'sendcan'
|
||||
include_tx_receipts: retain Panda TX receipts (sources 128 and above)
|
||||
valid: Whether the event is valid
|
||||
|
||||
Returns:
|
||||
@@ -65,13 +64,12 @@ def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True, *, source_observe
|
||||
return dat.to_bytes()
|
||||
|
||||
|
||||
def can_capnp_to_list(strings, msgtype='can', *, include_tx_receipts=True):
|
||||
def can_capnp_to_list(strings, msgtype='can'):
|
||||
"""Convert Cap'n Proto serialized bytes to list of CAN messages.
|
||||
|
||||
Args:
|
||||
strings: Tuple/list of serialized Cap'n Proto bytes
|
||||
msgtype: 'can' or 'sendcan'
|
||||
include_tx_receipts: retain Panda TX receipts (sources 128 and above)
|
||||
|
||||
Returns:
|
||||
List of tuples [(nanos, [(address, data, src), ...]), ...]
|
||||
@@ -89,14 +87,7 @@ def can_capnp_to_list(strings, msgtype='can', *, include_tx_receipts=True):
|
||||
|
||||
if _cached_reader_fields is not None:
|
||||
addr_f, dat_f, src_f = _cached_reader_fields
|
||||
if include_tx_receipts:
|
||||
frame_list = [(f._get_by_field(addr_f), f._get_by_field(dat_f), f._get_by_field(src_f)) for f in frames]
|
||||
else:
|
||||
frame_list = []
|
||||
for f in frames:
|
||||
src = f._get_by_field(src_f)
|
||||
if src < 128:
|
||||
frame_list.append((f._get_by_field(addr_f), f._get_by_field(dat_f), src))
|
||||
frame_list = [(f._get_by_field(addr_f), f._get_by_field(dat_f), f._get_by_field(src_f)) for f in frames]
|
||||
else:
|
||||
frame_list = []
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
|
||||
|
||||
|
||||
def test_optional_receipt_filter_preserves_physical_frames_and_batch_stamps():
|
||||
frames = [(0x340, b'physical', 0), (0x340, b'returned', 128),
|
||||
(0x421, b'physical', 2), (0x421, b'rejected', 194)]
|
||||
receipts = [frames[1], frames[3]]
|
||||
packets = [can_list_to_can_capnp(batch) for batch in (frames, receipts, [])]
|
||||
stamps = [int(messaging.log_from_bytes(packet).logMonoTime) for packet in packets]
|
||||
|
||||
assert can_capnp_to_list(packets) == list(zip(stamps, (frames, receipts, []), strict=True))
|
||||
assert can_capnp_to_list(packets, include_tx_receipts=False) == list(zip(stamps, ([frames[0], frames[2]], [], []), strict=True))
|
||||
@@ -17,38 +17,6 @@ from openpilot.starpilot.car.volkswagen.aol import temporary_restriction as volk
|
||||
from openpilot.starpilot.car.volvo.aol import (native_observation as volvo_native_observation,
|
||||
temporary_restriction as volvo_temporary_restriction)
|
||||
|
||||
from openpilot.starpilot.car.volkswagen.aol import qualified as qualified_volkswagen_aol
|
||||
from opendbc.car.rivian.stock_aol import qualified as qualified_rivian_aol
|
||||
from opendbc.car.mazda.stock_aol import qualified as qualified_mazda_aol
|
||||
from opendbc.car.hyundai.canfd_angle_aol import qualified as qualified_angle_aol
|
||||
from openpilot.starpilot.car.nissan.aol import qualified as qualified_nissan_aol
|
||||
from openpilot.starpilot.car.volvo.aol import qualified as qualified_volvo_aol
|
||||
from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol
|
||||
from opendbc.car.tesla.preap.aol import qualified as qualified_tesla_preap
|
||||
from openpilot.starpilot.car.ford.aol import qualified as qualified_ford_aol
|
||||
from openpilot.starpilot.aol.vehicle import policy_for
|
||||
|
||||
|
||||
def aol_configuration(card):
|
||||
cp = card.CP
|
||||
cached = getattr(card, '_aol_configuration', None)
|
||||
if cached is None or cached[0] is not cp:
|
||||
angle = qualified_angle_aol(cp, marked_only=True)
|
||||
ford = qualified_ford_aol(cp, marked_only=True)
|
||||
honda = qualified_honda_stock_aol(cp, marked_only=True)
|
||||
mazda = qualified_mazda_aol(cp, marked_only=True)
|
||||
preap = qualified_tesla_preap(cp, marked_only=True)
|
||||
volkswagen = qualified_volkswagen_aol(cp, marked_only=True)
|
||||
nissan = qualified_nissan_aol(cp, marked_only=True)
|
||||
rivian = qualified_rivian_aol(cp, marked_only=True)
|
||||
volvo = qualified_volvo_aol(cp, marked_only=True)
|
||||
owners = (angle, ford, honda, mazda, preap, volkswagen, rivian)
|
||||
handlers = native_handlers(card, volvo_aol=volvo, rivian_aol=rivian, volkswagen_aol=volkswagen,
|
||||
nissan_aol=nissan, preap_aol=preap, mazda_aol=mazda, honda_aol=honda,
|
||||
ford_aol=ford) if any(owners) or nissan or volvo else None
|
||||
cached = card._aol_configuration = (cp, (policy_for(cp), owners, handlers))
|
||||
return cached[1]
|
||||
|
||||
|
||||
def native_handlers(card, *, volvo_aol: bool, rivian_aol: bool, volkswagen_aol: bool, nissan_aol: bool, preap_aol: bool,
|
||||
mazda_aol: bool, honda_aol: bool, ford_aol: bool):
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
from types import SimpleNamespace
|
||||
from itertools import product
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.ford import aol as ford
|
||||
from opendbc.car.honda import stock_aol as honda
|
||||
from opendbc.car.hyundai import canfd_angle_aol as hyundai
|
||||
@@ -14,7 +12,7 @@ from opendbc.car.volkswagen import stock_aol as volkswagen_observer
|
||||
from openpilot.starpilot.car.nissan import aol as nissan
|
||||
from openpilot.starpilot.car.volkswagen import aol as volkswagen_restriction
|
||||
from openpilot.starpilot.car.volvo import aol as volvo
|
||||
from openpilot.starpilot.aol.card_native import aol_configuration, native_handlers
|
||||
from openpilot.starpilot.aol.card_native import native_handlers
|
||||
|
||||
|
||||
class _Card:
|
||||
@@ -43,18 +41,3 @@ def test_native_handlers_keep_card_priority_and_lazy_honda_binding(admitted):
|
||||
selected = native_handlers(card, **dict(zip(names, admitted, strict=True)))
|
||||
assert selected == (observations[expected], restrictions[expected])
|
||||
assert card.honda_lookups == int(expected == 6)
|
||||
|
||||
|
||||
|
||||
def test_aol_configuration_binds_only_finalized_car_params():
|
||||
card = SimpleNamespace(CP=structs.CarParams(brand='ford', carFingerprint='FORD_MAVERICK_MK1', flags=2,
|
||||
transmissionType='automatic', steerControlType='angle', pcmCruise=True,
|
||||
safetyConfigs=[{'safetyModel': 'ford', 'safetyParam': 16384}], alternativeExperience=32))
|
||||
first = aol_configuration(card)
|
||||
assert first[2] == (ford.native_observation, ford.temporary_restriction)
|
||||
assert aol_configuration(card) is first
|
||||
card.CP = structs.CarParams(brand='mock', passive=True)
|
||||
second = aol_configuration(card)
|
||||
assert second is not first
|
||||
assert second[2] is None
|
||||
assert not second[0].intent_supported
|
||||
|
||||
@@ -27,7 +27,6 @@ def test_all_gm_initializing_steps_keep_servicing_handoff(cp):
|
||||
state_update=Mock(return_value=(cs, None)), state_publish=Mock(),
|
||||
controls_update=Mock(), _deferred_radar_can=None,
|
||||
radar_update=Mock(), radar_publish=Mock())
|
||||
card._step = Car._step.__get__(card)
|
||||
events = [SimpleNamespace(name=1)]
|
||||
card.sm = type('SM', (), {'seen': {'onroadEvents': True}, '__getitem__': lambda _, key: events if key == 'onroadEvents' else None})()
|
||||
for method in ('gm_startup_keepalive', 'volt_startup_keepalive', 'volt_sdgm_startup_keepalive'):
|
||||
|
||||
@@ -39,11 +39,11 @@ def native_template(tmp_path_factory, request):
|
||||
timers = (ROOT / 'panda/board/drivers/timers.h').read_text()
|
||||
timer_check = timers[timers.index('bool timer_check('):timers.index('\nvoid interrupt_timer_init(')]
|
||||
interrupts = (ROOT / 'panda/board/drivers/interrupts.h').read_text()
|
||||
interrupts = interrupts[interrupts.index('static void unused_interrupt_handler'):interrupts.index('#endif // BOARD_DRIVERS_INTERRUPTS_H')]
|
||||
interrupts = interrupts[interrupts.index('static void unused_interrupt_handler'):]
|
||||
sys = (ROOT / 'panda/board/sys/sys.h').read_text()
|
||||
faults = sys[sys.index('#define FAULT_STATUS_NONE'):sys.index('// ******************** power_saving')]
|
||||
fault_impl = (ROOT / 'panda/board/sys/faults.h').read_text()
|
||||
faults += fault_impl[fault_impl.index('uint8_t fault_status'):fault_impl.index('#endif // BOARD_SYS_FAULTS_H')]
|
||||
faults += fault_impl[fault_impl.index('uint8_t fault_status'):]
|
||||
code = r'''
|
||||
#include "opendbc/safety/tests/libsafety/safety.c"
|
||||
uint32_t heartbeat_counter, heartbeat_tick_counter, uptime_cnt, ignition_can_cnt, wake_on_can_cnt;
|
||||
|
||||
@@ -1181,8 +1181,7 @@ class TransportPauseFeedback:
|
||||
self.retention_pending = False
|
||||
try:
|
||||
axis = sm['aolAxisState']
|
||||
same_cp = cp_identity(cp) == self.cp
|
||||
if not latched or not same_cp or self.session and str(axis.sessionId) != self.session:
|
||||
if not latched or cp_identity(cp) != self.cp or self.session and str(axis.sessionId) != self.session:
|
||||
self.fit_eps_intent = self.fit_eps_grant = None
|
||||
self.ordinary_warning_retained = False
|
||||
self.ordinary_brake_proof = None
|
||||
@@ -1208,7 +1207,7 @@ class TransportPauseFeedback:
|
||||
axis.qualified and axis.sessionId and axis.sequence > 0 and stamp == axis.observedMonoTime and
|
||||
0 < stamp <= now_ns <= axis.validUntilMonoTime and now_ns - stamp <= AXIS_MAX_AGE_NS and
|
||||
axis.validUntilMonoTime - stamp <= AXIS_MAX_AGE_NS and axis.faultSessionId == axis.sessionId and
|
||||
same_cp)
|
||||
cp_identity(cp) == self.cp)
|
||||
continuity = bool(not self.session or axis.sessionId == self.session and
|
||||
(axis.sequence > self.sequence or axis.sequence == self.sequence and signature == self.signature))
|
||||
pending_paddle = self.subaru_paddle_denial
|
||||
|
||||
@@ -45,6 +45,9 @@ DESCRIPTIONS = {
|
||||
'LaneCenteringPauseOnSignal': 'Pauses lane-centering correction while a turn signal is on.',
|
||||
'LaneCenterOffset': 'Moves the lane-centering target left or right of the detected lane center.',
|
||||
'LaneCenteringE2EAuthority': 'Lets a confident driving-model path reduce lane-centering correction when the model path differs from the lane center.',
|
||||
'ParkedClearance': 'Leaves extra room beside parked cars detected by radar. Adds nothing when no parked car is detected.',
|
||||
'ParkedClearanceGap': 'The room to aim for beside a parked car. The car moves left only as far as needed to reach it.',
|
||||
'ParkedClearanceShift': 'The most the car will move left for a parked car, even if the target gap is not reached.',
|
||||
'LaneCenteringStrength': 'Sets the strength of lane-centering correction. 100% is normal; higher values strengthen it.',
|
||||
'PauseLateralSpeed': 'Pauses steering assistance below this speed. Zero disables the speed-based pause.',
|
||||
'PauseLateralOnSignal': 'Limits the low-speed steering pause to times when a turn signal is on.',
|
||||
|
||||
@@ -78,6 +78,9 @@
|
||||
"PIPPreviewInvert",
|
||||
"PIPPreviewShowOnBSM",
|
||||
"PIPPreviewShowOnBlinker",
|
||||
"ParkedClearance",
|
||||
"ParkedClearanceGap",
|
||||
"ParkedClearanceShift",
|
||||
"PauseLateralOnSignal",
|
||||
"PauseLateralSpeed",
|
||||
"PromptDistractedVolume",
|
||||
|
||||
@@ -148,9 +148,7 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
self.assertEqual(status, 200)
|
||||
self.assertTrue(laboratory['runtimeSupported'])
|
||||
self.assertFalse(laboratory['runtime']['active'])
|
||||
published = {row['value'] for row in laboratory['models'] if row['modelLabArtifactAvailable']}
|
||||
self.assertLessEqual({'gwm8223', 'sc23'}, published)
|
||||
self.assertEqual(laboratory['summary']['published'], len(published))
|
||||
self.assertEqual(laboratory['summary']['published'], 92)
|
||||
pair = {'enabled': False, 'lateralModel': 'gwm8223', 'longitudinalModel': 'sc23'}
|
||||
self.assertEqual(request('/api/models/laboratory', pair)[0], 200)
|
||||
self.assertEqual(request('/api/models/laboratory', {**pair, 'enabled': True})[0], 409)
|
||||
|
||||
@@ -1312,6 +1312,35 @@ class SettingsGatewayTest(SettingsGatewayFixture):
|
||||
self.assertTrue(_onroad_preference("lane", key))
|
||||
self.assertFalse(_onroad_preference("torque", "reset_profiles"))
|
||||
|
||||
def test_parked_clearance_needs_radar_and_master_switch(self):
|
||||
def row(label):
|
||||
page = self.page("lane")
|
||||
index = next(i for i, item in enumerate(page["rows"]) if item["label"] == label)
|
||||
return page, index, page["rows"][index]
|
||||
self.assertFalse(row("Parked car clearance")[2]["available"])
|
||||
cp = SimpleNamespace(**vars(self.context.value.cp), radarUnavailable=False)
|
||||
self.context.value = AuthorityContext(True, cp, b"radar")
|
||||
page, index, toggle = row("Parked car clearance")
|
||||
self.assertTrue(toggle["available"])
|
||||
self.assertEqual(toggle["value"], "Off")
|
||||
self.assertFalse(row("Parked car target gap")[2]["available"])
|
||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value="On")
|
||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
||||
self.assertEqual(Path(self.params.get_param_path("ParkedClearance")).read_bytes(), b"1")
|
||||
page, index, gap = row("Parked car target gap")
|
||||
self.assertTrue(gap["available"])
|
||||
self.assertEqual((gap["value"], gap["minimum"], gap["maximum"], gap["unit"]), ("1.5", 1.0, 2.5, "m"))
|
||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=1.8)
|
||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
||||
self.assertEqual(Path(self.params.get_param_path("ParkedClearanceGap")).read_bytes(), b"1.8")
|
||||
from openpilot.starpilot.lateral.parked_runtime import ParkedSettings, read_settings
|
||||
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8))
|
||||
page, index, shift = row("Parked car max shift")
|
||||
self.assertEqual((shift["value"], shift["minimum"], shift["maximum"], shift["unit"]), ("0.3", 0.1, 0.8, "m"))
|
||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=0.45)
|
||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
||||
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8, 0.45))
|
||||
|
||||
def test_live_lane_rejects_unsupported_vehicle_and_master_dependency(self):
|
||||
self.params.put_bool("LaneCentering", False, block=True)
|
||||
tagged, _ = self._live_lane_context()
|
||||
|
||||
@@ -48,7 +48,7 @@ def supported_cp(CP):
|
||||
|
||||
TOYOTA_COROLLA_TSS2_PHASE_SCALE = 0.12
|
||||
TOYOTA_COROLLA_TSS2_TURN_IN_FF_BOOST = 0.035
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_FF_REDUCTION = 0.06
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_FF_REDUCTION = 0.12
|
||||
TOYOTA_COROLLA_TSS2_CURVE_LAT_ONSET = 0.24
|
||||
TOYOTA_COROLLA_TSS2_CURVE_LAT_WIDTH = 0.1
|
||||
TOYOTA_COROLLA_TSS2_SPEED_ONSET = 4.0
|
||||
@@ -69,6 +69,23 @@ TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_LAT = 0.24
|
||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_LAT_WIDTH = 0.1
|
||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK = 0.25
|
||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH = 0.1
|
||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_GAIN = 0.5
|
||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT = 0.5
|
||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT_WIDTH = 0.15
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN = 12.0
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_BLEND_TAU = 0.15
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET = 1.5
|
||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET_WIDTH = 0.5
|
||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_SECONDS = 1.5
|
||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_WN = 2.0
|
||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT = 0.3
|
||||
TOYOTA_COROLLA_TSS2_FIRM_PRESS_SECONDS = 0.3
|
||||
TOYOTA_COROLLA_TSS2_CARRY_RISE_SECONDS = 0.4
|
||||
TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS = 0.2
|
||||
TOYOTA_COROLLA_TSS2_CARRY_DRIVER_TORQUE_SCALE = 250.0
|
||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RATE = 0.8
|
||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX = 0.4
|
||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RELEASE_SECONDS = 1.0
|
||||
|
||||
|
||||
def get_toyota_corolla_tss2_ff_scale(desired_lateral_accel: float, desired_lateral_jerk: float, v_ego: float) -> float:
|
||||
@@ -87,6 +104,17 @@ def get_toyota_corolla_tss2_ff_scale(desired_lateral_accel: float, desired_later
|
||||
return 1.0 + curve_weight * speed_weight * (boost * turn_in_weight - unwind_reduction * unwind_weight)
|
||||
|
||||
|
||||
def get_toyota_corolla_tss2_unwind_weight(desired_lateral_accel: float, desired_lateral_jerk: float, v_ego: float) -> float:
|
||||
if desired_lateral_accel == 0.0:
|
||||
return 0.0
|
||||
phase = math.tanh(desired_lateral_accel * desired_lateral_jerk / TOYOTA_COROLLA_TSS2_PHASE_SCALE)
|
||||
curve_weight = _sigmoid((abs(desired_lateral_accel) - TOYOTA_COROLLA_TSS2_CURVE_LAT_ONSET) / TOYOTA_COROLLA_TSS2_CURVE_LAT_WIDTH)
|
||||
speed_weight = _sigmoid((v_ego - TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET) / TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET_WIDTH) * _sigmoid(
|
||||
(TOYOTA_COROLLA_TSS2_SPEED_CUTOFF - v_ego) / TOYOTA_COROLLA_TSS2_SPEED_CUTOFF_WIDTH
|
||||
)
|
||||
return curve_weight * speed_weight * max(-phase, 0.0)
|
||||
|
||||
|
||||
def get_toyota_corolla_tss2_friction_threshold(v_ego: float, desired_lateral_accel: float = 0.0, desired_lateral_jerk: float = 0.0) -> float:
|
||||
"""Reduce center-only friction chasing on highway-sized model corrections."""
|
||||
speed_weight = _sigmoid(
|
||||
@@ -98,8 +126,12 @@ def get_toyota_corolla_tss2_friction_threshold(v_ego: float, desired_lateral_acc
|
||||
calm_weight = _sigmoid(
|
||||
(TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK - abs(desired_lateral_jerk)) / TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH
|
||||
)
|
||||
curve_weight = _sigmoid(
|
||||
(abs(desired_lateral_accel) - TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT) / TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT_WIDTH
|
||||
)
|
||||
gain = TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_GAIN
|
||||
return get_standard_friction_threshold(v_ego) * (1.0 + gain * speed_weight * center_weight * calm_weight)
|
||||
curve_gain = TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_GAIN
|
||||
return get_standard_friction_threshold(v_ego) * (1.0 + gain * speed_weight * center_weight * calm_weight + curve_gain * curve_weight)
|
||||
|
||||
|
||||
def get_toyota_corolla_tss2_center_output_scale(desired_lateral_accel: float, v_ego: float) -> float:
|
||||
@@ -125,6 +157,14 @@ class CorollaTSS2TorquePolicy:
|
||||
self.previous_measurement = 0.0
|
||||
self.prev_desired_lateral_accel = 0.0
|
||||
self.prev_steering_pressed = False
|
||||
self.unwind_target = 0.0
|
||||
self.unwind_target_rate = 0.0
|
||||
self.unwind_blend = FirstOrderFilter(0.0, TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_BLEND_TAU, self.dt)
|
||||
self.release_hold = 0.0
|
||||
self.carry = 0.0
|
||||
self.carry_assist = 0.0
|
||||
self.press_seconds = 0.0
|
||||
self.prev_firm_press = False
|
||||
self.low_speed_reset_threshold = max(CP.minSteerSpeed, 0.3)
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
@@ -140,12 +180,22 @@ class CorollaTSS2TorquePolicy:
|
||||
self.previous_measurement = measurement
|
||||
self.measurement_rate_filter.x = 0.0
|
||||
self.jerk_filter.x = 0.0
|
||||
self.unwind_target = future_desired_lateral_accel
|
||||
self.unwind_target_rate = 0.0
|
||||
self.unwind_blend.x = 0.0
|
||||
self.release_hold = 0.0
|
||||
self.carry = 0.0
|
||||
self.carry_assist = 0.0
|
||||
self.press_seconds = 0.0
|
||||
self.prev_firm_press = False
|
||||
self.prev_desired_lateral_accel = future_desired_lateral_accel
|
||||
self.prev_steering_pressed = CS.steeringPressed
|
||||
pid_log.active = False
|
||||
return 0.0, 0.0, pid_log
|
||||
|
||||
if self.prev_steering_pressed and not CS.steeringPressed:
|
||||
self.press_seconds = self.press_seconds + self.dt if CS.steeringPressed else 0.0
|
||||
firm_press = self.press_seconds >= TOYOTA_COROLLA_TSS2_FIRM_PRESS_SECONDS
|
||||
if self.prev_firm_press and not firm_press:
|
||||
parent.pid.i *= 0.8
|
||||
roll_offset_fade = float(np.interp(CS.vEgo, FF_ROLL_OFFSET_FADE_BP, FF_ROLL_OFFSET_FADE_V))
|
||||
roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY * roll_offset_fade
|
||||
@@ -161,6 +211,39 @@ class CorollaTSS2TorquePolicy:
|
||||
desired_lateral_jerk = float(np.clip(self.jerk_filter.update(raw_lateral_jerk), -MAX_LAT_JERK_UP, MAX_LAT_JERK_UP))
|
||||
gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation
|
||||
setpoint = expected_lateral_accel + desired_lateral_jerk * lat_delay
|
||||
in_turn = abs(measurement) > TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT and CS.vEgo < TOYOTA_COROLLA_TSS2_SPEED_CUTOFF
|
||||
if firm_press and not self.prev_firm_press:
|
||||
self.carry = max(self.carry, self.release_hold)
|
||||
if firm_press and in_turn:
|
||||
self.carry = min(self.carry + self.dt / TOYOTA_COROLLA_TSS2_CARRY_RISE_SECONDS, 1.0)
|
||||
driver = float(np.clip(-float(getattr(CS, 'steeringTorque', 0.0)) / TOYOTA_COROLLA_TSS2_CARRY_DRIVER_TORQUE_SCALE, -1.0, 1.0))
|
||||
if driver * measurement > 0.0:
|
||||
self.carry_assist += TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RATE * driver * self.dt
|
||||
else:
|
||||
self.carry_assist *= 1.0 - self.dt / TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS
|
||||
self.carry_assist = float(np.clip(self.carry_assist, -TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX, TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX))
|
||||
else:
|
||||
self.carry = max(self.carry - self.dt / TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS, 0.0)
|
||||
fall = TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS if firm_press else TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RELEASE_SECONDS
|
||||
self.carry_assist *= 1.0 - self.dt / fall
|
||||
if firm_press:
|
||||
self.unwind_target = measurement
|
||||
self.unwind_target_rate = 0.0
|
||||
self.release_hold = 0.0
|
||||
elif self.prev_firm_press and abs(measurement) > TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT and CS.vEgo < TOYOTA_COROLLA_TSS2_SPEED_CUTOFF:
|
||||
self.release_hold = 1.0
|
||||
else:
|
||||
self.release_hold = max(self.release_hold - self.dt / TOYOTA_COROLLA_TSS2_RELEASE_HOLD_SECONDS, 0.0)
|
||||
wn = TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN + (TOYOTA_COROLLA_TSS2_RELEASE_HOLD_WN - TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN) * self.release_hold
|
||||
self.unwind_target_rate += (wn * wn * (setpoint - self.unwind_target) - 2.0 * wn * self.unwind_target_rate) * self.dt
|
||||
self.unwind_target += self.unwind_target_rate * self.dt
|
||||
unwind_blend = self.unwind_blend.update(get_toyota_corolla_tss2_unwind_weight(setpoint, desired_lateral_jerk, CS.vEgo))
|
||||
if firm_press:
|
||||
unwind_offset = self.carry * (measurement - setpoint)
|
||||
else:
|
||||
unwind_offset = max(unwind_blend, self.release_hold) * (self.unwind_target - setpoint)
|
||||
setpoint += unwind_offset
|
||||
gravity_adjusted_future_lateral_accel += unwind_offset + self.carry_assist
|
||||
desired_lateral_accel_magnitude_rate = (abs(setpoint) - abs(self.prev_desired_lateral_accel)) / self.dt
|
||||
unwind_detected = desired_lateral_accel_magnitude_rate < UNWIND_D_DES_THRESHOLD and abs(setpoint) < UNWIND_LAT_ACCEL_NEAR_ZERO
|
||||
self.prev_desired_lateral_accel = setpoint
|
||||
@@ -200,4 +283,5 @@ class CorollaTSS2TorquePolicy:
|
||||
pid_log.desiredLateralJerk = float(desired_lateral_jerk)
|
||||
pid_log.saturated = bool(parent._check_saturation(parent.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
|
||||
self.prev_steering_pressed = CS.steeringPressed
|
||||
self.prev_firm_press = firm_press
|
||||
return -output_torque, 0.0, pid_log
|
||||
|
||||
@@ -92,6 +92,7 @@ class LaneCenteringInput:
|
||||
time_discontinuity: bool = False
|
||||
measured_curvature: float | None = None
|
||||
lateral_delay_s: float | None = None
|
||||
hold: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -407,6 +408,9 @@ class LaneCenteringController:
|
||||
if settings.pause_on_signal and observation.turn_signal_active:
|
||||
self._tracker.reset()
|
||||
return self._fade(base, dt, "signal_release")
|
||||
if observation.hold is True:
|
||||
self._tracker.reset()
|
||||
return self._fade(base, dt, "parked_clearance")
|
||||
self._position_clock += dt
|
||||
# Filtering runs per control tick, including repeated model samples.
|
||||
geometry = _reader_geometry_key(observation.model)
|
||||
|
||||
@@ -7,6 +7,7 @@ from openpilot.selfdrive.controls.lib.highway_correction_gain import read_gain
|
||||
from openpilot.starpilot.lateral.lane_runtime import read_settings
|
||||
from openpilot.starpilot.lateral.lane_centering import LaneCenteringSettings
|
||||
from openpilot.starpilot.lateral.lane_change_preferences import read_saved, SavedLaneChange
|
||||
from openpilot.starpilot.lateral.parked_runtime import ParkedSettings, read_settings as read_parked
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,6 +15,7 @@ class SteeringPreferences:
|
||||
highway_gain: float
|
||||
lane_centering: LaneCenteringSettings
|
||||
lane_change: SavedLaneChange
|
||||
parked: ParkedSettings
|
||||
|
||||
|
||||
class LiveSteeringPreferences:
|
||||
@@ -26,7 +28,7 @@ class LiveSteeringPreferences:
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
def _read(self):
|
||||
return SteeringPreferences(read_gain(self.params), read_settings(self.params), read_saved(self.params))
|
||||
return SteeringPreferences(read_gain(self.params), read_settings(self.params), read_saved(self.params), read_parked(self.params))
|
||||
|
||||
def start(self):
|
||||
if self._thread is None:
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Left shift request beside stationary radar tracks on the right.
|
||||
|
||||
The caller owns freshness, lateral authority and final curvature limiting.
|
||||
This module neither reads settings nor sends commands.
|
||||
"""
|
||||
|
||||
from bisect import bisect_left
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
|
||||
MIN_SPEED = 4.5
|
||||
MAX_SPEED = 12.5
|
||||
STATIONARY_SPEED = 1.5
|
||||
MIN_DISTANCE = 4.0
|
||||
MAX_DISTANCE = 35.0
|
||||
MIN_LATERAL = 1.5
|
||||
MAX_LATERAL = 4.3
|
||||
TRACK_LATERAL = 6.0
|
||||
CONFIRM_SECONDS = 0.4
|
||||
TRACK_GAP_SECONDS = 0.2
|
||||
HOLD_SECONDS = 0.6
|
||||
LATERAL_TAU = 0.15
|
||||
EGO_HALF_WIDTH = 0.9
|
||||
OBJECT_HALF_WIDTH = 0.9
|
||||
MAX_GAP = 2.5
|
||||
MAX_SHIFT = 0.3
|
||||
MIN_LIMIT = 0.1
|
||||
MAX_LIMIT = 0.8
|
||||
RISE_RATE = 0.4
|
||||
FALL_RATE = 0.15
|
||||
ROOM_FALL_RATE = 1.0
|
||||
ROOM_HOLD_SECONDS = 0.5
|
||||
MIN_LINE_SPACING = 0.9
|
||||
ONCOMING_LINE_SPACING = 1.1
|
||||
MIN_EDGE_SPACING = 1.5
|
||||
LINE_PROB = 0.5
|
||||
LINE_STD = 0.3
|
||||
NO_LINE_PROB = 0.2
|
||||
UNCERTAIN_LINE_MARGIN = 0.5
|
||||
MAX_EDGE_STD = 1.5
|
||||
ONCOMING_SPEED = -2.0
|
||||
ONCOMING_LATERAL = 4.5
|
||||
ONCOMING_DISTANCE = 120.0
|
||||
ROADSIDE_LATERAL = 2.0
|
||||
MAX_ROADSIDE_EDGE_STD = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RadarPoint:
|
||||
identifier: int
|
||||
distance: float
|
||||
lateral: float
|
||||
speed: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Track:
|
||||
age: float
|
||||
unseen: float
|
||||
lateral: float
|
||||
|
||||
|
||||
def path_lateral(path_x, path_y, distance: float, y_rel: float) -> float | None:
|
||||
"""Metres right of the planned path for a radar point with left-positive yRel."""
|
||||
if len(path_x) < 2 or len(path_x) != len(path_y) or not path_x[0] <= distance <= path_x[-1]:
|
||||
return None
|
||||
index = max(1, bisect_left(path_x, distance))
|
||||
span = path_x[index] - path_x[index - 1]
|
||||
if span <= 0:
|
||||
return None
|
||||
ratio = (distance - path_x[index - 1]) / span
|
||||
value = -y_rel - (path_y[index - 1] + ratio * (path_y[index] - path_y[index - 1]))
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
def on_road(lateral: float, edge: float | None, edge_std: float) -> bool:
|
||||
"""Far targets at or beyond a confident right road edge are roadside objects."""
|
||||
if lateral <= ROADSIDE_LATERAL:
|
||||
return True
|
||||
if edge is None or not all(math.isfinite(v) for v in (lateral, edge, edge_std)):
|
||||
return False
|
||||
return edge_std > MAX_ROADSIDE_EDGE_STD or lateral < edge
|
||||
|
||||
|
||||
def oncoming_ahead(points) -> bool:
|
||||
return any(math.isfinite(p.distance) and math.isfinite(p.lateral) and math.isfinite(p.speed) and p.speed < ONCOMING_SPEED and
|
||||
-ONCOMING_LATERAL < p.lateral < 0 and 0 < p.distance < ONCOMING_DISTANCE for p in points)
|
||||
|
||||
|
||||
def left_room(line_spacing: float, line_prob: float, line_std: float, edge_spacing: float, edge_std: float, *, oncoming: bool = False) -> float:
|
||||
"""Metres the path may move left before the left line, or the left edge when no line is seen.
|
||||
|
||||
With oncoming traffic only a confident line grants room, at a wider spacing.
|
||||
"""
|
||||
if not all(math.isfinite(v) for v in (line_spacing, line_prob, line_std, edge_spacing, edge_std)) or line_std < 0 or edge_std < 0:
|
||||
return 0.0
|
||||
edge = edge_spacing - MIN_EDGE_SPACING - 2.0 * edge_std if edge_std <= MAX_EDGE_STD else 0.0
|
||||
confident = line_prob >= LINE_PROB and line_std <= LINE_STD
|
||||
if oncoming:
|
||||
return max(0.0, line_spacing - ONCOMING_LINE_SPACING) if confident else 0.0
|
||||
if line_prob < NO_LINE_PROB:
|
||||
return max(0.0, edge)
|
||||
line = line_spacing - MIN_LINE_SPACING
|
||||
if not confident:
|
||||
line -= min(line_std, UNCERTAIN_LINE_MARGIN)
|
||||
return max(0.0, min(line, edge))
|
||||
return max(0.0, line)
|
||||
|
||||
|
||||
class ParkedClearance:
|
||||
def __init__(self) -> None:
|
||||
self.tracks: dict[int, _Track] = {}
|
||||
self.shift = 0.0
|
||||
self.demand = 0.0
|
||||
self.hold = 0.0
|
||||
self.reason = 'inactive'
|
||||
self.rooms: list[tuple[float, float]] = []
|
||||
|
||||
def reset(self) -> None:
|
||||
self.tracks.clear()
|
||||
self.shift = 0.0
|
||||
self.demand = 0.0
|
||||
self.hold = 0.0
|
||||
self.reason = 'inactive'
|
||||
self.rooms = []
|
||||
|
||||
def _held_room(self, room: float, dt: float) -> float:
|
||||
self.rooms = [(age + dt, value) for age, value in self.rooms if age + dt <= ROOM_HOLD_SECONDS]
|
||||
self.rooms.append((0.0, room))
|
||||
return min(value for _, value in self.rooms)
|
||||
|
||||
def update(self, points, speed: float, dt: float, gap: float, room: float, active: bool, limit: float = MAX_SHIFT, watch: bool = False) -> float:
|
||||
values = (speed, dt, gap, room, limit)
|
||||
if not active or not all(type(v) in (int, float) and math.isfinite(v) for v in values) or dt <= 0 or gap <= 0 or limit <= 0:
|
||||
self.reset()
|
||||
return 0.0
|
||||
gap = min(gap, MAX_GAP)
|
||||
limit = min(limit, MAX_LIMIT)
|
||||
seen = set()
|
||||
for point in points:
|
||||
if not all(math.isfinite(v) for v in (point.distance, point.lateral, point.speed)):
|
||||
continue
|
||||
if (abs(point.speed) > STATIONARY_SPEED or not MIN_DISTANCE <= point.distance <= MAX_DISTANCE or
|
||||
not 0.0 <= point.lateral <= TRACK_LATERAL):
|
||||
continue
|
||||
seen.add(point.identifier)
|
||||
track = self.tracks.get(point.identifier)
|
||||
if track is None:
|
||||
self.tracks[point.identifier] = _Track(0.0, 0.0, point.lateral)
|
||||
continue
|
||||
track.unseen = 0.0
|
||||
track.lateral += (point.lateral - track.lateral) * (1.0 - math.exp(-dt / LATERAL_TAU))
|
||||
track.age = track.age + dt if MIN_LATERAL <= track.lateral <= MAX_LATERAL else 0.0
|
||||
for identifier in [i for i in self.tracks if i not in seen]:
|
||||
self.tracks[identifier].unseen += dt
|
||||
if self.tracks[identifier].unseen > TRACK_GAP_SECONDS:
|
||||
del self.tracks[identifier]
|
||||
if watch:
|
||||
self.shift, self.demand, self.hold, self.reason = 0.0, 0.0, 0.0, 'inactive'
|
||||
return 0.0
|
||||
confirmed = [t.lateral for i, t in self.tracks.items() if i in seen and t.age >= CONFIRM_SECONDS]
|
||||
if not MIN_SPEED <= speed <= MAX_SPEED:
|
||||
self.demand, self.hold, self.reason = 0.0, 0.0, 'speed'
|
||||
elif confirmed:
|
||||
self.demand = max(0.0, gap - (min(confirmed) - EGO_HALF_WIDTH - OBJECT_HALF_WIDTH))
|
||||
self.hold = HOLD_SECONDS
|
||||
self.reason = 'parked'
|
||||
elif self.hold > 0:
|
||||
self.hold = max(0.0, self.hold - dt)
|
||||
self.reason = 'hold'
|
||||
else:
|
||||
self.demand, self.reason = 0.0, 'clear'
|
||||
room = self._held_room(room, dt)
|
||||
cap = min(limit, max(0.0, room)) if self.reason != 'speed' else 0.0
|
||||
target = min(self.demand, cap)
|
||||
if target < self.demand and self.reason == 'parked' and room < min(self.demand, limit):
|
||||
self.reason = 'left_limited'
|
||||
if self.shift > cap:
|
||||
self.shift = max(cap, self.shift - ROOM_FALL_RATE * dt)
|
||||
step = target - self.shift
|
||||
self.shift += min(step, RISE_RATE * dt) if step > 0 else max(step, -FALL_RATE * dt)
|
||||
return self.shift
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Saved parked-clearance preferences and fresh radar, model and car inputs, off by default."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.cereal.services import SERVICE_LIST
|
||||
from openpilot.common.scalar_clip import clip_scalar
|
||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
||||
from openpilot.starpilot.lateral.parked_clearance import (
|
||||
MAX_GAP, MAX_LIMIT, MAX_SHIFT, MIN_LIMIT, ParkedClearance, RadarPoint, left_room, on_road, oncoming_ahead, path_lateral,
|
||||
)
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
|
||||
GAIN = 0.45
|
||||
MAX_CORRECTION = 0.009
|
||||
MAX_LATERAL_ACCEL = 0.7
|
||||
DEFAULT_GAP = 1.5
|
||||
DEFAULT_LIMIT = MAX_SHIFT
|
||||
MAX_RADAR_GAP_S = 0.25
|
||||
MAX_PATH_SLOPE = 0.1
|
||||
MAX_AGE_NS = {'carState': 100_000_000, 'modelV2': 200_000_000, 'radarTracks': 200_000_000}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ParkedSettings:
|
||||
enabled: bool = False
|
||||
gap: float = DEFAULT_GAP
|
||||
limit: float = DEFAULT_LIMIT
|
||||
|
||||
|
||||
def read_settings(params) -> ParkedSettings:
|
||||
try:
|
||||
enabled, readable = read_saved(params, 'ParkedClearance', 64)
|
||||
gap, gap_readable = read_saved(params, 'ParkedClearanceGap', 64)
|
||||
limit, limit_readable = read_saved(params, 'ParkedClearanceShift', 64)
|
||||
right_hand_drive, side_readable = read_saved(params, 'IsRhdDetected', 8)
|
||||
if (not readable or not gap_readable or not limit_readable or enabled not in (None, b'0', b'1') or
|
||||
not side_readable or right_hand_drive not in (None, b'0')):
|
||||
return ParkedSettings()
|
||||
value = DEFAULT_GAP if gap is None else float(gap)
|
||||
shift = DEFAULT_LIMIT if limit is None else float(limit)
|
||||
if not math.isfinite(value) or not 0 < value <= MAX_GAP or not math.isfinite(shift) or not MIN_LIMIT <= shift <= MAX_LIMIT:
|
||||
return ParkedSettings()
|
||||
return ParkedSettings(enabled == b'1', value, shift)
|
||||
except (OSError, ValueError):
|
||||
return ParkedSettings()
|
||||
|
||||
|
||||
def runtime_supported(CP) -> bool:
|
||||
return bool(lateral_supported(CP) and getattr(CP, 'radarUnavailable', True) is False)
|
||||
|
||||
|
||||
def _at(xs, ys, distance: float) -> float:
|
||||
value = path_lateral(xs, ys, distance, 0.0)
|
||||
if value is None:
|
||||
raise ValueError('Path does not cover distance')
|
||||
return -value
|
||||
|
||||
|
||||
class ParkedClearanceHost:
|
||||
REFRESH_NS = 1_000_000_000
|
||||
REQUIRED = tuple(MAX_AGE_NS)
|
||||
|
||||
def __init__(self, params, *, settings_reader=None):
|
||||
self.params = params
|
||||
self.settings_reader = settings_reader
|
||||
self.settings = ParkedSettings()
|
||||
self.detector = ParkedClearance()
|
||||
self.last_refresh_ns: int | None = None
|
||||
self.last_radar_ns = 0
|
||||
self.correction = 0.0
|
||||
self.shift = 0.0
|
||||
self.reason = 'inactive'
|
||||
|
||||
def _stop(self, reason: str) -> float:
|
||||
self.detector.reset()
|
||||
self.last_radar_ns = 0
|
||||
self.correction = 0.0
|
||||
self.shift = 0.0
|
||||
self.reason = reason
|
||||
return 0.0
|
||||
|
||||
def update(self, sm, *, now_ns: int, lateral_active: bool, maneuver: bool) -> float:
|
||||
if self.settings_reader is not None:
|
||||
self.settings = self.settings_reader()
|
||||
elif self.last_refresh_ns is None or not 0 <= now_ns - self.last_refresh_ns < self.REFRESH_NS:
|
||||
self.settings = read_settings(self.params)
|
||||
self.last_refresh_ns = now_ns
|
||||
if not self.settings.enabled:
|
||||
return self._stop('disabled')
|
||||
for name in self.REQUIRED:
|
||||
stamp = int(sm.logMonoTime[name])
|
||||
if not sm.valid[name] or not 0 <= now_ns - stamp <= MAX_AGE_NS[name]:
|
||||
return self._stop(f'{name}_stale')
|
||||
try:
|
||||
car, model, radar = sm['carState'], sm['modelV2'], sm['radarTracks']
|
||||
if not lateral_active or maneuver or not car.canValid or car.canTimeout or any(radar.errors.to_dict().values()):
|
||||
return self._stop('inactive')
|
||||
watch = bool(car.steeringPressed or car.leftBlinker or car.rightBlinker or car.leftBlindspot or
|
||||
model.meta.laneChangeState != log.LaneChangeState.off)
|
||||
speed = float(car.vEgo)
|
||||
if not math.isfinite(speed) or speed <= 0:
|
||||
return self._stop('inactive')
|
||||
lookahead = clip_scalar(speed, 8.0, 35.0)
|
||||
radar_ns = int(sm.logMonoTime['radarTracks'])
|
||||
if radar_ns != self.last_radar_ns:
|
||||
dt = (radar_ns - self.last_radar_ns) / 1e9 if self.last_radar_ns else 1.0 / SERVICE_LIST['radarTracks'].frequency
|
||||
if not 0 < dt <= MAX_RADAR_GAP_S:
|
||||
self.detector.reset()
|
||||
dt = 1.0 / SERVICE_LIST['radarTracks'].frequency
|
||||
self.last_radar_ns = radar_ns
|
||||
xs, ys = list(model.position.x), list(model.position.y)
|
||||
right_edge, right_edge_std = model.roadEdges[1], float(model.roadEdgeStds[1])
|
||||
ex, ey = list(right_edge.x), list(right_edge.y)
|
||||
points, candidates = [], []
|
||||
for point in radar.points:
|
||||
lateral = path_lateral(xs, ys, float(point.dRel), float(point.yRel))
|
||||
if lateral is not None:
|
||||
target = RadarPoint(int(point.trackId), float(point.dRel), lateral, float(point.vRel) + speed)
|
||||
points.append(target)
|
||||
edge = path_lateral(xs, ys, target.distance, 0.0)
|
||||
edge_y = path_lateral(ex, ey, target.distance, 0.0)
|
||||
if on_road(lateral, None if edge is None or edge_y is None else edge - edge_y, right_edge_std):
|
||||
candidates.append(target)
|
||||
center = _at(xs, ys, lookahead)
|
||||
if abs(center) > MAX_PATH_SLOPE * lookahead:
|
||||
return self._stop('curve')
|
||||
line, edge = model.laneLines[1], model.roadEdges[0]
|
||||
room = left_room(center - _at(list(line.x), list(line.y), lookahead), float(model.laneLineProbs[1]), float(model.laneLineStds[1]),
|
||||
center - _at(list(edge.x), list(edge.y), lookahead), float(model.roadEdgeStds[0]), oncoming=oncoming_ahead(points))
|
||||
self.detector.update(candidates, speed, dt, self.settings.gap, room, True, self.settings.limit, watch)
|
||||
self.reason = self.detector.reason
|
||||
elif watch:
|
||||
self.detector.shift, self.detector.demand, self.detector.hold, self.reason = 0.0, 0.0, 0.0, 'inactive'
|
||||
self.correction = clip_scalar(-2.0 * self.detector.shift / lookahead ** 2 * GAIN, -min(MAX_CORRECTION, MAX_LATERAL_ACCEL / speed ** 2), 0.0)
|
||||
self.shift = float(self.detector.shift)
|
||||
return self.correction
|
||||
except (AttributeError, IndexError, TypeError, ValueError, OverflowError):
|
||||
return self._stop('invalid')
|
||||
@@ -0,0 +1,193 @@
|
||||
import math
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.lateral import parked_clearance as pc
|
||||
from openpilot.starpilot.lateral.parked_clearance import ParkedClearance, RadarPoint
|
||||
|
||||
DT = 0.05
|
||||
|
||||
|
||||
def run(detector, points, seconds, *, speed=11.0, gap=1.0, room=0.6, active=True):
|
||||
shift = detector.shift
|
||||
for _ in range(round(seconds / DT)):
|
||||
shift = detector.update(points, speed, DT, gap, room, active)
|
||||
return shift
|
||||
|
||||
|
||||
def run_limit(points, limit):
|
||||
detector = ParkedClearance()
|
||||
shift = 0.0
|
||||
for _ in range(round(4.0 / DT)):
|
||||
shift = detector.update(points, 11.0, DT, 2.0, 1.0, True, limit)
|
||||
return shift
|
||||
|
||||
|
||||
class TestParkedClearance(unittest.TestCase):
|
||||
def test_clear_road_adds_nothing(self):
|
||||
self.assertEqual(run(ParkedClearance(), [], 5.0), 0.0)
|
||||
|
||||
def test_parked_car_shifts_left_within_cap(self):
|
||||
detector = ParkedClearance()
|
||||
shift = run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0)
|
||||
self.assertAlmostEqual(shift, pc.MAX_SHIFT)
|
||||
self.assertEqual(detector.reason, 'parked')
|
||||
|
||||
def test_shift_matches_missing_gap(self):
|
||||
shift = run(ParkedClearance(), [RadarPoint(1, 20.0, 2.7, 0.0)], 3.0)
|
||||
self.assertAlmostEqual(shift, 0.1)
|
||||
|
||||
def test_enough_gap_adds_nothing(self):
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 3.0, 0.0)], 3.0), 0.0)
|
||||
|
||||
def test_brief_track_ignored(self):
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], pc.CONFIRM_SECONDS - DT), 0.0)
|
||||
|
||||
def test_noisy_far_object_never_confirms(self):
|
||||
detector = ParkedClearance()
|
||||
for index in range(100):
|
||||
detector.update([RadarPoint(1, 20.0, 2.8 if index % 4 == 0 else 4.4, 0.0)], 11.0, DT, 1.5, 0.6, True)
|
||||
self.assertEqual(detector.shift, 0.0)
|
||||
|
||||
def test_close_roadside_target_and_high_speed_ignored(self):
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 1.3, 0.0)], 3.0), 0.0)
|
||||
detector = ParkedClearance()
|
||||
self.assertEqual(run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, speed=13.0), 0.0)
|
||||
self.assertEqual(detector.reason, 'speed')
|
||||
|
||||
def test_turning_speeds_add_nothing(self):
|
||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
||||
self.assertEqual(run(ParkedClearance(), point, 3.0, speed=4.0), 0.0)
|
||||
detector = ParkedClearance()
|
||||
self.assertGreater(run(detector, point, 3.0, speed=5.0), 0.0)
|
||||
run(detector, point, 0.35, speed=4.0)
|
||||
self.assertEqual(detector.shift, 0.0)
|
||||
|
||||
def test_shift_follows_room_drop_quickly(self):
|
||||
detector = ParkedClearance()
|
||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
||||
self.assertAlmostEqual(run(detector, point, 3.0, room=0.6), 0.3)
|
||||
run(detector, point, 0.25, room=0.05)
|
||||
self.assertLessEqual(detector.shift, 0.05 + 1e-9)
|
||||
|
||||
def test_release_after_passing_stays_gentle(self):
|
||||
detector = ParkedClearance()
|
||||
run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.6)
|
||||
run(detector, [], pc.HOLD_SECONDS + pc.TRACK_GAP_SECONDS + DT)
|
||||
before = detector.shift
|
||||
run(detector, [], 1.0)
|
||||
self.assertAlmostEqual(before - detector.shift, pc.FALL_RATE * 1.0, places=6)
|
||||
|
||||
def test_flickering_room_keeps_the_smaller_value(self):
|
||||
detector = ParkedClearance()
|
||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
||||
for i in range(round(3.0 / DT)):
|
||||
detector.update(point, 11.0, DT, 1.0, 0.6 if i % 2 else 0.1, True)
|
||||
self.assertLessEqual(detector.shift, 0.1 + 1e-9)
|
||||
self.assertAlmostEqual(detector.shift, 0.1)
|
||||
|
||||
def test_on_road(self):
|
||||
self.assertTrue(pc.on_road(2.6, 3.4, 0.4))
|
||||
self.assertFalse(pc.on_road(3.0, 2.5, 0.3))
|
||||
self.assertTrue(pc.on_road(1.8, 1.0, 0.3))
|
||||
self.assertTrue(pc.on_road(3.0, 2.5, 1.4))
|
||||
self.assertFalse(pc.on_road(3.0, None, 0.3))
|
||||
self.assertFalse(pc.on_road(3.0, math.nan, 0.3))
|
||||
|
||||
def test_far_lateral_and_moving_ignored(self):
|
||||
points = [RadarPoint(1, 20.0, 4.0, 0.0), RadarPoint(2, 20.0, 2.3, 8.0), RadarPoint(3, 20.0, -2.3, 0.0), RadarPoint(4, 40.0, 2.3, 0.0)]
|
||||
self.assertEqual(run(ParkedClearance(), points, 3.0), 0.0)
|
||||
|
||||
def test_left_room_limits_shift(self):
|
||||
detector = ParkedClearance()
|
||||
self.assertAlmostEqual(run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.1), 0.1)
|
||||
self.assertEqual(detector.reason, 'left_limited')
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.0), 0.0)
|
||||
|
||||
def test_oncoming_detection(self):
|
||||
self.assertTrue(pc.oncoming_ahead([RadarPoint(2, 100.0, -2.5, -10.0)]))
|
||||
for point in (RadarPoint(2, 130.0, -2.5, -10.0), RadarPoint(2, 50.0, 2.5, -10.0), RadarPoint(2, 50.0, -2.5, 0.0), RadarPoint(2, 50.0, -6.0, -10.0)):
|
||||
self.assertFalse(pc.oncoming_ahead([point]))
|
||||
|
||||
def test_speed_window(self):
|
||||
for speed in (pc.MIN_SPEED - 0.1, pc.MAX_SPEED + 0.1):
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, speed=speed), 0.0)
|
||||
|
||||
def test_rate_limited_rise_hold_and_release(self):
|
||||
detector = ParkedClearance()
|
||||
previous = 0.0
|
||||
for _ in range(60):
|
||||
shift = detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], 11.0, DT, 1.0, 0.6, True)
|
||||
self.assertLessEqual(shift - previous, pc.RISE_RATE * DT + 1e-9)
|
||||
previous = shift
|
||||
held = run(detector, [], pc.HOLD_SECONDS - DT)
|
||||
self.assertAlmostEqual(held, pc.MAX_SHIFT)
|
||||
for _ in range(100):
|
||||
shift = detector.update([], 11.0, DT, 1.0, 0.6, True)
|
||||
self.assertLessEqual(previous - shift, pc.FALL_RATE * DT + 1e-9)
|
||||
previous = shift
|
||||
self.assertEqual(shift, 0.0)
|
||||
|
||||
def test_inactive_resets_immediately(self):
|
||||
detector = ParkedClearance()
|
||||
run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0)
|
||||
self.assertEqual(detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], 11.0, DT, 1.0, 0.6, False), 0.0)
|
||||
self.assertEqual(detector.tracks, {})
|
||||
|
||||
def test_watch_tracks_without_shift(self):
|
||||
detector = ParkedClearance()
|
||||
points = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
||||
for _ in range(round(1.0 / DT)):
|
||||
self.assertEqual(detector.update(points, 11.0, DT, 1.0, 0.6, True, pc.MAX_SHIFT, True), 0.0)
|
||||
self.assertEqual(detector.reason, 'inactive')
|
||||
self.assertGreater(detector.update(points, 11.0, DT, 1.0, 0.6, True), 0.0)
|
||||
self.assertEqual(detector.reason, 'parked')
|
||||
self.assertEqual(detector.update(points, 11.0, DT, 1.0, 0.6, True, pc.MAX_SHIFT, True), 0.0)
|
||||
|
||||
def test_invalid_inputs_add_nothing(self):
|
||||
for speed, dt, gap, room in ((math.nan, DT, 1.0, 0.6), (11.0, 0.0, 1.0, 0.6), (11.0, DT, 0.0, 0.6), (11.0, DT, 1.0, math.inf)):
|
||||
detector = ParkedClearance()
|
||||
for _ in range(60):
|
||||
self.assertEqual(detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], speed, dt, gap, room, True), 0.0)
|
||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, math.nan, 2.3, 0.0)], 3.0), 0.0)
|
||||
|
||||
def test_wide_gap_reaches_far_curb_cars(self):
|
||||
point = [RadarPoint(1, 20.0, 3.5, 0.0)]
|
||||
self.assertAlmostEqual(run(ParkedClearance(), point, 3.0, gap=2.0, room=0.6), 0.3)
|
||||
self.assertEqual(run(ParkedClearance(), point, 3.0, gap=1.5, room=0.6), 0.0)
|
||||
|
||||
def test_gap_setting_capped(self):
|
||||
detector = ParkedClearance()
|
||||
run(detector, [RadarPoint(1, 20.0, 3.2, 0.0)], 3.0, gap=5.0)
|
||||
self.assertAlmostEqual(detector.demand, pc.MAX_GAP - 1.4)
|
||||
|
||||
def test_limit_setting_caps_shift(self):
|
||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
||||
self.assertAlmostEqual(run_limit(point, 0.1), 0.1)
|
||||
self.assertAlmostEqual(run_limit(point, 0.5), 0.5)
|
||||
self.assertAlmostEqual(run_limit(point, 0.8), 0.8)
|
||||
self.assertAlmostEqual(run_limit(point, 9.0), 0.8)
|
||||
for bad in (0.0, -0.2, math.nan):
|
||||
self.assertEqual(run_limit(point, bad), 0.0)
|
||||
|
||||
def test_path_lateral(self):
|
||||
self.assertAlmostEqual(pc.path_lateral([0.0, 10.0, 20.0], [0.0, 0.5, 1.0], 15.0, -3.0), 2.25)
|
||||
self.assertIsNone(pc.path_lateral([0.0, 10.0], [0.0, 0.5], 15.0, -3.0))
|
||||
self.assertIsNone(pc.path_lateral([0.0], [0.0], 0.0, -3.0))
|
||||
|
||||
def test_left_room(self):
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.1, 6.0, 0.8), 0.7)
|
||||
self.assertEqual(pc.left_room(0.8, 0.9, 0.1, 6.0, 0.2), 0.0)
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 0.7), 2.5)
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 1.2), 1.5)
|
||||
self.assertEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 1.6), 0.0)
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 0.5), 0.5)
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.9, 6.0, 0.5), 0.2)
|
||||
self.assertEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 1.6), 0.0)
|
||||
self.assertEqual(pc.left_room(math.nan, 0.9, 0.1, 6.0, 0.2), 0.0)
|
||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.1, 6.0, 0.8, oncoming=True), 0.5)
|
||||
self.assertEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 0.7, oncoming=True), 0.0)
|
||||
self.assertEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 0.5, oncoming=True), 0.0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,275 @@
|
||||
import math
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.cereal import log
|
||||
from openpilot.starpilot.lateral import parked_runtime as runtime
|
||||
from openpilot.starpilot.lateral.parked_runtime import ParkedClearanceHost, ParkedSettings, read_settings
|
||||
from openpilot.starpilot.lateral.lane_centering import LaneCenteringController, RELEASE_TAU
|
||||
from openpilot.starpilot.lateral.tests.test_lane_centering import model as lane_model, observation as lane_observation, settled
|
||||
|
||||
STEP_NS = 50_000_000
|
||||
|
||||
|
||||
class Bus:
|
||||
def __init__(self):
|
||||
self.data = {}
|
||||
self.logMonoTime = {}
|
||||
self.valid = {}
|
||||
|
||||
def __getitem__(self, name):
|
||||
return self.data[name]
|
||||
|
||||
def put(self, name, message, stamp, valid=True):
|
||||
self.data[name], self.logMonoTime[name], self.valid[name] = message, stamp, valid
|
||||
|
||||
|
||||
def model_message(left_line=-1.7, line_prob=0.9, right_edge=6.0, edge_std=0.3):
|
||||
model = log.ModelDataV2.new_message()
|
||||
xs = [float(x) for x in range(0, 100, 3)]
|
||||
model.position.x, model.position.y = xs, [0.0] * len(xs)
|
||||
lines = model.init('laneLines', 4)
|
||||
for line, y in zip(lines, (-5.0, left_line, 1.7, 5.0), strict=True):
|
||||
line.x, line.y = xs, [y] * len(xs)
|
||||
model.laneLineProbs, model.laneLineStds = [0.9, line_prob, 0.9, 0.9], [0.1] * 4
|
||||
edges = model.init('roadEdges', 2)
|
||||
for edge, y in zip(edges, (-6.0, right_edge), strict=True):
|
||||
edge.x, edge.y = xs, [y] * len(xs)
|
||||
model.roadEdgeStds = [0.3, edge_std]
|
||||
return model.as_reader()
|
||||
|
||||
|
||||
def radar_message(points):
|
||||
radar = car.RadarData.new_message()
|
||||
built = radar.init('points', len(points))
|
||||
for target, (identifier, distance, y_rel, v_rel) in zip(built, points, strict=True):
|
||||
target.trackId, target.dRel, target.yRel, target.vRel = identifier, distance, y_rel, v_rel
|
||||
return radar.as_reader()
|
||||
|
||||
|
||||
def car_message(speed=11.0, **fields):
|
||||
state = car.CarState.new_message(vEgo=speed, canValid=True, **fields)
|
||||
return state.as_reader()
|
||||
|
||||
|
||||
def drive(host, seconds, points, *, speed=11.0, model=None, active=True, maneuver=False, start=1_000_000_000, **fields):
|
||||
bus = Bus()
|
||||
model = model_message() if model is None else model
|
||||
correction = 0.0
|
||||
for index in range(round(seconds / 0.05)):
|
||||
now = start + index * STEP_NS
|
||||
bus.put('carState', car_message(speed, **fields), now)
|
||||
bus.put('modelV2', model, now)
|
||||
bus.put('radarTracks', radar_message(points), now)
|
||||
correction = host.update(bus, now_ns=now, lateral_active=active, maneuver=maneuver)
|
||||
return correction, bus, start + round(seconds / 0.05) * STEP_NS
|
||||
|
||||
|
||||
def host(enabled=True, gap=1.5, limit=runtime.DEFAULT_LIMIT):
|
||||
return ParkedClearanceHost(None, settings_reader=lambda: ParkedSettings(enabled, gap, limit))
|
||||
|
||||
|
||||
PARKED = [(7, 20.0, -2.6, -11.0)]
|
||||
|
||||
|
||||
class TestParkedRuntime(unittest.TestCase):
|
||||
def test_disabled_by_default_adds_nothing(self):
|
||||
self.assertEqual(ParkedSettings().enabled, False)
|
||||
self.assertEqual(drive(host(enabled=False), 3.0, PARKED)[0], 0.0)
|
||||
|
||||
def test_parked_car_steers_left_within_cap(self):
|
||||
subject = host()
|
||||
correction = drive(subject, 4.0, PARKED)[0]
|
||||
self.assertAlmostEqual(correction, -2.0 * 0.3 / 11.0 ** 2 * runtime.GAIN, places=9)
|
||||
self.assertLessEqual(-correction, min(runtime.MAX_CORRECTION, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2))
|
||||
self.assertEqual(subject.reason, 'parked')
|
||||
subject = host(gap=1.4)
|
||||
correction = drive(subject, 4.0, [(7, 20.0, -3.1, -11.0)])[0]
|
||||
self.assertAlmostEqual(subject.detector.shift, 0.1, places=5)
|
||||
self.assertAlmostEqual(correction, -2.0 * 0.1 / 11.0 ** 2 * runtime.GAIN, places=7)
|
||||
|
||||
def test_limit_setting_scales_cap(self):
|
||||
small, large = host(limit=0.1), host(gap=2.0, limit=0.5)
|
||||
self.assertAlmostEqual(drive(small, 4.0, PARKED)[0], -2.0 * 0.1 / 11.0 ** 2 * runtime.GAIN, places=7)
|
||||
self.assertAlmostEqual(small.shift, 0.1, places=5)
|
||||
wide = model_message(line_prob=0.05)
|
||||
correction = drive(large, 6.0, PARKED, model=wide)[0]
|
||||
self.assertAlmostEqual(correction, -2.0 * 0.5 / 11.0 ** 2 * runtime.GAIN, places=9)
|
||||
self.assertLessEqual(-correction, min(runtime.MAX_CORRECTION, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2))
|
||||
self.assertLessEqual(large.shift, 0.5)
|
||||
|
||||
def test_city_speed_shift_is_not_clipped(self):
|
||||
subject = host(gap=2.0, limit=0.5)
|
||||
correction = drive(subject, 6.0, [(7, 20.0, -2.6, -9.0)], speed=9.0, model=model_message(line_prob=0.05))[0]
|
||||
self.assertAlmostEqual(subject.shift, 0.5, places=5)
|
||||
self.assertAlmostEqual(correction, -0.9 * 0.5 / 81.0, places=9)
|
||||
|
||||
def test_lateral_accel_stays_bounded_at_speed(self):
|
||||
subject = host(gap=2.0, limit=0.5)
|
||||
start = 1_000_000_000
|
||||
for _ in range(12):
|
||||
correction, _, start = drive(subject, 0.5, [(7, 20.0, -2.6, -12.5)], speed=12.5, model=model_message(line_prob=0.05), start=start)
|
||||
self.assertLessEqual(-correction * 12.5 ** 2, runtime.MAX_LATERAL_ACCEL + 1e-12)
|
||||
self.assertLess(correction, 0.0)
|
||||
|
||||
def test_oncoming_mid_shift_pulls_back(self):
|
||||
subject = host()
|
||||
narrow = model_message(left_line=-1.3)
|
||||
_, _, now = drive(subject, 4.0, PARKED, model=narrow)
|
||||
self.assertAlmostEqual(subject.shift, 0.3, places=5)
|
||||
drive(subject, 0.3, PARKED + [(9, 90.0, 2.5, -22.0)], model=narrow, start=now)
|
||||
self.assertLessEqual(subject.shift, 0.2 + 1e-6)
|
||||
|
||||
def test_wide_gap_reaches_far_curb_car(self):
|
||||
wide = host(gap=2.5, limit=0.8)
|
||||
self.assertLess(drive(wide, 4.0, [(7, 20.0, -4.0, -11.0)])[0], 0.0)
|
||||
self.assertGreater(wide.shift, 0.25)
|
||||
self.assertEqual(drive(host(gap=1.5), 4.0, [(7, 20.0, -4.0, -11.0)])[0], 0.0)
|
||||
|
||||
def test_large_limit_is_capped_by_lateral_accel(self):
|
||||
subject = host(gap=2.5, limit=0.8)
|
||||
correction = drive(subject, 6.0, [(7, 20.0, -2.6, -11.0)], model=model_message(line_prob=0.05))[0]
|
||||
self.assertAlmostEqual(subject.shift, 0.8, places=5)
|
||||
self.assertAlmostEqual(correction, -min(2.0 * 0.8 / 11.0 ** 2 * runtime.GAIN, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2), places=9)
|
||||
|
||||
def test_roadside_objects_are_ignored(self):
|
||||
self.assertEqual(drive(host(), 4.0, PARKED, model=model_message(right_edge=2.2))[0], 0.0)
|
||||
self.assertLess(drive(host(), 4.0, PARKED, model=model_message(right_edge=2.2, edge_std=1.4))[0], 0.0)
|
||||
self.assertLess(drive(host(), 4.0, [(7, 20.0, -1.8, -11.0)], model=model_message(right_edge=1.0))[0], 0.0)
|
||||
self.assertEqual(drive(host(), 4.0, [(7, 20.0, -1.3, -11.0)])[0], 0.0)
|
||||
self.assertEqual(drive(host(), 4.0, [(7, 20.0, -2.6, -13.0)], speed=13.0)[0], 0.0)
|
||||
|
||||
def test_clear_road_and_far_objects_add_nothing(self):
|
||||
self.assertEqual(drive(host(), 3.0, [])[0], 0.0)
|
||||
self.assertEqual(drive(host(), 3.0, [(7, 20.0, -4.5, -11.0), (8, 20.0, 2.6, -11.0), (9, 20.0, -2.6, 0.0)])[0], 0.0)
|
||||
|
||||
def test_no_left_room_adds_nothing(self):
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, model=model_message(left_line=-0.9))[0], 0.0)
|
||||
|
||||
def test_oncoming_keeps_wider_line_spacing(self):
|
||||
oncoming = PARKED + [(9, 90.0, 2.5, -22.0)]
|
||||
self.assertLess(drive(host(), 4.0, oncoming)[0], 0.0)
|
||||
narrow = model_message(left_line=-1.05)
|
||||
self.assertLess(drive(host(), 4.0, PARKED, model=narrow)[0], 0.0)
|
||||
self.assertEqual(drive(host(), 4.0, oncoming, model=narrow)[0], 0.0)
|
||||
unmarked = model_message(line_prob=0.05)
|
||||
self.assertLess(drive(host(), 4.0, PARKED, model=unmarked)[0], 0.0)
|
||||
self.assertEqual(drive(host(), 4.0, oncoming, model=unmarked)[0], 0.0)
|
||||
|
||||
def test_driver_and_authority_gates_reset(self):
|
||||
for fields in ({'steeringPressed': True}, {'leftBlinker': True}, {'rightBlinker': True}, {'canTimeout': True}, {'leftBlindspot': True}):
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, **fields)[0], 0.0)
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, active=False)[0], 0.0)
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, maneuver=True)[0], 0.0)
|
||||
subject = host()
|
||||
_, bus, now = drive(subject, 4.0, PARKED)
|
||||
bus.put('carState', car_message(steeringPressed=True), now)
|
||||
bus.put('radarTracks', radar_message(PARKED), now)
|
||||
bus.put('modelV2', bus['modelV2'], now)
|
||||
self.assertGreater(subject.shift, 0.0)
|
||||
self.assertEqual(subject.shift, subject.detector.shift)
|
||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), 0.0)
|
||||
self.assertEqual(subject.detector.shift, 0.0)
|
||||
self.assertEqual(subject.shift, 0.0)
|
||||
|
||||
def test_blinker_keeps_watching_and_resumes_without_reconfirm(self):
|
||||
subject = host()
|
||||
correction, _, now = drive(subject, 2.0, PARKED, leftBlinker=True)
|
||||
self.assertEqual(correction, 0.0)
|
||||
self.assertEqual(subject.shift, 0.0)
|
||||
self.assertLess(drive(subject, 0.25, PARKED, start=now)[0], 0.0)
|
||||
|
||||
def test_stale_or_invalid_inputs_reset(self):
|
||||
for name in ParkedClearanceHost.REQUIRED:
|
||||
subject = host()
|
||||
_, bus, now = drive(subject, 4.0, PARKED)
|
||||
self.assertEqual(subject.update(bus, now_ns=now + 10 * STEP_NS, lateral_active=True, maneuver=False), 0.0)
|
||||
subject = host()
|
||||
_, bus, now = drive(subject, 4.0, PARKED)
|
||||
for other in ParkedClearanceHost.REQUIRED:
|
||||
bus.put(other, bus[other], now, valid=other != name)
|
||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), 0.0)
|
||||
self.assertEqual(subject.reason, f'{name}_stale')
|
||||
|
||||
def test_lane_change_and_speed_window(self):
|
||||
model = model_message().as_builder()
|
||||
model.meta.laneChangeState = log.LaneChangeState.laneChangeStarting
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, model=model.as_reader())[0], 0.0)
|
||||
self.assertEqual(drive(host(), 3.0, [(7, 20.0, -2.6, -25.0)], speed=25.0)[0], 0.0)
|
||||
|
||||
def test_held_between_radar_samples(self):
|
||||
subject = host()
|
||||
correction, bus, now = drive(subject, 4.0, PARKED)
|
||||
bus.put('carState', car_message(), now)
|
||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), correction)
|
||||
|
||||
def test_curving_path_adds_nothing(self):
|
||||
model = model_message().as_builder()
|
||||
model.position.y = [0.15 * x for x in model.position.x]
|
||||
subject = host()
|
||||
self.assertEqual(drive(subject, 3.0, [(7, 20.0, -5.6, -11.0)], model=model.as_reader())[0], 0.0)
|
||||
self.assertEqual(subject.reason, 'curve')
|
||||
|
||||
def test_malformed_model_adds_nothing(self):
|
||||
self.assertEqual(drive(host(), 3.0, PARKED, model=log.ModelDataV2.new_message().as_reader())[0], 0.0)
|
||||
|
||||
def test_saved_settings(self):
|
||||
class Saved:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
|
||||
def get_param_path(self, key):
|
||||
return str(Path(self.root) / key)
|
||||
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
saved = Saved(root)
|
||||
self.assertEqual(read_settings(saved), ParkedSettings(False, runtime.DEFAULT_GAP))
|
||||
(Path(root) / 'ParkedClearance').write_bytes(b'1')
|
||||
self.assertEqual(read_settings(saved), ParkedSettings(True, runtime.DEFAULT_GAP))
|
||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 1.2))
|
||||
for bad in (b'nan', b'0', b'2.6', b'9', b'x'):
|
||||
(Path(root) / 'ParkedClearanceGap').write_bytes(bad)
|
||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
||||
for side, expected in ((b'0', ParkedSettings(True, 1.2)), (b'1', ParkedSettings()), (b'x', ParkedSettings())):
|
||||
(Path(root) / 'IsRhdDetected').write_bytes(side)
|
||||
self.assertEqual(read_settings(saved), expected)
|
||||
(Path(root) / 'IsRhdDetected').unlink()
|
||||
(Path(root) / 'ParkedClearanceShift').write_bytes(b'0.45')
|
||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 1.2, 0.45))
|
||||
for bad in (b'nan', b'0', b'0.85', b'x'):
|
||||
(Path(root) / 'ParkedClearanceShift').write_bytes(bad)
|
||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
||||
(Path(root) / 'ParkedClearanceShift').write_bytes(b'0.8')
|
||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'2.5')
|
||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 2.5, 0.8))
|
||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
||||
(Path(root) / 'ParkedClearanceShift').unlink()
|
||||
(Path(root) / 'ParkedClearance').write_bytes(b'yes')
|
||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
||||
|
||||
|
||||
class TestParkedLaneCentering(unittest.TestCase):
|
||||
def test_hold_fades_lane_centering_and_resumes(self):
|
||||
lanes = lane_model(left=-1.5, right=2.1)
|
||||
controller = LaneCenteringController()
|
||||
start = previous = settled(controller, lane_observation(lanes)).correction
|
||||
self.assertGreater(start, 0.0)
|
||||
for _ in range(100):
|
||||
result = controller.update(lane_observation(lanes, hold=True))
|
||||
self.assertEqual(result.reason, 'parked_clearance')
|
||||
self.assertIsNotNone(result.candidate_curvature)
|
||||
self.assertLessEqual(result.correction, previous)
|
||||
self.assertGreaterEqual(result.correction, previous * math.exp(-0.01 / RELEASE_TAU) - 1e-15)
|
||||
previous = result.correction
|
||||
self.assertLess(previous, 0.01 * start)
|
||||
resumed = settled(controller, lane_observation(lanes))
|
||||
self.assertNotEqual(resumed.reason, 'parked_clearance')
|
||||
self.assertAlmostEqual(resumed.correction, start, delta=0.05 * start)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import patch
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.test import require_value
|
||||
from openpilot.starpilot.longitudinal.toyota_output_policy import Lead, ToyotaOutputPolicy, clock_pair_ns, eligible, leads_from_radar
|
||||
|
||||
|
||||
@@ -51,6 +52,14 @@ class ToyotaOutputPolicyTests(unittest.TestCase):
|
||||
policy.reset()
|
||||
self.assert_target(policy.target(1.0, 1.0, False, 0.0), 0.03225806451612903)
|
||||
|
||||
def test_corolla_standstill_release_skips_unwind(self):
|
||||
policy = ToyotaOutputPolicy(self.cp(CAR.TOYOTA_COROLLA_TSS2))
|
||||
self.assertGreaterEqual(require_value(policy.target(0.1, 0.0, False, -2.0, release_brake=True)), 0.0)
|
||||
policy.reset()
|
||||
self.assert_target(policy.target(0.1, 0.5, False, -2.0, release_brake=True), -2.0 + 0.01 / 0.31 * 2.1)
|
||||
policy.reset()
|
||||
self.assertLess(require_value(policy.target(0.1, 0.0, False, -2.0)), -1.5)
|
||||
|
||||
def test_sienna_low_speed_comfort_bypass_departure_cap_and_reset(self):
|
||||
policy = ToyotaOutputPolicy(self.cp(CAR.TOYOTA_SIENNA_4TH_GEN))
|
||||
empty = ()
|
||||
|
||||
@@ -29,6 +29,7 @@ _ACCEL_MIN, _ACCEL_MAX = -5.0, 3.0
|
||||
RADAR_MAX_AGE_NS = 100_000_000 # Two periods of the current 20 Hz radarState service.
|
||||
CLOCK_PAIR_MAX_SKEW_NS = 5_000_000
|
||||
COROLLA_BRAKE_RELEASE_RATE = 4.0 # Match the Toyota PCM acceleration unwind limit.
|
||||
COROLLA_STANDSTILL_SPEED = 0.1
|
||||
|
||||
|
||||
def clock_pair_ns() -> tuple[int, int] | None:
|
||||
@@ -235,7 +236,8 @@ class ToyotaOutputPolicy:
|
||||
tau = 0.18 if target < self.filtered_target else 0.30
|
||||
self.filtered_target += DT_CTRL / (tau + DT_CTRL) * (target - self.filtered_target)
|
||||
if self.releasing_brake:
|
||||
self.filtered_target = max(self.filtered_target, min(0.0, previous_output + COROLLA_BRAKE_RELEASE_RATE * DT_CTRL))
|
||||
self.filtered_target = max(self.filtered_target, 0.0 if speed <= COROLLA_STANDSTILL_SPEED else
|
||||
min(0.0, previous_output + COROLLA_BRAKE_RELEASE_RATE * DT_CTRL))
|
||||
return self.filtered_target
|
||||
|
||||
def _sienna(self, target: float, speed: float, should_stop: bool, leads: tuple[Lead, ...]) -> float:
|
||||
|
||||
@@ -15,19 +15,6 @@ def settings(monkeypatch, topology):
|
||||
monkeypatch.ford_topology = topology
|
||||
monkeypatch.ford_nonzero = True
|
||||
monkeypatch.ford_native_10hz = True
|
||||
calls = []
|
||||
observe = card_native.ford_native_observation
|
||||
|
||||
def traced_native(native, **kwargs):
|
||||
result = observe(native, **kwargs)
|
||||
calls.append({'now': kwargs['now_ns'], 'latched': kwargs['latched'], 'pending': kwargs['pending_since_ns'],
|
||||
'restricted': kwargs['restricted'], 'result': result,
|
||||
'native': None if native is None else [native.requestedLateral, native.lateralAllowed,
|
||||
native.requestedLongitudinal, native.longitudinalAllowed]})
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(card_native, 'ford_native_observation', traced_native)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity,alpha,hands_free,topology', [
|
||||
@@ -41,10 +28,10 @@ def settings(monkeypatch, topology):
|
||||
('startup', 'paired'), ('startup', 'axis-delayed'), ('startup', 'state-delayed'),
|
||||
('brake', 'health-first'), ('brake', 'wire-first'), ('startup', 'native-timeout'),
|
||||
])
|
||||
def test_initial_request_and_longitudinal_withdrawal(settings, ford_joined, monkeypatch, scenario, delivery):
|
||||
def test_initial_request_and_longitudinal_withdrawal(ford_joined, monkeypatch, scenario, delivery):
|
||||
invalid = [False]
|
||||
injected = [False]
|
||||
calls = settings
|
||||
calls = []
|
||||
delayed = {}
|
||||
negative_checked = [False]
|
||||
if delivery == 'native-timeout':
|
||||
@@ -78,6 +65,17 @@ def test_initial_request_and_longitudinal_withdrawal(settings, ford_joined, monk
|
||||
return update(timestamp, adjusted)
|
||||
|
||||
local.setattr(sd.sm, 'update_msgs', calibration)
|
||||
observe = card_native.ford_native_observation
|
||||
|
||||
def traced_native(native, **kwargs):
|
||||
result = observe(native, **kwargs)
|
||||
calls.append({'now': kwargs['now_ns'], 'latched': kwargs['latched'], 'pending': kwargs['pending_since_ns'],
|
||||
'restricted': kwargs['restricted'], 'result': result,
|
||||
'native': None if native is None else [native.requestedLateral, native.lateralAllowed,
|
||||
native.requestedLongitudinal, native.longitudinalAllowed]})
|
||||
return result
|
||||
|
||||
local.setattr(card_native, 'ford_native_observation', traced_native)
|
||||
pending = getattr(card_module, 'ford_awaiting_initial_request', None)
|
||||
if pending is not None:
|
||||
def checked_pending(cp, cs, sm, native, feedback, intent, **kwargs):
|
||||
|
||||
@@ -108,7 +108,7 @@ class TestVehicleStateContext(unittest.TestCase):
|
||||
enable_edge = next(node for node in helper.body[0].body if isinstance(node, ast.If) and initialize in ast.walk(node))
|
||||
self.assertEqual(ast.unparse(enable_edge.test), "self.sm['carControl'].enabled and (not self.CC_prev.enabled)")
|
||||
self.assertIn(initialize, list(ast.walk(enable_edge)))
|
||||
step = inspect.getsource(card.Car._step)
|
||||
step = inspect.getsource(card.Car.step)
|
||||
step_tree = ast.parse(textwrap.dedent(step))
|
||||
state_update = next(node for node in ast.walk(step_tree)
|
||||
if isinstance(node, ast.Call) and ast.unparse(node.func) == 'self.state_update')
|
||||
|
||||
@@ -30,6 +30,7 @@ BOOL_DEFAULTS = {
|
||||
WHEEL_OVERRIDE_KEY: False,
|
||||
"PauseLateralOnSignal": False,
|
||||
"LaneCentering": False, "LaneCenteringPauseOnSignal": True,
|
||||
"ParkedClearance": False,
|
||||
"CustomPersonalities": False, PLANNER_SELECTION_KEY: True,
|
||||
LEAD_APPROACH_KEY: False,
|
||||
LEAD_TAKEOFF_KEY: False,
|
||||
@@ -47,6 +48,8 @@ FLOAT_SPECS = {
|
||||
SURPLUS_KEY: (0, MAX_SURPLUS_MPH, 1, "mph"),
|
||||
"ForceStopDistanceOffset": (-20, 20, 1, "ft"),
|
||||
"LaneCenterOffset": (-0.3, 0.3, 0.01, "m"),
|
||||
"ParkedClearanceGap": (1.0, 2.5, 0.1, "m"),
|
||||
"ParkedClearanceShift": (0.1, 0.8, 0.05, "m"),
|
||||
"LaneCenteringE2EAuthority": (0.0, 1.0, 0.05, "fraction"),
|
||||
"LaneCenteringStrength": (0.5, STRENGTH_MAX, 0.015, "fraction"),
|
||||
**{f"{name}{suffix}": (0.5, 3.0, 0.05, "s")
|
||||
|
||||
@@ -7,12 +7,8 @@ Reset and migration actions additionally require a parked vehicle.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from openpilot.starpilot.ui.feature_profile_edit import (
|
||||
edit_document,
|
||||
PRESETS as PRESETS,
|
||||
PROFILE_NAMES as PROFILE_NAMES,
|
||||
DOCUMENT_PROFILE_NAMES as DOCUMENT_PROFILE_NAMES,
|
||||
)
|
||||
from openpilot.starpilot.ui.feature_profile_edit import (edit_document, PRESETS as PRESETS,
|
||||
PROFILE_NAMES as PROFILE_NAMES, DOCUMENT_PROFILE_NAMES as DOCUMENT_PROFILE_NAMES)
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextvars import ContextVar
|
||||
@@ -41,12 +37,9 @@ from openpilot.starpilot.longitudinal.profile_document import (
|
||||
personality_reference_curves, serialize_personality_profiles,
|
||||
synchronise_profile_document_enabled,
|
||||
)
|
||||
from openpilot.starpilot.ui.feature_defaults import (
|
||||
AGGRESSIVE_COOLING_DESCRIPTION as AGGRESSIVE_COOLING_DESCRIPTION,
|
||||
AGGRESSIVE_COOLING_KEY as AGGRESSIVE_COOLING_KEY,
|
||||
BOOL_DEFAULTS as BOOL_DEFAULTS,
|
||||
FLOAT_SPECS as FLOAT_SPECS,
|
||||
)
|
||||
from openpilot.starpilot.ui.feature_defaults import (AGGRESSIVE_COOLING_DESCRIPTION as AGGRESSIVE_COOLING_DESCRIPTION,
|
||||
AGGRESSIVE_COOLING_KEY as AGGRESSIVE_COOLING_KEY,
|
||||
BOOL_DEFAULTS as BOOL_DEFAULTS, FLOAT_SPECS as FLOAT_SPECS)
|
||||
from openpilot.starpilot.ui.feature_settings_state import (
|
||||
FeaturePage, FeatureRow, FeatureSettingsRequest, FeatureSettingsState, SettingLevel, SLC_CONFIRM_ACTIONS, SLC_OFFSET_KEYS, TORQUE_CONFIRM_ACTIONS,
|
||||
)
|
||||
@@ -66,14 +59,8 @@ from openpilot.starpilot.ui.controller_feature import ControllerFeature, SETUP_A
|
||||
from openpilot.starpilot.ui.slc_offset_feature import SlcOffsetOwner
|
||||
from openpilot.starpilot.ui.slc_policy_feature import SLC_ADVANCE_CHOICES, policy_rows
|
||||
from openpilot.starpilot.longitudinal.profile_preferences import read_document_value, read_profile_health
|
||||
from openpilot.starpilot.ui.long_profile_feature import (
|
||||
LongProfileFeature,
|
||||
is_long_confirm_action,
|
||||
VALUE_HELP,
|
||||
CATEGORY_HELP,
|
||||
preset_label,
|
||||
preset_value,
|
||||
)
|
||||
from openpilot.starpilot.ui.long_profile_feature import (LongProfileFeature, is_long_confirm_action, VALUE_HELP, CATEGORY_HELP,
|
||||
preset_label, preset_value)
|
||||
from openpilot.starpilot.ui.traffic_feature import TrafficFeature, EDIT_KEYS as TRAFFIC_EDIT_KEYS
|
||||
from openpilot.starpilot.ui.cruise_steps_feature import CRUISE_KEYS, apply_cruise, apply_reverse_cruise, cruise_rows
|
||||
from openpilot.starpilot.ui.lane_change_feature import LaneChangeFeature, KEYS as LANE_CHANGE_KEYS
|
||||
@@ -100,6 +87,8 @@ from openpilot.starpilot.curve_speed.preferences import (
|
||||
DOCUMENT_LIMIT as CURVE_DOCUMENT_LIMIT, read_learning,
|
||||
)
|
||||
from openpilot.starpilot.curve_speed.actions import ACTION_KEYS as CURVE_ACTION_KEYS, apply_learning, learning_snapshot
|
||||
|
||||
|
||||
from openpilot.starpilot.controllers.toyota_cruise import capability as toyota_cruise_capability
|
||||
|
||||
|
||||
@@ -124,6 +113,7 @@ AOL_LEGACY_THRESHOLD = "PauseAOLOnBrake"
|
||||
TORQUE_NUMBERS = LEGACY_KEYS
|
||||
LANE_LIVE_KEYS = frozenset(("LaneCentering", "LaneCenteringPauseOnSignal", "LaneCenterOffset",
|
||||
"LaneCenteringE2EAuthority", "LaneCenteringStrength"))
|
||||
PARKED_KEYS = frozenset(("ParkedClearance", "ParkedClearanceGap", "ParkedClearanceShift"))
|
||||
CURVE_KEYS = frozenset((CURVE_MASTER_KEY, CURVE_NO_LEAD_KEY))
|
||||
CURVE_PAGE_KEYS = CURVE_KEYS | {"ShowCSCStatus", GENTLE_KEY}
|
||||
|
||||
@@ -175,8 +165,8 @@ class FeatureSettingsOwner:
|
||||
self.volt_radar = VoltRadarFeature(self, galaxy=galaxy)
|
||||
self.panda_wake = PandaWakeFeature(self, galaxy=galaxy)
|
||||
self.traffic_profiles = TrafficFeature(self)
|
||||
self.lane_changes = LaneChangeFeature(
|
||||
params, authority, vehicle_fingerprint, self.vehicle_params, configuration_longitudinal=self.configuration_longitudinal)
|
||||
self.lane_changes = LaneChangeFeature(params, authority, vehicle_fingerprint, self.vehicle_params,
|
||||
configuration_longitudinal=self.configuration_longitudinal)
|
||||
self.conditional = ConditionalFeature(self)
|
||||
self.wheel = TeslaWheelRows(self)
|
||||
|
||||
@@ -1220,6 +1210,12 @@ class FeatureSettingsOwner:
|
||||
minimum=33, maximum=round(STRENGTH_MAX / STRENGTH_BASELINE * 100), step=1 if strength_row.step > 0 else 0,
|
||||
reason="100% is normal; lower values reduce centering and higher values strengthen it" if strength_supported else
|
||||
"Not available with this vehicle configuration"))
|
||||
from openpilot.starpilot.lateral.parked_runtime import runtime_supported as parked_supported
|
||||
parked_allowed = bool(configurable and lateral_context and parked_supported(self.vehicle_params()))
|
||||
parked_on = parked_allowed and self._value("ParkedClearance")[0] == "1"
|
||||
rows.extend((self._bool_row("ParkedClearance", "Parked car clearance", parked_allowed),
|
||||
self._number_row("ParkedClearanceGap", "Parked car target gap", parked_on),
|
||||
self._number_row("ParkedClearanceShift", "Parked car max shift", parked_on)))
|
||||
elif page == FeaturePage.LANE_CHANGE:
|
||||
title = "Lane Changes"
|
||||
rows.extend(self.lane_changes.rows(parked))
|
||||
@@ -1587,7 +1583,7 @@ class FeatureSettingsOwner:
|
||||
elif key in LANE_LIVE_KEYS and not self.authority("lane"):
|
||||
group = "lane_live"
|
||||
else:
|
||||
group = "lane" if key.startswith("LaneCenter") else "long" if long_key else "slc"
|
||||
group = "lane" if key.startswith("LaneCenter") or key in PARKED_KEYS else "long" if long_key else "slc"
|
||||
else:
|
||||
return False
|
||||
try:
|
||||
@@ -1624,6 +1620,10 @@ class FeatureSettingsOwner:
|
||||
from openpilot.starpilot.lateral.lane_runtime import runtime_supported
|
||||
if not runtime_supported(self.vehicle_params()):
|
||||
return False
|
||||
if key in PARKED_KEYS:
|
||||
from openpilot.starpilot.lateral.parked_runtime import runtime_supported as parked_supported
|
||||
if not parked_supported(self.vehicle_params()) or key != "ParkedClearance" and self._value("ParkedClearance")[0] != "1":
|
||||
return False
|
||||
if (key == "LaneCenteringPauseOnSignal" and self._value("LaneCentering")[0] != "1" and
|
||||
not (reset_default and request.value == ("On" if self._default(key) == "1" else "Off"))):
|
||||
return False
|
||||
@@ -1769,6 +1769,10 @@ class FeatureSettingsOwner:
|
||||
from openpilot.starpilot.lateral.lane_runtime import runtime_supported
|
||||
if not runtime_supported(self.vehicle_params()):
|
||||
return False
|
||||
if key in PARKED_KEYS:
|
||||
from openpilot.starpilot.lateral.parked_runtime import runtime_supported as parked_supported
|
||||
if not parked_supported(self.vehicle_params()) or key != "ParkedClearance" and self._value("ParkedClearance")[0] != "1":
|
||||
return False
|
||||
if ((request.vehicle_fingerprint is not None if key in ("ShowSpeedLimits", "AlwaysAllowUploads") else
|
||||
self.vehicle_fingerprint() != request.vehicle_fingerprint) or
|
||||
not self.authority(group) or self._raw(source_key) != request.expected or
|
||||
|
||||
@@ -316,16 +316,6 @@ class MiciSidebarWidgets:
|
||||
self._stop_icon(center)
|
||||
elif (preview is not None and preview.curve_curvature is not None and state.alert.size != AlertSize.FULL) or curve_controlling(state):
|
||||
self._curve_icon(center)
|
||||
elif state.e2e_preview_slowdown is not None and state.alert.size != AlertSize.FULL:
|
||||
match state.e2e_preview_slowdown:
|
||||
case 'Stopping':
|
||||
self._stop_icon(center)
|
||||
case 'Lead vehicle':
|
||||
self._lead_icon(center)
|
||||
case 'Curve':
|
||||
self._curve_icon(center)
|
||||
case _:
|
||||
self._slowdown_icon(center)
|
||||
elif conditional is not None and self.fonts is not None:
|
||||
family, _, color = conditional
|
||||
reason = conditional_reason(state)
|
||||
@@ -389,12 +379,6 @@ class MiciSidebarWidgets:
|
||||
def _lead_icon(self, rect: rl.Rectangle) -> None:
|
||||
draw_lead_icon(rect)
|
||||
|
||||
def _slowdown_icon(self, rect: rl.Rectangle) -> None:
|
||||
cx, cy = rect.x + rect.width / 2, rect.y + rect.height / 2
|
||||
blue = rl.Color(112, 192, 216, 255)
|
||||
_line(cx - 12, cy - 5, cx, cy + 7, blue, 4)
|
||||
_line(cx, cy + 7, cx + 12, cy - 5, blue, 4)
|
||||
|
||||
def _stop_icon(self, rect: rl.Rectangle) -> None:
|
||||
draw_stop_light_icon(rect)
|
||||
|
||||
|
||||
@@ -185,7 +185,6 @@ class OnroadState:
|
||||
experimental_available: bool = False
|
||||
experimental_enabled: bool = False
|
||||
e2e_slowdown: str | None = None
|
||||
e2e_preview_slowdown: str | None = None
|
||||
torque_utilization: float = 0.0
|
||||
personality: int = 1
|
||||
lead_detected: bool = False
|
||||
|
||||
@@ -801,27 +801,8 @@ class RuntimeSnapshotAdapter:
|
||||
drive_mode_source, display_car, cp=cp, drive_frame=after,
|
||||
event_ns=int(sm.logMonoTime['starpilotCarState']) if drive_mode_source is not None else 0, now_ns=now_ns,
|
||||
native_alert=alert, traffic_active=bool(traffic is not None and traffic.state == 'active'))
|
||||
e2e_mode = observed_experimental and self._conditional_choice in (None, ModeChoice.STOCK)
|
||||
e2e_preview_slowdown = None
|
||||
if e2e_mode and not display_long_active and ui.has_longitudinal_control and display_car_valid:
|
||||
model_action = getattr(display_model, 'action', None)
|
||||
if getattr(model_action, 'shouldStop', False):
|
||||
e2e_preview_slowdown = "Stopping"
|
||||
else:
|
||||
paired_plan = (display_plan is not None and display_model is not None and
|
||||
getattr(display_plan, 'modelMonoTime', None) == sm.logMonoTime['modelV2'])
|
||||
plan_target = getattr(display_plan, 'aTarget', 0.0) if paired_plan else 0.0
|
||||
source = getattr(display_plan, 'longitudinalPlanSource', None) if paired_plan else None
|
||||
model_target = getattr(model_action, 'desiredAcceleration', 0.0)
|
||||
if math.isfinite(plan_target) and plan_target < -0.15 and source in ('lead0', 'lead1') and getattr(display_plan, 'hasLead', False):
|
||||
e2e_preview_slowdown = "Lead vehicle"
|
||||
elif (math.isfinite(plan_target) and plan_target < -0.15 and source == 'cruise' and
|
||||
curve is not None and curve.applied and curve.controlling):
|
||||
e2e_preview_slowdown = "Curve"
|
||||
elif math.isfinite(model_target) and model_target < -0.15:
|
||||
e2e_preview_slowdown = "Slowing"
|
||||
e2e_slowdown = None
|
||||
if (e2e_mode and
|
||||
if (observed_experimental and self._conditional_choice in (None, ModeChoice.STOCK) and
|
||||
display_long_active and not longitudinal_overridden and display_plan is not None):
|
||||
target = getattr(display_plan, 'aTarget', None)
|
||||
if bool(getattr(display_plan, 'shouldStop', False)):
|
||||
@@ -852,7 +833,7 @@ class RuntimeSnapshotAdapter:
|
||||
appearance=self._appearance_value, customization=self._customization_value,
|
||||
alert=alert, metric=bool(ui.is_metric), slc_offset_schedule=self._slc_offset_schedule,
|
||||
experimental_available=bool(ui.has_longitudinal_control),
|
||||
experimental_enabled=observed_experimental, e2e_slowdown=e2e_slowdown, e2e_preview_slowdown=e2e_preview_slowdown,
|
||||
experimental_enabled=observed_experimental, e2e_slowdown=e2e_slowdown,
|
||||
personality=list(Personality).index(persona),
|
||||
lead_detected=bool(display_plan is not None and display_plan.hasLead),
|
||||
gas_pressed_override=bool(display_events is not None and any(
|
||||
|
||||
@@ -16,7 +16,7 @@ def test_native_chestnut_status_accepts_typed_params(raw, expected, tmp_path):
|
||||
params.get_param_path.side_effect = lambda key: str(tmp_path / key)
|
||||
params.get.return_value = raw
|
||||
params.get_bool.return_value = False
|
||||
state = Mock(spec=UIState, params=params, started=True, chestnut_compiled=True, usb_connected=False, _gpu_artifacts=None)
|
||||
state = Mock(spec=UIState, params=params, started=True, chestnut_compiled=True, usb_connected=False)
|
||||
with patch('openpilot.selfdrive.ui.ui_state.get_cache', return_value=None), \
|
||||
patch('openpilot.selfdrive.ui.ui_state.cable_connected', return_value=False):
|
||||
UIState.update_params(state)
|
||||
|
||||
@@ -505,14 +505,14 @@ class NativeSettingsPageTests(unittest.TestCase):
|
||||
# Run the real controller methods with only device services isolated.
|
||||
source = Path('openpilot/selfdrive/ui/layouts/settings/toggles.py')
|
||||
layout = next(node for node in ast.parse(source.read_text()).body if isinstance(node, ast.ClassDef) and node.name == 'TogglesLayout')
|
||||
methods = {'_update_toggles', '_update_state', '_toggle_callback', '_toggle_action',
|
||||
methods = {'_update_toggles', '_update_state', '_toggle_callback',
|
||||
'request_toggle', 'request_personality', '_set_longitudinal_personality'}
|
||||
layout.bases = []
|
||||
layout.body = [node for node in layout.body if isinstance(node, ast.FunctionDef) and node.name in methods]
|
||||
ui = NS(CP=None, engaged=False, parked=True, update_params=Mock(), sm=NS(updated={'selfdriveState': False}))
|
||||
app = NS(push_widget=Mock())
|
||||
namespace = ModuleType('toggles_controller_test')
|
||||
namespace.__dict__.update(tr=lambda text: text, ui_state=ui, ToggleAction=ToggleAction)
|
||||
namespace.__dict__.update(tr=lambda text: text, ui_state=ui)
|
||||
exec(compile(ast.Module(body=[layout], type_ignores=[]), str(source), 'exec'), namespace.__dict__)
|
||||
owner = namespace.TogglesLayout()
|
||||
class SavedParams(Params):
|
||||
|
||||
@@ -383,41 +383,6 @@ class TestOnroadAxes(unittest.TestCase):
|
||||
companion.sourcePlanMonoTime -= 1
|
||||
self.assertEqual(self.state(True, True).e2e_slowdown, 'Slowing')
|
||||
|
||||
def test_end_to_end_sidebar_previews_slowdown_without_longitudinal_engagement(self):
|
||||
self.ui.params.put('ConditionalModeConfig', json.loads(encode_preferences(SavedPreferences(mode=ModeChoice.STOCK))), block=True)
|
||||
sm = self.ui.sm
|
||||
sm['selfdriveState'].experimentalMode = True
|
||||
sm['selfdriveState'].enabled = False
|
||||
sidebar = MiciSidebarWidgets(Mock())
|
||||
center = rl.Rectangle(476, 80, 60, 80)
|
||||
for stop, target, source, plan_stamp, expected in (
|
||||
(True, -0.12, 'cruise', NOW, '_stop_icon'),
|
||||
(False, -0.25, 'e2e', NOW, '_slowdown_icon'),
|
||||
(False, -0.12, 'lead0', NOW, '_lead_icon'),
|
||||
(False, -0.12, 'lead0', NOW - 1, '_chill_icon'),
|
||||
(False, -0.12, 'cruise', NOW, '_chill_icon'),
|
||||
):
|
||||
with self.subTest(stop=stop, target=target, source=source, plan_stamp=plan_stamp):
|
||||
sm.put('modelV2', NS(action=NS(shouldStop=stop, desiredAcceleration=target)))
|
||||
sm.put('longitudinalPlan', NS(aTarget=-0.8, hasLead=source == 'lead0', shouldStop=False,
|
||||
longitudinalPlanSource=source, modelMonoTime=plan_stamp))
|
||||
for lateral in (True, False):
|
||||
state = self.state(lateral, False)
|
||||
self.assertFalse(state.longitudinal_active)
|
||||
self.assertIsNone(state.e2e_slowdown)
|
||||
self.assertEqual(rgba(axis_status_color(state)), (10, 186, 181, 255) if lateral else (18, 40, 57, 255))
|
||||
with patch.multiple(sidebar, **{name: Mock() for name in ('_stop_icon', '_slowdown_icon', '_lead_icon',
|
||||
'_curve_icon', '_chill_icon', '_speed_icon')}):
|
||||
sidebar._conditional(center, state)
|
||||
getattr(sidebar, expected).assert_called_once()
|
||||
sidebar._speed_icon.assert_not_called()
|
||||
sm.put('modelV2', NS(action=NS(shouldStop=True, desiredAcceleration=-0.5)))
|
||||
sm.valid['modelV2'] = False
|
||||
self.assertIsNone(self.state(True, False).e2e_preview_slowdown)
|
||||
sm.valid['modelV2'] = True
|
||||
sm['selfdriveState'].experimentalMode = False
|
||||
self.assertIsNone(self.state(True, False).e2e_preview_slowdown)
|
||||
|
||||
def test_end_to_end_sidebar_uses_a_moon_until_the_planner_reports_a_specific_reason(self):
|
||||
self.ui.params.put('ConditionalModeConfig', json.loads(encode_preferences(SavedPreferences(mode=ModeChoice.STOCK))), block=True)
|
||||
self.ui.sm['selfdriveState'].experimentalMode = True
|
||||
|
||||
@@ -158,7 +158,6 @@ def test_actual_c4_startup_redirect_only_yields_to_fresh_open_parked_game(monkey
|
||||
owner._prev_onroad, owner._prev_standstill = True, True
|
||||
owner._onroad_time_delay = 5.
|
||||
owner._onboarding_window = Mock()
|
||||
owner._home_layout = Mock()
|
||||
page = object.__new__(native.SpacePilotPage)
|
||||
page.closed = condition == 'closed'
|
||||
page.session = Mock(stage=native.Stage.CLOSED if page.closed else native.Stage.VERIFYING)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.enhanced_bsm import configured
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
@@ -14,14 +12,10 @@ from openpilot.starpilot.ui.vehicle_bool import VEHICLE_BOOL_KEYS, confirmation_
|
||||
from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences
|
||||
|
||||
|
||||
@pytest.mark.parametrize('factory_bsm', (False, True))
|
||||
def test_vehicle_setting_and_startup_permission(tmp_path, factory_bsm):
|
||||
def test_vehicle_setting_and_startup_permission(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
fw = [structs.CarParams.CarFw(ecu=structs.CarParams.Ecu.hybrid)]
|
||||
fp = gen_empty_fingerprint()
|
||||
if factory_bsm:
|
||||
fp[0][0x3F6] = 8
|
||||
current = SimpleNamespace(cp=CarInterface.get_params(CAR.TOYOTA_PRIUS_TSS2, fp, fw, False, False, False), parked=True)
|
||||
current = SimpleNamespace(cp=CarInterface.get_params(CAR.TOYOTA_PRIUS_TSS2, gen_empty_fingerprint(), fw, False, False, False), parked=True)
|
||||
owner = FeatureSettingsOwner(params, lambda group: current.parked and group in ('vehicle', 'parked_preferences'),
|
||||
vehicle_fingerprint=lambda: current.cp.carFingerprint, vehicle_params=lambda: current.cp)
|
||||
|
||||
@@ -52,6 +46,8 @@ def test_vehicle_setting_and_startup_permission(tmp_path, factory_bsm):
|
||||
params.put_bool('SafeMode', True, block=True)
|
||||
VehicleStartupPreferences.read(params, enabled=True).finalize(cp)
|
||||
assert not configured(cp)
|
||||
current.cp = CarInterface.get_params(CAR.TOYOTA_COROLLA_TSS2, fp, fw, False, False, False)
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0][0x3F6] = 8
|
||||
current.cp = CarInterface.get_params(CAR.TOYOTA_PRIUS_TSS2, fp, fw, False, False, False)
|
||||
assert not rows()
|
||||
assert not configured(prefs.prepare(current.cp))
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_renderer_dispatches_each_widget_in_saved_order(profile, viewport):
|
||||
method = next(node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == '_ordered_widgets')
|
||||
namespace: dict[str, Any] = {'CLOCK_WIDGET': CLOCK_WIDGET, 'MODE_WIDGET': MODE_WIDGET, 'placement': placement, 'widget_order': widget_order,
|
||||
'RAIL_WIDGETS': RAIL_WIDGETS, 'STOPPED_TIMER_WIDGET': STOPPED_TIMER_WIDGET,
|
||||
'render_rear_fog': lambda *args: seen.append('rear_fog'), 'compact_wheel_warning': lambda state: False,
|
||||
'render_rear_fog': lambda *args: seen.append('rear_fog'),
|
||||
'manual_slc_confirmation': lambda profile, state: False, 'AlertSize': NS(NONE='none', FULL='full'), 'CameraViewChoice': NS(NONE='none'),
|
||||
'rl': NS(Rectangle=lambda x, y, width, height: NS(x=x, y=y, width=width, height=height))}
|
||||
exec(compile(ast.Module(body=[method], type_ignores=[]), str(source), 'exec'), namespace)
|
||||
|
||||
@@ -462,24 +462,12 @@ class TestAthenadMethods(OpenpilotTestCase):
|
||||
fn = self._create_file('qlog.zst')
|
||||
item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251
|
||||
|
||||
started, release = threading.Event(), threading.Event()
|
||||
upload = athenad._do_upload
|
||||
athenad.upload_queue.put_nowait(item)
|
||||
self._wait_for_upload()
|
||||
|
||||
def hold_upload(*args, **kwargs):
|
||||
started.set()
|
||||
if not release.wait(5):
|
||||
raise TimeoutError("Upload queue assertion did not release the transfer")
|
||||
return upload(*args, **kwargs)
|
||||
|
||||
with mock.patch.object(athenad, "_do_upload", side_effect=hold_upload):
|
||||
athenad.upload_queue.put_nowait(item)
|
||||
try:
|
||||
assert started.wait(5)
|
||||
items = dispatcher["listUploadQueue"]()
|
||||
assert len(items) == 1
|
||||
assert items[0]['current'] and items[0]['path'] == fn
|
||||
finally:
|
||||
release.set()
|
||||
items = dispatcher["listUploadQueue"]()
|
||||
assert len(items) == 1
|
||||
assert items[0]['current']
|
||||
|
||||
def test_list_upload_queue_priority(self):
|
||||
priorities = (25, 50, 99, 75, 0)
|
||||
|
||||
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.
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.
Binary file not shown.
Binary file not shown.
@@ -1,4 +1,4 @@
|
||||
#pragma once
|
||||
|
||||
extern const uint8_t gitversion[29];
|
||||
const uint8_t gitversion[29] = "DEV-57f15547-Pf38f504f-DEBUG";
|
||||
const uint8_t gitversion[29] = "DEV-6bd89852-Pf38f504f-DEBUG";
|
||||
|
||||
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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user