subaru: add 2025 Legacy AOL, angle control, HUD/DBC, AVH, twitch guard, and standstill BSM mute

This commit is contained in:
Frogger900
2026-11-21 10:18:43 -05:00
parent 008b0cbcf1
commit cb3ebdd09e
55 changed files with 1916 additions and 230 deletions
+20 -7
View File
@@ -10,7 +10,7 @@ def checksum(address, data):
def avh_request(template, step):
if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2):
if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2, 3, 4):
raise ValueError("Invalid AVH template or counter step")
data = bytearray(template)
data[1] = (data[1] & 0xF0) | ((data[1] + step) & 0xF)
@@ -27,6 +27,8 @@ class AvhStartup:
self.last_time = None
self.stable_since = None
self.frames = {}
self.avh_req_gap = None
self.avh_req_same_payload = False
self.done = False
self.followup = None
@@ -85,6 +87,9 @@ class AvhStartup:
# checks their full counter stream; require consecutive head-unit frames here.
sequential = bool(previous and (address not in (AVH_REQUEST, AVH_STATUS) or
(data[1] & 15) == ((previous[1][1] + 1) & 15)))
if address == AVH_REQUEST and previous is not None and timestamp > previous[0]:
self.avh_req_gap = timestamp - previous[0]
self.avh_req_same_payload = data[2:] == previous[1][2:]
self.frames[address] = (timestamp, data, sequential)
fresh = all(a in self.frames and self.frames[a][2] and
@@ -104,20 +109,25 @@ class AvhStartup:
if self.stable_since is None:
self.stable_since = now
if self.followup is not None:
sent, timestamp, template = self.followup
sent, timestamp, template, step = self.followup
if now - sent > 0.075 or self.frames[AVH_REQUEST][0] != timestamp:
self.done = True
elif now - sent >= 0.05:
self.done = True
return [avh_request(template, 2)]
next_step = step + 1
if next_step == 4:
self.done = True
self.followup = None
else:
self.followup = (now, timestamp, template, next_step)
return [avh_request(template, next_step)]
return []
if (now - self.started < 10 or now - self.stable_since < 3 or
(self.configured_since is not None and now - self.configured_since < 10)):
return []
timestamp, template, _ = self.frames[AVH_REQUEST]
if now - timestamp > 0.010:
if now - timestamp > 0.010 or self.avh_req_gap is None or self.avh_req_gap < 0.80 or not self.avh_req_same_payload:
return []
self.followup = (now, timestamp, template)
self.followup = (now, timestamp, template, 1)
return [avh_request(template, 1)]
@@ -143,6 +153,7 @@ class AvhSources:
def __init__(self):
self.frames = {}
self.sequential = {}
self.source_ns = {}
self.blocked = False
def observe(self, packets, *, boot_ns, mono_ns):
@@ -163,10 +174,12 @@ class AvhSources:
if data != previous[1]:
self.blocked = True
continue
if source <= previous[0] * 1e9:
prev_ns = self.source_ns[address]
if source < prev_ns or (source == prev_ns and counter != ((previous[1][1] + 1) & 15)):
self.blocked = True
continue
self.sequential[address] = previous is not None and counter == ((previous[1][1] + 1) & 15)
self.source_ns[address] = source
self.frames[address] = source / 1e9, data
def fresh(self, now):
+155 -24
View File
@@ -27,13 +27,18 @@ class CarController(CarControllerBase):
from opendbc.car.subaru.avh import selected as avh_selected, AvhStartup
self.avh_startup = AvhStartup() if avh_selected(CP) else None
self.apply_torque_last = 0
self.angle_filter = FirstOrderFilter(0.0, 0.3, DT_CTRL) if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else None
self.angle_filter = (FirstOrderFilter(0.0, 0.3, DT_CTRL)
if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025)
else None)
self.apply_angle_last = 0.
self.angle_was_active = False
self.angle_override_frames = 0
self.eps_stall_count = 0
self.ascent_angle_initialized = False
self.ascent_es_distance_counter_last = None
self.ascent_lkas_alert_counter_last = None
self.aol_non_drive_ticks = 0
self.aol_dash_green_last = False
self.angle_driver_override = False
self.angle_handoff_active = False
self.VM = VehicleModel(CP) if CP.carFingerprint in GEN2_ANGLE_PORTS else None
@@ -62,7 +67,7 @@ class CarController(CarControllerBase):
self.angle_handoff_active = False
return False
high, low = (150, 100) if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else (200, 150)
torque = abs(CS.out.steeringTorque)
torque = abs(float(CS.out.steeringTorque))
if self.angle_driver_override:
if torque < low:
self.angle_driver_override = False
@@ -85,12 +90,72 @@ class CarController(CarControllerBase):
return False
return True
@staticmethod
def _legacy_2025_effective_lateral_off(CS, CC) -> bool:
if bool(getattr(CS, "aol_enabled", True)):
return bool(getattr(CS, "lateral_off", False))
return not bool(CC.enabled)
def _legacy_2025_aol_dash_green(self, hud_control, CS, cruise_available: bool, lateral_off: bool) -> bool:
if (
lateral_off or not cruise_available or
CS.out.steerFaultTemporary or CS.out.steerFaultPermanent
):
self.aol_non_drive_ticks = 0
self.aol_dash_green_last = False
return False
Gear = structs.CarState.GearShifter
if CS.out.gearShifter == Gear.park:
self.aol_non_drive_ticks = 0
green = bool(hud_control.lanesVisible)
self.aol_dash_green_last = green
return green
if CS.out.gearShifter in (Gear.drive, Gear.manumatic):
self.aol_non_drive_ticks = 0
stationary_aol_green = bool(
hud_control.lanesVisible and
(CS.out.standstill or CS.out.vEgoRaw <= 0.44704) and
not CS.out.steeringPressed and
not self.angle_driver_override and not self.angle_handoff_active
)
green = bool(self.angle_was_active or stationary_aol_green)
self.aol_dash_green_last = green
return green
self.aol_non_drive_ticks += 1
if self.aol_non_drive_ticks >= 80:
self.aol_dash_green_last = False
return False
return self.aol_dash_green_last
def _ascent_lkas_alert(self, CC, CS):
if self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023 or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
if self.CP.carFingerprint not in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
return None
dat = CS.es_lkas_alert_dat
lateral_active = self.angle_was_active and CC.latActive and (CC.enabled or subaru_aol_qualified(self.CP, marked_only=True))
msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert)
is_legacy_2025 = self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025
lateral_active = self.angle_was_active and CC.latActive and (
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
)
if is_legacy_2025:
armed = CS.out.cruiseState.available
if self.CP.openpilotLongitudinalControl:
acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible)
else:
dashstatus_msg = getattr(CS, "es_dashstatus_msg", None)
if dashstatus_msg and ("Cruise_Activated_Dash" in dashstatus_msg or "Cruise_State" in dashstatus_msg):
cruise_active = bool(
dashstatus_msg.get("Cruise_Activated_Dash", 0) and
dashstatus_msg.get("Cruise_State", 1) != 2 and
not CS.out.gasPressed
)
else:
cruise_active = bool(CS.out.cruiseState.enabled and not CS.out.gasPressed)
acc_lead_visible = bool(cruise_active and dashstatus_msg and dashstatus_msg.get("Car_Follow", 0))
msg = subarucan.create_ascent_lkas_alert(
dat, lateral_active, CC.hudControl.visualAlert,
armed=armed, acc_lead_visible=acc_lead_visible, legacy_2025=True,
)
else:
msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert)
if msg is None or (dat[1] & 0xf) == self.ascent_lkas_alert_counter_last:
return None
self.ascent_lkas_alert_counter_last = dat[1] & 0xf
@@ -127,21 +192,48 @@ class CarController(CarControllerBase):
if (self.frame % self.p.STEER_STEP) == 0:
if self.CP.carFingerprint in GEN2_ANGLE_PORTS:
independent_lateral = subaru_aol_qualified(self.CP, marked_only=True)
# Preserve large-turn admission; active Jacobw ports retain their native angle envelope.
angle_continuation = (self.angle_was_active and self.angle_filter is not None and
abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE)
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and
(abs(CS.out.steeringAngleDeg) < 120. or angle_continuation))
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
if CC.latActive and not CC.enabled:
# Hold max AOL angle cleanly inside the 210 deg cutout ceiling instead of steering out of bounds.
angle_target = float(np.clip(angle_target, -200., 200.))
max_mads_angle = 210. if self.angle_was_active else 200.
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and abs(CS.out.steeringAngleDeg) <= max_mads_angle)
gear_ok = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
else:
# Preserve large-turn admission; active Jacobw ports retain their native angle envelope.
angle_continuation = (self.angle_was_active and self.angle_filter is not None and
abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE)
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and
(abs(CS.out.steeringAngleDeg) < 120. or angle_continuation))
gear_ok = CS.out.gearShifter == structs.CarState.GearShifter.drive
legacy_lateral_off = self._legacy_2025_effective_lateral_off(CS, CC) if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 else False
angle_available = (CC.latActive and aol_motion_ok and CS.out.cruiseState.available and
(independent_lateral or CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed) and
CS.out.gearShifter == structs.CarState.GearShifter.drive and
(independent_lateral or (CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed)) and
gear_ok and
not legacy_lateral_off and
not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent)
angle_active = self.angle_active(CS, angle_available)
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
if angle_active and self.angle_was_active and abs(self.apply_angle_last - CS.out.steeringAngleDeg) > 5.0:
self.eps_stall_count += 1
if self.eps_stall_count >= 8:
# Yield via handoff before EPS rack latches Steer_Error_1, then re-sync next step.
self.angle_handoff_active = True
angle_active = False
self.eps_stall_count = 0
else:
self.eps_stall_count = 0
if not angle_active and self.angle_filter is not None:
self.angle_filter.x = CS.out.steeringAngleDeg
if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023 and not self.ascent_angle_initialized:
self.apply_angle_last = CS.out.steeringAngleDeg
self.ascent_angle_initialized = True
angle_active = False
if self.CP.carFingerprint in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
apply_angle = apply_std_steer_angle_limits(angle_target, self.apply_angle_last,
CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active,
self.p.LEGACY_2025_ANGLE_LIMITS)
elif self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
apply_angle = apply_std_steer_angle_limits(actuators.steeringAngleDeg, self.apply_angle_last,
CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active,
self.p.FIXED_ANGLE_LIMITS)
@@ -214,6 +306,14 @@ class CarController(CarControllerBase):
can_sends.extend(send_sng(self, CC, CS, now_nanos))
# *** alerts and pcm cancel ***
enabled_for_dash_2025 = False
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
enabled_for_dash_2025 = self._legacy_2025_aol_dash_green(
hud_control,
CS,
bool(CS.out.cruiseState.available),
self._legacy_2025_effective_lateral_off(CS, CC),
)
lkas_alert_msg = self._ascent_lkas_alert(CC, CS)
if lkas_alert_msg is not None:
can_sends.append(lkas_alert_msg)
@@ -241,18 +341,49 @@ class CarController(CarControllerBase):
can_sends.append(subarucan.create_es_dashstatus(self.packer, self.frame // 10, CS.es_dashstatus_msg, CC.enabled,
self.CP.openpilotLongitudinalControl, CC.longActive, hud_control.leadVisible))
lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled
lkas_state_msg = CS.es_lkas_state_msg
if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True):
if self.CP.carFingerprint not in GEN2_ANGLE_PORTS:
lkas_active = CC.latActive
lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active))
can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert,
hud_control.leftLaneVisible, hud_control.rightLaneVisible,
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
cruise_available = CS.out.cruiseState.available
lateral_off = self._legacy_2025_effective_lateral_off(CS, CC)
aol_enabled = bool(getattr(CS, "aol_enabled", True))
wheel_ready = bool(cruise_available and aol_enabled)
if not (in_drive and cruise_available) or lateral_off or not hud_control.lanesVisible:
left_line = 0
right_line = 0
left_depart = False
right_depart = False
else:
left_line = 1 if hud_control.leftLaneVisible else 0
right_line = 1 if hud_control.rightLaneVisible else 0
left_depart = bool(hud_control.leftLaneDepart)
right_depart = bool(hud_control.rightLaneDepart)
can_sends.append(subarucan.create_es_lkas_state(
self.packer, self.frame // 10, CS.es_lkas_state_msg, enabled_for_dash_2025, hud_control.visualAlert,
left_line, right_line, left_depart, right_depart,
ready=wheel_ready, lkas_active=True, in_drive=in_drive,
))
else:
lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled
lkas_state_msg = CS.es_lkas_state_msg
if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True):
if self.CP.carFingerprint not in GEN2_ANGLE_PORTS:
lkas_active = CC.latActive
lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active))
can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert,
hud_control.leftLaneVisible, hud_control.rightLaneVisible,
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
can_sends.append(subarucan.create_es_infotainment(self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert))
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
can_sends.append(subarucan.create_es_infotainment(
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
audible_alert=hud_control.audibleAlert, legacy_2025=True,
))
else:
can_sends.append(subarucan.create_es_infotainment(
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
))
if self.CP.openpilotLongitudinalControl:
if self.frame % 5 == 0:
@@ -266,7 +397,7 @@ class CarController(CarControllerBase):
self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle))
else:
cancel_frame_ready = True
if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023:
if self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
stock_counter = CS.es_distance_msg["COUNTER"]
cancel_frame_ready = stock_counter != self.ascent_es_distance_counter_last
self.ascent_es_distance_counter_last = stock_counter
+81 -6
View File
@@ -6,6 +6,10 @@ from opendbc.car.interfaces import CarStateBase
from opendbc.car.subaru.values import CAR, DBC, CanBus, SubaruFlags
from opendbc.car import CanSignalRateCalculator
# 8-speed Lineartronic CVT simulated paddle-shift ratios 1..8 on 0x48 Transmission.Gear
# (bits 0..2 = 0b001 Drive range, bits 3..6 = simulated gear 1..8 or 0 in shift transition, bit 7 = manual mode)
SUBARU_CVT_MANUAL_GEARS = frozenset({129, 137, 145, 153, 161, 169, 177, 185, 193})
class CarState(CarStateBase):
def __init__(self, CP):
@@ -33,6 +37,32 @@ class CarState(CarStateBase):
from opendbc.car.subaru.high_angle_guard import HighAngleGuard, selected
self.high_angle_guard = HighAngleGuard() if selected(CP) else None
self.high_angle_cut = False
self.prev_cam_lkas_toggle: bool | None = None
self.prev_cruise_available: bool | None = None
self.aol_enabled = True
self.lateral_off = False
self._prev_aol_enabled: bool | None = None
self._lkas_event_hold_frames = 0
self._lkas_mode_settle_frames = 0
def _sync_legacy_2025_lateral_mode(self, cruise_available: bool, lkas_pressed: bool) -> None:
aol = bool(getattr(self, "aol_enabled", True))
if not cruise_available:
self.lateral_off = not aol
self._lkas_mode_settle_frames = 0
self._prev_aol_enabled = aol
return
entered_mode = (not bool(self.prev_cruise_available)) or (aol != self._prev_aol_enabled)
if entered_mode:
self._lkas_mode_settle_frames = 15
self.lateral_off = not aol
elif lkas_pressed:
self._lkas_mode_settle_frames = 15
self.lateral_off = (not self.lateral_off) if aol else True
else:
self._lkas_mode_settle_frames = max(0, self._lkas_mode_settle_frames - 1)
self._prev_aol_enabled = aol
def update(self, can_parsers) -> structs.CarState:
cp = can_parsers[Bus.pt]
@@ -78,7 +108,12 @@ class CarState(CarStateBase):
cp_transmission = cp_alt if self.CP.flags & SubaruFlags.HYBRID else cp
can_gear = int(cp_transmission.vl["Transmission"]["Gear"])
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None))
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear in SUBARU_CVT_MANUAL_GEARS:
ret.gearShifter = structs.CarState.GearShifter.manumatic
elif self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear == 0:
ret.gearShifter = structs.CarState.GearShifter.neutral
else:
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None))
if not (self.CP.flags & SubaruFlags.LKAS_ANGLE):
ret.steeringAngleDeg = cp_angle.vl["Steering_Torque"]["Steering_Angle"]
@@ -102,11 +137,14 @@ class CarState(CarStateBase):
cp_cruise = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp
cp_es_brake = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp_cam
soft_disable = False
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
soft_disable = cp_cam.vl["ES_DashStatus"].get("Cruise_Soft_Disable", 0) != 0
if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023):
ret.cruiseState.enabled = cp_es_brake.vl["ES_Status"]["Cruise_Activated"] != 0
ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0
ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0) and not soft_disable
elif self.CP.flags & (SubaruFlags.HYBRID | SubaruFlags.LKAS_ANGLE):
# ES_DashStatus->Cruise_Activated_Dash is likely intended for the dash display only, as it falls
# during user gas override and at standstill. ES_Status is missing on hybrid, so we use ES_Brake instead
@@ -115,10 +153,10 @@ class CarState(CarStateBase):
# brake while engaged at a stop. ES_Status and ES_DashStatus->Signal7 correctly fell, but is either missing or
# always zero on hybrids. Probably need to split angle & hybrid. 0x27 and 0x225 on hybrids may work for them.
ret.cruiseState.enabled = cp_es_brake.vl["ES_Brake"]['Cruise_Activated'] != 0
ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0
ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0) and not soft_disable
else:
ret.cruiseState.enabled = cp_cruise.vl["CruiseControl"]["Cruise_Activated"] != 0
ret.cruiseState.available = cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0
ret.cruiseState.available = (cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0) and not soft_disable
ret.cruiseState.speed = cp_cam.vl["ES_DashStatus"]["Cruise_Set_Speed"] * CV.KPH_TO_MS
if (self.CP.flags & SubaruFlags.PREGLOBAL and cp.vl["Dash_State2"]["UNITS"] == 1) or \
@@ -148,6 +186,34 @@ class CarState(CarStateBase):
self.es_lkas_state_msg = copy.copy(cp_cam.vl["ES_LKAS_State"])
self.es_brake_msg = copy.copy(cp_es_brake.vl["ES_Brake"])
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
cam_lkas_toggle = int(self.es_lkas_state_msg.get("LKAS_Dash_State", 0)) > 0
steer_fault = bool(ret.steerFaultTemporary or ret.steerFaultPermanent)
lkas_pressed = False
if steer_fault or not ret.cruiseState.available:
self.prev_cam_lkas_toggle = None
self._lkas_event_hold_frames = 0
else:
if (
self.prev_cam_lkas_toggle is not None
and self.prev_cruise_available
and cam_lkas_toggle != self.prev_cam_lkas_toggle
):
lkas_pressed = True
self._lkas_event_hold_frames = 5
self.prev_cam_lkas_toggle = cam_lkas_toggle
if self._lkas_event_hold_frames > 0:
button_events = list(ret.buttonEvents) if ret.buttonEvents else []
ButtonType = structs.CarState.ButtonEvent.Type
button_events.extend([
structs.CarState.ButtonEvent(pressed=True, type=ButtonType.lkas),
structs.CarState.ButtonEvent(pressed=False, type=ButtonType.lkas),
])
ret.buttonEvents = button_events
self._lkas_event_hold_frames -= 1
self._sync_legacy_2025_lateral_mode(bool(ret.cruiseState.available), lkas_pressed)
self.prev_cruise_available = bool(ret.cruiseState.available)
# TODO: Hybrid cars don't have ES_Distance, need a replacement
if not (self.CP.flags & SubaruFlags.HYBRID):
# 8 is known AEB, there are a few other values related to AEB we ignore
@@ -190,8 +256,17 @@ class CarState(CarStateBase):
self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"])
if self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
alert = cp_cam.vl["ES_LKAS_Alert"]
self.es_lkas_alert_dat = (bytes((int(alert["CHECKSUM"]), int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4))) +
int(alert["Payload"]).to_bytes(6, "little"))
self.es_lkas_alert_dat = (
bytes((
int(alert["CHECKSUM"]),
int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4),
int(alert["LKAS_Alert"]),
int(alert["LKAS_Alert_Msg"]),
int(alert["LKAS_HUD_Lights"]),
int(alert["ACC_Lead_LED"]),
)) +
int(alert["Signal2"]).to_bytes(2, "little")
)
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
self.es_infotainment_msg = copy.copy(cp_cam.vl["ES_Infotainment"])
+2 -1
View File
@@ -14,6 +14,7 @@ GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025
class CarInterface(CarInterfaceBase):
CarState = CarState
CarController = CarController
DRIVABLE_GEARS = (structs.CarState.GearShifter.manumatic,)
def update(self, can_packets):
source = self.CS.startup_sources
@@ -58,7 +59,7 @@ class CarInterface(CarInterfaceBase):
if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]:
ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value
if candidate == CAR.SUBARU_ASCENT_2023 and fingerprint[CanBus.camera].get(0x3C4) == 8:
if candidate in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) and fingerprint[CanBus.camera].get(0x3C4) == 8:
ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value
if ret.flags & SubaruFlags.PREGLOBAL:
+7 -2
View File
@@ -30,7 +30,7 @@ def qualified(cp, *, marked_only=False):
if cp.flags & SubaruFlags.STOP_START_OFF:
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
if cp.carFingerprint == CAR.SUBARU_LEGACY_2025:
allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP)
allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
if cp.flags & SubaruFlags.AVH_STARTUP:
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
if cp.flags & SubaruFlags.STOP_START_OFF:
@@ -59,6 +59,11 @@ def qualified(cp, *, marked_only=False):
def temporary_restriction(cp, state):
allowed_gears = (
(structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
if cp is not None and cp.carFingerprint == CAR.SUBARU_LEGACY_2025 else
(structs.CarState.GearShifter.drive,)
)
return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and
not state.steerFaultPermanent and not state.accFaulted and state.cruiseState.available and
(state.gearShifter != structs.CarState.GearShifter.drive or state.steerFaultTemporary or state.standstill))
(state.gearShifter not in allowed_gears or state.steerFaultTemporary or state.standstill))
+119 -29
View File
@@ -2,6 +2,7 @@ from opendbc.car import structs
from opendbc.car.subaru.values import CanBus
VisualAlert = structs.CarControl.HUDControl.VisualAlert
AudibleAlert = structs.CarControl.HUDControl.AudibleAlert
def create_steering_control(packer, apply_torque, steer_req):
@@ -67,7 +68,8 @@ def create_es_distance(packer, frame, es_distance_msg, bus, pcm_cancel_cmd, long
return packer.make_can_msg("ES_Distance", bus, values)
def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart):
def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart,
ready=None, lkas_active=None, in_drive=False):
values = {s: es_lkas_state_msg[s] for s in [
"CHECKSUM",
"LKAS_Alert_Msg",
@@ -88,29 +90,43 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert
values["COUNTER"] = frame % 0x10
# Filter the stock LKAS "Keep hands on wheel" alert
if values["LKAS_Alert_Msg"] == 1:
values["LKAS_Alert_Msg"] = 0
legacy_2025_hud = (ready is not None) or (lkas_active is not None)
if legacy_2025_hud:
# Filter stock EyeSight centering engage/cancel and "Keep hands on wheel" alerts
# (25: centering engage beep, 27: centering off beep, 28: hands-on warning beep, 30: hands-on OFF cancel beep)
if values["LKAS_Alert"] in (25, 27, 28, 30):
values["LKAS_Alert"] = 0
if values["LKAS_Alert_Msg"] in (1, 7):
values["LKAS_Alert_Msg"] = 0
else:
# Filter the stock LKAS "Keep hands on wheel" alert
if values["LKAS_Alert_Msg"] == 1:
values["LKAS_Alert_Msg"] = 0
# Filter the stock LKAS sending an audible alert when it turns off LKAS
if values["LKAS_Alert"] == 27:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending an audible alert when it turns off LKAS
if values["LKAS_Alert"] == 27:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models)
if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models)
if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models)
if values["LKAS_Alert"] == 30:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models)
if values["LKAS_Alert"] == 30:
values["LKAS_Alert"] = 0
# Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models)
if values["LKAS_Alert_Msg"] == 7:
values["LKAS_Alert_Msg"] = 0
# Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models)
if values["LKAS_Alert_Msg"] == 7:
values["LKAS_Alert_Msg"] = 0
# Preserve stock EyeSight Lane Departure Warnings (11, 12) at all times.
# Show Keep hands on wheel alert for openpilot steerRequired alert
if visual_alert == VisualAlert.steerRequired:
values["LKAS_Alert_Msg"] = 1
if legacy_2025_hud:
if values["LKAS_Alert"] == 0 and values["LKAS_Alert_Msg"] == 0:
values["LKAS_Alert_Msg"] = 1
else:
values["LKAS_Alert_Msg"] = 1
# Ensure we don't overwrite potentially more important alerts from stock (e.g. FCW)
if visual_alert == VisualAlert.ldw and values["LKAS_Alert"] == 0:
@@ -119,14 +135,37 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert
elif right_lane_depart:
values["LKAS_Alert"] = 11 # Right lane departure dash alert
if enabled:
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines
values["LKAS_Dash_State"] = 2 # Green enabled indicator
else:
values["LKAS_Dash_State"] = 0 # LKAS Not enabled
if legacy_2025_hud:
screen_active = True if lkas_active is None else bool(lkas_active)
if screen_active:
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines / keep screen active
values["LKAS_Left_Line_Enable"] = 1
values["LKAS_Right_Line_Enable"] = 1
if enabled:
values["LKAS_Dash_State"] = 2 # 2: Green enabled / active steering
elif ready:
values["LKAS_Dash_State"] = 1 # 1: White ready / override
else:
values["LKAS_Dash_State"] = 0 # 0: Inactive / no steering wheel icon
line_visible = 1 if in_drive else 0
else:
values["LKAS_ACTIVE"] = 0
values["LKAS_Dash_State"] = 0
values["LKAS_Left_Line_Enable"] = 0
values["LKAS_Right_Line_Enable"] = 0
line_visible = 0
values["LKAS_Left_Line_Visible"] = int(left_line)
values["LKAS_Right_Line_Visible"] = int(right_line)
values["LKAS_Left_Line_Visible"] = line_visible if left_line else 0
values["LKAS_Right_Line_Visible"] = line_visible if right_line else 0
else:
if enabled:
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines
values["LKAS_Dash_State"] = 2 # Green enabled indicator
else:
values["LKAS_Dash_State"] = 0 # LKAS Not enabled
values["LKAS_Left_Line_Visible"] = int(left_line)
values["LKAS_Right_Line_Visible"] = int(right_line)
return packer.make_can_msg("ES_LKAS_State", CanBus.main, values)
@@ -231,7 +270,7 @@ def create_es_status(packer, frame, es_status_msg, long_enabled, long_active, cr
return packer.make_can_msg("ES_Status", CanBus.main, values)
def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert, audible_alert=AudibleAlert.none, legacy_2025=False):
# Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts
values = {s: es_infotainment_msg[s] for s in [
"CHECKSUM",
@@ -248,7 +287,12 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
# Show Keep hands on wheel alert for openpilot steerRequired alert
if visual_alert == VisualAlert.steerRequired:
values["LKAS_State_Infotainment"] = 3
if legacy_2025:
# 4 adds wheel OFF icon on lockout without clobbering existing warnings
if values["LKAS_State_Infotainment"] == 0:
values["LKAS_State_Infotainment"] = 4 if audible_alert == AudibleAlert.warningImmediate else 3
else:
values["LKAS_State_Infotainment"] = 3
# Show Obstacle Detected for fcw
if visual_alert == VisualAlert.fcw:
@@ -257,14 +301,60 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
return packer.make_can_msg("ES_Infotainment", CanBus.main, values)
def create_ascent_lkas_alert(raw_dat: bytes, lateral_active: bool, visual_alert):
def create_ascent_lkas_alert(
raw_dat: bytes,
lateral_active: bool,
visual_alert,
armed: bool = False,
acc_lead_visible: bool = False,
legacy_2025: bool = False,
):
address = 0x3C4
if len(raw_dat) != 8 or raw_dat[0] != (((address & 0xff) + (address >> 8) + sum(raw_dat[1:])) & 0xff):
return None
dat = bytearray(raw_dat)
if lateral_active and visual_alert != VisualAlert.steerRequired and dat[2:] == b"\x00\x01\x04\x00\x00\x00":
dat[3:5] = b"\x00\x00"
changed = False
if legacy_2025 and armed:
# 0x3C4 on Legacy 2025: dat[2]=chime (0x18 chirp, 0x1a/0x1b single, 0x1c 2x bouncy, 0x1e 4x strong),
# dat[3]=small-screen popup (0x01 hands-on, 0x07 flashing), dat[4]=HUD LEDs (0x01/0x02/0x04 yellow, 0x10/0x20/0x40 red).
target_alert = b"\x00\x01\x04" if visual_alert == VisualAlert.steerRequired else None
# Suppress all background EyeSight centering/toggle/hands-off alerts whenever Cruise Main is armed,
# while preserving stock FCW (0x01, 0x02, 0x0e), native LDW (0x0b, 0x0c), and opaque status bits in dat[5:].
if dat[2] in (0x19, 0x1b, 0x1c, 0x1e) or (
dat[2] == 0x00 and (
(dat[3] in (0x01, 0x07) and dat[4] in (0x04, 0x30)) or
(dat[3] == 0x00 and dat[4] in (0x02, 0x30))
)
):
if not (target_alert is not None and dat[2:5] == target_alert):
dat[2:5] = b"\x00\x00\x00"
changed = True
if target_alert is not None:
if dat[2:5] == b"\x00\x00\x00":
dat[2:5] = target_alert
changed = True
if dat[2:5] == target_alert and dat[5] == 0x01:
dat[5] = 0x00
changed = True
if lateral_active and visual_alert != VisualAlert.steerRequired:
if dat[2:] == b"\x00\x01\x04\x00\x00\x00":
dat[3:5] = b"\x00\x00"
changed = True
elif legacy_2025 and (dat[2] == 0x1b or (dat[2] == 0x00 and dat[3] == 0x00 and dat[4] == 0x02)):
# Suppress stock lane-centering toggle chime/LED while preserving native LDW (0x0b, 0x0c, 000005, 000006)
dat[2:5] = b"\x00\x00\x00"
changed = True
# Restore dat[5] = 0x01 when ACC is tracking a lead and background LKAS warning cleared dat[5].
if legacy_2025 and acc_lead_visible and dat[2:5] == b"\x00\x00\x00" and dat[5] == 0x00:
dat[5] = 0x01
changed = True
if changed:
dat[0] = ((address & 0xff) + (address >> 8) + sum(dat[1:])) & 0xff
return address, bytes(dat), CanBus.main
@@ -59,10 +59,12 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
cars = (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023,
CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023)
for car in cars:
for speed, angle, expected in ((5., 119.5, True), (5., -119.5, True),
(5., 120., False), (5., -120., False),
(5., 200., False), (5., -200., False),
(.4, 10., False), (.5, 10., True)):
cases = ((5., 199.5, True), (5., -199.5, True), (5., 200., True), (5., -200., True),
(5., 201., False), (5., -201., False), (.4, 10., False), (.5, 10., True)) \
if car == CAR.SUBARU_LEGACY_2025 else \
((5., 119.5, True), (5., -119.5, True), (5., 120., False), (5., -120., False),
(5., 200., False), (5., -200., False), (.4, 10., False), (.5, 10., True))
for speed, angle, expected in cases:
with self.subTest(car=car, speed=speed, angle=angle):
cp, controller, command, state = setup_controller(car)
cp.alternativeExperience = 32
@@ -80,6 +82,88 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
expected_angle = max(-190., min(190., angle)) if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else angle
self.assertAlmostEqual(decoded['LKAS_Output'], expected_angle, places=2)
def test_legacy_2025_mads_hysteresis_and_eps_stall_guard(self):
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
cp.alternativeExperience = 32
command.enabled = False
state.out.cruiseState.enabled = False
state.out.vEgoRaw = state.out.vEgo = 5.
state.out.standstill = False
state.out.steeringTorque = state.out.steeringRateDeg = 0
state.out.steeringAngleDeg = 199.
command.actuators.steeringAngleDeg = 199.
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
state.out.steeringAngleDeg = 205.
command.actuators.steeringAngleDeg = 205.
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
state.out.steeringAngleDeg = 211.
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 0)
# 8-frame EPS stall guard releases for 1 frame when wheel angle stops tracking target.
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
state.out.vEgoRaw = state.out.vEgo = 5.
state.out.standstill = False
state.out.steeringAngleDeg = 0.
command.actuators.steeringAngleDeg = 0.
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
command.actuators.steeringAngleDeg = 40.
stalled = 0
for _ in range(20):
prev_output = decoded['LKAS_Output']
_, decoded = step(controller, command, state)
if abs(prev_output - state.out.steeringAngleDeg) > 5.0:
stalled += 1
if stalled == 8:
self.assertEqual(decoded['LKAS_Request'], 0)
self.assertEqual(decoded['LKAS_Output'], 0.)
break
self.assertEqual(decoded['LKAS_Request'], 1)
else:
self.fail("EPS stall guard did not trigger after 8 stalled frames")
def test_legacy_2025_aol_clamps_target_to_hold_max_turn(self):
for sign in (-1, 1):
with self.subTest(sign=sign):
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
cp.alternativeExperience = 32
command.enabled = False
state.out.cruiseState.enabled = False
state.out.vEgoRaw = state.out.vEgo = 25.
state.out.standstill = False
state.out.steeringTorque = state.out.steeringRateDeg = 0
state.out.steeringAngleDeg = 199. * sign
command.latActive = False
step(controller, command, state)
command.latActive = True
command.actuators.steeringAngleDeg = 240. * sign
for _ in range(10):
_, decoded = step(controller, command, state)
state.out.steeringAngleDeg = decoded['LKAS_Output']
self.assertEqual(decoded['LKAS_Request'], 1)
self.assertAlmostEqual(decoded['LKAS_Output'], 200. * sign, places=2)
# Active cruise (ACC engaged) is not capped to the AOL 200 deg ceiling.
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
command.enabled = True
state.out.cruiseState.enabled = True
state.out.vEgoRaw = state.out.vEgo = 25.
state.out.standstill = False
state.out.steeringTorque = state.out.steeringRateDeg = 0
state.out.steeringAngleDeg = 199.
command.latActive = False
step(controller, command, state)
command.latActive = True
command.actuators.steeringAngleDeg = 220.
for _ in range(10):
_, decoded = step(controller, command, state)
state.out.steeringAngleDeg = decoded['LKAS_Output']
self.assertEqual(decoded['LKAS_Request'], 1)
self.assertGreater(decoded['LKAS_Output'], 200.)
def test_ordinary_engagement_preserves_transmitted_history_and_other_profiles(self):
for car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023,
CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023):
@@ -94,7 +178,7 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
for _ in range(3):
_, decoded = step(controller, command, state)
self.assertTrue(decoded['LKAS_Request'])
if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025):
if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025):
# The EPS bound applies to transmitted commands, not measured-angle admission.
# Follow the small target without jumping to the measured angle.
expected = -1.45 * (1. - (30. / 31.) ** 5)
@@ -196,7 +196,7 @@ class TestSubaruAscentController(unittest.TestCase):
self.assertEqual(values['Close_Distance'], state.es_distance_msg['Close_Distance'])
self.assertEqual(observed, [0, 1, 3])
def test_repeated_stock_cancel_gate_is_ascent_2023_only(self):
def test_repeated_stock_cancel_gate_cars(self):
for car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025,
CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023, CAR.SUBARU_ASCENT):
with self.subTest(car=car):
@@ -211,7 +211,7 @@ class TestSubaruAscentController(unittest.TestCase):
for tick in range(5):
_, sends = controller.update(command.as_reader(), state, 1_000_000_000 + tick * 10_000_000)
distance.extend(frame for frame in sends if frame[0] == 0x221)
self.assertEqual(len(distance), 1 if car == CAR.SUBARU_ASCENT_2023 else 5)
self.assertEqual(len(distance), 1 if car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) else 5)
self.assertEqual(len(set(distance)), 1)
self.assertEqual(distance[0][2], 1 if cp.flags & SubaruFlags.GLOBAL_GEN2 else 0)
@@ -18,13 +18,14 @@ class TestAscentLkasAlert(unittest.TestCase):
def test_platform_bus_length_gate_preserves_native_identity(self):
for car in CAR:
cp = self.params(car)
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025))
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
for bus, length in ((0, 8), (1, 8), (2, 4), (2, 16)):
cp = self.params(bus=bus, length=length)
self.assertFalse(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT)
self.assertEqual(cp.safetyConfigs[0].safetyParam, 0xB1)
self.assertEqual(self.params().safetyConfigs[0].safetyParam, 0x8B1)
self.assertEqual(self.params(CAR.SUBARU_LEGACY_2025).safetyConfigs[0].safetyParam, 0x91)
def test_production_parser_state_controller_and_actual_request(self):
cp = self.params()
@@ -66,3 +67,27 @@ class TestAscentLkasAlert(unittest.TestCase):
self.assertEqual(subarucan.create_ascent_lkas_alert(bytes(dat), True, 0)[1], dat)
for dat in (b"", bytes(7), bytes(9), bytes.fromhex("0002000104000000")):
self.assertIsNone(subarucan.create_ascent_lkas_alert(dat, True, 0))
def test_legacy_2025_alert_suppression_and_lead_restore(self):
def packet(hex_tail: str):
dat = bytearray(bytes.fromhex("0002" + hex_tail))
dat[0] = (0xC4 + 3 + sum(dat[1:])) & 0xFF
return bytes(dat)
for payload in ("000104000000", "1c0704000000", "000704000000", "1e0030000000", "1b0000000000", "000002000000"):
msg = subarucan.create_ascent_lkas_alert(packet(payload), False, 0, armed=True, acc_lead_visible=False, legacy_2025=True)
self.assertEqual(msg[1][2:5], b"\x00\x00\x00", payload)
self.assertEqual(msg[1][0], (0xC4 + 3 + sum(msg[1][1:])) & 0xFF)
# Restore green ACC lead-car LED (dat[5] = 0x01) when tracking a lead and background alert cleared it.
msg = subarucan.create_ascent_lkas_alert(packet("000104000000"), True, 0, armed=True, acc_lead_visible=True, legacy_2025=True)
self.assertEqual(msg[1][2:], bytes.fromhex("000000010000"))
# Native LDW (0x0b, 0x0c) and openpilot steerRequired (000104000000) work cleanly.
ldw = packet("0b0000010000")
self.assertEqual(subarucan.create_ascent_lkas_alert(ldw, True, 0, armed=True, legacy_2025=True)[1], ldw)
hands_on = subarucan.create_ascent_lkas_alert(
packet("000000010000"), False, structs.CarControl.HUDControl.VisualAlert.steerRequired,
armed=True, legacy_2025=True,
)
self.assertEqual(hands_on[1][2:], bytes.fromhex("000104000000"))
@@ -34,20 +34,30 @@ def test_captured_legacy_press_bytes():
template = bytes.fromhex('5b0b000100800e00')
assert avh_request(template, 1) == (0x6BB, bytes.fromhex('5e0c020100800e00'), 1)
assert avh_request(template, 2) == (0x6BB, bytes.fromhex('5f0d020100800e00'), 1)
assert avh_request(template, 3) == (0x6BB, bytes.fromhex('600e020100800e00'), 1)
assert avh_request(template, 4) == (0x6BB, bytes.fromhex('610f020100800e00'), 1)
wrap = sample(AVH_REQUEST, 15)
assert avh_request(wrap, 1)[1][1] == 0
assert avh_request(wrap, 2)[1][1] == 1
assert avh_request(wrap, 3)[1][1] == 2
assert avh_request(wrap, 4)[1][1] == 3
def test_two_frames_only_and_no_retry():
def test_four_frames_only_and_no_retry():
policy, frames = prepare()
assert policy.update(110.04, frames, True, True, False) == []
assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
assert policy.update(110.07, frames, True, True, False) == []
assert policy.update(110.10, frames, True, True, False) == []
assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
assert policy.update(110.16, frames, True, True, False) == []
assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
assert policy.update(110.20, frames, True, True, False) == []
assert policy.update(111, frames, True, True, False) == []
def test_controller_snapshots_may_skip_fast_can_samples():
policy, frames = prepare(fast_counter_step=2)
assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
@pytest.mark.parametrize('reason', ['late','new_template','manual','ack','moving','gas','gear','invalid','disabled','engaged','stale'])
def test_followup_aborts_permanently(reason):
@@ -69,3 +79,53 @@ def test_followup_aborts_permanently(reason):
assert policy.update(now, frames, reason != 'disabled', reason != 'invalid', reason == 'engaged') == []
assert policy.done
assert policy.update(111, frames, True, True, False) == []
def test_skips_state_change_and_50ms_burst_waits_for_steady_heartbeat():
policy = AvhStartup()
frames = {}
counter = 0
fast_counter = 0
for tick in range(100):
now = 100.0 + tick / 10
fast_counter = tick
for address in INPUTS:
if address != AVH_REQUEST or tick % 10 == 0:
if address == AVH_REQUEST:
counter += 1
c = counter if address == AVH_REQUEST else fast_counter
frames[address] = (now, sample(address, c))
assert policy.update(now, frames, True, True, False) == []
# Event transition (byte 6 changes) -> 1st burst frame at 109.95s, then 50ms burst at 110.00, 110.05, 110.10 (10s met mid-burst).
for offset, changed in ((109.95, True), (110.00, False), (110.05, False), (110.10, False)):
counter += 1
fast_counter += 1
data = bytearray(sample(AVH_REQUEST, counter))
data[6] = 0x0F if changed else 0x0E
data[0] = checksum(AVH_REQUEST, data)
frames[AVH_REQUEST] = (offset, bytes(data))
for address in INPUTS:
if address != AVH_REQUEST:
frames[address] = (offset, sample(address, fast_counter))
assert policy.update(offset, frames, True, True, False) == []
assert not policy.done
# Wait past 1.20s at 100ms ticks so configured/stable continuity stays intact, then send steady heartbeat at 111.30s.
for tick in range(1, 12):
now = 110.10 + tick * 0.10
fast_counter += 1
for address in INPUTS:
if address != AVH_REQUEST:
frames[address] = (now, sample(address, fast_counter))
assert policy.update(now, frames, True, True, False) == []
counter += 1
fast_counter += 1
for address in INPUTS:
frames[address] = (111.30, sample(address, counter if address == AVH_REQUEST else fast_counter))
assert policy.update(111.30, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 1)]
assert policy.update(111.36, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
assert policy.update(111.42, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
assert policy.update(111.48, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
assert policy.done
@@ -0,0 +1,531 @@
import unittest
from opendbc.can import CANPacker, CANParser
from opendbc.car import Bus, structs
from opendbc.car.subaru import subarucan
from opendbc.car.subaru.carcontroller import CarController
from opendbc.car.subaru.carstate import CarState
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
from opendbc.car.subaru.values import CAR, CanBus, DBC
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
def _step_to_hud(controller, command, state):
while controller.frame % 10 != 0:
controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000)
_, sends = controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000)
hud = next(frame for frame in sends if frame[0] == 0x322)
parser = CANParser(DBC[controller.CP.carFingerprint][Bus.pt], [('ES_LKAS_State', 0)], hud[2])
parser.update([(1, [hud])])
return parser.vl['ES_LKAS_State']
class TestLegacy2025Aol(unittest.TestCase):
def test_lkas_dash_state_toggle_emits_button_event_and_toggles_aol(self):
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
state = CarState(cp)
self.assertTrue(state.aol_enabled)
parsers = state.get_can_parsers(cp)
state.update(parsers)
for parser in parsers.values():
parser.update([(1_000_000_000, frames)])
ret = state.update(parsers)
self.assertTrue(ret.cruiseState.available)
self.assertFalse(state.lateral_off)
self.assertEqual(len(ret.buttonEvents), 0)
# Flip LKAS_Dash_State (0 -> 1) on bus 2: toggles AOL off once and holds Type.lkas press/release for 5 frames.
lkas_on = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1})
parsers[Bus.cam].update([(1_020_000_000, [lkas_on])])
ret = state.update(parsers)
self.assertTrue(state.lateral_off)
lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas]
self.assertEqual([be.pressed for be in lkas_events], [True, False])
for idx in range(4):
ret = state.update(parsers)
self.assertTrue(state.lateral_off)
lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas]
self.assertEqual([be.pressed for be in lkas_events], [True, False], f"hold frame {idx + 2}")
ret = state.update(parsers)
self.assertTrue(state.lateral_off)
self.assertEqual([be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas], [])
# Flip LKAS_Dash_State (1 -> 0): restores AOL active cleanly.
lkas_off = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0})
parsers[Bus.cam].update([(1_040_000_000, [lkas_off])])
ret = state.update(parsers)
self.assertFalse(state.lateral_off)
# Toggle off, then drop Cruise_On -> lateral_off resets to False when AOL is enabled.
parsers[Bus.cam].update([(1_060_000_000, [lkas_on])])
state.update(parsers)
self.assertTrue(state.lateral_off)
dash_off = packer.make_can_msg('ES_DashStatus', CanBus.camera, {'Cruise_On': 0})
parsers[Bus.cam].update([(1_080_000_000, [dash_off])])
state.update(parsers)
self.assertFalse(state.lateral_off)
def test_aol_mode_transitions_and_lkas_button_behavior(self):
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
def init_state(aol_enabled: bool):
state = CarState(cp)
state.aol_enabled = aol_enabled
parsers = state.get_can_parsers(cp)
state.update(parsers)
for parser in parsers.values():
parser.update([(1_000_000_000, frames)])
state.update(parsers)
return state, parsers
def press_lkas(state, parsers, ts_ns: int, dash_state: int):
msg = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': dash_state})
parsers[Bus.cam].update([(ts_ns, [msg])])
return state.update(parsers)
# 1. AOL ON: AOL Active <-> AOL Off.
state, parsers = init_state(True)
self.assertFalse(state.lateral_off)
press_lkas(state, parsers, 1_020_000_000, 1)
self.assertTrue(state.lateral_off)
press_lkas(state, parsers, 1_040_000_000, 0)
self.assertFalse(state.lateral_off)
# 2. AOL OFF: forced Off even after LKAS presses.
state, parsers = init_state(False)
self.assertTrue(state.lateral_off)
press_lkas(state, parsers, 1_020_000_000, 1)
self.assertTrue(state.lateral_off)
# 3. Dynamic transitions across AOL settings changes.
state, parsers = init_state(True)
self.assertFalse(state.lateral_off)
state.aol_enabled = False
state.update(parsers)
self.assertTrue(state.lateral_off)
state.aol_enabled = True
state.update(parsers)
self.assertFalse(state.lateral_off)
def test_carcontroller_dash_state_and_steering_across_lateral_modes(self):
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
state.out.cruiseState.available = True
state.out.gearShifter = structs.CarState.GearShifter.drive
state.out.vEgo = 20.0
state.out.standstill = False
# AOL active -> LKAS_Dash_State == 2, lines visible, and ES_LKAS_ANGLE LKAS_Request == 1.
state.aol_enabled = True
state.lateral_off = False
command.enabled = True
command.latActive = True
command.hudControl.lanesVisible = True
command.hudControl.leftLaneVisible = True
command.hudControl.rightLaneVisible = True
command.actuators.steeringAngleDeg = 10.0
_, angle = step(controller, command, state)
self.assertEqual(angle['LKAS_Request'], 1)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
# lateral_off with AOL toggle ON -> LKAS_Dash_State == 1 (white ready wheel), NO lines, and LKAS_Request == 0.
state.lateral_off = True
state.aol_enabled = True
command.hudControl.lanesVisible = False
_, angle = step(controller, command, state)
self.assertEqual(angle['LKAS_Request'], 0)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 1)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
self.assertEqual(hud['LKAS_Right_Line_Visible'], 0)
# AOL toggle OFF while not engaged -> LKAS_Dash_State == 0 (wheel off) and NO lines (even before lateral_off syncs).
state.aol_enabled = False
state.lateral_off = False
command.enabled = False
command.latActive = False
command.hudControl.lanesVisible = False
_, angle = step(controller, command, state)
self.assertEqual(angle['LKAS_Request'], 0)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 0)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
self.assertEqual(hud['LKAS_Right_Line_Visible'], 0)
# AOL toggle OFF with ACC engaged (even when state.lateral_off is still True) -> steers + green wheel + lines.
state.lateral_off = True
command.enabled = True
command.latActive = True
command.hudControl.lanesVisible = True
_, angle = step(controller, command, state)
self.assertEqual(angle['LKAS_Request'], 1)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
# Main cruise OFF -> LKAS_Dash_State == 0 (wheel icon off) even with AOL toggle ON.
state.aol_enabled = True
state.out.cruiseState.available = False
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 0)
def test_lkas_button_hold_survives_conflation_and_keeps_dash_wheel_in_sync(self):
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
state.aol_enabled = True
parsers = state.get_can_parsers(cp)
state.update(parsers)
for parser in parsers.values():
parser.update([(1_000_000_000, frames)])
state.update(parsers)
self.assertFalse(state.lateral_off)
controlsd_lateral_off = False
prev_lkas_pressed = False
def step_controlsd_from_ret(car_state):
nonlocal controlsd_lateral_off, prev_lkas_pressed
raw_pressed = any(
be.type == structs.CarState.ButtonEvent.Type.lkas and be.pressed
for be in car_state.buttonEvents
)
if not car_state.cruiseState.available:
prev_lkas_pressed = False
lkas_pressed = raw_pressed and not prev_lkas_pressed
prev_lkas_pressed = raw_pressed
if lkas_pressed:
controlsd_lateral_off = not controlsd_lateral_off
# 1. Press LKAS (0 -> 1): simulate SubMaster dropping the first two carState frames.
parsers[Bus.cam].update([(1_020_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1})])])
cs_frames = [state.update(parsers) for _ in range(6)]
self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames],
[True, True, True, True, True, False])
self.assertTrue(state.lateral_off)
for f in cs_frames[2:]:
step_controlsd_from_ret(f)
self.assertTrue(controlsd_lateral_off)
self.assertEqual(state.lateral_off, controlsd_lateral_off)
# With AOL toggled off, wheel icon must stay white (1) with no lane lines and no steering request.
state.out.cruiseState.available = True
state.out.gearShifter = structs.CarState.GearShifter.drive
state.out.vEgo = 20.0
state.out.standstill = False
command.enabled = False
command.latActive = True
command.hudControl.lanesVisible = False
command.hudControl.leftLaneVisible = True
command.actuators.steeringAngleDeg = -8.0
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 0)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 1)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
# 2. Press LKAS (1 -> 0) back to AOL: again drop first two carState frames via conflation.
parsers[Bus.cam].update([(1_100_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0})])])
cs_frames_2 = [state.update(parsers) for _ in range(6)]
self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames_2],
[True, True, True, True, True, False])
self.assertFalse(state.lateral_off)
for f in cs_frames_2[2:]:
step_controlsd_from_ret(f)
self.assertFalse(controlsd_lateral_off)
self.assertEqual(state.lateral_off, controlsd_lateral_off)
# In AOL mode with active steering, wheel icon turns back to green (2) and lines reappear.
command.enabled = True
command.latActive = True
command.hudControl.lanesVisible = True
command.actuators.steeringAngleDeg = 8.0
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
def test_carcontroller_aol_green_wheel_park_override_and_alerts(self):
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
state.out.cruiseState.available = True
state.out.gearShifter = structs.CarState.GearShifter.park
state.out.vEgo = 0.0
state.out.standstill = True
state.aol_enabled = True
# AOL active in Park / standstill (latActive=False, lanesVisible=True) -> green wheel icon (2).
state.lateral_off = False
command.enabled = False
command.latActive = False
command.hudControl.lanesVisible = True
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
# Toggle LKAS off in Park -> immediately drops to white wheel icon (1).
state.lateral_off = True
command.hudControl.lanesVisible = False
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 1)
# steerRequired visual alert maps to Keep Hands On Wheel message (1) cleanly on 0x322.
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired
command.hudControl.audibleAlert = structs.CarControl.HUDControl.AudibleAlert.none
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Alert_Msg'], 1)
self.assertEqual(hud['LKAS_Alert'], 0)
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.none
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Alert_Msg'], 0)
self.assertEqual(hud['LKAS_Alert'], 0)
# Driving in AOL / full OP: active steering -> green (2), manual override -> white (1), resume -> green (2).
state.lateral_off = False
state.out.gearShifter = structs.CarState.GearShifter.drive
state.out.vEgo = 20.0
state.out.vEgoRaw = 20.0
state.out.standstill = False
command.enabled = True
command.latActive = True
command.hudControl.lanesVisible = True
state.out.steeringTorque = 0.0
state.out.steeringRateDeg = 0.0
state.out.steeringPressed = False
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
# Driver manually overrides steering -> wheel icon turns white (1).
state.out.steeringTorque = 250.0
state.out.steeringRateDeg = 30.0
state.out.steeringPressed = True
step(controller, command, state)
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 0)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 1)
# Driver releases wheel -> openpilot resumes control and wheel icon turns back to green (2).
state.out.steeringTorque = 0.0
state.out.steeringRateDeg = 0.0
state.out.steeringPressed = False
step(controller, command, state)
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
# Stock EyeSight LDW / allowed alert takes priority over steerRequired alert.
state.es_lkas_state_msg["LKAS_Alert"] = 12
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Alert'], 12)
self.assertEqual(hud['LKAS_Alert_Msg'], 0)
dbc = DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]
packer = CANPacker(dbc)
info_parser = CANParser(dbc, [('ES_Infotainment', 0)], CanBus.main)
info_msg = subarucan.create_es_infotainment(
packer, 0, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 1, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
structs.CarControl.HUDControl.VisualAlert.steerRequired,
legacy_2025=True,
)
info_parser.update([(1, [info_msg])])
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 1)
for audible, expected in (
(structs.CarControl.HUDControl.AudibleAlert.none, 3),
(structs.CarControl.HUDControl.AudibleAlert.warningSoft, 3),
(structs.CarControl.HUDControl.AudibleAlert.warningImmediate, 4),
):
info_msg = subarucan.create_es_infotainment(
packer, 1, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 0, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
structs.CarControl.HUDControl.VisualAlert.steerRequired,
audible_alert=audible,
legacy_2025=True,
)
info_parser.update([(2, [info_msg])])
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], expected)
# Non-Legacy default (legacy_2025=False) preserves exact upstream 0x323 behavior.
for stock_state in (0, 1):
info_msg = subarucan.create_es_infotainment(
packer, 2, {'CHECKSUM': 0, 'LKAS_State_Infotainment': stock_state, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
structs.CarControl.HUDControl.VisualAlert.steerRequired,
audible_alert=structs.CarControl.HUDControl.AudibleAlert.warningImmediate,
)
info_parser.update([(3, [info_msg])])
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 3)
def test_carcontroller_aol_manumatic_and_unauthorized_gate(self):
cp, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
cp.alternativeExperience = 32
controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp)
state.out.gearShifter = structs.CarState.GearShifter.manumatic
state.lateral_off = False
state.out.steeringAngleDeg = 0.0
state.out.steeringRateDeg = 0.0
state.out.steeringTorque = 0.0
# Active AOL in manumatic: angle requested, green wheel icon (2), visible left line (1).
command.enabled = False
command.latActive = True
command.hudControl.lanesVisible = True
command.hudControl.leftLaneVisible = True
command.hudControl.rightLaneVisible = False
command.actuators.steeringAngleDeg = -8.0
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 1)
self.assertLess(decoded['LKAS_Output'], 0.0)
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 2)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
# Unauthorized gate: when controlsd keeps latActive=False, CarController must never request 0x124 torque/angle.
command.latActive = False
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 0)
_, decoded = step(controller, command, state)
self.assertEqual(decoded['LKAS_Request'], 0)
def test_legacy_2025_manumatic_transition_and_between_detent_gears(self):
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
state = CarState(cp)
parsers = state.get_can_parsers(cp)
state.update(parsers)
for parser in parsers.values():
parser.update([(1_000_000_000, frames)])
state.update(parsers)
Gear = structs.CarState.GearShifter
for can_gear, expected_gear in ((121, Gear.drive), (129, Gear.manumatic), (177, Gear.manumatic), (0, Gear.neutral), (4, Gear.park)):
msg = packer.make_can_msg('Transmission', 0, {'Gear': can_gear})
parsers[Bus.pt].update([(1_020_000_000, [msg])])
ret = state.update(parsers)
self.assertEqual(ret.gearShifter, expected_gear, f'can_gear={can_gear}')
def test_legacy_2025_acc_lead_led_preserved_and_aol_line_visibility_passthrough(self):
_, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {0x3C4: 8}}, [], False, False, False)
controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp)
state.out.cruiseState.available = True
state.out.gearShifter = structs.CarState.GearShifter.drive
state.out.vEgo = 20.0
state.out.standstill = False
# Stock ACC active via Cruise_Activated_Dash + Car_Follow (not gasPressed) preserves dat[5]=0x01 when masking 000104000000.
state.out.cruiseState.enabled = True
state.out.gasPressed = False
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 1})
raw = bytearray(bytes.fromhex('0002000104000000'))
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
state.es_lkas_alert_dat = bytes(raw)
msg = controller._ascent_lkas_alert(command.as_reader(), state)
self.assertIsNotNone(msg)
self.assertEqual(msg[1][2:], bytes.fromhex('000000010000'))
# Gas pedal override clears green lead LED (dat[5] = 0x00) even when cruiseState.enabled and Car_Follow remain set.
for idx, override_fields in enumerate((
{'gas': True, 'dash': 1, 'cstate': 0},
{'gas': False, 'dash': 0, 'cstate': 2},
)):
state.out.gasPressed = override_fields['gas']
state.es_dashstatus_msg.update({
'Cruise_Activated_Dash': override_fields['dash'],
'Cruise_State': override_fields['cstate'],
'Car_Follow': 1,
})
raw[1] = 0x03 + idx
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
state.es_lkas_alert_dat = bytes(raw)
msg = controller._ascent_lkas_alert(command.as_reader(), state)
self.assertIsNotNone(msg)
self.assertEqual(msg[1][2:], bytes.fromhex('000000000000'), override_fields)
state.out.gasPressed = False
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0})
# Without Car_Follow, dat[5] stays 0x00 when masking the alert.
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 0})
raw[1] = 0x05
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
state.es_lkas_alert_dat = bytes(raw)
msg = controller._ascent_lkas_alert(command.as_reader(), state)
self.assertIsNotNone(msg)
self.assertEqual(msg[1][2:], bytes.fromhex('000000000000'))
# AOL mode passes debounced hudControl lane visibility directly through to cluster CAN.
state.lateral_off = False
command.enabled = False
command.latActive = True
command.hudControl.lanesVisible = True
command.hudControl.leftLaneVisible = True
command.hudControl.rightLaneVisible = True
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
command.hudControl.leftLaneVisible = False
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
command.hudControl.leftLaneVisible = True
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
def test_aol_wheel_icon_park_reverse_neutral_and_shift_debounce(self):
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
state.out.cruiseState.available = True
state.out.vEgo = 0.0
state.out.vEgoRaw = 0.0
state.out.standstill = True
state.aol_enabled = True
state.lateral_off = False
command.enabled = False
command.latActive = False
command.hudControl.lanesVisible = True
# In Park: stays solid green even if steering wheel is moved slightly.
state.out.gearShifter = structs.CarState.GearShifter.park
state.out.steeringPressed = True
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
# Fast Park -> Reverse -> Neutral -> Drive shift (< 0.8s) holds green without flashing white.
state.out.steeringPressed = False
for gear, steps in (
(structs.CarState.GearShifter.reverse, 3),
(structs.CarState.GearShifter.neutral, 3),
):
state.out.gearShifter = gear
for _ in range(steps):
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
state.out.gearShifter = structs.CarState.GearShifter.drive
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
# Settling in Reverse (>= 0.8s) switches to solid white regardless of steering input.
state.out.gearShifter = structs.CarState.GearShifter.reverse
for _ in range(9):
hud = _step_to_hud(controller, command, state)
self.assertEqual(hud['LKAS_Dash_State'], 1)
state.out.steeringPressed = True
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1)
state.out.gearShifter = structs.CarState.GearShifter.neutral
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1)
# Returning to Park restores solid green cleanly.
state.out.gearShifter = structs.CarState.GearShifter.park
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
if __name__ == '__main__':
unittest.main()
@@ -71,9 +71,13 @@ def test_dash_uses_current_request_without_mutating_physical_template(car, enabl
if any(frame[0] == 0x322 for frame in sends):
expected = controller.angle_was_active if car in ANGLE_CARS else (lat_active if marked else enabled)
dash = decoder.vl['ES_LKAS_State']
if car in ANGLE_CARS or marked or enabled:
assert bool(dash['LKAS_ACTIVE']) == expected
assert dash['LKAS_Dash_State'] == (2 if expected else 0)
if car == CAR.SUBARU_LEGACY_2025:
assert bool(dash['LKAS_ACTIVE'])
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if state.out.cruiseState.available else 0))
else:
if car in ANGLE_CARS or marked or enabled:
assert bool(dash['LKAS_ACTIVE']) == expected
assert dash['LKAS_Dash_State'] == (2 if expected else 0)
assert state.es_lkas_state_msg == original
checked += 1
assert checked == 5
@@ -256,7 +256,11 @@ BO_ 964 ES_LKAS_Alert: 8 XXX
SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX
SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX
SG_ Signal1 : 12|4@1+ (1,0) [0|15] "" XXX
SG_ Payload : 16|48@1+ (1,0) [0|281474976710655] "" XXX
SG_ LKAS_Alert : 16|8@1+ (1,0) [0|255] "" XXX
SG_ LKAS_Alert_Msg : 24|8@1+ (1,0) [0|255] "" XXX
SG_ LKAS_HUD_Lights : 32|8@1+ (1,0) [0|255] "" XXX
SG_ ACC_Lead_LED : 40|8@1+ (1,0) [0|255] "" XXX
SG_ Signal2 : 48|16@1+ (1,0) [0|65535] "" XXX
BO_ 722 AC_State: 8 XXX
SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX
@@ -300,12 +304,24 @@ CM_ SG_ 801 LKAS_State_Msg "1 = LKAS_Off_Sharp_Curve, 2 = Keep_Hands_On_Steering
CM_ SG_ 801 Cruise_State_Msg "1 = Cruise_Off_Steep_Slope, 2 = Cruise_lvl1_eco, 3 = Cruise_lvl2_comfort, 4 = Cruise_off_empty_reason, 5 = Cruise_off, 6 = Cruise_Unable_to_set, 7 = Cruise_Unable_to_set_brakes_applied, 8 = Eyesight_not_ready, 9 = Cruise_lvl3_standard, 10 = Cruise_lvl4_dynamic, 11 = Cruise_Unable_to_set_steep_slope";
CM_ SG_ 801 Cruise_Soft_Disable "Eyesight soft disable (eg direct sunlight)";
CM_ SG_ 801 Cruise_Status_Msg "1 = Disabled_Bad_Visibility, 2 = Disabled_Check_Manual";
CM_ SG_ 292 SET_3 "2 = LKA / LDP mode, 3 = Lane Centering mode";
CM_ SG_ 802 LKAS_ACTIVE "Turns on the full LKAS dash display";
CM_ SG_ 802 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel, 6 = Pre_Collision_Braking, 7 = Keep_Hands_On_Wheel_Off";
CM_ SG_ 802 LKAS_Alert "1 = FCW_Cont_Beep, 2 = FCW_Repeated_Beep, 3 = Throttle_Management_Activated_Warning, 4 = Throttle_Management_Activated_Alert, 5 = Pre_Collision_Activated_Alert, 8 = Traffic_Light_Ahead, 9 = Apply_Brake_to_Hold Position, 11 = LDW_Right, 12 = LDW_Left, 13 = Stay_Alert, 14 = Lead_Vehicle_Start_Alert, 18 = Keep_Hands_On_Steering_Alert, 24 = Audio_Beep, 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged, 27 = Audio_LKAS_disabled, 28 = Audio_Ding_Ding, 30 = Audio_Repeated_Beep";
CM_ SG_ 802 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel (static), 6 = Pre_Collision_Braking, 7 = Keep_Hands_On_Wheel_Red_Flash (flashing red hands); 2-5 = Unused";
CM_ SG_ 802 LKAS_Alert "1 = FCW_Cont_Beep, 2 = FCW_Repeated_Beep, 3 = Throttle_Management_Activated_Warning, 4 = Throttle_Management_Activated_Alert, 5 = Pre_Collision_Activated_Alert, 8 = Traffic_Light_Ahead, 9 = Apply_Brake_to_Hold Position, 11 = LDW_Right, 12 = LDW_Left, 13 = Stay_Alert, 14 = Lead_Vehicle_Start_Alert, 18 = LC_LDW_Right (lane departure right during Lane Centering), 19 = LC_LDW_Left (lane departure left during Lane Centering), 24 = Audio_Beep, 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged, 27 = Audio_LKAS_disabled, 28 = Audio_Ding_Ding, 30 = Audio_Repeated_Beep";
CM_ SG_ 802 LKAS_Left_Line_Visible "0 = Off, 1 = White, 2 = Green, 3 = Orange";
CM_ SG_ 802 LKAS_Dash_State "0 = Off, 1 = Ready, 2 = Active";
CM_ SG_ 802 LKAS_Right_Line_Visible "0 = Off, 1 = White, 2 = Green, 3 = Orange";
CM_ SG_ 803 LKAS_State_Infotainment "1 = Obstacle_Ahead, 2 = Obstacle_Detected, 3 = Keep_Hands_On_Wheel (adds flashing yellow border on cluster/infotainment), 4 = Keep_Hands_On_Wheel_Off, 5 = Keep_Hands_On_Wheel_Alt; 6-7 = Unused";
CM_ SG_ 964 LKAS_Alert "11 = LDW_Right (+3 soft chimes), 12 = LDW_Left (+3 soft chimes), 13 = Stay_Alert (+3 soft chimes), 14 = Lead_Vehicle_Start_Alert (+tut-tut chime), 18 = LC_LDW_Right (lane departure right during Lane Centering), 19 = LC_LDW_Left (lane departure left during Lane Centering), 24 = Audio_Beep (soft chirp), 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged (1 strong chime), 27 = Audio_LKAS_disabled (1 strong chime), 28 = Audio_Ding_Ding (2 bouncy chimes), 30 = Audio_Repeated_Beep (4 strong chimes); 29,31 = Unused";
CM_ SG_ 964 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel (static), 7 = Keep_Hands_On_Wheel_Red_Flash (flashing red hands); 2-5,8 = Unused";
CM_ SG_ 964 LKAS_HUD_Lights "Windshield HUD LED bitmask: 1 = 2 Yellow Solid, 2 = 2 Yellow Rapid Flash, 4 = 2 Yellow Slow Flash, 16 = 4 Red Solid, 32 = 4 Red Rapid Flash, 48 = 4 Red Solid+Rapid Flash, 64 = 4 Red Slow Flash, 80 = 2 Red Solid + 2 Red Flash Right (0x50), 96 = 2 Red Solid + 2 Red Flash Left (0x60) (8,128 = Unused)";
CM_ SG_ 964 ACC_Lead_LED "1 = Green_Lead_Tracked";
CM_ SG_ 912 UNITS "0 = Metric, 1 = Imperial";
CM_ SG_ 912 ICY_ROAD "1 = DASHLIGHT ON, 2 = WARNING, 3 = OFF";
VAL_ 292 SET_3 3 "Lane_Centering" 2 "LKA_LDP" 0 "Off";
VAL_ 544 AEB_Status 12 "AEB related" 8 "AEB actuation" 4 "AEB related" 0 "No AEB actuation";
VAL_ 803 LKAS_State_Infotainment 7 "Unused_7" 6 "Unused_6" 5 "Keep_Hands_On_Wheel_Alt" 4 "Keep_Hands_On_Wheel_Off" 3 "Keep_Hands_On_Wheel" 2 "Obstacle_Detected" 1 "Obstacle_Ahead" 0 "None";
VAL_ 964 LKAS_Alert 31 "Unused_31" 30 "Audio_Repeated_Beep" 29 "Unused_29" 28 "Audio_Ding_Ding" 27 "Audio_LKAS_disabled" 26 "Audio_ACC_Disengaged" 25 "Audio_Lead_Car_Change" 24 "Audio_Beep_Chirp" 19 "LC_LDW_Left" 18 "LC_LDW_Right" 14 "Lead_Vehicle_Start_Alert" 13 "Stay_Alert" 12 "LDW_Left" 11 "LDW_Right" 0 "None";
VAL_ 964 LKAS_Alert_Msg 8 "Unused_8" 7 "Keep_Hands_On_Wheel_Red_Flash" 5 "Unused_5" 4 "Unused_4" 3 "Unused_3" 2 "Unused_2" 1 "Keep_Hands_On_Wheel" 0 "None";
VAL_ 964 LKAS_HUD_Lights 96 "Red_2_Solid_2_Flash_Left" 80 "Red_2_Solid_2_Flash_Right" 64 "Red_4_Slow_Flash" 48 "Red_4_Flash" 32 "Red_4_Rapid_Flash" 16 "Red_4_Solid" 4 "Yellow_2_Slow_Flash" 2 "Yellow_2_Rapid_Flash" 1 "Yellow_2_Solid" 0 "Off";
VAL_ 964 ACC_Lead_LED 1 "Green_Lead_Tracked" 0 "Off";
+12 -1
View File
@@ -343,17 +343,25 @@ static safety_config subaru_init(uint16_t raw_param) {
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
};
static const CanMsg SUBARU_LEGACY_ANGLE_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
};
static const CanMsg SUBARU_STOP_START_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
{0x390U, SUBARU_ALT_BUS, 8, .check_relay = false},
};
static const CanMsg SUBARU_AVH_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
{0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false},
};
static const CanMsg SUBARU_AVH_STOP_START_TX_MSGS[] = {
SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS)
{MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true},
{0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false},
{0x390U, SUBARU_ALT_BUS, 8, .check_relay = false},
};
@@ -400,10 +408,12 @@ static safety_config subaru_init(uint16_t raw_param) {
((unsigned int)alternative_experience == 32U)));
subaru_aol_reset();
subaru_aol_gear_bus = (uint8_t)(subaru_d_platform ? SUBARU_ALT_BUS : SUBARU_MAIN_BUS);
const bool legacy_2025 = (base_param == 145U);
subaru_aol_legacy_2025 = legacy_2025;
subaru_aol_enabled = ((unsigned int)alternative_experience == 32U) &&
((param == 209U) || (param == 465U) || (param == 16U) || (param == 0U) || (param == 1U) || (param == 17U) || (param == 145U) ||
avh || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U));
subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform);
subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform || legacy_2025);
if (subaru_aol_enabled) {
static const AolSafetyPolicy policy = {
.reset = subaru_aol_reset,
@@ -441,6 +451,7 @@ static safety_config subaru_init(uint16_t raw_param) {
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_TX_MSGS)) :
stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_STOP_START_TX_MSGS) :
ascent_alert ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) :
legacy_2025 ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_LEGACY_ANGLE_TX_MSGS) :
subaru_angle_main_bus ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST) :
BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_GEN2_ANGLE_TX_MSGS_LIST);
// Keep the original seven checks on other profiles; only MAIN arming needs ACC health.
@@ -109,8 +109,8 @@ static void subaru_avh_rx(const CANPacket_t *msg) {
static bool subaru_avh_tx(const CANPacket_t *msg) {
const uint32_t now = microsecond_timer_get();
const uint32_t elapsed = safety_get_ts_elapsed(now, subaru_avh_start);
const bool second = subaru_avh_count == 1U;
bool allowed = subaru_avh_enabled && !subaru_avh_done && (subaru_avh_count < 2U) &&
const bool followup = subaru_avh_count > 0U;
bool allowed = subaru_avh_enabled && !subaru_avh_done && (subaru_avh_count < 4U) &&
(msg->addr == 0x6BBU) && (msg->bus == 1U) && (GET_LEN(msg) == 8U) && !relay_malfunction && !safety_rx_checks_invalid &&
aol_rx_healthy() && !lateral_controls_allowed() && !gas_pressed && !subaru_software_fault &&
(elapsed >= 10000000U) && (elapsed <= 30000000U) && subaru_avh_ready(now) &&
@@ -124,10 +124,10 @@ static bool subaru_avh_tx(const CANPacket_t *msg) {
}
}
if (second) {
if (followup) {
const uint32_t spacing = safety_get_ts_elapsed(now, subaru_avh_sent);
allowed &= (spacing >= 45000U) && (spacing <= 80000U) && (subaru_avh_ts[0] == subaru_avh_template_ts) &&
(safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 110000U);
(safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 250000U);
} else {
allowed &= safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 30000U;
}
@@ -135,7 +135,7 @@ static bool subaru_avh_tx(const CANPacket_t *msg) {
for (int i = 1; i < 8; i++) {
uint8_t expected = subaru_avh_data[0][i];
if (i == 1) {
expected = (expected & 0xF0U) | ((expected + (second ? 2U : 1U)) & 0xFU);
expected = (expected & 0xF0U) | ((expected + subaru_avh_count + 1U) & 0xFU);
} else if (i == 2) {
expected |= 2U;
} else {
@@ -149,7 +149,7 @@ static bool subaru_avh_tx(const CANPacket_t *msg) {
subaru_avh_count++;
subaru_avh_sent = now;
subaru_avh_template_ts = subaru_avh_ts[0];
subaru_avh_done = second;
subaru_avh_done = (subaru_avh_count == 4U);
}
return allowed;
}
@@ -25,9 +25,18 @@ static bool subaru_aol_main_arm = false;
static bool subaru_aol_main_epoch = false;
static bool subaru_aol_main_low_seen = false;
static bool subaru_aol_acc_fault = false;
static bool subaru_aol_legacy_2025 = false;
static bool subaru_aol_park_seen = false;
static bool subaru_aol_drive_gear(uint8_t gear) {
// Drive (121 = 0x79) or CVT manual mode / paddle gears (129..193 step 8) on Legacy 2025.
return (gear == 121U) ||
(subaru_aol_legacy_2025 && (gear >= 129U) && (gear <= 193U) && (((gear - 129U) & 7U) == 0U));
}
static void subaru_aol_clear(void) {
subaru_aol_main_epoch = false;
subaru_aol_park_seen = false;
subaru_aol_armed = false;
subaru_aol_token = false;
subaru_aol_pending = false;
@@ -80,12 +89,14 @@ static void subaru_aol_observe_main(bool main_on) {
if (!main_on) {
subaru_aol_clear();
subaru_aol_main_low_seen = true;
} else if (subaru_aol_main_arm && subaru_aol_main_low_seen && !subaru_aol_main &&
subaru_aol_gear_qualified && subaru_aol_drive &&
} else if (subaru_aol_main_arm &&
((subaru_aol_main_low_seen && !subaru_aol_main) || (subaru_aol_legacy_2025 && subaru_aol_park_seen)) &&
subaru_aol_gear_qualified && (subaru_aol_drive || subaru_aol_legacy_2025) &&
(safety_get_ts_elapsed(microsecond_timer_get(), subaru_aol_gear_ts) <= 100000U) &&
!subaru_aol_permanent && !subaru_aol_temporary && !subaru_aol_acc_fault &&
!relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy()) {
subaru_aol_main_epoch = true;
subaru_aol_park_seen = false;
} else {
// No qualified MAIN edge; retain epoch.
}
@@ -181,11 +192,15 @@ static void subaru_aol_optional_rx(const CANPacket_t *msg) {
subaru_aol_gear_seen = true;
subaru_aol_gear_counter = counter;
subaru_aol_gear_ts = microsecond_timer_get();
subaru_aol_drive = msg->data[3] == 121U;
subaru_aol_drive = subaru_aol_drive_gear(msg->data[3]);
if (subaru_aol_legacy_2025 && (msg->data[3] == 4U) && !subaru_aol_armed &&
!subaru_aol_permanent && !subaru_aol_acc_fault) {
subaru_aol_park_seen = true;
}
} else {
// A contradictory duplicate must withdraw Drive immediately; it may
// neither renew the source receipt nor retain an old Drive permission.
if (((msg->data[3] == 121U) && !subaru_aol_drive) || ((msg->data[3] != 121U) && subaru_aol_drive)) {
if (subaru_aol_drive_gear(msg->data[3]) != subaru_aol_drive) {
subaru_aol_gear_qualified = false;
subaru_aol_gear_seen = false;
}
@@ -18,14 +18,16 @@ class TestSubaruAscentAlert(unittest.TestCase):
return libsafety_py.make_CANPacket(0x3C4, bus, data)
def test_exact_parameter_bus_checksum_length_and_forwarding(self):
for flags in (0, 1, 0x11, 0x91, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1):
for flags in (0, 1, 0x11, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1):
self.mode(flags)
self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0)
for flags in (0x8B1, 0x91, 401, 1169, 1425):
self.mode(flags)
self.assertTrue(self.safety.safety_tx_hook(self.packet()), hex(flags))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1)
self.assertEqual(self.safety.safety_fwd_hook(0, 0x3C4), 2)
self.mode(0x8B1)
self.assertTrue(self.safety.safety_tx_hook(self.packet()))
self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1)
self.assertEqual(self.safety.safety_fwd_hook(0, 0x3C4), 2)
for bus in (1, 2):
self.assertFalse(self.safety.safety_tx_hook(self.packet(bus=bus)))
for data in (bytes.fromhex("0002000104000000"), bytes(7), bytes(12)):
@@ -7,7 +7,22 @@ from opendbc.safety.tests.common import CANPackerSafety
from opendbc.safety.tests.libsafety import libsafety_py
def ready(param, ae):
def feed_step(safety, packer, last, tick):
safety.set_timer(1_000_000 + tick * 10_000)
for name, values, bus in [('Transmission', {'Gear': 4}, 0), ('Throttle', {'Engine_RPM': 800}, 0), ('Steering_Torque', {}, 0), ('Steering_2', {}, 0),
('Wheel_Speeds', dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0), 1), ('Brake_Status', {}, 1),
('ES_Status', {}, 1), ('ES_Distance', {}, 1), ('ES_DashStatus', {'Cruise_On': 1}, 2)]:
safety.safety_rx_hook(packer.make_can_msg_safety(name, bus, values))
for address in (0x6BB, 0x32B, 0x40, 0x48, 0x174):
if address == 0x6BB and tick % 100:
continue
data = sample(address, tick // 100 if address == 0x6BB else tick)
safety.safety_rx_hook(libsafety_py.make_CANPacket(address, 1, data))
last[address] = data
safety.safety_tick()
def _ready_with_packer(param, ae):
safety = libsafety_py.libsafety
safety.init_tests()
safety.set_timer(1_000_000)
@@ -16,19 +31,12 @@ def ready(param, ae):
packer = CANPackerSafety('subaru_global_2017_generated')
last = {}
for tick in range(1001):
safety.set_timer(1_000_000 + tick * 10_000)
for name, values, bus in [('Transmission', {'Gear': 4}, 0), ('Throttle', {'Engine_RPM': 800}, 0), ('Steering_Torque', {}, 0), ('Steering_2', {}, 0),
('Wheel_Speeds', dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0), 1), ('Brake_Status', {}, 1),
('ES_Status', {}, 1), ('ES_DashStatus', {'Cruise_On': 1}, 2)]:
raw = packer.make_can_msg_safety(name, bus, values)
safety.safety_rx_hook(raw)
for address in (0x6BB, 0x32B, 0x40, 0x48, 0x174):
if address == 0x6BB and tick % 100:
continue
data = sample(address, tick // 100 if address == 0x6BB else tick)
safety.safety_rx_hook(libsafety_py.make_CANPacket(address, 1, data))
last[address] = data
safety.safety_tick()
feed_step(safety, packer, last, tick)
return safety, last, packer
def ready(param, ae):
safety, last, _ = _ready_with_packer(param, ae)
return safety, last
@@ -38,13 +46,15 @@ def test_exact_pair_debug_only_and_status_never_tx(param, ae):
# Probe the loaded build, not the Subaru authority under test. ready() resets
# native state and selects Subaru before any RX or TX checks.
debug = libsafety_py.libsafety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0
safety, last = ready(param, ae)
for step in (1, 2):
if step == 2:
safety.set_timer(11_060_000)
addr, data, bus = avh_request(last[0x6BB], step)
safety, last, packer = _ready_with_packer(param, ae)
template = last[0x6BB]
for step in (1, 2, 3, 4):
if step > 1:
for offset in range(1, 7):
feed_step(safety, packer, last, 1000 + (step - 2) * 6 + offset)
addr, data, bus = avh_request(template, step)
assert bool(safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))) == debug
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x6BB, 1, avh_request(last[0x6BB], 2)[1]))
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x6BB, 1, avh_request(template, 4)[1]))
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x32B, 1, sample(0x32B, 1)))
@@ -265,7 +265,7 @@ class TestSubaruGen2AnglePair(unittest.TestCase):
f'{car.value} {speed=} {target=} {i=} {frame[1].hex()}')
seen.append(frame)
self.assertGreater(len(seen), 50)
self.assertNotEqual(seen[-1][1][5:7], b'\x00\x00')
self.assertTrue(any(frame[1][5:7] != b'\x00\x00' for frame in seen[-3:]))
def test_firmware_complete_partial_and_mixed(self):
# Complete supported identities select automatically; partial and
@@ -5,7 +5,7 @@ from opendbc.safety.tests.libsafety import libsafety_py
from opendbc.safety.tests import test_subaru_stock_aol as stock_module
@pytest.fixture(params=(17, 209, 465, 4096, 4104, 4608, 4616))
@pytest.fixture(params=(17, 145, 209, 401, 465, 4096, 4104, 4608, 4616))
def owner(request):
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
@@ -71,7 +71,7 @@ def test_new_physical_acc_source_is_required_before_main_edge(owner):
def test_acc_wire_checksum_and_counter_cannot_be_faked_by_host(owner):
neutral(owner)
assert owner.feed() == 1
bus = 1 if owner.param in (17, 209, 465) else 2
bus = 1 if owner.param in (17, 145, 209, 401, 465) else 2
bad = owner.frame('ES_Distance', {}, bus)
raw = bytearray(bytes(bad.data))
raw[0] ^= 1
@@ -97,9 +97,9 @@ def test_acc_fault_cannot_be_bypassed_by_stock_enable_packets(owner):
assert owner.feed() == 1
assert owner.feed(acc_fault=True) == 0
for enabled in (0, 1):
name = 'ES_Status' if owner.param in (17, 209, 465) else 'CruiseControl'
name = 'ES_Status' if owner.param in (17, 145, 209, 401, 465) else 'CruiseControl'
values = {'Cruise_Activated': enabled, 'Cruise_On': 1} if name == 'CruiseControl' else {'Cruise_Activated': enabled}
assert owner.safety.safety_rx_hook(owner.frame(name, values, 1 if owner.param in (17, 209, 465) else 0))
assert owner.safety.safety_rx_hook(owner.frame(name, values, 1 if owner.param in (17, 145, 209, 401, 465) else 0))
owner.safety.aol_set_host_request(1)
assert owner.safety.aol_get_permission_mask() == 0
@@ -116,3 +116,29 @@ def test_impreza_main_setting_cannot_select_unqualified_native_output(param, exp
assert not item.safety.safety_tx_hook(item.frame('ES_LKAS', {}, 0))
finally:
item.tearDown()
def test_legacy_2025_cvt_manual_gears():
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
try:
item.configure(145)
neutral(item)
assert item.feed() == 1
for gear in (137, 145, 153, 161, 169, 177, 185, 193):
assert item.feed(gear=gear) == 1
assert item.feed(gear=3) == 0
assert item.feed(gear=145) == 1
# Pressing MAIN while in Park (gear=4) then shifting to Drive grants permission.
assert item.feed(main=False, gear=4, speed=0) == 0
assert item.feed(main=True, gear=4, speed=0) == 0
assert item.feed(main=True, gear=3, speed=0) == 0
assert item.feed(main=True, gear=121, speed=54) == 1
item.configure(17)
neutral(item)
assert item.feed() == 1
assert item.feed(gear=137) == 0
finally:
item.tearDown()
@@ -47,8 +47,9 @@ class TestSubaruStockAol(unittest.TestCase):
('ES_Status', {'Cruise_Activated': int(cruise)}, 2 if self.param == 16 else 1),
('ES_DashStatus', {'Cruise_On': int(main)}, 2),
]
if not omit_distance and self.param in (17, 209, 465, 4096, 4104, 4608, 4616):
frames.append(('ES_Distance', {'Cruise_Fault': int(acc_fault)}, 1 if self.param in (17, 209, 465) else 2))
if not omit_distance and self.param in (17, 145, 209, 401, 465, 1169, 1425, 4096, 4104, 4608, 4616):
frames.append(('ES_Distance', {'Cruise_Fault': int(acc_fault)},
1 if self.param in (17, 145, 209, 401, 465, 1169, 1425) else 2))
if not omit_gear:
frames.append(('Transmission', {'Gear': gear}, gear_bus))
for name, fields, bus in frames:
@@ -79,7 +80,7 @@ class TestSubaruStockAol(unittest.TestCase):
self.assertEqual(self.feed(temporary=True), 0)
self.assertEqual(self.feed(), 1)
self.assertEqual(self.feed(main=False), 0)
self.assertEqual(self.feed(main=True), int(param in (17, 209, 465, 4096, 4104, 4608, 4616)))
self.assertEqual(self.feed(main=True), int(param in (17, 145, 209, 465, 4096, 4104, 4608, 4616)))
self.assertEqual(self.feed(cruise=True), 1)
def test_permanent_fault_and_rx_fault_require_fresh_ordinary_engagement(self):
+1
View File
@@ -160,6 +160,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LeadDepartingAlert", {PERSISTENT, BOOL, "0"}},
{"LoudBlindspotAlert", {PERSISTENT, BOOL, "0"}},
{"LoudBlindspotAlertWhenDisengaged", {PERSISTENT, BOOL, "0"}},
{"LoudBlindspotAlertMuteAtStandstill", {PERSISTENT, BOOL, "0"}},
{"SignalMetrics", {PERSISTENT, BOOL, "0"}},
{"PIPPreviewEnabled", {PERSISTENT, BOOL, "0"}},
{"PIPPreviewMask", {PERSISTENT | DONT_LOG, JSON, "{\"width\":1928,\"height\":1208,\"center_left\":[315,548],\"center_right\":[1571,539],\"crop_size\":580}"}},
+3
View File
@@ -71,6 +71,7 @@ from openpilot.starpilot.car.hyundai.aol import aol_safety_config as hyundai_aol
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,
awaiting_initial_request as ford_awaiting_initial_request)
from openpilot.starpilot.car.subaru import aol as subaru_aol
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
@@ -1923,6 +1924,7 @@ class Car:
update_subaru_sng(self, CS, CC, now_nanos)
from openpilot.starpilot.car.subaru.stop_start_caller import update as update_subaru_startup
update_subaru_startup(self, now_nanos)
subaru_aol.sync_legacy_card_lateral(self, CS, CC)
self.last_actuators_output, can_sends = self.CI.apply(CC, now_nanos)
self.publish_sendcan(can_sends, valid=CS.canValid)
if learning_snapshot is not None and self.learning_send_committed_mono_ns:
@@ -1995,6 +1997,7 @@ class Car:
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
if self.aol_card_intent is not None:
self.aol_card_intent.settings = read_settings(self.params)
subaru_aol.sync_legacy_card_aol(self)
now = time.monotonic()
if now >= next_cruise_read:
self.v_cruise_helper.low_speed_on_set = self.params.get_bool(LOW_SPEED_CRUISE_ON_SET)
+122 -6
View File
@@ -29,7 +29,12 @@ from openpilot.starpilot.car.hyundai.lateral_fault import LateralFaultLatch
from openpilot.starpilot.feature_runtime import enabled as feature_enabled
from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences
from openpilot.starpilot.lateral.pause import LateralPause, read_settings as read_lateral_pause
from openpilot.starpilot.lateral.model_turn_assist import CURVATURE_HOLD_CONFIRM_MIN, ModelTurnAssist, update_twitch_guard
from openpilot.starpilot.lateral.model_turn_assist import (
CURVATURE_HOLD_CONFIRM_MIN,
ModelTurnAssist,
limit_curvature_to_plan,
update_twitch_guard,
)
from openpilot.starpilot.lateral.turn_unlock import TurnUnlock
from openpilot.starpilot.lateral.turn_initiation_preferences import TurnInitiationPreference
from openpilot.starpilot.aol.runtime import (
@@ -71,6 +76,26 @@ LaneChangeDirection = log.LaneChangeDirection
ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys())
def _update_subaru_line_visibility(prev_vis: bool | None, timer: float, prob: float | bool, dt: float) -> tuple[bool, float]:
"""Apply confidence hysteresis and asymmetric debounce to Subaru dash lane line visibility."""
val = (1.0 if prob else 0.0) if isinstance(prob, bool) else float(prob)
if prev_vis is None:
return val >= 0.55, 0.0
if prev_vis:
if val < 0.40:
timer += max(0.0, dt)
if timer >= 0.25 - 1e-6:
return False, 0.0
return True, timer
return True, 0.0
if val >= 0.55:
timer += max(0.0, dt)
if timer >= 1.0 - 1e-6:
return True, 0.0
return False, timer
return False, 0.0
class Controls:
def __init__(self, *, predict_lane_clearance: bool = False) -> None:
if type(predict_lane_clearance) is not bool:
@@ -131,6 +156,19 @@ class Controls:
self.model_turn_assist = ModelTurnAssist()
self.turn_unlock = TurnUnlock()
self.turn_initiation_preferences = TurnInitiationPreference(self.params)
self.subaru_twitch_guard_armed = False
self.aol_enabled_setting = True
self.lateral_off = False
self._aol_left_line_vis: bool | None = None
self._aol_left_line_timer: float = 0.0
self._aol_right_line_vis: bool | None = None
self._aol_right_line_timer: float = 0.0
self._subaru_aol_last_read_ns = 0
self._prev_cruise_available = False
self._prev_aol_enabled: bool | None = None
self._prev_lkas_button_pressed = False
if self.CP.carFingerprint == "SUBARU_LEGACY_2025":
self._refresh_subaru_aol_setting(0, force=True)
self.lane_centering_controller = (
LaneCenteringController(body=interface_dimensions(self.CI, self.CP), body_required=True) if predict_lane_clearance else LaneCenteringController()
)
@@ -217,6 +255,12 @@ class Controls:
assist_enabled = self.vehicle_startup_preferences.turn_assist and model_turn_assist_supported(self.CP)
self.turn_assist_enabled = lambda: assist_enabled
def _refresh_subaru_aol_setting(self, now_ns: int, *, force: bool = False) -> None:
if not force and (now_ns - self._subaru_aol_last_read_ns) < 500_000_000:
return
self._subaru_aol_last_read_ns = now_ns
self.aol_enabled_setting = self.params.get_bool("AlwaysOnLateral")
def _configure_route_tune(self, manual_status):
from openpilot.starpilot.flm.offroad_runtime import configure
@@ -464,6 +508,32 @@ class Controls:
if cycle_timing is not None:
cycle_timing.mark()
legacy_2025 = self.CP.carFingerprint == "SUBARU_LEGACY_2025"
if legacy_2025:
mode_now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns()
self._refresh_subaru_aol_setting(mode_now_ns)
aol = bool(self.aol_enabled_setting)
raw_lkas_pressed = any(be.type == car.CarState.ButtonEvent.Type.lkas and be.pressed for be in CS.buttonEvents)
if not CS.cruiseState.available:
self._prev_lkas_button_pressed = False
lkas_pressed = raw_lkas_pressed and not self._prev_lkas_button_pressed
self._prev_lkas_button_pressed = raw_lkas_pressed
if not CS.cruiseState.available:
self.lateral_off = not aol
else:
entered_mode = (not self._prev_cruise_available) or (aol != self._prev_aol_enabled)
if entered_mode:
self.lateral_off = not aol
elif lkas_pressed and aol:
self.lateral_off = not self.lateral_off
self._prev_cruise_available = bool(CS.cruiseState.available)
self._prev_aol_enabled = aol
else:
self.lateral_off = False
if legacy_2025 and ((self.aol_enabled_setting and self.lateral_off) or (not self.aol_enabled_setting and not CC.enabled)):
CC.latActive = False
actuators = CC.actuators
actuators.longControlState = self.LoC.long_control_state
@@ -543,6 +613,14 @@ class Controls:
elif getattr(self, 'model_turn_assist', None) is not None:
self.model_turn_assist.reset()
self.model_turn_assist.twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
if not assist_ready and self.CP.carFingerprint == "SUBARU_LEGACY_2025":
subaru_gear_ok = CS.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low, car.CarState.GearShifter.manumatic)
if self.sm.all_checks(['modelV2']) and not CS.steerFaultTemporary and not CS.steerFaultPermanent and subaru_gear_ok:
self.subaru_twitch_guard_armed = update_twitch_guard(self.subaru_twitch_guard_armed, CS.vEgo, CS.standstill)
if CC.latActive and not CS.leftBlinker and not CS.rightBlinker and self.subaru_twitch_guard_armed:
new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo, min_reach=4.0)
else:
self.subaru_twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill)
if self.highway_smoothing_supported:
preferences = getattr(self, "live_steering_preferences", None)
if preferences is not None:
@@ -795,11 +873,49 @@ class Controls:
hudControl.leadDistanceBars = self.sm['selfdriveState'].personality.raw + 1
hudControl.visualAlert = self.sm['selfdriveState'].alertHudVisual
hudControl.rightLaneVisible = True
hudControl.leftLaneVisible = True
if self.sm.valid['driverAssistance']:
hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture
hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture
if self.CP.carFingerprint == "SUBARU_LEGACY_2025":
lines_allowed = bool(
CS.cruiseState.available and (
(self.aol_enabled_setting and not self.lateral_off) or
(not self.aol_enabled_setting and CC.enabled)
)
)
if not lines_allowed:
self._aol_left_line_vis = None
self._aol_left_line_timer = 0.0
self._aol_right_line_vis = None
self._aol_right_line_timer = 0.0
hudControl.lanesVisible = False
hudControl.leftLaneVisible = False
hudControl.rightLaneVisible = False
hudControl.leftLaneDepart = False
hudControl.rightLaneDepart = False
else:
hudControl.lanesVisible = True
lane_probs = self.sm['modelV2'].laneLineProbs if self.sm.valid['modelV2'] and len(self.sm['modelV2'].laneLineProbs) >= 3 else None
if lane_probs is not None:
left_prob = float(lane_probs[1])
right_prob = float(lane_probs[2])
self._aol_left_line_vis, self._aol_left_line_timer = _update_subaru_line_visibility(
self._aol_left_line_vis, self._aol_left_line_timer, left_prob, DT_CTRL
)
self._aol_right_line_vis, self._aol_right_line_timer = _update_subaru_line_visibility(
self._aol_right_line_vis, self._aol_right_line_timer, right_prob, DT_CTRL
)
hudControl.leftLaneVisible = bool(self._aol_left_line_vis)
hudControl.rightLaneVisible = bool(self._aol_right_line_vis)
else:
hudControl.leftLaneVisible = True
hudControl.rightLaneVisible = True
if self.sm.valid['driverAssistance']:
hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture
hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture
else:
hudControl.rightLaneVisible = True
hudControl.leftLaneVisible = True
if self.sm.valid['driverAssistance']:
hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture
hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture
feedback_input_limited = self.steer_limited_by_safety
if CC.latActive:
+21 -1
View File
@@ -9,6 +9,18 @@ from openpilot.starpilot.aol.runtime import monitoring_lateral_engaged
from openpilot.starpilot.feature_runtime import requested as feature_requested
def _read_allow_manumatic(params: Params) -> bool | None:
try:
cp_bytes = params.get("CarParams")
except Exception:
return None
if not cp_bytes:
return None
from opendbc.car.structs import car
with car.CarParams.from_bytes(cp_bytes) as cp:
return cp.carFingerprint == "SUBARU_LEGACY_2025"
def dmonitoringd_thread():
config_realtime_process([0, 1, 2, 3], 5)
@@ -18,7 +30,10 @@ def dmonitoringd_thread():
required = ['driverStateV2', 'extrinsicsCalibration', 'carState', 'selfdriveState', 'modelV2']
sm = messaging.SubMaster(required + (['aolAxisState', 'aolSafetyWire'] if aol_replay else []), poll='driverStateV2')
DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM"))
allow_manumatic = _read_allow_manumatic(params)
cp_checked = allow_manumatic is not None
DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM"),
allow_manumatic=bool(allow_manumatic))
demo_mode=False
# 20Hz <- dmonitoringmodeld
@@ -43,6 +58,11 @@ def dmonitoringd_thread():
if sm['driverStateV2'].frameId % 40 == 1:
DM.always_on = params.get_bool("AlwaysOnDM")
demo_mode = params.get_bool("IsDriverViewEnabled")
if not cp_checked:
allow_manumatic = _read_allow_manumatic(params)
if allow_manumatic is not None:
DM.allow_manumatic = allow_manumatic
cp_checked = True
# save rhd virtual toggle every 5 mins
if (sm['driverStateV2'].frameId % 6000 == 0 and not demo_mode and
+8 -2
View File
@@ -129,7 +129,7 @@ def face_orientation_from_model(orient_model, pos_model, rpy_calib):
class DriverMonitoring:
def __init__(self, rhd_saved=False, settings=None, always_on=False):
def __init__(self, rhd_saved=False, settings=None, always_on=False, allow_manumatic=False):
# init policy settings
self.settings = settings if settings is not None else DRIVER_MONITOR_SETTINGS()
@@ -143,6 +143,7 @@ class DriverMonitoring:
self.alert_level = AlertLevel.none
self.always_on = always_on
self.allow_manumatic = allow_manumatic
self.distracted_types = defaultdict(bool)
self.driver_distracted = False
self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, DT_DMON)
@@ -441,7 +442,12 @@ class DriverMonitoring:
else:
car_speed = sm['carState'].vEgo
enabled = sm['selfdriveState'].enabled or aol_lateral_engaged
wrong_gear = sm['carState'].gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low)
allowed_gears = (
(car.CarState.GearShifter.drive, car.CarState.GearShifter.low, car.CarState.GearShifter.manumatic)
if self.allow_manumatic else
(car.CarState.GearShifter.drive, car.CarState.GearShifter.low)
)
wrong_gear = sm['carState'].gearShifter not in allowed_gears
lowspeed = car_speed < self.settings._ALERT_MIN_SPEED
driver_engaged = sm['carState'].steeringPressed or sm['carState'].gasPressed
brake_disengage_prob = sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s
+35 -8
View File
@@ -26,7 +26,7 @@ from openpilot.starpilot.gps.source import observation as gps_observation
from openpilot.selfdrive.car.car_events import CarEvents
from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose
from openpilot.selfdrive.selfdrived.events import Events, ET, Alert, Priority as AlertPriority
from openpilot.selfdrive.selfdrived.events import Events, ET, Alert, EngagementAlert, Priority as AlertPriority
from openpilot.selfdrive.selfdrived.bookmarks import BookmarkCounter
from openpilot.starpilot.bookmark_state import BookmarkCheckpoint
from openpilot.starpilot.longitudinal.force_stop_alert import HoldAlertState, EVENT_TYPE as FORCE_STOP_HOLD
@@ -218,7 +218,8 @@ class SelfdriveD:
self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator")
self.radar_recovery_enabled = self.params.get_bool("RadarRecoveryAlert")
self.blindspot_alert_settings = (self.params.get_bool("LoudBlindspotAlert"),
self.params.get_bool("LoudBlindspotAlertWhenDisengaged"))
self.params.get_bool("LoudBlindspotAlertWhenDisengaged"),
self.params.get_bool("LoudBlindspotAlertMuteAtStandstill"))
car_recognized = self.CP.brand != 'mock'
@@ -253,6 +254,7 @@ class SelfdriveD:
self.dm_lockout_set = False
self.dm_uncertain_alerted = False
self.state_machine = StateMachine()
self.legacy_2025_green_wheel_active = False
self.rk = Ratekeeper(100, print_delay_threshold=None)
# Observational only. Do not cache this qualification for authority decisions.
@@ -1002,8 +1004,9 @@ class SelfdriveD:
active_longitudinal and sample.gasPressed and not held_gas or
sample.seatbeltUnlatched or sample.accFaulted or sample.doorOpen or physical_cancel(sample, self.CP) or
qualified_gm(self.CP) and not sample.cruiseState.available or
sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
car.CarState.GearShifter.low, car.CarState.GearShifter.brake)
(sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
car.CarState.GearShifter.low, car.CarState.GearShifter.brake) and
not (self.CP.carFingerprint == "SUBARU_LEGACY_2025" and sample.gearShifter == car.CarState.GearShifter.manumatic))
for sample, valid in samples):
return 0
native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=session)
@@ -1187,11 +1190,12 @@ class SelfdriveD:
now_ns = time.monotonic_ns()
drive = int(self.sm['deviceState'].startedMonoTime) if self.sm['deviceState'].started else 0
from openpilot.starpilot.audio.blindspot_alert import ALERT_TYPE as BSM_ALERT, blindspot_alert
loud, without_lateral = getattr(self, 'blindspot_alert_settings', (False, False))
loud, without_lateral, mute_at_standstill = getattr(self, 'blindspot_alert_settings', (False, False, False))
blindspot = blindspot_alert(CS, self.sm, loud=loud, without_lateral=without_lateral,
lane_change_blocked=EventName.laneChangeBlocked in self.events.names, now_ns=now_ns,
car_ns=getattr(self, 'aol_car_state_log_ns', 0),
car_valid=getattr(self, 'conditional_car_state_valid', False))
car_valid=getattr(self, 'conditional_car_state_valid', False),
mute_at_standstill=mute_at_standstill)
if blindspot is not None:
alerts = [alert for alert in alerts if alert.alert_type != 'laneChangeBlocked/warning']
self.AM.alerts.pop('laneChangeBlocked/warning', None)
@@ -1290,6 +1294,27 @@ class SelfdriveD:
# Saturation is already ignored during override; retire its held presentation too.
alerts = [alert for alert in alerts if alert.alert_type != 'steerSaturated/warning']
self.AM.alerts.pop('steerSaturated/warning', None)
if self.CP.carFingerprint == "SUBARU_LEGACY_2025":
alerts = [alert for alert in alerts if alert.alert_type not in ("pcmEnable/enable", "pcmDisable/userDisable")]
self.AM.alerts.pop("pcmEnable/enable", None)
self.AM.alerts.pop("pcmDisable/userDisable", None)
if self.CP.passive:
self.legacy_2025_green_wheel_active = False
elif self.sm.seen['carControl'] and self.sm.valid['carControl'] and CS.canValid and not CS.canTimeout:
hud = self.sm['carControl'].hudControl
green_wheel_active = bool(
CS.cruiseState.available and hud.lanesVisible and
not CS.steerFaultTemporary and not CS.steerFaultPermanent
)
if green_wheel_active != self.legacy_2025_green_wheel_active:
self.legacy_2025_green_wheel_active = green_wheel_active
chime = EngagementAlert(
log.SelfdriveState.AudibleAlert.engage if green_wheel_active else log.SelfdriveState.AudibleAlert.disengage
)
chime.alert_type = "legacy2025AolEngage/enable" if green_wheel_active else "legacy2025AolDisengage/userDisable"
chime.event_type = "legacy2025AolChime"
self.AM.alerts.pop("legacy2025AolDisengage/userDisable" if green_wheel_active else "legacy2025AolEngage/enable", None)
alerts.append(chime)
from openpilot.starpilot.audio.departure_alert import protect_safety_alerts
retained = ()
if departure:
@@ -1927,7 +1952,8 @@ class SelfdriveD:
self.sm['driverMonitoringState'].alertLevel == AlertLevel.three)),
pause_brake_mps=pause_brake_mps,
gear_pause=reverse_pause,
lateral_inhibit=self.aol_dm_lateral_inhibit or sng_standstill_lateral_inhibit(self.CP, CS) or
lateral_inhibit=self.aol_dm_lateral_inhibit or sng_standstill_lateral_inhibit(
self.CP, CS, initial_wait=bool(native is None or not native.lateralAllowed)) or
volkswagen_lateral_output_inhibited(self.CP, CS) or any(
sample.steerFaultTemporary or pause_brake_mps > 0 and sample.brakePressed and not sample.standstill and
sample.vEgo < pause_brake_mps
@@ -2437,7 +2463,8 @@ class SelfdriveD:
self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator")
self.radar_recovery_enabled = self.params.get_bool("RadarRecoveryAlert")
self.blindspot_alert_settings = (self.params.get_bool("LoudBlindspotAlert"),
self.params.get_bool("LoudBlindspotAlertWhenDisengaged"))
self.params.get_bool("LoudBlindspotAlertWhenDisengaged"),
self.params.get_bool("LoudBlindspotAlertMuteAtStandstill"))
self.departure_alert_settings = (self.params.get_bool("GreenLightAlert"), self.params.get_bool("LeadDepartingAlert"))
self.nostalgia_enabled = nostalgia_saved_enabled(self.params)
self.refresh_saved_driving_mode(time.monotonic_ns())
+16
View File
@@ -107,6 +107,8 @@ class Soundd:
self.stream_report_at = None
self.native_audio = None
self.axis_alerts = AxisAlerts()
self._cp_checked = False
self._refresh_car_fingerprint()
self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False)
@@ -152,11 +154,25 @@ class Soundd:
immediate_ramp=self.current_volume if producing_alert in (AudibleAlert.warningSoft, AudibleAlert.warningImmediate) else None)
return ret * gain
def _refresh_car_fingerprint(self) -> None:
if getattr(self, "_cp_checked", False) or not hasattr(self, "axis_alerts"):
return
try:
cp_bytes = self.volume_params.get("CarParams")
except Exception:
cp_bytes = None
if cp_bytes:
from opendbc.car.structs import car
with car.CarParams.from_bytes(cp_bytes) as cp:
self.axis_alerts.suppress_lateral = (cp.carFingerprint == "SUBARU_LEGACY_2025")
self._cp_checked = True
def refresh_saved_volumes(self, now: float) -> None:
"""Read slow Params state from the service loop, never the audio callback."""
if now - self.volume_read_at < 0.25:
return
self.volume_read_at = now
self._refresh_car_fingerprint()
self.saved_volumes = {key: read_volume(self.volume_params, key).value for key, _, _ in VOLUMES}
def callback(self, data_out: np.ndarray, frames: int, time, status) -> None:
+3 -2
View File
@@ -7,8 +7,9 @@ def armed_lateral_current(cp, cs, intent, native, *, source_ns, now_ns, axis_ses
return bool(policy_for(cp).intent_supported and
cs.canValid and not cs.canTimeout and not cs.accFaulted and not cs.doorOpen and
not cs.steerFaultTemporary and not cs.steerFaultPermanent and cs.cruiseState.available and
cs.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low,
car.CarState.GearShifter.sport, car.CarState.GearShifter.brake) and
(cs.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low,
car.CarState.GearShifter.sport, car.CarState.GearShifter.brake) or
cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == car.CarState.GearShifter.manumatic) and
intent is not None and intent.settingsQualified and intent.allowedLatch and intent.lateralArmed and
intent.producerSessionId and intent.carStateLogMonoTime == source_ns and
0 < source_ns <= intent.observedMonoTime <= now_ns <= intent.validUntilMonoTime and
+1 -1
View File
@@ -328,7 +328,7 @@ class AolCardIntent:
# owners keep their current event and native contracts.
main_toggle = (not independent_buttons or main_managed) and not (
self.independent_cruise_buttons and self.settings.main_wheel_action)
lkas_toggle = not independent_buttons or lkas_managed
lkas_toggle = (not independent_buttons or lkas_managed) and not getattr(self, 'allow_manumatic', False)
previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle)
cancel_pressed = False
for event in CS.buttonEvents:
+5 -3
View File
@@ -7,8 +7,10 @@ def seatbelt_lateral_soft_event_allowed(cp, cs, intent, native, event, *, source
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, native_inventory_matches_cp
try:
gears = car.CarState.GearShifter
paused_gear = bool(gear_pause is True and cs.gearShifter in
(gears.drive, gears.low, gears.sport, gears.brake, gears.neutral, gears.reverse))
legacy_manumatic = cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == gears.manumatic
paused_gear = bool(gear_pause is True and (cs.gearShifter in
(gears.drive, gears.low, gears.sport, gears.brake, gears.neutral, gears.reverse) or
legacy_manumatic))
paused_native = bool(paused_gear and native is not None and
not native.requestedLateral and not native.lateralAllowed and
not native.requestedLongitudinal and not native.longitudinalAllowed)
@@ -23,7 +25,7 @@ def seatbelt_lateral_soft_event_allowed(cp, cs, intent, native, event, *, source
event.noEntry and not event.immediateDisable and not event.userDisable and
cs.seatbeltUnlatched and cs.canValid and not cs.canTimeout and not cs.accFaulted and not cs.doorOpen and
(not cs.steerFaultTemporary or paused_eps) and not cs.steerFaultPermanent and cs.cruiseState.available and
(paused_gear or cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake)) and
(paused_gear or cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake) or legacy_manumatic) and
intent is not None and intent.settingsQualified and
((intent.allowedLatch or paused_gear) and intent.lateralArmed or
pending_native and not intent.allowedLatch and not intent.lateralArmed) and
+11 -7
View File
@@ -13,6 +13,12 @@ EventName = log.OnroadEvent.EventName
AlertLevel = log.DriverMonitoringState.AlertLevel
def _forward_gear_allowed(cp, gear) -> bool:
gears = car.CarState.GearShifter
return gear in (gears.drive, gears.sport, gears.low, gears.brake) or (
cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic)
def stock_lateral_role(self, CS, native, intent=None, *, allow_independent_cancel=False, allow_independent_brake=False,
allow_independent_gas=False, allow_expired_source=False, now_ns=0):
"""Current stock USER role while an established independent LAT owner remains."""
@@ -65,7 +71,8 @@ def stock_lateral_role(self, CS, native, intent=None, *, allow_independent_cance
getattr(self, 'aol_fault_reason', 'none') == 'availabilityPause' and previous.desired_lateral) and
(previous.native_acknowledged or allow_expired_source) and not previous.longitudinal_active and
(CS.gearShifter == car.CarState.GearShifter.drive or self.CP.brand == 'gm' and
CS.gearShifter == car.CarState.GearShifter.low) and isfinite(CS.vEgoRaw) and isfinite(CS.vEgo))
CS.gearShifter == car.CarState.GearShifter.low or
self.CP.carFingerprint == 'SUBARU_LEGACY_2025' and CS.gearShifter == car.CarState.GearShifter.manumatic) and isfinite(CS.vEgoRaw) and isfinite(CS.vEgo))
rules = self.events.event_rules
stock_user = stock_lateral_user_event(self.CP)
users = [name for name in self.events.names if ET.USER_DISABLE in rules.get(name, {})]
@@ -128,8 +135,7 @@ def stock_lateral_fault_proof(self, CS, message, now_ns):
if any(not valid or not sample.canValid or sample.canTimeout or sample.steerFaultPermanent or
sample.steerFaultTemporary or sample.accFaulted or sample.doorOpen or sample.seatbeltUnlatched or
sample.brakePressed or sample.regenBraking or sample.gasPressed or physical_cancel(sample, self.CP) or
sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
car.CarState.GearShifter.low, car.CarState.GearShifter.brake) for sample, valid in samples):
not _forward_gear_allowed(self.CP, sample.gearShifter) for sample, valid in samples):
return None
return (published, stock_user)
@@ -266,8 +272,7 @@ def ordinary_source_availability(self, CS, now_ns, native=None, *, replay: bool,
(sample.brakePressed or sample.regenBraking) and not held_pedal or
sample.gasPressed and not (toyota_pedal or stock_gas or ford_gas or toyota_gas) or
(stock_gas or ford_gas or toyota_gas) and sample.gasPressed != accepted_state.gasPressed or physical_cancel(sample, self.CP) or
sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
car.CarState.GearShifter.low, car.CarState.GearShifter.brake)
not _forward_gear_allowed(self.CP, sample.gearShifter)
for sample, valid in samples):
return False
def valid_metadata(stamp, value):
@@ -374,6 +379,5 @@ def fresh_ordinary_lag_continuation(self, CS, intent, native, now_ns):
return not any(not valid or not sample.canValid or sample.canTimeout or sample.steerFaultPermanent or
sample.steerFaultTemporary or sample.accFaulted or sample.doorOpen or sample.seatbeltUnlatched or
sample.brakePressed or sample.regenBraking or sample.gasPressed or physical_cancel(sample, self.CP) or
sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
car.CarState.GearShifter.low, car.CarState.GearShifter.brake)
not _forward_gear_allowed(self.CP, sample.gearShifter)
for sample, valid in samples)
@@ -158,7 +158,8 @@ def temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *,
(previous[9] and previous[11] and previous[13] or
self.temporary_eps_event_ns and previous[6] == self.temporary_eps_event_ns))
stock_subaru_eps = bool(subaru_temporary_restriction(cp, cs) and subaru_predecessor and
cs.gearShifter == structs.CarState.GearShifter.drive and not cs.doorOpen and
(cs.gearShifter == structs.CarState.GearShifter.drive or
cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == structs.CarState.GearShifter.manumatic) and not cs.doorOpen and
not cs.vehicleSensorsInvalid and not cs.steeringDisengage and not cs.buttonEvents and
all(not event.userDisable or event.name == log.OnroadEvent.EventName.pcmDisable and
not event.softDisable and not event.immediateDisable for event in events))
+7 -14
View File
@@ -2,7 +2,8 @@
from openpilot.cereal import log
from openpilot.starpilot.aol.transport_pause_conditions import (
AVAILABILITY_EVENTS as AVAILABILITY_EVENTS, HOST_SOURCE_AVAILABILITY_EVENTS as HOST_SOURCE_AVAILABILITY_EVENTS,
availability_only as availability_only, host_source_availability_only, stock_lateral_off,
availability_only as availability_only, forward_gear_allowed, host_source_availability_only, stock_lateral_off,
subaru_stop_drive_gear,
)
from openpilot.starpilot.aol.transport_pause_session import (
AvailabilityPause as AvailabilityPause, TransportPause as TransportPause, cp_identity as cp_identity,
@@ -303,7 +304,6 @@ class TransportPauseFeedback:
def _ordinary_warning_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer):
from openpilot.starpilot.aol.vehicle import policy_for
from openpilot.starpilot.nostalgia import physical_cancel
from opendbc.car import structs
pending_baseline = self.ordinary_warning_pending_baseline
pending = bool(pending_baseline is not None and self.pending_event)
@@ -316,8 +316,7 @@ class TransportPauseFeedback:
axis.intentIntegrityEpoch != self.availability_epoch or
not cs.canValid or cs.canTimeout or cs.steerFaultPermanent or cs.accFaulted or cs.doorOpen or
cs.steeringDisengage or
cs.gearShifter not in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport,
structs.CarState.GearShifter.low, structs.CarState.GearShifter.brake) or
not forward_gear_allowed(cp, cs.gearShifter) or
not 0 < self.lateral_source_ns <= axis.sourceCarStateMonoTime <= stamp <= now_ns or
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
str(axis.faultReason) not in ('none', 'availabilityPause') or
@@ -450,8 +449,6 @@ class TransportPauseFeedback:
from opendbc.car.hyundai.canfd_angle_aol import qualified as angle_qualified
from opendbc.car.hyundai.canfd_stock_aol import qualified as stock_canfd_qualified
from opendbc.car.hyundai.classic_scc_aol import qualified as stock_classic_qualified
from opendbc.car import structs
gears = structs.CarState.GearShifter
# PCM-off is not AOL-off: retain intent for location/EPS recovery;
recovering_user = bool((location_fault or eps_recovery) and users)
@@ -468,7 +465,7 @@ class TransportPauseFeedback:
or cp.brand == 'volkswagen' and volkswagen_qualified(cp, marked_only=True)) and users and
not axis.desiredLongitudinal and not axis.longitudinalActive and
(cs.cruiseState.available or classic_eps_recovery) and not cs.cruiseState.enabled and
cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake) and
forward_gear_allowed(cp, cs.gearShifter) and
not cs.doorOpen and (not cs.seatbeltUnlatched or belt_eps_recovery) and not cs.brakePressed and not cs.regenBraking and
(not cs.gasPressed or stock_angle or classic_eps_recovery or eps_recovery and stock_canfd_qualified(cp, marked_only=True)) and
all((event.name == stock_user or classic_eps_recovery and not cs.cruiseState.available and
@@ -1078,7 +1075,6 @@ class TransportPauseFeedback:
return True
def _angle_stop_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer):
from opendbc.car.structs import car
from opendbc.car.hyundai.canfd_angle_aol import qualified, temporary_restriction
from opendbc.car.mazda.stock_aol import qualified as mazda_qualified, temporary_restriction as mazda_restriction
from opendbc.car.subaru.stock_aol import temporary_restriction as subaru_restriction
@@ -1091,7 +1087,7 @@ class TransportPauseFeedback:
pending_stop = bool(ccnc_stop and axis.desiredLongitudinal and not axis.longitudinalActive and not axis.lateralActive)
subaru_stop = cs.standstill and subaru_restriction(cp, cs)
if (not (qualified(cp, marked_only=True) or mazda_qualified(cp, marked_only=True) or subaru_stop or ccnc_stop) or
cs.gearShifter != car.CarState.GearShifter.drive or
not subaru_stop_drive_gear(cp, cs.gearShifter, subaru_stop) or
not (temporary_restriction(cp, cs) or mazda_restriction(cp, cs) or subaru_stop) or cs.steerFaultTemporary or cs.steerFaultPermanent or
not latched or self.failed or self.paused or self.pending_event or self.retention_started_ns or
not (self.lateral_only_baseline or ccnc_stop) or not self.lateral_inventory or not self.lateral_baseline_ns or
@@ -1174,7 +1170,6 @@ class TransportPauseFeedback:
from openpilot.starpilot.car.subaru.paused_intent import retain_stopped_source_feedback
if retain_stopped_source_feedback(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=producer):
return True
from opendbc.car import structs
previous = self.signature
if (not latched or self.failed or self.paused or self.pending_event or self.retention_started_ns or
self.source_retention_started_ns or not self.ever_lateral_active or previous is None or
@@ -1183,8 +1178,7 @@ class TransportPauseFeedback:
not producer or previous[14] != producer or
not 0 < previous[8] <= previous[2] <= self.healthy_feedback_ns <= now_ns or
now_ns - previous[8] > SAFETY_MAX_AGE_NS or
cs.gearShifter not in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.low,
structs.CarState.GearShifter.sport, structs.CarState.GearShifter.brake) or
not forward_gear_allowed(cp, cs.gearShifter) or
not cs.canValid or cs.canTimeout or cs.steerFaultTemporary or cs.steerFaultPermanent or
cs.accFaulted or cs.vehicleSensorsInvalid or cs.doorOpen or cs.seatbeltUnlatched or
cs.steeringDisengage or not cs.cruiseState.available or cs.buttonEvents or
@@ -1557,8 +1551,7 @@ class TransportPauseFeedback:
str(axis.mode) == 'off' and not any(signature[9:13]) and
cs.cruiseState.available and not cs.accFaulted and not cs.vehicleSensorsInvalid and
not cs.doorOpen and not cs.steeringDisengage and
(cs.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport,
structs.CarState.GearShifter.low, structs.CarState.GearShifter.brake) or
(forward_gear_allowed(cp, cs.gearShifter) or
intent_paused and cs.gearShifter in (structs.CarState.GearShifter.reverse, structs.CarState.GearShifter.neutral)) and
sm.seen['onroadEvents'] and sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and
0 < int(sm.logMonoTime['onroadEvents']) <= now_ns and
@@ -51,3 +51,17 @@ def stock_lateral_off(cp, cs, native, *, allow_independent_cancel=False, allow_i
cp.brand == 'hyundai' and (stock_canfd_qualified(cp, marked_only=True) or classic_stock))) and
(not physical_cancel(cs, cp) or independent_angle and allow_independent_cancel) and
native is not None and native.requestedLateral and native.lateralAllowed and not native.requestedLongitudinal)
def forward_gear_allowed(cp, gear) -> bool:
from opendbc.car import structs
gears = structs.CarState.GearShifter
return gear in (gears.drive, gears.sport, gears.low, gears.brake) or (
cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic)
def subaru_stop_drive_gear(cp, gear, subaru_stop: bool) -> bool:
from opendbc.car import structs
gears = structs.CarState.GearShifter
return gear == gears.drive or (
subaru_stop and cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic)
+5 -3
View File
@@ -96,6 +96,7 @@ class AxisAlerts:
self.steering_session = None
self.steering_warned = False
self.steering_recovered_since = 0
self.suppress_lateral = False
def temporary_steering_sound(self, sm, intent, native_sound, now_ns, state_fresh):
if intent is None or not state_fresh:
@@ -132,9 +133,10 @@ class AxisAlerts:
sm.valid['selfdriveState'] and sm.alive['selfdriveState'])
lateral_known = intent is not None and (intent.pauseLateral or intent.lateralArmed or state_fresh)
axis = current_axis(sm, now_ns=now_ns) if 'aolAxisState' in sm.logMonoTime else None
lateral = self.lateral.update(intent if lateral_known else None,
bool(intent and not intent.pauseLateral and
(intent.lateralArmed or (state_fresh and sm['selfdriveState'].active))), axis, now_ns)
lateral = 0 if self.suppress_lateral else self.lateral.update(
intent if lateral_known else None,
bool(intent and not intent.pauseLateral and
(intent.lateralArmed or (state_fresh and sm['selfdriveState'].active))), axis, now_ns)
longitudinal = self.longitudinal.update(
intent.producerSessionId if intent is not None and state_fresh else None,
intent.sequence if intent is not None else 0,
+5 -3
View File
@@ -1,12 +1,12 @@
"""Optional blind-spot presentation; never changes lane-change or control authority."""
KEYS = ("LoudBlindspotAlert", "LoudBlindspotAlertWhenDisengaged")
KEYS = ("LoudBlindspotAlert", "LoudBlindspotAlertWhenDisengaged", "LoudBlindspotAlertMuteAtStandstill")
ALERT_TYPE = "blindSpotAdvisory/warning"
EVENT_TYPE = "blindSpotAdvisory"
def blindspot_alert(cs, sm, *, loud: bool, without_lateral: bool, lane_change_blocked: bool, now_ns: int,
car_ns: int, car_valid: bool):
car_ns: int, car_valid: bool, mute_at_standstill: bool = False):
if not loud and not without_lateral:
return None
try:
@@ -21,8 +21,10 @@ def blindspot_alert(cs, sm, *, loud: bool, without_lateral: bool, lane_change_bl
return None
matching_signal = (bool(cs.leftBlinker) != bool(cs.rightBlinker) and
(cs.leftBlinker and cs.leftBlindspot or cs.rightBlinker and cs.rightBlindspot))
standstill = bool(getattr(cs, 'standstill', False) or float(getattr(cs, 'vEgo', 1.0)) < 0.5)
if not (loud and lane_change_blocked or
without_lateral and not sm['carControl'].latActive and matching_signal):
without_lateral and not sm['carControl'].latActive and matching_signal and
not (mute_at_standstill and standstill)):
return None
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
return None
@@ -45,6 +45,19 @@ def test_no_wrong_side_hazards_or_invalid_can(fields):
lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True)
def test_standstill_mute_only_applies_without_lateral_when_enabled():
for fields in ({'standstill': True}, {'vEgo': 0.49}):
assert blindspot_alert(car(**fields), Messages(), loud=False, without_lateral=True,
lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True)
assert not blindspot_alert(car(**fields), Messages(), loud=False, without_lateral=True,
lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True,
mute_at_standstill=True)
# LoudBlindspotAlert during an active/blocked lane change is never muted at standstill.
assert blindspot_alert(car(**fields), Messages(active=True), loud=True, without_lateral=False,
lane_change_blocked=True, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True,
mute_at_standstill=True)
def test_right_side_and_stale_or_offroad_inputs():
cs = car(leftBlinker=False, leftBlindspot=False, rightBlinker=True, rightBlindspot=True)
sm = Messages()
@@ -84,13 +97,23 @@ def test_switch_defaults_persistence_and_exact_authority(tmp_path):
params = Params(str(tmp_path))
allowed = True
owner = SoundsOwner(params, lambda: allowed)
for key in KEYS:
mute_row = next(row for row in owner.snapshot().rows if row.key == KEYS[2])
assert not mute_row.available
assert not owner.apply(FeatureSettingsRequest(KEYS[2], mute_row.source, 'On'))
for key in KEYS[:2]:
row = next(row for row in owner.snapshot().rows if row.key == key)
assert row.value == 'Off' and row.default_value == 'Off'
request = FeatureSettingsRequest(key, row.source, 'On')
assert owner.apply(request)
assert params.get_bool(key)
assert not owner.apply(request)
if key == KEYS[1]:
mute_row = next(row for row in owner.snapshot().rows if row.key == KEYS[2])
assert mute_row.available
assert owner.apply(FeatureSettingsRequest(KEYS[2], mute_row.source, 'On'))
assert params.get_bool(KEYS[2])
assert owner.apply(FeatureSettingsRequest(KEYS[2], b'1', 'Off'))
assert not params.get_bool(KEYS[2])
allowed = False
assert not owner.apply(FeatureSettingsRequest(key, b'1', 'Off'))
allowed = True
@@ -106,7 +129,10 @@ def test_galaxy_sounds_switches_save_and_reset_with_session_checks(tmp_path):
context = Context()
gateway = SettingsGateway(params, context)
for key, label in zip(KEYS, ('Loud Blindspot Alert', 'Blindspot Alert While Lateral Is Off'), strict=True):
for key, label in zip(KEYS, ('Loud Blindspot Alert', 'Blindspot Alert While Lateral Is Off',
'Mute Blindspot Alert at Standstill'), strict=True):
if key == KEYS[2]:
params.put_bool(KEYS[1], True, block=True)
page = gateway.page('sounds', 'session', b'generation')
index, row = next((i, row) for i, row in enumerate(page['rows']) if row['label'] == label)
assert row['choices'] == ['Off', 'On'] and row['defaultValue'] == 'Off'
@@ -121,6 +147,7 @@ def test_galaxy_sounds_switches_save_and_reset_with_session_checks(tmp_path):
reset = gateway.preview(page['view'], index, 0, 'session', b'generation', reset_default=True)
assert gateway.confirm(reset['intent'], 'session', b'generation')
assert not params.get_bool(key)
params.put_bool(KEYS[1], False, block=True)
@pytest.mark.parametrize('car_ns,valid', [(0, True), (NOW + 1, True), (NOW - 200_000_001, True), (NOW, False)])
@@ -178,7 +205,7 @@ def test_actual_selfdrived_socket_live_setting_publication_and_sound(tmp_path):
stop = threading.Event()
with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()):
sd.params_thread(stop)
assert sd.blindspot_alert_settings == (False, True)
assert sd.blindspot_alert_settings == (False, True, False)
state, stamp = sample(20)
assert sd.AM.current_alert.alert_type == ALERT_TYPE, 'BLINDSPOT_CALLER_SILENT'
output = {}
@@ -200,9 +227,17 @@ def test_actual_selfdrived_socket_live_setting_publication_and_sound(tmp_path):
(23, {'age': -1}), (24, {'active': True})]:
sample(tick, **fields)
assert ALERT_TYPE not in sd.AM.alerts
params.put_bool(KEYS[1], False, block=True)
params.put_bool(KEYS[2], True, block=True)
stop.clear()
with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()):
sd.params_thread(stop)
assert sd.blindspot_alert_settings == (False, True, True)
sample(25)
assert ALERT_TYPE in sd.AM.alerts # vEgo == 8.0 is above standstill mute threshold
params.put_bool(KEYS[1], False, block=True)
params.put_bool(KEYS[2], False, block=True)
stop.clear()
with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()):
sd.params_thread(stop)
sample(26)
assert ALERT_TYPE not in sd.AM.alerts
+4
View File
@@ -12,4 +12,8 @@ def unsupported_gear(cp, gear) -> bool:
if cp.brand == "gm":
from openpilot.starpilot.car.gm.events import unsupported_gear as gm_unsupported
return gm_unsupported(cp, gear)
if cp.brand == "subaru":
from opendbc.car.structs import car
from opendbc.car.subaru.values import CAR
return cp.carFingerprint != CAR.SUBARU_LEGACY_2025 and gear == car.CarState.GearShifter.manumatic
return False
+54 -18
View File
@@ -6,18 +6,26 @@ from openpilot.starpilot.aol.intent import AolCardIntent
from openpilot.starpilot.aol.policy import AolVehiclePolicy
def _drive_gear(cp, state):
if cp is not None and cp.carFingerprint == CAR.SUBARU_LEGACY_2025:
return state.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
return state.gearShifter == structs.CarState.GearShifter.drive
class SubaruStockCardIntent(AolCardIntent):
observe_stock_engagement = True
def __init__(self, settings, *, main_arm=False):
def __init__(self, settings, *, main_arm=False, allow_manumatic=False):
super().__init__(settings, explicit_latch=True, lkas_button_supported=False)
self.main_arm = main_arm
self.allow_manumatic = allow_manumatic
self._previous_main = None
self._main_observed_ns = 0
self._main_event_ns = 0
self._pending_main_ns = 0
self._pending_main_after_ns = 0
self._pending_main_restriction_ns = 0
self._deferred_park_main = False
self.main_arm_ns = 0
def observe_startup_readiness(self, sm, CS, *, now_ns, **kwargs):
@@ -31,12 +39,23 @@ class SubaruStockCardIntent(AolCardIntent):
now_ns = kwargs.get('now_ns', 0)
main = bool(CS.cruiseState.available)
fresh_main = self._previous_main is False and main
physical_safe = (self.settings.enabled and CS.canValid and not CS.canTimeout and
not self._calibration_inhibit and not self._calibration_rearm_required and
not CS.steerFaultPermanent and not CS.accFaulted and
not any(e.type == structs.CarState.ButtonEvent.Type.cancel and e.pressed for e in CS.buttonEvents) and
CS.gearShifter == structs.CarState.GearShifter.drive)
if self.main_arm and fresh_main and physical_safe:
allowed_gears = (
(structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
if self.allow_manumatic else
(structs.CarState.GearShifter.drive,)
)
base_safe = (self.settings.enabled and CS.canValid and not CS.canTimeout and
not self._calibration_inhibit and not self._calibration_rearm_required and
not CS.steerFaultPermanent and not CS.accFaulted and
not any(e.type == structs.CarState.ButtonEvent.Type.cancel and e.pressed for e in CS.buttonEvents))
physical_safe = base_safe and CS.gearShifter in allowed_gears
if not main or not base_safe:
self._deferred_park_main = False
elif self.main_arm and self.allow_manumatic and not physical_safe:
if fresh_main or (self._previous_main is None and CS.gearShifter == structs.CarState.GearShifter.park):
self._deferred_park_main = True
if self.main_arm and (fresh_main or self._deferred_park_main) and physical_safe:
self._deferred_park_main = False
self._pending_main_ns = now_ns
self._pending_main_after_ns = self._main_observed_ns
self._pending_main_restriction_ns = 0
@@ -63,6 +82,7 @@ class SubaruStockCardIntent(AolCardIntent):
self._pending_main_ns = 0
if not main:
self.main_arm_ns = 0
self._deferred_park_main = False
self._record_latch_clear('subaru_main_off')
self.allowed_latch = False
self._withdraw_full_engagement()
@@ -102,14 +122,16 @@ def ordinary_axis_request_allowed(cp, state):
def create_intent(cp, settings):
main_arm = (cp.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) or
(cp.carFingerprint in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_OUTBACK_2023) and qualified(cp)))
return SubaruStockCardIntent(settings, main_arm=main_arm)
(cp.carFingerprint in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023) and qualified(cp)))
return SubaruStockCardIntent(settings, main_arm=main_arm,
allow_manumatic=(cp.carFingerprint == CAR.SUBARU_LEGACY_2025))
def sng_standstill_lateral_inhibit(cp, state):
# All stock Subaru native profiles require movement. Withdraw the request before its expected denial,
# preserving ordinary stock ACC without granting either active axis.
return bool(qualified(cp, marked_only=True) and state.standstill)
def sng_standstill_lateral_inhibit(cp, state, *, initial_wait: bool = False):
# All stock Subaru native profiles require movement (and Legacy 2025 waits for !brake_pressed before initial grant).
# Withdraw the request before its expected denial, preserving ordinary stock ACC without granting either axis.
legacy_brake_wait = bool(cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and initial_wait and state.brakePressed)
return bool(qualified(cp, marked_only=True) and (state.standstill or legacy_brake_wait))
def temporary_eps_brake_recovery(cp, state, *, previous_brake=False):
@@ -117,7 +139,7 @@ def temporary_eps_brake_recovery(cp, state, *, previous_brake=False):
not state.steerFaultPermanent and not state.accFaulted and not state.doorOpen and
not state.vehicleSensorsInvalid and not state.steeringDisengage and not state.buttonEvents and
state.cruiseState.available and not state.cruiseState.enabled and
state.gearShifter == structs.CarState.GearShifter.drive and
_drive_gear(cp, state) and
(state.brakePressed or previous_brake) and not state.regenBraking and not state.gasPressed)
@@ -127,7 +149,7 @@ def retain_braked_main_intent(feedback, sm, cp, state, axis, now_ns, *, arm_ns,
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
pending = feedback.subaru_braked_main
epoch = int(axis.intentIntegrityEpoch)
if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025) or not qualified(cp, marked_only=True) or
if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025) or not qualified(cp, marked_only=True) or
feedback.failed or feedback.paused or feedback.pending_event or arm_ns <= feedback.subaru_lateral_grant_ns or
not producer or axis.intentProducerSessionId != producer or
not 0 < arm_ns <= axis.sourceCarStateMonoTime <= now_ns or
@@ -137,7 +159,7 @@ def retain_braked_main_intent(feedback, sm, cp, state, axis, now_ns, *, arm_ns,
state.accFaulted or state.vehicleSensorsInvalid or state.doorOpen or state.seatbeltUnlatched or
state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or
not state.cruiseState.available or state.cruiseState.enabled or
state.gearShifter != structs.CarState.GearShifter.drive):
not _drive_gear(cp, state)):
return False
if pending is None:
if (not state.brakePressed or now_ns - arm_ns > SAFETY_MAX_AGE_NS or
@@ -170,7 +192,7 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro
from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity
previous = feedback.signature
if (cp.carFingerprint != CAR.SUBARU_IMPREZA_2020 or not qualified(cp, marked_only=True) or
if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_LEGACY_2025) or not qualified(cp, marked_only=True) or
not latched or not feedback.ever_lateral_active or feedback.failed or feedback.paused or
feedback.pending_event or feedback.retention_started_ns or feedback.source_retention_started_ns or
not feedback.session or cp_identity(cp) != feedback.cp or previous is None or signature != previous or
@@ -182,7 +204,7 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro
previous[2] - previous[8] > AXIS_MAX_AGE_NS or previous[4] != previous[2] + AXIS_MAX_AGE_NS or
not previous[4] < now_ns or now_ns - previous[8] > SAFETY_MAX_AGE_NS or
not state.canValid or state.canTimeout or not state.standstill or not state.brakePressed or
state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or
not _drive_gear(cp, state) or not state.cruiseState.available or
state.cruiseState.enabled or state.gasPressed or state.regenBraking or state.buttonEvents or
state.steerFaultTemporary or state.steerFaultPermanent or state.accFaulted or state.doorOpen or
state.seatbeltUnlatched or state.vehicleSensorsInvalid or state.steeringDisengage):
@@ -201,3 +223,17 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro
not (native.requestedLateral or native.lateralAllowed or native.requestedLongitudinal or native.longitudinalAllowed) and
native.observedMonoTime >= feedback.healthy_native_ns and feedback.healthy_inventory ==
(native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)))
def sync_legacy_card_lateral(card, cs, cc) -> None:
if (card.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and cs.cruiseState.available and
getattr(card.CI.CS, "_lkas_mode_settle_frames", 0) == 0):
card.CI.CS.lateral_off = not bool(cc.hudControl.lanesVisible)
def sync_legacy_card_aol(card) -> None:
cs = getattr(getattr(card, "CI", None), "CS", None)
if cs is not None and getattr(getattr(cs, "CP", None), "carFingerprint", None) == CAR.SUBARU_LEGACY_2025:
intent = getattr(card, "aol_card_intent", None)
settings = getattr(intent, "settings", None)
cs.aol_enabled = bool(settings.enabled) if settings is not None else bool(card.params.get_bool("AlwaysOnLateral"))
@@ -155,7 +155,9 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
not state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or
state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or state.cruiseState.enabled or
(state.gearShifter != structs.CarState.GearShifter.drive and
not (cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and state.gearShifter == structs.CarState.GearShifter.manumatic)) or
not state.cruiseState.available or state.cruiseState.enabled or
not 0 < feedback.healthy_feedback_ns <= now_ns or not feedback.healthy_inventory):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
@@ -220,7 +222,9 @@ def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, no
state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
state.steeringDisengage or state.buttonEvents or state.regenBraking or
state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or state.cruiseState.enabled):
(state.gearShifter != structs.CarState.GearShifter.drive and
not (cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and state.gearShifter == structs.CarState.GearShifter.manumatic)) or
not state.cruiseState.available or state.cruiseState.enabled):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
temporary = (log.OnroadEvent.EventName.steerTempUnavailable, log.OnroadEvent.EventName.steerTempUnavailableSilent)
@@ -70,6 +70,10 @@ def test_release_saved_choice_retained_without_avh_marker(tmp_path):
def test_original_source_clock_and_conflicting_duplicate():
from opendbc.car.subaru.avh import AvhSources, INPUTS, checksum
from opendbc.car.subaru.tests.test_avh import sample
batch_source = AvhSources()
batch_frames = [(a, sample(a, counter), 1) for counter in (1, 2) for a in INPUTS]
batch_source.observe([(10_020_000_000, batch_frames)], boot_ns=10_020_000_000, mono_ns=1_020_000_000)
assert not batch_source.blocked and batch_source.fresh(1.02)
for target in INPUTS:
source = AvhSources()
for counter in (1, 2):
@@ -190,8 +190,12 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub
if any(address == 0x322 for address, _, _ in outgoing):
dash = dash_decoder.vl['ES_LKAS_State']
expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
if candidate == 'SUBARU_LEGACY_2025':
assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if cs.cruiseState.available else 0)), (candidate, tick, expected, dash)
else:
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
assert all(accepted == (tick >= configure_delay) for address, _, _, accepted in tx if address == 0x322)
dash_emissions += 1
for address, data_hex, bus, accepted in tx:
@@ -236,9 +240,9 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub
assert bool(stop_start_emissions) == combined
assert dash_emissions >= 20
assert bool(startup_emissions) == enabled
assert len(startup_emissions) == (2 if enabled else 0)
assert len(startup_emissions) == (4 if enabled else 0)
if startup_emissions:
assert 45_000_000 <= startup_emissions[-1][0] - startup_emissions[0][0] <= 80_000_000
assert all(45_000_000 <= b[0] - a[0] <= 80_000_000 for a, b in zip(startup_emissions, startup_emissions[1:], strict=False))
earliest = 10_000_000_000 + configure_delay * 10_000_000
assert all(earliest <= stamp - base < earliest + 1_500_000_000 for stamp, _ in startup_emissions)
finally:
@@ -116,7 +116,206 @@ def test_outback_main_intent_uses_only_existing_exact_native_profiles():
assert qualified(cp, marked_only=True)
cp.safetyConfigs[0].safetyParam |= 2
assert not qualified(cp) and not create_intent(cp, owner().settings).main_arm
for candidate in (CAR.SUBARU_OUTBACK, CAR.SUBARU_LEGACY_2025):
cp = CarInterface.get_non_essential_params(candidate)
cp.alternativeExperience = 32
assert qualified(cp) and not create_intent(cp, owner().settings).main_arm
legacy = CarInterface.get_non_essential_params(CAR.SUBARU_LEGACY_2025)
legacy.alternativeExperience = 32
legacy_intent = create_intent(legacy, owner().settings)
assert qualified(legacy) and legacy_intent.main_arm and legacy_intent.allow_manumatic
legacy_cs = state()
legacy_cs.gearShifter = structs.CarState.GearShifter.manumatic
observe(legacy_intent, legacy_cs, 1_000_000, 1_000_000, False)
legacy_cs.cruiseState.available = True
observe(legacy_intent, legacy_cs, 10_000_000, 1_000_000, False)
observe(legacy_intent, legacy_cs, 20_000_000, 10_000_000, False)
assert legacy_intent.allowed_latch
# Pressing MAIN while still in Park, passing through Reverse, then shifting to Drive arms AOL.
park_intent = create_intent(legacy, owner().settings)
park_cs = state()
park_cs.gearShifter = structs.CarState.GearShifter.park
observe(park_intent, park_cs, 1_000_000, 1_000_000, False)
park_cs.cruiseState.available = True
observe(park_intent, park_cs, 10_000_000, 1_000_000, False)
assert not park_intent.allowed_latch
park_cs.gearShifter = structs.CarState.GearShifter.reverse
observe(park_intent, park_cs, 20_000_000, 10_000_000, False)
assert not park_intent.allowed_latch
park_cs.gearShifter = structs.CarState.GearShifter.drive
observe(park_intent, park_cs, 30_000_000, 20_000_000, False)
observe(park_intent, park_cs, 40_000_000, 30_000_000, False)
assert park_intent.allowed_latch
outback = CarInterface.get_non_essential_params(CAR.SUBARU_OUTBACK)
outback.alternativeExperience = 32
assert qualified(outback) and not create_intent(outback, owner().settings).main_arm
def test_legacy_2025_manumatic_and_aol_intent():
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.stock_aol import qualified
from opendbc.car.subaru.values import CAR
from openpilot.starpilot.aol.intent import independent_axis_requested
from openpilot.starpilot.car.events import unsupported_gear
from openpilot.starpilot.car.subaru.aol import create_intent
Gear = structs.CarState.GearShifter
ButtonEvent = structs.CarState.ButtonEvent
ButtonType = ButtonEvent.Type
assert Gear.manumatic in CarInterface.DRIVABLE_GEARS
legacy = CarInterface.get_non_essential_params(CAR.SUBARU_LEGACY_2025)
legacy.alternativeExperience = 32
outback_2023 = CarInterface.get_non_essential_params(CAR.SUBARU_OUTBACK_2023)
ascent_2023 = CarInterface.get_non_essential_params(CAR.SUBARU_ASCENT_2023)
assert not unsupported_gear(legacy, Gear.manumatic)
assert unsupported_gear(outback_2023, Gear.manumatic)
assert unsupported_gear(ascent_2023, Gear.manumatic)
aol_settings = AolSettings(True, 0., 0, 0, (0, 0, 0), (0, 0, 0))
disabled_settings = AolSettings(False, 0., 0, 0, (0, 0, 0), (0, 0, 0))
assert independent_axis_requested(aol_settings)
assert not independent_axis_requested(disabled_settings)
legacy_intent = create_intent(legacy, aol_settings)
assert qualified(legacy) and legacy_intent.main_arm and legacy_intent.allow_manumatic
legacy_cs = state()
legacy_cs.gearShifter = Gear.drive
observe(legacy_intent, legacy_cs, 1_000_000, 1_000_000, False)
legacy_cs.cruiseState.available = True
observe(legacy_intent, legacy_cs, 10_000_000, 1_000_000, False)
observe(legacy_intent, legacy_cs, 20_000_000, 10_000_000, False)
assert legacy_intent.allowed_latch
legacy_cs.gearShifter = Gear.manumatic
legacy_cs.buttonEvents = [
ButtonEvent.new_message(type=ButtonType.lkas, pressed=True),
ButtonEvent.new_message(type=ButtonType.lkas, pressed=False),
]
observe(legacy_intent, legacy_cs, 30_000_000, 20_000_000, False)
assert legacy_intent.allowed_latch
legacy_cs.buttonEvents = []
observe(legacy_intent, legacy_cs, 40_000_000, 30_000_000, False)
assert legacy_intent.allowed_latch
def test_legacy_2025_line_visibility_and_passive_dashcam_chimes():
import time
from openpilot.cereal import log, messaging
from openpilot.common.params import Params
from openpilot.selfdrive.controls.controlsd import _update_subaru_line_visibility
from openpilot.selfdrive.selfdrived.alertmanager import AlertManager
from openpilot.selfdrive.selfdrived.events import Events
from openpilot.selfdrive.selfdrived.selfdrived import SelfdriveD
from openpilot.starpilot.controllers.mode_actions import SwitchbackCooldown
vis, timer = _update_subaru_line_visibility(None, 0.0, 0.55, 0.01)
assert vis and timer == 0.0
vis, timer = _update_subaru_line_visibility(vis, timer, 0.42, 0.01)
assert vis and timer == 0.0
for _ in range(24):
vis, timer = _update_subaru_line_visibility(vis, timer, 0.35, 0.01)
assert vis
vis, timer = _update_subaru_line_visibility(vis, timer, 0.35, 0.01)
assert not vis
for _ in range(99):
vis, timer = _update_subaru_line_visibility(vis, timer, 0.56, 0.01)
assert not vis
vis, timer = _update_subaru_line_visibility(vis, timer, 0.56, 0.01)
assert vis
now = time.monotonic_ns()
names = ('deviceState', 'carControl', 'longitudinalPlan', 'starpilotLongitudinalPlan', 'modelV2', 'slcState')
data = {name: getattr(messaging.new_message(name), name) for name in names}
data['carControl'].hudControl.lanesVisible = True
class _Sm:
def __init__(self):
self.frame = 1
self.seen = dict.fromkeys(names, True)
self.valid = dict.fromkeys(names, True)
self.alive = dict.fromkeys(names, True)
self.logMonoTime = dict.fromkeys(names, now)
self.recv_time = dict.fromkeys(names, now / 1e9)
def __getitem__(self, key):
return data[key]
drive = SelfdriveD.__new__(SelfdriveD)
drive.CP = structs.CarParams(carFingerprint="SUBARU_LEGACY_2025", passive=True)
drive.enabled = False
drive.personality = log.LongitudinalPersonality.standard
drive.is_metric = False
drive.events = Events()
drive.AM = AlertManager()
drive.params = Params()
drive.switchback_capable = False
drive.switchback_setting_ns = now
drive.switchback_cooldown_ns = 0
drive.switchback_cooldown = SwitchbackCooldown()
drive.aol_axis_decision = None
drive.aol_fault_reason = 'none'
drive.radar_recovery_enabled = False
drive.legacy_2025_green_wheel_active = True
vars(drive)['state_machine'] = SimpleNamespace(current_alert_types=[], soft_disable_timer=0)
vars(drive)['sm'] = _Sm()
cs = structs.CarState(canValid=True, canTimeout=False)
cs.cruiseState.available = True
drive.update_alerts(cs)
assert not drive.legacy_2025_green_wheel_active
assert drive.AM.current_alert.alert_type == ""
drive.CP.passive = False
drive.sm.frame += 1
drive.update_alerts(cs)
assert drive.legacy_2025_green_wheel_active
assert drive.AM.current_alert.alert_type == "legacy2025AolEngage/enable"
def test_legacy_2025_manumatic_driver_monitoring_isolation(tmp_path):
from unittest.mock import patch
from openpilot.cereal import messaging
from openpilot.common.params import Params
from openpilot.selfdrive.monitoring.dmonitoringd import _read_allow_manumatic
from openpilot.selfdrive.monitoring.policy import DriverMonitoring
params = Params(str(tmp_path))
assert _read_allow_manumatic(params) is None
for fingerprint, expected in (("SUBARU_OUTBACK_2023", False), ("SUBARU_LEGACY_2025", True)):
params.put("CarParams", structs.CarParams(carFingerprint=fingerprint).to_bytes(), block=True)
assert _read_allow_manumatic(params) is expected
car_state = structs.CarState(vEgo=10.0, gearShifter=structs.CarState.GearShifter.manumatic)
selfdrive_state = messaging.new_message('selfdriveState').selfdriveState
model_v2 = messaging.new_message('modelV2').modelV2
model_v2.meta.disengagePredictions.brakeDisengageProbs = [0.0]
extrinsics = messaging.new_message('extrinsicsCalibration').extrinsicsCalibration
extrinsics.rpyCalib = [0.0, 0.0, 0.0]
driver_state = messaging.new_message('driverStateV2').driverStateV2
driver_state.leftDriverData.faceOrientation = [0.0, 0.0, 0.0]
driver_state.leftDriverData.facePosition = [0.0, 0.0]
driver_state.leftDriverData.faceOrientationStd = [0.0, 0.0]
driver_state.leftDriverData.facePositionStd = [0.0, 0.0]
sm = {
'carState': car_state,
'selfdriveState': selfdrive_state,
'modelV2': model_v2,
'extrinsicsCalibration': extrinsics,
'driverStateV2': driver_state,
}
with patch('openpilot.selfdrive.monitoring.policy.Params', return_value=params):
default_dm = DriverMonitoring(always_on=True)
default_dm.awareness = 0.8
default_dm.run_step(sm)
assert default_dm.awareness == 1.0
legacy_dm = DriverMonitoring(always_on=True, allow_manumatic=True)
legacy_dm.run_step(sm)
car_state.gearShifter = structs.CarState.GearShifter.drive
drive_dm = DriverMonitoring(always_on=True, allow_manumatic=True)
drive_dm.run_step(sm)
assert legacy_dm.awareness == drive_dm.awareness < 1.0
@@ -142,6 +142,16 @@ def test_sng_standstill_request_withdrawal_is_exact_and_does_not_grant_axis():
assert sng_standstill_lateral_inhibit(cp, stopped)
stopped.standstill = False
assert not sng_standstill_lateral_inhibit(cp, stopped)
# Non-Legacy Subarus keep upstream standstill-only inhibit even with initial_wait=True.
stopped.brakePressed = True
assert not sng_standstill_lateral_inhibit(cp, stopped, initial_wait=True)
# Legacy 2025 rolling with foot lightly on brake waits before Panda's initial !brake_pressed grant, then releases once brake lifts.
legacy_cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, gen_empty_fingerprint(), [], False, False, False)
legacy_cp.alternativeExperience = 32
assert sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=True)
assert not sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=False)
stopped.brakePressed = False
assert not sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=True)
cp.openpilotLongitudinalControl = True
stopped.standstill = True
assert not sng_standstill_lateral_inhibit(cp, stopped)
@@ -334,8 +334,18 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if any(address == 0x322 for address, _, _ in outgoing):
dash = dash_decoder.vl['ES_LKAS_State']
expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
if candidate == 'SUBARU_LEGACY_2025':
assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash)
if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent:
assert not ci.CC.aol_dash_green_last, (candidate, tick, dash)
if expected:
assert ci.CC.aol_dash_green_last, (candidate, tick, dash)
ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True))
expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0)
assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash)
else:
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
assert all(accepted for address, _, _, accepted in tx if address == 0x322)
dash_emissions += 1
decoded_steering = []
@@ -445,7 +455,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0), row
if 240 <= tick < 255:
assert not command.latActive and bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0, row
main_rearm = aol and candidate in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_OUTBACK_2023)
main_rearm = aol and candidate in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_IMPREZA_2020,
CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023)
if 330 <= tick < (350 if main_rearm else 400):
assert not command.latActive and not bool(intent and intent.allowedLatch), row
if rearm_on_brake and 355 <= tick < 365:
@@ -698,7 +709,7 @@ def test_actual_subaru_eps_clear_during_blinker_pause_keeps_armed_intent(
subaru_native_pair, tmp_path, recovery, axis_first, candidate=CAR.SUBARU_IMPREZA_2020):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
candidate, subaru_native_pair, tmp_path, main_only=candidate in (
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_OUTBACK_2023),
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023),
eps_clear_join=recovery, eps_clear_axis_first=axis_first,
preferences={'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.})
@@ -724,7 +735,7 @@ def test_actual_subaru_stop_creep_restriction_preserves_armed_intent(
subaru_native_pair, tmp_path, restriction, cold_stop, candidate=CAR.SUBARU_IMPREZA_2020):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
candidate, subaru_native_pair, tmp_path, main_only=candidate in (
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_OUTBACK_2023),
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023),
stop_resume=True, hard_stop_native_first=not cold_stop, stop_creep_eps=restriction, cold_stop=cold_stop)
rows = json.loads((tmp_path / (str(candidate) + '-True-actual.json')).read_text())
assert any(row['cardLatch'] and row['armed'] and not row['lat'] and row['permission'] == 0 for row in rows if 135 <= row['tick'] < 137)
@@ -175,8 +175,12 @@ def test_actual_startup_factory_card_controls_native(enabled, manual, aol, subar
if any(address == 0x322 for address, _, _ in outgoing):
dash = dash_decoder.vl['ES_LKAS_State']
expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
if candidate == 'SUBARU_LEGACY_2025':
assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if cs.cruiseState.available else 0)), (candidate, tick, expected, dash)
else:
assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash)
assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash)
assert all(accepted == (tick >= configure_delay) for address, _, _, accepted in tx if address == 0x322)
dash_emissions += 1
for address, data_hex, bus, accepted in tx:
@@ -148,6 +148,7 @@ DESCRIPTIONS = {
'KeepScreenOnGpuLoading': 'Keeps the driving screen visible while an eGPU model loads. Manual Screen Off still works.',
'TurnOffCommaScreen': 'Pauses comma UI rendering to reduce CPU and GPU use. Tap once to wake the screen.',
'LoudBlindspotAlert': 'Uses the soft-warning sound when a lane change is blocked by a detected blind-spot vehicle.',
'LoudBlindspotAlertMuteAtStandstill': 'Mutes Blindspot Alert While Lateral Is Off when stopped or moving below 1 mph.',
'LoudBlindspotAlertWhenDisengaged': ('Warns when signaling toward a detected blind-spot vehicle with steering assistance off or paused. ' +
'Independent of Loud Blindspot Alert. Hazards do not trigger it.'),
'SoundPack': 'Chooses the sounds used for driving alerts and chimes.',
@@ -65,6 +65,7 @@
"LongPitch",
"LowSpeedCruiseOnSet",
"LoudBlindspotAlert",
"LoudBlindspotAlertMuteAtStandstill",
"LoudBlindspotAlertWhenDisengaged",
"NostalgiaMode",
"PIPPreviewEnabled",
@@ -101,7 +101,7 @@ def _plan_positions_are_finite(model_v2) -> bool:
return False
def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float) -> float:
def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float, min_reach: float = TWITCH_GUARD_MIN_REACH) -> float:
if not (math.isfinite(curvature) and math.isfinite(v_ego)):
return curvature
if v_ego >= TWITCH_GUARD_MAX_SPEED or curvature == 0.0:
@@ -109,9 +109,9 @@ def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float) -> float:
if not _plan_positions_are_finite(model_v2):
return curvature
reach = get_plan_reach(model_v2)
if not math.isfinite(reach) or reach < TWITCH_GUARD_MIN_REACH:
if not math.isfinite(reach) or reach < min_reach:
return curvature
plan = abs(_plan_circle_curvature(model_v2.position.x, model_v2.position.y, CURVATURE_HOLD_PLAN_LOOKAHEAD_FAR))
plan = abs(_plan_circle_curvature(model_v2.position.x, model_v2.position.y, min(CURVATURE_HOLD_PLAN_LOOKAHEAD_FAR, reach)))
if not math.isfinite(plan):
return curvature
straightness = (plan - TWITCH_GUARD_STRAIGHT_LO) / (TWITCH_GUARD_STRAIGHT_HI - TWITCH_GUARD_STRAIGHT_LO)
@@ -2,7 +2,7 @@ import unittest
from types import SimpleNamespace
from openpilot.starpilot.lateral.model_turn_assist import (
STOP_HOLD_MAX_SPEED, TWITCH_GUARD_FLOOR, TWITCH_GUARD_MAX_SPEED, ModelTurnAssist, update_twitch_guard,
STOP_HOLD_MAX_SPEED, TWITCH_GUARD_FLOOR, TWITCH_GUARD_MAX_SPEED, ModelTurnAssist, limit_curvature_to_plan, update_twitch_guard,
)
STRAIGHT = SimpleNamespace(position=SimpleNamespace(x=[0., 1., 2., 3.], y=[0., 0., 0., 0.]),
@@ -124,6 +124,12 @@ class TestTwitchGuardArming(unittest.TestCase):
self.assertFalse(assist.twitch_guard_armed)
self.assertEqual(step(assist, 2.0, 0., .012, model=LONG_STRAIGHT), .012)
def test_short_straight_plan_down_to_4m_is_guarded(self):
short_straight = SimpleNamespace(position=SimpleNamespace(x=[0., 1., 2., 3., 4., 5.], y=[0.] * 6),
meta=SimpleNamespace(laneChangeState=0))
self.assertEqual(limit_curvature_to_plan(short_straight, .012, 1.0), .012)
self.assertEqual(limit_curvature_to_plan(short_straight, .012, 1.0, min_reach=4.0), TWITCH_GUARD_FLOOR)
if __name__ == '__main__':
unittest.main()
+24 -5
View File
@@ -687,7 +687,11 @@ class RuntimeSnapshotAdapter:
display_message(sm, "carOutput", now_ns, after_frame=after) if started else None,
display_message(sm, "vehicleParameters", now_ns, after_frame=after) if started else None, cp,
)
display_lat_active = bool(display_control.latActive) if display_control is not None else False
legacy_2025_lateral_off = bool(
cp is not None and getattr(cp, 'carFingerprint', '') == 'SUBARU_LEGACY_2025' and
display_control is not None and not getattr(getattr(display_control, 'hudControl', None), 'lanesVisible', True)
)
display_lat_active = bool(display_control.latActive) if (display_control is not None and not legacy_2025_lateral_off) else False
display_long_active = bool(display_control.longActive) if display_control is not None else False
long_engaged = bool(display_selfdrive is not None and getattr(display_selfdrive, 'enabled', False))
if getattr(ui, 'aol_runtime', False):
@@ -742,10 +746,25 @@ class RuntimeSnapshotAdapter:
weather_location = (fix[1].latitude, fix[1].longitude)
break
aol_latched = (display_aol_latch(sm, now_ns, after_frame=after)
if started and getattr(ui, "aol_runtime", False) else None)
armed_at_stop = bool(aol_latched and cp is not None and getattr(cp, 'brand', '') == 'subaru' and display_car_valid and
display_car.standstill and str(display_car.gearShifter) == 'drive' and
not display_car.steerFaultTemporary and not display_car.steerFaultPermanent and not display_car.accFaulted)
if started and getattr(ui, "aol_runtime", False) and not legacy_2025_lateral_off else None)
if cp is not None and getattr(cp, 'carFingerprint', '') == 'SUBARU_LEGACY_2025':
armed_at_stop = False
if (aol_latched and display_car_valid and
str(getattr(display_car, 'gearShifter', '')) in ('drive', 'manumatic') and
not getattr(display_car, 'steerFaultTemporary', False) and
not getattr(display_car, 'steerFaultPermanent', False) and
not getattr(display_car, 'accFaulted', False)):
min_steer_speed = max(float(getattr(cp, 'minSteerSpeed', 0.0) or 0.0), 0.3)
raw_v = getattr(display_car, 'vEgo', None)
car_speed = _finite(abs(float(raw_v))) if raw_v is not None else None
armed_at_stop = bool(
getattr(display_car, 'standstill', False) or
(car_speed is not None and car_speed <= min_steer_speed)
)
else:
armed_at_stop = bool(aol_latched and cp is not None and getattr(cp, 'brand', '') == 'subaru' and display_car_valid and
display_car.standstill and str(display_car.gearShifter) == 'drive' and
not display_car.steerFaultTemporary and not display_car.steerFaultPermanent and not display_car.accFaulted)
drive_mode_source = display_message(sm, 'starpilotCarState', now_ns, after_frame=after) if started else None
alert = self._drive_mode_notice.update(
drive_mode_source, display_car, cp=cp, drive_frame=after,
+10 -1
View File
@@ -61,16 +61,21 @@ class SoundsOwner:
rows.append(FeatureRow(AUTO_PREFIX + key, "Use Auto " + label, "Follow ambient sound", source=saved.raw,
available=parked and saved.readable, repair_value="Auto"))
rows.append(pack_row)
without_lateral_raw, without_lateral_readable = read_saved(self.params, BLINDSPOT_KEYS[1], 8)
without_lateral_on = without_lateral_readable and without_lateral_raw == b"1"
for key, label, reason in (*DEPARTURE_TOGGLES,
(BLINDSPOT_KEYS[0], "Loud Blindspot Alert", "Uses the soft-warning sound when a lane change is blocked by a detected blind-spot vehicle."),
(BLINDSPOT_KEYS[1], "Blindspot Alert While Lateral Is Off",
"Warns when signaling toward a detected blind-spot vehicle with steering assistance off or paused. "
+ "Independent of Loud Blindspot Alert. Hazards do not trigger it."),
(BLINDSPOT_KEYS[2], "Mute Blindspot Alert at Standstill",
"Mutes Blindspot Alert While Lateral Is Off when stopped or moving below 1 mph."),
):
raw, readable = read_saved(self.params, key, 8)
valid = readable and raw in (None, b"0", b"1")
row_available = parked and valid and (without_lateral_on if key == BLINDSPOT_KEYS[2] else True)
rows.append(FeatureRow(key, label, ("On" if raw == b"1" else "Off") if valid else "Invalid saved value",
raw, ("Off", "On") if valid else (), available=parked and valid,
raw, ("Off", "On") if valid else (), available=row_available,
reason=reason, default_value="Off"))
defaults = dict.fromkeys(SPECS, 'Auto')
defaults['SoundPack'] = PACK_LABELS.get(DEFAULT_PACK, DEFAULT_PACK)
@@ -83,6 +88,10 @@ class SoundsOwner:
if request.key in (*BLINDSPOT_KEYS, *DEPARTURE_KEYS):
if request.value not in ("Off", "On") or request.expected not in (None, b"0", b"1"):
return False
if request.key == BLINDSPOT_KEYS[2] and request.value == "On":
without_raw, without_readable = read_saved(self.params, BLINDSPOT_KEYS[1], 8)
if not (without_readable and without_raw == b"1"):
return False
result = commit_exact(self.params, key=request.key, max_bytes=8,
raw=b"1" if request.value == "On" else b"0", expected=request.expected,
authorized=self.parked, temp_prefix=".optional-alert-")
@@ -99,6 +99,37 @@ class TestOnroadAxes(unittest.TestCase):
self.publish_latch(False)
self.assertFalse(self.state(False, False).aol_armed_at_stop)
def test_legacy_2025_armed_stop_covers_creep_threshold_and_manumatic(self):
self.ui.aol_runtime = True
self.ui.CP.brand = 'subaru'
self.ui.CP.carFingerprint = 'SUBARU_LEGACY_2025'
self.ui.CP.minSteerSpeed = 0.0
car = self.ui.sm['carState']
car.steerFaultTemporary = car.steerFaultPermanent = car.accFaulted = False
self.publish_latch()
for gear in ('drive', 'manumatic'):
car.gearShifter = gear
car.standstill = False
for speed, expected_stop in ((0.0, True), (0.2, True), (0.3, True), (0.35, False)):
car.vEgo = speed
with self.subTest(gear=gear, speed=speed):
st = self.state(False, False)
self.assertEqual(st.aol_armed_at_stop, expected_stop)
expected_color = (10, 100, 98, 255) if expected_stop else (18, 40, 57, 255)
self.assertEqual(rgba(axis_status_color(st)), expected_color)
self.ui.CP.carFingerprint = 'SUBARU_OUTBACK_2023'
for gear, standstill, speed, expected_stop in (
('drive', False, 0.2, False),
('manumatic', True, 0.0, False),
('drive', True, 0.0, True),
):
car.gearShifter = gear
car.standstill = standstill
car.vEgo = speed
with self.subTest(car='SUBARU_OUTBACK_2023', gear=gear, standstill=standstill, speed=speed):
self.assertEqual(self.state(False, False).aol_armed_at_stop, expected_stop)
def test_missing_model_cannot_show_armed_aol_as_active_steering(self):
self.ui.aol_runtime = True
self.publish_latch()
@@ -49,7 +49,7 @@ class SoundsSettingsTests(unittest.TestCase):
def test_absence_auto_no_writes_and_native_registry(self):
state = self.owner.snapshot()
self.assertEqual(len(state.rows), 12)
self.assertEqual(len(state.rows), 13)
for key, _, _ in VOLUMES:
self.assertEqual(self.row(key).value, "Auto")
self.assertEqual((self.row(key).step, self.row(key).maximum, self.row(key).unit), (5.0, 100.0, "%"))
@@ -264,7 +264,7 @@ class SoundsSettingsTests(unittest.TestCase):
session.sounds_scroll = 5
state = replace(session.sounds_snapshot(), scroll=5)
self.assertEqual(state.page, "sounds:overview")
self.assertEqual(len(state.rows), 12)
self.assertEqual(len(state.rows), 13)
self.assertTrue(all(value_buttons(state, row) == () for row in state.rows))
self.assertEqual(next(row for row in state.rows if row.key == "EngageVolume").value, "40")
received = []