IQ.Pilot Prebuilt Release @ 27f668a

This commit is contained in:
IQ.Lvbs CI [bot]
2026-09-03 18:23:24 -05:00
commit b073c5182b
2554 changed files with 679696 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
{% set footnote_tag = '[<sup>{}</sup>](#footnotes)' %}
{% set star_icon = '[![star](assets/icon-star-{}.svg)](##)' %}
{% set video_icon = '<a href="{}" target="_blank"><img height="18px" src="assets/icon-youtube.svg"></img></a>' %}
{# Force hardware column wider by using a blank image with max width. #}
{% set width_tag = '<a href="##"><img width=2000></a>%s<br>&nbsp;' %}
{% set hardware_col_name = 'Hardware Needed' %}
{% set wide_hardware_col_name = width_tag|format(hardware_col_name) -%}
<!--- AUTOGENERATED FROM selfdrive/car/CARS_template.md, DO NOT EDIT. --->
# Supported Cars
A supported vehicle is one that just works when you install a comma device. All supported cars provide a better experience than any stock system. Supported vehicles reference the US market unless otherwise specified.
# {{all_car_docs | selectattr('support_type', 'eq', SupportType.UPSTREAM) | list | length}} Supported Cars
|{{Column | map(attribute='value') | join('|') | replace(hardware_col_name, wide_hardware_col_name)}}|
|---|---|---|{% for _ in range((Column | length) - 3) %}{{':---:|'}}{% endfor +%}
{% for car_docs in all_car_docs | selectattr('support_type', 'eq', SupportType.UPSTREAM) %}
|{% for column in Column %}{{car_docs.get_column(column, star_icon, video_icon, footnote_tag)}}|{% endfor %}
{% endfor %}
### Footnotes
{% for footnote in footnotes %}
<sup>{{loop.index}}</sup>{{footnote | replace('</br>', '')}} <br />
{% endfor %}
## Community Maintained Cars
Although they're not upstream, the community has openpilot running on other makes and models. See the 'Community Supported Models' section of each make [on our wiki](https://wiki.comma.ai/).
# Don't see your car here?
**openpilot can support many more cars than it currently does.** There are a few reasons your car may not be supported.
If your car doesn't fit into any of the incompatibility criteria here, then there's a good chance it can be supported! We're adding support for new cars all the time. **We don't have a roadmap for car support**, and in fact, most car support comes from users like you!
### Which cars are able to be supported?
openpilot uses the existing steering, gas, and brake interfaces in your car. If your car lacks any one of these interfaces, openpilot will not be able to control the car. If your car has [ACC](https://en.wikipedia.org/wiki/Adaptive_cruise_control) and any form of [LKAS](https://en.wikipedia.org/wiki/Automated_Lane_Keeping_Systems)/[LCA](https://en.wikipedia.org/wiki/Lane_centering), then it almost certainly has these interfaces. These features generally started shipping on cars around 2016. Note that manufacturers will often make their own [marketing terms](https://en.wikipedia.org/wiki/Adaptive_cruise_control#Vehicle_models_supporting_adaptive_cruise_control) for these features, such as Hyundai's "Smart Cruise Control" branding of Adaptive Cruise Control.
If your car has the following packages or features, then it's a good candidate for support.
| Make | Required Package/Features |
| ---- | ------------------------- |
| Acura | Any car with AcuraWatch will work. AcuraWatch comes standard on many newer models. |
| Ford | Any car with Lane Centering will likely work. |
| Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. |
| Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. |
| Nissan | Any car with ProPILOT will likely work. |
| Toyota & Lexus | Any car that has Toyota/Lexus Safety Sense with "Lane Departure Alert with Steering Assist (LDA w/SA)" and/or "Lane Tracing Assist (LTA)" will work. Note that LDA without Steering Assist will not work. These features come standard on most newer models. |
| Hyundai, Kia, & Genesis | Any car with Smart Cruise Control (SCC) and Lane Following Assist (LFA) or Lane Keeping Assist (LKAS) will work. LKAS/LFA comes standard on most newer models. Any form of SCC will work, such as NSCC. |
| Chrysler, Jeep, & Ram | Any car with LaneSense and Adaptive Cruise Control will likely work. These come standard on many newer models. |
### FlexRay
All the cars that openpilot supports use a [CAN bus](https://en.wikipedia.org/wiki/CAN_bus) for communication between all the car's computers, however a CAN bus isn't the only way that the computers in your car can communicate. Most, if not all, vehicles from the following manufacturers use [FlexRay](https://en.wikipedia.org/wiki/FlexRay) instead of a CAN bus: **BMW, Mercedes, Audi, Land Rover, and some Volvo**. These cars may one day be supported, but we have no immediate plans to support FlexRay.
### Toyota Security
openpilot does not yet support these Toyota models due to a new message authentication method.
[Vote](https://comma.ai/shop#toyota-security) if you'd like to see openpilot support on these models.
* Toyota RAV4 Prime 2021+
* Toyota Sienna 2021+
* Toyota Venza 2021+
* Toyota Sequoia 2023+
* Toyota Tundra 2022+
* Toyota Highlander 2024+
* Toyota Corolla Cross 2022+ (only US model)
* Toyota Camry 2025+
* Lexus NX 2022+
* Toyota bZ4x 2023+
* Subaru Solterra 2023+

View File

View File

@@ -0,0 +1,189 @@
from iqpilot.cereal import car, log
from iqdbc.car import DT_CTRL, structs
from iqdbc.car.car_helpers import interfaces
from iqdbc.car.interfaces import MAX_CTRL_SPEED
from iqdbc.car.toyota.values import ToyotaFlags
from iqpilot.selfdrive.selfdrived.events import Events
ButtonType = structs.CarState.ButtonEvent.Type
GearShifter = structs.CarState.GearShifter
EventName = log.OnroadEvent.EventName
NetworkLocation = structs.CarParams.NetworkLocation
class CarSpecificEvents:
def __init__(self, CP: structs.CarParams):
self.CP = CP
self.steering_unpressed = 0
self.low_speed_alert = False
self.no_steer_warning = False
self.silent_steer_warning = True
def update(self, CS: car.CarState, CS_prev: car.CarState, CC: car.CarControl):
if self.CP.brand in ('body', 'mock'):
return Events()
events = self.create_common_events(CS, CS_prev)
if self.CP.brand == 'chrysler':
# Low speed steer alert hysteresis logic
if self.CP.minSteerSpeed > 0. and CS.vEgo < (self.CP.minSteerSpeed + 0.5):
self.low_speed_alert = True
elif CS.vEgo > (self.CP.minSteerSpeed + 1.):
self.low_speed_alert = False
if self.low_speed_alert:
events.add(EventName.belowSteerSpeed)
elif self.CP.brand == 'honda':
if self.CP.pcmCruise and CS.vEgo < self.CP.minEnableSpeed:
events.add(EventName.belowEngageSpeed)
if self.CP.pcmCruise:
# we engage when pcm is active (rising edge)
if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled:
events.add(EventName.pcmEnable)
elif not CS.cruiseState.enabled and (CC.actuators.accel >= 0. or not self.CP.openpilotLongitudinalControl):
# it can happen that car cruise disables while comma system is enabled: need to
# keep braking if needed or if the speed is very low
if CS.vEgo < self.CP.minEnableSpeed + 2.:
# non loud alert if cruise disables below 25mph as expected (+ a little margin)
events.add(EventName.speedTooLow)
else:
events.add(EventName.cruiseDisabled)
if self.CP.minEnableSpeed > 0 and CS.vEgo < 0.001:
events.add(EventName.manualRestart)
elif self.CP.brand == 'toyota':
# TODO: when we check for unexpected disengagement, check gear not S1, S2, S3
if self.CP.openpilotLongitudinalControl:
# Only can leave standstill when planner wants to move
if CS.cruiseState.standstill and not CS.brakePressed and (CC.cruiseControl.resume or self.CP.flags & ToyotaFlags.HYBRID.value):
events.add(EventName.resumeRequired)
if CS.vEgo < self.CP.minEnableSpeed:
events.add(EventName.belowEngageSpeed)
if CC.actuators.accel > 0.3:
# some margin on the actuator to not false trigger cancellation while stopping
events.add(EventName.speedTooLow)
if CS.vEgo < 0.001:
# while in standstill, send a user alert
events.add(EventName.manualRestart)
elif self.CP.brand == 'gm':
# Enabling at a standstill with brake is allowed
# TODO: verify 17 Volt can enable for the first time at a stop and allow for all GMs
if CS.vEgo < self.CP.minEnableSpeed and not (CS.standstill and CS.brake >= 20 and
self.CP.networkLocation == NetworkLocation.fwdCamera):
events.add(EventName.belowEngageSpeed)
if CS.cruiseState.standstill:
events.add(EventName.resumeRequired)
elif self.CP.brand == 'volkswagen':
if self.CP.openpilotLongitudinalControl:
if CS.vEgo < self.CP.minEnableSpeed + 0.5:
events.add(EventName.belowEngageSpeed)
if CC.enabled and CS.vEgo < self.CP.minEnableSpeed:
events.add(EventName.speedTooLow)
# TODO: this needs to be implemented generically in carState struct
# if CC.eps_timer_soft_disable_alert:
# events.add(EventName.steerTimeLimit)
return events
def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState):
events = Events()
CI = interfaces[self.CP.carFingerprint]
# TODO: cleanup the honda-specific logic
pcm_enable = self.CP.pcmCruise and self.CP.brand != 'honda'
# TODO: on some hyundai cars, the cancel button is also the pause/resume button,
# so only use it for cancel when running openpilot longitudinal
allow_button_cancel = self.CP.brand != 'hyundai'
if CS.doorOpen:
events.add(EventName.doorOpen)
if CS.seatbeltUnlatched:
events.add(EventName.seatbeltNotLatched)
if CS.gearShifter != GearShifter.drive and CS.gearShifter not in CI.DRIVABLE_GEARS:
events.add(EventName.wrongGear)
if CS.gearShifter == GearShifter.reverse:
events.add(EventName.reverseGear)
if not CS.cruiseState.available and not getattr(CS, 'cruiseFaultLateralMode', False):
events.add(EventName.wrongCarMode)
if CS.espDisabled:
events.add(EventName.espDisabled)
if CS.espActive:
events.add(EventName.espActive)
if CS.stockFcw:
events.add(EventName.stockFcw)
if CS.stockAeb:
events.add(EventName.stockAeb)
if CS.stockLkas:
events.add(EventName.stockLkas)
if CS.vEgo > MAX_CTRL_SPEED:
events.add(EventName.speedTooHigh)
if CS.cruiseState.nonAdaptive:
events.add(EventName.wrongCruiseMode)
if CS.brakeHoldActive and self.CP.openpilotLongitudinalControl:
events.add(EventName.brakeHold)
if CS.parkingBrake:
events.add(EventName.parkBrake)
if getattr(CS, 'cruiseFaultLateralMode', False):
events.add(EventName.cruiseFaultLateralAllowed)
elif CS.accFaulted:
events.add(EventName.accFaulted)
if CS.steeringPressed:
events.add(EventName.steerOverride)
if CS.steeringDisengage and not CS_prev.steeringDisengage:
events.add(EventName.steerDisengage)
if CS.brakePressed and CS.standstill:
events.add(EventName.preEnableStandstill)
if CS.gasPressed:
events.add(EventName.gasPressedOverride)
if CS.vehicleSensorsInvalid:
events.add(EventName.vehicleSensorsInvalid)
if CS.invalidLkasSetting:
events.add(EventName.invalidLkasSetting)
if CS.lowSpeedAlert:
events.add(EventName.belowSteerSpeed)
if CS.buttonEnable:
events.add(EventName.buttonEnable)
# Handle cancel button presses
for b in CS.buttonEvents:
# Disable on rising and falling edge of cancel for both stock and OP long
# TODO: only check the cancel button with openpilot longitudinal on all brands to match panda safety
if b.type == ButtonType.cancel and (allow_button_cancel or not self.CP.pcmCruise):
events.add(EventName.buttonCancel)
# Handle permanent and temporary steering faults
self.steering_unpressed = 0 if CS.steeringPressed else self.steering_unpressed + 1
if CS.steerFaultTemporary:
if CS.steeringPressed and (not CS_prev.steerFaultTemporary or self.no_steer_warning):
self.no_steer_warning = True
else:
self.no_steer_warning = False
# if the user overrode recently, show a less harsh alert
if self.silent_steer_warning or CS.standstill or self.steering_unpressed < int(1.5 / DT_CTRL):
self.silent_steer_warning = True
events.add(EventName.steerTempUnavailableSilent)
else:
events.add(EventName.steerTempUnavailable)
else:
self.no_steer_warning = False
self.silent_steer_warning = False
if CS.steerFaultPermanent:
events.add(EventName.steerUnavailable)
# we engage when pcm is active (rising edge)
# enabling can optionally be blocked by the car interface
if pcm_enable:
if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled and not CS.blockPcmEnable:
events.add(EventName.pcmEnable)
elif not CS.cruiseState.enabled and not getattr(CS, 'cruiseFaultLateralMode', False):
events.add(EventName.pcmDisable)
return events

585
iqpilot/selfdrive/car/card.py Executable file
View File

@@ -0,0 +1,585 @@
#!/usr/bin/env python3
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
import json
import math
import os
import time
import threading
import iqpilot.cereal.messaging as messaging
from iqpilot.cereal import car, log, custom
from iqpilot.common.iq_perf import PerfSample, PerfTraceEmitter, PerfTraceRing
from iqpilot.common.params import Params, UnknownKeyName
from iqpilot.common.realtime import config_background_thread, config_realtime_process, lock_memory, Priority, Ratekeeper
from iqpilot.common.swaglog import cloudlog, ForwardingHandler
from iqdbc.car import DT_CTRL, structs
from iqdbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
from iqdbc.car.carlog import carlog
from iqdbc.car.fw_versions import ObdCallback
from iqdbc.car.car_helpers import get_car, interfaces
from iqdbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase
from iqpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
from iqpilot.selfdrive.car.cruise import VCruiseHelper
from iqpilot.selfdrive.car.helpers import convert_iq_car_control_compact, convert_to_capnp
from iqpilot.sab.behavior import apply_aol_experience_flags, apply_aol_brand_overrides
from iqpilot.selfdrive.car import interfaces as iqpilot_interfaces
REPLAY = "REPLAY" in os.environ
EventName = log.OnroadEvent.EventName
CARD_FLAG_FALLBACK_ACTIVE = 1 << 0
CARD_FLAG_CARSTATE_ALIVE = 1 << 1
CARD_FLAG_SENDCAN_GAP = 1 << 2
CARD_SENDCAN_GAP_WARN_US = 20_000
CARD_SENDCAN_GAP_ERROR_US = 60_000
# forward
carlog.addHandler(ForwardingHandler(cloudlog))
def obd_callback(params: Params) -> ObdCallback:
def set_obd_multiplexing(obd_multiplexing: bool):
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
params.remove("ObdMultiplexingChanged")
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing)
params.get_bool("ObdMultiplexingChanged", block=True)
cloudlog.warning("OBD multiplexing set successfully")
return set_obd_multiplexing
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
"""
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
Returns: CAN packets comprised of CanData objects for easy access
"""
ret = []
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
ret.append([CanData(msg.address, msg.dat, msg.src) for msg in can.can])
return ret
def can_send(msgs: list[CanData]) -> None:
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
return can_recv, can_send
def run_optional_pre_init(CI: CarInterfaceBase, CP: structs.CarParams, CP_IQ: structs.IQCarParams,
can_callbacks: tuple[CanRecvCallable, CanSendCallable]) -> None:
pre_init = getattr(CI, "pre_init", None)
if callable(pre_init):
pre_init(CP, CP_IQ, *can_callbacks)
class Car:
CI: CarInterfaceBase
RI: RadarInterfaceBase
CP: car.CarParams
CP_IQ: structs.IQCarParams
CP_IQ_capnp: custom.IQCarParams
def __init__(self, CI=None, RI=None) -> None:
self.can_sock = messaging.sub_sock('can', timeout=20)
self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents', 'testJoystick', 'modelV2'] + ['iqCarControl', 'iqPlan'])
self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput', 'radarTracks', 'iqPerfTrace'] + ['iqCarParams', 'iqCarState'])
self.can_rcv_cum_timeout_counter = 0
self.CC_prev = car.CarControl.new_message()
self.CS_prev = car.CarState.new_message()
self.CS_IQ_prev = custom.IQCarState.new_message()
self.initialized_prev = False
self.last_actuators_output = structs.CarControl.Actuators()
self.params = Params()
self.joystick_buttons_prev = [False, False]
self.joystick_debug_mode = self.params.get_bool("JoystickDebugMode")
self.can_callbacks = can_comm_callbacks(self.can_sock, self.pm.sock['sendcan'])
is_release = self.params.get_bool("IsReleaseBranch")
is_release_iq = self.params.get_bool("IsReleaseIqBranch")
if CI is None:
# wait for one pandaState and one CAN packet
print("Waiting for CAN messages...")
while True:
can = messaging.recv_one_retry(self.can_sock)
if len(can.can) > 0:
break
alpha_long_allowed = self.params.get_bool("AlphaLongitudinalEnabled")
num_pandas = len(messaging.recv_one_retry(self.sm.sock['pandaStates']).pandaStates)
cached_params = None
cached_params_raw = self.params.get("CarParamsCache")
if cached_params_raw is not None:
with car.CarParams.from_bytes(cached_params_raw) as _cached_params:
cached_params = _cached_params
fixed_fingerprint = (self.params.get("CarPlatformBundle") or {}).get("platform", None)
init_params_list_iq = iqpilot_interfaces.initialize_params(self.params)
self.CI = get_car(*self.can_callbacks, obd_callback(self.params), alpha_long_allowed, is_release, num_pandas, cached_params,
fixed_fingerprint, init_params_list_iq, is_release_iq)
iqpilot_interfaces.apply_iq_car_config(self.CI, self.params)
self.RI = interfaces[self.CI.CP.carFingerprint].RadarInterface(self.CI.CP, self.CI.CP_IQ)
self.CP = self.CI.CP
self.CP_IQ = self.CI.CP_IQ
# continue onto next fingerprinting step in pandad
self.params.put_bool("FirmwareQueryDone", True)
else:
self.CI, self.CP, self.CP_IQ = CI, CI.CP, CI.CP_IQ
self.RI = RI
self.CP.alternativeExperience = 0
# Steering assistance behavior flags
apply_aol_experience_flags(self.CP, self.CP_IQ, self.params)
apply_aol_brand_overrides(self.CP, self.CP_IQ, self.params)
# IQ.Dynamic control mode
self.iq_dynamic_mode = self.params.get_bool("IQDynamicMode")
openpilot_enabled_toggle = self.params.get_bool("OpenpilotEnabledToggle")
run_optional_pre_init(self.CI, self.CP, self.CP_IQ, self.can_callbacks)
controller_available = self.CI.CC is not None and openpilot_enabled_toggle and not self.CP.dashcamOnly
self.CP.passive = not controller_available or self.CP.dashcamOnly
if self.CP.passive:
safety_config = structs.CarParams.SafetyConfig()
safety_config.safetyModel = structs.CarParams.SafetyModel.noOutput
self.CP.safetyConfigs = [safety_config]
if self.CP.secOcRequired:
# Copy user key if available
try:
with open("/cache/params/SecOCKey") as f:
user_key = f.readline().strip()
if len(user_key) == 32:
self.params.put("SecOCKey", user_key)
except Exception:
pass
secoc_key = self.params.get("SecOCKey")
if secoc_key is not None:
saved_secoc_key = bytes.fromhex(secoc_key.strip())
if len(saved_secoc_key) == 16:
self.CP.secOcKeyAvailable = True
self.CI.CS.secoc_key = saved_secoc_key
if controller_available:
self.CI.CC.secoc_key = saved_secoc_key
else:
cloudlog.warning("Saved SecOC key is invalid")
if controller_available:
self._seed_learned_factors()
# Write previous route's CarParams
prev_cp = self.params.get("CarParamsPersistent")
if prev_cp is not None:
self.params.put("CarParamsPrevRoute", prev_cp)
# Write CarParams for controls and radard
cp_bytes = self.CP.to_bytes()
self.params.put("CarParams", cp_bytes)
self.params.put_nonblocking("CarParamsCache", cp_bytes)
self.params.put_nonblocking("CarParamsPersistent", cp_bytes)
self.CP_IQ_capnp = convert_to_capnp(self.CP_IQ)
cp_IQ_bytes = self.CP_IQ_capnp.to_bytes()
self.params.put("IQCarParams", cp_IQ_bytes)
self.params.put_nonblocking("IQCarParamsCache", cp_IQ_bytes)
# V2 key: the IQCarParams schema was renumbered, so pre-update persisted bytes
# must never be decoded with the new schema. The old key is left to age out.
self.params.put_nonblocking("IQCarParamsPersistentV2", cp_IQ_bytes)
self.v_cruise_helper = VCruiseHelper(self.CP, self.CP_IQ)
self._needs_iq_lead_data = self.CP.brand == "hyundai"
self.carcontrol_stale_frames = max(1, int(round(0.06 / DT_CTRL)))
self._perf = PerfTraceEmitter("card", pubmaster=self.pm)
self._perf_ring = PerfTraceRing()
self._last_sendcan_mono_ns: int | None = None
self._lag_initialized = False
self.is_metric = self.params.get_bool("IsMetric")
self.experimental_mode = self.params.get_bool("ExperimentalMode")
# card is driven by can recv, expected at 100Hz
self.rk = Ratekeeper(100, print_delay_threshold=None)
# log fingerprint in sentry
iqpilot_interfaces.log_fingerprint(self.CP)
def state_update(self) -> tuple[car.CarState, custom.IQCarState, structs.RadarDataT | None]:
"""carState update loop, driven by can"""
can_strs = messaging.drain_sock_raw(self.can_sock, wait_for_one=True)
can_list = can_capnp_to_list(can_strs)
# Update carState from CAN
CS, CS_IQ = self.CI.update(can_list)
CS_IQ = convert_to_capnp(CS_IQ)
# Update radar tracks from CAN
RD: structs.RadarDataT | None = self.RI.update(can_list)
self.sm.update(0)
self.inject_joystick_buttons(CS)
can_rcv_valid = len(can_strs) > 0
# Check for CAN timeout
if not can_rcv_valid:
self.can_rcv_cum_timeout_counter += 1
if can_rcv_valid and REPLAY:
self.can_log_mono_time = messaging.log_from_bytes(can_strs[0]).logMonoTime
if self.sm.updated['iqPlan']:
self.v_cruise_helper.update_speed_limit_assist(self.is_metric, self.sm['iqPlan'])
if self.v_cruise_helper.volkswagen_standby_set_speed and CS.cruiseState.available and not self.v_cruise_helper.v_cruise_initialized:
self.v_cruise_helper.initialize_v_cruise(CS, self.experimental_mode, self.iq_dynamic_mode)
self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric)
if self.sm['carControl'].enabled and not self.CC_prev.enabled:
# Use CarState w/ buttons from the step selfdrived enables on
self.v_cruise_helper.initialize_v_cruise(self.CS_prev, self.experimental_mode, self.iq_dynamic_mode)
# TODO: mirror the carState.cruiseState struct?
CS.vCruise = float(self.v_cruise_helper.v_cruise_kph)
CS.vCruiseCluster = float(self.v_cruise_helper.v_cruise_cluster_kph)
CS_IQ.slcSetSpeedRequestId = self.v_cruise_helper.slc_set_speed_request_id
CS_IQ.slcSetSpeedGestureId = self.v_cruise_helper.slc_set_speed_gesture_id
CS_IQ.slcSetSpeedRequestKph = self.v_cruise_helper.slc_set_speed_request_kph
return CS, CS_IQ, RD
def _learned_factor_attrs(self):
if self.CI.CC is None:
return ()
return tuple(attr for attr in ("gasfactor", "windfactor") if hasattr(self.CI.CC, attr))
def _stored_learned_factors(self) -> dict:
# JSON-typed params come back already parsed from params_pyx; only the pure-python fallback
# returns raw bytes
stored = self.params.get("IQLongLearnedFactors")
if isinstance(stored, bytes | str):
try:
stored = json.loads(stored)
except ValueError:
stored = None
return stored if isinstance(stored, dict) else {}
def _seed_learned_factors(self):
attrs = self._learned_factor_attrs()
if not attrs:
return
factors = self._stored_learned_factors().get(str(self.CP.carFingerprint), {})
for attr in attrs:
value = factors.get(attr)
if isinstance(value, int | float) and math.isfinite(value):
setattr(self.CI.CC, attr, float(value))
def _save_learned_factors(self):
attrs = self._learned_factor_attrs()
if not attrs:
return
stored = self._stored_learned_factors()
stored[str(self.CP.carFingerprint)] = {attr: float(getattr(self.CI.CC, attr)) for attr in attrs}
# JSON-typed params take the dict itself; params_pyx serializes and rejects pre-dumped strings
self.params.put_nonblocking("IQLongLearnedFactors", stored)
def state_publish(self, CS: car.CarState, CS_IQ: custom.IQCarState, RD: structs.RadarDataT | None):
"""carState and carParams publish loop"""
# persist live-learned longitudinal factors so they survive across drives; card authors the
# car's CAN stream, so a persistence failure must never take it down mid-drive
if self.sm.frame > 0 and self.sm.frame % int(60. / DT_CTRL) == 0:
try:
self._save_learned_factors()
except Exception:
cloudlog.exception("failed to persist learned longitudinal factors")
# carParams - logged every 50 seconds (> 1 per segment)
if self.sm.frame % int(50. / DT_CTRL) == 0:
cp_send = messaging.new_message('carParams')
cp_send.valid = True
cp_send.carParams = self.CP
self.pm.send('carParams', cp_send)
# publish new carOutput
co_send = messaging.new_message('carOutput')
co_send.valid = self.sm.all_checks(['carControl'])
co_send.carOutput.actuatorsOutput = self.last_actuators_output
self.pm.send('carOutput', co_send)
# kick off controlsd step while we actuate the latest carControl packet
cs_send = messaging.new_message('carState')
cs_send.valid = CS.canValid
cs_send.carState = CS
cs_send.carState.canErrorCounter = self.can_rcv_cum_timeout_counter
cs_send.carState.cumLagMs = self.rk.lag * 1000. if self._lag_initialized else 0.
self.pm.send('carState', cs_send)
if RD is not None:
tracks_msg = messaging.new_message('radarTracks')
tracks_msg.valid = not any(RD.errors.to_dict().values())
tracks_msg.radarTracks = RD
self.pm.send('radarTracks', tracks_msg)
# iqCarParams - logged every 50 seconds (> 1 per segment)
if self.sm.frame % int(50. / DT_CTRL) == 0:
iq_cp_send = messaging.new_message('iqCarParams')
iq_cp_send.valid = True
iq_cp_send.iqCarParams = self.CP_IQ_capnp
self.pm.send('iqCarParams', iq_cp_send)
iq_cs_send = messaging.new_message('iqCarState')
iq_cs_send.valid = CS.canValid
iq_cs_send.iqCarState = CS_IQ
self.pm.send('iqCarState', iq_cs_send)
def controls_update(self, CS: car.CarState, CC: car.CarControl, CC_IQ: custom.IQCarControl):
"""control update loop, driven by carControl"""
if not self.initialized_prev:
# Initialize CarInterface, once controls are ready
# TODO: this can make us miss at least a few cycles when doing an ECU knockout
self.CI.init(self.CP, self.CP_IQ, *self.can_callbacks)
# signal pandad to switch to car safety mode
self.params.put_bool_nonblocking("ControlsReady", True)
stale_frames = max(0, self.sm.frame - self.sm.recv_frame['carControl'])
stale_carcontrol_us = int(round(stale_frames * DT_CTRL * 1_000_000))
carstate_alive = bool(CS.canValid)
fallback_active = False
if self.sm.all_alive(['carControl']):
# send car controls over can
now_nanos = self.can_log_mono_time if REPLAY else int(time.monotonic() * 1e9)
started = time.monotonic_ns()
cc_iq = convert_iq_car_control_compact(CC_IQ, include_leads=self._needs_iq_lead_data)
convert_us = (time.monotonic_ns() - started) // 1000
model = self.sm['modelV2'] if self.sm.valid['modelV2'] else None
started = time.monotonic_ns()
self.last_actuators_output, can_sends = self.CI.apply(CC, cc_iq, now_nanos, model)
apply_us = (time.monotonic_ns() - started) // 1000
started = time.monotonic_ns()
self.pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
sendcan_us = (time.monotonic_ns() - started) // 1000
self.CC_prev = CC
else:
convert_us = 0
apply_us = 0
sendcan_us = 0
if stale_frames >= self.carcontrol_stale_frames:
fallback_active = True
fallback_cc = CC.as_builder()
fallback_cc.enabled = False
fallback_cc.latActive = False
fallback_cc.longActive = False
fallback_cc.leftBlinker = False
fallback_cc.rightBlinker = False
fallback_cc.cruiseControl.cancel = bool(CS.cruiseState.enabled or self.CC_prev.enabled or self.CC_prev.longActive)
fallback_cc.cruiseControl.resume = False
fallback_cc.cruiseControl.override = False
fallback_cc.actuators.torque = 0.0
fallback_cc.actuators.steeringAngleDeg = float(getattr(CS, 'steeringAngleDeg', 0.0))
fallback_cc.actuators.curvature = 0.0
fallback_cc.actuators.accel = 0.0
fallback_cc.actuators.longControlState = car.CarControl.Actuators.LongControlState.off
fallback_cc_iq = custom.IQCarControl.new_message()
now_nanos = self.can_log_mono_time if REPLAY else int(time.monotonic() * 1e9)
started = time.monotonic_ns()
cc_iq = convert_iq_car_control_compact(fallback_cc_iq, include_leads=self._needs_iq_lead_data)
convert_us = (time.monotonic_ns() - started) // 1000
started = time.monotonic_ns()
self.last_actuators_output, can_sends = self.CI.apply(fallback_cc.as_reader(), cc_iq, now_nanos)
apply_us = (time.monotonic_ns() - started) // 1000
started = time.monotonic_ns()
self.pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
sendcan_us = (time.monotonic_ns() - started) // 1000
now_ns = time.monotonic_ns()
sendcan_gap_us = 0
if sendcan_us > 0:
if self._last_sendcan_mono_ns is not None:
sendcan_gap_us = max(0, (now_ns - self._last_sendcan_mono_ns) // 1000)
self._last_sendcan_mono_ns = now_ns
flags = 0
if fallback_active:
flags |= CARD_FLAG_FALLBACK_ACTIVE
if carstate_alive:
flags |= CARD_FLAG_CARSTATE_ALIVE
if sendcan_gap_us >= CARD_SENDCAN_GAP_WARN_US:
flags |= CARD_FLAG_SENDCAN_GAP
sample = PerfSample(
frame_id=self.sm.frame,
stale_carcontrol_us=stale_carcontrol_us,
stale_carcontrol_frames=stale_frames,
sendcan_gap_us=int(sendcan_gap_us),
publish_us=int(convert_us),
state_control_us=int(apply_us),
tail_work_us=int(sendcan_us),
flags=flags,
)
self._perf_ring.push(sample)
if stale_carcontrol_us >= 20_000 or fallback_active or sendcan_gap_us >= CARD_SENDCAN_GAP_WARN_US:
severity = "warning"
if stale_carcontrol_us >= 60_000 or sendcan_gap_us >= CARD_SENDCAN_GAP_ERROR_US:
severity = "error"
detail = (
f"stale_carcontrol_us={stale_carcontrol_us} stale_frames={stale_frames} "
f"convert_us={convert_us} apply_us={apply_us} sendcan_us={sendcan_us} "
f"sendcan_gap_us={sendcan_gap_us} fallback={int(fallback_active)}"
)
self._perf.emit(
"card_stale_carcontrol" if stale_carcontrol_us >= 20_000 else "card_sendcan_gap",
severity=severity,
frame_id=self.sm.frame,
total_time_us=int(convert_us + apply_us + sendcan_us),
batch_size=len(self._perf_ring.snapshot()),
flags=flags,
samples=self._perf_ring.snapshot(),
detail=detail,
min_interval_s=0.25,
)
def step(self):
started_ns = time.monotonic_ns()
checkpoint_ns = started_ns
CS, CS_IQ, RD = self.state_update()
state_update_us = (time.monotonic_ns() - checkpoint_ns) // 1000
checkpoint_ns = time.monotonic_ns()
self.state_publish(CS, CS_IQ, RD)
state_publish_us = (time.monotonic_ns() - checkpoint_ns) // 1000
checkpoint_ns = time.monotonic_ns()
initialized = (not any(e.name == EventName.selfdriveInitializing for e in self.sm['onroadEvents']) and
self.sm.seen['onroadEvents'])
if not self.CP.passive and initialized:
self.controls_update(CS, self.sm['carControl'], self.sm['iqCarControl'])
if initialized and not self._lag_initialized:
self.rk.reset()
self._lag_initialized = True
controls_update_us = (time.monotonic_ns() - checkpoint_ns) // 1000
self.initialized_prev = initialized
self.CS_prev = CS
self.CS_IQ_prev = CS_IQ
total_us = (time.monotonic_ns() - started_ns) // 1000
step_sample = PerfSample(
frame_id=self.sm.frame,
loop_dt_us=int(total_us),
update_us=int(state_update_us),
publish_us=int(state_publish_us),
state_control_us=int(controls_update_us),
)
self._perf_ring.push(step_sample)
if total_us >= 15_000 or state_update_us >= 8_000 or controls_update_us >= 8_000:
detail = (
f"state_update_us={state_update_us} state_publish_us={state_publish_us} "
f"controls_update_us={controls_update_us}"
)
self._perf.emit(
"card_slow_loop",
severity="warning" if total_us < 50_000 else "error",
frame_id=self.sm.frame,
total_time_us=int(total_us),
samples=self._perf_ring.snapshot(),
detail=detail,
min_interval_s=0.25,
)
def inject_joystick_buttons(self, CS: car.CarState) -> None:
if not self.joystick_debug_mode:
self.joystick_buttons_prev = [False, False]
return
if self.sm.recv_frame['testJoystick'] == 0:
self.joystick_buttons_prev = [False, False]
return
age_s = (self.sm.frame - self.sm.recv_frame['testJoystick']) * DT_CTRL
buttons = list(getattr(self.sm['testJoystick'], 'buttons', []))
current = [
bool(buttons[0]) if len(buttons) > 0 else False,
bool(buttons[1]) if len(buttons) > 1 else False,
]
if age_s > 0.2:
current = [False, False]
engage = current[0] and not self.joystick_buttons_prev[0]
disengage = current[1] and not self.joystick_buttons_prev[1]
self.joystick_buttons_prev = current
if engage:
try:
self.params.put("JoystickAolRequest", "enable")
except UnknownKeyName:
pass
if disengage:
try:
self.params.put("JoystickAolRequest", "disable")
except UnknownKeyName:
pass
def params_thread(self, evt):
config_background_thread()
while not evt.is_set():
self.is_metric = self.params.get_bool("IsMetric")
self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl
# iqpilot
self.iq_dynamic_mode = self.params.get_bool("IQDynamicMode")
self.joystick_debug_mode = self.params.get_bool("JoystickDebugMode")
self.v_cruise_helper.read_custom_set_speed_params()
time.sleep(0.1)
def card_thread(self):
e = threading.Event()
t = threading.Thread(target=self.params_thread, args=(e, ))
try:
t.start()
while True:
self.step()
self.rk.monitor_time()
finally:
e.set()
t.join()
def main():
config_realtime_process(4, Priority.CTRL_HIGH)
lock_memory()
car = Car()
car.card_thread()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,387 @@
import math
import numpy as np
from iqpilot.cereal import car
from iqpilot.common.constants import CV
from iqpilot.cereal import car, custom
from iqdbc.car import structs
from iqpilot.common.params import Params
from iqpilot.common.realtime import DT_CTRL
from iqpilot.selfdrive.car.long_increments import LongIncrementConfig, read_long_increment_config, resolve_button_step
# ===== VCruiseHelperIQ (dissolved from iqpilot vcruise_helper_iq) =====
ButtonType = car.CarState.ButtonEvent.Type
SpeedLimitAssistState = custom.IQPlan.SpeedLimit.AssistState
SPEED_LIMIT_CONTROL_ACTIVE_STATES = (SpeedLimitAssistState.active, SpeedLimitAssistState.adapting)
def compare_cluster_target(v_cruise_cluster: float, target_set_speed: float, is_metric: bool) -> tuple[bool, bool]:
"""Whether the cluster set-speed needs +/- presses to reach the target, in display units."""
to_shown = CV.MS_TO_KPH if is_metric else CV.MS_TO_MPH
now = round(v_cruise_cluster * to_shown)
goal = round(target_set_speed * to_shown)
return now < goal, now > goal
CRUISE_BUTTON_TIMER = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0,
ButtonType.setCruise: 0, ButtonType.resumeCruise: 0,
ButtonType.cancel: 0, ButtonType.mainCruise: 0}
V_CRUISE_MIN = 8
V_CRUISE_MAX = 200 # ~ 124 mph
V_CRUISE_UNSET = 255
IQ_SET_SPEED_MODE_OFF = 0
IQ_SET_SPEED_MODE_FIXED = 1
IQ_SET_SPEED_MPH_DEFAULT = 65
IQ_SET_SPEED_MPH_MIN = 20
IQ_SET_SPEED_MPH_MAX = 120
def get_minimum_set_speed_kph(_is_metric: bool) -> float:
# IQ minimum set speed floor, expressed in kph for VCruiseHelper integration.
return float(V_CRUISE_MIN)
def update_manual_button_timers(CS: car.CarState, button_timers: dict[car.CarState.ButtonEvent.Type, int]) -> None:
# age any button that's currently held (nonzero timer)
for btn, held_frames in button_timers.items():
if held_frames > 0:
button_timers[btn] = held_frames + 1
# a press/release edge (re)starts the timer at 1 or clears it to 0
for event in CS.buttonEvents:
raw = event.type.raw
if raw in button_timers:
button_timers[raw] = 1 if event.pressed else 0
class VCruiseHelperIQ:
def __init__(self, CP: structs.CarParams, CP_IQ: structs.IQCarParams) -> None:
self.CP = CP
self.CP_IQ = CP_IQ
self.v_cruise_kph = V_CRUISE_UNSET
self.v_cruise_cluster_kph = V_CRUISE_UNSET
self.params = Params()
self.v_cruise_min = 0
self.enabled_prev = False
self.long_increment_config: LongIncrementConfig = read_long_increment_config(self.params)
self.set_speed_to_limit = self._read_set_speed_to_limit()
self.iq_set_speed_mode = self._read_iq_set_speed_mode()
self.iq_set_speed_use_current = self._read_iq_set_speed_use_current()
self.iq_set_speed_mph = self._read_iq_set_speed_mph()
self.enable_button_timers = CRUISE_BUTTON_TIMER
# Speed Limit Assist
self.speed_limit_state = SpeedLimitAssistState.disabled
self.prev_speed_limit_state = SpeedLimitAssistState.disabled
self.has_speed_limit = False
self.speed_limit_final_last = 0.
self.speed_limit_final_last_kph = 0.
self.prev_speed_limit_final_last_kph = 0.
self.req_plus = False
self.req_minus = False
def _read_set_speed_to_limit(self) -> bool:
try:
return self.params.get_bool("SLCSetSpeedToLimit")
except Exception:
return False
def _read_iq_set_speed_mode(self) -> int:
try:
return int(self.params.get("IQE2ESetSpeedMode", return_default=True) or IQ_SET_SPEED_MODE_OFF)
except Exception:
return IQ_SET_SPEED_MODE_OFF
def _read_iq_set_speed_use_current(self) -> bool:
try:
return bool(self.params.get_bool("IQE2ESetSpeedUseCurrent"))
except Exception:
return False
def _read_iq_set_speed_mph(self) -> int:
try:
value = int(self.params.get("IQE2ESetSpeedMph", return_default=True) or IQ_SET_SPEED_MPH_DEFAULT)
except Exception:
value = IQ_SET_SPEED_MPH_DEFAULT
return int(np.clip(value, IQ_SET_SPEED_MPH_MIN, IQ_SET_SPEED_MPH_MAX))
def read_custom_set_speed_params(self) -> None:
self.long_increment_config = read_long_increment_config(self.params)
self.set_speed_to_limit = self._read_set_speed_to_limit()
self.iq_set_speed_mode = self._read_iq_set_speed_mode()
self.iq_set_speed_use_current = self._read_iq_set_speed_use_current()
self.iq_set_speed_mph = self._read_iq_set_speed_mph()
def get_iq_mode_initial_set_speed_kph(self, current_speed_kph: float, fallback_kph: float) -> float:
if self.iq_set_speed_mode != IQ_SET_SPEED_MODE_FIXED:
return fallback_kph
if self.iq_set_speed_use_current:
return float(np.clip(round(current_speed_kph, 1), self.v_cruise_min, V_CRUISE_MAX))
fixed_kph = float(self.iq_set_speed_mph) * CV.MPH_TO_KPH
return float(np.clip(round(fixed_kph, 1), self.v_cruise_min, V_CRUISE_MAX))
def update_v_cruise_delta(self, long_press: bool, v_cruise_delta: float) -> tuple[bool, float]:
return resolve_button_step(self.long_increment_config, long_press, v_cruise_delta)
def get_minimum_set_speed(self, is_metric: bool) -> None:
if self.CP_IQ.pcmCruiseSpeed:
self.v_cruise_min = V_CRUISE_MIN
return
self.v_cruise_min = get_minimum_set_speed_kph(is_metric)
def update_enabled_state(self, CS: car.CarState, enabled: bool) -> bool:
# pcmCruiseSpeed cars keep the stock enabled flag; others gate engagement on button release
if self.CP_IQ.pcmCruiseSpeed:
return enabled
update_manual_button_timers(CS, self.enable_button_timers)
button_pressed = any(t > 0 for t in self.enable_button_timers.values())
if enabled and not self.enabled_prev:
# first engage frame while the button is still down: hold off until it's let go
self.enabled_prev = not button_pressed
return False
if not enabled:
self.enabled_prev = False
return enabled and self.enabled_prev
def update_speed_limit_assist(self, is_metric, LP_IQ: custom.IQPlan) -> None:
resolver = LP_IQ.speedLimit.resolver
self.has_speed_limit = resolver.speedLimitValid or resolver.speedLimitLastValid
self.speed_limit_final_last = LP_IQ.speedLimit.resolver.speedLimitFinalLast
self.speed_limit_final_last_kph = self.speed_limit_final_last * CV.MS_TO_KPH
self.speed_limit_state = LP_IQ.speedLimit.assist.state
self.req_plus, self.req_minus = compare_cluster_target(self.v_cruise_cluster_kph * CV.KPH_TO_MS,
self.speed_limit_final_last, is_metric)
@property
def update_speed_limit_final_last_changed(self) -> bool:
if not self.has_speed_limit:
return False
return self.speed_limit_final_last_kph != self.prev_speed_limit_final_last_kph
def update_speed_limit_assist_v_cruise_non_pcm(self) -> None:
if self.set_speed_to_limit and \
self.speed_limit_state in SPEED_LIMIT_CONTROL_ACTIVE_STATES and \
(self.prev_speed_limit_state not in SPEED_LIMIT_CONTROL_ACTIVE_STATES or self.update_speed_limit_final_last_changed):
self.v_cruise_kph = np.clip(round(self.speed_limit_final_last_kph, 1), self.v_cruise_min, V_CRUISE_MAX)
self.prev_speed_limit_state = self.speed_limit_state
self.prev_speed_limit_final_last_kph = self.speed_limit_final_last_kph
def update_speed_limit_assist_v_cruise_op_long(self) -> None:
if not self.CP.openpilotLongitudinalControl or not self.set_speed_to_limit:
return
if self.speed_limit_state == SpeedLimitAssistState.disabled:
self.prev_speed_limit_state = self.speed_limit_state
self.prev_speed_limit_final_last_kph = self.speed_limit_final_last_kph
return
if not self.has_speed_limit or self.speed_limit_final_last_kph <= 0:
self.prev_speed_limit_state = self.speed_limit_state
self.prev_speed_limit_final_last_kph = self.speed_limit_final_last_kph
return
target_kph = float(np.clip(round(self.speed_limit_final_last_kph, 1), self.v_cruise_min, V_CRUISE_MAX))
# OP Long uses planner min(v_cruise, slc target) to enforce limits.
# Do not clamp the user's max (v_cruise) here, or they cannot raise/lower it.
# Only sync on initial activation or when the resolved limit changes.
if (self.v_cruise_kph == V_CRUISE_UNSET and self.speed_limit_state in SPEED_LIMIT_CONTROL_ACTIVE_STATES) or \
self.update_speed_limit_final_last_changed:
self.v_cruise_kph = target_kph
self.v_cruise_cluster_kph = target_kph
self.prev_speed_limit_state = self.speed_limit_state
self.prev_speed_limit_final_last_kph = self.speed_limit_final_last_kph
# WARNING: this value was determined based on the model's training distribution,
# model predictions above this speed can be unpredictable
# V_CRUISE's are in kph
V_CRUISE_MIN = 8
V_CRUISE_MAX = 200 # ~ 124 mph
V_CRUISE_UNSET = 255
V_CRUISE_INITIAL = 40
V_CRUISE_INITIAL_EXPERIMENTAL_MODE = 105
IMPERIAL_INCREMENT = round(CV.MPH_TO_KPH, 1) # round here to avoid rounding errors incrementing set speed
ButtonEvent = car.CarState.ButtonEvent
ButtonType = car.CarState.ButtonEvent.Type
CRUISE_LONG_PRESS = 50
CRUISE_NEAREST_FUNC = {
ButtonType.accelCruise: math.ceil,
ButtonType.decelCruise: math.floor,
}
CRUISE_INTERVAL_SIGN = {
ButtonType.accelCruise: +1,
ButtonType.decelCruise: -1,
}
class VCruiseHelper(VCruiseHelperIQ):
def __init__(self, CP, CP_IQ):
VCruiseHelperIQ.__init__(self, CP, CP_IQ)
self.CP = CP
self.v_cruise_kph = V_CRUISE_UNSET
self.v_cruise_cluster_kph = V_CRUISE_UNSET
self.v_cruise_kph_last = 0
self.button_timers = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0}
self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers}
self.slc_set_speed_request_id = 0
self.slc_set_speed_gesture_id = 0
self.slc_set_speed_request_kph = 0.0
self._slc_accel_held = False
self._slc_accel_release_frames = 0
self._slc_pcm_speed_last = None
def _update_slc_accel_gesture(self, CS):
self._slc_accel_release_frames = max(0, self._slc_accel_release_frames - 1)
for button in CS.buttonEvents:
if button.type in (ButtonType.accelCruise, ButtonType.resumeCruise):
if button.pressed:
self.slc_set_speed_gesture_id = (self.slc_set_speed_gesture_id + 1) % (1 << 32)
self._slc_accel_release_frames = 0
else:
self._slc_accel_release_frames = int(0.5 / DT_CTRL)
self._slc_accel_held = button.pressed
elif button.pressed:
self._slc_accel_held = False
self._slc_accel_release_frames = 0
if not CS.cruiseState.available:
self._slc_accel_held = False
self._slc_accel_release_frames = 0
def _record_slc_set_speed_increase(self, previous_kph, enabled):
if enabled and (self._slc_accel_held or self._slc_accel_release_frames > 0) and \
previous_kph is not None and 0 < previous_kph < self.v_cruise_kph <= V_CRUISE_MAX:
self.slc_set_speed_request_id = (self.slc_set_speed_request_id + 1) % (1 << 32)
self.slc_set_speed_request_kph = float(self.v_cruise_kph)
@property
def v_cruise_initialized(self):
return self.v_cruise_kph != V_CRUISE_UNSET
@property
def volkswagen_standby_set_speed(self) -> bool:
return self.CP.brand == "volkswagen" and self.CP.openpilotLongitudinalControl and not self.CP.pcmCruise
def update_v_cruise(self, CS, enabled, is_metric):
self.v_cruise_kph_last = self.v_cruise_kph
self._update_slc_accel_gesture(CS)
self.get_minimum_set_speed(is_metric)
if CS.cruiseState.available:
_enabled = self.update_enabled_state(CS, enabled)
if not self.CP.pcmCruise or (not self.CP_IQ.pcmCruiseSpeed and _enabled):
# if stock cruise is completely disabled, then we can use our own set speed logic
self._update_v_cruise_non_pcm(CS, _enabled, is_metric, self.volkswagen_standby_set_speed)
self._record_slc_set_speed_increase(self.v_cruise_kph_last, _enabled)
self.update_speed_limit_assist_v_cruise_non_pcm()
self.v_cruise_cluster_kph = self.v_cruise_kph
self.update_button_timers(CS, enabled)
else:
self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH
self.v_cruise_cluster_kph = CS.cruiseState.speedCluster * CV.MS_TO_KPH
self._record_slc_set_speed_increase(self._slc_pcm_speed_last, _enabled)
self._slc_pcm_speed_last = self.v_cruise_kph
if CS.cruiseState.speed == 0:
self.v_cruise_kph = V_CRUISE_UNSET
self.v_cruise_cluster_kph = V_CRUISE_UNSET
elif CS.cruiseState.speed == -1:
self.v_cruise_kph = -1
self.v_cruise_cluster_kph = -1
else:
self.update_speed_limit_assist_v_cruise_op_long()
else:
self.v_cruise_kph = V_CRUISE_UNSET
self.v_cruise_cluster_kph = V_CRUISE_UNSET
self._slc_pcm_speed_last = None
def _update_v_cruise_non_pcm(self, CS, enabled, is_metric, allow_standby_adjustment=False):
# handle button presses. TODO: this should be in state_control, but a decelCruise press
# would have the effect of both enabling and changing speed is checked after the state transition
if not enabled and not allow_standby_adjustment:
return
long_press = False
button_type = None
v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT
for b in CS.buttonEvents:
if b.type.raw in self.button_timers and not b.pressed:
if self.button_timers[b.type.raw] > CRUISE_LONG_PRESS:
return # end long press
button_type = b.type.raw
break
else:
for k, timer in self.button_timers.items():
if timer and timer % CRUISE_LONG_PRESS == 0:
button_type = k
long_press = True
break
if button_type is None:
return
# Don't adjust speed when pressing resume to exit standstill
cruise_standstill = self.button_change_states[button_type]["standstill"] or CS.cruiseState.standstill
if button_type == ButtonType.accelCruise and cruise_standstill:
return
# Don't adjust speed if we've enabled since the button was depressed (some ports enable on rising edge)
if enabled and not self.button_change_states[button_type]["enabled"]:
return
long_press, v_cruise_delta = VCruiseHelperIQ.update_v_cruise_delta(self, long_press, v_cruise_delta)
if long_press and self.v_cruise_kph % v_cruise_delta != 0: # partial interval
self.v_cruise_kph = CRUISE_NEAREST_FUNC[button_type](self.v_cruise_kph / v_cruise_delta) * v_cruise_delta
else:
self.v_cruise_kph += v_cruise_delta * CRUISE_INTERVAL_SIGN[button_type]
# If set is pressed while overriding, clip cruise speed to minimum of vEgo
if enabled and CS.gasPressed and button_type in (ButtonType.decelCruise, ButtonType.setCruise):
self.v_cruise_kph = max(self.v_cruise_kph, CS.vEgo * CV.MS_TO_KPH)
self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), self.v_cruise_min, V_CRUISE_MAX)
def update_button_timers(self, CS, enabled):
# increment timer for buttons still pressed
for k in self.button_timers:
if self.button_timers[k] > 0:
self.button_timers[k] += 1
for b in CS.buttonEvents:
if b.type.raw in self.button_timers:
# Start/end timer and store current state on change of button pressed
self.button_timers[b.type.raw] = 1 if b.pressed else 0
self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled}
def initialize_v_cruise(self, CS, experimental_mode: bool, iq_dynamic_mode: bool) -> None:
# initializing is handled by the PCM
if self.CP.pcmCruise or self.v_cruise_initialized:
return
initial_experimental_mode = experimental_mode and not iq_dynamic_mode
initial = V_CRUISE_INITIAL_EXPERIMENTAL_MODE if initial_experimental_mode else V_CRUISE_INITIAL
if initial_experimental_mode:
initial = self.get_iq_mode_initial_set_speed_kph(CS.vEgo * CV.MS_TO_KPH, initial)
if any(b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) and self.v_cruise_initialized:
self.v_cruise_kph = self.v_cruise_kph_last
else:
self.v_cruise_kph = int(round(np.clip(CS.vEgo * CV.MS_TO_KPH, initial, V_CRUISE_MAX)))
self.v_cruise_cluster_kph = self.v_cruise_kph

