IQ.Pilot Release Commit @ 4fcea4d
This commit is contained in:
74
selfdrive/car/CARS_template.md
Normal file
74
selfdrive/car/CARS_template.md
Normal file
@@ -0,0 +1,74 @@
|
||||
{% set footnote_tag = '[<sup>{}</sup>](#footnotes)' %}
|
||||
{% set star_icon = '[](##)' %}
|
||||
{% 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> ' %}
|
||||
{% 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+
|
||||
|
||||
0
selfdrive/car/__init__.py
Normal file
0
selfdrive/car/__init__.py
Normal file
189
selfdrive/car/car_specific.py
Normal file
189
selfdrive/car/car_specific.py
Normal file
@@ -0,0 +1,189 @@
|
||||
from cereal import car, log
|
||||
from opendbc.car import DT_CTRL, structs
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.interfaces import MAX_CTRL_SPEED
|
||||
from opendbc.car.toyota.values import ToyotaFlags
|
||||
|
||||
from openpilot.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
|
||||
528
selfdrive/car/card.py
Executable file
528
selfdrive/car/card.py
Executable file
@@ -0,0 +1,528 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Copyright © IQ.Lvbs, apart of Project Teal Lvbs, All Rights Reserved, licensed under https://konn3kt.com/tos
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
|
||||
import cereal.messaging as messaging
|
||||
|
||||
from cereal import car, log, custom
|
||||
|
||||
from openpilot.common.iq_perf import PerfSample, PerfTraceEmitter, PerfTraceRing
|
||||
from openpilot.common.params import Params, UnknownKeyName
|
||||
from openpilot.common.realtime import config_realtime_process, lock_memory, Priority, Ratekeeper
|
||||
from openpilot.common.swaglog import cloudlog, ForwardingHandler
|
||||
|
||||
from opendbc.car import DT_CTRL, structs
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.carlog import carlog
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.car_helpers import get_car, interfaces
|
||||
from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase
|
||||
from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
|
||||
from openpilot.selfdrive.car.cruise import VCruiseHelper
|
||||
from openpilot.selfdrive.car.helpers import convert_iq_car_control_compact, convert_to_capnp
|
||||
|
||||
from openpilot.iqpilot.sab.behavior import apply_aol_experience_flags, apply_aol_brand_overrides
|
||||
from openpilot.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'] + ['iqCarControl', 'iqPlan'])
|
||||
self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput', 'liveTracks', '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.setup_interfaces(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")
|
||||
|
||||
# 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.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)
|
||||
|
||||
return CS, CS_IQ, RD
|
||||
|
||||
def state_publish(self, CS: car.CarState, CS_IQ: custom.IQCarState, RD: structs.RadarDataT | None):
|
||||
"""carState and carParams publish loop"""
|
||||
|
||||
# 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.remaining * 1000.
|
||||
self.pm.send('carState', cs_send)
|
||||
|
||||
if RD is not None:
|
||||
tracks_msg = messaging.new_message('liveTracks')
|
||||
tracks_msg.valid = not any(RD.errors.to_dict().values())
|
||||
tracks_msg.liveTracks = RD
|
||||
self.pm.send('liveTracks', 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
|
||||
|
||||
started = time.monotonic_ns()
|
||||
self.last_actuators_output, can_sends = self.CI.apply(CC, 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
|
||||
|
||||
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'])
|
||||
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):
|
||||
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()
|
||||
348
selfdrive/car/cruise.py
Normal file
348
selfdrive/car/cruise.py
Normal file
@@ -0,0 +1,348 @@
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
from cereal import car
|
||||
from openpilot.common.constants import CV
|
||||
from cereal import car, custom
|
||||
from opendbc.car import structs
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.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:
|
||||
# increment timer for buttons still pressed
|
||||
for k in button_timers:
|
||||
if button_timers[k] > 0:
|
||||
button_timers[k] += 1
|
||||
|
||||
for b in CS.buttonEvents:
|
||||
if b.type.raw in button_timers:
|
||||
# Start/end timer and store current state on change of button pressed
|
||||
button_timers[b.type.raw] = 1 if b.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:
|
||||
# special enabled state for non pcmCruiseSpeed, unchanged for non pcmCruise
|
||||
if not self.CP_IQ.pcmCruiseSpeed:
|
||||
update_manual_button_timers(CS, self.enable_button_timers)
|
||||
button_pressed = any(self.enable_button_timers[k] > 0 for k in self.enable_button_timers)
|
||||
|
||||
if enabled and not self.enabled_prev:
|
||||
self.enabled_prev = not button_pressed
|
||||
enabled = False
|
||||
elif not enabled:
|
||||
self.enabled_prev = enabled
|
||||
|
||||
return enabled and self.enabled_prev
|
||||
|
||||
return enabled
|
||||
|
||||
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:
|
||||
return self.has_speed_limit and bool(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}
|
||||
|
||||
@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.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.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
|
||||
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
|
||||
|
||||
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
selfdrive/car/docs.py
Executable file
21
selfdrive/car/docs.py
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from opendbc.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, "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}")
|
||||
193
selfdrive/car/helpers.py
Normal file
193
selfdrive/car/helpers.py
Normal file
@@ -0,0 +1,193 @@
|
||||
import capnp
|
||||
from typing import Any
|
||||
|
||||
from cereal import custom
|
||||
from opendbc.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 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)
|
||||
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
|
||||
1
selfdrive/car/tests/.gitignore
vendored
Normal file
1
selfdrive/car/tests/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
*.bz2
|
||||
0
selfdrive/car/tests/__init__.py
Normal file
0
selfdrive/car/tests/__init__.py
Normal file
11
selfdrive/car/tests/big_cars_test.sh
Executable file
11
selfdrive/car/tests/big_cars_test.sh
Executable 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 selfdrive/car/tests && pytest test_models.py test_car_interfaces.py
|
||||
131
selfdrive/car/tests/test_car_interfaces.py
Normal file
131
selfdrive/car/tests/test_car_interfaces.py
Normal file
@@ -0,0 +1,131 @@
|
||||
import os
|
||||
import hypothesis.strategies as st
|
||||
from hypothesis import Phase, given, settings
|
||||
from parameterized import parameterized
|
||||
from types import SimpleNamespace
|
||||
|
||||
from cereal import car, custom
|
||||
from opendbc.car import DT_CTRL
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.tests.test_car_interfaces import get_fuzzy_car_interface
|
||||
from opendbc.car.mock.values import CAR as MOCK
|
||||
from opendbc.car.values import PLATFORMS
|
||||
from openpilot.selfdrive.car.card import run_optional_pre_init
|
||||
from openpilot.selfdrive.car.helpers import convert_iq_car_control, convert_iq_car_control_compact
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque
|
||||
from openpilot.selfdrive.controls.lib.longcontrol import LongControl
|
||||
from openpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator
|
||||
|
||||
from openpilot.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"}
|
||||
|
||||
|
||||
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 sorted(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):
|
||||
car_interface = get_fuzzy_car_interface(car_name, data.draw)
|
||||
# IQ.Pilot VW MLB ports keep custom ACC behavior; don't fuzz long-apply path
|
||||
# in this generic interface test for these specific platforms.
|
||||
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.setup_interfaces(car_interface)
|
||||
|
||||
cc_msg = FuzzyGenerator.get_random_msg(data.draw, car.CarControl, real_floats=True)
|
||||
cc_sp_msg = FuzzyGenerator.get_random_msg(data.draw, custom.IQCarControl, real_floats=True)
|
||||
# Run car interface
|
||||
now_nanos = 0
|
||||
CC = car.CarControl.new_message(**cc_msg)
|
||||
CC = CC.as_reader()
|
||||
CC_IQ = custom.IQCarControl.new_message(**cc_sp_msg)
|
||||
CC_IQ = convert_iq_car_control(CC_IQ.as_reader())
|
||||
for _ in range(10):
|
||||
car_interface.update([])
|
||||
car_interface.apply(CC, CC_IQ, now_nanos)
|
||||
now_nanos += DT_CTRL * 1e9 # 10 ms
|
||||
|
||||
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 # 10ms
|
||||
|
||||
# Test controller initialization
|
||||
# TODO: wait until card refactor is merged to run controller a few times,
|
||||
# hypothesis also slows down significantly with just one more message draw
|
||||
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)
|
||||
|
||||
|
||||
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)]
|
||||
117
selfdrive/car/tests/test_car_specific_events.py
Normal file
117
selfdrive/car/tests/test_car_specific_events.py
Normal file
@@ -0,0 +1,117 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from cereal import log
|
||||
from opendbc.car import structs
|
||||
|
||||
from openpilot.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)
|
||||
175
selfdrive/car/tests/test_cruise_speed.py
Normal file
175
selfdrive/car/tests/test_cruise_speed.py
Normal file
@@ -0,0 +1,175 @@
|
||||
import pytest
|
||||
import itertools
|
||||
import numpy as np
|
||||
|
||||
from parameterized import parameterized_class
|
||||
from cereal import log
|
||||
from openpilot.selfdrive.car.cruise import VCruiseHelper, V_CRUISE_MIN, V_CRUISE_MAX, V_CRUISE_INITIAL, IMPERIAL_INCREMENT
|
||||
from cereal import car, custom
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.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=1.5), 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))
|
||||
22
selfdrive/car/tests/test_docs.py
Normal file
22
selfdrive/car/tests/test_docs.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import os
|
||||
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from opendbc.car.docs import generate_cars_md, get_all_car_docs
|
||||
from openpilot.selfdrive.debug.dump_car_docs import dump_car_docs
|
||||
from openpilot.selfdrive.debug.print_docs_diff import print_car_docs_diff
|
||||
from openpilot.selfdrive.car.docs import CARS_MD_TEMPLATE
|
||||
|
||||
|
||||
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, "selfdrive", "car", "tests", "cars_dump")
|
||||
dump_car_docs(dump_path)
|
||||
print_car_docs_diff(dump_path)
|
||||
os.remove(dump_path)
|
||||
484
selfdrive/car/tests/test_models.py
Normal file
484
selfdrive/car/tests/test_models.py
Normal file
@@ -0,0 +1,484 @@
|
||||
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 parameterized import parameterized_class
|
||||
|
||||
from opendbc.car import DT_CTRL, gen_empty_fingerprint, structs
|
||||
from opendbc.car.can_definitions import CanData
|
||||
from opendbc.car.car_helpers import FRAME_FINGERPRINT, interfaces
|
||||
from opendbc.car.fingerprints import MIGRATION
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tests.routes import non_tested_cars, routes, CarTestRoute
|
||||
from opendbc.car.values import Platform, PLATFORMS
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.selfdrive.pandad import can_capnp_to_list
|
||||
from openpilot.selfdrive.test.helpers import read_segment_list
|
||||
from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT
|
||||
from openpilot.tools.lib.logreader import LogReader, LogsUnavailable, openpilotci_source, internal_source, comma_api_source
|
||||
from openpilot.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
|
||||
|
||||
|
||||
def get_test_cases() -> list[tuple[str, CarTestRoute | None]]:
|
||||
# build list of test cases
|
||||
test_cases = []
|
||||
if not len(INTERNAL_SEG_LIST):
|
||||
routes_by_car = defaultdict(set)
|
||||
for r in routes:
|
||||
routes_by_car[str(r.car_model)].add(r)
|
||||
|
||||
for i, c in enumerate(sorted(PLATFORMS)):
|
||||
if i % NUM_JOBS == JOB_ID:
|
||||
test_cases.extend(sorted((c, r) for r in routes_by_car.get(c, (None,))))
|
||||
|
||||
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
|
||||
class TestCarModelBase(unittest.TestCase):
|
||||
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):
|
||||
if cls.__name__ == 'TestCarModel' or cls.__name__.endswith('Base'):
|
||||
raise unittest.SkipTest
|
||||
|
||||
if cls.test_route is None:
|
||||
if cls.platform in non_tested_cars:
|
||||
print(f"Skipping tests for {cls.platform}: missing route")
|
||||
raise unittest.SkipTest
|
||||
raise Exception(f"missing test route for {cls.platform}")
|
||||
|
||||
car_fw, cls.can_msgs, alpha_long = cls.get_testing_data()
|
||||
|
||||
# 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):
|
||||
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):
|
||||
if self.CP.dashcamOnly:
|
||||
self.skipTest("no need to check carParams for 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):
|
||||
# TODO: also check for checksum violations from can parser
|
||||
can_invalid_cnt = 0
|
||||
CC = structs.CarControl().as_reader()
|
||||
CC_IQ = structs.IQCarControl()
|
||||
|
||||
for i, msg in enumerate(self.can_msgs):
|
||||
CS, _ = self.CI.update(msg)
|
||||
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
|
||||
|
||||
self.assertEqual(can_invalid_cnt, 0)
|
||||
|
||||
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(msg)
|
||||
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):
|
||||
if self.CP.dashcamOnly:
|
||||
self.skipTest("no need to check panda safety for dashcamOnly")
|
||||
|
||||
start_ts = self.can_msgs[0][0]
|
||||
|
||||
failed_addrs = Counter()
|
||||
for can in 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 = 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
|
||||
|
||||
# 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())
|
||||
|
||||
# Don't check relay malfunction on disabled routes (relay closed),
|
||||
# or before fingerprinting is done (elm327 and noOutput)
|
||||
if self.openpilot_enabled and t / 1e4 > self.car_safety_mode_frame:
|
||||
self.assertFalse(self.safety.get_relay_malfunction())
|
||||
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"""
|
||||
if self.CP.dashcamOnly:
|
||||
self.skipTest("no need to check panda safety for dashcamOnly")
|
||||
|
||||
if self.CP.notCar:
|
||||
self.skipTest("Skipping test for notCar")
|
||||
|
||||
def test_car_controller(car_control, car_control_iq):
|
||||
now_nanos = 0
|
||||
msgs_sent = 0
|
||||
CI = self.CarInterface(self.CP, self.CP_IQ)
|
||||
for _ in range(round(10.0 / DT_CTRL)): # make sure we hit the slowest messages
|
||||
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 = libsafety_py.make_CANPacket(addr, bus % 4, dat)
|
||||
self.assertTrue(self.safety.safety_tx_hook(to_send), (addr, dat, bus))
|
||||
|
||||
# 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.
|
||||
"""
|
||||
|
||||
if self.CP.dashcamOnly:
|
||||
self.skipTest("no need to check panda safety for dashcamOnly")
|
||||
|
||||
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 = 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
|
||||
"""
|
||||
if self.CP.dashcamOnly:
|
||||
self.skipTest("no need to check panda safety for dashcamOnly")
|
||||
|
||||
# warm up pass, as initial states may be different
|
||||
for can in self.can_msgs[:300]:
|
||||
self.CI.update(can)
|
||||
for msg in filter(lambda m: m.src < 64, can[1]):
|
||||
to_send = 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)
|
||||
vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar
|
||||
for idx, can in enumerate(self.can_msgs):
|
||||
CS, _ = self.CI.update(can)
|
||||
CS = CS.as_reader()
|
||||
for msg in filter(lambda m: m.src < 64, can[1]):
|
||||
to_send = 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()
|
||||
checks['standstill'] += (CS.standstill == self.safety.get_vehicle_moving()) and not self.CP.notCar
|
||||
|
||||
# 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}")
|
||||
|
||||
|
||||
@parameterized_class(('platform', 'test_route'), get_test_cases())
|
||||
@pytest.mark.xdist_group_class_property('test_route')
|
||||
class TestCarModel(TestCarModelBase):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
3884
selfdrive/car/tests/test_models_segs.txt
Normal file
3884
selfdrive/car/tests/test_models_segs.txt
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user