mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-09-09 17:53:45 +08:00
ee5c1c4507
* allow re-regage
* bump opendbc
* bump panda
* apply pause/resume fix for hyundai (should do this in a separate PR)
* bump opendbc
* fix
* rename
* Fix?
* make sure to disengage for allow always cars
* fix
* combine
* more fix
* not needed
* check if engagement is from openpilot's state machine
* Rename
* fix panda safety
* fix
* no fake lfa button for @devtekve ;)
* fix non drive gear re-engage
* fix settings
* combine
* add replace method
* use replace
* remoev already checks if it exists
* fix
* group
* add todo
* reserve events
* cleaner
* hyundai: only allow for cars with lfa button
* sunnyParams
* make sure it's car only
* Move car-specific changes to opendbc
* no need
* bump opendbc
* more fixes
* no more available
* more!
* final?
* always emit user disable
* no longer needed
* move unit test
* add sunnypilot to unit tests
* bump opendbc
* use new cereal
* bump opendbc
* static analysis
* no unittest
* no need available
* UI border update
* show MADS updates
* Add TODO
* no longer needed
* fix changed events
* fix cluster enabled
* don't add pre enable if not long
* should use enabled
* enabled <-> active
* better format
* bump opendbc
* static analysis
* static analysis
* Rename test as collector was dying
* Show our overriding
* Revert "show MADS updates"
This reverts commit daf0ad62
Revert "fix changed events"
This reverts commit 31d8c97f
* ignoring reserved events
* adjusting creation delays
* back to stock
removing allow_cancel
* should be enabled
* revert
* silent lkas disable
* no need
* user disable tests
* just warning
* MUST REMOVE test process replay
* fix no entry
* fixme
* bump opendbc
* need this check
* cleanup
* allow entering paused state if no entry from disabled
* brake hold should apply to all
* in lists
* update unit test
* simpler
* unused
* same thing
* fix
* only mads in enabled state and long in disabled state
* unify silent enable
* do this for dlob
* bump submodules
* fix
* bump submodules
* bump opendbc
* less frequent
* more events
* fix
* allow no entry to paused for non-drive gears
* fix
* use cereal
* Revert "allow no entry to paused for non-drive gears"
This reverts commit 6d64a4dd9c6de5ad14ef1e88dbc3b6ad174232d8.
* allow in all
* Revert "allow in all"
This reverts commit 6375f1489176dc6c69cb7fa388676e482713f80a.
* should not be all!
* rename for clarity
* silent park brake
* flipped
* bump submodules
* Bump to latest mads-new panda
* bump panda
* more nissan
* bump panda
* bump msgq
* bump panda
* bump submodules
* bump opendbc
* bump opendbc
* improving the state
* Revert "PlayStation® model (#34133)"
This reverts commit 5160bee543.
* should be none
* bump panda
* bump opendbc
* Apply suggestions from code review
* bump panda
* bump ref panda
* add todo-sp
* bump panda ref
* bump more panda
* changing refs
* nuke nuke nuke
* use sunny's newer states
* bump with new panda
* bump panda
* Parse more flags from alt exp, more tests, hyundai main cruise allowed
* Parse more flags from alt exp, more tests, hyundai main cruise allowed
* missed
* mutation for controls allowed rising edge
* ford mutation
* license
* remove
* unused
* bump submodules
* use always allowed mads button alt exp
* fix
* whitelist jason's lastname to codespell
* test_processes: update ref logs to 82c0278
* bump submodules
* bump submodules
* bump submodules
* bump panda
* add controls mismatch lateral event
* Simplify lateral disengagement logic for MADS configuration
Reversed the conditional to align the logic with the `disengage_lateral_on_brake` parameter. This ensures that lateral disengagement behavior is more intuitive and matches the expected configuration. Improves code readability and reduces potential misconfigurations.
* remove unified engagement mode in panda
* controls allow should be allowed at all times
* squash! treat MADS button as user entry
* heartbeat for mads
* heartbeat mismatch exit control
* remove always allow mads button from alt
* move to safety_mads
* remove main cruise allowed from alt
* bump panda
* heartbeat engaged mads mismatch mutation test
* bump panda
* use mads the third panda
* ignore pre enable with mads
* only force exit if actually actuating
* use brake signal instead of pedal events when dlob is active
* fix tests
* fix panda tests
* bump panda
* new events to retain long blocks
* format
* uem: do not engage mads if long is engaged
* bump submodules
* fix not allowed engaged bug
* block uem from engaging
* flipped
* use different heartbeat check if dlob
* hard code to skip heartbeat check
* remove toyota lta status for lkas, causes weird behaviors
* block tesla
* bump panda
* bump to merged panda
* bump opendbc
* bump opendbc
* bump opendbc
* bump opendbc
* Apply suggestions from code review
* code ignore spells
* needs to be in carstate
* Bump opendbc
* Update MADS toggle descriptions for clarity.
Added notes to clarify behavior of the "MadsMainCruiseAllowed" setting, particularly its impact on vehicles without LFA/LKAS buttons. This ensures users are informed about potential implications when disabling this feature.
* Updating translations + Adding spanish
* Disengage Lateral on Brake -> Pause Lateral on Brake
* test_processes: update ref logs to dd41005
* Apply suggestions from code review
* fix mads button not allowed
* bump submodules
* bump submodule
* test_processes: update ref logs to 0a0b998
* has multiple lists
* Revert "has multiple lists"
This reverts commit a37c1d26feac02f63bfb86a08f9b6fb06b095cf1.
* base
* Reapply "has multiple lists"
This reverts commit d1cd8dcc815721a4113b26ab98ee2571c071e225.
* migrate mads toggles to sp panel
* this is why it keeps crashing
* house keeping
* more housekeeping
* more housekeeping
* don't show description by default (yet)
* reset to main panel when clicked away
* more
* some more with interactions
* don't stretch cause it looks weird with descriptions
* simpler to handle offroad transition
* some are toggleable while onroad
* remove unused event
* slight cleanup
* default to true for HKG main cruise toggle
* append to list after
* add Customize MADS to UI preview
* simpler
* move to sp list
* how tf was this removed
* update mads settings button on show event
* test_processes: update ref logs to efa9c32
---------
Co-authored-by: Jason Wen <haibin.wen3@gmail.com>
286 lines
10 KiB
Python
Executable File
286 lines
10 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
import os
|
|
import time
|
|
import threading
|
|
|
|
import cereal.messaging as messaging
|
|
|
|
from cereal import car, log
|
|
|
|
from panda import ALTERNATIVE_EXPERIENCE
|
|
|
|
from openpilot.common.params import Params
|
|
from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper
|
|
from openpilot.common.swaglog import cloudlog, ForwardingHandler
|
|
|
|
from opendbc.car import DT_CTRL, carlog, structs
|
|
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
|
from opendbc.car.fw_versions import ObdCallback
|
|
from opendbc.car.car_helpers import get_car, get_radar_interface
|
|
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.car_specific import MockCarState
|
|
|
|
from openpilot.sunnypilot.mads.mads import MadsParams
|
|
|
|
REPLAY = "REPLAY" in os.environ
|
|
|
|
EventName = log.OnroadEvent.EventName
|
|
|
|
# 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
|
|
|
|
|
|
class Car:
|
|
CI: CarInterfaceBase
|
|
RI: RadarInterfaceBase
|
|
CP: car.CarParams
|
|
|
|
def __init__(self, CI=None, RI=None) -> None:
|
|
self.can_sock = messaging.sub_sock('can', timeout=20)
|
|
self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents'])
|
|
self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput', 'liveTracks'])
|
|
|
|
self.can_rcv_cum_timeout_counter = 0
|
|
|
|
self.CC_prev = car.CarControl.new_message()
|
|
self.initialized_prev = False
|
|
|
|
self.last_actuators_output = structs.CarControl.Actuators()
|
|
|
|
self.params = Params()
|
|
|
|
self.can_callbacks = can_comm_callbacks(self.can_sock, self.pm.sock['sendcan'])
|
|
|
|
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
|
|
|
|
experimental_long_allowed = self.params.get_bool("ExperimentalLongitudinalEnabled")
|
|
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
|
|
|
|
self.CI = get_car(*self.can_callbacks, obd_callback(self.params), experimental_long_allowed, num_pandas, cached_params)
|
|
self.RI = get_radar_interface(self.CI.CP)
|
|
self.CP = self.CI.CP
|
|
|
|
# continue onto next fingerprinting step in pandad
|
|
self.params.put_bool("FirmwareQueryDone", True)
|
|
else:
|
|
self.CI, self.CP = CI, CI.CP
|
|
self.RI = RI
|
|
|
|
# set alternative experiences from parameters
|
|
disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator")
|
|
self.CP.alternativeExperience = 0
|
|
if not disengage_on_accelerator:
|
|
self.CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS
|
|
|
|
# mads
|
|
MadsParams().set_alternative_experience(self.CP)
|
|
MadsParams().set_car_specific_params(self.CP)
|
|
|
|
openpilot_enabled_toggle = self.params.get_bool("OpenpilotEnabledToggle")
|
|
|
|
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 and not self.params.get_bool("IsReleaseBranch"):
|
|
secoc_key = self.params.get("SecOCKey", encoding='utf8')
|
|
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.mock_carstate = MockCarState()
|
|
self.v_cruise_helper = VCruiseHelper(self.CP)
|
|
|
|
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)
|
|
|
|
def state_update(self) -> tuple[car.CarState, 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 = self.CI.update(can_list)
|
|
if self.CP.carName == 'mock':
|
|
CS = self.mock_carstate.update(CS)
|
|
|
|
# Update radar tracks from CAN
|
|
RD: structs.RadarDataT | None = self.RI.update(can_list)
|
|
|
|
self.sm.update(0)
|
|
|
|
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
|
|
|
|
# TODO: mirror the carState.cruiseState struct?
|
|
self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric)
|
|
CS.vCruise = float(self.v_cruise_helper.v_cruise_kph)
|
|
CS.vCruiseCluster = float(self.v_cruise_helper.v_cruise_cluster_kph)
|
|
|
|
return CS, RD
|
|
|
|
def state_publish(self, CS: car.CarState, 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 = len(RD.errors) == 0
|
|
tracks_msg.liveTracks = RD
|
|
self.pm.send('liveTracks', tracks_msg)
|
|
|
|
def controls_update(self, CS: car.CarState, CC: car.CarControl):
|
|
"""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.can_callbacks)
|
|
# signal pandad to switch to car safety mode
|
|
self.params.put_bool_nonblocking("ControlsReady", True)
|
|
|
|
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)
|
|
self.last_actuators_output, can_sends = self.CI.apply(CC, now_nanos)
|
|
self.pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
|
|
|
|
self.CC_prev = CC
|
|
|
|
def step(self):
|
|
CS, RD = self.state_update()
|
|
|
|
if self.sm['carControl'].enabled and not self.CC_prev.enabled:
|
|
self.v_cruise_helper.initialize_v_cruise(CS, self.experimental_mode)
|
|
|
|
self.state_publish(CS, RD)
|
|
|
|
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.initialized_prev = initialized
|
|
|
|
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
|
|
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)
|
|
car = Car()
|
|
car.card_thread()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|