21
iqpilot/selfdrive/car/docs.py Executable file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env python3
import argparse
import os
from iqpilot.common.basedir import BASEDIR
from iqdbc.car.docs import get_all_car_docs, generate_cars_md
CARS_MD_OUT = os.path.join(BASEDIR, "docs", "CARS.md")
CARS_MD_TEMPLATE = os.path.join(BASEDIR, "iqpilot", "selfdrive", "car", "CARS_template.md")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Auto generates supported cars documentation",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--template", default=CARS_MD_TEMPLATE, help="Override default template filename")
parser.add_argument("--out", default=CARS_MD_OUT, help="Override default generated filename")
args = parser.parse_args()
with open(args.out, 'w') as f:
f.write(generate_cars_md(get_all_car_docs(), args.template))
print(f"Generated and written to {args.out}")

View File

@@ -0,0 +1,67 @@
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
from __future__ import annotations
from iqpilot.common.constants import CV
from iqpilot.selfdrive.car.cruise import V_CRUISE_MAX
from iqdbc.car import structs
ENHANCED_STOCK_LONGITUDINAL_CONTROL_SET_SPEED_KPH_KEY = "enhancedStockLongitudinalControl.setSpeedKph"
def _float_param(key: str, value: float) -> dict[str, object]:
return {"key": key, "type": "float", "value": f"{float(value):.3f}".encode("utf-8")}
def _clamp_set_speed_kph(value: float) -> float:
return max(0.0, min(V_CRUISE_MAX, float(value)))
def build_iq_control_params_from_plan(CP: structs.CarParams, iq_plan, selfdrive_enabled: bool,
current_set_speed_kph: float, previous_sync_limit_kph: float | None,
pending_sync_limit_kph: float | None) -> tuple[list[dict[str, object]], float | None, float | None]:
if not CP.openpilotLongitudinalControl or not selfdrive_enabled:
return [], None, None
resolver = getattr(getattr(iq_plan, "speedLimit", None), "resolver", None)
assist = getattr(getattr(iq_plan, "speedLimit", None), "assist", None)
if resolver is None or assist is None:
return [], None, None
speed_limit_final_last = float(getattr(resolver, "speedLimitFinalLast", 0.0) or 0.0)
assist_enabled = bool(getattr(assist, "enabled", False))
if not assist_enabled or speed_limit_final_last <= 0.0:
return [], None, None
resolved_limit_kph = _clamp_set_speed_kph(speed_limit_final_last * CV.MS_TO_KPH)
limit_changed = previous_sync_limit_kph is None or abs(resolved_limit_kph - previous_sync_limit_kph) > 0.05
if limit_changed:
pending_sync_limit_kph = resolved_limit_kph
if pending_sync_limit_kph is not None:
if abs(current_set_speed_kph - pending_sync_limit_kph) <= 0.25:
pending_sync_limit_kph = None
set_speed_kph = _clamp_set_speed_kph(current_set_speed_kph or resolved_limit_kph)
else:
set_speed_kph = pending_sync_limit_kph
else:
set_speed_kph = _clamp_set_speed_kph(current_set_speed_kph or resolved_limit_kph)
return [_float_param(ENHANCED_STOCK_LONGITUDINAL_CONTROL_SET_SPEED_KPH_KEY, set_speed_kph)], resolved_limit_kph, pending_sync_limit_kph
def get_set_speed_kph_from_params(params) -> float | None:
for param in params:
key = param.key if hasattr(param, "key") else param.get("key")
if key != ENHANCED_STOCK_LONGITUDINAL_CONTROL_SET_SPEED_KPH_KEY:
continue
raw_value = param.value if hasattr(param, "value") else param.get("value")
try:
raw = raw_value.decode("utf-8") if isinstance(raw_value, (bytes, bytearray)) else str(raw_value)
value = float(raw)
except (AttributeError, TypeError, ValueError):
return None
return _clamp_set_speed_kph(value)
return None

