Files
dragonpilot/selfdrive/controls/controlsd.py

575 lines
22 KiB
Python
Raw Normal View History

2019-10-09 18:43:53 +00:00
#!/usr/bin/env python3
import os
2018-07-12 18:52:06 -07:00
import gc
2019-06-28 21:11:30 +00:00
import capnp
2017-12-23 17:15:27 -08:00
from cereal import car, log
2016-12-14 21:29:12 -08:00
from common.numpy_fast import clip
2019-06-28 21:11:30 +00:00
from common.realtime import sec_since_boot, set_realtime_priority, Ratekeeper, DT_CTRL
2017-01-09 20:59:00 -08:00
from common.profiler import Profiler
2019-09-09 23:03:02 +00:00
from common.params import Params, put_nonblocking
2017-08-09 17:32:45 -07:00
import selfdrive.messaging as messaging
2017-07-28 01:24:39 -07:00
from selfdrive.config import Conversions as CV
2019-06-06 04:38:45 +00:00
from selfdrive.boardd.boardd import can_list_to_can_capnp
2019-10-31 17:14:40 -07:00
from selfdrive.car.car_helpers import get_car, get_startup_alert
2019-08-13 01:36:45 +00:00
from selfdrive.controls.lib.lane_planner import CAMERA_OFFSET
2019-06-28 21:11:30 +00:00
from selfdrive.controls.lib.drive_helpers import get_events, \
2017-09-30 03:07:27 -07:00
create_event, \
2018-05-01 23:19:47 +00:00
EventTypes as ET, \
update_v_cruise, \
2018-11-17 02:08:34 -08:00
initialize_v_cruise
2017-09-30 03:07:27 -07:00
from selfdrive.controls.lib.longcontrol import LongControl, STARTING_TARGET_SPEED
2019-05-16 13:20:29 -07:00
from selfdrive.controls.lib.latcontrol_pid import LatControlPID
from selfdrive.controls.lib.latcontrol_indi import LatControlINDI
2019-08-13 01:36:45 +00:00
from selfdrive.controls.lib.latcontrol_lqr import LatControlLQR
2016-12-12 17:47:46 -08:00
from selfdrive.controls.lib.alertmanager import AlertManager
2017-08-09 17:32:45 -07:00
from selfdrive.controls.lib.vehicle_model import VehicleModel
2019-07-22 19:17:47 +00:00
from selfdrive.controls.lib.driver_monitor import DriverStatus, MAX_TERMINAL_ALERTS
2019-06-28 21:11:30 +00:00
from selfdrive.controls.lib.planner import LON_MPC_STEP
2019-09-09 23:03:02 +00:00
from selfdrive.controls.lib.gps_helpers import is_rhd_region
2018-12-10 14:13:12 -08:00
from selfdrive.locationd.calibration_helpers import Calibration, Filter
2017-11-22 04:30:24 -08:00
2018-07-12 18:52:06 -07:00
ThermalStatus = log.ThermalData.ThermalStatus
2019-06-06 04:38:45 +00:00
State = log.ControlsState.OpenpilotState
2019-10-09 18:43:53 +00:00
HwType = log.HealthData.HwType
2017-09-30 03:07:27 -07:00
2018-07-12 18:52:06 -07:00
2017-09-30 03:07:27 -07:00
def isActive(state):
2018-11-17 02:08:34 -08:00
"""Check if the actuators are enabled"""
2017-12-23 17:15:27 -08:00
return state in [State.enabled, State.softDisabling]
2017-09-30 03:07:27 -07:00
def isEnabled(state):
2018-11-17 02:08:34 -08:00
"""Check if openpilot is engaged"""
2017-12-23 17:15:27 -08:00
return (isActive(state) or state == State.preEnabled)
2016-11-29 18:34:21 -08:00
2019-06-28 21:11:30 +00:00
def events_to_bytes(events):
# optimization when comparing capnp structs: str() or tree traverse are much slower
ret = []
for e in events:
if isinstance(e, capnp.lib.capnp._DynamicStructReader):
e = e.as_builder()
ret.append(e.to_bytes())
return ret
2017-05-11 12:41:17 -07:00
2019-10-31 17:14:40 -07:00
def data_sample(CI, CC, sm, can_sock, cal_status, cal_perc, overtemp, free_space, low_battery,
2019-06-28 21:11:30 +00:00
driver_status, state, mismatch_counter, params):
2018-11-17 02:08:34 -08:00
"""Receive data from sockets and create events for battery, temperature and disk space"""
2017-05-11 12:41:17 -07:00
2018-11-17 02:08:34 -08:00
# Update carstate from CAN and create events
2019-10-31 17:14:40 -07:00
can_strs = messaging.drain_sock_raw(can_sock, wait_for_one=True)
2019-07-22 19:17:47 +00:00
CS = CI.update(CC, can_strs)
sm.update(0)
2017-09-30 03:07:27 -07:00
events = list(CS.events)
2018-07-12 18:52:06 -07:00
enabled = isEnabled(state)
2017-07-28 01:24:39 -07:00
2019-07-22 19:17:47 +00:00
# Check for CAN timeout
if not can_strs:
events.append(create_event('canError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
2019-06-28 21:11:30 +00:00
if sm.updated['thermal']:
overtemp = sm['thermal'].thermalStatus >= ThermalStatus.red
free_space = sm['thermal'].freeSpace < 0.07 # under 7% of space free no enable allowed
low_battery = sm['thermal'].batteryPercent < 1 and sm['thermal'].chargingError # at zero percent battery, while discharging, OP should not allowed
2017-07-28 01:24:39 -07:00
2018-11-17 02:08:34 -08:00
# Create events for battery, temperature and disk space
2018-09-25 00:13:41 -07:00
if low_battery:
events.append(create_event('lowBattery', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
2017-10-03 23:40:21 -07:00
if overtemp:
events.append(create_event('overheat', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if free_space:
events.append(create_event('outOfSpace', [ET.NO_ENTRY]))
2016-11-29 18:34:21 -08:00
2019-09-09 23:03:02 +00:00
# GPS coords RHD parsing, once every restart
if sm.updated['gpsLocation'] and not driver_status.is_rhd_region_checked:
is_rhd = is_rhd_region(sm['gpsLocation'].latitude, sm['gpsLocation'].longitude)
driver_status.is_rhd_region = is_rhd
driver_status.is_rhd_region_checked = True
2019-10-09 18:43:53 +00:00
put_nonblocking("IsRHD", "1" if is_rhd else "0")
2019-07-22 19:17:47 +00:00
2018-11-17 02:08:34 -08:00
# Handle calibration
2019-06-28 21:11:30 +00:00
if sm.updated['liveCalibration']:
cal_status = sm['liveCalibration'].calStatus
cal_perc = sm['liveCalibration'].calPerc
2016-12-12 17:47:46 -08:00
2019-08-13 01:36:45 +00:00
cal_rpy = [0,0,0]
2017-09-30 03:07:27 -07:00
if cal_status != Calibration.CALIBRATED:
if cal_status == Calibration.UNCALIBRATED:
2018-09-25 00:13:41 -07:00
events.append(create_event('calibrationIncomplete', [ET.NO_ENTRY, ET.SOFT_DISABLE, ET.PERMANENT]))
2017-09-30 03:07:27 -07:00
else:
events.append(create_event('calibrationInvalid', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
2019-08-13 01:36:45 +00:00
else:
rpy = sm['liveCalibration'].rpyCalib
if len(rpy) == 3:
cal_rpy = rpy
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# When the panda and controlsd do not agree on controls_allowed
# we want to disengage openpilot. However the status from the panda goes through
2019-06-28 21:11:30 +00:00
# another socket other than the CAN messages and one can arrive earlier than the other.
2018-11-17 02:08:34 -08:00
# Therefore we allow a mismatch for two samples, then we trigger the disengagement.
2018-07-12 18:52:06 -07:00
if not enabled:
mismatch_counter = 0
2019-06-28 21:11:30 +00:00
if sm.updated['health']:
controls_allowed = sm['health'].controlsAllowed
2018-07-12 18:52:06 -07:00
if not controls_allowed and enabled:
mismatch_counter += 1
if mismatch_counter >= 2:
2017-12-23 17:15:27 -08:00
events.append(create_event('controlsMismatch', [ET.IMMEDIATE_DISABLE]))
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# Driver monitoring
2019-06-28 21:11:30 +00:00
if sm.updated['driverMonitoring']:
2019-09-09 23:03:02 +00:00
driver_status.get_pose(sm['driverMonitoring'], cal_rpy, CS.vEgo, enabled)
2017-09-30 03:07:27 -07:00
2019-07-22 19:17:47 +00:00
if driver_status.terminal_alert_cnt >= MAX_TERMINAL_ALERTS:
events.append(create_event("tooDistracted", [ET.NO_ENTRY]))
2019-06-28 21:11:30 +00:00
return CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
def state_transition(frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM):
2018-11-17 02:08:34 -08:00
"""Compute conditional state transitions and execute actions on state transitions"""
2017-09-30 03:07:27 -07:00
enabled = isEnabled(state)
2017-12-23 17:15:27 -08:00
v_cruise_kph_last = v_cruise_kph
2018-05-01 23:19:47 +00:00
# if stock cruise is completely disabled, then we can use our own set speed logic
if not CP.enableCruise:
v_cruise_kph = update_v_cruise(v_cruise_kph, CS.buttonEvents, enabled)
2018-07-12 18:52:06 -07:00
elif CP.enableCruise and CS.cruiseState.enabled:
v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH
2017-09-30 03:07:27 -07:00
# decrease the soft disable timer at every step, as it's reset on
# entrance in SOFT_DISABLING state
soft_disable_timer = max(0, soft_disable_timer - 1)
# DISABLED
2017-12-23 17:15:27 -08:00
if state == State.disabled:
2017-09-30 03:07:27 -07:00
if get_events(events, [ET.ENABLE]):
2017-12-23 17:15:27 -08:00
if get_events(events, [ET.NO_ENTRY]):
2017-09-30 03:07:27 -07:00
for e in get_events(events, [ET.NO_ENTRY]):
2019-06-28 21:11:30 +00:00
AM.add(frame, str(e) + "NoEntry", enabled)
2017-12-23 17:15:27 -08:00
2017-09-30 03:07:27 -07:00
else:
if get_events(events, [ET.PRE_ENABLE]):
2017-12-23 17:15:27 -08:00
state = State.preEnabled
2017-07-28 01:24:39 -07:00
else:
2017-12-23 17:15:27 -08:00
state = State.enabled
2019-06-28 21:11:30 +00:00
AM.add(frame, "enable", enabled)
2018-07-12 18:52:06 -07:00
v_cruise_kph = initialize_v_cruise(CS.vEgo, CS.buttonEvents, v_cruise_kph_last)
2017-09-30 03:07:27 -07:00
# ENABLED
2017-12-23 17:15:27 -08:00
elif state == State.enabled:
2017-09-30 03:07:27 -07:00
if get_events(events, [ET.USER_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2019-06-28 21:11:30 +00:00
AM.add(frame, "disable", enabled)
2017-09-30 03:07:27 -07:00
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2017-09-30 03:07:27 -07:00
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled)
2017-09-30 03:07:27 -07:00
elif get_events(events, [ET.SOFT_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.softDisabling
2018-11-17 02:08:34 -08:00
soft_disable_timer = 300 # 3s
2017-09-30 03:07:27 -07:00
for e in get_events(events, [ET.SOFT_DISABLE]):
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled)
2017-09-30 03:07:27 -07:00
# SOFT DISABLING
2017-12-23 17:15:27 -08:00
elif state == State.softDisabling:
2017-09-30 03:07:27 -07:00
if get_events(events, [ET.USER_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2019-06-28 21:11:30 +00:00
AM.add(frame, "disable", enabled)
2017-09-30 03:07:27 -07:00
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2017-09-30 03:07:27 -07:00
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled)
2017-09-30 03:07:27 -07:00
elif not get_events(events, [ET.SOFT_DISABLE]):
# no more soft disabling condition, so go back to ENABLED
2017-12-23 17:15:27 -08:00
state = State.enabled
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
elif get_events(events, [ET.SOFT_DISABLE]) and soft_disable_timer > 0:
for e in get_events(events, [ET.SOFT_DISABLE]):
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled)
2018-11-17 02:08:34 -08:00
2017-09-30 03:07:27 -07:00
elif soft_disable_timer <= 0:
2017-12-23 17:15:27 -08:00
state = State.disabled
2017-10-03 23:40:21 -07:00
2017-12-23 17:15:27 -08:00
# PRE ENABLING
elif state == State.preEnabled:
2017-09-30 03:07:27 -07:00
if get_events(events, [ET.USER_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2019-06-28 21:11:30 +00:00
AM.add(frame, "disable", enabled)
2017-09-30 03:07:27 -07:00
elif get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
2017-12-23 17:15:27 -08:00
state = State.disabled
2017-09-30 03:07:27 -07:00
for e in get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled)
2017-09-30 03:07:27 -07:00
elif not get_events(events, [ET.PRE_ENABLE]):
2017-12-23 17:15:27 -08:00
state = State.enabled
2017-09-30 03:07:27 -07:00
2017-12-23 17:15:27 -08:00
return state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
def state_control(frame, rcv_frame, plan, path_plan, CS, CP, state, events, v_cruise_kph, v_cruise_kph_last,
2019-10-09 18:43:53 +00:00
AM, rk, driver_status, LaC, LoC, read_only, is_metric, cal_perc):
2018-11-17 02:08:34 -08:00
"""Given the state, this function returns an actuators packet"""
2017-09-30 03:07:27 -07:00
actuators = car.CarControl.Actuators.new_message()
enabled = isEnabled(state)
active = isActive(state)
2018-07-12 18:52:06 -07:00
# check if user has interacted with the car
driver_engaged = len(CS.buttonEvents) > 0 or \
v_cruise_kph != v_cruise_kph_last or \
CS.steeringPressed
2016-11-29 18:34:21 -08:00
2018-07-12 18:52:06 -07:00
# add eventual driver distracted events
events = driver_status.update(events, driver_engaged, isActive(state), CS.standstill)
2016-11-29 18:34:21 -08:00
2017-09-30 03:07:27 -07:00
# send FCW alert if triggered by planner
if plan.fcw:
2019-06-28 21:11:30 +00:00
AM.add(frame, "fcw", enabled)
2016-11-29 18:34:21 -08:00
2018-11-17 02:08:34 -08:00
# State specific actions
2016-11-29 18:34:21 -08:00
2017-12-23 17:15:27 -08:00
if state in [State.preEnabled, State.disabled]:
2017-09-30 03:07:27 -07:00
LaC.reset()
LoC.reset(v_pid=CS.vEgo)
2016-11-29 18:34:21 -08:00
2017-12-23 17:15:27 -08:00
elif state in [State.enabled, State.softDisabling]:
2017-09-30 03:07:27 -07:00
# parse warnings from car specific interface
for e in get_events(events, [ET.WARNING]):
2018-09-25 00:13:41 -07:00
extra_text = ""
if e == "belowSteerSpeed":
if is_metric:
extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_KPH))) + " kph"
else:
extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_MPH))) + " mph"
2019-06-28 21:11:30 +00:00
AM.add(frame, e, enabled, extra_text_2=extra_text)
2016-11-29 18:34:21 -08:00
2019-06-28 21:11:30 +00:00
plan_age = DT_CTRL * (frame - rcv_frame['plan'])
dt = min(plan_age, LON_MPC_STEP + DT_CTRL) + DT_CTRL # no greater than dt mpc + dt, to prevent too high extraps
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
a_acc_sol = plan.aStart + (dt / LON_MPC_STEP) * (plan.aTarget - plan.aStart)
2019-02-20 01:39:02 +00:00
v_acc_sol = plan.vStart + dt * (a_acc_sol + plan.aStart) / 2.0
2018-11-17 02:08:34 -08:00
# Gas/Brake PID loop
2017-11-22 04:30:24 -08:00
actuators.gas, actuators.brake = LoC.update(active, CS.vEgo, CS.brakePressed, CS.standstill, CS.cruiseState.standstill,
2019-02-20 01:39:02 +00:00
v_cruise_kph, v_acc_sol, plan.vTargetFuture, a_acc_sol, CP)
2018-11-17 02:08:34 -08:00
# Steering PID loop and lateral MPC
2019-10-09 18:43:53 +00:00
actuators.steer, actuators.steerAngle, lac_log = LaC.update(active, CS.vEgo, CS.steeringAngle, CS.steeringRate, CS.steeringTorqueEps, CS.steeringPressed, CP, path_plan)
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# Send a "steering required alert" if saturation count has reached the limit
2018-05-01 23:19:47 +00:00
if LaC.sat_flag and CP.steerLimitAlert:
2019-06-28 21:11:30 +00:00
AM.add(frame, "steerSaturated", enabled)
2018-05-01 23:19:47 +00:00
2018-11-17 02:08:34 -08:00
# Parse permanent warnings to display constantly
2017-12-23 17:15:27 -08:00
for e in get_events(events, [ET.PERMANENT]):
2018-09-25 00:13:41 -07:00
extra_text_1, extra_text_2 = "", ""
if e == "calibrationIncomplete":
extra_text_1 = str(cal_perc) + "%"
if is_metric:
extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_KPH))) + " kph"
else:
extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_MPH))) + " mph"
2019-06-28 21:11:30 +00:00
AM.add(frame, str(e) + "Permanent", enabled, extra_text_1=extra_text_1, extra_text_2=extra_text_2)
2017-12-23 17:15:27 -08:00
2019-06-28 21:11:30 +00:00
AM.process_alerts(frame)
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
return actuators, v_cruise_kph, driver_status, v_acc_sol, a_acc_sol, lac_log
2017-09-30 03:07:27 -07:00
2019-09-09 23:03:02 +00:00
def data_send(sm, pm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, AM,
driver_status, LaC, LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev):
2019-06-06 04:38:45 +00:00
"""Send actuators and hud commands to the car, send controlsstate and MPC logging"""
2017-09-30 03:07:27 -07:00
CC = car.CarControl.new_message()
2019-06-28 21:11:30 +00:00
CC.enabled = isEnabled(state)
CC.actuators = actuators
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
CC.cruiseControl.override = True
CC.cruiseControl.cancel = not CP.enableCruise or (not isEnabled(state) and CS.cruiseState.enabled)
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
# Some override values for Honda
brake_discount = (1.0 - clip(actuators.brake * 3., 0.0, 1.0)) # brake discount removes a sharp nonlinearity
CC.cruiseControl.speedOverride = float(max(0.0, (LoC.v_pid + CS.cruiseState.speedOffset) * brake_discount) if CP.enableCruise else 0.0)
CC.cruiseControl.accelOverride = CI.calc_accel_override(CS.aEgo, sm['plan'].aTarget, CS.vEgo, sm['plan'].vTarget)
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
CC.hudControl.setSpeed = float(v_cruise_kph * CV.KPH_TO_MS)
CC.hudControl.speedVisible = isEnabled(state)
CC.hudControl.lanesVisible = isEnabled(state)
CC.hudControl.leadVisible = sm['plan'].hasLead
2019-05-07 22:27:23 -07:00
2019-06-28 21:11:30 +00:00
right_lane_visible = sm['pathPlan'].rProb > 0.5
left_lane_visible = sm['pathPlan'].lProb > 0.5
2019-05-07 22:27:23 -07:00
2019-06-28 21:11:30 +00:00
CC.hudControl.rightLaneVisible = bool(right_lane_visible)
CC.hudControl.leftLaneVisible = bool(left_lane_visible)
2019-05-07 22:27:23 -07:00
2019-06-28 21:11:30 +00:00
blinker = CS.leftBlinker or CS.rightBlinker
ldw_allowed = CS.vEgo > 12.5 and not blinker
2019-05-07 22:27:23 -07:00
2019-06-28 21:11:30 +00:00
if len(list(sm['pathPlan'].rPoly)) == 4:
2019-08-13 01:36:45 +00:00
CC.hudControl.rightLaneDepart = bool(ldw_allowed and sm['pathPlan'].rPoly[3] > -(1.08 + CAMERA_OFFSET) and right_lane_visible)
2019-06-28 21:11:30 +00:00
if len(list(sm['pathPlan'].lPoly)) == 4:
2019-08-13 01:36:45 +00:00
CC.hudControl.leftLaneDepart = bool(ldw_allowed and sm['pathPlan'].lPoly[3] < (1.08 - CAMERA_OFFSET) and left_lane_visible)
2019-05-07 22:27:23 -07:00
2019-06-28 21:11:30 +00:00
CC.hudControl.visualAlert = AM.visual_alert
2017-10-31 02:27:39 -07:00
2019-06-28 21:11:30 +00:00
if not read_only:
2017-10-31 02:27:39 -07:00
# send car controls over can
2019-06-06 04:38:45 +00:00
can_sends = CI.apply(CC)
2019-09-09 23:03:02 +00:00
pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
2019-02-20 01:39:02 +00:00
force_decel = driver_status.awareness < 0.
2017-09-30 03:07:27 -07:00
2019-06-06 04:38:45 +00:00
# controlsState
2017-09-30 03:07:27 -07:00
dat = messaging.new_message()
2019-06-06 04:38:45 +00:00
dat.init('controlsState')
2019-06-28 21:11:30 +00:00
dat.valid = CS.canValid
2019-06-06 04:38:45 +00:00
dat.controlsState = {
2018-07-12 18:52:06 -07:00
"alertText1": AM.alert_text_1,
"alertText2": AM.alert_text_2,
"alertSize": AM.alert_size,
"alertStatus": AM.alert_status,
"alertBlinkingRate": AM.alert_rate,
2018-10-21 15:00:31 -07:00
"alertType": AM.alert_type,
2019-08-13 01:36:45 +00:00
"alertSound": AM.audible_alert,
2019-10-09 18:43:53 +00:00
"awarenessStatus": max(driver_status.awareness, -0.1) if isEnabled(state) else 1.0,
2019-09-09 23:03:02 +00:00
"driverMonitoringOn": bool(driver_status.face_detected),
2018-07-12 18:52:06 -07:00
"canMonoTimes": list(CS.canMonoTimes),
2019-06-28 21:11:30 +00:00
"planMonoTime": sm.logMonoTime['plan'],
"pathPlanMonoTime": sm.logMonoTime['pathPlan'],
2018-07-12 18:52:06 -07:00
"enabled": isEnabled(state),
"active": isActive(state),
"vEgo": CS.vEgo,
"vEgoRaw": CS.vEgoRaw,
"angleSteers": CS.steeringAngle,
2019-07-25 17:00:50 -05:00
"curvature": VM.calc_curvature((CS.steeringAngle - sm['pathPlan'].angleOffset) * CV.DEG_TO_RAD, CS.vEgo),
2018-07-12 18:52:06 -07:00
"steerOverride": CS.steeringPressed,
"state": state,
"engageable": not bool(get_events(events, [ET.NO_ENTRY])),
"longControlState": LoC.long_control_state,
"vPid": float(LoC.v_pid),
"vCruise": float(v_cruise_kph),
"upAccelCmd": float(LoC.pid.p),
"uiAccelCmd": float(LoC.pid.i),
"ufAccelCmd": float(LoC.pid.f),
"angleSteersDes": float(LaC.angle_steers_des),
2019-02-20 01:39:02 +00:00
"vTargetLead": float(v_acc),
"aTarget": float(a_acc),
2019-06-28 21:11:30 +00:00
"jerkFactor": float(sm['plan'].jerkFactor),
"gpsPlannerActive": sm['plan'].gpsPlannerActive,
"vCurvature": sm['plan'].vCurvature,
2019-07-30 02:27:48 +00:00
"decelForModel": sm['plan'].longitudinalPlanSource == log.Plan.LongitudinalPlanSource.model,
2018-11-17 02:08:34 -08:00
"cumLagMs": -rk.remaining * 1000.,
2019-05-16 13:20:29 -07:00
"startMonoTime": int(start_time * 1e9),
2019-06-28 21:11:30 +00:00
"mapValid": sm['plan'].mapValid,
2019-02-20 01:39:02 +00:00
"forceDecel": bool(force_decel),
2018-07-12 18:52:06 -07:00
}
2019-05-16 13:20:29 -07:00
if CP.lateralTuning.which() == 'pid':
2019-06-06 04:38:45 +00:00
dat.controlsState.lateralControlState.pidState = lac_log
2019-08-13 01:36:45 +00:00
elif CP.lateralTuning.which() == 'lqr':
dat.controlsState.lateralControlState.lqrState = lac_log
elif CP.lateralTuning.which() == 'indi':
2019-06-06 04:38:45 +00:00
dat.controlsState.lateralControlState.indiState = lac_log
2019-09-09 23:03:02 +00:00
pm.send('controlsState', dat)
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# carState
2017-09-30 03:07:27 -07:00
cs_send = messaging.new_message()
cs_send.init('carState')
2019-06-28 21:11:30 +00:00
cs_send.valid = CS.canValid
2018-07-12 18:52:06 -07:00
cs_send.carState = CS
2018-03-19 23:40:24 -07:00
cs_send.carState.events = events
2019-09-09 23:03:02 +00:00
pm.send('carState', cs_send)
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
# carEvents - logged every second or on change
events_bytes = events_to_bytes(events)
if (sm.frame % int(1. / DT_CTRL) == 0) or (events_bytes != events_prev):
ce_send = messaging.new_message()
ce_send.init('carEvents', len(events))
ce_send.carEvents = events
2019-09-09 23:03:02 +00:00
pm.send('carEvents', ce_send)
2019-06-28 21:11:30 +00:00
# carParams - logged every 50 seconds (> 1 per segment)
if (sm.frame % int(50. / DT_CTRL) == 0):
cp_send = messaging.new_message()
cp_send.init('carParams')
cp_send.carParams = CP
2019-09-09 23:03:02 +00:00
pm.send('carParams', cp_send)
2019-06-28 21:11:30 +00:00
2018-11-17 02:08:34 -08:00
# carControl
2017-09-30 03:07:27 -07:00
cc_send = messaging.new_message()
cc_send.init('carControl')
2019-06-28 21:11:30 +00:00
cc_send.valid = CS.canValid
2018-07-12 18:52:06 -07:00
cc_send.carControl = CC
2019-09-09 23:03:02 +00:00
pm.send('carControl', cc_send)
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
return CC, events_bytes
2017-07-28 01:24:39 -07:00
2019-09-09 23:03:02 +00:00
def controlsd_thread(sm=None, pm=None, can_sock=None):
2018-07-12 18:52:06 -07:00
gc.disable()
2017-07-28 01:24:39 -07:00
# start the loop
2017-12-23 17:15:27 -08:00
set_realtime_priority(3)
2017-09-30 03:07:27 -07:00
2017-10-31 02:27:39 -07:00
params = Params()
2019-10-09 18:43:53 +00:00
is_metric = params.get("IsMetric", encoding='utf8') == "1"
passive = params.get("Passive", encoding='utf8') == "1"
openpilot_enabled_toggle = params.get("OpenpilotEnabledToggle", encoding='utf8') == "1"
passive = passive or not openpilot_enabled_toggle
2018-11-17 02:08:34 -08:00
2019-09-09 23:03:02 +00:00
# Pub/Sub Sockets
if pm is None:
pm = messaging.PubMaster(['sendcan', 'controlsState', 'carState', 'carControl', 'carEvents', 'carParams'])
if sm is None:
sm = messaging.SubMaster(['thermal', 'health', 'liveCalibration', 'driverMonitoring', 'plan', 'pathPlan', \
'gpsLocation'], ignore_alive=['gpsLocation'])
2019-07-22 19:17:47 +00:00
2019-10-09 18:43:53 +00:00
2019-09-09 23:03:02 +00:00
if can_sock is None:
can_timeout = None if os.environ.get('NO_CAN_TIMEOUT', False) else 100
2019-10-31 17:14:40 -07:00
can_sock = messaging.sub_sock('can', timeout=can_timeout)
2019-07-30 02:27:48 +00:00
# wait for health and CAN packets
hw_type = messaging.recv_one(sm.sock['health']).health.hwType
2019-10-09 18:43:53 +00:00
has_relay = hw_type in [HwType.blackPanda, HwType.uno]
2019-09-09 23:03:02 +00:00
print("Waiting for CAN messages...")
2019-10-31 17:14:40 -07:00
messaging.get_one_can(can_sock)
2019-07-22 19:17:47 +00:00
2019-10-09 18:43:53 +00:00
CI, CP = get_car(can_sock, pm.sock['sendcan'], has_relay)
2017-09-30 03:07:27 -07:00
2019-06-06 04:38:45 +00:00
car_recognized = CP.carName != 'mock'
# If stock camera is disconnected, we loaded car controls and it's not chffrplus
controller_available = CP.enableCamera and CI.CC is not None and not passive
2019-09-09 23:03:02 +00:00
read_only = not car_recognized or not controller_available or CP.dashcamOnly
2019-06-06 04:38:45 +00:00
if read_only:
2019-10-31 17:14:40 -07:00
CP.safetyModel = car.CarParams.SafetyModel.noOutput
2018-03-17 00:01:50 -07:00
2019-07-30 02:27:48 +00:00
# Write CarParams for radard and boardd safety mode
params.put("CarParams", CP.to_bytes())
params.put("LongitudinalControl", "1" if CP.openpilotLongitudinalControl else "0")
CC = car.CarControl.new_message()
AM = AlertManager()
2019-06-06 04:38:45 +00:00
startup_alert = get_startup_alert(car_recognized, controller_available)
2019-06-28 21:11:30 +00:00
AM.add(sm.frame, startup_alert, False)
2017-10-31 02:27:39 -07:00
2017-11-22 04:30:24 -08:00
LoC = LongControl(CP, CI.compute_gb)
2017-09-30 03:07:27 -07:00
VM = VehicleModel(CP)
2019-05-16 13:20:29 -07:00
if CP.lateralTuning.which() == 'pid':
LaC = LatControlPID(CP)
2019-08-13 01:36:45 +00:00
elif CP.lateralTuning.which() == 'indi':
2019-05-16 13:20:29 -07:00
LaC = LatControlINDI(CP)
2019-08-13 01:36:45 +00:00
elif CP.lateralTuning.which() == 'lqr':
LaC = LatControlLQR(CP)
2019-05-16 13:20:29 -07:00
2018-08-02 02:58:52 +00:00
driver_status = DriverStatus()
2019-09-09 23:03:02 +00:00
is_rhd = params.get("IsRHD")
if is_rhd is not None:
driver_status.is_rhd = bool(int(is_rhd))
2017-09-30 03:07:27 -07:00
2017-12-23 17:15:27 -08:00
state = State.disabled
2017-09-30 03:07:27 -07:00
soft_disable_timer = 0
v_cruise_kph = 255
2018-07-12 18:52:06 -07:00
v_cruise_kph_last = 0
2017-10-03 23:40:21 -07:00
overtemp = False
free_space = False
2018-09-25 00:13:41 -07:00
cal_status = Calibration.INVALID
cal_perc = 0
2018-07-12 18:52:06 -07:00
mismatch_counter = 0
2018-09-25 00:13:41 -07:00
low_battery = False
2019-06-28 21:11:30 +00:00
events_prev = []
2017-09-30 03:07:27 -07:00
2019-06-28 21:11:30 +00:00
sm['pathPlan'].sensorValid = True
2019-07-30 02:27:48 +00:00
sm['pathPlan'].posenetValid = True
2017-09-30 03:07:27 -07:00
2019-08-13 01:36:45 +00:00
# detect sound card presence
sounds_available = not os.path.isfile('/EON') or (os.path.isdir('/proc/asound/card0') and open('/proc/asound/card0/state').read().strip() == 'ONLINE')
2019-06-06 04:38:45 +00:00
# controlsd is driven by can recv, expected at 100Hz
rk = Ratekeeper(100, print_delay_threshold=None)
2017-09-30 03:07:27 -07:00
2019-10-31 17:14:40 -07:00
internet_needed = params.get("Offroad_ConnectivityNeeded", encoding='utf8') is not None
2019-10-09 18:43:53 +00:00
2017-12-23 17:15:27 -08:00
prof = Profiler(False) # off by default
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
while True:
2019-05-16 13:20:29 -07:00
start_time = sec_since_boot()
2018-06-16 20:59:34 -07:00
prof.checkpoint("Ratekeeper", ignore=True)
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# Sample data and compute car events
2019-06-28 21:11:30 +00:00
CS, events, cal_status, cal_perc, overtemp, free_space, low_battery, mismatch_counter =\
2019-10-31 17:14:40 -07:00
data_sample(CI, CC, sm, can_sock, cal_status, cal_perc, overtemp, free_space, low_battery,
2019-06-28 21:11:30 +00:00
driver_status, state, mismatch_counter, params)
2017-09-30 03:07:27 -07:00
prof.checkpoint("Sample")
2019-05-16 13:20:29 -07:00
# Create alerts
2019-06-28 21:11:30 +00:00
if not sm.all_alive_and_valid():
events.append(create_event('commIssue', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if not sm['pathPlan'].mpcSolutionValid:
events.append(create_event('plannerError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
if not sm['pathPlan'].sensorValid:
2019-06-06 04:38:45 +00:00
events.append(create_event('sensorDataInvalid', [ET.NO_ENTRY, ET.PERMANENT]))
2019-06-28 21:11:30 +00:00
if not sm['pathPlan'].paramsValid:
2019-03-26 01:09:18 -07:00
events.append(create_event('vehicleModelInvalid', [ET.WARNING]))
2019-07-30 02:27:48 +00:00
if not sm['pathPlan'].posenetValid:
events.append(create_event('posenetInvalid', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
2019-06-28 21:11:30 +00:00
if not sm['plan'].radarValid:
2019-05-16 13:20:29 -07:00
events.append(create_event('radarFault', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
2019-06-28 21:11:30 +00:00
if sm['plan'].radarCanError:
events.append(create_event('radarCanError', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if not CS.canValid:
events.append(create_event('canError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
2019-08-13 01:36:45 +00:00
if not sounds_available:
events.append(create_event('soundsUnavailable', [ET.NO_ENTRY, ET.PERMANENT]))
2019-10-09 18:43:53 +00:00
if internet_needed:
events.append(create_event('internetConnectivityNeeded', [ET.NO_ENTRY, ET.PERMANENT]))
2019-02-20 01:39:02 +00:00
# Only allow engagement with brake pressed when stopped behind another stopped car
2019-06-28 21:11:30 +00:00
if CS.brakePressed and sm['plan'].vTargetFuture >= STARTING_TARGET_SPEED and not CP.radarOffCan and CS.vEgo < 0.3:
2019-02-20 01:39:02 +00:00
events.append(create_event('noTarget', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
2017-09-30 03:07:27 -07:00
2019-06-06 04:38:45 +00:00
if not read_only:
2017-10-31 02:27:39 -07:00
# update control state
2018-07-12 18:52:06 -07:00
state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last = \
2019-06-28 21:11:30 +00:00
state_transition(sm.frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM)
2017-10-31 02:27:39 -07:00
prof.checkpoint("State transition")
2017-09-30 03:07:27 -07:00
2018-11-17 02:08:34 -08:00
# Compute actuators (runs PID loops and lateral MPC)
2019-06-28 21:11:30 +00:00
actuators, v_cruise_kph, driver_status, v_acc, a_acc, lac_log = \
state_control(sm.frame, sm.rcv_frame, sm['plan'], sm['pathPlan'], CS, CP, state, events, v_cruise_kph, v_cruise_kph_last, AM, rk,
2019-10-09 18:43:53 +00:00
driver_status, LaC, LoC, read_only, is_metric, cal_perc)
2019-02-20 01:39:02 +00:00
2017-09-30 03:07:27 -07:00
prof.checkpoint("State Control")
2018-11-17 02:08:34 -08:00
# Publish data
2019-09-09 23:03:02 +00:00
CC, events_prev = data_send(sm, pm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, AM, driver_status, LaC,
LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev)
2017-09-30 03:07:27 -07:00
prof.checkpoint("Sent")
2019-06-06 04:38:45 +00:00
rk.monitor_time()
2017-12-23 17:15:27 -08:00
prof.display()
2017-07-28 01:24:39 -07:00
2016-11-29 18:34:21 -08:00
2019-09-09 23:03:02 +00:00
def main(sm=None, pm=None, logcan=None):
controlsd_thread(sm, pm, logcan)
2016-11-29 18:34:21 -08:00
2018-11-17 02:08:34 -08:00
2016-11-29 18:34:21 -08:00
if __name__ == "__main__":
main()