View File

@@ -0,0 +1,48 @@
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
from iqpilot.cereal import car, custom
from iqdbc.car import structs
from iqpilot.common.params import Params
_Button = car.CarState.ButtonEvent.Type
_IQEvent = custom.IQOnroadEvent.EventName
_GAP_BUTTON = _Button.gapAdjustCruise
HOLD_FRAMES_TO_TOGGLE = 50
class GapButtonActions:
def __init__(self, CP: structs.CarParams):
self._CP = CP
self._params = Params()
self._gap_hold_frames = 0
self._already_toggled = False
# read (and cleared) by the personality-decrement handler in selfdrived so a
# release that ends a toggle-hold does not also decrement personality
self.experimental_mode_switched = False
def update(self, CS, events, experimental_mode) -> None:
if not (self._CP.openpilotLongitudinalControl and CS.cruiseState.available):
return
self._advance_hold(CS)
self._toggle_experimental_on_long_hold(events, experimental_mode)
def _advance_hold(self, CS) -> None:
# once counting, keep incrementing each frame the hold persists
if self._gap_hold_frames > 0:
self._gap_hold_frames += 1
# a fresh press seeds the counter; a release zeroes it
for be in CS.buttonEvents:
if be.type.raw == _GAP_BUTTON:
self._gap_hold_frames = int(be.pressed)
if not be.pressed:
self._already_toggled = False
def _toggle_experimental_on_long_hold(self, events, experimental_mode) -> None:
if self._already_toggled or self._gap_hold_frames < HOLD_FRAMES_TO_TOGGLE:
return
self._params.put_bool_nonblocking("ExperimentalMode", not experimental_mode)
events.add(_IQEvent.experimentalToggled)
self._already_toggled = True
self.experimental_mode_switched = True

View File

@@ -0,0 +1,198 @@
import capnp
from enum import Enum
from typing import Any
from iqpilot.cereal import custom
from iqdbc.car import structs
_FIELDS = '__dataclass_fields__' # copy of dataclasses._FIELDS
def is_dataclass(obj):
"""Similar to dataclasses.is_dataclass without instance type check checking"""
return hasattr(obj, _FIELDS)
def _asdictref_inner(obj) -> dict[str, Any] | Any:
if isinstance(obj, Enum):
return _asdictref_inner(obj.value)
elif is_dataclass(obj):
ret = {}
for field in getattr(obj, _FIELDS): # similar to dataclasses.fields()
ret[field] = _asdictref_inner(getattr(obj, field))
return ret
elif isinstance(obj, (tuple, list)):
return type(obj)(_asdictref_inner(v) for v in obj)
elif isinstance(obj, dict):
return {key: _asdictref_inner(value) for key, value in obj.items()}
else:
return obj
def asdictref(obj) -> dict[str, Any]:
"""
Similar to dataclasses.asdict without recursive type checking and copy.deepcopy
Note that the resulting dict will contain references to the original struct as a result
"""
if not is_dataclass(obj):
raise TypeError("asdictref() should be called on dataclass instances")
return _asdictref_inner(obj)
def convert_to_capnp(struct: structs.IQCarParams | structs.IQCarState) -> capnp.lib.capnp._DynamicStructBuilder:
struct_dict = asdictref(struct)
if isinstance(struct, structs.IQCarParams):
struct_capnp = custom.IQCarParams.new_message(**struct_dict)
elif isinstance(struct, structs.IQCarState):
struct_capnp = custom.IQCarState.new_message(**struct_dict)
else:
raise ValueError(f"Unsupported struct type: {type(struct)}")
return struct_capnp
def convert_iq_car_control(struct: capnp.lib.capnp._DynamicStructReader) -> structs.IQCarControl:
# NOTE: Avoid `to_dict()` here; it can throw on fuzzed messages when capnp
# tries to resolve unknown/invalid union-like internals. Explicit mapping is
# stable and keeps this conversion deterministic for tests.
struct_dataclass = structs.IQCarControl()
aol = struct.aol
struct_dataclass.aol = structs.AlwaysOnLateral(
state=str(aol.state),
enabled=aol.enabled,
active=aol.active,
available=aol.available,
)
struct_dataclass.params = [
structs.IQCarControl.Param(
key=p.key,
value=bytes(p.value),
type=str(p.type),
) for p in struct.params
]
struct_dataclass.angleOffsetDeg = float(getattr(struct, "angleOffsetDeg", 0.0))
lead_one = struct.leadOne
struct_dataclass.leadOne = structs.LeadData(
dRel=lead_one.dRel,
yRel=lead_one.yRel,
vRel=lead_one.vRel,
aRel=lead_one.aRel,
vLead=lead_one.vLead,
dPath=lead_one.dPath,
vLat=lead_one.vLat,
vLeadK=lead_one.vLeadK,
aLeadK=lead_one.aLeadK,
fcw=lead_one.fcw,
status=lead_one.status,
aLeadTau=lead_one.aLeadTau,
modelProb=lead_one.modelProb,
radar=lead_one.radar,
radarTrackId=lead_one.radarTrackId,
)
lead_two = struct.leadTwo
struct_dataclass.leadTwo = structs.LeadData(
dRel=lead_two.dRel,
yRel=lead_two.yRel,
vRel=lead_two.vRel,
aRel=lead_two.aRel,
vLead=lead_two.vLead,
dPath=lead_two.dPath,
vLat=lead_two.vLat,
vLeadK=lead_two.vLeadK,
aLeadK=lead_two.aLeadK,
fcw=lead_two.fcw,
status=lead_two.status,
aLeadTau=lead_two.aLeadTau,
modelProb=lead_two.modelProb,
radar=lead_two.radar,
radarTrackId=lead_two.radarTrackId,
)
struct_dataclass.angleOffsetDeg = struct.angleOffsetDeg
struct_dataclass.radarBlendActive = bool(getattr(struct, "radarBlendActive", False))
struct_dataclass.radarEngageReq = bool(getattr(struct, "radarEngageReq", False))
struct_dataclass.radarCancelReq = bool(getattr(struct, "radarCancelReq", False))
struct_dataclass.useRadarAccel = bool(getattr(struct, "useRadarAccel", False))
struct_dataclass.radarSetSpeedKph = float(getattr(struct, "radarSetSpeedKph", 0.0))
struct_dataclass.radarGapBars = int(getattr(struct, "radarGapBars", 0))
return struct_dataclass
def convert_iq_car_control_compact(struct: capnp.lib.capnp._DynamicStructReader, *, include_leads: bool) -> structs.IQCarControl:
struct_dataclass = structs.IQCarControl()
aol = struct.aol
struct_dataclass.aol = structs.AlwaysOnLateral(
state=str(aol.state),
enabled=aol.enabled,
active=aol.active,
available=aol.available,
)
struct_dataclass.params = [
structs.IQCarControl.Param(
key=p.key,
value=bytes(p.value),
type=str(p.type),
) for p in struct.params
]
struct_dataclass.angleOffsetDeg = float(getattr(struct, "angleOffsetDeg", 0.0))
if include_leads:
lead_one = struct.leadOne
struct_dataclass.leadOne = structs.LeadData(
dRel=lead_one.dRel,
yRel=lead_one.yRel,
vRel=lead_one.vRel,
aRel=lead_one.aRel,
vLead=lead_one.vLead,
dPath=lead_one.dPath,
vLat=lead_one.vLat,
vLeadK=lead_one.vLeadK,
aLeadK=lead_one.aLeadK,
fcw=lead_one.fcw,
status=lead_one.status,
aLeadTau=lead_one.aLeadTau,
modelProb=lead_one.modelProb,
radar=lead_one.radar,
radarTrackId=lead_one.radarTrackId,
)
lead_two = struct.leadTwo
struct_dataclass.leadTwo = structs.LeadData(
dRel=lead_two.dRel,
yRel=lead_two.yRel,
vRel=lead_two.vRel,
aRel=lead_two.aRel,
vLead=lead_two.vLead,
dPath=lead_two.dPath,
vLat=lead_two.vLat,
vLeadK=lead_two.vLeadK,
aLeadK=lead_two.aLeadK,
fcw=lead_two.fcw,
status=lead_two.status,
aLeadTau=lead_two.aLeadTau,
modelProb=lead_two.modelProb,
radar=lead_two.radar,
radarTrackId=lead_two.radarTrackId,
)
struct_dataclass.angleOffsetDeg = struct.angleOffsetDeg
# VW PQ "Blend IQ.Pilot + Stock ACC Radar" intent must survive the conversion or the RadarHandler
# never sees the engage/cancel/passthrough request.
struct_dataclass.radarBlendActive = bool(getattr(struct, "radarBlendActive", False))
struct_dataclass.radarEngageReq = bool(getattr(struct, "radarEngageReq", False))
struct_dataclass.radarCancelReq = bool(getattr(struct, "radarCancelReq", False))
struct_dataclass.useRadarAccel = bool(getattr(struct, "useRadarAccel", False))
struct_dataclass.radarSetSpeedKph = float(getattr(struct, "radarSetSpeedKph", 0.0))
struct_dataclass.radarGapBars = int(getattr(struct, "radarGapBars", 0))
return struct_dataclass

View File

@@ -0,0 +1,92 @@
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
from iqdbc.car import structs as _dbc
from iqpilot.common.params import Params as _Store, UnknownKeyName as _UnknownKey
from iqpilot.common.swaglog import cloudlog as _log
from iqpilot.selfdrive.controls.lib.latcontrol_torque import get_nn_model_path as _resolve_nn
import iqpilot.system.sentry as _telemetry
_ANGLE = _dbc.CarParams.SteerControlType.angle
# Port tunables surfaced to the fingerprint step, flat so the read is one pass.
_TUNABLES = (
"IQHyundaiLongTune",
"IQSubaruCreepAssist",
"IQSubaruCreepAssistManualBrake",
"IQTeslaFsdVisualization",
"IQTeslaTorqueBlend",
"IQToyotaFactoryLong",
"ToyotaSnGHack",
)
def initialize_params(store):
return [{name: store.get(name, return_default=True)} for name in _TUNABLES]
def log_fingerprint(cp) -> None:
ident = cp.carFingerprint
if ident == "MOCK":
_telemetry.capture_fingerprint_mock()
else:
_telemetry.capture_fingerprint(ident, cp.brand)
def set_speed_limit_controller_availability(cp, cp_iq, store=None) -> bool:
"""Gate the speed-limit controller off on platforms that can't run it, dropping a
stuck 'control' mode down to 'warning'."""
store = store or _Store()
brand = cp.brand
off = (brand == "rivian"
or (brand == "tesla" and store.get_bool("IsReleaseIqBranch"))
or (not cp.openpilotLongitudinalControl and cp_iq.pcmCruiseSpeed))
if off and store.get("IQSpeedAssistMode", return_default=True) == 3: # control -> warning
store.put("IQSpeedAssistMode", 2)
return not off
def _stamp_lateral_model(cp, cp_iq, store) -> bool:
where, label, precise = _resolve_nn(cp)
nn = cp_iq.iqLateralNet
nn.model.path, nn.model.name, nn.fuzzyFingerprint = where, label, not precise
if label == "MOCK":
_log.error({"nnff event": "car doesn't match any Neural Network model"})
return False
return cp.steerControlType != _ANGLE and store.get_bool("NeuralNetworkFeedForward")
def _cleanup_unsupported_params(cp, cp_iq, store=None) -> None:
store = store or _Store()
doomed = {
"NeuralNetworkFeedForward": cp.steerControlType == _ANGLE,
"LongIncrementsEnabled": not cp.openpilotLongitudinalControl and cp_iq.pcmCruiseSpeed,
}
for name, gone in doomed.items():
if gone:
_log.warning(f"unsupported on this port, clearing {name}")
store.remove(name)
set_speed_limit_controller_availability(cp, cp_iq, store)
def _apply_radar_scan_switch(cp, store) -> None:
if cp.brand != "honda" or cp.radarUnavailable:
return
try:
switch = store.get("IQHondaRadarScan")
except _UnknownKey:
# params store predates the key (mid-update): the switch defaults on
return
# opt-out kill switch: only an explicit "0" disables, so a never-materialized param stays on
if switch in (b"0", "0"):
_log.warning("IQHondaRadarScan disabled, running without the radar object scan")
cp.radarUnavailable = True
def apply_iq_car_config(ci, store=None) -> None:
store = store or _Store()
if _stamp_lateral_model(ci.CP, ci.CP_IQ, store):
ci.configure_torque_tune(ci.CP.carFingerprint, ci.CP.lateralTuning)
_cleanup_unsupported_params(ci.CP, ci.CP_IQ, store)
_apply_radar_scan_switch(ci.CP, store)

View File

@@ -0,0 +1,58 @@
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
from dataclasses import dataclass
from iqpilot.common.params import Params
# Cruise set-speed step (in the caller's working unit, kph or the imperial increment)
# a user is allowed to dial in for the accel/decel cruise buttons.
MIN_BUTTON_STEP = 1
MAX_BUTTON_STEP = 10
# Once the resolved step reaches this size, we snap the set speed to the nearest
# multiple of the step (e.g. a step of 5 lands on 45/50/55...) instead of just
# adding it on top of whatever odd number the set speed currently sits at.
SNAP_TO_GRID_THRESHOLD = 5
# Stock behavior (feature disabled): tap moves by one unit, a held button moves
# five times faster. This mirrors what every other unmodified button-input car
# already does, so it's kept as the fallback rather than living in this module.
STOCK_HOLD_MULTIPLIER = 5
@dataclass(frozen=True)
class LongIncrementConfig:
enabled: bool
tap_step: int
hold_step: int
def _clamp_step(value) -> int:
try:
step = int(value)
except (TypeError, ValueError):
return MIN_BUTTON_STEP
return min(max(step, MIN_BUTTON_STEP), MAX_BUTTON_STEP)
def read_long_increment_config(params: Params) -> LongIncrementConfig:
return LongIncrementConfig(
enabled=params.get_bool("LongIncrementsEnabled"),
tap_step=_clamp_step(params.get("LongIncrementTapStep", return_default=True)),
hold_step=_clamp_step(params.get("LongIncrementHoldStep", return_default=True)),
)
def resolve_button_step(config: LongIncrementConfig, held: bool, unit_step: float) -> tuple[bool, float]:
"""
Turn a single tap/hold cruise button event into a (snap_to_grid, delta) pair,
where delta is expressed in the same unit as unit_step (kph, or the mph-derived
increment used for imperial cars).
"""
if not config.enabled:
return held, unit_step * (STOCK_HOLD_MULTIPLIER if held else 1)
multiplier = config.hold_step if held else config.tap_step
snap_to_grid = multiplier >= SNAP_TO_GRID_THRESHOLD
return snap_to_grid, unit_step * multiplier

View File

@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
from iqpilot.common.params import Params
from iqpilot.common.swaglog import cloudlog
from iqpilot.selfdrive.car.vehicle_catalog import load_catalog
def refresh_car_list_param() -> None:
platforms = load_catalog()
if not platforms:
cloudlog.warning("vehicle catalog not found; leaving CarList param unchanged")
return
params = Params()
if params.get("CarList") == platforms:
cloudlog.warning("CarList param already current, nothing to write")
return
params.put("CarList", platforms)
cloudlog.warning("CarList param refreshed from vehicle catalog")
if __name__ == "__main__":
refresh_car_list_param()

View File

@@ -0,0 +1 @@
*.bz2

View File

View File

@@ -0,0 +1,11 @@
#!/usr/bin/env bash
SCRIPT_DIR=$(dirname "$0")
BASEDIR=$(realpath "$SCRIPT_DIR/../../../../")
cd $BASEDIR
export MAX_EXAMPLES=300
export INTERNAL_SEG_CNT=300
export INTERNAL_SEG_LIST=selfdrive/car/tests/test_models_segs.txt
cd iqpilot/selfdrive/car/tests && pytest test_models.py test_car_interfaces.py

View File

@@ -0,0 +1,152 @@
import os
import pytest
import hypothesis.strategies as st
from hypothesis import Phase, given, settings
from parameterized import parameterized
from types import SimpleNamespace
from iqpilot.cereal import car, custom
from iqdbc.car import DT_CTRL
from iqdbc.car.structs import CarParams
from iqdbc.car.car_helpers import interfaces
from iqdbc.car.tests.test_car_interfaces import get_fuzzy_car_interface, get_fuzzy_strategy
from iqdbc.car.mock.values import CAR as MOCK
from iqdbc.car.values import PLATFORMS
from iqpilot.selfdrive.car.card import run_optional_pre_init
from iqpilot.selfdrive.car.helpers import convert_iq_car_control, convert_iq_car_control_compact
from iqpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
from iqpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID
from iqpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque
from iqpilot.selfdrive.controls.lib.longcontrol import LongControl
from iqpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator
from iqpilot.selfdrive.car import interfaces as iqpilot_interfaces
MAX_EXAMPLES = int(os.environ.get('MAX_EXAMPLES', '60'))
VW_MLB_LONG_APPLY_EXCLUDE = {"AUDI_Q5_MK1", "PORSCHE_MACAN_MK1"}
SIGNED_RUNTIME_BRANDS = {"tesla", "volkswagen"}
SIGNED_RUNTIME_PLATFORMS = tuple(car_name for car_name in sorted(PLATFORMS)
if interfaces[car_name].__module__.split(".")[-2] in SIGNED_RUNTIME_BRANDS)
PUBLIC_INTERFACE_PLATFORMS = tuple(car_name for car_name in sorted(PLATFORMS)
if car_name not in SIGNED_RUNTIME_PLATFORMS)
def exercise_car_interface(car_name, draw):
car_interface = get_fuzzy_car_interface(car_name, draw)
if car_name in VW_MLB_LONG_APPLY_EXCLUDE:
car_interface.CP.openpilotLongitudinalControl = False
car_params = car_interface.CP.as_reader()
car_params_iq = car_interface.CP_IQ
iqpilot_interfaces.apply_iq_car_config(car_interface)
cc_msg = FuzzyGenerator.get_random_msg(draw, car.CarControl, real_floats=True)
cc_sp_msg = FuzzyGenerator.get_random_msg(draw, custom.IQCarControl, real_floats=True)
now_nanos = 0
CC = car.CarControl.new_message(**cc_msg).as_reader()
CC_IQ = convert_iq_car_control(custom.IQCarControl.new_message(**cc_sp_msg).as_reader())
for _ in range(10):
car_interface.update([])
car_interface.apply(CC, CC_IQ, now_nanos)
now_nanos += DT_CTRL * 1e9
CC = car.CarControl.new_message(**cc_msg)
CC.enabled = True
CC.latActive = True
CC.longActive = True
CC = CC.as_reader()
for _ in range(10):
car_interface.update([])
car_interface.apply(CC, CC_IQ, now_nanos)
now_nanos += DT_CTRL * 1e9
LongControl(car_params, car_params_iq)
if car_params.steerControlType == CarParams.SteerControlType.angle:
LatControlAngle(car_params, car_params_iq, car_interface, DT_CTRL)
elif car_params.lateralTuning.which() == 'pid':
LatControlPID(car_params, car_params_iq, car_interface, DT_CTRL)
elif car_params.lateralTuning.which() == 'torque':
LatControlTorque(car_params, car_params_iq, car_interface, DT_CTRL)
@pytest.mark.car_ports
class TestCarInterfaces:
# FIXME: Due to the lists used in carParams, Phase.target is very slow and will cause
# many generated examples to overrun when max_examples > ~20, don't use it
@parameterized.expand([(car,) for car in PUBLIC_INTERFACE_PLATFORMS] + [MOCK.MOCK])
@settings(max_examples=MAX_EXAMPLES, deadline=None,
phases=(Phase.reuse, Phase.generate, Phase.shrink))
@given(data=st.data())
def test_car_interfaces(self, car_name, data):
exercise_car_interface(car_name, data.draw)
@parameterized.expand([(car,) for car in SIGNED_RUNTIME_PLATFORMS])
@settings(max_examples=MAX_EXAMPLES, deadline=None,
phases=(Phase.reuse, Phase.generate, Phase.shrink))
@given(data=st.data())
def test_public_car_params(self, car_name, data):
params = data.draw(get_fuzzy_strategy())
params['fingerprints'] |= {key + 1: params['fingerprints'][0] for key in range(6)}
car_interface = interfaces[car_name]
car_params = car_interface.get_params(car_name, params['fingerprints'], params['car_fw'],
alpha_long=params['alpha_long'], is_release=False, docs=False)
car_params_iq = car_interface.get_params_iq(car_params, car_name, params['fingerprints'], params['car_fw'],
alpha_long=params['alpha_long'], is_release_iq=False, docs=False)
assert car_params.mass > 1
assert car_params.wheelbase > 0
assert car_params.maxLateralAccel > 0
assert car_params_iq is not None
def test_convert_iq_car_control_compact_skips_leads():
msg = custom.IQCarControl.new_message()
msg.aol.enabled = True
msg.aol.active = True
msg.aol.available = True
param = msg.init("params", 1)
param[0].key = "enhancedStockLongitudinalControl.setSpeedKph"
param[0].type = "float"
param[0].value = b"42.0"
msg.leadOne.dRel = 42.0
msg.leadOne.status = True
msg.leadTwo.dRel = 84.0
msg.leadTwo.status = True
compact = convert_iq_car_control_compact(msg.as_reader(), include_leads=False)
assert compact.aol.enabled
assert compact.aol.active
assert compact.aol.available
assert len(compact.params) == 1
assert compact.params[0].key == "enhancedStockLongitudinalControl.setSpeedKph"
assert compact.params[0].type == "float"
assert compact.params[0].value == b"42.0"
assert compact.leadOne.dRel == 0.0
assert not compact.leadOne.status
assert compact.leadTwo.dRel == 0.0
assert not compact.leadTwo.status
full = convert_iq_car_control_compact(msg.as_reader(), include_leads=True)
assert full.leadOne.dRel == 42.0
assert full.leadOne.status
assert full.leadTwo.dRel == 84.0
assert full.leadTwo.status
def test_run_optional_pre_init_skips_missing_hook():
ci = SimpleNamespace()
run_optional_pre_init(ci, car.CarParams(), custom.IQCarParams(), (lambda wait_for_one=False: [], lambda msgs: None))
def test_run_optional_pre_init_calls_hook():
called = []
class CI:
@staticmethod
def pre_init(CP, CP_IQ, can_recv, can_send):
called.append((CP, CP_IQ, can_recv, can_send))
can_callbacks = (lambda wait_for_one=False: [], lambda msgs: None)
cp = car.CarParams()
cp_iq = custom.IQCarParams()
run_optional_pre_init(CI(), cp, cp_iq, can_callbacks)
assert called == [(cp, cp_iq, *can_callbacks)]

View File

@@ -0,0 +1,117 @@
from types import SimpleNamespace
from iqpilot.cereal import log
from iqdbc.car import structs
from iqpilot.selfdrive.car.car_specific import CarSpecificEvents
EventName = log.OnroadEvent.EventName
GearShifter = structs.CarState.GearShifter
def make_car_state(**overrides):
base = dict(
doorOpen=False,
seatbeltUnlatched=False,
gearShifter=GearShifter.drive,
cruiseState=SimpleNamespace(available=True, enabled=False, nonAdaptive=False),
cruiseFaultLateralMode=False,
espDisabled=False,
espActive=False,
stockFcw=False,
stockAeb=False,
stockLkas=False,
vEgo=15.0,
brakeHoldActive=False,
parkingBrake=False,
accFaulted=False,
steeringPressed=False,
steeringDisengage=False,
brakePressed=False,
standstill=False,
gasPressed=False,
vehicleSensorsInvalid=False,
invalidLkasSetting=False,
lowSpeedAlert=False,
buttonEnable=False,
buttonEvents=[],
steerFaultTemporary=False,
steerFaultPermanent=False,
blockPcmEnable=False,
)
base.update(overrides)
return SimpleNamespace(**base)
def test_pcm_disable_suppressed_during_cruise_fault_lateral_mode():
cp = SimpleNamespace(
brand="volkswagen",
openpilotLongitudinalControl=False,
minEnableSpeed=0.0,
pcmCruise=True,
carFingerprint="MOCK",
)
events = CarSpecificEvents(cp)
cs = make_car_state(cruiseFaultLateralMode=True)
cs_prev = make_car_state(cruiseState=SimpleNamespace(available=True, enabled=True, nonAdaptive=False))
out = events.update(cs, cs_prev, SimpleNamespace(actuators=SimpleNamespace(accel=0.0)))
assert not out.has(EventName.pcmDisable)
def test_cruise_fault_lateral_mode_replaces_acc_faulted_alert():
cp = SimpleNamespace(
brand="volkswagen",
openpilotLongitudinalControl=False,
minEnableSpeed=0.0,
pcmCruise=True,
carFingerprint="MOCK",
)
events = CarSpecificEvents(cp)
cs = make_car_state(accFaulted=True, cruiseFaultLateralMode=True)
cs_prev = make_car_state()
out = events.update(cs, cs_prev, SimpleNamespace(actuators=SimpleNamespace(accel=0.0)))
assert out.has(EventName.cruiseFaultLateralAllowed)
assert not out.has(EventName.accFaulted)
def test_acc_faulted_still_emitted_without_cruise_fault_lateral_mode():
cp = SimpleNamespace(
brand="volkswagen",
openpilotLongitudinalControl=False,
minEnableSpeed=0.0,
pcmCruise=True,
carFingerprint="MOCK",
)
events = CarSpecificEvents(cp)
cs = make_car_state(accFaulted=True)
cs_prev = make_car_state()
out = events.update(cs, cs_prev, SimpleNamespace(actuators=SimpleNamespace(accel=0.0)))
assert out.has(EventName.accFaulted)
assert not out.has(EventName.cruiseFaultLateralAllowed)
def test_pcm_disable_still_emitted_without_cruise_fault_lateral_mode():
cp = SimpleNamespace(
brand="volkswagen",
openpilotLongitudinalControl=False,
minEnableSpeed=0.0,
pcmCruise=True,
carFingerprint="MOCK",
)
events = CarSpecificEvents(cp)
cs = make_car_state()
cs_prev = make_car_state(cruiseState=SimpleNamespace(available=True, enabled=True, nonAdaptive=False))
out = events.update(cs, cs_prev, SimpleNamespace(actuators=SimpleNamespace(accel=0.0)))
assert out.has(EventName.pcmDisable)

View File

@@ -0,0 +1,175 @@
import pytest
import itertools
import numpy as np
from parameterized import parameterized_class
from iqpilot.cereal import log
from iqpilot.selfdrive.car.cruise import VCruiseHelper, V_CRUISE_MIN, V_CRUISE_MAX, V_CRUISE_INITIAL, IMPERIAL_INCREMENT
from iqpilot.cereal import car, custom
from iqpilot.common.constants import CV
from iqpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver
ButtonEvent = car.CarState.ButtonEvent
ButtonType = car.CarState.ButtonEvent.Type
def run_cruise_simulation(cruise, e2e, personality, t_end=20.):
man = Maneuver(
'',
duration=t_end,
initial_speed=max(cruise - 1., 0.0),
lead_relevancy=True,
initial_distance_lead=100,
cruise_values=[cruise],
prob_lead_values=[0.0],
breakpoints=[0.],
e2e=e2e,
personality=personality,
)
valid, output = man.evaluate()
assert valid
return output[-1, 3]
@parameterized_class(("e2e", "personality", "speed"), itertools.product(
[True, False], # e2e
log.LongitudinalPersonality.schema.enumerants, # personality
[5,35])) # speed
class TestCruiseSpeed:
def test_cruise_speed(self):
print(f'Testing {self.speed} m/s')
cruise_speed = float(self.speed)
simulation_steady_state = run_cruise_simulation(cruise_speed, self.e2e, self.personality)
assert simulation_steady_state == pytest.approx(cruise_speed, abs=.01), f'Did not reach {self.speed} m/s'
# TODO: test pcmCruise and pcmCruiseSpeed
@parameterized_class(('pcm_cruise', 'pcm_cruise_speed'), [(False, True)])
class TestVCruiseHelper:
def setup_method(self):
self.CP = car.CarParams(pcmCruise=self.pcm_cruise)
self.CP_IQ = custom.IQCarParams(pcmCruiseSpeed=self.pcm_cruise_speed)
self.v_cruise_helper = VCruiseHelper(self.CP, self.CP_IQ)
self.reset_cruise_speed_state()
def reset_cruise_speed_state(self):
self.v_cruise_helper.params.put("IQE2ESetSpeedMode", 0)
self.v_cruise_helper.params.put_bool("IQE2ESetSpeedUseCurrent", False)
self.v_cruise_helper.params.put("IQE2ESetSpeedMph", 65)
self.v_cruise_helper.read_custom_set_speed_params()
# Two resets previous cruise speed
for _ in range(2):
self.v_cruise_helper.update_v_cruise(car.CarState(cruiseState={"available": False}), enabled=False, is_metric=False)
def enable(self, v_ego, experimental_mode, iq_dynamic_mode):
# Simulates user pressing set with a current speed
self.v_cruise_helper.initialize_v_cruise(car.CarState(vEgo=v_ego), experimental_mode, iq_dynamic_mode)
def test_adjust_speed(self):
"""
Asserts speed changes on falling edges of buttons.
"""
self.enable(V_CRUISE_INITIAL * CV.KPH_TO_MS, False, False)
for btn in (ButtonType.accelCruise, ButtonType.decelCruise):
for pressed in (True, False):
CS = car.CarState(cruiseState={"available": True})
CS.buttonEvents = [ButtonEvent(type=btn, pressed=pressed)]
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
assert pressed == (self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last)
def test_rising_edge_enable(self):
"""
Some car interfaces may enable on rising edge of a button,
ensure we don't adjust speed if enabled changes mid-press.
"""
# NOTE: enabled is always one frame behind the result from button press in controlsd
for enabled, pressed in ((False, False),
(False, True),
(True, False)):
CS = car.CarState(cruiseState={"available": True})
CS.buttonEvents = [ButtonEvent(type=ButtonType.decelCruise, pressed=pressed)]
self.v_cruise_helper.update_v_cruise(CS, enabled=enabled, is_metric=False)
if pressed:
self.enable(V_CRUISE_INITIAL * CV.KPH_TO_MS, False, False)
# Expected diff on enabling. Speed should not change on falling edge of pressed
assert not pressed == self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last
def test_resume_in_standstill(self):
"""
Asserts we don't increment set speed if user presses resume/accel to exit cruise standstill.
"""
self.enable(0, False, False)
for standstill in (True, False):
for pressed in (True, False):
CS = car.CarState(cruiseState={"available": True, "standstill": standstill})
CS.buttonEvents = [ButtonEvent(type=ButtonType.accelCruise, pressed=pressed)]
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
# speed should only update if not at standstill and button falling edge
should_equal = standstill or pressed
assert should_equal == (self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last)
def test_set_gas_pressed(self):
"""
Asserts pressing set while enabled with gas pressed sets
the speed to the maximum of vEgo and current cruise speed.
"""
for v_ego in np.linspace(0, 100, 101):
self.reset_cruise_speed_state()
self.enable(V_CRUISE_INITIAL * CV.KPH_TO_MS, False, False)
# first decrement speed, then perform gas pressed logic
expected_v_cruise_kph = self.v_cruise_helper.v_cruise_kph - IMPERIAL_INCREMENT
expected_v_cruise_kph = max(expected_v_cruise_kph, v_ego * CV.MS_TO_KPH) # clip to min of vEgo
expected_v_cruise_kph = float(np.clip(round(expected_v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX))
CS = car.CarState(vEgo=float(v_ego), gasPressed=True, cruiseState={"available": True})
CS.buttonEvents = [ButtonEvent(type=ButtonType.decelCruise, pressed=False)]
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
# TODO: fix skipping first run due to enabled on rising edge exception
if v_ego == 0.0:
continue
assert expected_v_cruise_kph == self.v_cruise_helper.v_cruise_kph
def test_initialize_v_cruise(self):
"""
Asserts allowed cruise speeds on enabling with SET.
"""
for experimental_mode in (True, False):
for iq_dynamic_mode in (True, False):
for v_ego in np.linspace(0, 100, 101):
self.reset_cruise_speed_state()
assert not self.v_cruise_helper.v_cruise_initialized
self.enable(float(v_ego), experimental_mode, iq_dynamic_mode)
assert V_CRUISE_INITIAL <= self.v_cruise_helper.v_cruise_kph <= V_CRUISE_MAX
assert self.v_cruise_helper.v_cruise_initialized
def test_iq_mode_fixed_set_speed(self):
self.v_cruise_helper.params.put("IQE2ESetSpeedMode", 1)
self.v_cruise_helper.params.put_bool("IQE2ESetSpeedUseCurrent", False)
self.v_cruise_helper.params.put("IQE2ESetSpeedMph", 72)
self.v_cruise_helper.read_custom_set_speed_params()
self.enable(30 * CV.MPH_TO_MS, True, False)
assert self.v_cruise_helper.v_cruise_kph == int(round(72 * CV.MPH_TO_KPH))
def test_iq_mode_current_speed_override(self):
self.v_cruise_helper.params.put("IQE2ESetSpeedMode", 1)
self.v_cruise_helper.params.put_bool("IQE2ESetSpeedUseCurrent", True)
self.v_cruise_helper.params.put("IQE2ESetSpeedMph", 72)
self.v_cruise_helper.read_custom_set_speed_params()
self.enable(47 * CV.MPH_TO_MS, True, False)
assert self.v_cruise_helper.v_cruise_kph == int(round(47 * CV.MPH_TO_KPH))

View File

@@ -0,0 +1,27 @@
import os
from iqpilot.common.basedir import BASEDIR
from iqdbc.car.docs import generate_cars_md, get_all_car_docs
from iqdbc.lvbs.car.car_catalog import build_car_catalog
from iqpilot.selfdrive.debug.dump_car_docs import dump_car_docs
from iqpilot.selfdrive.debug.print_docs_diff import print_car_docs_diff
from iqpilot.selfdrive.car.docs import CARS_MD_TEMPLATE
from iqpilot.selfdrive.car.vehicle_catalog import load_catalog
class TestCarDocs:
@classmethod
def setup_class(cls):
cls.all_cars = get_all_car_docs()
def test_generator(self):
generate_cars_md(self.all_cars, CARS_MD_TEMPLATE)
def test_docs_diff(self):
dump_path = os.path.join(BASEDIR, "iqpilot", "selfdrive", "car", "tests", "cars_dump")
dump_car_docs(dump_path)
print_car_docs_diff(dump_path)
os.remove(dump_path)
def test_vehicle_catalog(self):
assert load_catalog() == build_car_catalog()

View File

@@ -0,0 +1,50 @@
from dataclasses import dataclass
from enum import Enum
import pytest
from iqdbc.car import structs
from iqdbc.car.hyundai.values import HyundaiFlagsIQ
from iqpilot.selfdrive.car.helpers import asdictref, convert_to_capnp
class SampleEnum(Enum):
value = 7
@dataclass
class SampleStruct:
enum: SampleEnum
values: tuple[int, ...]
mapping: dict[str, list[SampleEnum]]
def test_convert_to_capnp_normalizes_enum_values():
params = structs.IQCarParams(flags=HyundaiFlagsIQ.HAS_LFA_BUTTON)
assert asdictref(params)["flags"] == HyundaiFlagsIQ.HAS_LFA_BUTTON.value
assert convert_to_capnp(params).flags == HyundaiFlagsIQ.HAS_LFA_BUTTON.value
def test_asdictref_preserves_container_types_and_resolves_enums():
source = SampleStruct(SampleEnum.value, (1, 2), {"items": [SampleEnum.value]})
converted = asdictref(source)
assert converted == {"enum": 7, "values": (1, 2), "mapping": {"items": [7]}}
assert isinstance(converted["values"], tuple)
assert isinstance(converted["mapping"]["items"], list)
def test_asdictref_rejects_non_dataclass_values():
with pytest.raises(TypeError, match="dataclass instances"):
asdictref(object())
def test_convert_to_capnp_supports_iq_car_state():
state = convert_to_capnp(structs.IQCarState())
assert state.speedLimit == 0
assert not state.accelPressed
def test_convert_to_capnp_rejects_unknown_dataclass():
with pytest.raises(ValueError, match="Unsupported struct type"):
convert_to_capnp(SampleStruct(SampleEnum.value, (), {}))

View File

@@ -0,0 +1,119 @@
import json
from types import SimpleNamespace
from iqpilot.selfdrive.car.card import Car
class DummyParams:
def __init__(self):
self.values: dict[str, object] = {}
def get(self, key: str):
return self.values.get(key)
def put_nonblocking(self, key: str, value) -> None:
self.values[key] = value
class HondaLikeController:
def __init__(self):
self.gasfactor = 1.0
self.windfactor = 1.0
def make_car(controller):
car = object.__new__(Car)
car.params = DummyParams()
car.CI = SimpleNamespace(CC=controller)
car.CP = SimpleNamespace(carFingerprint="HONDA_CRV_6G")
return car
class TestLearnedFactorPersistence:
def test_save_then_seed_round_trip(self):
car = make_car(HondaLikeController())
car.CI.CC.gasfactor = 1.37
car.CI.CC.windfactor = 0.84
car._save_learned_factors()
fresh = make_car(HondaLikeController())
fresh.params.values = car.params.values
fresh._seed_learned_factors()
assert fresh.CI.CC.gasfactor == 1.37
assert fresh.CI.CC.windfactor == 0.84
def test_factors_keyed_per_fingerprint(self):
car = make_car(HondaLikeController())
car.CI.CC.gasfactor = 2.0
car._save_learned_factors()
other = make_car(HondaLikeController())
other.params.values = car.params.values
other.CP = SimpleNamespace(carFingerprint="HONDA_CIVIC_BOSCH")
other._seed_learned_factors()
assert other.CI.CC.gasfactor == 1.0
other.CI.CC.gasfactor = 0.5
other._save_learned_factors()
stored = other.params.values["IQLongLearnedFactors"]
assert stored["HONDA_CRV_6G"]["gasfactor"] == 2.0
assert stored["HONDA_CIVIC_BOSCH"]["gasfactor"] == 0.5
def test_seed_ignores_corrupt_or_nonfinite_values(self):
car = make_car(HondaLikeController())
car.params.values["IQLongLearnedFactors"] = "not json"
car._seed_learned_factors()
assert car.CI.CC.gasfactor == 1.0
car.params.values["IQLongLearnedFactors"] = json.dumps({"HONDA_CRV_6G": {"gasfactor": float("nan"), "windfactor": "x"}})
car._seed_learned_factors()
assert car.CI.CC.gasfactor == 1.0
assert car.CI.CC.windfactor == 1.0
def test_noop_for_controllers_without_factors(self):
car = make_car(SimpleNamespace())
car._seed_learned_factors()
car._save_learned_factors()
assert "IQLongLearnedFactors" not in car.params.values
car = make_car(None)
car._seed_learned_factors()
car._save_learned_factors()
assert "IQLongLearnedFactors" not in car.params.values
class TestLearnedFactorRealParams:
"""Round-trips through the actual params store so the pyx JSON type marshaling is exercised:
JSON params take dicts on put and come back parsed on get."""
def make_real_car(self, tmp_path, controller):
from iqpilot.common.params import Params
car = object.__new__(Car)
car.params = Params(str(tmp_path))
car.CI = SimpleNamespace(CC=controller)
car.CP = SimpleNamespace(carFingerprint="HONDA_CIVIC_2022")
return car
def test_save_then_seed_through_real_params(self, tmp_path):
import time
car = self.make_real_car(tmp_path, HondaLikeController())
car.CI.CC.gasfactor = 1.31
car.CI.CC.windfactor = 0.88
car._save_learned_factors()
time.sleep(0.3)
fresh = self.make_real_car(tmp_path, HondaLikeController())
fresh._seed_learned_factors()
assert fresh.CI.CC.gasfactor == 1.31
assert fresh.CI.CC.windfactor == 0.88
def test_repeated_saves_through_real_params(self, tmp_path):
import time
car = self.make_real_car(tmp_path, HondaLikeController())
for value in (1.1, 1.2, 1.3):
car.CI.CC.gasfactor = value
car._save_learned_factors()
time.sleep(0.3)
fresh = self.make_real_car(tmp_path, HondaLikeController())
fresh._seed_learned_factors()
assert fresh.CI.CC.gasfactor == 1.3

View File

@@ -0,0 +1,38 @@
from iqpilot.cereal import custom
from iqdbc.car import structs
from iqpilot.selfdrive.car.interfaces import _cleanup_unsupported_params
class DummyParams:
def __init__(self):
self.removed: list[str] = []
self.values: dict[str, object] = {}
def remove(self, key: str) -> None:
self.removed.append(key)
def get_bool(self, key: str) -> bool:
return bool(self.values.get(key, False))
def get(self, key: str, return_default: bool = False):
return self.values.get(key)
def put(self, key: str, value) -> None:
self.values[key] = value
class TestLongitudinalModePersistence:
def test_iq_dynamic_mode_is_not_removed_when_openpilot_long_is_unavailable(self):
params = DummyParams()
cp = structs.CarParams()
cp.openpilotLongitudinalControl = False
cp.steerControlType = structs.CarParams.SteerControlType.torque
cp_iq = custom.IQCarParams()
cp_iq.pcmCruiseSpeed = True
_cleanup_unsupported_params(cp, cp_iq, params)
assert "IQDynamicMode" not in params.removed
assert "LongIncrementsEnabled" in params.removed

View File

@@ -0,0 +1,547 @@
import time
import copy
import os
import pytest
import random
import unittest # noqa: TID251
from collections import defaultdict, Counter
import hypothesis.strategies as st
from hypothesis import Phase, given, settings
from iqdbc.car import DT_CTRL, gen_empty_fingerprint, structs
from iqdbc.can.parser import MAX_BAD_COUNTER
from iqdbc.car.can_definitions import CanData
from iqdbc.car.car_helpers import FRAME_FINGERPRINT, interfaces
from iqdbc.car.fingerprints import MIGRATION
from iqdbc.car.honda.values import CAR as HONDA, HondaFlags
from iqdbc.car.structs import car
from iqdbc.car.tests.routes import routes, CarTestRoute
from iqdbc.car.values import Platform
from iqpilot.common.basedir import BASEDIR
from iqpilot.common.params import Params
from iqpilot.selfdrive.pandad import can_capnp_to_list
from iqpilot.selfdrive.test.helpers import read_segment_list
from iqpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT
from iqpilot.tools.lib.logreader import LogReader, LogsUnavailable, openpilotci_source, internal_source, comma_api_source
from iqpilot.tools.lib.route import SegmentName
SafetyModel = car.CarParams.SafetyModel
SteerControlType = structs.CarParams.SteerControlType
NUM_JOBS = int(os.environ.get("NUM_JOBS", "1"))
JOB_ID = int(os.environ.get("JOB_ID", "0"))
INTERNAL_SEG_LIST = os.environ.get("INTERNAL_SEG_LIST", "")
INTERNAL_SEG_CNT = int(os.environ.get("INTERNAL_SEG_CNT", "0"))
MAX_EXAMPLES = int(os.environ.get("MAX_EXAMPLES", "300"))
CI = os.environ.get("CI", None) is not None
RELAY_TRANSITION_TIMEOUT_US = 10_000_000
PRIVATE_RUNTIME_BRANDS = {"tesla", "volkswagen"}
UNSUPPORTED_ROUTE_BRANDS = {"body"}
DASHCAM_ONLY_PLATFORMS = {
"BUICK_REGAL",
"GMC_YUKON",
"MAZDA_3",
"MAZDA_6",
"MAZDA_CX5",
"MAZDA_CX9",
"PSA_PEUGEOT_208",
"SUBARU_ASCENT_2023",
"SUBARU_CROSSTREK_HYBRID",
"SUBARU_FORESTER_2022",
"SUBARU_OUTBACK_2023",
}
@pytest.fixture(autouse=True)
def controls_ready_params(openpilot_function_fixture, tmp_path):
root = str(tmp_path)
os.mkdir(os.path.join(root, "d_tmp"))
os.symlink("d_tmp", os.path.join(root, "d"))
os.environ["PARAMS_ROOT"] = root
Params().put_bool("ControlsReady", True)
yield
def normalize_can_buses(can: tuple[int, list[CanData]], raw_can_keys: set[tuple[int, int]]) -> tuple[int, list[CanData]]:
timestamp, messages = can
return timestamp, [CanData(msg.address, msg.dat, msg.src % 128) for msg in messages
if msg.src < 128 or (msg.address, msg.src % 128) not in raw_can_keys]
def get_test_cases() -> list[tuple[str, CarTestRoute | None]]:
test_cases = []
if not len(INTERNAL_SEG_LIST):
for i, route in enumerate(sorted(routes, key=lambda item: (str(item.car_model), item.route, item.segment or -1))):
brand = interfaces[str(route.car_model)].__module__.split(".")[-2]
if brand not in PRIVATE_RUNTIME_BRANDS | UNSUPPORTED_ROUTE_BRANDS and i % NUM_JOBS == JOB_ID:
test_cases.append((str(route.car_model), route))
else:
segment_list = read_segment_list(os.path.join(BASEDIR, INTERNAL_SEG_LIST))
segment_list = random.sample(segment_list, INTERNAL_SEG_CNT or len(segment_list))
for platform, segment in segment_list:
platform = MIGRATION.get(platform, platform)
segment_name = SegmentName(segment)
test_cases.append((platform, CarTestRoute(segment_name.route_name.canonical_name, platform,
segment=segment_name.segment_num)))
return test_cases
@pytest.mark.slow
@pytest.mark.shared_download_cache
@pytest.mark.xdist_group_class_property('test_route')
class CarModelTestBase(unittest.TestCase):
__test__ = False
platform: Platform | None = None
test_route: CarTestRoute | None = None
can_msgs: list[tuple[int, list[CanData]]]
fingerprint: dict[int, dict[int, int]]
elm_frame: int | None
car_safety_mode_frame: int | None
@classmethod
def get_testing_data_from_logreader(cls, lr):
car_fw = []
can_msgs = []
cls.elm_frame = None
cls.car_safety_mode_frame = None
cls.fingerprint = gen_empty_fingerprint()
alpha_long = False
for msg in lr:
if msg.which() == "can":
can = can_capnp_to_list((msg.as_builder().to_bytes(),))[0]
can_msgs.append((can[0], [CanData(*can) for can in can[1]]))
if len(can_msgs) <= FRAME_FINGERPRINT:
for m in msg.can:
if m.src < 64:
cls.fingerprint[m.src][m.address] = len(m.dat)
elif msg.which() == "carParams":
car_fw = msg.carParams.carFw
if msg.carParams.openpilotLongitudinalControl:
alpha_long = True
if cls.platform is None:
live_fingerprint = msg.carParams.carFingerprint
cls.platform = MIGRATION.get(live_fingerprint, live_fingerprint)
# Log which can frame the panda safety mode left ELM327, for CAN validity checks
elif msg.which() == 'pandaStates':
for ps in msg.pandaStates:
if cls.elm_frame is None and ps.safetyModel != SafetyModel.elm327:
cls.elm_frame = len(can_msgs)
if cls.car_safety_mode_frame is None and ps.safetyModel not in \
(SafetyModel.elm327, SafetyModel.noOutput):
cls.car_safety_mode_frame = len(can_msgs)
elif msg.which() == 'pandaStateDEPRECATED':
if cls.elm_frame is None and msg.pandaStateDEPRECATED.safetyModel != SafetyModel.elm327:
cls.elm_frame = len(can_msgs)
if cls.car_safety_mode_frame is None and msg.pandaStateDEPRECATED.safetyModel not in \
(SafetyModel.elm327, SafetyModel.noOutput):
cls.car_safety_mode_frame = len(can_msgs)
assert len(can_msgs) > int(50 / DT_CTRL), "no can data found"
return car_fw, can_msgs, alpha_long
@classmethod
def get_testing_data(cls):
test_segs = (2, 1, 0)
if cls.test_route.segment is not None:
test_segs = (cls.test_route.segment,)
for seg in test_segs:
segment_range = f"{cls.test_route.route}/{seg}"
try:
sources = [internal_source] if len(INTERNAL_SEG_LIST) else [openpilotci_source, comma_api_source]
lr = LogReader(segment_range, sources=sources, sort_by_time=True)
return cls.get_testing_data_from_logreader(lr)
except (LogsUnavailable, AssertionError):
pass
raise Exception(f"Route: {repr(cls.test_route.route)} with segments: {test_segs} not found or no CAN msgs found. Is it uploaded and public?")
@classmethod
def setUpClass(cls):
car_fw, cls.can_msgs, alpha_long = cls.get_testing_data()
cls.raw_can_keys = {(msg.address, msg.src) for _, messages in cls.can_msgs for msg in messages if msg.src < 128}
# if relay is expected to be open in the route
cls.openpilot_enabled = cls.car_safety_mode_frame is not None
cls.CarInterface = interfaces[cls.platform]
cls.CP = cls.CarInterface.get_params(cls.platform, cls.fingerprint, car_fw, alpha_long, False, docs=False)
cls.CP_IQ = cls.CarInterface.get_params_iq(cls.CP, cls.platform, cls.fingerprint, car_fw, alpha_long, False, docs=False)
assert cls.CP
assert cls.CP_IQ
assert cls.CP.carFingerprint == cls.platform
os.environ["COMMA_CACHE"] = DEFAULT_DOWNLOAD_CACHE_ROOT
@classmethod
def tearDownClass(cls):
del cls.can_msgs
def setUp(self):
from iqdbc.safety.tests.libsafety import libsafety_py
self.libsafety_py = libsafety_py
self.CI = self.CarInterface(self.CP.copy(), copy.deepcopy(self.CP_IQ))
assert self.CI
# TODO: check safetyModel is in release panda build
self.safety = libsafety_py.libsafety
safety_param_iq = self.CP_IQ.iqSafetyFlags
self.safety.set_current_safety_param_iq(safety_param_iq)
cfg = self.CP.safetyConfigs[-1]
set_status = self.safety.set_safety_hooks(cfg.safetyModel.raw, cfg.safetyParam)
self.assertEqual(0, set_status, f"failed to set safetyModel {cfg}")
self.safety.init_tests()
def test_car_params(self):
self.assertFalse(self.CP.dashcamOnly)
# make sure car params are within a valid range
self.assertGreater(self.CP.mass, 1)
if self.CP.steerControlType != SteerControlType.angle:
tuning = self.CP.lateralTuning.which()
if tuning == 'pid':
self.assertTrue(len(self.CP.lateralTuning.pid.kpV))
elif tuning == 'torque':
self.assertTrue(self.CP.lateralTuning.torque.latAccelFactor > 0)
else:
raise Exception("unknown tuning")
def test_car_interface(self):
can_invalid_cnt = 0
invalid_reasons = Counter()
CC = structs.CarControl().as_reader()
CC_IQ = structs.IQCarControl()
for i, msg in enumerate(self.can_msgs):
CS, _ = self.CI.update(normalize_can_buses(msg, self.raw_can_keys))
self.CI.apply(CC, CC_IQ, msg[0])
# wait max of 2s for low frequency msgs to be seen
if i > 250:
can_invalid_cnt += not CS.canValid
if not CS.canValid:
for bus, cp in self.CI.can_parsers.items():
bus_timeout = cp.bus_timeout
for state in cp.message_states.values():
if state.counter_fail >= MAX_BAD_COUNTER:
invalid_reasons[f"{bus}:{state.name}:counter"] += 1
if not state.valid(cp._last_update_nanos, bus_timeout):
invalid_reasons[f"{bus}:{state.name}:timeout"] += 1
self.assertEqual(can_invalid_cnt, 0, dict(invalid_reasons))
def test_radar_interface(self):
RI = self.CarInterface.RadarInterface(self.CP, self.CP_IQ)
assert RI
# Since OBD port is multiplexed to bus 1 (commonly radar bus) while fingerprinting,
# start parsing CAN messages after we've left ELM mode and can expect CAN traffic
error_cnt = 0
for i, msg in enumerate(self.can_msgs[self.elm_frame:]):
rr: structs.RadarData | None = RI.update(normalize_can_buses(msg, self.raw_can_keys))
if rr is not None and i > 50:
error_cnt += rr.errors.canError
self.assertEqual(error_cnt, 0)
def test_panda_safety_rx_checks(self):
start_ts = self.can_msgs[0][0]
failed_addrs = Counter()
last_relay_malfunction_us = 0.
relay_open_inferred = False
for can_idx, can in enumerate(self.can_msgs):
# update panda timer
t = (can[0] - start_ts) / 1e3
self.safety.set_timer(int(t))
# run all msgs through the safety RX hook
for msg in can[1]:
if msg.src >= 64:
continue
to_send = self.libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat)
if self.safety.safety_rx_hook(to_send) != 1:
failed_addrs[hex(msg.address)] += 1
relay_malfunction = self.safety.get_relay_malfunction()
for msg in can[1]:
if msg.src >= 128 and (msg.address, msg.src % 128) not in self.raw_can_keys:
to_send = self.libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat)
self.safety.safety_rx_hook(to_send)
self.safety.set_relay_malfunction(relay_malfunction)
# ensure all msgs defined in the addr checks are valid
self.safety.safety_tick_current_safety_config()
if t > 1e6:
self.assertTrue(self.safety.safety_config_valid())
if self.car_safety_mode_frame is not None:
if can_idx >= self.car_safety_mode_frame:
self.assertFalse(self.safety.get_relay_malfunction())
else:
self.safety.set_relay_malfunction(False)
elif relay_open_inferred:
self.assertFalse(self.safety.get_relay_malfunction())
elif self.safety.get_relay_malfunction():
last_relay_malfunction_us = t
self.safety.set_relay_malfunction(False)
elif t - last_relay_malfunction_us > RELAY_TRANSITION_TIMEOUT_US:
relay_open_inferred = True
else:
self.safety.set_relay_malfunction(False)
self.assertFalse(len(failed_addrs), f"panda safety RX check failed: {failed_addrs}")
# ensure RX checks go invalid after small time with no traffic
self.safety.set_timer(int(t + (2*1e6)))
self.safety.safety_tick_current_safety_config()
self.assertFalse(self.safety.safety_config_valid())
def test_panda_safety_tx_cases(self, data=None):
"""Asserts we can tx common messages"""
def test_car_controller(car_control, car_control_iq):
def run_controller(CI):
now_nanos = 0
msgs_sent = 0
for _ in range(round(10.0 / DT_CTRL)):
CI.update([])
_, sendcan = CI.apply(car_control, car_control_iq, now_nanos)
now_nanos += DT_CTRL * 1e9
msgs_sent += len(sendcan)
for addr, dat, bus in sendcan:
to_send = self.libsafety_py.make_CANPacket(addr, bus % 4, dat)
self.assertTrue(self.safety.safety_tx_hook(to_send), (addr, dat, bus))
return msgs_sent
CI = self.CarInterface(self.CP, self.CP_IQ)
msgs_sent = run_controller(CI)
if msgs_sent == 0:
CI = self.CarInterface(self.CP, self.CP_IQ)
for can in self.can_msgs[self.elm_frame:]:
CI.update(normalize_can_buses(can, self.raw_can_keys))
msgs_sent = run_controller(CI)
# Make sure we attempted to send messages
self.assertGreater(msgs_sent, 50)
# Make sure we can send all messages while inactive
CC = structs.CarControl()
CC_IQ = structs.IQCarControl()
test_car_controller(CC.as_reader(), CC_IQ)
# Test cancel + general messages (controls_allowed=False & cruise_engaged=True)
self.safety.set_cruise_engaged_prev(True)
CC = structs.CarControl(cruiseControl=structs.CarControl.CruiseControl(cancel=True))
test_car_controller(CC.as_reader(), CC_IQ)
# Test resume + general messages (controls_allowed=True & cruise_engaged=True)
self.safety.set_controls_allowed(True)
CC = structs.CarControl(cruiseControl=structs.CarControl.CruiseControl(resume=True))
test_car_controller(CC.as_reader(), CC_IQ)
# Skip stdout/stderr capture with pytest, causes elevated memory usage
@pytest.mark.nocapture
@settings(max_examples=MAX_EXAMPLES, deadline=None,
phases=(Phase.reuse, Phase.generate, Phase.shrink))
@given(data=st.data())
def test_panda_safety_carstate_fuzzy(self, data):
"""
For each example, pick a random CAN message on the bus and fuzz its data,
checking for panda state mismatches.
"""
valid_addrs = [(addr, bus, size) for bus, addrs in self.fingerprint.items() for addr, size in addrs.items()]
address, bus, size = data.draw(st.sampled_from(valid_addrs))
msg_strategy = st.binary(min_size=size, max_size=size)
msgs = data.draw(st.lists(msg_strategy, min_size=20))
vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar
for n, dat in enumerate(msgs):
# due to panda updating state selectively, only edges are expected to match
# TODO: warm up CarState with real CAN messages to check edge of both sources
# (eg. toyota's gasPressed is the inverse of a signal being set)
prev_panda_gas = self.safety.get_gas_pressed_prev()
prev_panda_brake = self.safety.get_brake_pressed_prev()
prev_panda_regen_braking = self.safety.get_regen_braking_prev()
prev_panda_steering_disengage = self.safety.get_steering_disengage_prev()
prev_panda_vehicle_moving = self.safety.get_vehicle_moving()
prev_panda_vehicle_speed_min = self.safety.get_vehicle_speed_min()
prev_panda_vehicle_speed_max = self.safety.get_vehicle_speed_max()
prev_panda_cruise_engaged = self.safety.get_cruise_engaged_prev()
prev_panda_acc_main_on = self.safety.get_acc_main_on()
to_send = self.libsafety_py.make_CANPacket(address, bus, dat)
self.safety.safety_rx_hook(to_send)
can = [(int(time.monotonic() * 1e9), [CanData(address=address, dat=dat, src=bus)])]
CS, _ = self.CI.update(can)
if n < 5: # CANParser warmup time
continue
if self.safety.get_gas_pressed_prev() != prev_panda_gas:
self.assertEqual(CS.gasPressed, self.safety.get_gas_pressed_prev())
if self.safety.get_brake_pressed_prev() != prev_panda_brake:
# TODO: remove this exception once this mismatch is resolved
brake_pressed = CS.brakePressed
if CS.brakePressed and not self.safety.get_brake_pressed_prev():
if self.CP.carFingerprint in (HONDA.HONDA_PILOT, HONDA.HONDA_RIDGELINE) and CS.brake > 0.05:
brake_pressed = False
self.assertEqual(brake_pressed, self.safety.get_brake_pressed_prev())
if self.safety.get_regen_braking_prev() != prev_panda_regen_braking:
self.assertEqual(CS.regenBraking, self.safety.get_regen_braking_prev())
if self.safety.get_steering_disengage_prev() != prev_panda_steering_disengage:
self.assertEqual(CS.steeringDisengage, self.safety.get_steering_disengage_prev())
if self.safety.get_vehicle_moving() != prev_panda_vehicle_moving and not self.CP.notCar:
self.assertEqual(not CS.standstill, self.safety.get_vehicle_moving())
# check vehicle speed if angle control car or available
if self.safety.get_vehicle_speed_min() > 0 or self.safety.get_vehicle_speed_max() > 0:
vehicle_speed_seen = True
if vehicle_speed_seen and (self.safety.get_vehicle_speed_min() != prev_panda_vehicle_speed_min or
self.safety.get_vehicle_speed_max() != prev_panda_vehicle_speed_max):
v_ego_raw = CS.vEgoRaw / self.CP.wheelSpeedFactor
self.assertFalse(v_ego_raw > (self.safety.get_vehicle_speed_max() + 1e-3) or
v_ego_raw < (self.safety.get_vehicle_speed_min() - 1e-3))
if not (self.CP.brand == "honda" and not (self.CP.flags & HondaFlags.BOSCH)):
if self.safety.get_cruise_engaged_prev() != prev_panda_cruise_engaged:
self.assertEqual(CS.cruiseState.enabled, self.safety.get_cruise_engaged_prev())
if self.CP.brand == "honda":
if self.safety.get_acc_main_on() != prev_panda_acc_main_on:
self.assertEqual(CS.cruiseState.available, self.safety.get_acc_main_on())
def test_panda_safety_carstate(self):
"""
Assert that panda safety matches openpilot's carState
"""
# warm up pass, as initial states may be different
for can in self.can_msgs[:300]:
self.CI.update(normalize_can_buses(can, self.raw_can_keys))
for msg in filter(lambda m: m.src < 64, can[1]):
to_send = self.libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat)
self.safety.safety_rx_hook(to_send)
controls_allowed_prev = False
CS_prev = car.CarState.new_message()
checks = defaultdict(int)
standstill_mismatches = []
vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar
for idx, can in enumerate(self.can_msgs[300:]):
CS, _ = self.CI.update(normalize_can_buses(can, self.raw_can_keys))
CS = CS.as_reader()
for msg in filter(lambda m: m.src < 64, can[1]):
to_send = self.libsafety_py.make_CANPacket(msg.address, msg.src % 4, msg.dat)
ret = self.safety.safety_rx_hook(to_send)
self.assertEqual(1, ret, f"safety rx failed ({ret=}): {(msg.address, msg.src % 4)}")
# Skip first frame so CS_prev is properly initialized
if idx == 0:
CS_prev = CS
# Button may be left pressed in warm up period
if not self.CP.pcmCruise:
self.safety.set_controls_allowed(0)
continue
# TODO: check rest of panda's carstate (steering, ACC main on, etc.)
checks['gasPressed'] += CS.gasPressed != self.safety.get_gas_pressed_prev()
standstill_mismatch = CS.standstill == self.safety.get_vehicle_moving()
checks['standstill'] += standstill_mismatch and not self.CP.notCar
if standstill_mismatch and len(standstill_mismatches) < 10:
standstill_mismatches.append((idx, CS.standstill, self.safety.get_vehicle_moving(), CS.vEgoRaw,
self.safety.get_vehicle_speed_min(), self.safety.get_vehicle_speed_max()))
# check vehicle speed if angle control car or available
if self.safety.get_vehicle_speed_min() > 0 or self.safety.get_vehicle_speed_max() > 0:
vehicle_speed_seen = True
if vehicle_speed_seen:
v_ego_raw = CS.vEgoRaw / self.CP.wheelSpeedFactor
checks['vEgoRaw'] += (v_ego_raw > (self.safety.get_vehicle_speed_max() + 1e-3) or
v_ego_raw < (self.safety.get_vehicle_speed_min() - 1e-3))
# TODO: remove this exception once this mismatch is resolved
brake_pressed = CS.brakePressed
if CS.brakePressed and not self.safety.get_brake_pressed_prev():
if self.CP.carFingerprint in (HONDA.HONDA_PILOT, HONDA.HONDA_RIDGELINE) and CS.brake > 0.05:
brake_pressed = False
checks['brakePressed'] += brake_pressed != self.safety.get_brake_pressed_prev()
checks['regenBraking'] += CS.regenBraking != self.safety.get_regen_braking_prev()
checks['steeringDisengage'] += CS.steeringDisengage != self.safety.get_steering_disengage_prev()
if self.CP.pcmCruise:
# On most pcmCruise cars, openpilot's state is always tied to the PCM's cruise state.
# On Honda Nidec, we always engage on the rising edge of the PCM cruise state, but
# openpilot brakes to zero even if the min ACC speed is non-zero (i.e. the PCM disengages).
if self.CP.brand == "honda" and not (self.CP.flags & HondaFlags.BOSCH):
# only the rising edges are expected to match
if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled:
checks['controlsAllowed'] += not self.safety.get_controls_allowed()
else:
checks['controlsAllowed'] += not CS.cruiseState.enabled and self.safety.get_controls_allowed()
# TODO: fix notCar mismatch
if not self.CP.notCar:
checks['cruiseState'] += CS.cruiseState.enabled != self.safety.get_cruise_engaged_prev()
else:
# Check for user button enable on rising edge of controls allowed
button_enable = CS.buttonEnable and (not CS.brakePressed or CS.standstill)
mismatch = button_enable != (self.safety.get_controls_allowed() and not controls_allowed_prev)
checks['controlsAllowed'] += mismatch
controls_allowed_prev = self.safety.get_controls_allowed()
if button_enable and not mismatch:
self.safety.set_controls_allowed(False)
if self.CP.brand == "honda":
checks['mainOn'] += CS.cruiseState.available != self.safety.get_acc_main_on()
CS_prev = CS
failed_checks = {k: v for k, v in checks.items() if v > 0}
self.assertFalse(len(failed_checks),
f"panda safety doesn't agree with openpilot: {failed_checks}, standstill={standstill_mismatches}")
class DashcamCarModelTestBase(CarModelTestBase):
__test__ = False
test_panda_safety_rx_checks = None
test_panda_safety_tx_cases = None
test_panda_safety_carstate_fuzzy = None
test_panda_safety_carstate = None
def test_car_params(self):
self.assertTrue(self.CP.dashcamOnly)
for case_index, (case_platform, case_route) in enumerate(get_test_cases()):
case_name = f"TestCarModel_{case_index}_{case_platform}"
base = DashcamCarModelTestBase if case_platform in DASHCAM_ONLY_PLATFORMS else CarModelTestBase
globals()[case_name] = type(case_name, (base,), {
"__test__": True,
"platform": case_platform,
"test_route": case_route,
})
if __name__ == "__main__":
unittest.main()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,180 @@
from types import SimpleNamespace
import pytest
from iqpilot.cereal import car, custom
from iqpilot.common.constants import CV
from iqpilot.selfdrive.car.enhanced_stock_longitudinal_control import build_iq_control_params_from_plan
from iqpilot.selfdrive.car.cruise import VCruiseHelper
class TestSpeedLimitSetSpeedMirror:
def setup_method(self):
self.CP = car.CarParams(pcmCruise=True, openpilotLongitudinalControl=True)
self.CP_IQ = custom.IQCarParams(pcmCruiseSpeed=True)
self.v_cruise_helper = VCruiseHelper(self.CP, self.CP_IQ)
self.v_cruise_helper.set_speed_to_limit = True
@staticmethod
def _iq_plan(limit_mps: float, state) -> SimpleNamespace:
resolver = SimpleNamespace(
speedLimitValid=limit_mps > 0,
speedLimitLastValid=limit_mps > 0,
speedLimitFinalLast=limit_mps,
)
assist = SimpleNamespace(state=state)
return SimpleNamespace(speedLimit=SimpleNamespace(resolver=resolver, assist=assist))
def test_op_long_mirrors_active_speed_limit_target_into_cluster_speed(self):
self.v_cruise_helper.update_speed_limit_assist(False, self._iq_plan(17.88, custom.IQPlan.SpeedLimit.AssistState.active))
CS = car.CarState(cruiseState={"available": True, "speed": 22.35, "speedCluster": 22.35})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
assert self.v_cruise_helper.v_cruise_kph == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert self.v_cruise_helper.v_cruise_cluster_kph == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
def test_op_long_syncs_to_new_limit_even_when_assist_not_active(self):
self.v_cruise_helper.update_speed_limit_assist(False, self._iq_plan(17.88, custom.IQPlan.SpeedLimit.AssistState.inactive))
CS = car.CarState(cruiseState={"available": True, "speed": 22.35, "speedCluster": 22.35})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
assert self.v_cruise_helper.v_cruise_kph == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert self.v_cruise_helper.v_cruise_cluster_kph == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
def test_op_long_allows_manual_set_speed_changes_between_limit_changes(self):
self.v_cruise_helper.update_speed_limit_assist(False, self._iq_plan(17.88, custom.IQPlan.SpeedLimit.AssistState.inactive))
# First cycle after a valid limit appears will sync to the resolved target.
CS = car.CarState(cruiseState={"available": True, "speed": 22.35, "speedCluster": 22.35})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
# On later cycles with the same limit, manual set speed changes should be preserved.
CS = car.CarState(cruiseState={"available": True, "speed": 15.64, "speedCluster": 15.64})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
assert self.v_cruise_helper.v_cruise_kph == pytest.approx(15.64 * CV.MS_TO_KPH, abs=0.1)
assert self.v_cruise_helper.v_cruise_cluster_kph == pytest.approx(15.64 * CV.MS_TO_KPH, abs=0.1)
def test_op_long_resyncs_when_limit_changes(self):
self.v_cruise_helper.update_speed_limit_assist(False, self._iq_plan(17.88, custom.IQPlan.SpeedLimit.AssistState.inactive))
CS = car.CarState(cruiseState={"available": True, "speed": 22.35, "speedCluster": 22.35})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
CS = car.CarState(cruiseState={"available": True, "speed": 15.64, "speedCluster": 15.64})
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
self.v_cruise_helper.update_speed_limit_assist(False, self._iq_plan(13.41, custom.IQPlan.SpeedLimit.AssistState.inactive))
self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False)
assert self.v_cruise_helper.v_cruise_kph == pytest.approx(13.41 * CV.MS_TO_KPH, abs=0.1)
assert self.v_cruise_helper.v_cruise_cluster_kph == pytest.approx(13.41 * CV.MS_TO_KPH, abs=0.1)
@pytest.mark.parametrize("pcm_cruise", [False, True])
@pytest.mark.parametrize("is_metric", [False, True])
def test_driver_increase_marker_survives_button_release(pcm_cruise, is_metric):
helper = VCruiseHelper(car.CarParams(pcmCruise=pcm_cruise), custom.IQCarParams(pcmCruiseSpeed=True))
helper.set_speed_to_limit = False
helper.v_cruise_kph = helper.v_cruise_cluster_kph = 80.0
state = car.CarState(cruiseState={"available": True, "speed": 80 * CV.KPH_TO_MS, "speedCluster": 80 * CV.KPH_TO_MS})
helper.update_v_cruise(state, True, is_metric)
state.buttonEvents = [car.CarState.ButtonEvent(type="accelCruise", pressed=True)]
helper.update_v_cruise(state, True, is_metric)
assert helper.slc_set_speed_request_id == 0
state.buttonEvents = [car.CarState.ButtonEvent(type="accelCruise", pressed=False)]
if pcm_cruise:
state.cruiseState.speed = state.cruiseState.speedCluster = 81 * CV.KPH_TO_MS
helper.update_v_cruise(state, True, is_metric)
request = custom.IQCarState.new_message(
slcSetSpeedRequestId=helper.slc_set_speed_request_id,
slcSetSpeedGestureId=helper.slc_set_speed_gesture_id,
slcSetSpeedRequestKph=helper.slc_set_speed_request_kph,
)
assert request.slcSetSpeedRequestId == 1
assert request.slcSetSpeedRequestKph == pytest.approx(helper.v_cruise_kph)
state.buttonEvents = []
for _ in range(100):
helper.update_v_cruise(state, True, is_metric)
assert helper.slc_set_speed_request_id == request.slcSetSpeedRequestId
assert helper.slc_set_speed_gesture_id == request.slcSetSpeedGestureId
def test_stock_cruise_sync_is_not_a_driver_increase():
helper = VCruiseHelper(car.CarParams(pcmCruise=True, openpilotLongitudinalControl=True),
custom.IQCarParams(pcmCruiseSpeed=True))
helper.set_speed_to_limit = True
helper.update_speed_limit_assist(True, TestSpeedLimitSetSpeedMirror._iq_plan(
50 * CV.KPH_TO_MS, custom.IQPlan.SpeedLimit.AssistState.active))
state = car.CarState(cruiseState={"available": True, "speed": 80 * CV.KPH_TO_MS, "speedCluster": 80 * CV.KPH_TO_MS})
for _ in range(10):
helper.update_v_cruise(state, True, True)
assert helper.slc_set_speed_request_id == 0
state.cruiseState.speed = state.cruiseState.speedCluster = 90 * CV.KPH_TO_MS
helper.update_v_cruise(state, True, True)
assert helper.slc_set_speed_request_id == 0
def test_held_increase_uses_one_gesture_and_multiple_requests():
helper = VCruiseHelper(car.CarParams(pcmCruise=False), custom.IQCarParams(pcmCruiseSpeed=True))
helper.set_speed_to_limit = False
helper.v_cruise_kph = 80.0
state = car.CarState(cruiseState={"available": True})
state.buttonEvents = [car.CarState.ButtonEvent(type="accelCruise", pressed=True)]
helper.update_v_cruise(state, True, True)
state.buttonEvents = []
for _ in range(110):
helper.update_v_cruise(state, True, True)
assert helper.slc_set_speed_gesture_id == 1
assert helper.slc_set_speed_request_id >= 2
assert helper.slc_set_speed_request_kph == pytest.approx(helper.v_cruise_kph)
def test_set_speed_does_not_follow_limit_when_feature_off():
# Default off: set speed must stay the driver's value (limiter-only via planner min-blend).
CP = car.CarParams(pcmCruise=True, openpilotLongitudinalControl=True)
CP_IQ = custom.IQCarParams(pcmCruiseSpeed=True)
helper = VCruiseHelper(CP, CP_IQ)
helper.set_speed_to_limit = False
helper.update_speed_limit_assist(False, TestSpeedLimitSetSpeedMirror._iq_plan(
17.88, custom.IQPlan.SpeedLimit.AssistState.active))
CS = car.CarState(cruiseState={"available": True, "speed": 22.35, "speedCluster": 22.35})
helper.update_v_cruise(CS, enabled=True, is_metric=False)
# Set speed tracks the car's cruise speed, NOT the 17.88 m/s limit.
assert helper.v_cruise_kph == pytest.approx(22.35 * CV.MS_TO_KPH, abs=0.1)
def test_enhanced_stock_longitudinal_control_syncs_once_then_follows_cluster_speed():
CP = car.CarParams(pcmCruise=True, openpilotLongitudinalControl=True)
resolver = SimpleNamespace(speedLimitFinalLast=17.88)
assist = SimpleNamespace(enabled=True)
iq_plan = SimpleNamespace(speedLimit=SimpleNamespace(resolver=resolver, assist=assist))
params, sync_limit, pending_limit = build_iq_control_params_from_plan(
CP, iq_plan, True, current_set_speed_kph=100.0, previous_sync_limit_kph=None, pending_sync_limit_kph=None
)
assert sync_limit == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert pending_limit == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert float(params[0]["value"].decode("utf-8")) == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
params, sync_limit, pending_limit = build_iq_control_params_from_plan(
CP, iq_plan, True, current_set_speed_kph=22.0, previous_sync_limit_kph=sync_limit, pending_sync_limit_kph=pending_limit
)
assert sync_limit == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert pending_limit == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert float(params[0]["value"].decode("utf-8")) == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
params, sync_limit, pending_limit = build_iq_control_params_from_plan(
CP, iq_plan, True, current_set_speed_kph=17.88 * CV.MS_TO_KPH, previous_sync_limit_kph=sync_limit, pending_sync_limit_kph=pending_limit
)
assert sync_limit == pytest.approx(17.88 * CV.MS_TO_KPH, abs=0.1)
assert pending_limit is None
params, sync_limit, pending_limit = build_iq_control_params_from_plan(
CP, iq_plan, True, current_set_speed_kph=22.0, previous_sync_limit_kph=sync_limit, pending_sync_limit_kph=pending_limit
)
assert float(params[0]["value"].decode("utf-8")) == pytest.approx(22.0, abs=0.1)

View File

@@ -0,0 +1,26 @@
from iqdbc.car import structs
from iqdbc.lvbs.car.interfaces import apply_iq_car_config
from iqdbc.lvbs.car.tesla.values import TeslaFlagsIQ, TeslaSafetyFlagsIQ
from iqpilot.selfdrive.car.interfaces import initialize_params
class ParamStore:
def get(self, name, return_default=False):
return name == "IQTeslaFsdVisualization"
class CarInterface:
def get_longitudinal_tuning_iq(self, CP, CP_IQ):
return None
def test_fsd_visualization_is_snapshotted():
snapshot = initialize_params(ParamStore())
params = {key: value for item in snapshot for key, value in item.items()}
assert params["IQTeslaFsdVisualization"] is True
CP = structs.CarParams(brand="tesla")
CP_IQ = structs.IQCarParams()
apply_iq_car_config(CarInterface(), CP, CP_IQ, snapshot)
assert CP_IQ.flags & TeslaFlagsIQ.FSD_VISUALIZATION
assert CP_IQ.iqSafetyFlags & TeslaSafetyFlagsIQ.FSD_VISUALIZATION

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,85 @@
"""
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
"""
import json
import os
from iqpilot.common.basedir import BASEDIR
SCHEMA = "iqlvbs/supported-vehicles"
REV = 1
CATALOG_FILENAME = "vehicle_catalog.json"
_CANDIDATE_PARTS = (
("iqpilot", "selfdrive", "car", CATALOG_FILENAME),
)
# in-memory (car-interface) field -> on-disk compact key
_ATTR_TO_KEY = (
("platform", "id"),
("make", "mk"),
("brand", "grp"),
("model", "mdl"),
("year", "yrs"),
("package", "req"),
)
def _reference(platform: str, years: list[str], claimed: set[str]) -> str:
span = f"{years[0]}-{years[-1]}" if len(years) > 1 else (years[0] if years else "na")
stem = f"{platform}|{span}"
ref, bump = stem, 2
while ref in claimed:
ref = f"{stem}#{bump}"
bump += 1
claimed.add(ref)
return ref
def encode(vehicles: dict[str, dict]) -> dict:
records: dict[str, dict] = {}
claimed: set[str] = set()
for label, attrs in vehicles.items():
years = list(attrs.get("year") or [])
ref = _reference(attrs.get("platform", ""), years, claimed)
record = {"label": label}
for attr, key in _ATTR_TO_KEY:
record[key] = attrs.get(attr)
records[ref] = record
return {"catalog": SCHEMA, "rev": REV, "vehicles": records}
def decode(envelope: dict) -> dict[str, dict]:
vehicles: dict[str, dict] = {}
for record in (envelope.get("vehicles") or {}).values():
attrs = {attr: record.get(key) for attr, key in _ATTR_TO_KEY}
vehicles[record.get("label", "")] = attrs
return vehicles
def catalog_path(basedir: str = BASEDIR) -> str | None:
for parts in _CANDIDATE_PARTS:
candidate = os.path.join(basedir, *parts)
if os.path.isfile(candidate):
return candidate
return None
def load_catalog(basedir: str = BASEDIR) -> dict[str, dict]:
path = catalog_path(basedir)
if path is None:
return {}
with open(path) as handle:
return decode(json.load(handle))
def _write(vehicles: dict[str, dict], basedir: str = BASEDIR) -> str:
out = os.path.join(basedir, "iqpilot", "selfdrive", "car", CATALOG_FILENAME)
with open(out, "w") as handle:
json.dump(encode(vehicles), handle, indent=2, ensure_ascii=False)
return out
if __name__ == "__main__":
from iqdbc.lvbs.car.car_catalog import build_car_catalog
print("wrote", _write(build_car_catalog()))