Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3ff579607a |
@@ -1,15 +1,12 @@
|
||||
import numpy as np
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from opendbc.car.common.filter_simple import FirstOrderFilter
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import Bus, DT_CTRL, make_tester_present_msg, structs, rate_limit
|
||||
from opendbc.car.lateral import apply_driver_steer_torque_limits, common_fault_avoidance, apply_steer_angle_limits_vm
|
||||
from opendbc.car import Bus, DT_CTRL, make_tester_present_msg, structs
|
||||
from opendbc.car.lateral import apply_driver_steer_torque_limits, common_fault_avoidance
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.hyundai import hyundaicanfd, hyundaican
|
||||
from opendbc.car.hyundai.hyundaicanfd import CanBus
|
||||
from opendbc.car.hyundai.values import HyundaiFlags, Buttons, CarControllerParams, CAR
|
||||
from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.hyundai.torque_reduction_gain import TorqueReductionGainController
|
||||
|
||||
from opendbc.sunnypilot.car.hyundai.escc import EsccCarController
|
||||
from opendbc.sunnypilot.car.hyundai.icbm import IntelligentCruiseButtonManagementInterface
|
||||
@@ -32,13 +29,6 @@ MAX_ANGLE_CONSECUTIVE_FRAMES = 2
|
||||
# naturally on brake press. We send ~100 ms later if it fails to do so, or if we want to cancel for another reason.
|
||||
CANCEL_BUTTON_DELAY_FRAMES = 10
|
||||
|
||||
ANGLE_SAFETY_BASELINE_MODEL = "GENESIS_GV80_2025"
|
||||
|
||||
|
||||
def get_baseline_safety_cp():
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
return CarInterface.get_non_essential_params(ANGLE_SAFETY_BASELINE_MODEL)
|
||||
|
||||
|
||||
def process_hud_alert(enabled, fingerprint, hud_control):
|
||||
sys_warning = (hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw))
|
||||
@@ -64,58 +54,6 @@ def process_hud_alert(enabled, fingerprint, hud_control):
|
||||
return sys_warning, sys_state, left_lane_warning, right_lane_warning
|
||||
|
||||
|
||||
def compute_torque_reduction_gain(steering_torque, v_ego, lat_active, last_gain):
|
||||
if lat_active:
|
||||
# full torque at near-stop
|
||||
ceiling = np.interp(v_ego, [0.5, 1.5], [1.0, 0.85])
|
||||
# # target = np.interp(abs(steering_torque), [75, 400], [ceiling, 0.2])
|
||||
# # stock reduces gain earlier depending on speed
|
||||
# start_bp = np.interp(v_ego, [2, 11], [75, 125])
|
||||
# shelf_bp = start_bp + 25
|
||||
# # shelf_bp = np.interp(v_ego, [2, 11], [])
|
||||
#
|
||||
# target = np.interp(abs(steering_torque), [start_bp, shelf_bp + 25, shelf_bp + 100, 400],
|
||||
# [ceiling, 0.5, 0.5, 0.2])
|
||||
|
||||
shelf = np.interp(v_ego, [2, 11], [0.45, 0.6])
|
||||
floor = np.interp(v_ego, [2, 22], [0.1, 0.3])
|
||||
bp1 = np.interp(v_ego, [2, 11], [75, 125])
|
||||
bp2 = np.interp(v_ego, [2, 11], [125, 150])
|
||||
bp3 = np.interp(v_ego, [2, 11], [175, 275])
|
||||
bp4 = np.interp(v_ego, [2, 22], [400, 700])
|
||||
target = np.interp(abs(steering_torque), [bp1, bp2, bp3, bp4], [ceiling, shelf, shelf, floor])
|
||||
|
||||
else:
|
||||
target = 0.0
|
||||
gain = rate_limit(target, last_gain, -0.014, 0.004)
|
||||
return round(gain / 0.004) * 0.004
|
||||
|
||||
|
||||
def sp_smooth_angle(v_ego_raw: float, apply_angle: float, apply_angle_last: float) -> float:
|
||||
"""
|
||||
Smooth the steering angle change based on vehicle speed and an optional smoothing offset.
|
||||
|
||||
This function helps prevent abrupt steering changes by blending the new desired angle (`apply_angle`)
|
||||
with the previously applied angle (`apply_angle_last`). The blend factor (alpha) is dynamically calculated
|
||||
based on the vehicle's current speed using a predefined lookup table.
|
||||
|
||||
Behavior:
|
||||
- At low speeds, the smoothing is strong, keeping the steering more stable.
|
||||
- At higher speeds, the smoothing is relaxed, allowing quicker responses.
|
||||
|
||||
Parameters:
|
||||
v_ego_raw (float): Raw vehicle speed in m/s.
|
||||
apply_angle (float): New target steering angle in degrees.
|
||||
apply_angle_last (float): Previously applied steering angle in degrees.
|
||||
|
||||
Returns:
|
||||
float: Smoothed steering angle.
|
||||
"""
|
||||
adjusted_alpha = np.interp(v_ego_raw, CarControllerParams.SMOOTHING_ANGLE_VEGO_MATRIX, CarControllerParams.SMOOTHING_ANGLE_ALPHA_MATRIX)
|
||||
adjusted_alpha_limited = float(min(float(adjusted_alpha), 1.)) # Limit the smoothing factor to 1 if adjusted_alpha is greater than 1
|
||||
return (apply_angle * adjusted_alpha_limited) + (apply_angle_last * (1 - adjusted_alpha_limited))
|
||||
|
||||
|
||||
class CarController(CarControllerBase, EsccCarController, LeadDataCarController, LongitudinalController, MadsCarController,
|
||||
IntelligentCruiseButtonManagementInterface):
|
||||
def __init__(self, dbc_names, CP, CP_SP):
|
||||
@@ -129,8 +67,6 @@ class CarController(CarControllerBase, EsccCarController, LeadDataCarController,
|
||||
self.params = CarControllerParams(CP)
|
||||
self.packer = CANPacker(dbc_names[Bus.pt])
|
||||
self.angle_limit_counter = 0
|
||||
self.angle_filter = FirstOrderFilter(0.0, 0.1, 0.01)
|
||||
self.angle_steady = 0
|
||||
|
||||
self.accel_last = 0
|
||||
self.apply_torque_last = 0
|
||||
@@ -138,13 +74,6 @@ class CarController(CarControllerBase, EsccCarController, LeadDataCarController,
|
||||
self.last_button_frame = 0
|
||||
self.cancel_counter = 0
|
||||
|
||||
self.apply_angle_last = 0
|
||||
|
||||
# Vehicle model used for angle steering lateral limiting
|
||||
self.VM = VehicleModel(get_baseline_safety_cp())
|
||||
|
||||
self.torque_reduction_gain_controller = TorqueReductionGainController()
|
||||
|
||||
def update(self, CC, CC_SP, CS, now_nanos):
|
||||
EsccCarController.update(self, CS)
|
||||
LeadDataCarController.update(self, CC_SP)
|
||||
@@ -155,47 +84,17 @@ class CarController(CarControllerBase, EsccCarController, LeadDataCarController,
|
||||
actuators = CC.actuators
|
||||
hud_control = CC.hudControl
|
||||
|
||||
# angle control
|
||||
if self.CP.flags & HyundaiFlags.CANFD_ANGLE_STEERING:
|
||||
desired_angle = actuators.steeringAngleDeg
|
||||
# steering torque
|
||||
new_torque = int(round(actuators.torque * self.params.STEER_MAX))
|
||||
apply_torque = apply_driver_steer_torque_limits(new_torque, self.apply_torque_last, CS.out.steeringTorque, self.params)
|
||||
|
||||
# EPS is sensitive to small jitter from model desired angle at low speed,
|
||||
# so we apply speed-dependent smoothing to prevent this.
|
||||
if CC.latActive:
|
||||
# deadzone = np.interp(CS.out.vEgo, [10, 15], [2, 0])
|
||||
# desired_angle = apply_hysteresis(desired_angle, self.angle_steady, deadzone)
|
||||
# self.angle_steady = desired_angle
|
||||
# >90 degree steering fault prevention
|
||||
self.angle_limit_counter, apply_steer_req = common_fault_avoidance(abs(CS.out.steeringAngleDeg) >= MAX_ANGLE, CC.latActive,
|
||||
self.angle_limit_counter, MAX_ANGLE_FRAMES,
|
||||
MAX_ANGLE_CONSECUTIVE_FRAMES)
|
||||
|
||||
# self.angle_filter.update_alpha(float(np.interp(CS.out.vEgo, [15, 20], [0.25, 0.0])))
|
||||
self.angle_filter.update_alpha(float(np.interp(CS.out.vEgo, [5, 10, 20], [0.2, 0.1, 0.0])))
|
||||
desired_angle = self.angle_filter.update(desired_angle)
|
||||
|
||||
self.apply_angle_last = apply_steer_angle_limits_vm(desired_angle, self.apply_angle_last,
|
||||
CS.out.vEgoRaw, CS.out.steeringAngleDeg,
|
||||
CC.latActive, self.params, self.VM)
|
||||
|
||||
# TODO: consider angle direction so you can override in direction and it doesn't reduce torque as much
|
||||
# TODO: max_allowed_torque
|
||||
apply_torque = compute_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
|
||||
CC.latActive, self.apply_torque_last)
|
||||
|
||||
apply_steer_req = CC.latActive
|
||||
if not CC.latActive:
|
||||
self.angle_filter.x = self.apply_angle_last
|
||||
self.angle_steady = self.apply_angle_last
|
||||
|
||||
# torque control
|
||||
else:
|
||||
new_torque = int(round(actuators.torque * self.params.STEER_MAX))
|
||||
apply_torque = apply_driver_steer_torque_limits(new_torque, self.apply_torque_last, CS.out.steeringTorque, self.params)
|
||||
|
||||
# >90 degree steering fault prevention
|
||||
self.angle_limit_counter, apply_steer_req = common_fault_avoidance(abs(CS.out.steeringAngleDeg) >= MAX_ANGLE, CC.latActive,
|
||||
self.angle_limit_counter, MAX_ANGLE_FRAMES,
|
||||
MAX_ANGLE_CONSECUTIVE_FRAMES)
|
||||
|
||||
if not CC.latActive:
|
||||
apply_torque = 0
|
||||
if not CC.latActive:
|
||||
apply_torque = 0
|
||||
|
||||
self.apply_torque_last = apply_torque
|
||||
|
||||
@@ -243,7 +142,6 @@ class CarController(CarControllerBase, EsccCarController, LeadDataCarController,
|
||||
new_actuators = actuators.as_builder()
|
||||
new_actuators.torque = apply_torque / self.params.STEER_MAX
|
||||
new_actuators.torqueOutputCan = apply_torque
|
||||
new_actuators.steeringAngleDeg = self.apply_angle_last
|
||||
new_actuators.accel = self.tuning.actual_accel
|
||||
|
||||
self.frame += 1
|
||||
@@ -304,8 +202,7 @@ class CarController(CarControllerBase, EsccCarController, LeadDataCarController,
|
||||
lka_steering_long = lka_steering and self.CP.openpilotLongitudinalControl
|
||||
|
||||
# steering control
|
||||
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN, CC.enabled, apply_steer_req,
|
||||
apply_torque, self.apply_angle_last, self.lkas_icon))
|
||||
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN, CC.enabled, apply_steer_req, apply_torque, self.lkas_icon))
|
||||
|
||||
# prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
|
||||
if self.frame % 5 == 0 and lka_steering:
|
||||
|
||||
@@ -70,7 +70,6 @@ class CarState(CarStateBase, EsccCarStateBase, MadsCarState, CarStateExt):
|
||||
self.cluster_speed_counter = CLUSTER_SAMPLE_RATE
|
||||
|
||||
self.params = CarControllerParams(CP)
|
||||
self.is_canfd_angle_steering = CP.flags & HyundaiFlags.CANFD_ANGLE_STEERING
|
||||
|
||||
def recent_button_interaction(self) -> bool:
|
||||
# On some newer model years, the CANCEL button acts as a pause/resume button based on the PCM state
|
||||
@@ -251,20 +250,15 @@ class CarState(CarStateBase, EsccCarStateBase, MadsCarState, CarStateExt):
|
||||
cp.vl["WHEEL_SPEEDS"]["WHL_SpdRLVal"] <= STANDSTILL_THRESHOLD and cp.vl["WHEEL_SPEEDS"]["WHL_SpdRRVal"] <= STANDSTILL_THRESHOLD
|
||||
|
||||
ret.steeringRateDeg = cp.vl["STEERING_SENSORS"]["STEERING_RATE"]
|
||||
ret.steeringAngleDeg = cp.vl["STEERING_SENSORS"]["STEERING_ANGLE"]
|
||||
ret.steeringTorque = cp.vl["MDPS"]["MDPS_StrTqSnsrVal"]
|
||||
ret.steeringTorqueEps = cp.vl["MDPS"]["MDPS_OutTqVal"]
|
||||
ret.steeringPressed = self.update_steering_pressed(abs(ret.steeringTorque) > self.params.STEER_THRESHOLD, 5)
|
||||
|
||||
if self.is_canfd_angle_steering:
|
||||
ret.steeringAngleDeg = cp.vl["MDPS"]["MDPS_EstStrAnglVal"]
|
||||
ret.steerFaultTemporary = cp.vl["MDPS"]["MDPS_LkaFailSta"] != 0 or cp.vl["MDPS"]["MDPS_ADAS_AciFltSig_Lv2"] != 0
|
||||
else:
|
||||
ret.steeringAngleDeg = cp.vl["STEERING_SENSORS"]["STEERING_ANGLE"]
|
||||
ret.steerFaultTemporary = cp.vl["MDPS"]["MDPS_LkaFailSta"] != 0
|
||||
ret.steerFaultTemporary = cp.vl["MDPS"]["MDPS_LkaFailSta"] != 0
|
||||
|
||||
# TODO: alt signal usage may be described by cp.vl['BLINKERS']['USE_ALT_LAMP']
|
||||
left_blinker_sig, right_blinker_sig = "LEFT_LAMP", "RIGHT_LAMP"
|
||||
if self.CP.carFingerprint == CAR.HYUNDAI_KONA_EV_2ND_GEN or self.is_canfd_angle_steering:
|
||||
if self.CP.carFingerprint == CAR.HYUNDAI_KONA_EV_2ND_GEN:
|
||||
left_blinker_sig, right_blinker_sig = "LEFT_LAMP_ALT", "RIGHT_LAMP_ALT"
|
||||
ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp(50, cp.vl["BLINKERS"][left_blinker_sig],
|
||||
cp.vl["BLINKERS"][right_blinker_sig])
|
||||
|
||||
@@ -1069,17 +1069,6 @@ FW_VERSIONS = {
|
||||
b'\xf1\x00NE1 MFC AT USA LHD 1.00 1.06 99211-GI010 230110',
|
||||
],
|
||||
},
|
||||
CAR.HYUNDAI_IONIQ_5_PE: {
|
||||
(Ecu.fwdRadar, 0x7d0, None): [
|
||||
b'\xf1\x00NE__ RDR ----- 1.00 1.00 99110-PI000 ',
|
||||
b'\xf1\x00NE__ RDR ----- 1.00 1.01 99110-GI500 '
|
||||
],
|
||||
(Ecu.fwdCamera, 0x7C4, None): [
|
||||
b'\xf1\x00NE MFC AT USA LHD 1.00 1.01 99211-PI000 240905',
|
||||
b'\xf1\x00NE MFC AT EUR LHD 1.00 1.03 99211-GI500 240809',
|
||||
b'\xf1\x00NE MFC AT USA LHD 1.00 1.00 99211-PI010 250407',
|
||||
],
|
||||
},
|
||||
CAR.HYUNDAI_IONIQ_6: {
|
||||
(Ecu.fwdRadar, 0x7d0, None): [
|
||||
b'\xf1\x00CE__ RDR ----- 1.00 1.01 99110-KL000 ',
|
||||
@@ -1311,16 +1300,6 @@ FW_VERSIONS = {
|
||||
b'\xf1\x00T01G00BL T01I00A1 DOS2T16X4XI00NS0\x99L\xeeq',
|
||||
],
|
||||
},
|
||||
CAR.GENESIS_GV80_2025: {
|
||||
(Ecu.fwdRadar, 0x7d0, None): [
|
||||
b'\xf1\x00JX__ RDR ----- 1.00 1.03 99110-T6500 ',
|
||||
],
|
||||
(Ecu.fwdCamera, 0x7c4, None): [
|
||||
b'\xf1\x00JX MFC AT USA LHD 1.00 1.03 99211-T6510 240124',
|
||||
b'\xf1\x00JX MFC AT USA LHD 1.00 1.04 99211-T6510 240502',
|
||||
b'\xf1\x00JX MFC AT USA LHD 1.00 1.12 99211-T6600 250423',
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
FW_VERSIONS = merge_fw_versions(FW_VERSIONS, FW_VERSIONS_EXT)
|
||||
|
||||
@@ -36,7 +36,7 @@ class CanBus(CanBusBase):
|
||||
return self._cam
|
||||
|
||||
|
||||
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, apply_angle, lkas_icon):
|
||||
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, lkas_icon):
|
||||
values = {
|
||||
"LKA_OptUsmSta": 2,
|
||||
"LKA_SysIndReq": lkas_icon,
|
||||
@@ -44,23 +44,10 @@ def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque,
|
||||
"LKA_SysWrn": 0,
|
||||
"ActToiSta": 1 if lat_active else 0,
|
||||
"LKA_UsmMod": 0, # hide LKAS settings
|
||||
"LKA_RcgSta": 0, # lane recognition status (0 for "not recognized")
|
||||
"LKA_RcgSta": 0,
|
||||
"Damping_Gain": 100, # can potentially tuned for better perf [3, 200]
|
||||
}
|
||||
|
||||
# Angle control doesn't support using LFA yet
|
||||
if CP.flags & HyundaiFlags.CANFD_ANGLE_STEERING:
|
||||
# LKAS messages take priority over LFA messages on HDA2.
|
||||
values |= {
|
||||
"LKA_OptUsmSta": 0, # TODO: not used by the stock system
|
||||
"StrTqReqVal": 0, # we don't use torque
|
||||
"ActToiSta": 0, # we don't use torque
|
||||
"LKA_RcgSta": 3 if lat_active else 0,
|
||||
"ADAS_StrAnglReqVal": apply_angle,
|
||||
"LKAS_ANGLE_ACTIVE": 2 if lat_active else 1,
|
||||
"ADAS_ACIAnglTqRedcGainVal": apply_torque if lat_active else 0,
|
||||
}
|
||||
|
||||
ret = []
|
||||
if CP.flags & HyundaiFlags.CANFD_LKA_STEER_MSG:
|
||||
lkas_msg = "LKAS_ALT" if CP.flags & HyundaiFlags.CANFD_LKA_STEER_MSG_ALT else "LKAS"
|
||||
|
||||
@@ -48,10 +48,6 @@ class CarInterface(CarInterfaceBase):
|
||||
|
||||
ret.enableBsm = 0x1ba in fingerprint[CAN.ECAN]
|
||||
|
||||
# no longitudinal for all lka_steering angle steering
|
||||
if lka_steering and ret.flags & HyundaiFlags.CANFD_ANGLE_STEERING:
|
||||
ret.alphaLongitudinalAvailable = False
|
||||
|
||||
# Check if the car is hybrid. Only HEV/PHEV cars have 0xFA on E-CAN.
|
||||
if 0xFA in fingerprint[CAN.ECAN]:
|
||||
ret.flags |= HyundaiFlags.HYBRID.value
|
||||
@@ -89,9 +85,6 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.safetyConfigs[-1].safetyParam |= HyundaiSafetyFlags.CANFD_ALT_BUTTONS.value
|
||||
if ret.flags & HyundaiFlags.CANFD_CAMERA_SCC:
|
||||
ret.safetyConfigs[-1].safetyParam |= HyundaiSafetyFlags.CAMERA_SCC.value
|
||||
if ret.flags & HyundaiFlags.CANFD_ANGLE_STEERING:
|
||||
ret.steerControlType = structs.CarParams.SteerControlType.angle
|
||||
ret.safetyConfigs[-1].safetyParam |= HyundaiSafetyFlags.CANFD_ANGLE_STEERING.value
|
||||
|
||||
else:
|
||||
# Shared configuration for non CAN-FD cars
|
||||
@@ -124,8 +117,7 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.centerToFront = ret.wheelbase * 0.4
|
||||
ret.steerActuatorDelay = 0.1
|
||||
ret.steerLimitTimer = 0.4
|
||||
if not (ret.flags & HyundaiFlags.CANFD_ANGLE_STEERING):
|
||||
CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning)
|
||||
CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning)
|
||||
|
||||
if ret.flags & HyundaiFlags.ALT_LIMITS:
|
||||
ret.safetyConfigs[-1].safetyParam |= HyundaiSafetyFlags.ALT_LIMITS.value
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import numpy as np
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
|
||||
|
||||
class TorqueReductionGainController:
|
||||
"""
|
||||
Controls the ADAS_ACIAnglTqRedcGainVal signal for HKG CAN-FD angle steering.
|
||||
|
||||
The gain controls how hard the EPS tries to track the commanded angle:
|
||||
- Speed-dependent ceiling: higher at highway speed for precision,
|
||||
lower at low speed to reduce EPS internal PID oscillation.
|
||||
- Override: drops gain when steeringPressed for easy driver takeover.
|
||||
- Smooth ramp: prevents sudden gain changes that jerk the steering.
|
||||
"""
|
||||
|
||||
SPEED_BP = [0., 10., 30., 50., 80.] # km/h
|
||||
SPEED_CEILING = [0.55, 0.55, 0.75, 0.90, 1.0]
|
||||
|
||||
OVERRIDE_FACTOR = 0.1
|
||||
|
||||
RAMP_RATE = 0.008
|
||||
RECOVERY_RATE = 0.02
|
||||
OVERRIDE_DROP_RATE = 0.05
|
||||
|
||||
def __init__(self):
|
||||
self.gain = 0.0
|
||||
self._was_overriding = False
|
||||
|
||||
def update(self, steering_pressed: bool, lat_active: bool, v_ego: float) -> float:
|
||||
if not lat_active:
|
||||
target = 0.0
|
||||
self._was_overriding = False
|
||||
else:
|
||||
speed_kmh = v_ego * CV.MS_TO_KPH
|
||||
ceiling = float(np.interp(speed_kmh, self.SPEED_BP, self.SPEED_CEILING))
|
||||
target = ceiling * self.OVERRIDE_FACTOR if steering_pressed else ceiling
|
||||
|
||||
if steering_pressed:
|
||||
self._was_overriding = True
|
||||
elif self._was_overriding and lat_active and self.gain >= target - 0.001:
|
||||
self._was_overriding = False
|
||||
|
||||
if target < self.gain:
|
||||
rate = self.OVERRIDE_DROP_RATE if steering_pressed else self.RAMP_RATE
|
||||
self.gain = max(self.gain - rate, target)
|
||||
else:
|
||||
rate = self.RECOVERY_RATE if self._was_overriding else self.RAMP_RATE
|
||||
self.gain = min(self.gain + rate, target)
|
||||
|
||||
return self.gain
|
||||
@@ -3,7 +3,6 @@ from dataclasses import dataclass, field
|
||||
from enum import IntFlag
|
||||
|
||||
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, uds
|
||||
from opendbc.car.lateral import AngleSteeringLimitsVM
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.docs_definitions import CarHarness, CarDocs, CarParts, SupportType
|
||||
@@ -18,22 +17,6 @@ class CarControllerParams:
|
||||
ACCEL_MIN = -3.5 # m/s^2
|
||||
ACCEL_MAX = 2.0 # m/s^2
|
||||
|
||||
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
|
||||
# Steering angle limits based on observed stock ADAS behavior:
|
||||
# - LKAS max requested angle is 176.7°, but no fault occurs if higher values are requested.
|
||||
# - LFA max stock value is 119.9°.
|
||||
# The ADAS ECU clamps LKAS commands above 176.7° down to 176.7°,
|
||||
# and clamps LFA commands above 119.9° down to 119.9°.
|
||||
360, # degrees (must match safety max_angle / angle_deg_to_can)
|
||||
MAX_ANGLE_RATE=5 # comfort rate limit for angle commands, in degrees per frame.
|
||||
)
|
||||
|
||||
# More torque optimization
|
||||
# The torque is calculated based on the curvature of the road and the speed of the car and it's a percentage of the maximum torque.
|
||||
SMOOTHING_ANGLE_VEGO_MATRIX = [0, 8.5, 11, 13.8, 18]
|
||||
SMOOTHING_ANGLE_ALPHA_MATRIX = [0.05, 0.1, 0.3, 0.6, 1]
|
||||
SMOOTHING_ANGLE_MAX_VEGO = SMOOTHING_ANGLE_VEGO_MATRIX[-1]
|
||||
|
||||
def __init__(self, CP):
|
||||
self.STEER_DELTA_UP = 3
|
||||
self.STEER_DELTA_DOWN = 7
|
||||
@@ -85,7 +68,6 @@ class HyundaiSafetyFlags(IntFlag):
|
||||
CANFD_LKA_STEER_MSG_ALT = 128
|
||||
FCEV_GAS = 256
|
||||
ALT_LIMITS_2 = 512
|
||||
CANFD_ANGLE_STEERING = 1024
|
||||
|
||||
|
||||
# Hyundai/Kia/Genesis SCC (Smart Cruise Control) and steering architecture:
|
||||
@@ -167,8 +149,6 @@ class HyundaiFlags(IntFlag):
|
||||
|
||||
ALT_LIMITS_2 = 2 ** 26
|
||||
|
||||
CANFD_ANGLE_STEERING = 2 ** 27
|
||||
|
||||
|
||||
@dataclass
|
||||
class HyundaiCarDocs(CarDocs):
|
||||
@@ -403,14 +383,6 @@ class CAR(Platforms):
|
||||
CarSpecs(mass=1948, wheelbase=2.97, steerRatio=14.26, tireStiffnessFactor=0.65),
|
||||
flags=HyundaiFlags.EV,
|
||||
)
|
||||
HYUNDAI_IONIQ_5_PE = HyundaiCanFDPlatformConfig(
|
||||
[
|
||||
HyundaiCarDocs("Hyundai Ioniq 5 PE (with HDA II & LFA2) 2025-26", "Highway Driving Assist II & Lane Follow Assist 2",
|
||||
car_parts=CarParts.common([CarHarness.hyundai_q]))
|
||||
],
|
||||
HYUNDAI_IONIQ_5.specs,
|
||||
flags=HyundaiFlags.EV | HyundaiFlags.CANFD_ANGLE_STEERING,
|
||||
)
|
||||
HYUNDAI_IONIQ_6 = HyundaiCanFDPlatformConfig(
|
||||
[
|
||||
HyundaiCarDocs("Hyundai Ioniq 6 (without HDA II) 2023-24", "Highway Driving Assist", car_parts=CarParts.common([CarHarness.hyundai_l])),
|
||||
@@ -708,18 +680,6 @@ class CAR(Platforms):
|
||||
flags=HyundaiFlags.CHECKSUM_CRC8,
|
||||
sp_flags=HyundaiFlagsSP.NON_SCC_RADAR_FCA,
|
||||
)
|
||||
GENESIS_GV80_2025 = HyundaiCanFDPlatformConfig(
|
||||
[
|
||||
HyundaiCarDocs("Genesis GV80 (3.5T, with HDA2 & LFA2) 2025-26", "Highway Driving Assist 2 & Lane Follow Assist 2",
|
||||
car_parts=CarParts.common([CarHarness.hyundai_q])),
|
||||
HyundaiCarDocs("Genesis GV80 Coupe (3.5 T, with HDA2 & LFA2) 2025-26", "Highway Driving Assist 2 & Lane Follow Assist 2",
|
||||
car_parts=CarParts.common([CarHarness.hyundai_q])),
|
||||
HyundaiCarDocs("Genesis GV80 (2.5T, with HDA2 & LFA2) 2025-26", "Highway Driving Assist 2 & Lane Follow Assist 2",
|
||||
car_parts=CarParts.common([CarHarness.hyundai_r])),
|
||||
],
|
||||
GENESIS_GV80.specs,
|
||||
flags=HyundaiFlags.CANFD_ANGLE_STEERING,
|
||||
)
|
||||
|
||||
|
||||
class Buttons:
|
||||
|
||||
@@ -44,7 +44,6 @@ non_tested_cars = [
|
||||
HYUNDAI.KIA_FORTE_2021_NON_SCC,
|
||||
HYUNDAI.KIA_SELTOS_2023_NON_SCC,
|
||||
HYUNDAI.GENESIS_G70_2021_NON_SCC,
|
||||
HYUNDAI.HYUNDAI_IONIQ_5_PE,
|
||||
HONDA.HONDA_CLARITY,
|
||||
GM.CHEVROLET_BOLT_NON_ACC,
|
||||
GM.CHEVROLET_BOLT_NON_ACC_1ST_GEN,
|
||||
@@ -236,7 +235,6 @@ routes = [
|
||||
CarTestRoute("7120aa90bbc3add7/2021-08-02--07-12-31", HYUNDAI.HYUNDAI_SONATA_HYBRID),
|
||||
CarTestRoute("715ac05b594e9c59/2021-10-27--23-24-56", HYUNDAI.GENESIS_G70_2020),
|
||||
CarTestRoute("6b0d44d22df18134/2023-05-06--10-36-55", HYUNDAI.GENESIS_GV80),
|
||||
CarTestRoute("1779f6dcf3ba4edb/00000002--974d547296", HYUNDAI.GENESIS_GV80_2025),
|
||||
|
||||
CarTestRoute("00c829b1b7613dea/2021-06-24--09-10-10", TOYOTA.TOYOTA_ALPHARD_TSS2),
|
||||
CarTestRoute("912119ebd02c7a42/2022-03-19--07-24-50", TOYOTA.TOYOTA_ALPHARD_TSS2), # hybrid
|
||||
|
||||
@@ -116,7 +116,3 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"]
|
||||
# port extensions
|
||||
"HONDA_CLARITY" = [0.96, 0.4018518740819229, 0.19]
|
||||
"CHEVROLET_MALIBU_NON_ACC_9TH_GEN" = [1.85, 1.85, 0.075]
|
||||
|
||||
# Hyundai/Kia/Genesis angle control
|
||||
"GENESIS_GV80_2025" = [2.5, 2.5, 0.1]
|
||||
"HYUNDAI_IONIQ_5_PE" = [3.172929, 3.5, 0.096019]
|
||||
|
||||
@@ -209,9 +209,6 @@ BO_ 298 LFA: 16 ADRV
|
||||
SG_ ELK_SymbDisp : 90|3@1+ (1,0) [0|7] "" ADRV
|
||||
SG_ FCA_ESA_WrnSta : 93|1@1+ (1,0) [0|7] "" ADRV
|
||||
SG_ FCA_ESA_CtrlSta : 101|1@1+ (1,0) [0|7] "" ADRV
|
||||
SG_ LKAS_ANGLE_ACTIVE : 77|2@0+ (1,0) [0|3] "" XXX
|
||||
SG_ ADAS_StrAnglReqVal : 82|14@1- (0.1,0) [0|176.7] "Deg" GW_RGW,MDPS,SFA
|
||||
SG_ ADAS_ACIAnglTqRedcGainVal : 96|8@1+ (0.004,0) [0|1] "" GW_RGW,MDPS,SFA
|
||||
SG_ Damping_Gain : 104|8@1+ (1,0) [0|255] "" CGW
|
||||
|
||||
BO_ 304 GEAR_SHIFTER: 16 XXX
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
|
||||
static bool hyundai_canfd_alt_buttons = false;
|
||||
static bool hyundai_canfd_lka_steer_msg_alt = false;
|
||||
static bool hyundai_canfd_angle_steering = false;
|
||||
|
||||
static unsigned int hyundai_canfd_get_lka_addr(void) {
|
||||
return hyundai_canfd_lka_steer_msg_alt ? 0x110U : 0x50U;
|
||||
@@ -79,10 +78,6 @@ static void hyundai_canfd_rx_hook(const CANPacket_t *msg) {
|
||||
int torque_driver_new = ((msg->data[11] & 0x1fU) << 8U) | msg->data[10];
|
||||
torque_driver_new -= 4095;
|
||||
update_sample(&torque_driver, torque_driver_new);
|
||||
|
||||
int angle_meas_new = (msg->data[17] << 8) | msg->data[16];
|
||||
angle_meas_new = to_signed(angle_meas_new, 16);
|
||||
update_sample(&angle_meas, angle_meas_new);
|
||||
}
|
||||
|
||||
// cruise buttons
|
||||
@@ -146,7 +141,7 @@ static void hyundai_canfd_rx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
const TorqueSteeringLimits HYUNDAI_CANFD_TORQUE_STEERING_LIMITS = {
|
||||
const TorqueSteeringLimits HYUNDAI_CANFD_STEERING_LIMITS = {
|
||||
.max_torque = 270,
|
||||
.max_rt_delta = 112,
|
||||
.max_rate_up = 2,
|
||||
@@ -163,76 +158,16 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
.has_steer_req_tolerance = true,
|
||||
};
|
||||
|
||||
const AngleSteeringLimits HYUNDAI_CANFD_ANGLE_STEERING_LIMITS = {
|
||||
.max_angle = 3600,
|
||||
.angle_deg_to_can = 10,
|
||||
.frequency = 100U,
|
||||
};
|
||||
|
||||
// We need to find a middle ground between all the possible params or find a way to properly fingerprint.
|
||||
// HYUNDAI_IONIQ_5_PE: -0.0008688329819908074
|
||||
// KIA_EV6_2025: -0.000889804937754786
|
||||
// KIA_EV9: -0.0005410588125765342
|
||||
// GENESIS_GV80_2025: -0.0005685702046115589
|
||||
// HYUNDAI_SANTA_FE_HEV_5TH_GEN: -0.00059689759884299
|
||||
|
||||
// IONIQ 5 PE values.
|
||||
// const AngleSteeringParams HYUNDAI_STEERING_PARAMS = {
|
||||
// .slip_factor = -0.0008688329819908074, // calc_slip_factor(VM)
|
||||
// .steer_ratio = 14.26,
|
||||
// .wheelbase = 2.97,
|
||||
// };
|
||||
|
||||
// GENESIS_GV80_2025 values. (values can be found on values.py)
|
||||
const AngleSteeringParams HYUNDAI_STEERING_PARAMS = {
|
||||
.slip_factor = -0.0005685702046115589, // calc_slip_factor(VM)
|
||||
.steer_ratio = 14.14,
|
||||
.wheelbase = 2.95,
|
||||
};
|
||||
|
||||
// HYUNDAI_SANTA_FE_HEV_5TH_GEN values. (values can be found on values.py)
|
||||
// const AngleSteeringParams HYUNDAI_STEERING_PARAMS = {
|
||||
// .slip_factor = -0.00059689759884299, // calc_slip_factor(VM)
|
||||
// .steer_ratio = 13.72,
|
||||
// .wheelbase = 2.81,
|
||||
// };
|
||||
|
||||
// KIA_SPORTAGE_HEV_2026 values. (most conservative for now) (values can be found on values.py)
|
||||
// const AngleSteeringParams HYUNDAI_STEERING_PARAMS = {
|
||||
// .slip_factor = -0.0006085930193026732, // calc_slip_factor(VM)
|
||||
// .steer_ratio = 13.7,
|
||||
// .wheelbase = 2.756,
|
||||
// };
|
||||
|
||||
bool tx = true;
|
||||
|
||||
// steering
|
||||
const unsigned int steer_addr = (hyundai_canfd_lka_steer_msg && !hyundai_longitudinal) ? hyundai_canfd_get_lka_addr() : 0x12aU;
|
||||
if (msg->addr == steer_addr) {
|
||||
if (hyundai_canfd_angle_steering) {
|
||||
const int lkas_angle_active = (msg->data[9] >> 4U) & 0x3U;
|
||||
const bool steer_angle_req = lkas_angle_active != 1;
|
||||
int desired_torque = (((msg->data[6] & 0xFU) << 7U) | (msg->data[5] >> 1U)) - 1024U;
|
||||
bool steer_req = GET_BIT(msg, 52U);
|
||||
|
||||
int desired_angle = (msg->data[11] << 6U) | (msg->data[10] >> 2U);
|
||||
desired_angle = to_signed(desired_angle, 14);
|
||||
|
||||
// ADAS_ACIAnglTqRedcGainVal: bit 96, 8 bits, unsigned. Raw 0-250 valid, 251-255 reserved.
|
||||
const uint8_t gain_raw = msg->data[12];
|
||||
bool gain_violation = gain_raw > 250U;
|
||||
if (!steer_angle_req && (gain_raw != 0U)) {
|
||||
gain_violation = true;
|
||||
}
|
||||
|
||||
if (steer_angle_cmd_checks_vm(desired_angle, steer_angle_req, HYUNDAI_CANFD_ANGLE_STEERING_LIMITS, HYUNDAI_STEERING_PARAMS) || gain_violation) {
|
||||
tx = false;
|
||||
}
|
||||
} else {
|
||||
int desired_torque = (((msg->data[6] & 0xFU) << 7U) | (msg->data[5] >> 1U)) - 1024U;
|
||||
bool steer_req = GET_BIT(msg, 52U);
|
||||
|
||||
if (steer_torque_cmd_checks(desired_torque, steer_req, HYUNDAI_CANFD_TORQUE_STEERING_LIMITS)) {
|
||||
tx = false;
|
||||
}
|
||||
if (steer_torque_cmd_checks(desired_torque, steer_req, HYUNDAI_CANFD_STEERING_LIMITS)) {
|
||||
tx = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,7 +227,6 @@ static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
static safety_config hyundai_canfd_init(uint16_t param) {
|
||||
const uint16_t HYUNDAI_PARAM_CANFD_LKA_STEER_MSG_ALT = 128;
|
||||
const uint16_t HYUNDAI_PARAM_CANFD_ALT_BUTTONS = 32;
|
||||
const uint16_t HYUNDAI_PARAM_CANFD_ANGLE_STEERING = 1024;
|
||||
|
||||
static const CanMsg HYUNDAI_CANFD_LKA_STEER_MSG_TX_MSGS[] = {
|
||||
HYUNDAI_CANFD_LKA_STEER_MSG_COMMON_TX_MSGS(0, 1)
|
||||
@@ -342,7 +276,6 @@ static safety_config hyundai_canfd_init(uint16_t param) {
|
||||
gen_crc_lookup_table_16(0x1021, hyundai_canfd_crc_lut);
|
||||
hyundai_canfd_alt_buttons = GET_FLAG(param, HYUNDAI_PARAM_CANFD_ALT_BUTTONS);
|
||||
hyundai_canfd_lka_steer_msg_alt = GET_FLAG(param, HYUNDAI_PARAM_CANFD_LKA_STEER_MSG_ALT);
|
||||
hyundai_canfd_angle_steering = GET_FLAG(param, HYUNDAI_PARAM_CANFD_ANGLE_STEERING);
|
||||
|
||||
safety_config ret;
|
||||
if (hyundai_longitudinal) {
|
||||
|
||||
@@ -60,11 +60,7 @@ def get_steer_value(mode, param, msg):
|
||||
elif mode in (CarParams.SafetyModel.hyundai, CarParams.SafetyModel.hyundaiLegacy):
|
||||
torque = (((msg.data[3] & 0x7) << 8) | msg.data[2]) - 1024
|
||||
elif mode == CarParams.SafetyModel.hyundaiCanfd:
|
||||
if param & HyundaiSafetyFlags.CANFD_ANGLE_STEERING:
|
||||
angle = (msg.data[11] << 6) | (msg.data[10] >> 2)
|
||||
angle = to_signed(angle, 14)
|
||||
else:
|
||||
torque = ((msg.data[5] >> 1) | (msg.data[6] & 0xF) << 7) - 1024
|
||||
torque = ((msg.data[5] >> 1) | (msg.data[6] & 0xF) << 7) - 1024
|
||||
elif mode == CarParams.SafetyModel.chrysler:
|
||||
torque = (((msg.data[0] & 0x7) << 8) | msg.data[1]) - 1024
|
||||
elif mode == CarParams.SafetyModel.subaru:
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
from opendbc.testing import parameterized_class
|
||||
import unittest
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car.hyundai.carcontroller import ANGLE_SAFETY_BASELINE_MODEL
|
||||
from opendbc.car.hyundai.values import HyundaiSafetyFlags, CAR, HyundaiFlags, CarControllerParams
|
||||
from opendbc.car.hyundai.values import HyundaiSafetyFlags
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vehicle_model import VehicleModel, calc_slip_factor
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
import opendbc.safety.tests.common as common
|
||||
from opendbc.safety.tests.common import CANPackerSafety, away_round, round_speed
|
||||
from opendbc.safety.tests.common import CANPackerSafety
|
||||
from opendbc.safety.tests.hyundai_common import HyundaiButtonBase, HyundaiLongitudinalBase
|
||||
from opendbc.car.lateral import get_max_angle_delta_vm, get_max_angle_vm, AngleSteeringLimitsVM
|
||||
from opendbc.testing import parameterized
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
|
||||
# All combinations of radar/camera-SCC and gas/hybrid/EV cars
|
||||
ALL_GAS_EV_HYBRID_COMBOS = [
|
||||
@@ -28,16 +22,10 @@ ALL_GAS_EV_HYBRID_COMBOS = [
|
||||
]
|
||||
|
||||
|
||||
def round_angle(angle_deg: float, can_offset=0):
|
||||
scaled = angle_deg / 0.1
|
||||
scaled += can_offset
|
||||
return int(scaled) * 0.1
|
||||
|
||||
|
||||
class TestHyundaiCanfdBase(HyundaiButtonBase, common.CarSafetyTest, common.DriverTorqueSteeringSafetyTest, common.SteerRequestCutSafetyTest):
|
||||
|
||||
TX_MSGS = [[0x50, 0], [0x1CF, 1], [0x2A4, 0]]
|
||||
STANDSTILL_THRESHOLD = 0.375 * 0.03125 # 0.375 kph
|
||||
STANDSTILL_THRESHOLD = 12 # 0.375 kph
|
||||
FWD_BLACKLISTED_ADDRS = {2: [0x50, 0x2a4]}
|
||||
|
||||
MAX_RATE_UP = 2
|
||||
@@ -69,7 +57,7 @@ class TestHyundaiCanfdBase(HyundaiButtonBase, common.CarSafetyTest, common.Drive
|
||||
return self.packer.make_can_msg_safety(self.STEER_MSG, self.STEER_BUS, values)
|
||||
|
||||
def _speed_msg(self, speed):
|
||||
values = {f"WHL_Spd{pos}Val": speed * 3.6 for pos in ["FL", "FR", "RL", "RR"]}
|
||||
values = {f"WHL_Spd{pos}Val": speed * 0.03125 for pos in ["FL", "FR", "RL", "RR"]}
|
||||
return self.packer.make_can_msg_safety("WHEEL_SPEEDS", self.PT_BUS, values)
|
||||
|
||||
def _user_brake_msg(self, brake):
|
||||
@@ -105,285 +93,7 @@ class TestHyundaiCanfdBase(HyundaiButtonBase, common.CarSafetyTest, common.Drive
|
||||
return self._button_msg(0, enabled)
|
||||
|
||||
|
||||
class TestHyundaiCanfdTorqueSteering(TestHyundaiCanfdBase, common.DriverTorqueSteeringSafetyTest, common.SteerRequestCutSafetyTest):
|
||||
|
||||
MAX_RATE_UP = 2
|
||||
MAX_RATE_DOWN = 3
|
||||
MAX_TORQUE = 270
|
||||
|
||||
MAX_RT_DELTA = 112
|
||||
RT_INTERVAL = 250000
|
||||
|
||||
DRIVER_TORQUE_ALLOWANCE = 250
|
||||
DRIVER_TORQUE_FACTOR = 2
|
||||
|
||||
# Safety around steering req bit
|
||||
MIN_VALID_STEERING_FRAMES = 89
|
||||
MAX_INVALID_STEERING_FRAMES = 2
|
||||
MIN_VALID_STEERING_RT_INTERVAL = 810000 # a ~10% buffer, can send steer up to 110Hz
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
if cls.__name__ == "TestHyundaiCanfdTorqueSteering":
|
||||
cls.packer = None
|
||||
cls.safety = None
|
||||
raise unittest.SkipTest
|
||||
|
||||
def setUp(self):
|
||||
self.packer = CANPackerSafety("hyundai_canfd_generated")
|
||||
self.safety = libsafety_py.libsafety
|
||||
self.safety.set_safety_hooks(CarParams.SafetyModel.hyundaiCanfd, 0)
|
||||
self.safety.init_tests()
|
||||
|
||||
|
||||
class TestHyundaiCanfdAngleSteering(TestHyundaiCanfdBase, common.AngleSteeringSafetyTest):
|
||||
PLATFORMS = {str(platform): platform for platform in CAR if
|
||||
platform.config.flags & HyundaiFlags.CANFD_ANGLE_STEERING and not CarInterface.get_non_essential_params(str(platform)).dashcamOnly}
|
||||
|
||||
# Angle control limits
|
||||
BASELINE_PANDA_ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
|
||||
360, # degrees
|
||||
MAX_ANGLE_RATE=5 # comfort rate limit for angle commands, in degrees per frame.
|
||||
)
|
||||
|
||||
STEER_ANGLE_MAX = 360 # deg
|
||||
DEG_TO_CAN = 10
|
||||
ANGLE_SAFETY_THRESHOLD_PCT = -2.0 # Fail if difference is less than -2%
|
||||
|
||||
# Hyundai uses get_max_angle_delta and get_max_angle for real lateral accel and jerk limits
|
||||
# TODO: integrate this into AngleSteeringSafetyTest
|
||||
ANGLE_RATE_BP = None
|
||||
ANGLE_RATE_UP = None
|
||||
ANGLE_RATE_DOWN = None
|
||||
|
||||
# Real time limits
|
||||
LATERAL_FREQUENCY = 100 # Hz
|
||||
|
||||
cnt_angle_cmd = 0
|
||||
|
||||
def get_baseline_limits(self):
|
||||
limits = CarControllerParams(CarInterface.get_non_essential_params(ANGLE_SAFETY_BASELINE_MODEL))
|
||||
limits.ANGLE_LIMITS = self.BASELINE_PANDA_ANGLE_LIMITS
|
||||
return limits
|
||||
|
||||
def _angle_cmd_msg(self, angle: float, enabled: bool, increment_timer: bool = True, gain: float = 0.0):
|
||||
if increment_timer:
|
||||
self.safety.set_timer(self.cnt_angle_cmd * int(1e6 / self.LATERAL_FREQUENCY))
|
||||
self.__class__.cnt_angle_cmd += 1
|
||||
values = {"ADAS_StrAnglReqVal": angle, "LKAS_ANGLE_ACTIVE": 2 if enabled else 1,
|
||||
"ADAS_ACIAnglTqRedcGainVal": gain}
|
||||
return self.packer.make_can_msg_safety(self.STEER_MSG, self.STEER_BUS, values)
|
||||
|
||||
def _angle_meas_msg(self, angle: float):
|
||||
values = {"MDPS_EstStrAnglVal": angle}
|
||||
return self.packer.make_can_msg_safety("MDPS", self.PT_BUS, values)
|
||||
|
||||
def _get_steer_cmd_angle_max(self, speed):
|
||||
baseline_vm = self.get_vm(ANGLE_SAFETY_BASELINE_MODEL)
|
||||
return get_max_angle_vm(max(speed, 1), baseline_vm, self.get_baseline_limits())
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
if cls.__name__ == "TestHyundaiCanfdAngleSteering":
|
||||
cls.packer = None
|
||||
cls.safety = None
|
||||
raise unittest.SkipTest
|
||||
|
||||
def get_vm(self, car_name):
|
||||
return VehicleModel(CarInterface.get_non_essential_params(car_name))
|
||||
|
||||
def setUp(self):
|
||||
self.packer = CANPackerSafety("hyundai_canfd_generated")
|
||||
self.safety = libsafety_py.libsafety
|
||||
self.safety.set_safety_hooks(CarParams.SafetyModel.hyundaiCanfd, HyundaiSafetyFlags.CANFD_ANGLE_STEERING)
|
||||
self.safety.init_tests()
|
||||
|
||||
def test_angle_cmd_when_enabled(self):
|
||||
# We properly test lateral acceleration and jerk below
|
||||
pass
|
||||
|
||||
def test_lateral_accel_limit(self):
|
||||
car_name = ANGLE_SAFETY_BASELINE_MODEL
|
||||
for speed in np.linspace(0, 40, 100):
|
||||
speed = round_speed(away_round(speed / 0.03125 * 3.6) * 0.03125 / 3.6)
|
||||
speed = max(speed, 1)
|
||||
for sign in (-1, 1):
|
||||
self.safety.set_controls_allowed(True)
|
||||
self._reset_speed_measurement(speed + 1) # safety fudges the speed
|
||||
|
||||
# at limit (safety tolerance adds 1)
|
||||
angl = get_max_angle_vm(speed, self.get_vm(car_name), self.get_baseline_limits())
|
||||
max_angle = round_angle(get_max_angle_vm(speed, self.get_vm(car_name), self.get_baseline_limits()), 1) * sign
|
||||
max_angle = np.clip(max_angle, -self.STEER_ANGLE_MAX, self.STEER_ANGLE_MAX)
|
||||
self.safety.set_desired_angle_last(round(max_angle * self.DEG_TO_CAN))
|
||||
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(max_angle, True)), f"{angl} -- {max_angle}")
|
||||
|
||||
# above limit (offset 6 to reliably exceed C float tolerance)
|
||||
max_angle_raw = round_angle(get_max_angle_vm(speed, self.get_vm(car_name), self.get_baseline_limits()), 6) * sign
|
||||
max_angle = np.clip(max_angle_raw, -self.STEER_ANGLE_MAX, self.STEER_ANGLE_MAX)
|
||||
self._tx(self._angle_cmd_msg(max_angle, True))
|
||||
|
||||
# at low speeds max angle is above 360, so adding 1 has no effect
|
||||
should_tx = abs(max_angle_raw) >= self.STEER_ANGLE_MAX
|
||||
self.assertEqual(should_tx, self._tx(self._angle_cmd_msg(max_angle, True)), f"should_tx: {should_tx}, max_angle: {max_angle}, speed: {speed}")
|
||||
|
||||
def test_lateral_jerk_limit(self):
|
||||
car_name = ANGLE_SAFETY_BASELINE_MODEL
|
||||
for speed in np.linspace(0, 40, 100):
|
||||
speed = round_speed(away_round(speed / 0.03125 * 3.6) * 0.03125 / 3.6)
|
||||
speed = max(speed, 1)
|
||||
for sign in (-1, 1): # (-1, 1):
|
||||
self.safety.set_controls_allowed(True)
|
||||
self._reset_speed_measurement(speed + 1) # safety fudges the speed
|
||||
self._tx(self._angle_cmd_msg(0, True))
|
||||
|
||||
# Stay within limits
|
||||
# Up
|
||||
max_angle_delta = round_angle(get_max_angle_delta_vm(speed, self.get_vm(car_name), self.get_baseline_limits())) * sign
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(max_angle_delta, True)))
|
||||
|
||||
# Don't change
|
||||
self.safety.set_desired_angle_last(round(max_angle_delta * self.DEG_TO_CAN))
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(max_angle_delta, True)))
|
||||
|
||||
# Down
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(0, True)))
|
||||
|
||||
# Inject too high rates
|
||||
# Up
|
||||
# TODO-SP: Why do I need to set a can_offset so high to pass the tests and why tesla only does +1? and why does it seem to differ based on the baseline?
|
||||
max_angle_delta = round_angle(get_max_angle_delta_vm(speed, self.get_vm(car_name), self.get_baseline_limits()), 6) * sign
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(max_angle_delta, True)), vars(self.get_baseline_limits()))
|
||||
|
||||
# Don't change
|
||||
self.safety.set_desired_angle_last(round(max_angle_delta * self.DEG_TO_CAN))
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(max_angle_delta, True)))
|
||||
|
||||
# Down
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(0, True)))
|
||||
|
||||
# Recover
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(0, True)))
|
||||
|
||||
def test_rt_limits(self):
|
||||
# TODO: remove and check all safety modes
|
||||
if self.LATERAL_FREQUENCY == -1:
|
||||
raise unittest.SkipTest("No real time limits")
|
||||
|
||||
# Angle safety enforces real time limits by checking the message send frequency in a 250ms time window
|
||||
self.safety.set_timer(0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
max_rt_msgs = int(self.LATERAL_FREQUENCY * common.RT_INTERVAL / 1e6 * 1.2 + 1) # 1.2x buffer
|
||||
|
||||
for i in range(max_rt_msgs * 2):
|
||||
should_tx = i <= max_rt_msgs
|
||||
self.assertEqual(should_tx, self._tx(self._angle_cmd_msg(0, True, increment_timer=False)))
|
||||
|
||||
# One under RT interval should do nothing
|
||||
self.safety.set_timer(common.RT_INTERVAL - 1)
|
||||
for _ in range(5):
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(0, True, increment_timer=False)))
|
||||
|
||||
# Increment timer and send 1 message to reset RT window
|
||||
self.safety.set_timer(common.RT_INTERVAL)
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(0, True, increment_timer=False)))
|
||||
for _ in range(5):
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(0, True, increment_timer=False)))
|
||||
|
||||
def test_torque_reduction_gain(self):
|
||||
# Valid gains when enabled
|
||||
for gain in [0.0, 0.5, 1.0]:
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(0, True, gain=gain)),
|
||||
f"gain={gain} should be allowed when enabled")
|
||||
|
||||
# Reserved values (raw 251+) must fail even when enabled
|
||||
for gain in [1.004, 1.008, 1.02]:
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(0, True, gain=gain)),
|
||||
f"gain={gain} (reserved) should be blocked")
|
||||
|
||||
# Non-zero gain when disabled must fail
|
||||
for gain in [0.004, 0.5, 1.0]:
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertFalse(self._tx(self._angle_cmd_msg(0, False, gain=gain)),
|
||||
f"gain={gain} should be blocked when disabled")
|
||||
|
||||
# Zero gain when disabled must pass
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(self._angle_cmd_msg(0, False, gain=0.0)))
|
||||
|
||||
@parameterized("car_name", sorted(PLATFORMS))
|
||||
def test_max_steering_angle_safety(self, car_name):
|
||||
"""
|
||||
Test that ensures the current car's max steering angles are never more than 2%
|
||||
lower than the baseline car across all test speeds.
|
||||
"""
|
||||
baseline_car = ANGLE_SAFETY_BASELINE_MODEL
|
||||
baseline_vm = self.get_vm(baseline_car)
|
||||
current_vm = self.get_vm(car_name)
|
||||
|
||||
for speed in np.linspace(1, 40, 10):
|
||||
baseline_max_angle = get_max_angle_vm(speed, baseline_vm, self.get_baseline_limits())
|
||||
current_max_angle = get_max_angle_vm(speed, current_vm, self.get_baseline_limits())
|
||||
|
||||
# Skip if both exceed STEER_ANGLE_MAX (only_relevant_angles logic)
|
||||
if current_max_angle > self.STEER_ANGLE_MAX and baseline_max_angle > self.STEER_ANGLE_MAX:
|
||||
continue
|
||||
|
||||
# Calculate percentage difference
|
||||
if baseline_max_angle != 0:
|
||||
angle_diff_pct = ((current_max_angle - baseline_max_angle) / baseline_max_angle) * 100
|
||||
else:
|
||||
angle_diff_pct = 0
|
||||
|
||||
# Assert that difference is not dangerously low
|
||||
self.assertTrue(
|
||||
angle_diff_pct >= self.ANGLE_SAFETY_THRESHOLD_PCT,
|
||||
f"{car_name} max steering angle at {speed:.1f} m/s [{current_max_angle:.2f}°] is {angle_diff_pct:.2f}% " +
|
||||
f"lower than baseline {baseline_car} ({current_max_angle:.2f}° vs {baseline_max_angle:.2f}°). " +
|
||||
f"Must be >= {self.ANGLE_SAFETY_THRESHOLD_PCT}% to ensure safety." +
|
||||
f"Consider updating the baseline model to be {car_name} (which will lower the threshold for ALL models). " +
|
||||
f"Slip Factor: {repr(calc_slip_factor(current_vm))}"
|
||||
)
|
||||
|
||||
@parameterized("car_name", sorted(PLATFORMS))
|
||||
def test_max_steering_angle_delta_safety(self, car_name):
|
||||
"""
|
||||
Test that ensures the current car's max steering angle deltas are never more than 2%
|
||||
lower than the baseline car across all test speeds.
|
||||
"""
|
||||
baseline_car = ANGLE_SAFETY_BASELINE_MODEL
|
||||
baseline_vm = self.get_vm(baseline_car)
|
||||
baseline_limits = CarControllerParams(CarInterface.get_non_essential_params(baseline_car))
|
||||
current_vm = self.get_vm(car_name)
|
||||
current_limits = CarControllerParams(CarInterface.get_non_essential_params(car_name))
|
||||
|
||||
for speed in np.linspace(1, 40, 10):
|
||||
baseline_max_delta = get_max_angle_delta_vm(speed, baseline_vm, baseline_limits)
|
||||
current_max_delta = get_max_angle_delta_vm(speed, current_vm, current_limits)
|
||||
|
||||
# Calculate percentage difference
|
||||
if baseline_max_delta != 0:
|
||||
delta_diff_pct = ((current_max_delta - baseline_max_delta) / baseline_max_delta) * 100
|
||||
else:
|
||||
delta_diff_pct = 0
|
||||
|
||||
# Assert that difference is not dangerously low
|
||||
self.assertTrue(
|
||||
delta_diff_pct >= self.ANGLE_SAFETY_THRESHOLD_PCT,
|
||||
f"{car_name} max steering angle delta at {speed:.1f} m/s is {delta_diff_pct:.2f}% " +
|
||||
f"lower than {baseline_car} ({current_max_delta:.4f} vs {baseline_max_delta:.4f} deg/frame). " +
|
||||
f"Must be >= {self.ANGLE_SAFETY_THRESHOLD_PCT}% to ensure safety." +
|
||||
f"Consider updating the baseline model to be {car_name} (which will lower the threshold for ALL models)." +
|
||||
f"Slip Factor: {repr(calc_slip_factor(current_vm))}"
|
||||
)
|
||||
|
||||
|
||||
class TestHyundaiCanfdLFASteeringBase(TestHyundaiCanfdTorqueSteering):
|
||||
class TestHyundaiCanfdLFASteeringBase(TestHyundaiCanfdBase):
|
||||
|
||||
TX_MSGS = [[0x12A, 0], [0x1A0, 1], [0x1CF, 0], [0x1E0, 0]]
|
||||
RELAY_MALFUNCTION_ADDRS = {0: (0x12A, 0x1E0)} # LFA, LFAHDA_CLUSTER
|
||||
@@ -461,7 +171,7 @@ class TestHyundaiCanfdLFASteeringAltButtons(TestHyundaiCanfdLFASteeringAltButton
|
||||
pass
|
||||
|
||||
|
||||
class TestHyundaiCanfdLKASteeringEV(TestHyundaiCanfdTorqueSteering):
|
||||
class TestHyundaiCanfdLKASteeringEV(TestHyundaiCanfdBase):
|
||||
|
||||
TX_MSGS = [[0x50, 0], [0x1CF, 1], [0x2A4, 0]]
|
||||
RELAY_MALFUNCTION_ADDRS = {0: (0x50, 0x2a4)} # LKAS, CAM_0x2A4
|
||||
@@ -480,7 +190,7 @@ class TestHyundaiCanfdLKASteeringEV(TestHyundaiCanfdTorqueSteering):
|
||||
|
||||
|
||||
# TODO: Handle ICE and HEV configurations once we see cars that use the new messages
|
||||
class TestHyundaiCanfdLKASteeringAltEVBase(TestHyundaiCanfdBase):
|
||||
class TestHyundaiCanfdLKASteeringAltEV(TestHyundaiCanfdBase):
|
||||
|
||||
TX_MSGS = [[0x110, 0], [0x1CF, 1], [0x362, 0]]
|
||||
RELAY_MALFUNCTION_ADDRS = {0: (0x110, 0x362)} # LKAS_ALT, CAM_0x362
|
||||
@@ -499,60 +209,6 @@ class TestHyundaiCanfdLKASteeringAltEVBase(TestHyundaiCanfdBase):
|
||||
self.safety.init_tests()
|
||||
|
||||
|
||||
class TestHyundaiCanfdLKASteeringAltEVTorque(TestHyundaiCanfdLKASteeringAltEVBase, TestHyundaiCanfdTorqueSteering):
|
||||
|
||||
def setUp(self):
|
||||
self.packer = CANPackerSafety("hyundai_canfd_generated")
|
||||
self.safety = libsafety_py.libsafety
|
||||
self.safety.set_safety_hooks(CarParams.SafetyModel.hyundaiCanfd, HyundaiSafetyFlags.CANFD_LKA_STEER_MSG | HyundaiSafetyFlags.EV_GAS |
|
||||
HyundaiSafetyFlags.CANFD_LKA_STEER_MSG_ALT)
|
||||
self.safety.init_tests()
|
||||
|
||||
|
||||
class TestHyundaiCanfdLKASteeringAltAngle(TestHyundaiCanfdAngleSteering):
|
||||
|
||||
TX_MSGS = [[0x110, 0], [0x1CF, 1], [0x362, 0]]
|
||||
RELAY_MALFUNCTION_ADDRS = {0: (0x110, 0x362)}
|
||||
FWD_BLACKLISTED_ADDRS = {2: [0x110, 0x362]}
|
||||
|
||||
PT_BUS = 1
|
||||
SCC_BUS = 1
|
||||
STEER_MSG = "LKAS_ALT"
|
||||
GAS_MSG = ("ACCELERATOR_BRAKE_ALT", "ACCELERATOR_PEDAL_PRESSED")
|
||||
|
||||
def setUp(self):
|
||||
self.packer = CANPackerSafety("hyundai_canfd_generated")
|
||||
self.safety = libsafety_py.libsafety
|
||||
self.safety.set_safety_hooks(CarParams.SafetyModel.hyundaiCanfd, HyundaiSafetyFlags.CANFD_LKA_STEER_MSG |
|
||||
HyundaiSafetyFlags.CANFD_LKA_STEER_MSG_ALT | HyundaiSafetyFlags.CANFD_ANGLE_STEERING)
|
||||
self.safety.init_tests()
|
||||
|
||||
# Angle steering does not use torque — override inherited torque tests
|
||||
def test_steer_safety_check(self):
|
||||
pass
|
||||
|
||||
def test_non_realtime_limit_up(self):
|
||||
pass
|
||||
|
||||
def test_steer_req_bit(self):
|
||||
pass
|
||||
|
||||
def test_steer_req_bit_frames(self):
|
||||
pass
|
||||
|
||||
def test_steer_req_bit_multi_invalid(self):
|
||||
pass
|
||||
|
||||
def test_steer_req_bit_realtime(self):
|
||||
pass
|
||||
|
||||
def test_against_torque_driver(self):
|
||||
pass
|
||||
|
||||
def test_realtime_limits(self):
|
||||
pass
|
||||
|
||||
|
||||
class TestHyundaiCanfdLKASteeringLongEV(HyundaiLongitudinalBase, TestHyundaiCanfdLKASteeringEV):
|
||||
|
||||
TX_MSGS = [[0x50, 0], [0x1CF, 1], [0x2A4, 0], [0x51, 0], [0x730, 1], [0x12a, 1], [0x160, 1],
|
||||
|
||||
@@ -972,39 +972,6 @@
|
||||
],
|
||||
"package": "All"
|
||||
},
|
||||
"Genesis GV80 (2.5T, with HDA2 & LFA2) 2025-26": {
|
||||
"platform": "GENESIS_GV80_2025",
|
||||
"make": "Genesis",
|
||||
"brand": "hyundai",
|
||||
"model": "GV80 (2.5T, with HDA2 & LFA2)",
|
||||
"year": [
|
||||
"2025",
|
||||
"2026"
|
||||
],
|
||||
"package": "Highway Driving Assist 2 & Lane Follow Assist 2"
|
||||
},
|
||||
"Genesis GV80 (3.5T, with HDA2 & LFA2) 2025-26": {
|
||||
"platform": "GENESIS_GV80_2025",
|
||||
"make": "Genesis",
|
||||
"brand": "hyundai",
|
||||
"model": "GV80 (3.5T, with HDA2 & LFA2)",
|
||||
"year": [
|
||||
"2025",
|
||||
"2026"
|
||||
],
|
||||
"package": "Highway Driving Assist 2 & Lane Follow Assist 2"
|
||||
},
|
||||
"Genesis GV80 Coupe (3.5 T, with HDA2 & LFA2) 2025-26": {
|
||||
"platform": "GENESIS_GV80_2025",
|
||||
"make": "Genesis",
|
||||
"brand": "hyundai",
|
||||
"model": "GV80 Coupe (3.5 T, with HDA2 & LFA2)",
|
||||
"year": [
|
||||
"2025",
|
||||
"2026"
|
||||
],
|
||||
"package": "Highway Driving Assist 2 & Lane Follow Assist 2"
|
||||
},
|
||||
"GMC Acadia 2018": {
|
||||
"platform": "GMC_ACADIA",
|
||||
"make": "GMC",
|
||||
@@ -1653,17 +1620,6 @@
|
||||
],
|
||||
"package": "Highway Driving Assist"
|
||||
},
|
||||
"Hyundai Ioniq 5 PE (with HDA II & LFA2) 2025-26": {
|
||||
"platform": "HYUNDAI_IONIQ_5_PE",
|
||||
"make": "Hyundai",
|
||||
"brand": "hyundai",
|
||||
"model": "Ioniq 5 PE (with HDA II & LFA2)",
|
||||
"year": [
|
||||
"2025",
|
||||
"2026"
|
||||
],
|
||||
"package": "Highway Driving Assist II & Lane Follow Assist 2"
|
||||
},
|
||||
"Hyundai Ioniq 6 (with HDA II) 2023-24": {
|
||||
"platform": "HYUNDAI_IONIQ_6",
|
||||
"make": "Hyundai",
|
||||
|
||||
@@ -131,6 +131,7 @@ struct ModelManagerSP @0xaedffd8f31e7b55d {
|
||||
downloaded @2;
|
||||
cached @3;
|
||||
failed @4;
|
||||
verifying @5;
|
||||
}
|
||||
|
||||
struct DownloadProgress {
|
||||
@@ -352,6 +353,7 @@ struct OnroadEventSP @0xda96579883444c35 {
|
||||
speedLimitPending @22;
|
||||
e2eChime @23;
|
||||
laneChangeRoadEdge @24;
|
||||
bigModelReady @25;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1114,7 +1114,7 @@ const ::capnp::_::RawSchema s_d8cbae8ae9dfe286 = {
|
||||
0, 2, i_d8cbae8ae9dfe286, nullptr, nullptr, { &s_d8cbae8ae9dfe286, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<43> b_da834d53e62048b9 = {
|
||||
static const ::capnp::_::AlignedData<48> b_da834d53e62048b9 = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
185, 72, 32, 230, 83, 77, 131, 218,
|
||||
28, 0, 0, 0, 2, 0, 0, 0,
|
||||
@@ -1124,7 +1124,7 @@ static const ::capnp::_::AlignedData<43> b_da834d53e62048b9 = {
|
||||
21, 0, 0, 0, 90, 1, 0, 0,
|
||||
41, 0, 0, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
37, 0, 0, 0, 127, 0, 0, 0,
|
||||
37, 0, 0, 0, 151, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
@@ -1134,21 +1134,24 @@ static const ::capnp::_::AlignedData<43> b_da834d53e62048b9 = {
|
||||
108, 111, 97, 100, 83, 116, 97, 116,
|
||||
117, 115, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 1, 0, 1, 0,
|
||||
20, 0, 0, 0, 1, 0, 2, 0,
|
||||
24, 0, 0, 0, 1, 0, 2, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
53, 0, 0, 0, 122, 0, 0, 0,
|
||||
65, 0, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
49, 0, 0, 0, 98, 0, 0, 0,
|
||||
61, 0, 0, 0, 98, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
2, 0, 0, 0, 0, 0, 0, 0,
|
||||
45, 0, 0, 0, 90, 0, 0, 0,
|
||||
57, 0, 0, 0, 90, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
3, 0, 0, 0, 0, 0, 0, 0,
|
||||
41, 0, 0, 0, 58, 0, 0, 0,
|
||||
53, 0, 0, 0, 58, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
4, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 0, 0, 0, 58, 0, 0, 0,
|
||||
45, 0, 0, 0, 58, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
5, 0, 0, 0, 0, 0, 0, 0,
|
||||
37, 0, 0, 0, 82, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
110, 111, 116, 68, 111, 119, 110, 108,
|
||||
111, 97, 100, 105, 110, 103, 0, 0,
|
||||
@@ -1157,14 +1160,16 @@ static const ::capnp::_::AlignedData<43> b_da834d53e62048b9 = {
|
||||
100, 111, 119, 110, 108, 111, 97, 100,
|
||||
101, 100, 0, 0, 0, 0, 0, 0,
|
||||
99, 97, 99, 104, 101, 100, 0, 0,
|
||||
102, 97, 105, 108, 101, 100, 0, 0, }
|
||||
102, 97, 105, 108, 101, 100, 0, 0,
|
||||
118, 101, 114, 105, 102, 121, 105, 110,
|
||||
103, 0, 0, 0, 0, 0, 0, 0, }
|
||||
};
|
||||
::capnp::word const* const bp_da834d53e62048b9 = b_da834d53e62048b9.words;
|
||||
#if !CAPNP_LITE
|
||||
static const uint16_t m_da834d53e62048b9[] = {3, 2, 1, 4, 0};
|
||||
static const uint16_t m_da834d53e62048b9[] = {3, 2, 1, 4, 0, 5};
|
||||
const ::capnp::_::RawSchema s_da834d53e62048b9 = {
|
||||
0xda834d53e62048b9, b_da834d53e62048b9.words, 43, nullptr, m_da834d53e62048b9,
|
||||
0, 5, nullptr, nullptr, nullptr, { &s_da834d53e62048b9, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
0xda834d53e62048b9, b_da834d53e62048b9.words, 48, nullptr, m_da834d53e62048b9,
|
||||
0, 6, nullptr, nullptr, nullptr, { &s_da834d53e62048b9, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
CAPNP_DEFINE_ENUM(DownloadStatus_da834d53e62048b9, da834d53e62048b9);
|
||||
@@ -3517,7 +3522,7 @@ const ::capnp::_::RawSchema s_f6e831752fcdf793 = {
|
||||
1, 11, i_f6e831752fcdf793, nullptr, nullptr, { &s_f6e831752fcdf793, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
static const ::capnp::_::AlignedData<164> b_b8007ed8a646b5e6 = {
|
||||
static const ::capnp::_::AlignedData<169> b_b8007ed8a646b5e6 = {
|
||||
{ 0, 0, 0, 0, 5, 0, 6, 0,
|
||||
230, 181, 70, 166, 216, 126, 0, 184,
|
||||
27, 0, 0, 0, 2, 0, 0, 0,
|
||||
@@ -3527,7 +3532,7 @@ static const ::capnp::_::AlignedData<164> b_b8007ed8a646b5e6 = {
|
||||
21, 0, 0, 0, 42, 1, 0, 0,
|
||||
37, 0, 0, 0, 7, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 0, 0, 0, 95, 2, 0, 0,
|
||||
33, 0, 0, 0, 119, 2, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
99, 117, 115, 116, 111, 109, 46, 99,
|
||||
@@ -3536,81 +3541,84 @@ static const ::capnp::_::AlignedData<164> b_b8007ed8a646b5e6 = {
|
||||
83, 80, 46, 69, 118, 101, 110, 116,
|
||||
78, 97, 109, 101, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 1, 0, 1, 0,
|
||||
100, 0, 0, 0, 1, 0, 2, 0,
|
||||
104, 0, 0, 0, 1, 0, 2, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
37, 1, 0, 0, 90, 0, 0, 0,
|
||||
49, 1, 0, 0, 90, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
1, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 1, 0, 0, 98, 0, 0, 0,
|
||||
45, 1, 0, 0, 98, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
2, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 186, 0, 0, 0,
|
||||
41, 1, 0, 0, 186, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
3, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 218, 0, 0, 0,
|
||||
41, 1, 0, 0, 218, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
4, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 1, 0, 0, 138, 0, 0, 0,
|
||||
45, 1, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
5, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 1, 0, 0, 146, 0, 0, 0,
|
||||
45, 1, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
6, 0, 0, 0, 0, 0, 0, 0,
|
||||
33, 1, 0, 0, 130, 0, 0, 0,
|
||||
45, 1, 0, 0, 130, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
7, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 130, 0, 0, 0,
|
||||
41, 1, 0, 0, 130, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
8, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 1, 0, 0, 146, 0, 0, 0,
|
||||
37, 1, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
9, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 1, 0, 0, 122, 0, 0, 0,
|
||||
37, 1, 0, 0, 122, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
10, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 202, 0, 0, 0,
|
||||
33, 1, 0, 0, 202, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
11, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 1, 0, 0, 130, 0, 0, 0,
|
||||
37, 1, 0, 0, 130, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
12, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 194, 0, 0, 0,
|
||||
33, 1, 0, 0, 194, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
13, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 226, 0, 0, 0,
|
||||
33, 1, 0, 0, 226, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
14, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 1, 0, 0, 202, 0, 0, 0,
|
||||
37, 1, 0, 0, 202, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
15, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 178, 0, 0, 0,
|
||||
41, 1, 0, 0, 178, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
16, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 178, 0, 0, 0,
|
||||
41, 1, 0, 0, 178, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
17, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 106, 0, 0, 0,
|
||||
41, 1, 0, 0, 106, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
18, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 1, 0, 0, 114, 0, 0, 0,
|
||||
37, 1, 0, 0, 114, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
19, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 162, 0, 0, 0,
|
||||
33, 1, 0, 0, 162, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
20, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 138, 0, 0, 0,
|
||||
33, 1, 0, 0, 138, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 146, 0, 0, 0,
|
||||
33, 1, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
22, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 146, 0, 0, 0,
|
||||
33, 1, 0, 0, 146, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
23, 0, 0, 0, 0, 0, 0, 0,
|
||||
21, 1, 0, 0, 74, 0, 0, 0,
|
||||
33, 1, 0, 0, 74, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
24, 0, 0, 0, 0, 0, 0, 0,
|
||||
17, 1, 0, 0, 154, 0, 0, 0,
|
||||
29, 1, 0, 0, 154, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
25, 0, 0, 0, 0, 0, 0, 0,
|
||||
29, 1, 0, 0, 114, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
108, 107, 97, 115, 69, 110, 97, 98,
|
||||
108, 101, 0, 0, 0, 0, 0, 0,
|
||||
@@ -3681,14 +3689,16 @@ static const ::capnp::_::AlignedData<164> b_b8007ed8a646b5e6 = {
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
108, 97, 110, 101, 67, 104, 97, 110,
|
||||
103, 101, 82, 111, 97, 100, 69, 100,
|
||||
103, 101, 0, 0, 0, 0, 0, 0, }
|
||||
103, 101, 0, 0, 0, 0, 0, 0,
|
||||
98, 105, 103, 77, 111, 100, 101, 108,
|
||||
82, 101, 97, 100, 121, 0, 0, 0, }
|
||||
};
|
||||
::capnp::word const* const bp_b8007ed8a646b5e6 = b_b8007ed8a646b5e6.words;
|
||||
#if !CAPNP_LITE
|
||||
static const uint16_t m_b8007ed8a646b5e6[] = {12, 23, 14, 13, 24, 17, 18, 1, 0, 3, 2, 16, 6, 9, 5, 4, 11, 8, 10, 7, 20, 21, 22, 19, 15};
|
||||
static const uint16_t m_b8007ed8a646b5e6[] = {25, 12, 23, 14, 13, 24, 17, 18, 1, 0, 3, 2, 16, 6, 9, 5, 4, 11, 8, 10, 7, 20, 21, 22, 19, 15};
|
||||
const ::capnp::_::RawSchema s_b8007ed8a646b5e6 = {
|
||||
0xb8007ed8a646b5e6, b_b8007ed8a646b5e6.words, 164, nullptr, m_b8007ed8a646b5e6,
|
||||
0, 25, nullptr, nullptr, nullptr, { &s_b8007ed8a646b5e6, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
0xb8007ed8a646b5e6, b_b8007ed8a646b5e6.words, 169, nullptr, m_b8007ed8a646b5e6,
|
||||
0, 26, nullptr, nullptr, nullptr, { &s_b8007ed8a646b5e6, nullptr, nullptr, 0, 0, nullptr }, false
|
||||
};
|
||||
#endif // !CAPNP_LITE
|
||||
CAPNP_DEFINE_ENUM(EventName_b8007ed8a646b5e6, b8007ed8a646b5e6);
|
||||
|
||||
@@ -93,6 +93,7 @@ enum class DownloadStatus_da834d53e62048b9: uint16_t {
|
||||
DOWNLOADED,
|
||||
CACHED,
|
||||
FAILED,
|
||||
VERIFYING,
|
||||
};
|
||||
CAPNP_DECLARE_ENUM(DownloadStatus, da834d53e62048b9);
|
||||
CAPNP_DECLARE_SCHEMA(a677b25114d64c73);
|
||||
@@ -206,6 +207,7 @@ enum class EventName_b8007ed8a646b5e6: uint16_t {
|
||||
SPEED_LIMIT_PENDING,
|
||||
E2E_CHIME,
|
||||
LANE_CHANGE_ROAD_EDGE,
|
||||
BIG_MODEL_READY,
|
||||
};
|
||||
CAPNP_DECLARE_ENUM(EventName, b8007ed8a646b5e6);
|
||||
CAPNP_DECLARE_SCHEMA(80ae746ee2596b11);
|
||||
|
||||
@@ -130,8 +130,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"UpdaterLastFetchTime", {PERSISTENT, TIME}},
|
||||
{"UptimeOffroad", {PERSISTENT, FLOAT, "0.0"}},
|
||||
{"UptimeOnroad", {PERSISTENT, FLOAT, "0.0"}},
|
||||
{"UsbGpuActive", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
|
||||
{"UsbGpuLoading", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
|
||||
{"ChestnutActive", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
|
||||
{"ChestnutLoading", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION | CLEAR_ON_IGNITION_ON, BOOL}},
|
||||
{"Version", {PERSISTENT, STRING}},
|
||||
|
||||
// --- sunnypilot params --- //
|
||||
@@ -195,16 +195,16 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
|
||||
// Model Manager params
|
||||
{"ModelManager_ActiveBundle", {PERSISTENT, JSON}},
|
||||
{"ModelManager_ActiveJson", {CLEAR_ON_MANAGER_START, STRING}},
|
||||
{"ModelManager_PrevBundle", {PERSISTENT, JSON}},
|
||||
{"ModelManager_PrevBundle_USBGPU", {PERSISTENT, JSON}},
|
||||
{"ModelManager_ActiveBundleUSBGPU", {PERSISTENT, JSON}}, //TODO-SP: kept for migration, remove on next sync?
|
||||
{"ModelManager_ActiveBundleChestnut", {PERSISTENT, JSON}},
|
||||
{"ModelManager_ActiveJson", {CLEAR_ON_MANAGER_START, JSON}},
|
||||
{"ModelManager_ClearCache", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"ModelManager_DownloadIndex", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, INT}},
|
||||
{"ModelManager_DownloadRef", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, STRING}},
|
||||
{"ModelManager_Favs", {PERSISTENT | BACKUP, STRING}},
|
||||
{"ModelManager_LastSyncTime", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT, "0"}},
|
||||
{"ModelManager_LastSyncTime_USBGPU", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT, "0"}},
|
||||
{"ModelManager_LastSyncTime_Chestnut", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT, "0"}},
|
||||
{"ModelManager_ModelsCache", {PERSISTENT | BACKUP, JSON}},
|
||||
{"ModelManager_ModelsCache_USBGPU", {PERSISTENT | BACKUP, JSON}},
|
||||
{"ModelManager_ModelsCache_Chestnut", {PERSISTENT | BACKUP, JSON}},
|
||||
|
||||
// Neural Network Lateral Control
|
||||
{"NeuralNetworkLateralControl", {PERSISTENT | BACKUP, BOOL, "0"}},
|
||||
@@ -247,6 +247,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
|
||||
// mapd
|
||||
{"MapAdvisorySpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, FLOAT}},
|
||||
{"Mapd_ClearCache", {CLEAR_ON_MANAGER_START, BOOL}},
|
||||
{"MapdVersion", {PERSISTENT, STRING}},
|
||||
{"MapSpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, FLOAT, "0.0"}},
|
||||
{"NextMapSpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, JSON}},
|
||||
|
||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 7.1 KiB |
|
Before Width: | Height: | Size: 11 KiB |
@@ -45,326 +45,326 @@ const static double MAHA_THRESH_31 = 3.8414588206941227;
|
||||
* *
|
||||
* This file is part of 'ekf' *
|
||||
******************************************************************************/
|
||||
void err_fun(double *nom_x, double *delta_x, double *out_5070392900769873758) {
|
||||
out_5070392900769873758[0] = delta_x[0] + nom_x[0];
|
||||
out_5070392900769873758[1] = delta_x[1] + nom_x[1];
|
||||
out_5070392900769873758[2] = delta_x[2] + nom_x[2];
|
||||
out_5070392900769873758[3] = delta_x[3] + nom_x[3];
|
||||
out_5070392900769873758[4] = delta_x[4] + nom_x[4];
|
||||
out_5070392900769873758[5] = delta_x[5] + nom_x[5];
|
||||
out_5070392900769873758[6] = delta_x[6] + nom_x[6];
|
||||
out_5070392900769873758[7] = delta_x[7] + nom_x[7];
|
||||
out_5070392900769873758[8] = delta_x[8] + nom_x[8];
|
||||
void err_fun(double *nom_x, double *delta_x, double *out_205475353292099530) {
|
||||
out_205475353292099530[0] = delta_x[0] + nom_x[0];
|
||||
out_205475353292099530[1] = delta_x[1] + nom_x[1];
|
||||
out_205475353292099530[2] = delta_x[2] + nom_x[2];
|
||||
out_205475353292099530[3] = delta_x[3] + nom_x[3];
|
||||
out_205475353292099530[4] = delta_x[4] + nom_x[4];
|
||||
out_205475353292099530[5] = delta_x[5] + nom_x[5];
|
||||
out_205475353292099530[6] = delta_x[6] + nom_x[6];
|
||||
out_205475353292099530[7] = delta_x[7] + nom_x[7];
|
||||
out_205475353292099530[8] = delta_x[8] + nom_x[8];
|
||||
}
|
||||
void inv_err_fun(double *nom_x, double *true_x, double *out_3742760733154016051) {
|
||||
out_3742760733154016051[0] = -nom_x[0] + true_x[0];
|
||||
out_3742760733154016051[1] = -nom_x[1] + true_x[1];
|
||||
out_3742760733154016051[2] = -nom_x[2] + true_x[2];
|
||||
out_3742760733154016051[3] = -nom_x[3] + true_x[3];
|
||||
out_3742760733154016051[4] = -nom_x[4] + true_x[4];
|
||||
out_3742760733154016051[5] = -nom_x[5] + true_x[5];
|
||||
out_3742760733154016051[6] = -nom_x[6] + true_x[6];
|
||||
out_3742760733154016051[7] = -nom_x[7] + true_x[7];
|
||||
out_3742760733154016051[8] = -nom_x[8] + true_x[8];
|
||||
void inv_err_fun(double *nom_x, double *true_x, double *out_6859088956493527341) {
|
||||
out_6859088956493527341[0] = -nom_x[0] + true_x[0];
|
||||
out_6859088956493527341[1] = -nom_x[1] + true_x[1];
|
||||
out_6859088956493527341[2] = -nom_x[2] + true_x[2];
|
||||
out_6859088956493527341[3] = -nom_x[3] + true_x[3];
|
||||
out_6859088956493527341[4] = -nom_x[4] + true_x[4];
|
||||
out_6859088956493527341[5] = -nom_x[5] + true_x[5];
|
||||
out_6859088956493527341[6] = -nom_x[6] + true_x[6];
|
||||
out_6859088956493527341[7] = -nom_x[7] + true_x[7];
|
||||
out_6859088956493527341[8] = -nom_x[8] + true_x[8];
|
||||
}
|
||||
void H_mod_fun(double *state, double *out_5758456641177717920) {
|
||||
out_5758456641177717920[0] = 1.0;
|
||||
out_5758456641177717920[1] = 0.0;
|
||||
out_5758456641177717920[2] = 0.0;
|
||||
out_5758456641177717920[3] = 0.0;
|
||||
out_5758456641177717920[4] = 0.0;
|
||||
out_5758456641177717920[5] = 0.0;
|
||||
out_5758456641177717920[6] = 0.0;
|
||||
out_5758456641177717920[7] = 0.0;
|
||||
out_5758456641177717920[8] = 0.0;
|
||||
out_5758456641177717920[9] = 0.0;
|
||||
out_5758456641177717920[10] = 1.0;
|
||||
out_5758456641177717920[11] = 0.0;
|
||||
out_5758456641177717920[12] = 0.0;
|
||||
out_5758456641177717920[13] = 0.0;
|
||||
out_5758456641177717920[14] = 0.0;
|
||||
out_5758456641177717920[15] = 0.0;
|
||||
out_5758456641177717920[16] = 0.0;
|
||||
out_5758456641177717920[17] = 0.0;
|
||||
out_5758456641177717920[18] = 0.0;
|
||||
out_5758456641177717920[19] = 0.0;
|
||||
out_5758456641177717920[20] = 1.0;
|
||||
out_5758456641177717920[21] = 0.0;
|
||||
out_5758456641177717920[22] = 0.0;
|
||||
out_5758456641177717920[23] = 0.0;
|
||||
out_5758456641177717920[24] = 0.0;
|
||||
out_5758456641177717920[25] = 0.0;
|
||||
out_5758456641177717920[26] = 0.0;
|
||||
out_5758456641177717920[27] = 0.0;
|
||||
out_5758456641177717920[28] = 0.0;
|
||||
out_5758456641177717920[29] = 0.0;
|
||||
out_5758456641177717920[30] = 1.0;
|
||||
out_5758456641177717920[31] = 0.0;
|
||||
out_5758456641177717920[32] = 0.0;
|
||||
out_5758456641177717920[33] = 0.0;
|
||||
out_5758456641177717920[34] = 0.0;
|
||||
out_5758456641177717920[35] = 0.0;
|
||||
out_5758456641177717920[36] = 0.0;
|
||||
out_5758456641177717920[37] = 0.0;
|
||||
out_5758456641177717920[38] = 0.0;
|
||||
out_5758456641177717920[39] = 0.0;
|
||||
out_5758456641177717920[40] = 1.0;
|
||||
out_5758456641177717920[41] = 0.0;
|
||||
out_5758456641177717920[42] = 0.0;
|
||||
out_5758456641177717920[43] = 0.0;
|
||||
out_5758456641177717920[44] = 0.0;
|
||||
out_5758456641177717920[45] = 0.0;
|
||||
out_5758456641177717920[46] = 0.0;
|
||||
out_5758456641177717920[47] = 0.0;
|
||||
out_5758456641177717920[48] = 0.0;
|
||||
out_5758456641177717920[49] = 0.0;
|
||||
out_5758456641177717920[50] = 1.0;
|
||||
out_5758456641177717920[51] = 0.0;
|
||||
out_5758456641177717920[52] = 0.0;
|
||||
out_5758456641177717920[53] = 0.0;
|
||||
out_5758456641177717920[54] = 0.0;
|
||||
out_5758456641177717920[55] = 0.0;
|
||||
out_5758456641177717920[56] = 0.0;
|
||||
out_5758456641177717920[57] = 0.0;
|
||||
out_5758456641177717920[58] = 0.0;
|
||||
out_5758456641177717920[59] = 0.0;
|
||||
out_5758456641177717920[60] = 1.0;
|
||||
out_5758456641177717920[61] = 0.0;
|
||||
out_5758456641177717920[62] = 0.0;
|
||||
out_5758456641177717920[63] = 0.0;
|
||||
out_5758456641177717920[64] = 0.0;
|
||||
out_5758456641177717920[65] = 0.0;
|
||||
out_5758456641177717920[66] = 0.0;
|
||||
out_5758456641177717920[67] = 0.0;
|
||||
out_5758456641177717920[68] = 0.0;
|
||||
out_5758456641177717920[69] = 0.0;
|
||||
out_5758456641177717920[70] = 1.0;
|
||||
out_5758456641177717920[71] = 0.0;
|
||||
out_5758456641177717920[72] = 0.0;
|
||||
out_5758456641177717920[73] = 0.0;
|
||||
out_5758456641177717920[74] = 0.0;
|
||||
out_5758456641177717920[75] = 0.0;
|
||||
out_5758456641177717920[76] = 0.0;
|
||||
out_5758456641177717920[77] = 0.0;
|
||||
out_5758456641177717920[78] = 0.0;
|
||||
out_5758456641177717920[79] = 0.0;
|
||||
out_5758456641177717920[80] = 1.0;
|
||||
void H_mod_fun(double *state, double *out_8201686483145055601) {
|
||||
out_8201686483145055601[0] = 1.0;
|
||||
out_8201686483145055601[1] = 0.0;
|
||||
out_8201686483145055601[2] = 0.0;
|
||||
out_8201686483145055601[3] = 0.0;
|
||||
out_8201686483145055601[4] = 0.0;
|
||||
out_8201686483145055601[5] = 0.0;
|
||||
out_8201686483145055601[6] = 0.0;
|
||||
out_8201686483145055601[7] = 0.0;
|
||||
out_8201686483145055601[8] = 0.0;
|
||||
out_8201686483145055601[9] = 0.0;
|
||||
out_8201686483145055601[10] = 1.0;
|
||||
out_8201686483145055601[11] = 0.0;
|
||||
out_8201686483145055601[12] = 0.0;
|
||||
out_8201686483145055601[13] = 0.0;
|
||||
out_8201686483145055601[14] = 0.0;
|
||||
out_8201686483145055601[15] = 0.0;
|
||||
out_8201686483145055601[16] = 0.0;
|
||||
out_8201686483145055601[17] = 0.0;
|
||||
out_8201686483145055601[18] = 0.0;
|
||||
out_8201686483145055601[19] = 0.0;
|
||||
out_8201686483145055601[20] = 1.0;
|
||||
out_8201686483145055601[21] = 0.0;
|
||||
out_8201686483145055601[22] = 0.0;
|
||||
out_8201686483145055601[23] = 0.0;
|
||||
out_8201686483145055601[24] = 0.0;
|
||||
out_8201686483145055601[25] = 0.0;
|
||||
out_8201686483145055601[26] = 0.0;
|
||||
out_8201686483145055601[27] = 0.0;
|
||||
out_8201686483145055601[28] = 0.0;
|
||||
out_8201686483145055601[29] = 0.0;
|
||||
out_8201686483145055601[30] = 1.0;
|
||||
out_8201686483145055601[31] = 0.0;
|
||||
out_8201686483145055601[32] = 0.0;
|
||||
out_8201686483145055601[33] = 0.0;
|
||||
out_8201686483145055601[34] = 0.0;
|
||||
out_8201686483145055601[35] = 0.0;
|
||||
out_8201686483145055601[36] = 0.0;
|
||||
out_8201686483145055601[37] = 0.0;
|
||||
out_8201686483145055601[38] = 0.0;
|
||||
out_8201686483145055601[39] = 0.0;
|
||||
out_8201686483145055601[40] = 1.0;
|
||||
out_8201686483145055601[41] = 0.0;
|
||||
out_8201686483145055601[42] = 0.0;
|
||||
out_8201686483145055601[43] = 0.0;
|
||||
out_8201686483145055601[44] = 0.0;
|
||||
out_8201686483145055601[45] = 0.0;
|
||||
out_8201686483145055601[46] = 0.0;
|
||||
out_8201686483145055601[47] = 0.0;
|
||||
out_8201686483145055601[48] = 0.0;
|
||||
out_8201686483145055601[49] = 0.0;
|
||||
out_8201686483145055601[50] = 1.0;
|
||||
out_8201686483145055601[51] = 0.0;
|
||||
out_8201686483145055601[52] = 0.0;
|
||||
out_8201686483145055601[53] = 0.0;
|
||||
out_8201686483145055601[54] = 0.0;
|
||||
out_8201686483145055601[55] = 0.0;
|
||||
out_8201686483145055601[56] = 0.0;
|
||||
out_8201686483145055601[57] = 0.0;
|
||||
out_8201686483145055601[58] = 0.0;
|
||||
out_8201686483145055601[59] = 0.0;
|
||||
out_8201686483145055601[60] = 1.0;
|
||||
out_8201686483145055601[61] = 0.0;
|
||||
out_8201686483145055601[62] = 0.0;
|
||||
out_8201686483145055601[63] = 0.0;
|
||||
out_8201686483145055601[64] = 0.0;
|
||||
out_8201686483145055601[65] = 0.0;
|
||||
out_8201686483145055601[66] = 0.0;
|
||||
out_8201686483145055601[67] = 0.0;
|
||||
out_8201686483145055601[68] = 0.0;
|
||||
out_8201686483145055601[69] = 0.0;
|
||||
out_8201686483145055601[70] = 1.0;
|
||||
out_8201686483145055601[71] = 0.0;
|
||||
out_8201686483145055601[72] = 0.0;
|
||||
out_8201686483145055601[73] = 0.0;
|
||||
out_8201686483145055601[74] = 0.0;
|
||||
out_8201686483145055601[75] = 0.0;
|
||||
out_8201686483145055601[76] = 0.0;
|
||||
out_8201686483145055601[77] = 0.0;
|
||||
out_8201686483145055601[78] = 0.0;
|
||||
out_8201686483145055601[79] = 0.0;
|
||||
out_8201686483145055601[80] = 1.0;
|
||||
}
|
||||
void f_fun(double *state, double dt, double *out_730595102125265078) {
|
||||
out_730595102125265078[0] = state[0];
|
||||
out_730595102125265078[1] = state[1];
|
||||
out_730595102125265078[2] = state[2];
|
||||
out_730595102125265078[3] = state[3];
|
||||
out_730595102125265078[4] = state[4];
|
||||
out_730595102125265078[5] = dt*((-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]))*state[6] - 9.8100000000000005*state[8] + stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*state[1]) + (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*state[4])) + state[5];
|
||||
out_730595102125265078[6] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*state[4])) + state[6];
|
||||
out_730595102125265078[7] = state[7];
|
||||
out_730595102125265078[8] = state[8];
|
||||
void f_fun(double *state, double dt, double *out_2204957494938772746) {
|
||||
out_2204957494938772746[0] = state[0];
|
||||
out_2204957494938772746[1] = state[1];
|
||||
out_2204957494938772746[2] = state[2];
|
||||
out_2204957494938772746[3] = state[3];
|
||||
out_2204957494938772746[4] = state[4];
|
||||
out_2204957494938772746[5] = dt*((-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]))*state[6] - 9.8100000000000005*state[8] + stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*state[1]) + (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*state[4])) + state[5];
|
||||
out_2204957494938772746[6] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*state[4])) + state[6];
|
||||
out_2204957494938772746[7] = state[7];
|
||||
out_2204957494938772746[8] = state[8];
|
||||
}
|
||||
void F_fun(double *state, double dt, double *out_7198115545780111359) {
|
||||
out_7198115545780111359[0] = 1;
|
||||
out_7198115545780111359[1] = 0;
|
||||
out_7198115545780111359[2] = 0;
|
||||
out_7198115545780111359[3] = 0;
|
||||
out_7198115545780111359[4] = 0;
|
||||
out_7198115545780111359[5] = 0;
|
||||
out_7198115545780111359[6] = 0;
|
||||
out_7198115545780111359[7] = 0;
|
||||
out_7198115545780111359[8] = 0;
|
||||
out_7198115545780111359[9] = 0;
|
||||
out_7198115545780111359[10] = 1;
|
||||
out_7198115545780111359[11] = 0;
|
||||
out_7198115545780111359[12] = 0;
|
||||
out_7198115545780111359[13] = 0;
|
||||
out_7198115545780111359[14] = 0;
|
||||
out_7198115545780111359[15] = 0;
|
||||
out_7198115545780111359[16] = 0;
|
||||
out_7198115545780111359[17] = 0;
|
||||
out_7198115545780111359[18] = 0;
|
||||
out_7198115545780111359[19] = 0;
|
||||
out_7198115545780111359[20] = 1;
|
||||
out_7198115545780111359[21] = 0;
|
||||
out_7198115545780111359[22] = 0;
|
||||
out_7198115545780111359[23] = 0;
|
||||
out_7198115545780111359[24] = 0;
|
||||
out_7198115545780111359[25] = 0;
|
||||
out_7198115545780111359[26] = 0;
|
||||
out_7198115545780111359[27] = 0;
|
||||
out_7198115545780111359[28] = 0;
|
||||
out_7198115545780111359[29] = 0;
|
||||
out_7198115545780111359[30] = 1;
|
||||
out_7198115545780111359[31] = 0;
|
||||
out_7198115545780111359[32] = 0;
|
||||
out_7198115545780111359[33] = 0;
|
||||
out_7198115545780111359[34] = 0;
|
||||
out_7198115545780111359[35] = 0;
|
||||
out_7198115545780111359[36] = 0;
|
||||
out_7198115545780111359[37] = 0;
|
||||
out_7198115545780111359[38] = 0;
|
||||
out_7198115545780111359[39] = 0;
|
||||
out_7198115545780111359[40] = 1;
|
||||
out_7198115545780111359[41] = 0;
|
||||
out_7198115545780111359[42] = 0;
|
||||
out_7198115545780111359[43] = 0;
|
||||
out_7198115545780111359[44] = 0;
|
||||
out_7198115545780111359[45] = dt*(stiffness_front*(-state[2] - state[3] + state[7])/(mass*state[1]) + (-stiffness_front - stiffness_rear)*state[5]/(mass*state[4]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[6]/(mass*state[4]));
|
||||
out_7198115545780111359[46] = -dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*pow(state[1], 2));
|
||||
out_7198115545780111359[47] = -dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_7198115545780111359[48] = -dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_7198115545780111359[49] = dt*((-1 - (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*pow(state[4], 2)))*state[6] - (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*pow(state[4], 2)));
|
||||
out_7198115545780111359[50] = dt*(-stiffness_front*state[0] - stiffness_rear*state[0])/(mass*state[4]) + 1;
|
||||
out_7198115545780111359[51] = dt*(-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]));
|
||||
out_7198115545780111359[52] = dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_7198115545780111359[53] = -9.8100000000000005*dt;
|
||||
out_7198115545780111359[54] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front - pow(center_to_rear, 2)*stiffness_rear)*state[6]/(rotational_inertia*state[4]));
|
||||
out_7198115545780111359[55] = -center_to_front*dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*pow(state[1], 2));
|
||||
out_7198115545780111359[56] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_7198115545780111359[57] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_7198115545780111359[58] = dt*(-(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*pow(state[4], 2)) - (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*pow(state[4], 2)));
|
||||
out_7198115545780111359[59] = dt*(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(rotational_inertia*state[4]);
|
||||
out_7198115545780111359[60] = dt*(-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])/(rotational_inertia*state[4]) + 1;
|
||||
out_7198115545780111359[61] = center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_7198115545780111359[62] = 0;
|
||||
out_7198115545780111359[63] = 0;
|
||||
out_7198115545780111359[64] = 0;
|
||||
out_7198115545780111359[65] = 0;
|
||||
out_7198115545780111359[66] = 0;
|
||||
out_7198115545780111359[67] = 0;
|
||||
out_7198115545780111359[68] = 0;
|
||||
out_7198115545780111359[69] = 0;
|
||||
out_7198115545780111359[70] = 1;
|
||||
out_7198115545780111359[71] = 0;
|
||||
out_7198115545780111359[72] = 0;
|
||||
out_7198115545780111359[73] = 0;
|
||||
out_7198115545780111359[74] = 0;
|
||||
out_7198115545780111359[75] = 0;
|
||||
out_7198115545780111359[76] = 0;
|
||||
out_7198115545780111359[77] = 0;
|
||||
out_7198115545780111359[78] = 0;
|
||||
out_7198115545780111359[79] = 0;
|
||||
out_7198115545780111359[80] = 1;
|
||||
void F_fun(double *state, double dt, double *out_2327939745960551937) {
|
||||
out_2327939745960551937[0] = 1;
|
||||
out_2327939745960551937[1] = 0;
|
||||
out_2327939745960551937[2] = 0;
|
||||
out_2327939745960551937[3] = 0;
|
||||
out_2327939745960551937[4] = 0;
|
||||
out_2327939745960551937[5] = 0;
|
||||
out_2327939745960551937[6] = 0;
|
||||
out_2327939745960551937[7] = 0;
|
||||
out_2327939745960551937[8] = 0;
|
||||
out_2327939745960551937[9] = 0;
|
||||
out_2327939745960551937[10] = 1;
|
||||
out_2327939745960551937[11] = 0;
|
||||
out_2327939745960551937[12] = 0;
|
||||
out_2327939745960551937[13] = 0;
|
||||
out_2327939745960551937[14] = 0;
|
||||
out_2327939745960551937[15] = 0;
|
||||
out_2327939745960551937[16] = 0;
|
||||
out_2327939745960551937[17] = 0;
|
||||
out_2327939745960551937[18] = 0;
|
||||
out_2327939745960551937[19] = 0;
|
||||
out_2327939745960551937[20] = 1;
|
||||
out_2327939745960551937[21] = 0;
|
||||
out_2327939745960551937[22] = 0;
|
||||
out_2327939745960551937[23] = 0;
|
||||
out_2327939745960551937[24] = 0;
|
||||
out_2327939745960551937[25] = 0;
|
||||
out_2327939745960551937[26] = 0;
|
||||
out_2327939745960551937[27] = 0;
|
||||
out_2327939745960551937[28] = 0;
|
||||
out_2327939745960551937[29] = 0;
|
||||
out_2327939745960551937[30] = 1;
|
||||
out_2327939745960551937[31] = 0;
|
||||
out_2327939745960551937[32] = 0;
|
||||
out_2327939745960551937[33] = 0;
|
||||
out_2327939745960551937[34] = 0;
|
||||
out_2327939745960551937[35] = 0;
|
||||
out_2327939745960551937[36] = 0;
|
||||
out_2327939745960551937[37] = 0;
|
||||
out_2327939745960551937[38] = 0;
|
||||
out_2327939745960551937[39] = 0;
|
||||
out_2327939745960551937[40] = 1;
|
||||
out_2327939745960551937[41] = 0;
|
||||
out_2327939745960551937[42] = 0;
|
||||
out_2327939745960551937[43] = 0;
|
||||
out_2327939745960551937[44] = 0;
|
||||
out_2327939745960551937[45] = dt*(stiffness_front*(-state[2] - state[3] + state[7])/(mass*state[1]) + (-stiffness_front - stiffness_rear)*state[5]/(mass*state[4]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[6]/(mass*state[4]));
|
||||
out_2327939745960551937[46] = -dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(mass*pow(state[1], 2));
|
||||
out_2327939745960551937[47] = -dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_2327939745960551937[48] = -dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_2327939745960551937[49] = dt*((-1 - (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*pow(state[4], 2)))*state[6] - (-stiffness_front*state[0] - stiffness_rear*state[0])*state[5]/(mass*pow(state[4], 2)));
|
||||
out_2327939745960551937[50] = dt*(-stiffness_front*state[0] - stiffness_rear*state[0])/(mass*state[4]) + 1;
|
||||
out_2327939745960551937[51] = dt*(-state[4] + (-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(mass*state[4]));
|
||||
out_2327939745960551937[52] = dt*stiffness_front*state[0]/(mass*state[1]);
|
||||
out_2327939745960551937[53] = -9.8100000000000005*dt;
|
||||
out_2327939745960551937[54] = dt*(center_to_front*stiffness_front*(-state[2] - state[3] + state[7])/(rotational_inertia*state[1]) + (-center_to_front*stiffness_front + center_to_rear*stiffness_rear)*state[5]/(rotational_inertia*state[4]) + (-pow(center_to_front, 2)*stiffness_front - pow(center_to_rear, 2)*stiffness_rear)*state[6]/(rotational_inertia*state[4]));
|
||||
out_2327939745960551937[55] = -center_to_front*dt*stiffness_front*(-state[2] - state[3] + state[7])*state[0]/(rotational_inertia*pow(state[1], 2));
|
||||
out_2327939745960551937[56] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_2327939745960551937[57] = -center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_2327939745960551937[58] = dt*(-(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])*state[5]/(rotational_inertia*pow(state[4], 2)) - (-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])*state[6]/(rotational_inertia*pow(state[4], 2)));
|
||||
out_2327939745960551937[59] = dt*(-center_to_front*stiffness_front*state[0] + center_to_rear*stiffness_rear*state[0])/(rotational_inertia*state[4]);
|
||||
out_2327939745960551937[60] = dt*(-pow(center_to_front, 2)*stiffness_front*state[0] - pow(center_to_rear, 2)*stiffness_rear*state[0])/(rotational_inertia*state[4]) + 1;
|
||||
out_2327939745960551937[61] = center_to_front*dt*stiffness_front*state[0]/(rotational_inertia*state[1]);
|
||||
out_2327939745960551937[62] = 0;
|
||||
out_2327939745960551937[63] = 0;
|
||||
out_2327939745960551937[64] = 0;
|
||||
out_2327939745960551937[65] = 0;
|
||||
out_2327939745960551937[66] = 0;
|
||||
out_2327939745960551937[67] = 0;
|
||||
out_2327939745960551937[68] = 0;
|
||||
out_2327939745960551937[69] = 0;
|
||||
out_2327939745960551937[70] = 1;
|
||||
out_2327939745960551937[71] = 0;
|
||||
out_2327939745960551937[72] = 0;
|
||||
out_2327939745960551937[73] = 0;
|
||||
out_2327939745960551937[74] = 0;
|
||||
out_2327939745960551937[75] = 0;
|
||||
out_2327939745960551937[76] = 0;
|
||||
out_2327939745960551937[77] = 0;
|
||||
out_2327939745960551937[78] = 0;
|
||||
out_2327939745960551937[79] = 0;
|
||||
out_2327939745960551937[80] = 1;
|
||||
}
|
||||
void h_25(double *state, double *unused, double *out_5441109048213736058) {
|
||||
out_5441109048213736058[0] = state[6];
|
||||
void h_25(double *state, double *unused, double *out_8734450240234959528) {
|
||||
out_8734450240234959528[0] = state[6];
|
||||
}
|
||||
void H_25(double *state, double *unused, double *out_4766949399557973891) {
|
||||
out_4766949399557973891[0] = 0;
|
||||
out_4766949399557973891[1] = 0;
|
||||
out_4766949399557973891[2] = 0;
|
||||
out_4766949399557973891[3] = 0;
|
||||
out_4766949399557973891[4] = 0;
|
||||
out_4766949399557973891[5] = 0;
|
||||
out_4766949399557973891[6] = 1;
|
||||
out_4766949399557973891[7] = 0;
|
||||
out_4766949399557973891[8] = 0;
|
||||
void H_25(double *state, double *unused, double *out_6133161197384342845) {
|
||||
out_6133161197384342845[0] = 0;
|
||||
out_6133161197384342845[1] = 0;
|
||||
out_6133161197384342845[2] = 0;
|
||||
out_6133161197384342845[3] = 0;
|
||||
out_6133161197384342845[4] = 0;
|
||||
out_6133161197384342845[5] = 0;
|
||||
out_6133161197384342845[6] = 1;
|
||||
out_6133161197384342845[7] = 0;
|
||||
out_6133161197384342845[8] = 0;
|
||||
}
|
||||
void h_24(double *state, double *unused, double *out_2797667639827089179) {
|
||||
out_2797667639827089179[0] = state[4];
|
||||
out_2797667639827089179[1] = state[5];
|
||||
void h_24(double *state, double *unused, double *out_8806581475742121932) {
|
||||
out_8806581475742121932[0] = state[4];
|
||||
out_8806581475742121932[1] = state[5];
|
||||
}
|
||||
void H_24(double *state, double *unused, double *out_4461115786511221334) {
|
||||
out_4461115786511221334[0] = 0;
|
||||
out_4461115786511221334[1] = 0;
|
||||
out_4461115786511221334[2] = 0;
|
||||
out_4461115786511221334[3] = 0;
|
||||
out_4461115786511221334[4] = 1;
|
||||
out_4461115786511221334[5] = 0;
|
||||
out_4461115786511221334[6] = 0;
|
||||
out_4461115786511221334[7] = 0;
|
||||
out_4461115786511221334[8] = 0;
|
||||
out_4461115786511221334[9] = 0;
|
||||
out_4461115786511221334[10] = 0;
|
||||
out_4461115786511221334[11] = 0;
|
||||
out_4461115786511221334[12] = 0;
|
||||
out_4461115786511221334[13] = 0;
|
||||
out_4461115786511221334[14] = 1;
|
||||
out_4461115786511221334[15] = 0;
|
||||
out_4461115786511221334[16] = 0;
|
||||
out_4461115786511221334[17] = 0;
|
||||
void H_24(double *state, double *unused, double *out_5738011069733690670) {
|
||||
out_5738011069733690670[0] = 0;
|
||||
out_5738011069733690670[1] = 0;
|
||||
out_5738011069733690670[2] = 0;
|
||||
out_5738011069733690670[3] = 0;
|
||||
out_5738011069733690670[4] = 1;
|
||||
out_5738011069733690670[5] = 0;
|
||||
out_5738011069733690670[6] = 0;
|
||||
out_5738011069733690670[7] = 0;
|
||||
out_5738011069733690670[8] = 0;
|
||||
out_5738011069733690670[9] = 0;
|
||||
out_5738011069733690670[10] = 0;
|
||||
out_5738011069733690670[11] = 0;
|
||||
out_5738011069733690670[12] = 0;
|
||||
out_5738011069733690670[13] = 0;
|
||||
out_5738011069733690670[14] = 1;
|
||||
out_5738011069733690670[15] = 0;
|
||||
out_5738011069733690670[16] = 0;
|
||||
out_5738011069733690670[17] = 0;
|
||||
}
|
||||
void h_30(double *state, double *unused, double *out_1188271489450022901) {
|
||||
out_1188271489450022901[0] = state[4];
|
||||
void h_30(double *state, double *unused, double *out_971184983414287087) {
|
||||
out_971184983414287087[0] = state[4];
|
||||
}
|
||||
void H_30(double *state, double *unused, double *out_9152098344023969527) {
|
||||
out_9152098344023969527[0] = 0;
|
||||
out_9152098344023969527[1] = 0;
|
||||
out_9152098344023969527[2] = 0;
|
||||
out_9152098344023969527[3] = 0;
|
||||
out_9152098344023969527[4] = 1;
|
||||
out_9152098344023969527[5] = 0;
|
||||
out_9152098344023969527[6] = 0;
|
||||
out_9152098344023969527[7] = 0;
|
||||
out_9152098344023969527[8] = 0;
|
||||
void H_30(double *state, double *unused, double *out_5396892534833592016) {
|
||||
out_5396892534833592016[0] = 0;
|
||||
out_5396892534833592016[1] = 0;
|
||||
out_5396892534833592016[2] = 0;
|
||||
out_5396892534833592016[3] = 0;
|
||||
out_5396892534833592016[4] = 1;
|
||||
out_5396892534833592016[5] = 0;
|
||||
out_5396892534833592016[6] = 0;
|
||||
out_5396892534833592016[7] = 0;
|
||||
out_5396892534833592016[8] = 0;
|
||||
}
|
||||
void h_26(double *state, double *unused, double *out_6530138725336053464) {
|
||||
out_6530138725336053464[0] = state[7];
|
||||
void h_26(double *state, double *unused, double *out_1416855028350640224) {
|
||||
out_1416855028350640224[0] = state[7];
|
||||
}
|
||||
void H_26(double *state, double *unused, double *out_8508452718432030115) {
|
||||
out_8508452718432030115[0] = 0;
|
||||
out_8508452718432030115[1] = 0;
|
||||
out_8508452718432030115[2] = 0;
|
||||
out_8508452718432030115[3] = 0;
|
||||
out_8508452718432030115[4] = 0;
|
||||
out_8508452718432030115[5] = 0;
|
||||
out_8508452718432030115[6] = 0;
|
||||
out_8508452718432030115[7] = 1;
|
||||
out_8508452718432030115[8] = 0;
|
||||
void H_26(double *state, double *unused, double *out_2391657878510286621) {
|
||||
out_2391657878510286621[0] = 0;
|
||||
out_2391657878510286621[1] = 0;
|
||||
out_2391657878510286621[2] = 0;
|
||||
out_2391657878510286621[3] = 0;
|
||||
out_2391657878510286621[4] = 0;
|
||||
out_2391657878510286621[5] = 0;
|
||||
out_2391657878510286621[6] = 0;
|
||||
out_2391657878510286621[7] = 1;
|
||||
out_2391657878510286621[8] = 0;
|
||||
}
|
||||
void h_27(double *state, double *unused, double *out_8003961757834969913) {
|
||||
out_8003961757834969913[0] = state[3];
|
||||
void h_27(double *state, double *unused, double *out_5511166866350839857) {
|
||||
out_5511166866350839857[0] = state[3];
|
||||
}
|
||||
void H_27(double *state, double *unused, double *out_6977335032223544616) {
|
||||
out_6977335032223544616[0] = 0;
|
||||
out_6977335032223544616[1] = 0;
|
||||
out_6977335032223544616[2] = 0;
|
||||
out_6977335032223544616[3] = 1;
|
||||
out_6977335032223544616[4] = 0;
|
||||
out_6977335032223544616[5] = 0;
|
||||
out_6977335032223544616[6] = 0;
|
||||
out_6977335032223544616[7] = 0;
|
||||
out_6977335032223544616[8] = 0;
|
||||
void H_27(double *state, double *unused, double *out_7571655846634016927) {
|
||||
out_7571655846634016927[0] = 0;
|
||||
out_7571655846634016927[1] = 0;
|
||||
out_7571655846634016927[2] = 0;
|
||||
out_7571655846634016927[3] = 1;
|
||||
out_7571655846634016927[4] = 0;
|
||||
out_7571655846634016927[5] = 0;
|
||||
out_7571655846634016927[6] = 0;
|
||||
out_7571655846634016927[7] = 0;
|
||||
out_7571655846634016927[8] = 0;
|
||||
}
|
||||
void h_29(double *state, double *unused, double *out_1416133831358674750) {
|
||||
out_1416133831358674750[0] = state[1];
|
||||
void h_29(double *state, double *unused, double *out_5235972804066333968) {
|
||||
out_5235972804066333968[0] = state[1];
|
||||
}
|
||||
void H_29(double *state, double *unused, double *out_8784414385371189905) {
|
||||
out_8784414385371189905[0] = 0;
|
||||
out_8784414385371189905[1] = 1;
|
||||
out_8784414385371189905[2] = 0;
|
||||
out_8784414385371189905[3] = 0;
|
||||
out_8784414385371189905[4] = 0;
|
||||
out_8784414385371189905[5] = 0;
|
||||
out_8784414385371189905[6] = 0;
|
||||
out_8784414385371189905[7] = 0;
|
||||
out_8784414385371189905[8] = 0;
|
||||
void H_29(double *state, double *unused, double *out_9161725500205983656) {
|
||||
out_9161725500205983656[0] = 0;
|
||||
out_9161725500205983656[1] = 1;
|
||||
out_9161725500205983656[2] = 0;
|
||||
out_9161725500205983656[3] = 0;
|
||||
out_9161725500205983656[4] = 0;
|
||||
out_9161725500205983656[5] = 0;
|
||||
out_9161725500205983656[6] = 0;
|
||||
out_9161725500205983656[7] = 0;
|
||||
out_9161725500205983656[8] = 0;
|
||||
}
|
||||
void h_28(double *state, double *unused, double *out_7400645873158492396) {
|
||||
out_7400645873158492396[0] = state[0];
|
||||
void h_28(double *state, double *unused, double *out_7891338238985058206) {
|
||||
out_7891338238985058206[0] = state[0];
|
||||
}
|
||||
void H_28(double *state, double *unused, double *out_6820784113805863654) {
|
||||
out_6820784113805863654[0] = 1;
|
||||
out_6820784113805863654[1] = 0;
|
||||
out_6820784113805863654[2] = 0;
|
||||
out_6820784113805863654[3] = 0;
|
||||
out_6820784113805863654[4] = 0;
|
||||
out_6820784113805863654[5] = 0;
|
||||
out_6820784113805863654[6] = 0;
|
||||
out_6820784113805863654[7] = 0;
|
||||
out_6820784113805863654[8] = 0;
|
||||
void H_28(double *state, double *unused, double *out_4079326483136453082) {
|
||||
out_4079326483136453082[0] = 1;
|
||||
out_4079326483136453082[1] = 0;
|
||||
out_4079326483136453082[2] = 0;
|
||||
out_4079326483136453082[3] = 0;
|
||||
out_4079326483136453082[4] = 0;
|
||||
out_4079326483136453082[5] = 0;
|
||||
out_4079326483136453082[6] = 0;
|
||||
out_4079326483136453082[7] = 0;
|
||||
out_4079326483136453082[8] = 0;
|
||||
}
|
||||
void h_31(double *state, double *unused, double *out_1803659519959713708) {
|
||||
out_1803659519959713708[0] = state[8];
|
||||
void h_31(double *state, double *unused, double *out_8694811794428211892) {
|
||||
out_8694811794428211892[0] = state[8];
|
||||
}
|
||||
void H_31(double *state, double *unused, double *out_9134660820665381591) {
|
||||
out_9134660820665381591[0] = 0;
|
||||
out_9134660820665381591[1] = 0;
|
||||
out_9134660820665381591[2] = 0;
|
||||
out_9134660820665381591[3] = 0;
|
||||
out_9134660820665381591[4] = 0;
|
||||
out_9134660820665381591[5] = 0;
|
||||
out_9134660820665381591[6] = 0;
|
||||
out_9134660820665381591[7] = 0;
|
||||
out_9134660820665381591[8] = 1;
|
||||
void H_31(double *state, double *unused, double *out_6163807159261303273) {
|
||||
out_6163807159261303273[0] = 0;
|
||||
out_6163807159261303273[1] = 0;
|
||||
out_6163807159261303273[2] = 0;
|
||||
out_6163807159261303273[3] = 0;
|
||||
out_6163807159261303273[4] = 0;
|
||||
out_6163807159261303273[5] = 0;
|
||||
out_6163807159261303273[6] = 0;
|
||||
out_6163807159261303273[7] = 0;
|
||||
out_6163807159261303273[8] = 1;
|
||||
}
|
||||
#include <eigen3/Eigen/Dense>
|
||||
#include <iostream>
|
||||
@@ -518,68 +518,68 @@ void car_update_28(double *in_x, double *in_P, double *in_z, double *in_R, doubl
|
||||
void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea) {
|
||||
update<1, 3, 0>(in_x, in_P, h_31, H_31, NULL, in_z, in_R, in_ea, MAHA_THRESH_31);
|
||||
}
|
||||
void car_err_fun(double *nom_x, double *delta_x, double *out_5070392900769873758) {
|
||||
err_fun(nom_x, delta_x, out_5070392900769873758);
|
||||
void car_err_fun(double *nom_x, double *delta_x, double *out_205475353292099530) {
|
||||
err_fun(nom_x, delta_x, out_205475353292099530);
|
||||
}
|
||||
void car_inv_err_fun(double *nom_x, double *true_x, double *out_3742760733154016051) {
|
||||
inv_err_fun(nom_x, true_x, out_3742760733154016051);
|
||||
void car_inv_err_fun(double *nom_x, double *true_x, double *out_6859088956493527341) {
|
||||
inv_err_fun(nom_x, true_x, out_6859088956493527341);
|
||||
}
|
||||
void car_H_mod_fun(double *state, double *out_5758456641177717920) {
|
||||
H_mod_fun(state, out_5758456641177717920);
|
||||
void car_H_mod_fun(double *state, double *out_8201686483145055601) {
|
||||
H_mod_fun(state, out_8201686483145055601);
|
||||
}
|
||||
void car_f_fun(double *state, double dt, double *out_730595102125265078) {
|
||||
f_fun(state, dt, out_730595102125265078);
|
||||
void car_f_fun(double *state, double dt, double *out_2204957494938772746) {
|
||||
f_fun(state, dt, out_2204957494938772746);
|
||||
}
|
||||
void car_F_fun(double *state, double dt, double *out_7198115545780111359) {
|
||||
F_fun(state, dt, out_7198115545780111359);
|
||||
void car_F_fun(double *state, double dt, double *out_2327939745960551937) {
|
||||
F_fun(state, dt, out_2327939745960551937);
|
||||
}
|
||||
void car_h_25(double *state, double *unused, double *out_5441109048213736058) {
|
||||
h_25(state, unused, out_5441109048213736058);
|
||||
void car_h_25(double *state, double *unused, double *out_8734450240234959528) {
|
||||
h_25(state, unused, out_8734450240234959528);
|
||||
}
|
||||
void car_H_25(double *state, double *unused, double *out_4766949399557973891) {
|
||||
H_25(state, unused, out_4766949399557973891);
|
||||
void car_H_25(double *state, double *unused, double *out_6133161197384342845) {
|
||||
H_25(state, unused, out_6133161197384342845);
|
||||
}
|
||||
void car_h_24(double *state, double *unused, double *out_2797667639827089179) {
|
||||
h_24(state, unused, out_2797667639827089179);
|
||||
void car_h_24(double *state, double *unused, double *out_8806581475742121932) {
|
||||
h_24(state, unused, out_8806581475742121932);
|
||||
}
|
||||
void car_H_24(double *state, double *unused, double *out_4461115786511221334) {
|
||||
H_24(state, unused, out_4461115786511221334);
|
||||
void car_H_24(double *state, double *unused, double *out_5738011069733690670) {
|
||||
H_24(state, unused, out_5738011069733690670);
|
||||
}
|
||||
void car_h_30(double *state, double *unused, double *out_1188271489450022901) {
|
||||
h_30(state, unused, out_1188271489450022901);
|
||||
void car_h_30(double *state, double *unused, double *out_971184983414287087) {
|
||||
h_30(state, unused, out_971184983414287087);
|
||||
}
|
||||
void car_H_30(double *state, double *unused, double *out_9152098344023969527) {
|
||||
H_30(state, unused, out_9152098344023969527);
|
||||
void car_H_30(double *state, double *unused, double *out_5396892534833592016) {
|
||||
H_30(state, unused, out_5396892534833592016);
|
||||
}
|
||||
void car_h_26(double *state, double *unused, double *out_6530138725336053464) {
|
||||
h_26(state, unused, out_6530138725336053464);
|
||||
void car_h_26(double *state, double *unused, double *out_1416855028350640224) {
|
||||
h_26(state, unused, out_1416855028350640224);
|
||||
}
|
||||
void car_H_26(double *state, double *unused, double *out_8508452718432030115) {
|
||||
H_26(state, unused, out_8508452718432030115);
|
||||
void car_H_26(double *state, double *unused, double *out_2391657878510286621) {
|
||||
H_26(state, unused, out_2391657878510286621);
|
||||
}
|
||||
void car_h_27(double *state, double *unused, double *out_8003961757834969913) {
|
||||
h_27(state, unused, out_8003961757834969913);
|
||||
void car_h_27(double *state, double *unused, double *out_5511166866350839857) {
|
||||
h_27(state, unused, out_5511166866350839857);
|
||||
}
|
||||
void car_H_27(double *state, double *unused, double *out_6977335032223544616) {
|
||||
H_27(state, unused, out_6977335032223544616);
|
||||
void car_H_27(double *state, double *unused, double *out_7571655846634016927) {
|
||||
H_27(state, unused, out_7571655846634016927);
|
||||
}
|
||||
void car_h_29(double *state, double *unused, double *out_1416133831358674750) {
|
||||
h_29(state, unused, out_1416133831358674750);
|
||||
void car_h_29(double *state, double *unused, double *out_5235972804066333968) {
|
||||
h_29(state, unused, out_5235972804066333968);
|
||||
}
|
||||
void car_H_29(double *state, double *unused, double *out_8784414385371189905) {
|
||||
H_29(state, unused, out_8784414385371189905);
|
||||
void car_H_29(double *state, double *unused, double *out_9161725500205983656) {
|
||||
H_29(state, unused, out_9161725500205983656);
|
||||
}
|
||||
void car_h_28(double *state, double *unused, double *out_7400645873158492396) {
|
||||
h_28(state, unused, out_7400645873158492396);
|
||||
void car_h_28(double *state, double *unused, double *out_7891338238985058206) {
|
||||
h_28(state, unused, out_7891338238985058206);
|
||||
}
|
||||
void car_H_28(double *state, double *unused, double *out_6820784113805863654) {
|
||||
H_28(state, unused, out_6820784113805863654);
|
||||
void car_H_28(double *state, double *unused, double *out_4079326483136453082) {
|
||||
H_28(state, unused, out_4079326483136453082);
|
||||
}
|
||||
void car_h_31(double *state, double *unused, double *out_1803659519959713708) {
|
||||
h_31(state, unused, out_1803659519959713708);
|
||||
void car_h_31(double *state, double *unused, double *out_8694811794428211892) {
|
||||
h_31(state, unused, out_8694811794428211892);
|
||||
}
|
||||
void car_H_31(double *state, double *unused, double *out_9134660820665381591) {
|
||||
H_31(state, unused, out_9134660820665381591);
|
||||
void car_H_31(double *state, double *unused, double *out_6163807159261303273) {
|
||||
H_31(state, unused, out_6163807159261303273);
|
||||
}
|
||||
void car_predict(double *in_x, double *in_P, double *in_Q, double dt) {
|
||||
predict(in_x, in_P, in_Q, dt);
|
||||
|
||||
@@ -9,27 +9,27 @@ void car_update_27(double *in_x, double *in_P, double *in_z, double *in_R, doubl
|
||||
void car_update_29(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void car_update_28(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void car_update_31(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void car_err_fun(double *nom_x, double *delta_x, double *out_5070392900769873758);
|
||||
void car_inv_err_fun(double *nom_x, double *true_x, double *out_3742760733154016051);
|
||||
void car_H_mod_fun(double *state, double *out_5758456641177717920);
|
||||
void car_f_fun(double *state, double dt, double *out_730595102125265078);
|
||||
void car_F_fun(double *state, double dt, double *out_7198115545780111359);
|
||||
void car_h_25(double *state, double *unused, double *out_5441109048213736058);
|
||||
void car_H_25(double *state, double *unused, double *out_4766949399557973891);
|
||||
void car_h_24(double *state, double *unused, double *out_2797667639827089179);
|
||||
void car_H_24(double *state, double *unused, double *out_4461115786511221334);
|
||||
void car_h_30(double *state, double *unused, double *out_1188271489450022901);
|
||||
void car_H_30(double *state, double *unused, double *out_9152098344023969527);
|
||||
void car_h_26(double *state, double *unused, double *out_6530138725336053464);
|
||||
void car_H_26(double *state, double *unused, double *out_8508452718432030115);
|
||||
void car_h_27(double *state, double *unused, double *out_8003961757834969913);
|
||||
void car_H_27(double *state, double *unused, double *out_6977335032223544616);
|
||||
void car_h_29(double *state, double *unused, double *out_1416133831358674750);
|
||||
void car_H_29(double *state, double *unused, double *out_8784414385371189905);
|
||||
void car_h_28(double *state, double *unused, double *out_7400645873158492396);
|
||||
void car_H_28(double *state, double *unused, double *out_6820784113805863654);
|
||||
void car_h_31(double *state, double *unused, double *out_1803659519959713708);
|
||||
void car_H_31(double *state, double *unused, double *out_9134660820665381591);
|
||||
void car_err_fun(double *nom_x, double *delta_x, double *out_205475353292099530);
|
||||
void car_inv_err_fun(double *nom_x, double *true_x, double *out_6859088956493527341);
|
||||
void car_H_mod_fun(double *state, double *out_8201686483145055601);
|
||||
void car_f_fun(double *state, double dt, double *out_2204957494938772746);
|
||||
void car_F_fun(double *state, double dt, double *out_2327939745960551937);
|
||||
void car_h_25(double *state, double *unused, double *out_8734450240234959528);
|
||||
void car_H_25(double *state, double *unused, double *out_6133161197384342845);
|
||||
void car_h_24(double *state, double *unused, double *out_8806581475742121932);
|
||||
void car_H_24(double *state, double *unused, double *out_5738011069733690670);
|
||||
void car_h_30(double *state, double *unused, double *out_971184983414287087);
|
||||
void car_H_30(double *state, double *unused, double *out_5396892534833592016);
|
||||
void car_h_26(double *state, double *unused, double *out_1416855028350640224);
|
||||
void car_H_26(double *state, double *unused, double *out_2391657878510286621);
|
||||
void car_h_27(double *state, double *unused, double *out_5511166866350839857);
|
||||
void car_H_27(double *state, double *unused, double *out_7571655846634016927);
|
||||
void car_h_29(double *state, double *unused, double *out_5235972804066333968);
|
||||
void car_H_29(double *state, double *unused, double *out_9161725500205983656);
|
||||
void car_h_28(double *state, double *unused, double *out_7891338238985058206);
|
||||
void car_H_28(double *state, double *unused, double *out_4079326483136453082);
|
||||
void car_h_31(double *state, double *unused, double *out_8694811794428211892);
|
||||
void car_H_31(double *state, double *unused, double *out_6163807159261303273);
|
||||
void car_predict(double *in_x, double *in_P, double *in_Q, double dt);
|
||||
void car_set_mass(double x);
|
||||
void car_set_rotational_inertia(double x);
|
||||
|
||||
@@ -5,18 +5,18 @@ void pose_update_4(double *in_x, double *in_P, double *in_z, double *in_R, doubl
|
||||
void pose_update_10(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void pose_update_13(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void pose_update_14(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void pose_err_fun(double *nom_x, double *delta_x, double *out_8299703332077589328);
|
||||
void pose_inv_err_fun(double *nom_x, double *true_x, double *out_4608058237383429265);
|
||||
void pose_H_mod_fun(double *state, double *out_7885453398379249088);
|
||||
void pose_f_fun(double *state, double dt, double *out_1688144950946873165);
|
||||
void pose_F_fun(double *state, double dt, double *out_4851283621730691038);
|
||||
void pose_h_4(double *state, double *unused, double *out_2329133011647763937);
|
||||
void pose_H_4(double *state, double *unused, double *out_8639614400433961695);
|
||||
void pose_h_10(double *state, double *unused, double *out_3294648635274985008);
|
||||
void pose_H_10(double *state, double *unused, double *out_3780608178453222524);
|
||||
void pose_h_13(double *state, double *unused, double *out_8905113933939181200);
|
||||
void pose_H_13(double *state, double *unused, double *out_6594855847943257120);
|
||||
void pose_h_14(double *state, double *unused, double *out_8324071568749841126);
|
||||
void pose_H_14(double *state, double *unused, double *out_5843888816936105392);
|
||||
void pose_err_fun(double *nom_x, double *delta_x, double *out_7491504487925958906);
|
||||
void pose_inv_err_fun(double *nom_x, double *true_x, double *out_8173082431785614969);
|
||||
void pose_H_mod_fun(double *state, double *out_3955896825213980969);
|
||||
void pose_f_fun(double *state, double dt, double *out_6226431844178190638);
|
||||
void pose_F_fun(double *state, double dt, double *out_5590858509180719260);
|
||||
void pose_h_4(double *state, double *unused, double *out_8311116516369893334);
|
||||
void pose_H_4(double *state, double *unused, double *out_1196621559825099766);
|
||||
void pose_h_10(double *state, double *unused, double *out_8024633733467632830);
|
||||
void pose_H_10(double *state, double *unused, double *out_9211636060607930666);
|
||||
void pose_h_13(double *state, double *unused, double *out_5246243153983473200);
|
||||
void pose_H_13(double *state, double *unused, double *out_4408895385157432567);
|
||||
void pose_h_14(double *state, double *unused, double *out_2666716766060469740);
|
||||
void pose_H_14(double *state, double *unused, double *out_5159862416164584295);
|
||||
void pose_predict(double *in_x, double *in_P, double *in_Q, double dt);
|
||||
}
|
||||
@@ -29,7 +29,7 @@ class ModelState:
|
||||
output: np.ndarray
|
||||
|
||||
def __init__(self, cam_w: int, cam_h: int):
|
||||
self.DEV = get_tg_input_devices(PROCESS_NAME, usbgpu=False)['DEV']
|
||||
self.DEV = get_tg_input_devices(PROCESS_NAME, chestnut=False)['DEV']
|
||||
with open(METADATA_PATH, 'rb') as f:
|
||||
model_metadata = pickle.load(f)
|
||||
self.input_shapes = model_metadata['input_shapes']
|
||||
|
||||
@@ -13,12 +13,12 @@ MODELS_DIR = Path(__file__).resolve().parent / 'models'
|
||||
TG_INPUT_DEVICES_PATH = MODELS_DIR / 'tg_input_devices.json'
|
||||
|
||||
|
||||
def get_tg_input_devices(process_name: str, usbgpu: bool):
|
||||
def get_tg_input_devices(process_name: str, chestnut: bool):
|
||||
with open(TG_INPUT_DEVICES_PATH) as f:
|
||||
return json.load(f)[process_name]['default' if not usbgpu else 'usbgpu']
|
||||
return json.load(f)[process_name]['default' if not chestnut else 'chestnut']
|
||||
|
||||
def modeld_pkl_path(usbgpu: bool):
|
||||
prefix = 'big_' if usbgpu else ''
|
||||
def modeld_pkl_path(chestnut: bool):
|
||||
prefix = 'big_' if chestnut else ''
|
||||
return MODELS_DIR / f'{prefix}driving_tinygrad.pkl'
|
||||
|
||||
def dump_oob(obj, f):
|
||||
@@ -45,7 +45,7 @@ def load_oob(f):
|
||||
yield pb
|
||||
return pickle.load(io.BytesIO(opcodes), buffers=buffers())
|
||||
|
||||
def usbgpu_present() -> bool:
|
||||
def chestnut_present() -> bool:
|
||||
for d in USB_DEVICES_PATH.glob("*"):
|
||||
try:
|
||||
usb_id = (int((d / "idVendor").read_text(), 16), int((d / "idProduct").read_text(), 16))
|
||||
@@ -56,5 +56,5 @@ def usbgpu_present() -> bool:
|
||||
pass
|
||||
return False
|
||||
|
||||
def usbgpu_compiled() -> bool:
|
||||
return Path(get_manifest_path(modeld_pkl_path(usbgpu=True))).is_file()
|
||||
def chestnut_compiled() -> bool:
|
||||
return Path(get_manifest_path(modeld_pkl_path(chestnut=True))).is_file()
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
from collections.abc import Callable
|
||||
import ctypes
|
||||
from functools import cached_property
|
||||
import os
|
||||
os.environ['GMMU'] = '0' # for usbgpu fast loading, noop for qcom
|
||||
os.environ['GMMU'] = '0' # for chestnut fast loading, noop for qcom
|
||||
from tinygrad.tensor import Tensor
|
||||
from tinygrad.device import Device
|
||||
import struct
|
||||
@@ -30,7 +32,7 @@ from openpilot.selfdrive.modeld.compile_modeld import make_input_queues, WARP_IN
|
||||
from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_driving_model_data, fill_pose_msg, PublishState
|
||||
from openpilot.common.file_chunker import open_file_chunked
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
|
||||
from openpilot.selfdrive.modeld.helpers import usbgpu_present, usbgpu_compiled, modeld_pkl_path, get_tg_input_devices, load_oob
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present, chestnut_compiled, modeld_pkl_path, get_tg_input_devices, load_oob
|
||||
|
||||
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
|
||||
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
|
||||
@@ -94,8 +96,10 @@ class ChestnutState:
|
||||
if self.big and "AMD" in Device._opened_devices and self.sends % 100 == 1:
|
||||
try:
|
||||
smu = Device["AMD"].iface.dev_impl.smu
|
||||
metrics_t = smu.smu_mod.SmuMetricsExternal_t
|
||||
smu._send_msg(smu.smu_mod.PPSMC_MSG_TransferTableSmu2Dram, smu.smu_mod.TABLE_SMU_METRICS, timeout=100)
|
||||
metrics = smu.read_table(smu.smu_mod.SmuMetricsExternal_t, smu.smu_mod.TABLE_SMU_METRICS).SmuMetrics
|
||||
metrics_buf = bytearray(smu.adev.vram.view(smu.driver_table_paddr, ctypes.sizeof(metrics_t))[:])
|
||||
metrics = metrics_t.from_buffer(metrics_buf).SmuMetrics
|
||||
self.metrics = {'tempC': metrics.AvgTemperature[smu.smu_mod.TEMP_HOTSPOT],
|
||||
'memoryTempC': metrics.AvgTemperature[smu.smu_mod.TEMP_MEM],
|
||||
'powerDrawW': metrics.AverageSocketPower,
|
||||
@@ -141,18 +145,18 @@ class FrameMeta:
|
||||
class ModelState(ModelStateBase):
|
||||
prev_desire: np.ndarray # for tracking the rising edge of the pulse
|
||||
|
||||
def __init__(self, cam_w: int, cam_h: int, usbgpu: bool):
|
||||
def __init__(self, cam_w: int, cam_h: int, chestnut: bool):
|
||||
ModelStateBase.__init__(self)
|
||||
input_devices = get_tg_input_devices(PROCESS_NAME, usbgpu)
|
||||
input_devices = get_tg_input_devices(PROCESS_NAME, chestnut)
|
||||
self.WARP_DEV, self.QUEUE_DEV = input_devices['WARP_DEV'], input_devices['QUEUE_DEV']
|
||||
jits = load_oob(open_file_chunked(modeld_pkl_path(usbgpu)))
|
||||
jits = load_oob(open_file_chunked(modeld_pkl_path(chestnut)))
|
||||
metadata = jits['metadata']
|
||||
self.input_shapes = metadata['input_shapes']
|
||||
self.vision_input_names = [k for k in self.input_shapes if 'img' in k]
|
||||
self.output_slices = metadata['output_slices']
|
||||
|
||||
self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
|
||||
self.usbgpu = usbgpu
|
||||
self.chestnut = chestnut
|
||||
|
||||
self.frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ
|
||||
self.input_queues, self.npy = make_input_queues(self.input_shapes, self.frame_skip, device=self.QUEUE_DEV)
|
||||
@@ -168,7 +172,7 @@ class ModelState(ModelStateBase):
|
||||
return parsed_model_outputs
|
||||
|
||||
def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray],
|
||||
inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None:
|
||||
inputs: dict[str, np.ndarray], after_enqueue: Callable[[], None] | None = None) -> dict[str, np.ndarray]:
|
||||
for key in bufs.keys():
|
||||
ptr = np.frombuffer(bufs[key].data, dtype=np.uint8).ctypes.data
|
||||
yuv_size = self.frame_buf_params[key][3]
|
||||
@@ -192,11 +196,11 @@ class ModelState(ModelStateBase):
|
||||
outs, = self.run_policy(
|
||||
**{k: self.input_queues[k] for k in POLICY_INPUTS if k in self.input_queues}, warped=warped
|
||||
)
|
||||
if after_enqueue is not None:
|
||||
after_enqueue()
|
||||
model_output = outs.numpy()[0]
|
||||
if self.usbgpu and not np.all(np.isfinite(model_output)):
|
||||
# TODO remove with prev_feat
|
||||
cloudlog.error("model output not finite, dropping frame")
|
||||
return None
|
||||
if self.chestnut and not np.all(np.isfinite(model_output)):
|
||||
raise RuntimeError("model output not finite")
|
||||
outputs_dict = self.parser.parse_outputs(self.slice_outputs(model_output, self.output_slices))
|
||||
self.npy['prev_feat'][:] = model_output[self.output_slices['hidden_state']]
|
||||
|
||||
@@ -218,12 +222,12 @@ class ModelState(ModelStateBase):
|
||||
def main(demo=False):
|
||||
cloudlog.warning("modeld init")
|
||||
|
||||
USBGPU = usbgpu_present() and usbgpu_compiled()
|
||||
if USBGPU:
|
||||
CHESTNUT = chestnut_present() and chestnut_compiled()
|
||||
if CHESTNUT:
|
||||
os.environ['HCQDEV_WAIT_TIMEOUT_MS'] = '3000'
|
||||
params = Params()
|
||||
params.put_bool("UsbGpuLoading", USBGPU)
|
||||
params.remove("UsbGpuActive")
|
||||
params.put_bool("ChestnutLoading", CHESTNUT)
|
||||
params.remove("ChestnutActive")
|
||||
|
||||
config_realtime_process(7, 54)
|
||||
|
||||
@@ -253,7 +257,7 @@ def main(demo=False):
|
||||
st = time.monotonic()
|
||||
cloudlog.warning("loading model")
|
||||
model = None
|
||||
if USBGPU:
|
||||
if CHESTNUT:
|
||||
big_model = None
|
||||
def load_big():
|
||||
nonlocal big_model
|
||||
@@ -267,23 +271,23 @@ def main(demo=False):
|
||||
loader.start()
|
||||
loader.join(BIG_MODEL_TIMEOUT)
|
||||
model = big_model
|
||||
params.put_bool("UsbGpuActive", model is not None)
|
||||
params.put_bool("ChestnutActive", model is not None)
|
||||
|
||||
small_model = ModelState(vipc_client_main.width, vipc_client_main.height, False) if model is None or USBGPU else None
|
||||
small_model = ModelState(vipc_client_main.width, vipc_client_main.height, False) if model is None or CHESTNUT else None
|
||||
if model is None:
|
||||
model = small_model
|
||||
params.put_bool("UsbGpuLoading", False)
|
||||
params.put_bool("ChestnutLoading", False)
|
||||
assert model is not None
|
||||
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
|
||||
|
||||
# messaging
|
||||
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutState"] if USBGPU else [])
|
||||
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutState"] if CHESTNUT else [])
|
||||
pm = PubMaster(pub_socks)
|
||||
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState", "carControl", "lateralDelay"])
|
||||
|
||||
publish_state = PublishState()
|
||||
params = Params()
|
||||
chestnut_state = ChestnutState(pm, model.usbgpu) if USBGPU else None
|
||||
chestnut_state = ChestnutState(pm, model.chestnut) if CHESTNUT else None
|
||||
|
||||
# setup filter to track dropped frames
|
||||
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ)
|
||||
@@ -393,13 +397,15 @@ def main(demo=False):
|
||||
|
||||
mt1 = time.perf_counter()
|
||||
try:
|
||||
model_output = model.run(bufs, transforms, inputs)
|
||||
send_chestnut = (chestnut_state is not None and
|
||||
run_count % round(ModelConstants.MODEL_RUN_FREQ / SERVICE_LIST['chestnutState'].frequency) == 0)
|
||||
model_output = model.run(bufs, transforms, inputs, chestnut_state.send if send_chestnut else None)
|
||||
except Exception:
|
||||
if not params.get_bool("UsbGpuActive"):
|
||||
if not params.get_bool("ChestnutActive"):
|
||||
raise
|
||||
# fallback to small model
|
||||
cloudlog.exception("big model failed, fall back to small")
|
||||
params.put_bool("UsbGpuActive", False)
|
||||
params.put_bool("ChestnutActive", False)
|
||||
assert small_model is not None
|
||||
model = small_model
|
||||
if chestnut_state is not None:
|
||||
@@ -419,7 +425,7 @@ def main(demo=False):
|
||||
fill_model_msg(modelv2_send, model_output, action,
|
||||
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
||||
frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, extrinsics_calibration_seen)
|
||||
modelv2_send.modelV2.big = model.usbgpu
|
||||
modelv2_send.modelV2.big = model.chestnut
|
||||
|
||||
desire_state = modelv2_send.modelV2.meta.desireState
|
||||
l_lane_change_prob = desire_state[log.Desire.laneChangeLeft]
|
||||
@@ -441,10 +447,6 @@ def main(demo=False):
|
||||
pm.send('modelDataV2SP', mdv2sp_send)
|
||||
last_vipc_frame_id = meta_main.frame_id
|
||||
|
||||
if chestnut_state is not None and run_count % round(ModelConstants.MODEL_RUN_FREQ / SERVICE_LIST['chestnutState'].frequency) == 0:
|
||||
chestnut_state.send()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
import argparse
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"openpilot.selfdrive.modeld.modeld": {"default": {"WARP_DEV": "QCOM", "QUEUE_DEV": "QCOM"}, "usbgpu": {"WARP_DEV": "QCOM", "QUEUE_DEV": "AMD"}}, "openpilot.selfdrive.modeld.dmonitoringmodeld": {"default": {"DEV": "QCOM"}}}
|
||||
{"openpilot.selfdrive.modeld.modeld": {"default": {"WARP_DEV": "QCOM", "QUEUE_DEV": "QCOM"}, "chestnut": {"WARP_DEV": "QCOM", "QUEUE_DEV": "AMD"}}, "openpilot.selfdrive.modeld.dmonitoringmodeld": {"default": {"DEV": "QCOM"}}}
|
||||
|
||||
@@ -195,17 +195,18 @@ class SelfdriveD(CruiseHelper):
|
||||
self.events.add(EventName.joystickDebug)
|
||||
self.startup_event = None
|
||||
|
||||
loading = self.params.get_bool("UsbGpuLoading")
|
||||
loading = self.params.get_bool("ChestnutLoading")
|
||||
if self.big_model_loading and not loading:
|
||||
self.big_model_ready_t = time.monotonic()
|
||||
self.events_sp.add(custom.OnroadEventSP.EventName.bigModelReady)
|
||||
self.big_model_loading = loading
|
||||
if self.big_model_loading:
|
||||
self.events.add(EventName.bigModelLoading)
|
||||
|
||||
big_active = self.params.get("UsbGpuActive")
|
||||
usbgpu_present = self.sm['deviceState'].chestnutPresent
|
||||
big_active = self.params.get("ChestnutActive")
|
||||
chestnut_present = self.sm['deviceState'].chestnutPresent
|
||||
model_unavailable = big_active is True and self.sm.seen['modelV2'] and not self.sm.alive['modelV2']
|
||||
big_failed = big_active is False or model_unavailable or (self.big_model_active and not usbgpu_present)
|
||||
big_failed = big_active is False or model_unavailable or (self.big_model_active and not chestnut_present)
|
||||
if big_failed and not self.big_model_failed:
|
||||
self.events.add(EventName.bigModelFailed)
|
||||
self.big_model_failed = big_failed
|
||||
|
||||
@@ -168,9 +168,16 @@ class Sidebar(Widget, SidebarSP):
|
||||
# Home/Flag button
|
||||
flag_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, HOME_BTN)
|
||||
button_img = self._flag_img if ui_state.started else self._home_img
|
||||
button_pos = rl.Vector2(HOME_BTN.x, HOME_BTN.y)
|
||||
icon_opacity = 1.0
|
||||
|
||||
if gui_app.sunnypilot_ui():
|
||||
button_img, button_pos, icon_opacity = SidebarSP._get_home_icon(self, button_img)
|
||||
|
||||
tint = Colors.BUTTON_PRESSED if (ui_state.started and flag_pressed) else Colors.BUTTON_NORMAL
|
||||
rl.draw_texture_ex(button_img, rl.Vector2(HOME_BTN.x, HOME_BTN.y), 0.0, 1.0, tint)
|
||||
if icon_opacity < 1.0:
|
||||
tint = rl.Color(tint[0], tint[1], tint[2], int(255 * icon_opacity))
|
||||
rl.draw_texture_ex(button_img, button_pos, 0.0, 1.0, tint)
|
||||
|
||||
# Microphone button
|
||||
if self._recording_audio:
|
||||
|
||||
@@ -9,7 +9,7 @@ from openpilot.system.ui.widgets.layouts import HBoxLayout
|
||||
from openpilot.system.ui.widgets.icon_widget import IconWidget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel, gui_label
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.common.version import RELEASE_BRANCHES
|
||||
|
||||
HEAD_BUTTON_FONT_SIZE = 40
|
||||
@@ -139,8 +139,8 @@ class MiciHomeLayout(Widget):
|
||||
self._version_text = self._get_version_text()
|
||||
|
||||
self._experimental_icon = IconWidget("icons_mici/experimental_mode.png", (48, 48))
|
||||
self._egpu_icon = IconWidget("icons_mici/egpu_green.png", (50, 37))
|
||||
self._egpu_icon_gray = IconWidget("icons_mici/egpu_gray.png", (50, 37))
|
||||
self._chestnut_icon = IconWidget("icons_mici/chestnut_green.png", (68, 40))
|
||||
self._chestnut_failed_icon = IconWidget("icons_mici/chestnut_orange.png", (68, 40))
|
||||
self._mic_icon = IconWidget("icons_mici/microphone.png", (32, 46))
|
||||
self._body_icon = IconWidget("icons_mici/body.png", (54, 37))
|
||||
|
||||
@@ -150,8 +150,8 @@ class MiciHomeLayout(Widget):
|
||||
IconWidget("icons_mici/settings.png", (48, 48), opacity=0.9),
|
||||
NetworkIcon(),
|
||||
self._experimental_icon,
|
||||
self._egpu_icon,
|
||||
self._egpu_icon_gray,
|
||||
self._chestnut_icon,
|
||||
self._chestnut_failed_icon,
|
||||
self._body_icon,
|
||||
self._mic_icon,
|
||||
], spacing=18)
|
||||
@@ -248,8 +248,11 @@ class MiciHomeLayout(Widget):
|
||||
|
||||
# ***** Center-aligned bottom section icons *****
|
||||
self._experimental_icon.set_visible(ui_state.experimental_mode)
|
||||
self._egpu_icon.set_visible(ui_state.sm["deviceState"].chestnutPresent and ui_state.usbgpu_compiled)
|
||||
self._egpu_icon_gray.set_visible(ui_state.sm["deviceState"].chestnutPresent and not ui_state.usbgpu_compiled)
|
||||
if gui_app.sunnypilot_ui():
|
||||
self._set_chestnut_visibility()
|
||||
else:
|
||||
self._chestnut_icon.set_visible(ui_state.chestnut_state in (ChestnutState.READY, ChestnutState.LOADING, ChestnutState.ACTIVE))
|
||||
self._chestnut_failed_icon.set_visible(ui_state.chestnut_state in (ChestnutState.UNCOMPILED, ChestnutState.FAILED))
|
||||
self._mic_icon.set_visible(ui_state.recording_audio)
|
||||
self._body_icon.set_visible(bool(ui_state.is_body))
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import pyray as rl
|
||||
from dataclasses import dataclass
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.selfdrive.ui.mici.onroad.torque_bar import TorqueBar
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus, ChestnutState
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
@@ -107,8 +107,7 @@ class HudRenderer(Widget):
|
||||
self.speed: float = 0.0
|
||||
self.v_ego_cluster_seen: bool = False
|
||||
self._engaged: bool = False
|
||||
self._small_model_engaged: bool = False
|
||||
self._egpu_fade_time: float = 0
|
||||
self._chestnut_fade_time: float = 0
|
||||
|
||||
self._can_draw_top_icons = True
|
||||
self._show_wheel_critical = False
|
||||
@@ -124,17 +123,15 @@ class HudRenderer(Widget):
|
||||
self._txt_wheel: rl.Texture = gui_app.texture('icons_mici/wheel.png', 50, 50)
|
||||
self._txt_wheel_critical: rl.Texture = gui_app.texture('icons_mici/wheel_critical.png', 50, 50)
|
||||
self._txt_exclamation_point: rl.Texture = gui_app.texture('icons_mici/exclamation_point.png', 9, 44)
|
||||
self._txt_egpu: rl.Texture = gui_app.texture('icons_mici/egpu.png', 60, 44)
|
||||
self._txt_egpu_green: rl.Texture = gui_app.texture('icons_mici/egpu_green.png', 60, 44)
|
||||
self._txt_egpu_orange: rl.Texture = gui_app.texture('icons_mici/egpu_orange.png', 60, 44)
|
||||
self._txt_egpu_crossed: rl.Texture = gui_app.texture('icons_mici/egpu_crossed.png', 60, 52)
|
||||
self._egpu_icon: rl.Texture | None = None
|
||||
|
||||
self._txt_chestnut: rl.Texture = gui_app.texture('icons_mici/chestnut.png', 60, 44)
|
||||
self._txt_chestnut_green: rl.Texture = gui_app.texture('icons_mici/chestnut_green.png', 60, 44)
|
||||
self._txt_chestnut_orange: rl.Texture = gui_app.texture('icons_mici/chestnut_orange.png', 75, 44)
|
||||
self._chestnut_icon: rl.Texture | None = None
|
||||
self._wheel_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps)
|
||||
self._wheel_y_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps)
|
||||
|
||||
self._set_speed_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps)
|
||||
self._egpu_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps)
|
||||
self._chestnut_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps)
|
||||
|
||||
def set_wheel_critical_icon(self, critical: bool):
|
||||
"""Set the wheel icon to critical or normal state."""
|
||||
@@ -165,13 +162,10 @@ class HudRenderer(Widget):
|
||||
controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
|
||||
)
|
||||
engaged = sm['selfdriveState'].enabled
|
||||
if (engaged and not self._engaged and not ui_state.usbgpu_loading and ui_state.usbgpu_active is not True and
|
||||
ui_state.sm.recv_frame['modelV2'] > ui_state.started_frame):
|
||||
self._small_model_engaged = True
|
||||
if engaged != self._engaged:
|
||||
self._egpu_fade_time = rl.get_time() if engaged else 0
|
||||
if (set_speed != self.set_speed and engaged) or (engaged and not self._engaged):
|
||||
self._set_speed_changed_time = rl.get_time()
|
||||
if engaged != self._engaged:
|
||||
self._chestnut_fade_time = rl.get_time() if engaged else 0
|
||||
self._engaged = engaged
|
||||
self.set_speed = set_speed
|
||||
self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA
|
||||
@@ -191,8 +185,7 @@ class HudRenderer(Widget):
|
||||
if self.is_cruise_set:
|
||||
self._draw_set_speed(rect)
|
||||
|
||||
if ui_state.usbgpu and ui_state.usbgpu_compiled:
|
||||
self._draw_model_source(rect)
|
||||
self._draw_model_source(rect)
|
||||
|
||||
self._draw_steering_wheel(rect)
|
||||
|
||||
@@ -200,30 +193,24 @@ class HudRenderer(Widget):
|
||||
if ui_state.sm.recv_frame['selfdriveState'] < ui_state.started_frame:
|
||||
return
|
||||
|
||||
big_failed = (ui_state.usbgpu_active is False or not ui_state.sm['deviceState'].chestnutPresent or
|
||||
(ui_state.usbgpu_active is True and ui_state.sm.recv_frame['modelV2'] > ui_state.started_frame and
|
||||
not ui_state.sm.alive['modelV2']) or
|
||||
(ui_state.usbgpu_active is None and ui_state.sm.recv_frame['modelV2'] > ui_state.started_frame))
|
||||
self._small_model_engaged &= big_failed
|
||||
loading = ui_state.usbgpu_loading or (ui_state.usbgpu_active is None and not big_failed)
|
||||
loading = ui_state.chestnut_state == ChestnutState.LOADING
|
||||
if loading:
|
||||
pulse = 0.5 - 0.5 * math.cos(rl.get_time() * 6.0)
|
||||
icon = self._txt_egpu
|
||||
opacity = 0.35 + 0.65 * pulse
|
||||
elif self._small_model_engaged:
|
||||
icon = self._txt_egpu_crossed
|
||||
opacity = 0.65
|
||||
elif big_failed:
|
||||
icon = self._txt_egpu_orange
|
||||
icon = self._txt_chestnut
|
||||
opacity = 0.35 + 0.65 * (0.5 - 0.5 * math.cos(rl.get_time() * 6.0))
|
||||
elif ui_state.chestnut_state in (ChestnutState.UNCOMPILED, ChestnutState.FAILED):
|
||||
icon = self._txt_chestnut_orange
|
||||
opacity = 1.0
|
||||
elif ui_state.chestnut_state == ChestnutState.ACTIVE:
|
||||
icon = self._txt_chestnut_green
|
||||
opacity = 1.0
|
||||
else:
|
||||
icon = self._txt_egpu_green
|
||||
opacity = 1.0
|
||||
return
|
||||
|
||||
if icon is not self._egpu_icon:
|
||||
self._egpu_fade_time = rl.get_time()
|
||||
self._egpu_icon = icon
|
||||
alpha = self._egpu_alpha_filter.update(loading or 0 < rl.get_time() - self._egpu_fade_time < SET_SPEED_PERSISTENCE)
|
||||
if icon is not self._chestnut_icon:
|
||||
self._chestnut_fade_time = rl.get_time()
|
||||
self._chestnut_icon = icon
|
||||
visible = loading or rl.get_time() - self._chestnut_fade_time < SET_SPEED_PERSISTENCE
|
||||
alpha = self._chestnut_alpha_filter.update(visible)
|
||||
if alpha < 1e-2:
|
||||
return
|
||||
|
||||
|
||||
@@ -10,9 +10,10 @@ import time
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.cereal import custom
|
||||
from openpilot.sunnypilot.models.default_model import get_default_model
|
||||
from openpilot.sunnypilot.models.helpers import ACTIVE_BUNDLE_KEYS, get_selected_bundle, resolve_bundle_by_ref
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.selfdrive.ui.ui_state import device, ui_state
|
||||
from openpilot.selfdrive.ui.sunnypilot.model_info import big_model_state, bundles_for_source, carrying_model, default_model_name, queued_name
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.widgets import DialogResult, Widget
|
||||
@@ -36,7 +37,10 @@ class ModelsLayout(Widget):
|
||||
super().__init__()
|
||||
self.model_manager = None
|
||||
self.model_dialog = None
|
||||
self._selection_source = None
|
||||
self._downloading = False
|
||||
self._verifying = False
|
||||
self._last_note = None
|
||||
self.last_cache_calc_time = 0
|
||||
|
||||
self._initialize_items()
|
||||
@@ -48,17 +52,24 @@ class ModelsLayout(Widget):
|
||||
self._scroller = Scroller(self.items, line_separator=True, spacing=0)
|
||||
|
||||
def _initialize_items(self):
|
||||
self.current_model_item = ListItemSP(
|
||||
title=tr("Current Model"),
|
||||
self.small_model_item = ListItemSP(
|
||||
title=tr("Small Model"),
|
||||
description="",
|
||||
action_item=ScrollingButtonAction(tr("SELECT")),
|
||||
callback=self._handle_current_model_clicked
|
||||
callback=lambda: self._open_source_dialog("qcom")
|
||||
)
|
||||
|
||||
self.big_model_item = ListItemSP(
|
||||
title=tr("Big Model"),
|
||||
action_item=ScrollingButtonAction(tr("SELECT")),
|
||||
callback=lambda: self._open_source_dialog("chestnut")
|
||||
)
|
||||
|
||||
self.download_item = download_status_item(lambda: tr("Download") if self._downloading else tr("Model Status"))
|
||||
|
||||
self.refresh_item = button_item(tr("Refresh Model List"), tr("REFRESH"), "",
|
||||
lambda: (ui_state.params.put("ModelManager_LastSyncTime", 0),
|
||||
ui_state.params.put("ModelManager_LastSyncTime_Chestnut", 0),
|
||||
gui_app.push_widget(alert_dialog(tr("Fetching Latest Models")))))
|
||||
|
||||
self.clear_cache_item = ListItemSP(
|
||||
@@ -68,7 +79,9 @@ class ModelsLayout(Widget):
|
||||
callback=self._clear_cache
|
||||
)
|
||||
|
||||
self.cancel_download_item = button_item(tr("Cancel Download"), tr("Cancel"), "", lambda: ui_state.params.remove("ModelManager_DownloadIndex"))
|
||||
self.cancel_download_item = button_item(lambda: tr("Cancel Verification") if self._verifying else tr("Cancel Download"),
|
||||
tr("Cancel"), "",
|
||||
lambda: ui_state.params.remove("ModelManager_DownloadRef"))
|
||||
|
||||
self.lane_turn_value_control = option_item_sp(tr("Adjust Lane Turn Speed"), "LaneTurnValue", 500, 2000,
|
||||
tr("Set the maximum speed for lane turn desires. Default is 19 mph."),
|
||||
@@ -93,7 +106,7 @@ class ModelsLayout(Widget):
|
||||
1, None, True, "", style.BUTTON_ACTION_WIDTH, None, True,
|
||||
lambda v: f"{v / 100:.2f} m")
|
||||
|
||||
self.items = [self.current_model_item, self.cancel_download_item, self.download_item, self.refresh_item, self.clear_cache_item,
|
||||
self.items = [self.small_model_item, self.big_model_item, self.cancel_download_item, self.download_item, self.refresh_item, self.clear_cache_item,
|
||||
self.lane_turn_desire_toggle, self.lane_turn_value_control, self.lagd_toggle, self.delay_control, self.camera_offset]
|
||||
|
||||
def _update_lagd_description(self, lagd_toggle: bool):
|
||||
@@ -107,10 +120,6 @@ class ModelsLayout(Widget):
|
||||
desc += f"<br>{tr('Actuator Delay:')} {cp:.2f} s + {tr('Software Delay:')} {sw:.2f} s = {tr('Total Delay:')} {cp + sw:.2f} s"
|
||||
self.lagd_toggle.set_description(desc)
|
||||
|
||||
def _is_downloading(self):
|
||||
return (self.model_manager and self.model_manager.selectedBundle and
|
||||
self.model_manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.downloading)
|
||||
|
||||
@staticmethod
|
||||
def calculate_cache_size():
|
||||
cache_size = 0.0
|
||||
@@ -133,36 +142,90 @@ class ModelsLayout(Widget):
|
||||
gui_app.push_widget(dialog)
|
||||
|
||||
def _handle_bundle_download_progress(self):
|
||||
self.download_item.set_visible(False)
|
||||
self.cancel_download_item.set_visible(False)
|
||||
self._downloading = False
|
||||
|
||||
if not self.model_manager or (not self.model_manager.selectedBundle and not self.model_manager.activeBundle):
|
||||
return
|
||||
|
||||
bundle = self.model_manager.selectedBundle if self._is_downloading() or (
|
||||
self.model_manager.selectedBundle and self.model_manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.failed
|
||||
) else self.model_manager.activeBundle
|
||||
if not bundle:
|
||||
return
|
||||
|
||||
self.cancel_download_item.set_visible(bool(self.model_manager.selectedBundle) and ui_state.params.get("ModelManager_DownloadIndex") is not None)
|
||||
self._verifying = False
|
||||
self.download_item.set_visible(True)
|
||||
|
||||
if (current_time := time.monotonic()) - self.last_cache_calc_time > 0.5:
|
||||
self.last_cache_calc_time = current_time
|
||||
self.clear_cache_item.action_item.set_value(f"{self.calculate_cache_size():.2f} MB")
|
||||
|
||||
bundle = self.model_manager.selectedBundle if self.model_manager else None
|
||||
progresses = [model.artifact.downloadProgress for model in bundle.models if model.artifact.fileName] if bundle else []
|
||||
if not progresses or bundle.status not in (custom.ModelManagerSP.DownloadStatus.downloading,
|
||||
custom.ModelManagerSP.DownloadStatus.failed):
|
||||
self.download_item.action_item.update(name="", segments=self._slot_segments())
|
||||
return
|
||||
|
||||
self.cancel_download_item.set_visible(ui_state.params.get("ModelManager_DownloadRef") is not None)
|
||||
if bundle.status == custom.ModelManagerSP.DownloadStatus.downloading:
|
||||
device._reset_interactive_timeout()
|
||||
|
||||
# every bundle is a single chunked artifact now
|
||||
progresses = [model.artifact.downloadProgress for model in bundle.models if model.artifact.fileName]
|
||||
if not progresses:
|
||||
return
|
||||
|
||||
self.download_item.set_visible(True)
|
||||
self.download_item.action_item.update(**self._download_row_state(progresses, bundle.internalName))
|
||||
state = self._download_row_state(progresses, bundle.internalName)
|
||||
if queued := queued_name(bundle.ref):
|
||||
state["name"] += f" | {queued} {tr('queued')}"
|
||||
self.download_item.action_item.update(**state)
|
||||
self._downloading = self.download_item.action_item.downloading
|
||||
ds = custom.ModelManagerSP.DownloadStatus
|
||||
self._verifying = any(getattr(p.status, 'raw', p.status) == ds.verifying for p in progresses)
|
||||
|
||||
def _slot_segments(self):
|
||||
"""small and big slots side by side; green marks the slot whose pick is actually
|
||||
driving (runner-matched, so a failed Default big greens neither slot), an empty
|
||||
slot shows its default."""
|
||||
big_state = big_model_state()
|
||||
carry_source, carry_internal, _ = carrying_model()
|
||||
segments = []
|
||||
for source, label in (("qcom", tr("small")), ("chestnut", tr("big"))):
|
||||
if segments:
|
||||
segments.append(("|", rl.GRAY, None, None))
|
||||
bundle = get_selected_bundle(ui_state.params, source)
|
||||
name = bundle.internalName if bundle else default_model_name(source)
|
||||
color = ON_COLOR if (source == carry_source and name == carry_internal) else rl.LIGHTGRAY
|
||||
name = "● " + name
|
||||
if source == "chestnut":
|
||||
if big_state == 'failed':
|
||||
color = rl.RED
|
||||
elif big_state == 'loading':
|
||||
color = rl.GOLD
|
||||
segments.append((label, rl.GRAY, None, None))
|
||||
segments.append((name, color, None, None))
|
||||
return segments
|
||||
|
||||
@staticmethod
|
||||
def _set_item_note(item, text):
|
||||
# a description renders only while shown; hide before clearing or the
|
||||
# empty description keeps its visible state
|
||||
if text:
|
||||
item.set_description(text)
|
||||
item.show_description(True)
|
||||
else:
|
||||
item.show_description(False)
|
||||
item.set_description("")
|
||||
|
||||
def _status_note(self) -> str:
|
||||
"""The failover story for the Model Status row. One-way big -> small, and the
|
||||
fallback is runner-matched: a Default big can only fall back to the Default
|
||||
small (stock modeld), a custom big has no automatic fallback yet."""
|
||||
if not ui_state.chestnut_present:
|
||||
return ""
|
||||
big_bundle = get_selected_bundle(ui_state.params, "chestnut")
|
||||
big_name = big_bundle.internalName if big_bundle else default_model_name("chestnut")
|
||||
big_is_default = big_bundle is None
|
||||
fallback_name = default_model_name("qcom")
|
||||
state = big_model_state()
|
||||
if state == 'failed':
|
||||
if big_is_default:
|
||||
return tr("Big model unavailable, {} is driving until the next drive.").format(fallback_name)
|
||||
return tr("Big model unavailable until the next drive.")
|
||||
if state == 'loading':
|
||||
if big_is_default:
|
||||
return tr("{} drives until the big model is ready.").format(fallback_name)
|
||||
return tr("Getting the big model ready.")
|
||||
if big_is_default:
|
||||
return tr("{} will drive. If it fails during a drive, {} takes over until the next drive.").format(big_name, fallback_name)
|
||||
return tr("{} will drive when the chestnut is ready.").format(big_name)
|
||||
|
||||
@staticmethod
|
||||
def _download_row_state(progresses, name: str) -> dict:
|
||||
@@ -175,6 +238,8 @@ class ModelsLayout(Widget):
|
||||
if ds.failed in statuses:
|
||||
# close.png is authored black and a tint cannot lift it, hence close2
|
||||
return {"name": name, "status_text": tr("download failed"), "text_color": rl.RED, "icon": "icons/close2.png"}
|
||||
if ds.verifying in statuses:
|
||||
return {"name": name, "downloading": True, "progress": progress, "status_text": tr("verifying")}
|
||||
if ds.downloading in statuses:
|
||||
return {"name": name, "downloading": True, "progress": progress}
|
||||
if statuses <= {ds.downloaded, ds.cached}:
|
||||
@@ -184,50 +249,71 @@ class ModelsLayout(Widget):
|
||||
|
||||
def _on_model_selected(self, result):
|
||||
if result != DialogResult.CONFIRM:
|
||||
self.model_dialog = None
|
||||
return
|
||||
selected_ref = self.model_dialog.selection_ref
|
||||
if selected_ref == "Default":
|
||||
ui_state.params.remove("ModelManager_ActiveBundle")
|
||||
elif selected_bundle := next((bundle for bundle in self.model_manager.availableBundles if bundle.ref == selected_ref), None):
|
||||
ui_state.params.put("ModelManager_DownloadIndex", selected_bundle.index)
|
||||
self.model_dialog = None
|
||||
if selected_ref == "Default":
|
||||
if self._selection_source in ACTIVE_BUNDLE_KEYS:
|
||||
ui_state.params.remove(ACTIVE_BUNDLE_KEYS[self._selection_source])
|
||||
return
|
||||
if selected_bundle := self._resolve_selected_bundle(selected_ref):
|
||||
ui_state.params.put("ModelManager_DownloadRef", selected_bundle.ref)
|
||||
|
||||
def _resolve_selected_bundle(self, ref):
|
||||
source_bundles = {source: bundles_for_source(source) for source in ("qcom", "chestnut")}
|
||||
resolved = resolve_bundle_by_ref(ref, source_bundles)
|
||||
return resolved[0] if resolved else None
|
||||
|
||||
@staticmethod
|
||||
def _bundle_to_node(bundle):
|
||||
return TreeNode(bundle.ref, {'display_name': bundle.displayName, 'short_name': bundle.internalName})
|
||||
|
||||
def _get_folders(self, favorites):
|
||||
bundles = self.model_manager.availableBundles
|
||||
def _get_folders(self, favorites, bundles):
|
||||
folders = {}
|
||||
for bundle in bundles:
|
||||
folders.setdefault(next((ov_ride.value for ov_ride in bundle.overrides if ov_ride.key == "folder"), ""), []).append(bundle)
|
||||
|
||||
folders_list = [TreeFolder("", [TreeNode("Default", {'display_name': f"{get_default_model()} (Default)",
|
||||
'short_name': "Default"})])]
|
||||
folders_list = []
|
||||
for folder, folder_bundles in sorted(folders.items(), key=lambda x: max((bundle.index for bundle in x[1]), default=-1), reverse=True):
|
||||
folder_bundles.sort(key=lambda bundle: bundle.index, reverse=True)
|
||||
name = folder + (f" - (Updated: {m.group(1)})" if folder_bundles and (m := re.search(r'\(([^)]*)\)[^(]*$', folder_bundles[0].displayName)) else "")
|
||||
folders_list.append(TreeFolder(name, [self._bundle_to_node(bundle) for bundle in folder_bundles]))
|
||||
|
||||
if favorites and (fav_bundles := [bundle for bundle in bundles if bundle.ref in favorites]):
|
||||
folders_list.insert(1, TreeFolder("Favorites", [self._bundle_to_node(bundle) for bundle in fav_bundles]))
|
||||
folders_list.insert(0, TreeFolder("Favorites", [self._bundle_to_node(bundle) for bundle in fav_bundles]))
|
||||
return folders_list
|
||||
|
||||
def _handle_current_model_clicked(self):
|
||||
def _open_source_dialog(self, source):
|
||||
self._selection_source = source
|
||||
favs = ui_state.params.get("ModelManager_Favs")
|
||||
favorites = set(favs.split(';')) if favs else set()
|
||||
folders_list = self._get_folders(favorites)
|
||||
|
||||
active_ref = self.model_manager.activeBundle.ref if self.model_manager.activeBundle else "Default"
|
||||
self.model_dialog = TreeOptionDialog(tr("Select a Model"), folders_list, active_ref, "ModelManager_Favs",
|
||||
get_folders_fn=self._get_folders, on_exit=self._on_model_selected)
|
||||
folders_list = self._source_folders(favorites, source)
|
||||
if not folders_list:
|
||||
gui_app.push_widget(alert_dialog(tr("No models are available for this hardware yet. Connect to the internet and refresh the model list.")))
|
||||
return
|
||||
self.model_dialog = TreeOptionDialog(tr("Select a Model"), folders_list, self._slot_active_ref(source), "ModelManager_Favs",
|
||||
get_folders_fn=lambda favs: self._source_folders(favs, source), on_exit=self._on_model_selected)
|
||||
gui_app.push_widget(self.model_dialog)
|
||||
|
||||
def _source_folders(self, favorites, source):
|
||||
bundles = bundles_for_source(source)
|
||||
if not bundles:
|
||||
return []
|
||||
folders_list = [TreeFolder("", [TreeNode("Default", {'display_name': default_model_name(source)})])]
|
||||
folders_list.extend(self._get_folders(favorites, bundles))
|
||||
return folders_list
|
||||
|
||||
@staticmethod
|
||||
def _slot_active_ref(source: str) -> str:
|
||||
bundle = get_selected_bundle(ui_state.params, source)
|
||||
return bundle.ref if bundle else "Default"
|
||||
|
||||
def _update_state(self):
|
||||
advanced_controls: bool = ui_state.params.get_bool("ShowAdvancedControls")
|
||||
turn_desire: bool = ui_state.params.get_bool("LaneTurnDesire")
|
||||
live_delay: bool = ui_state.params.get_bool("LagdToggle")
|
||||
camera_offset: bool = ui_state.params.get("ModelManager_ActiveBundle") is not None
|
||||
camera_offset: bool = ui_state.active_bundle is not None
|
||||
|
||||
self.lane_turn_desire_toggle.action_item.set_state(turn_desire)
|
||||
self.lane_turn_value_control.set_visible(turn_desire and advanced_controls)
|
||||
@@ -241,19 +327,27 @@ class ModelsLayout(Widget):
|
||||
self._update_lagd_description(live_delay)
|
||||
self.model_manager = ui_state.sm["modelManagerSP"]
|
||||
self._handle_bundle_download_progress()
|
||||
default_label = f"{get_default_model()} (Default)"
|
||||
active_name = self.model_manager.activeBundle.displayName if self.model_manager and self.model_manager.activeBundle.ref else default_label
|
||||
self.current_model_item.action_item.set_value(active_name)
|
||||
|
||||
if not ui_state.is_offroad():
|
||||
self.current_model_item.action_item.set_enabled(False)
|
||||
self.current_model_item.set_description(tr("Only available when vehicle is off, or always offroad mode is on"))
|
||||
else:
|
||||
self.current_model_item.action_item.set_enabled(True)
|
||||
self.current_model_item.set_description("")
|
||||
carry_source, _, carry_display = carrying_model()
|
||||
for item, item_source in ((self.small_model_item, "qcom"), (self.big_model_item, "chestnut")):
|
||||
bundle = get_selected_bundle(ui_state.params, item_source)
|
||||
name = bundle.displayName if bundle else default_model_name(item_source)
|
||||
color = ON_COLOR if (item_source == carry_source and name == carry_display) else style.ITEM_TEXT_VALUE_COLOR
|
||||
item.action_item.set_value(name, color)
|
||||
|
||||
note = self._status_note()
|
||||
if note != self._last_note:
|
||||
self._last_note = note
|
||||
self._set_item_note(self.download_item, note)
|
||||
|
||||
offroad = ui_state.is_offroad()
|
||||
self.small_model_item.action_item.set_enabled(offroad)
|
||||
self.big_model_item.action_item.set_enabled(offroad)
|
||||
self.small_model_item.set_description("" if offroad else tr("Only available when vehicle is off, or always offroad mode is on"))
|
||||
|
||||
def _render(self, rect):
|
||||
self._scroller.render(rect)
|
||||
|
||||
def show_event(self):
|
||||
self._scroller.show_event()
|
||||
self._last_note = None # re-expand the failover note every time the page opens
|
||||
|
||||
@@ -8,7 +8,6 @@ import datetime
|
||||
import os
|
||||
import platform
|
||||
import requests
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from time import monotonic
|
||||
@@ -75,22 +74,12 @@ class OSMLayout(Widget):
|
||||
def _update_map_size(self):
|
||||
threading.Thread(target=self.calculate_size, daemon=True).start()
|
||||
|
||||
def _do_delete_maps(self):
|
||||
if MAP_PATH.exists():
|
||||
shutil.rmtree(MAP_PATH)
|
||||
|
||||
for param in ("OsmDownloadedDate", "OsmLocal", "OsmLocationName", "OsmLocationTitle", "OsmStateName", "OsmStateTitle"):
|
||||
ui_state.params.remove(param)
|
||||
|
||||
def _on_confirm_delete_maps(self):
|
||||
ui_state.params.put_bool("Mapd_ClearCache", True)
|
||||
self._delete_maps_btn.action_item.set_enabled(True)
|
||||
self._delete_maps_btn.action_item.set_text(tr("DELETE"))
|
||||
self._update_map_size()
|
||||
|
||||
def _on_confirm_delete_maps(self):
|
||||
self._delete_maps_btn.action_item.set_enabled(False)
|
||||
self._delete_maps_btn.action_item.set_text("DELETING...")
|
||||
threading.Thread(target=self._do_delete_maps).start()
|
||||
|
||||
def _delete_maps(self):
|
||||
self._show_confirm(tr("This will delete ALL downloaded maps\n\nAre you sure you want to delete all maps?"),
|
||||
tr("Yes, delete all maps"), self._on_confirm_delete_maps)
|
||||
|
||||
@@ -4,11 +4,14 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr_noop
|
||||
|
||||
|
||||
@@ -18,6 +21,9 @@ METRIC_MARGIN = 30
|
||||
METRIC_START_Y = 300
|
||||
HOME_BTN = rl.Rectangle(60, 860, 180, 180)
|
||||
|
||||
CHESTNUT_ICON_WIDTH = 180
|
||||
CHESTNUT_ICON_HEIGHT = 133
|
||||
|
||||
|
||||
# Color scheme
|
||||
class Colors:
|
||||
@@ -53,6 +59,9 @@ class MetricData:
|
||||
class SidebarSP:
|
||||
def __init__(self):
|
||||
self._sunnylink_status = MetricData(tr_noop("SUNNYLINK"), tr_noop("OFFLINE"), Colors.WARNING)
|
||||
self._chestnut_green_img = gui_app.texture("icons_mici/chestnut_green.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_default_img = gui_app.texture("icons_mici/chestnut.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_orange_img = gui_app.texture("icons_mici/chestnut_orange.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
|
||||
def _update_sunnylink_status(self):
|
||||
if not ui_state.params.get_bool("SunnylinkEnabled"):
|
||||
@@ -78,6 +87,24 @@ class SidebarSP:
|
||||
|
||||
self._sunnylink_status.update(tr_noop("SUNNYLINK"), status, color)
|
||||
|
||||
def _get_home_icon(self, default_img: rl.Texture) -> tuple[rl.Texture, rl.Vector2, float]:
|
||||
default_pos = rl.Vector2(HOME_BTN.x, HOME_BTN.y)
|
||||
state = ui_state.chestnut_state
|
||||
if state == ChestnutState.DISCONNECTED:
|
||||
return default_img, default_pos, 1.0
|
||||
|
||||
if state == ChestnutState.LOADING:
|
||||
icon = self._chestnut_default_img
|
||||
opacity = 0.35 + 0.65 * (0.5 - 0.5 * math.cos(rl.get_time() * 6.0))
|
||||
elif state in (ChestnutState.UNCOMPILED, ChestnutState.FAILED):
|
||||
icon, opacity = self._chestnut_orange_img, 1.0
|
||||
else:
|
||||
icon, opacity = self._chestnut_green_img, 1.0
|
||||
|
||||
x = HOME_BTN.x + (HOME_BTN.width - icon.width) / 2
|
||||
y = HOME_BTN.y + (HOME_BTN.height - icon.height) / 2
|
||||
return icon, rl.Vector2(x, y), opacity
|
||||
|
||||
def _draw_metrics_w_sunnylink(self, rect: rl.Rectangle, _temp, _panda, _connect):
|
||||
metrics = [_temp, _panda, _connect, self._sunnylink_status]
|
||||
start_y = int(rect.y) + METRIC_START_Y
|
||||
|
||||
@@ -4,8 +4,14 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import math
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.system.ui.lib.application import FontWeight
|
||||
from openpilot.system.ui.widgets.icon_widget import IconWidget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
|
||||
@@ -13,3 +19,16 @@ class MiciHomeLayoutSP(MiciHomeLayout):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._openpilot_label = UnifiedLabel("sunnypilot", font_size=88, font_weight=FontWeight.AUDIOWIDE, max_width=480, wrap_text=False)
|
||||
self._chestnut_loading_icon = IconWidget("icons_mici/chestnut.png", (68, 40))
|
||||
self._chestnut_loading_icon.set_visible(False)
|
||||
failed_idx = self._status_bar_layout.widgets.index(self._chestnut_failed_icon)
|
||||
self._status_bar_layout.widgets.insert(failed_idx + 1, self._chestnut_loading_icon)
|
||||
|
||||
def _set_chestnut_visibility(self):
|
||||
# stock has no loading tier: it shows green from the moment a big model is available. keep the
|
||||
# pulse so the status bar and the onroad HUD agree on what loading looks like.
|
||||
loading = ui_state.chestnut_state == ChestnutState.LOADING
|
||||
self._chestnut_loading_icon._opacity = 0.35 + 0.65 * (0.5 - 0.5 * math.cos(rl.get_time() * 6.0))
|
||||
self._chestnut_loading_icon.set_visible(loading)
|
||||
self._chestnut_icon.set_visible(not loading and ui_state.chestnut_state in (ChestnutState.READY, ChestnutState.ACTIVE))
|
||||
self._chestnut_failed_icon.set_visible(ui_state.chestnut_state in (ChestnutState.UNCOMPILED, ChestnutState.FAILED))
|
||||
|
||||
@@ -7,16 +7,37 @@ See the LICENSE.md file in the root directory for more details.
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.cereal import custom
|
||||
from openpilot.sunnypilot.models.default_model import get_default_model
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog
|
||||
from openpilot.sunnypilot.models.helpers import ACTIVE_BUNDLE_KEYS, get_selected_bundle
|
||||
from openpilot.selfdrive.ui.mici.widgets.button import BigButton
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.models import ModelsLayout
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, device
|
||||
from openpilot.selfdrive.ui.sunnypilot.model_info import (active_source, big_model_state, bundles_for_source, carrying_model,
|
||||
default_model_name, model_info, queued_name)
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
|
||||
def _model_info() -> tuple[str, str, str]:
|
||||
"""(active model, info header, info text) for the panel. Runner-matched: the
|
||||
active line names what actually drives, and a notable big-model state takes
|
||||
the info pair."""
|
||||
source, active_name, other_name = model_info()
|
||||
state = big_model_state()
|
||||
_, _, carry_display = carrying_model()
|
||||
if carry_display is None:
|
||||
big = get_selected_bundle(ui_state.params, "chestnut")
|
||||
carry_display = big.displayName if big else default_model_name("chestnut")
|
||||
active_text = (carry_display or active_name).lower()
|
||||
if state == 'failed':
|
||||
return active_text, tr("big model"), tr("unavailable")
|
||||
if state == 'loading':
|
||||
return active_text, tr("big model"), tr("getting ready")
|
||||
header = tr("small model") if source == "chestnut" else tr("big model")
|
||||
return active_text, header, other_name.lower()
|
||||
|
||||
|
||||
class CurrentModelInfo(Widget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
@@ -26,12 +47,12 @@ class CurrentModelInfo(Widget):
|
||||
header_color = rl.Color(255, 255, 255, int(255 * 0.9))
|
||||
subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65))
|
||||
max_width = int(self._rect.width - 20)
|
||||
active_text, info_header, info_text = _model_info()
|
||||
self.current_model_header = UnifiedLabel(tr("active model"), 48, max_width=max_width, text_color=header_color, font_weight=FontWeight.DISPLAY)
|
||||
default_text = f"{get_default_model()} (Default)".lower()
|
||||
self.current_model_text = UnifiedLabel(default_text, 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN, scroll=True)
|
||||
self.current_model_text = UnifiedLabel(active_text, 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN, scroll=True)
|
||||
|
||||
self.info_header = UnifiedLabel("cache size", 48, max_width=max_width, text_color=header_color, font_weight=FontWeight.DISPLAY)
|
||||
self.info_text = UnifiedLabel("0 mb", 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN)
|
||||
self.info_header = UnifiedLabel(info_header, 48, max_width=max_width, text_color=header_color, font_weight=FontWeight.DISPLAY)
|
||||
self.info_text = UnifiedLabel(info_text, 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN, scroll=True)
|
||||
|
||||
def _render(self, _):
|
||||
self.current_model_header.set_position(self._rect.x + 20, self._rect.y - 10)
|
||||
@@ -55,12 +76,13 @@ class ModelsLayoutMici(NavScroller):
|
||||
self._download_progress = "."
|
||||
self._download_frame = 0
|
||||
self._was_downloading = False
|
||||
self._selection_source: str | None = None
|
||||
|
||||
self.select_model_btn = BigButton(tr("select model"))
|
||||
self.select_model_btn.set_click_callback(self._show_folders)
|
||||
|
||||
self.cancel_download_btn = BigButton(tr("cancel download"))
|
||||
self.cancel_download_btn.set_click_callback(lambda: ui_state.params.remove("ModelManager_DownloadIndex"))
|
||||
self.cancel_download_btn.set_click_callback(lambda: ui_state.params.remove("ModelManager_DownloadRef"))
|
||||
|
||||
self.main_items = [self.current_model_info, self.select_model_btn, self.cancel_download_btn]
|
||||
self._scroller.add_widgets(self.main_items)
|
||||
@@ -69,8 +91,7 @@ class ModelsLayoutMici(NavScroller):
|
||||
def model_manager(self):
|
||||
return ui_state.sm["modelManagerSP"]
|
||||
|
||||
def _get_grouped_bundles(self, favorites = None):
|
||||
bundles = self.model_manager.availableBundles
|
||||
def _get_grouped_bundles(self, bundles, favorites = None):
|
||||
folders = {}
|
||||
for bundle in bundles:
|
||||
folder = next((override.value for override in bundle.overrides if override.key == "folder"), "")
|
||||
@@ -90,47 +111,70 @@ class ModelsLayoutMici(NavScroller):
|
||||
def _show_folders(self):
|
||||
self.focused_widget = self.select_model_btn
|
||||
|
||||
hardware_btns = []
|
||||
active = active_source()
|
||||
for source, label in (("qcom", tr("small models")), ("chestnut", tr("big models"))):
|
||||
bundle = get_selected_bundle(ui_state.params, source)
|
||||
value = (bundle.internalName if bundle else default_model_name(source)).lower()
|
||||
if source == active:
|
||||
value += f" ({tr('active')})"
|
||||
btn = BigButton(label.lower(), value=value)
|
||||
btn.set_click_callback(lambda s=source: self._select_hardware(s))
|
||||
hardware_btns.append(btn)
|
||||
self._push_selection_view(hardware_btns)
|
||||
|
||||
def _select_hardware(self, source):
|
||||
self._selection_source = source
|
||||
|
||||
favs = ui_state.params.get("ModelManager_Favs")
|
||||
favorites = set(favs.split(';')) if favs else set()
|
||||
|
||||
folders = self._get_grouped_bundles(favorites)
|
||||
bundles = bundles_for_source(source)
|
||||
if not bundles:
|
||||
gui_app.push_widget(BigDialog(title=tr("No models available"),
|
||||
description=tr("No models are available for this hardware yet. Connect to the internet and refresh the model list.")))
|
||||
return
|
||||
folders = self._get_grouped_bundles(bundles, favorites)
|
||||
|
||||
folder_buttons = []
|
||||
default_btn = BigButton(f"{get_default_model()} (Default)".lower())
|
||||
default_btn.set_click_callback(self._select_default)
|
||||
default_btn = BigButton(default_model_name(source).lower())
|
||||
default_btn.set_click_callback(lambda s=source: self._select_default(s))
|
||||
folder_buttons.append(default_btn)
|
||||
|
||||
for folder in sorted(folders.keys(), key=lambda f: max((bundle.index for bundle in folders[f]), default=-1), reverse=True):
|
||||
if folder.lower() in ["release models", "master models", "favorites"]:
|
||||
btn = BigButton(folder.lower())
|
||||
btn.set_click_callback(lambda f=folder: self._select_folder(f))
|
||||
if folder.lower() == "favorites":
|
||||
folder_buttons.insert(0, btn)
|
||||
else:
|
||||
folder_buttons.append(btn)
|
||||
btn = BigButton(folder.lower())
|
||||
btn.set_click_callback(lambda f=folder: self._select_folder(f))
|
||||
if folder.lower() == "favorites":
|
||||
folder_buttons.insert(0, btn)
|
||||
else:
|
||||
folder_buttons.append(btn)
|
||||
self._push_selection_view(folder_buttons)
|
||||
|
||||
def _pop_to_main(self):
|
||||
gui_app.pop_widgets_to(self)
|
||||
self._scroller.scroll_panel.set_offset(0.0)
|
||||
|
||||
def _select_model(self, bundle):
|
||||
ui_state.params.put("ModelManager_DownloadIndex", bundle.index)
|
||||
ui_state.params.put("ModelManager_DownloadRef", bundle.ref)
|
||||
self._pop_to_main()
|
||||
|
||||
def _select_default(self):
|
||||
ui_state.params.remove("ModelManager_ActiveBundle")
|
||||
def _select_default(self, source):
|
||||
ui_state.params.remove(ACTIVE_BUNDLE_KEYS[source])
|
||||
self._pop_to_main()
|
||||
|
||||
def _select_folder(self, folder_name):
|
||||
source = self._selection_source
|
||||
if source is None: # folders are only reachable after picking a hardware
|
||||
return
|
||||
favs = ui_state.params.get("ModelManager_Favs")
|
||||
favorites = set(favs.split(';')) if favs else set()
|
||||
|
||||
folders = self._get_grouped_bundles(favorites)
|
||||
folders = self._get_grouped_bundles(bundles_for_source(source), favorites)
|
||||
bundles = sorted(folders.get(folder_name, []), key=lambda b: b.index, reverse=True)
|
||||
|
||||
btns = []
|
||||
for bundle in bundles:
|
||||
txt = bundle.displayName.lower()
|
||||
btn = BigButton(txt)
|
||||
btn = BigButton(bundle.displayName.lower())
|
||||
btn.set_click_callback(lambda b=bundle: self._select_model(b))
|
||||
btns.append(btn)
|
||||
self._push_selection_view(btns)
|
||||
@@ -162,11 +206,10 @@ class ModelsLayoutMici(NavScroller):
|
||||
self._was_downloading = is_downloading
|
||||
|
||||
self.current_model_info.current_model_header.set_text(tr("active model"))
|
||||
default_model_text = f"{get_default_model()} (Default)".lower()
|
||||
model_text = manager.activeBundle.displayName.lower() if manager.activeBundle.ref else default_model_text
|
||||
self.current_model_info.current_model_text.set_text(model_text)
|
||||
self.current_model_info.info_header.set_text(tr("cache size"))
|
||||
self.current_model_info.info_text.set_text(f"{ModelsLayout.calculate_cache_size():.2f} MB")
|
||||
active_text, info_header, info_text = _model_info()
|
||||
self.current_model_info.current_model_text.set_text(active_text)
|
||||
self.current_model_info.info_header.set_text(info_header)
|
||||
self.current_model_info.info_text.set_text(info_text)
|
||||
|
||||
if manager.selectedBundle and manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.failed:
|
||||
self.current_model_info.info_header.set_text(tr("error") + self._download_progress)
|
||||
@@ -177,18 +220,29 @@ class ModelsLayoutMici(NavScroller):
|
||||
device.set_override_interactive_timeout(5)
|
||||
progress = 0.0
|
||||
count = 0
|
||||
verifying = False
|
||||
for model in manager.selectedBundle.models:
|
||||
count += 1
|
||||
p = model.artifact.downloadProgress
|
||||
if p.status == custom.ModelManagerSP.DownloadStatus.downloading:
|
||||
if p.status in (custom.ModelManagerSP.DownloadStatus.downloading,
|
||||
custom.ModelManagerSP.DownloadStatus.verifying):
|
||||
progress += p.progress
|
||||
verifying = verifying or p.status == custom.ModelManagerSP.DownloadStatus.verifying
|
||||
elif p.status in (custom.ModelManagerSP.DownloadStatus.downloaded,
|
||||
custom.ModelManagerSP.DownloadStatus.cached):
|
||||
progress += 100.0
|
||||
|
||||
self.current_model_info.current_model_header.set_text(tr("downloading"))
|
||||
self.current_model_info.current_model_header.set_text(tr("verifying") if verifying else tr("downloading"))
|
||||
self.cancel_download_btn.set_text(tr("cancel verification") if verifying else tr("cancel download"))
|
||||
self.current_model_info.current_model_header._shimmer = True
|
||||
self.current_model_info.current_model_text.set_text(f"{manager.selectedBundle.internalName.lower()}")
|
||||
name_text = manager.selectedBundle.internalName.lower()
|
||||
if queued := queued_name(manager.selectedBundle.ref):
|
||||
name_text += f" | {queued.lower()} {tr('queued')}"
|
||||
self.current_model_info.current_model_text.set_text(name_text)
|
||||
self.current_model_info.info_header.set_text(tr("progress") + self._download_progress)
|
||||
self.current_model_info.info_header._shimmer = True
|
||||
self.current_model_info.info_text.set_text(f"{progress/count:.2f}%")
|
||||
|
||||
elif manager.selectedBundle and manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.downloaded:
|
||||
self.current_model_info.info_header.set_text(tr("downloaded"))
|
||||
self.current_model_info.info_text.set_text(tr("downloaded"))
|
||||
|
||||
@@ -12,13 +12,23 @@ from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, Bi
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
|
||||
ICON_SIZE = 70
|
||||
BIG_ICON_SIZE = 110
|
||||
|
||||
|
||||
class SunnylinkBigButton(SettingsBigButton):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._label.set_font_weight(FontWeight.AUDIOWIDE)
|
||||
|
||||
def _get_label_font_size(self):
|
||||
# Audiowide runs wider than Inter: "sunnylink" wraps to two lines at 64
|
||||
return 56
|
||||
|
||||
|
||||
class SettingsLayoutSP(OP.SettingsLayout):
|
||||
def __init__(self):
|
||||
OP.SettingsLayout.__init__(self)
|
||||
@@ -33,7 +43,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
self.icon_offroad_slider = gui_app.texture("icons_mici/settings/device/lkas.png", BIG_ICON_SIZE, BIG_ICON_SIZE)
|
||||
|
||||
sunnylink_panel = SunnylinkLayoutMici()
|
||||
sunnylink_btn = SettingsBigButton(tr("sunnylink"), "", gui_app.texture("icons_mici/settings/developer/ssh.png", 55, 55))
|
||||
sunnylink_btn = SunnylinkBigButton(tr("sunnylink"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/icons_mici/sunnylink.png", 76, 44))
|
||||
sunnylink_btn.set_click_callback(lambda: gui_app.push_widget(sunnylink_panel))
|
||||
|
||||
models_panel = ModelsLayoutMici()
|
||||
@@ -56,8 +66,8 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
|
||||
items = self._scroller._items.copy()
|
||||
|
||||
items.insert(1, sunnylink_btn)
|
||||
items.insert(2, models_btn)
|
||||
items.insert(1, models_btn)
|
||||
items.insert(5, sunnylink_btn)
|
||||
|
||||
# front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad
|
||||
items.insert(0, self._enable_offroad_btn_onroad)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.models.fetcher import get_cached_bundles
|
||||
from openpilot.sunnypilot.models.helpers import get_active_source, get_selected_bundle, resolve_bundle_by_ref
|
||||
from openpilot.sunnypilot.models.model_name import DEFAULT_BIG_MODEL, DEFAULT_MODEL
|
||||
|
||||
|
||||
def active_source() -> str:
|
||||
return get_active_source(chestnut=ui_state.chestnut_present,
|
||||
chestnut_active=ui_state.chestnut_active, chestnut_loading=ui_state.chestnut_loading,
|
||||
offroad=ui_state.is_offroad())
|
||||
|
||||
|
||||
def bundles_for_source(source: str):
|
||||
if source == active_source():
|
||||
return ui_state.sm["modelManagerSP"].availableBundles
|
||||
return get_cached_bundles(ui_state.params, source)
|
||||
|
||||
|
||||
def default_model(source: str) -> str:
|
||||
return DEFAULT_BIG_MODEL if source == 'chestnut' else DEFAULT_MODEL
|
||||
|
||||
|
||||
def default_model_name(source: str) -> str:
|
||||
return f"{default_model(source)} (Default)"
|
||||
|
||||
|
||||
def big_model_state() -> str | None:
|
||||
"""'failed' | 'loading' | None, from the same state the icons render."""
|
||||
return {ChestnutState.UNCOMPILED: 'failed',
|
||||
ChestnutState.FAILED: 'failed',
|
||||
ChestnutState.LOADING: 'loading'}.get(ui_state.chestnut_state)
|
||||
|
||||
|
||||
def carrying_model() -> tuple[str | None, str | None, str | None]:
|
||||
"""(source, internal name, display name) of what actually drives. Runner-matched:
|
||||
when a Default big cannot carry, stock modeld runs the Default small, never the
|
||||
small slot's pick; a custom big has no automatic fallback yet -> (None, None, None)."""
|
||||
source = active_source()
|
||||
if source == "chestnut":
|
||||
bundle = get_selected_bundle(ui_state.params, "chestnut")
|
||||
if bundle:
|
||||
return "chestnut", bundle.internalName, bundle.displayName
|
||||
name = default_model_name("chestnut")
|
||||
return "chestnut", name, name
|
||||
if ui_state.chestnut_present:
|
||||
if get_selected_bundle(ui_state.params, "chestnut") is None:
|
||||
name = default_model_name("qcom")
|
||||
return "qcom", name, name
|
||||
return None, None, None
|
||||
bundle = get_selected_bundle(ui_state.params, "qcom")
|
||||
if bundle:
|
||||
return "qcom", bundle.internalName, bundle.displayName
|
||||
name = default_model_name("qcom")
|
||||
return "qcom", name, name
|
||||
|
||||
|
||||
def queued_name(current_ref) -> str | None:
|
||||
ref = ui_state.params.get("ModelManager_DownloadRef")
|
||||
if ref and ref != current_ref:
|
||||
source_bundles = {source: bundles_for_source(source) for source in ("qcom", "chestnut")}
|
||||
if resolved := resolve_bundle_by_ref(ref, source_bundles):
|
||||
return resolved[0].internalName
|
||||
return None
|
||||
|
||||
|
||||
def model_info() -> tuple[str, str, str]:
|
||||
"""returns (active source, active model name, other model name)
|
||||
|
||||
Names come from the params slots, never modelManagerSP.activeBundle — the
|
||||
manager republishes a tick after a chestnut change, so the stale bundle
|
||||
would flash the wrong model."""
|
||||
source = active_source()
|
||||
other = "qcom" if source == "chestnut" else "chestnut"
|
||||
active_bundle = get_selected_bundle(ui_state.params, source)
|
||||
other_bundle = get_selected_bundle(ui_state.params, other)
|
||||
|
||||
active_name = active_bundle.displayName if active_bundle else default_model_name(source)
|
||||
other_name = other_bundle.displayName if other_bundle else default_model_name(other)
|
||||
return source, active_name, other_name
|
||||
@@ -10,6 +10,7 @@ from openpilot.cereal import messaging, log, custom
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.display import OnroadBrightness
|
||||
from openpilot.sunnypilot.models.helpers import ACTIVE_BUNDLE_KEYS, get_active_source
|
||||
from openpilot.sunnypilot.sunnylink.sunnylink_state import SunnylinkState
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.sunnypilot.widgets.screen_saver import ScreenSaverSP
|
||||
@@ -43,6 +44,7 @@ class UIStateSP:
|
||||
self.screensaver_enabled: bool = False
|
||||
|
||||
self.active_bundle = None
|
||||
self.model_runner_tinygrad: bool = False
|
||||
self.blindspot: bool = False
|
||||
self.chevron_metrics = None
|
||||
self.custom_interactive_timeout: int = 0
|
||||
@@ -150,7 +152,13 @@ class UIStateSP:
|
||||
self.has_icbm = self.CP_SP.intelligentCruiseButtonManagementAvailable and self.params.get_bool("IntelligentCruiseButtonManagement")
|
||||
|
||||
self._enforce_constraints()
|
||||
self.active_bundle = self.params.get("ModelManager_ActiveBundle")
|
||||
source = get_active_source(chestnut=self.chestnut_present, chestnut_active=self.chestnut_active,
|
||||
chestnut_loading=self.chestnut_loading, offroad=self.is_offroad())
|
||||
self.active_bundle = self.params.get(ACTIVE_BUNDLE_KEYS[source])
|
||||
self.model_runner_tinygrad = self.active_bundle is not None and self.active_bundle.get("runner") == "tinygrad"
|
||||
# stock only counts the default big model's compiled pkl. a downloaded big bundle runs on the
|
||||
# chestnut just the same, so ChestnutState has to see it as available too.
|
||||
self.chestnut_compiled = self.chestnut_compiled or self.model_runner_tinygrad
|
||||
self.blindspot = self.params.get_bool("BlindSpot")
|
||||
self.chevron_metrics = self.params.get("ChevronInfo")
|
||||
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
|
||||
|
||||
@@ -12,7 +12,7 @@ from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.ui.lib.prime_state import PrimeState
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.common.hardware import HARDWARE, PC
|
||||
from openpilot.selfdrive.modeld.helpers import usbgpu_compiled
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_compiled
|
||||
|
||||
from openpilot.selfdrive.ui.sunnypilot.ui_state import UIStateSP, DeviceSP
|
||||
|
||||
@@ -28,6 +28,15 @@ class UIStatus(Enum):
|
||||
LONG_ONLY = "long_only"
|
||||
|
||||
|
||||
class ChestnutState(Enum):
|
||||
DISCONNECTED = "disconnected"
|
||||
UNCOMPILED = "uncompiled"
|
||||
READY = "ready"
|
||||
LOADING = "loading"
|
||||
ACTIVE = "active"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class UIState(UIStateSP):
|
||||
_instance: 'UIState | None' = None
|
||||
|
||||
@@ -82,10 +91,11 @@ class UIState(UIStateSP):
|
||||
self.always_on_dm: bool = self.params.get_bool("AlwaysOnDM")
|
||||
self.experimental_mode: bool = self.params.get_bool("ExperimentalMode")
|
||||
self.experimental_mode_confirmed: bool = self.params.get_bool("ExperimentalModeConfirmed")
|
||||
self.usbgpu: bool = False
|
||||
self.usbgpu_compiled: bool = usbgpu_compiled()
|
||||
self.usbgpu_active: bool | None = self.params.get("UsbGpuActive")
|
||||
self.usbgpu_loading: bool = self.params.get_bool("UsbGpuLoading")
|
||||
self.chestnut_present: bool = False
|
||||
self.chestnut_compiled: bool = chestnut_compiled()
|
||||
self.chestnut_active: bool | None = None
|
||||
self.chestnut_loading: bool = False
|
||||
self.chestnut_state = ChestnutState.DISCONNECTED
|
||||
self.started: bool = False
|
||||
self.ignition: bool = False
|
||||
self.recording_audio: bool = False
|
||||
@@ -131,6 +141,7 @@ class UIState(UIStateSP):
|
||||
self.sm.update(0)
|
||||
self._update_state()
|
||||
self._update_status()
|
||||
self._update_chestnut_state()
|
||||
device.update()
|
||||
UIStateSP.update(self)
|
||||
|
||||
@@ -194,12 +205,35 @@ class UIState(UIStateSP):
|
||||
self.status = UIStatus.DISENGAGED
|
||||
self.started_frame = self.sm.frame
|
||||
self.started_time = time.monotonic()
|
||||
self.chestnut_present = self.sm["deviceState"].chestnutPresent
|
||||
|
||||
for callback in self._offroad_transition_callbacks:
|
||||
callback()
|
||||
|
||||
self._started_prev = self.started
|
||||
|
||||
def _update_chestnut_state(self) -> None:
|
||||
detected = self.sm["deviceState"].chestnutPresent
|
||||
if not self.started:
|
||||
self.chestnut_present = detected
|
||||
self.chestnut_state = (ChestnutState.READY if detected and self.chestnut_compiled else
|
||||
ChestnutState.UNCOMPILED if detected else ChestnutState.DISCONNECTED)
|
||||
return
|
||||
|
||||
model_seen = self.sm.recv_frame["modelV2"] > self.started_frame
|
||||
if not self.chestnut_present:
|
||||
self.chestnut_state = ChestnutState.DISCONNECTED
|
||||
elif not self.chestnut_compiled:
|
||||
self.chestnut_state = ChestnutState.UNCOMPILED
|
||||
elif self.chestnut_state == ChestnutState.FAILED or not detected or (model_seen and (not self.sm.alive["modelV2"] or not self.sm["modelV2"].big)):
|
||||
self.chestnut_state = ChestnutState.FAILED
|
||||
elif self.chestnut_loading or not model_seen:
|
||||
self.chestnut_state = ChestnutState.LOADING
|
||||
elif self.chestnut_active is False:
|
||||
self.chestnut_state = ChestnutState.FAILED
|
||||
else:
|
||||
self.chestnut_state = ChestnutState.ACTIVE
|
||||
|
||||
def update_params(self) -> None:
|
||||
# For slower operations
|
||||
# Update longitudinal control state
|
||||
@@ -216,12 +250,10 @@ class UIState(UIStateSP):
|
||||
self.always_on_dm = self.params.get_bool("AlwaysOnDM")
|
||||
self.experimental_mode = self.params.get_bool("ExperimentalMode")
|
||||
self.experimental_mode_confirmed = self.params.get_bool("ExperimentalModeConfirmed")
|
||||
# keep usbgpu UI active until offroad transition when gpu disappears
|
||||
self.usbgpu = self.sm["deviceState"].chestnutPresent or (self.usbgpu and self.started)
|
||||
if not self.usbgpu_compiled:
|
||||
self.usbgpu_compiled = usbgpu_compiled()
|
||||
self.usbgpu_active = self.params.get("UsbGpuActive")
|
||||
self.usbgpu_loading = self.params.get_bool("UsbGpuLoading")
|
||||
if not self.chestnut_compiled:
|
||||
self.chestnut_compiled = chestnut_compiled()
|
||||
self.chestnut_active = self.params.get("ChestnutActive")
|
||||
self.chestnut_loading = self.params.get_bool("ChestnutLoading")
|
||||
|
||||
UIStateSP.update_params(self)
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
#define SUNNYPILOT_VERSION "2026.08.25-4794"
|
||||
#define SUNNYPILOT_VERSION "2026.08.30-4818"
|
||||
|
||||
@@ -55,6 +55,19 @@ def cleanup_old_osm_data(files_to_remove: list[str]) -> None:
|
||||
shutil.rmtree(file, ignore_errors=False)
|
||||
|
||||
|
||||
def clear_downloaded_maps() -> None:
|
||||
"""Deletes downloaded OSM map data and resets params."""
|
||||
path = f"{Paths.mapd_root()}/offline"
|
||||
if os.path.exists(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
for param in ("OsmDownloadedDate", "OsmLocal", "OsmLocationName", "OsmLocationTitle",
|
||||
"OsmStateName", "OsmStateTitle"):
|
||||
params.remove(param)
|
||||
|
||||
cloudlog.info("mapd: downloaded maps cleared")
|
||||
|
||||
|
||||
def request_refresh_osm_location_data(nations: list[str], states: list[str] | None = None) -> None:
|
||||
params.put("OsmDownloadedDate", str(datetime.now().timestamp()), block=True)
|
||||
params.put_bool("OsmDbUpdatesCheck", False, block=True)
|
||||
@@ -131,6 +144,10 @@ def main_thread():
|
||||
show_alert = bool(get_files_for_cleanup() and params.get_bool("OsmLocal"))
|
||||
set_offroad_alert("Offroad_OSMUpdateRequired", show_alert, "This alert will be cleared when new maps are downloaded.")
|
||||
|
||||
if params.get("Mapd_ClearCache"):
|
||||
clear_downloaded_maps()
|
||||
params.remove("Mapd_ClearCache")
|
||||
|
||||
update_osm_db()
|
||||
live_map_sp.tick()
|
||||
rk.keep_time()
|
||||
|
||||
@@ -298,7 +298,7 @@ def _load_policy_runners(args: argparse.Namespace) -> tuple[list, list]:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if 'USB' in os.getenv('DEV', '') or os.getenv('USBGPU'):
|
||||
if 'USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT'):
|
||||
from openpilot.system.hardware.chestnut.flash import link_up
|
||||
for _ in range(10):
|
||||
if link_up():
|
||||
|
||||
@@ -8,22 +8,22 @@ See the LICENSE.md file in the root directory for more details.
|
||||
|
||||
import os
|
||||
os.environ['GMMU'] = '0'
|
||||
from openpilot.common.hardware import COMMA_HARDWARE
|
||||
from openpilot.selfdrive.modeld.helpers import usbgpu_present, load_oob
|
||||
import time
|
||||
import numpy as np
|
||||
import threading
|
||||
import time
|
||||
from setproctitle import setproctitle
|
||||
from tinygrad.tensor import Tensor
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
from openpilot.common.hardware import COMMA_HARDWARE
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present, load_oob
|
||||
from openpilot.cereal import log
|
||||
from opendbc.car.structs import car
|
||||
from openpilot.cereal.services import SERVICE_LIST
|
||||
from setproctitle import setproctitle
|
||||
from openpilot.cereal.messaging import PubMaster, SubMaster
|
||||
from openpilot.cereal.visionipc import VisionStreamType
|
||||
from msgq.visionipc import VisionIpcClient, VisionBuf
|
||||
from opendbc.car.car_helpers import get_demo_car_params
|
||||
|
||||
from tinygrad.tensor import Tensor
|
||||
|
||||
from openpilot.common.file_chunker import open_file_chunked
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.common.params import Params
|
||||
@@ -42,13 +42,13 @@ from openpilot.sunnypilot.modeld_v2.constants import Plan
|
||||
from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants
|
||||
from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper
|
||||
from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip, make_split_input_queues, make_supercombo_input_queues, WARP_INPUTS, POLICY_INPUTS
|
||||
|
||||
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
|
||||
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
|
||||
from openpilot.sunnypilot.models.helpers import get_active_bundle
|
||||
from openpilot.sunnypilot.selfdrive.controls.lib.relc import RoadEdgeLaneChangeController
|
||||
|
||||
PROCESS_NAME = "openpilot.selfdrive.modeld.modeld_tinygrad"
|
||||
BIG_MODEL_TIMEOUT = 60
|
||||
|
||||
|
||||
def _pkl_exists(path):
|
||||
@@ -68,6 +68,7 @@ def _find_driving_pkl(bundle):
|
||||
pkl_path = os.path.join(model_root, pkl_name)
|
||||
if _pkl_exists(pkl_path):
|
||||
return pkl_path
|
||||
return None
|
||||
|
||||
|
||||
class FrameMeta:
|
||||
@@ -84,14 +85,14 @@ class ModelState(ModelStateBase):
|
||||
inputs: dict[str, np.ndarray]
|
||||
prev_desire: np.ndarray
|
||||
|
||||
def __init__(self, cam_w: int, cam_h: int, usbgpu: bool = False):
|
||||
def __init__(self, cam_w: int, cam_h: int, chestnut: bool = False):
|
||||
ModelStateBase.__init__(self)
|
||||
|
||||
env_pkl = os.environ.get('COMBINED_MODEL_PKL')
|
||||
if env_pkl and os.path.exists(env_pkl):
|
||||
model_bundle = None
|
||||
else:
|
||||
model_bundle = get_active_bundle()
|
||||
model_bundle = get_active_bundle(chestnut=chestnut)
|
||||
self.generation = model_bundle.generation if model_bundle is not None else None
|
||||
overrides = {override.key: override.value for override in model_bundle.overrides} if model_bundle else {}
|
||||
|
||||
@@ -99,10 +100,10 @@ class ModelState(ModelStateBase):
|
||||
self.LONG_SMOOTH_SECONDS = float(overrides.get('long', ".0"))
|
||||
self.MIN_LAT_CONTROL_SPEED = 0.3
|
||||
self.PLANPLUS_CONTROL: float = 1.0
|
||||
self.usbgpu = usbgpu
|
||||
self.chestnut = chestnut
|
||||
|
||||
pkl_path = _find_driving_pkl(model_bundle)
|
||||
assert pkl_path is not None, "No driving pkl found — all models must be compiled with compile_modeld.py"
|
||||
assert pkl_path is not None, f"No driving pkl found for {'chestnut' if chestnut else 'small model'} — all models must be compiled with compile_modeld.py"
|
||||
self._init_combined(pkl_path, cam_w, cam_h, model_bundle)
|
||||
|
||||
def _init_combined(self, pkl_path, cam_w, cam_h, bundle):
|
||||
@@ -110,7 +111,7 @@ class ModelState(ModelStateBase):
|
||||
jits = load_oob(open_file_chunked(pkl_path))
|
||||
|
||||
self.WARP_DEV = 'QCOM' if COMMA_HARDWARE else 'CPU'
|
||||
self.DEV = 'AMD' if self.usbgpu else self.WARP_DEV
|
||||
self.DEV = 'AMD' if self.chestnut else self.WARP_DEV
|
||||
self.QUEUE_DEV = self.DEV
|
||||
metadata = jits['metadata']
|
||||
|
||||
@@ -185,9 +186,6 @@ class ModelState(ModelStateBase):
|
||||
else:
|
||||
self.warp(**{k: self.input_queues[k] for k in WARP_INPUTS}, frame=frame_tensor, big_frame=big_frame_tensor)
|
||||
|
||||
if self.usbgpu:
|
||||
self.warmup()
|
||||
|
||||
def warmup(self) -> None:
|
||||
dummy_frames = {k: np.zeros(self.frame_buf_params[k][3], dtype=np.uint8) for k in self._vision_input_names}
|
||||
transforms = {k: np.eye(3, dtype=np.float32) for k in [self._road_key, self._wide_key] if k}
|
||||
@@ -287,9 +285,8 @@ class ModelState(ModelStateBase):
|
||||
buf[0, :-1] = buf[0, 1:]
|
||||
buf[0, -1, :] = outputs['desired_curvature'][0, :] if not self.mlsim else 0
|
||||
|
||||
if self.usbgpu and not np.all(np.isfinite(outputs.get('plan', np.array([0.])))):
|
||||
cloudlog.error("model output not finite, dropping frame")
|
||||
return None
|
||||
if self.chestnut and not np.all(np.isfinite(outputs.get('plan', np.array([0.])))):
|
||||
raise RuntimeError("model output not finite")
|
||||
|
||||
return outputs
|
||||
|
||||
@@ -327,13 +324,13 @@ def main(demo=False):
|
||||
setproctitle(PROCESS_NAME)
|
||||
config_realtime_process(7, 54)
|
||||
|
||||
USBGPU = usbgpu_present()
|
||||
if USBGPU:
|
||||
CHESTNUT = chestnut_present()
|
||||
if CHESTNUT:
|
||||
os.environ['HCQDEV_WAIT_TIMEOUT_MS'] = '3000'
|
||||
|
||||
params = Params()
|
||||
params.put_bool("UsbGpuLoading", USBGPU)
|
||||
params.remove("UsbGpuActive")
|
||||
params.put_bool("ChestnutLoading", CHESTNUT)
|
||||
params.remove("ChestnutActive")
|
||||
|
||||
# visionipc clients
|
||||
while True:
|
||||
@@ -362,31 +359,36 @@ def main(demo=False):
|
||||
st = time.monotonic()
|
||||
|
||||
model = None
|
||||
if USBGPU:
|
||||
import threading
|
||||
def load():
|
||||
nonlocal model
|
||||
model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, usbgpu=True)
|
||||
t = threading.Thread(target=load, daemon=True)
|
||||
t.start()
|
||||
t.join(60)
|
||||
if model is None:
|
||||
params.put_bool("UsbGpuActive", False)
|
||||
raise RuntimeError("eGPU model load failed or timed out (60s)")
|
||||
params.put_bool("UsbGpuActive", True)
|
||||
else:
|
||||
model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, usbgpu=False)
|
||||
if CHESTNUT:
|
||||
big_model = None
|
||||
def load_big():
|
||||
nonlocal big_model
|
||||
try:
|
||||
m = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=True)
|
||||
m.warmup()
|
||||
big_model = m
|
||||
except Exception:
|
||||
cloudlog.exception("chestnut load failed")
|
||||
loader = threading.Thread(target=load_big, daemon=True)
|
||||
loader.start()
|
||||
loader.join(BIG_MODEL_TIMEOUT)
|
||||
model = big_model
|
||||
params.put_bool("ChestnutActive", model is not None)
|
||||
|
||||
params.put_bool("UsbGpuLoading", False)
|
||||
small_model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height, chestnut=False) if model is None or CHESTNUT else None
|
||||
if model is None:
|
||||
model = small_model
|
||||
params.put_bool("ChestnutLoading", False)
|
||||
assert model is not None
|
||||
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
|
||||
|
||||
# messaging
|
||||
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutState"] if USBGPU else [])
|
||||
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutState"] if CHESTNUT else [])
|
||||
pm = PubMaster(pub_socks)
|
||||
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState", "carControl", "lateralDelay"])
|
||||
|
||||
publish_state = PublishState()
|
||||
chestnut_state = ChestnutState(pm, USBGPU) if USBGPU else None
|
||||
chestnut_state = ChestnutState(pm, model.chestnut) if CHESTNUT else None
|
||||
|
||||
# setup filter to track dropped frames
|
||||
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / model.constants.MODEL_FREQ)
|
||||
@@ -509,7 +511,19 @@ def main(demo=False):
|
||||
inputs['action_t'] = np.array([lat_action_t, long_action_t], dtype=np.float32)
|
||||
|
||||
mt1 = time.perf_counter()
|
||||
model_output = model.run(bufs, transforms, inputs, prepare_only)
|
||||
try:
|
||||
model_output = model.run(bufs, transforms, inputs, prepare_only)
|
||||
except Exception:
|
||||
if not params.get_bool("ChestnutActive"):
|
||||
raise
|
||||
cloudlog.exception("chestnut failed, falling back to small")
|
||||
params.put_bool("ChestnutActive", False)
|
||||
assert small_model is not None
|
||||
model = small_model
|
||||
if chestnut_state is not None:
|
||||
chestnut_state.big = False
|
||||
run_count = 0
|
||||
model_output = None
|
||||
mt2 = time.perf_counter()
|
||||
model_execution_time = mt2 - mt1
|
||||
|
||||
@@ -524,7 +538,7 @@ def main(demo=False):
|
||||
fill_model_msg(drivingdata_send, modelv2_send, model_output, action,
|
||||
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
||||
frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen, meta_constants)
|
||||
modelv2_send.modelV2.big = model.usbgpu
|
||||
modelv2_send.modelV2.big = model.chestnut
|
||||
|
||||
desire_state = modelv2_send.modelV2.meta.desireState
|
||||
l_lane_change_prob = desire_state[log.Desire.laneChangeLeft]
|
||||
|
||||
@@ -37,7 +37,7 @@ class DummyModel:
|
||||
|
||||
|
||||
class DummyBundle:
|
||||
def __init__(self, is_20hz=False, models=None, generation=10):
|
||||
def __init__(self, is_20hz=False, models=None, generation=10, is_big=False):
|
||||
self.overrides = [DummyOverride('lat', '.1'), DummyOverride('long', '.3')]
|
||||
self.generation = generation
|
||||
self.is20hz = is_20hz
|
||||
@@ -190,8 +190,8 @@ def tmp_path():
|
||||
|
||||
def patch_modeld(monkeypatch):
|
||||
def _patch(bundle):
|
||||
monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None: bundle)
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None: bundle)
|
||||
monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None, *, chestnut=None: bundle)
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: bundle)
|
||||
|
||||
return _patch
|
||||
|
||||
|
||||
@@ -59,8 +59,8 @@ class TestFindDrivingPkl(OpenpilotTestCase):
|
||||
class TestModelStateCombinedInit(OpenpilotTestCase):
|
||||
def test_asserts_when_no_pkl(self, monkeypatch):
|
||||
bundle = DummyBundle(models=[], is_20hz=True)
|
||||
monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None: bundle)
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None: bundle)
|
||||
monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None, *, chestnut=None: bundle)
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: bundle)
|
||||
with self.assertRaisesRegex(AssertionError, "No driving pkl found"):
|
||||
ModelState(cam_w=CAM_W, cam_h=CAM_H)
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import io
|
||||
import requests
|
||||
from unittest import mock
|
||||
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
from openpilot.common.hardware import hw
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.selfdrive.modeld.helpers import dump_oob
|
||||
import openpilot.sunnypilot.modeld_v2.modeld as modeld_module
|
||||
from openpilot.sunnypilot.modeld_v2.tests import helpers as tests_helpers
|
||||
from openpilot.sunnypilot.modeld_v2.tests.helpers import DummyModel, DummyBundle, CAM_W, CAM_H
|
||||
from openpilot.sunnypilot.models.fetcher import ModelParser, ModelFetcher
|
||||
|
||||
tmp_path = tests_helpers.tmp_path
|
||||
|
||||
|
||||
class TestFallback(OpenpilotTestCase):
|
||||
def test_find_dual_model_in_bundle(self, tmp_path, monkeypatch):
|
||||
lebowski_file = 'driving_lebowski.pkl'
|
||||
tsfdo_file = 'driving_tsfdo.pkl'
|
||||
(tmp_path / lebowski_file).write_bytes(b'fkasdjfkljf')
|
||||
(tmp_path / tsfdo_file).write_bytes(b'dskfajklsdjlsfka')
|
||||
|
||||
monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path)))
|
||||
big_bundle = DummyBundle(models=[DummyModel('supercombo', lebowski_file)], is_big=True)
|
||||
small_bundle = DummyBundle(models=[DummyModel('supercombo', tsfdo_file)], is_big=False)
|
||||
big_pkl = modeld_module._find_driving_pkl(big_bundle)
|
||||
small_pkl = modeld_module._find_driving_pkl(small_bundle)
|
||||
|
||||
assert big_pkl is not None and lebowski_file in big_pkl
|
||||
assert small_pkl is not None and tsfdo_file in small_pkl
|
||||
|
||||
def test_download_models_and_init_modelstate_fallback(self, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path)))
|
||||
big_json = requests.get(ModelFetcher.MODEL_URL_CHESTNUT).json()
|
||||
big_bundle = ModelParser.parse_models(big_json)[-1]
|
||||
small_json = requests.get(ModelFetcher.MODEL_URL).json()
|
||||
small_bundle = ModelParser.parse_models(small_json)[-1]
|
||||
|
||||
buf = io.BytesIO()
|
||||
dump_oob(tests_helpers.make_pkl_data(tests_helpers.ARCHETYPES['supercombo_non20hz']), buf)
|
||||
oob_bytes = buf.getvalue()
|
||||
|
||||
for bundle in (big_bundle, small_bundle):
|
||||
artifact = bundle.models[0].artifact
|
||||
for i in range(len(artifact.chunks)):
|
||||
(tmp_path / get_chunk_name(artifact.fileName, i, len(artifact.chunks))).write_bytes(oob_bytes if i == 0 else b"")
|
||||
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: small_bundle)
|
||||
assert modeld_module.ModelState(CAM_W, CAM_H, chestnut=False).chestnut is False
|
||||
|
||||
monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None, *, chestnut=None: big_bundle)
|
||||
try:
|
||||
assert modeld_module.ModelState(CAM_W, CAM_H, chestnut=True).chestnut is True
|
||||
except Exception as e:
|
||||
assert "AMD" in str(e) or "device" in str(e).lower()
|
||||
|
||||
def test_runtime_fallback_from_big_to_small(self):
|
||||
params = mock.MagicMock()
|
||||
params.get_bool.return_value = True
|
||||
|
||||
big = mock.MagicMock(chestnut=True)
|
||||
big.run.side_effect = RuntimeError("eGPU error")
|
||||
|
||||
small = mock.MagicMock(chestnut=False)
|
||||
small.run.return_value = {"plan": []}
|
||||
|
||||
chestnut = mock.MagicMock(big=True)
|
||||
model, run_count = big, 50
|
||||
|
||||
try:
|
||||
model.run()
|
||||
except Exception:
|
||||
if not params.get_bool("chestnutActive"):
|
||||
raise
|
||||
params.put_bool("chestnutActive", False)
|
||||
model = small
|
||||
chestnut.big = False
|
||||
run_count = 0
|
||||
|
||||
assert model is small
|
||||
assert not chestnut.big
|
||||
assert run_count == 0
|
||||
params.put_bool.assert_called_with("chestnutActive", False)
|
||||
|
||||
model.run()
|
||||
small.run.assert_called_once()
|
||||
|
||||
def test_runtime_stays_on_big_model_if_no_errors(self):
|
||||
params = mock.MagicMock()
|
||||
params.get_bool.return_value = True
|
||||
|
||||
big = mock.MagicMock(chestnut=True)
|
||||
big.run.return_value = {"plan": [1, 2, 3]}
|
||||
|
||||
small = mock.MagicMock(chestnut=False)
|
||||
chestnut = mock.MagicMock(big=True)
|
||||
model, run_count = big, 50
|
||||
try:
|
||||
model.run()
|
||||
except Exception:
|
||||
if not params.get_bool("ChestnutActive"):
|
||||
raise
|
||||
params.put_bool("ChestnutActive", False)
|
||||
model = small
|
||||
chestnut.big = False
|
||||
run_count = 0
|
||||
|
||||
assert model is big
|
||||
assert chestnut.big is True
|
||||
assert run_count == 50
|
||||
params.put_bool.assert_not_called()
|
||||
small.run.assert_not_called()
|
||||
|
||||
def test_runtime_exception_on_small_model_raises(self):
|
||||
params = mock.MagicMock()
|
||||
params.get_bool.return_value = False
|
||||
|
||||
model = mock.MagicMock(chestnut=False)
|
||||
model.run.side_effect = RuntimeError("CPU error")
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
try:
|
||||
model.run()
|
||||
except Exception:
|
||||
if not params.get_bool("ChestnutActive"):
|
||||
raise
|
||||
@@ -1,16 +1,19 @@
|
||||
import argparse
|
||||
import os
|
||||
import hashlib
|
||||
import requests
|
||||
import re
|
||||
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.sunnypilot import get_file_hash
|
||||
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL, DEFAULT_BIG_MODEL
|
||||
from openpilot.sunnypilot.models.fetcher import ModelFetcher
|
||||
|
||||
|
||||
def get_default_model() -> str:
|
||||
show_big_model = (ui_state.usbgpu
|
||||
and (ui_state.usbgpu_active or ui_state.usbgpu_loading or ui_state.is_offroad()))
|
||||
show_big_model = (ui_state.chestnut_present
|
||||
and (ui_state.chestnut_active or ui_state.chestnut_loading or ui_state.is_offroad()))
|
||||
|
||||
return DEFAULT_BIG_MODEL if show_big_model else DEFAULT_MODEL
|
||||
|
||||
@@ -30,14 +33,29 @@ def update_model_hash():
|
||||
print(f"Generated and updated new combined model hash to {MODEL_HASH_PATH}")
|
||||
|
||||
|
||||
def get_ref_for_name(url: str, name: str) -> str:
|
||||
response = requests.get(url, timeout=10)
|
||||
if response.status_code == 200:
|
||||
bundles = response.json()["bundles"]
|
||||
matching = [b for b in bundles if re.search(name, f"{b['short_name']} {b['display_name']}", re.IGNORECASE)]
|
||||
if matching:
|
||||
return max(matching, key=lambda b: int(b["index"]))["ref"]
|
||||
return ""
|
||||
|
||||
|
||||
def update_default_model_names(default_model_name: str, default_big_model_name: str):
|
||||
print("[CHANGE DEFAULT MODEL NAMES]")
|
||||
small_ref = get_ref_for_name(ModelFetcher.MODEL_URL, default_model_name)
|
||||
big_ref = get_ref_for_name(ModelFetcher.MODEL_URL_CHESTNUT, default_big_model_name)
|
||||
|
||||
with open(DEFAULT_MODEL_NAME_PATH, "w") as f:
|
||||
f.write(f'DEFAULT_MODEL = "{default_model_name}"\n')
|
||||
f.write(f'DEFAULT_MODEL_REF = "{small_ref}"\n')
|
||||
f.write(f'DEFAULT_BIG_MODEL = "{default_big_model_name}"\n')
|
||||
f.write(f'DEFAULT_BIG_MODEL_REF = "{big_ref}"\n')
|
||||
|
||||
print(f'New default small model name: "{default_model_name}"')
|
||||
print(f'New default big model name: "{default_big_model_name}"')
|
||||
print(f'New default small model name: "{default_model_name}" (ref: {small_ref})')
|
||||
print(f'New default big model name: "{default_big_model_name}" (ref: {big_ref})')
|
||||
print("[DONE]")
|
||||
|
||||
|
||||
|
||||
@@ -139,43 +139,52 @@ class ModelCache:
|
||||
class ModelFetcher:
|
||||
"""Handles fetching and caching of model data from remote source"""
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v21.json"
|
||||
MODEL_URL_USBGPU = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_usbgpu_v22.json"
|
||||
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v22.json"
|
||||
|
||||
MODEL_SOURCES = {
|
||||
"qcom": (MODEL_URL, ""),
|
||||
"chestnut": (MODEL_URL_CHESTNUT, "_Chestnut"),
|
||||
}
|
||||
|
||||
def __init__(self, params: Params):
|
||||
self.params = params
|
||||
self.model_parser = ModelParser()
|
||||
self._is_usbgpu: bool | None = None
|
||||
self.model_cache = ModelCache(params)
|
||||
self.model_url = self.MODEL_URL
|
||||
self.model_caches = {
|
||||
source: ModelCache(params, suffix=suffix)
|
||||
for source, (_, suffix) in self.MODEL_SOURCES.items()
|
||||
}
|
||||
self._refetched: set[str] = set()
|
||||
self.params.put("ModelManager_ActiveJson", {
|
||||
"qcom": self.MODEL_URL,
|
||||
"chestnut": self.MODEL_URL_CHESTNUT,
|
||||
}, block=True)
|
||||
|
||||
def _update_model_source(self, chestnut_present: bool) -> None:
|
||||
"""Updates what json to use based on chestnut hardware presence via deviceState"""
|
||||
is_usbgpu = chestnut_present
|
||||
if is_usbgpu != self._is_usbgpu:
|
||||
self._is_usbgpu = is_usbgpu
|
||||
self.model_cache = ModelCache(self.params, suffix="_USBGPU" if is_usbgpu else "")
|
||||
self.model_url = self.MODEL_URL_USBGPU if is_usbgpu else self.MODEL_URL
|
||||
self.params.put("ModelManager_ActiveJson", self.model_url, block=True)
|
||||
@staticmethod
|
||||
def active_source(chestnut_present: bool) -> str:
|
||||
return "chestnut" if chestnut_present else "qcom"
|
||||
|
||||
def _fetch_and_cache_models(self) -> list[custom.ModelManagerSP.ModelBundle] | None:
|
||||
def _fetch_and_cache_models(self, source: str) -> list[custom.ModelManagerSP.ModelBundle] | None:
|
||||
"""Fetches fresh model data from remote and updates cache.
|
||||
Returns None on transport errors. Raises on 404 and other fatal HTTP errors.
|
||||
"""
|
||||
model_url, _ = self.MODEL_SOURCES[source]
|
||||
try:
|
||||
response = requests.get(self.model_url, timeout=10)
|
||||
response = requests.get(model_url, timeout=10)
|
||||
|
||||
# Explicitly handle 404 differently
|
||||
if response.status_code == 404:
|
||||
cloudlog.error(f"Models URL returned 404 Not Found: {self.model_url}")
|
||||
raise HTTPError(f"404 Not Found: {self.model_url}", response=response)
|
||||
cloudlog.error(f"Models URL returned 404 Not Found: {model_url}")
|
||||
raise HTTPError(f"404 Not Found: {model_url}", response=response)
|
||||
|
||||
# Raise for any other 4xx/5xx
|
||||
response.raise_for_status()
|
||||
|
||||
json_data = response.json()
|
||||
self.model_cache.set(json_data)
|
||||
cloudlog.debug("Successfully updated models cache")
|
||||
return self.model_parser.parse_models(json_data)
|
||||
parsed = self.model_parser.parse_models(json_data)
|
||||
if parsed:
|
||||
self.model_caches[source].set(json_data)
|
||||
cloudlog.debug(f"Successfully updated models cache for {source}")
|
||||
return parsed
|
||||
|
||||
except ConnectionError as e:
|
||||
cloudlog.warning(f"DNS/connection error while fetching models: {e}")
|
||||
@@ -188,16 +197,40 @@ class ModelFetcher:
|
||||
|
||||
return None
|
||||
|
||||
def get_available_bundles(self, chestnut_present: bool = False) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
"""Gets the list of available models, with smart cache handling"""
|
||||
self._update_model_source(chestnut_present)
|
||||
cached_data, is_expired = self.model_cache.get()
|
||||
@staticmethod
|
||||
def _cache_matches_source(source: str, cached_data: dict) -> bool:
|
||||
bundles = cached_data.get("bundles", [])
|
||||
if source == "chestnut":
|
||||
return any(bundle.get("is_big") is True for bundle in bundles)
|
||||
return not any(bundle.get("is_big") is True for bundle in bundles)
|
||||
|
||||
def get_bundles_for_source(self, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
if source not in self.MODEL_SOURCES:
|
||||
cloudlog.warning(f"Unknown model source: {source}")
|
||||
return []
|
||||
|
||||
cached_data, is_expired = self.model_caches[source].get()
|
||||
|
||||
if cached_data and not is_expired:
|
||||
cloudlog.debug("Using valid cached models data")
|
||||
return self.model_parser.parse_models(cached_data)
|
||||
# a source is refetched over a mismatch at most once per process: if the fresh
|
||||
# manifest still mismatches, the URL is authoritative and the cache is trusted
|
||||
if self._cache_matches_source(source, cached_data) or source in self._refetched:
|
||||
try:
|
||||
parsed = self.model_parser.parse_models(cached_data)
|
||||
except Exception:
|
||||
cloudlog.warning(f"Failed to parse cached models for {source}; refetching", exc_info=True)
|
||||
else:
|
||||
if parsed:
|
||||
cloudlog.debug(f"Using valid cached models data for source {source}")
|
||||
return parsed
|
||||
# a source-matching cache that yields no valid bundles is stale (e.g. an old
|
||||
# manifest version) - do not trust it, refetch so the source is repopulated
|
||||
cloudlog.warning(f"Cached models for {source} have no valid bundles; refetching")
|
||||
else:
|
||||
self._refetched.add(source)
|
||||
cloudlog.warning(f"Cached models for {source} not valid; refetching once")
|
||||
|
||||
fetched_bundles = self._fetch_and_cache_models()
|
||||
fetched_bundles = self._fetch_and_cache_models(source)
|
||||
if fetched_bundles is not None:
|
||||
return fetched_bundles
|
||||
|
||||
@@ -205,14 +238,33 @@ class ModelFetcher:
|
||||
cloudlog.warning("Failed to fetch fresh data and no cache available")
|
||||
|
||||
cloudlog.warning("Failed to fetch fresh data. Using expired cache as fallback")
|
||||
return self.model_parser.parse_models(cached_data)
|
||||
try:
|
||||
return self.model_parser.parse_models(cached_data)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def get_cached_bundles(params: Params, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
|
||||
if source not in ModelFetcher.MODEL_SOURCES:
|
||||
cloudlog.warning(f"Unknown model source: {source}")
|
||||
return []
|
||||
_, suffix = ModelFetcher.MODEL_SOURCES[source]
|
||||
cached_data = params.get(f"ModelManager_ModelsCache{suffix}")
|
||||
if not cached_data:
|
||||
return []
|
||||
try:
|
||||
return ModelParser.parse_models(cached_data)
|
||||
except Exception as e:
|
||||
cloudlog.warning(f"Failed to parse cached models for source {source}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from openpilot.selfdrive.modeld.helpers import usbgpu_present
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
params = Params()
|
||||
model_fetcher = ModelFetcher(params)
|
||||
bundles = model_fetcher.get_available_bundles(chestnut_present=usbgpu_present())
|
||||
bundles = model_fetcher.get_bundles_for_source(ModelFetcher.active_source(chestnut_present()))
|
||||
for bundle in bundles:
|
||||
for model in bundle.models:
|
||||
model_overrides = {override.key: override.value for override in bundle.overrides}
|
||||
|
||||
@@ -16,6 +16,7 @@ from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.sunnypilot.models.constants import Meta, MetaSimPose, MetaTombRaider
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
|
||||
# SET ME TO THE EXACT JSON VERSION WE SET IN SUNNYPILOT_MODELS REPO
|
||||
REQUIRED_JSON_VERSION = 18
|
||||
@@ -24,6 +25,12 @@ CUSTOM_MODEL_PATH = Paths.model_root()
|
||||
METADATA_PATH = Path(__file__).parent / '../models/supercombo_metadata.pkl'
|
||||
ModelManager = custom.ModelManagerSP
|
||||
|
||||
ACTIVE_BUNDLE_KEYS = {
|
||||
"qcom": "ModelManager_ActiveBundle",
|
||||
"chestnut": "ModelManager_ActiveBundleChestnut",
|
||||
}
|
||||
_LAST_VALIDATED_RAW: dict[str, dict | None] = {}
|
||||
|
||||
|
||||
def _compute_hash(file_path: str) -> str | None:
|
||||
from openpilot.common.file_chunker import open_file_chunked
|
||||
@@ -97,55 +104,81 @@ def _bundle_needs_reset(active_bundle: custom.ModelManagerSP.ModelBundle, availa
|
||||
return True
|
||||
if active_bundle.minimumSelectorVersion != matching_bundle.minimumSelectorVersion:
|
||||
return True
|
||||
if active_bundle.runner.raw != matching_bundle.runner.raw:
|
||||
if active_bundle.runner != matching_bundle.runner:
|
||||
return True
|
||||
if set(_bundle_artifacts(active_bundle)) != set(_bundle_artifacts(matching_bundle)):
|
||||
return True
|
||||
|
||||
# missing files trigger re-download, not selection reset
|
||||
return False
|
||||
return not _bundle_is_valid_locally(active_bundle)
|
||||
|
||||
|
||||
def _prev_bundle_key(is_usbgpu: bool) -> str:
|
||||
return "ModelManager_PrevBundle_USBGPU" if is_usbgpu else "ModelManager_PrevBundle"
|
||||
|
||||
|
||||
def validate_active_bundle(params: Params, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None = None,
|
||||
is_usbgpu: bool = False) -> None:
|
||||
raw_bundle = params.get("ModelManager_ActiveBundle")
|
||||
if not raw_bundle:
|
||||
prev = params.get(_prev_bundle_key(is_usbgpu))
|
||||
if prev and (prev_bundle := get_active_bundle(params, raw_bundle_dict=prev)) is not None:
|
||||
if not _bundle_needs_reset(prev_bundle, available_bundles):
|
||||
params.put("ModelManager_ActiveBundle", prev, block=True)
|
||||
return
|
||||
|
||||
active_bundle = get_active_bundle(params, raw_bundle_dict=raw_bundle)
|
||||
if active_bundle is None or _bundle_needs_reset(active_bundle, available_bundles):
|
||||
cloudlog.warning("Active model bundle invalid; resetting to default")
|
||||
params.put(_prev_bundle_key(not is_usbgpu), raw_bundle, block=True)
|
||||
|
||||
prev = params.get(_prev_bundle_key(is_usbgpu))
|
||||
if prev and (prev_bundle := get_active_bundle(params, raw_bundle_dict=prev)) is not None:
|
||||
if not _bundle_needs_reset(prev_bundle, available_bundles):
|
||||
params.put("ModelManager_ActiveBundle", prev, block=True)
|
||||
return
|
||||
|
||||
params.remove("ModelManager_ActiveBundle")
|
||||
params.put("ModelRunnerTypeCache", int(custom.ModelManagerSP.Runner.stock), block=True)
|
||||
|
||||
|
||||
def get_active_bundle(params: Params | None = None, raw_bundle_dict: dict | bytes | None = None) -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
params = params or Params()
|
||||
def _parse_active_bundle(raw_bundle) -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
try:
|
||||
active_bundle_dict = raw_bundle_dict if raw_bundle_dict is not None else (params.get("ModelManager_ActiveBundle") or {})
|
||||
if isinstance(active_bundle_dict, dict) and active_bundle_dict and is_bundle_version_compatible(active_bundle_dict):
|
||||
return custom.ModelManagerSP.ModelBundle(**active_bundle_dict)
|
||||
if isinstance(raw_bundle, dict) and raw_bundle and is_bundle_version_compatible(raw_bundle):
|
||||
return custom.ModelManagerSP.ModelBundle(**raw_bundle)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def get_selected_bundle(params: Params | None = None, source: str = "qcom") -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
params = params or Params()
|
||||
return _parse_active_bundle(params.get(ACTIVE_BUNDLE_KEYS[source]))
|
||||
|
||||
|
||||
def get_active_source(chestnut: bool | None = None, chestnut_active: bool | None = None,
|
||||
chestnut_loading: bool | None = None, offroad: bool | None = None) -> str:
|
||||
if chestnut is None:
|
||||
chestnut = chestnut_present()
|
||||
state_valid = chestnut_active is not None or chestnut_loading is not None or offroad is not None
|
||||
big_active = chestnut and (not state_valid or chestnut_active or chestnut_loading or offroad)
|
||||
return "chestnut" if big_active else "qcom"
|
||||
|
||||
|
||||
def get_active_bundle(params: Params | None = None, *, chestnut: bool | None = None) -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
# no cross-slot fallback: an empty active slot means the hardware default, which
|
||||
# only stock modeld can run - modeld_v2 requires a real bundle
|
||||
params = params or Params()
|
||||
return get_selected_bundle(params, get_active_source(chestnut=chestnut))
|
||||
|
||||
|
||||
def resolve_bundle_by_ref(
|
||||
ref: str, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]],
|
||||
) -> "tuple[custom.ModelManagerSP.ModelBundle, str] | None":
|
||||
for source, bundles in source_bundles.items():
|
||||
for bundle in bundles:
|
||||
if bundle.ref == ref:
|
||||
return bundle, source
|
||||
return None
|
||||
|
||||
|
||||
def _validate_active_bundle(params: Params, source: str, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None = None) -> None:
|
||||
global _LAST_VALIDATED_RAW
|
||||
|
||||
key = ACTIVE_BUNDLE_KEYS[source]
|
||||
raw_bundle = params.get(key)
|
||||
if not raw_bundle:
|
||||
return
|
||||
|
||||
if _LAST_VALIDATED_RAW.get(key) == raw_bundle:
|
||||
return
|
||||
|
||||
active_bundle = _parse_active_bundle(raw_bundle)
|
||||
if active_bundle is None or _bundle_needs_reset(active_bundle, available_bundles):
|
||||
cloudlog.warning(f"Active model bundle invalid for {source}; resetting to default")
|
||||
params.remove(key)
|
||||
_LAST_VALIDATED_RAW[key] = None
|
||||
else:
|
||||
_LAST_VALIDATED_RAW[key] = raw_bundle
|
||||
|
||||
|
||||
def validate_active_bundles(params: Params, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]]) -> None:
|
||||
# an empty list means the fetch failed, not that the catalog dropped the bundle
|
||||
for source, bundles in source_bundles.items():
|
||||
_validate_active_bundle(params, source, bundles or None)
|
||||
get_active_model_runner(params, force_check=True)
|
||||
|
||||
|
||||
def get_active_model_runner(params: Params | None = None, force_check: bool = False) -> int:
|
||||
params = params or Params()
|
||||
cached_runner_type = params.get("ModelRunnerTypeCache")
|
||||
|
||||
@@ -17,12 +17,17 @@ from openpilot.common.hardware.hw import Paths
|
||||
|
||||
from openpilot.cereal import messaging, custom
|
||||
from openpilot.sunnypilot.models.fetcher import ModelFetcher
|
||||
from openpilot.sunnypilot.models.helpers import get_active_bundle, validate_active_bundle, verify_file
|
||||
from openpilot.sunnypilot.models.helpers import (ACTIVE_BUNDLE_KEYS, get_active_bundle, get_selected_bundle,
|
||||
resolve_bundle_by_ref, validate_active_bundles, verify_file)
|
||||
|
||||
# (connect, read) seconds. read is per-request inactivity, not a total cap
|
||||
DOWNLOAD_TIMEOUT = (30, 30)
|
||||
|
||||
|
||||
class DownloadCancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ModelManagerSP:
|
||||
"""Manages model downloads and status reporting"""
|
||||
|
||||
@@ -31,11 +36,24 @@ class ModelManagerSP:
|
||||
self.model_fetcher = ModelFetcher(self.params)
|
||||
self.pm = messaging.PubMaster(["modelManagerSP"])
|
||||
self.sm = messaging.SubMaster(["deviceState"])
|
||||
self.chestnut_present = False
|
||||
self.available_models: list[custom.ModelManagerSP.ModelBundle] = []
|
||||
self.source_models: dict[str, list[custom.ModelManagerSP.ModelBundle]] = {}
|
||||
self.selected_bundle: custom.ModelManagerSP.ModelBundle = None
|
||||
self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params)
|
||||
self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
self._chunk_size = 128 * 1000 # 128 KB chunks
|
||||
self._download_start_times: dict[str, float] = {} # Track start time per model
|
||||
self._download_ref: bytes | str | None = None
|
||||
|
||||
def _download_interrupted(self) -> bool:
|
||||
# only removal cancels: a different ref is a queued selection that
|
||||
# _release_download_ref leaves in place for the next tick
|
||||
return self.params.get("ModelManager_DownloadRef") is None
|
||||
|
||||
def _release_download_ref(self) -> None:
|
||||
if self.params.get("ModelManager_DownloadRef") == self._download_ref:
|
||||
self.params.remove("ModelManager_DownloadRef")
|
||||
self._download_ref = None
|
||||
|
||||
def _sync_artifact_progress(self, source_artifact) -> None:
|
||||
"""Mirror download progress to all artifacts sharing the same filename in the selected bundle."""
|
||||
@@ -77,8 +95,8 @@ class ModelManagerSP:
|
||||
f.write(chunk)
|
||||
bytes_downloaded += len(chunk)
|
||||
|
||||
if self.params.get("ModelManager_DownloadIndex") is None:
|
||||
raise Exception("Download cancelled")
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
|
||||
if total_size > 0:
|
||||
progress = (bytes_downloaded / total_size) * 100
|
||||
@@ -91,7 +109,7 @@ class ModelManagerSP:
|
||||
# Clean up start time after download completes
|
||||
del self._download_start_times[model.fileName]
|
||||
|
||||
async def _download_chunked(self, base_url: str, base_path: str, artifact) -> None:
|
||||
async def _download_chunked(self, base_url: str, base_path: str, artifact, skip: frozenset[int] | set[int] = frozenset()) -> None:
|
||||
from openpilot.common.file_chunker import get_chunk_name, get_manifest_path
|
||||
|
||||
num_chunks = len(artifact.chunks)
|
||||
@@ -103,8 +121,11 @@ class ModelManagerSP:
|
||||
|
||||
# Shared connection saves a TCP+TLS handshake per chunk.
|
||||
# Keep sequential: the link saturates on one stream and Session is not thread-safe.
|
||||
completed = len(skip)
|
||||
with requests.Session() as session:
|
||||
for i, _ in enumerate(artifact.chunks):
|
||||
if i in skip:
|
||||
continue
|
||||
chunk_url = get_chunk_name(base_url, i, num_chunks)
|
||||
chunk_path = get_chunk_name(base_path, i, num_chunks)
|
||||
chunk_downloaded = 0
|
||||
@@ -115,15 +136,16 @@ class ModelManagerSP:
|
||||
for data in response.iter_content(chunk_size=self._chunk_size):
|
||||
f.write(data)
|
||||
chunk_downloaded += len(data)
|
||||
if self.params.get("ModelManager_DownloadIndex") is None:
|
||||
raise Exception("Download cancelled")
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
intra = chunk_downloaded / max(chunk_size, 1)
|
||||
progress = min(99.0, ((i + intra) / num_chunks) * 100)
|
||||
progress = min(99.0, ((completed + intra) / num_chunks) * 100)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
artifact.downloadProgress.progress = progress
|
||||
artifact.downloadProgress.eta = self._calculate_eta(artifact.fileName, progress)
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
completed += 1
|
||||
|
||||
with open(manifest_path, 'w') as f: # noqa: ASYNC230
|
||||
f.write(str(num_chunks))
|
||||
@@ -134,6 +156,8 @@ class ModelManagerSP:
|
||||
async def _process_artifact(self, artifact, destination_path: str) -> None:
|
||||
if not artifact.downloadUri.uri:
|
||||
return None
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
|
||||
url = artifact.downloadUri.uri
|
||||
expected_hash = artifact.downloadUri.sha256
|
||||
@@ -141,21 +165,23 @@ class ModelManagerSP:
|
||||
full_path = os.path.join(destination_path, filename)
|
||||
|
||||
try:
|
||||
# progress counts only valid chunks so a resumed download continues the
|
||||
# bar from where verification left it, instead of falling back to zero
|
||||
is_cached = False
|
||||
valid_chunks: set[int] = set()
|
||||
if len(artifact.chunks) > 0:
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
num_chunks = len(artifact.chunks)
|
||||
chunks_valid = True
|
||||
for i, chunk in enumerate(artifact.chunks):
|
||||
chunk_path = get_chunk_name(full_path, i, num_chunks)
|
||||
if not await verify_file(chunk_path, chunk.sha256):
|
||||
chunks_valid = False
|
||||
break
|
||||
artifact.downloadProgress.progress = ((i + 1) / num_chunks) * 100
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
if await verify_file(get_chunk_name(full_path, i, num_chunks), chunk.sha256):
|
||||
valid_chunks.add(i)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.verifying
|
||||
artifact.downloadProgress.progress = (len(valid_chunks) / num_chunks) * 100
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
if chunks_valid and num_chunks > 0:
|
||||
is_cached = True
|
||||
is_cached = len(valid_chunks) == num_chunks
|
||||
else:
|
||||
if await verify_file(full_path, expected_hash):
|
||||
is_cached = True
|
||||
@@ -169,7 +195,7 @@ class ModelManagerSP:
|
||||
return
|
||||
|
||||
if len(artifact.chunks) > 0:
|
||||
await self._download_chunked(url, full_path, artifact)
|
||||
await self._download_chunked(url, full_path, artifact, skip=valid_chunks)
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
for i, chunk in enumerate(artifact.chunks):
|
||||
chunk_path = get_chunk_name(full_path, i, len(artifact.chunks))
|
||||
@@ -186,6 +212,17 @@ class ModelManagerSP:
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
|
||||
except DownloadCancelled:
|
||||
# a cancel keeps whatever is on disk: complete chunks resume the next attempt
|
||||
self._download_start_times.pop(artifact.fileName, None)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
artifact.downloadProgress.eta = 0
|
||||
self._sync_artifact_progress(artifact)
|
||||
if self.selected_bundle:
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
self._report_status()
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
cloudlog.error(f"Error downloading {filename}: {str(e)}")
|
||||
for f in [full_path] + [p for p in (os.path.join(destination_path, f) for f in os.listdir(destination_path)) if filename in p]:
|
||||
@@ -217,8 +254,7 @@ class ModelManagerSP:
|
||||
model_manager_state.availableBundles = self.available_models
|
||||
self.pm.send('modelManagerSP', msg)
|
||||
|
||||
async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None:
|
||||
"""Downloads all models in a bundle"""
|
||||
async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
|
||||
self.selected_bundle = model_bundle
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
for model in self.selected_bundle.models:
|
||||
@@ -240,10 +276,11 @@ class ModelManagerSP:
|
||||
seen_artifacts.add(artifact.fileName)
|
||||
await self._process_artifact(artifact, destination_path)
|
||||
|
||||
self.active_bundle = self.selected_bundle
|
||||
self.active_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
self.params.put("ModelManager_ActiveBundle", self.active_bundle.to_dict(), block=True)
|
||||
self.selected_bundle = None
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
self.params.put(ACTIVE_BUNDLE_KEYS[source], model_bundle.to_dict(), block=True)
|
||||
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
|
||||
except Exception:
|
||||
if self.selected_bundle is not None:
|
||||
@@ -253,38 +290,51 @@ class ModelManagerSP:
|
||||
finally:
|
||||
self._report_status()
|
||||
|
||||
def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None:
|
||||
def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
|
||||
"""Main entry point for downloading a model bundle"""
|
||||
asyncio.run(self._download_bundle(model_bundle, destination_path))
|
||||
asyncio.run(self._download_bundle(model_bundle, destination_path, source))
|
||||
|
||||
BOOT_SETTLE_TICKS = 10 # seconds at 1 Hz before validating active bundle
|
||||
def _process_download_requests(self) -> None:
|
||||
# loops so a ref queued during a download starts in the same tick, without
|
||||
# the bar dropping to idle for a tick between the two transfers
|
||||
last_ref = None
|
||||
while (ref_to_download := self.params.get("ModelManager_DownloadRef")) is not None:
|
||||
if ref_to_download == last_ref: # a repeating ref falls back to the next tick instead of spinning
|
||||
return
|
||||
last_ref = ref_to_download
|
||||
resolved = resolve_bundle_by_ref(ref_to_download, self.source_models)
|
||||
if not resolved:
|
||||
return
|
||||
model_to_download, source = resolved
|
||||
self._download_ref = ref_to_download
|
||||
try:
|
||||
self.download(model_to_download, Paths.model_root(), source)
|
||||
except Exception as e:
|
||||
cloudlog.exception(e)
|
||||
finally:
|
||||
self._release_download_ref()
|
||||
self.selected_bundle = None
|
||||
|
||||
def main_thread(self) -> None:
|
||||
"""Main thread for model management"""
|
||||
rk = Ratekeeper(1, print_delay_threshold=None)
|
||||
boot_ticks = 0
|
||||
|
||||
while True:
|
||||
try:
|
||||
self.sm.update(0)
|
||||
chestnut_present = self.sm['deviceState'].chestnutPresent
|
||||
self.available_models = self.model_fetcher.get_available_bundles(chestnut_present)
|
||||
if boot_ticks >= self.BOOT_SETTLE_TICKS:
|
||||
validate_active_bundle(self.params, self.available_models, is_usbgpu=chestnut_present)
|
||||
boot_ticks = min(boot_ticks + 1, self.BOOT_SETTLE_TICKS)
|
||||
self.active_bundle = get_active_bundle(self.params)
|
||||
self.chestnut_present = self.sm['deviceState'].chestnutPresent
|
||||
self.source_models = {source: self.model_fetcher.get_bundles_for_source(source) for source in ModelFetcher.MODEL_SOURCES}
|
||||
self.available_models = self.source_models[ModelFetcher.active_source(self.chestnut_present)]
|
||||
validate_active_bundles(self.params, self.source_models)
|
||||
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
|
||||
if (index_to_download := self.params.get("ModelManager_DownloadIndex")) is not None:
|
||||
if self.active_bundle and self.active_bundle.index == index_to_download:
|
||||
self.params.remove("ModelManager_DownloadIndex")
|
||||
elif model_to_download := next((model for model in self.available_models if model.index == index_to_download), None):
|
||||
try:
|
||||
self.download(model_to_download, Paths.model_root())
|
||||
except Exception as e:
|
||||
cloudlog.exception(e)
|
||||
finally:
|
||||
self.params.remove("ModelManager_DownloadIndex")
|
||||
self.selected_bundle = None
|
||||
if get_selected_bundle(self.params, "chestnut") is not None and get_selected_bundle(self.params, "qcom") is None:
|
||||
if self.params.get("ModelManager_DownloadRef") is None:
|
||||
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL_REF
|
||||
if DEFAULT_MODEL_REF:
|
||||
self.params.put("ModelManager_DownloadRef", DEFAULT_MODEL_REF)
|
||||
|
||||
self._process_download_requests()
|
||||
|
||||
if self.params.get("ModelManager_ClearCache"):
|
||||
self.clear_model_cache()
|
||||
@@ -302,12 +352,14 @@ class ModelManagerSP:
|
||||
Clears the model cache directory of all files except those in the active model bundle.
|
||||
"""
|
||||
|
||||
# Get list of files used by active model bundle
|
||||
# Get list of files used by both slots' selected bundles (either may become
|
||||
# the truly active bundle depending on hardware availability)
|
||||
active_files = []
|
||||
if self.active_bundle is not None: # When the default model is active
|
||||
for model in self.active_bundle.models:
|
||||
if hasattr(model, 'artifact') and model.artifact.fileName:
|
||||
active_files.append(model.artifact.fileName)
|
||||
for source in ACTIVE_BUNDLE_KEYS:
|
||||
if selected_bundle := get_selected_bundle(self.params, source):
|
||||
for model in selected_bundle.models:
|
||||
if model.artifact.fileName:
|
||||
active_files.append(model.artifact.fileName)
|
||||
|
||||
# Remove all files except active ones (including their chunk files)
|
||||
model_dir = Paths.model_root()
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
DEFAULT_MODEL = "CD210"
|
||||
DEFAULT_MODEL_REF = "5b6436a90cf6902b8aaa71c2b6f3d7164d8ae391"
|
||||
DEFAULT_BIG_MODEL = "Lebowski"
|
||||
DEFAULT_BIG_MODEL_REF = "fa0c6876d3cf070e91e25e5353ceadc68a5b3285"
|
||||
|
||||
@@ -11,6 +11,7 @@ import http.server
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from typing import Any
|
||||
from unittest import mock
|
||||
@@ -23,6 +24,10 @@ from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.common.file_chunker import get_chunk_name, get_manifest_path
|
||||
from openpilot.selfdrive.test.helpers import http_server_context
|
||||
from openpilot.sunnypilot.models import manager as manager_module
|
||||
from openpilot.sunnypilot.models.fetcher import ModelFetcher, get_cached_bundles
|
||||
from openpilot.sunnypilot.models import helpers
|
||||
from openpilot.sunnypilot.models.helpers import (get_active_bundle, get_active_source, get_selected_bundle,
|
||||
resolve_bundle_by_ref, validate_active_bundles)
|
||||
from openpilot.sunnypilot.models.manager import ModelManagerSP
|
||||
|
||||
CHUNK_BODIES = [b'A' * 5000, b'B' * 5000, b'C' * 3000]
|
||||
@@ -98,11 +103,13 @@ class ManagerDownloadTestBase(OpenpilotTestCase):
|
||||
self.manager = ModelManagerSP.__new__(ModelManagerSP)
|
||||
self.manager.params = mock.MagicMock()
|
||||
self.manager.params.get.return_value = b'0' # not cancelled
|
||||
self.manager._download_ref = b'0'
|
||||
self.manager.pm = mock.MagicMock()
|
||||
self.manager.pm.send.side_effect = self._record_progress
|
||||
self.manager.selected_bundle = None
|
||||
self.manager.active_bundle = None
|
||||
self.manager.available_models = []
|
||||
self.manager.chestnut_present = False
|
||||
self.manager._chunk_size = 1024
|
||||
self.manager._download_start_times = {}
|
||||
|
||||
@@ -249,6 +256,166 @@ class TestManagerDownload(ManagerDownloadTestBase):
|
||||
assert self.manager._download_start_times == {}
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_download_ref_present_keeps_download_alive(self):
|
||||
"""A pending download request (DownloadRef set) must not be cancelled mid-transfer."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
self.manager.params.get.side_effect = lambda key: b"ref" if key == "ModelManager_DownloadRef" else None
|
||||
self.manager._download_ref = b"ref"
|
||||
asyncio.run(self.manager._download_chunked(artifact.downloadUri.uri, base_path, artifact))
|
||||
assert os.path.isfile(get_manifest_path(base_path))
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_cancellation_via_download_ref(self):
|
||||
"""Removing DownloadRef mid-transfer cancels the download."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
checks = {"n": 0}
|
||||
|
||||
def get(key):
|
||||
if key == "ModelManager_DownloadRef":
|
||||
checks["n"] += 1
|
||||
return b"ref" if checks["n"] <= 2 else None
|
||||
return b"0"
|
||||
|
||||
self.manager.params.get.side_effect = get
|
||||
self.manager._download_ref = b"ref"
|
||||
with self.assertRaises(Exception) as ctx:
|
||||
asyncio.run(self.manager._download_chunked(artifact.downloadUri.uri, base_path, artifact))
|
||||
assert 'cancelled' in str(ctx.exception).lower()
|
||||
assert not os.path.isfile(get_manifest_path(base_path))
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_replaced_download_ref_queues_instead_of_cancelling(self):
|
||||
"""Selecting another model mid-transfer lets the running download finish."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
self.manager.params.get.side_effect = lambda key: b"other-ref" if key == "ModelManager_DownloadRef" else None
|
||||
self.manager._download_ref = b"ref"
|
||||
asyncio.run(self.manager._download_chunked(artifact.downloadUri.uri, base_path, artifact))
|
||||
assert os.path.isfile(get_manifest_path(base_path))
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_replaced_download_ref_is_kept(self):
|
||||
"""A selection made during a download must survive that download's cleanup."""
|
||||
self.manager.params.get.return_value = b"new-ref"
|
||||
self.manager._download_ref = b"old-ref"
|
||||
self.manager._release_download_ref()
|
||||
self.manager.params.remove.assert_not_called()
|
||||
|
||||
def test_own_download_ref_is_released(self):
|
||||
self.manager.params.get.return_value = b"ref"
|
||||
self.manager._download_ref = b"ref"
|
||||
self.manager._release_download_ref()
|
||||
self.manager.params.remove.assert_called_once_with("ModelManager_DownloadRef")
|
||||
|
||||
def test_cached_bundle_cancel_skips_slot_write(self):
|
||||
"""A cancel must stop an already-on-disk bundle before it is applied to the slot."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
for i, data in enumerate(CHUNK_BODIES):
|
||||
with open(get_chunk_name(base_path, i, len(CHUNK_BODIES)), 'wb') as f:
|
||||
f.write(data)
|
||||
self._bundle.ref = "test-ref"
|
||||
params, store = self._make_params_with_store()
|
||||
store["ModelManager_DownloadRef"] = None # removed -> cancelled
|
||||
self.manager.params = params
|
||||
self.manager._download_ref = b"ref"
|
||||
with self.assertRaises(Exception) as ctx:
|
||||
asyncio.run(self.manager._download_bundle(self._bundle, self.dest, "qcom"))
|
||||
assert 'cancelled' in str(ctx.exception).lower()
|
||||
assert "ModelManager_ActiveBundle" not in store
|
||||
assert all(os.path.isfile(p) for p in self.chunk_paths(base_path)), "cancel must not delete cached chunks"
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_resume_skips_valid_chunks(self):
|
||||
"""A chunk already on disk is kept and not re-downloaded; progress starts above its share."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
with open(get_chunk_name(base_path, 0, len(CHUNK_BODIES)), 'wb') as f:
|
||||
f.write(CHUNK_BODIES[0])
|
||||
|
||||
asyncio.run(self.manager._process_artifact(artifact, self.dest))
|
||||
|
||||
chunk0_suffix = get_chunk_name('', 0, len(CHUNK_BODIES))
|
||||
assert not any(p.endswith(chunk0_suffix) for p in DownloadHandler.request_paths), "valid chunk was re-downloaded"
|
||||
for i, expected in enumerate(CHUNK_BODIES):
|
||||
with open(get_chunk_name(base_path, i, len(CHUNK_BODIES)), 'rb') as f:
|
||||
assert f.read() == expected
|
||||
assert os.path.isfile(get_manifest_path(base_path))
|
||||
assert min(self.reported) >= (1 / len(CHUNK_BODIES)) * 100 - 1, "progress must not restart below the resumed share"
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_verify_reports_valid_fraction_then_cached(self):
|
||||
"""A fully cached bundle publishes climbing verify progress and ends cached."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
base_path = os.path.join(self.dest, artifact.fileName)
|
||||
for i, data in enumerate(CHUNK_BODIES):
|
||||
with open(get_chunk_name(base_path, i, len(CHUNK_BODIES)), 'wb') as f:
|
||||
f.write(data)
|
||||
|
||||
asyncio.run(self.manager._process_artifact(artifact, self.dest))
|
||||
|
||||
assert DownloadHandler.request_paths == [], "cached bundle must not hit the network"
|
||||
assert [round(p) for p in self.reported[:3]] == [33, 67, 100]
|
||||
assert artifact.downloadProgress.status == custom.ModelManagerSP.DownloadStatus.cached
|
||||
self.run_with_server(body)
|
||||
|
||||
def _make_params_with_store(self):
|
||||
params = mock.MagicMock()
|
||||
store = {}
|
||||
|
||||
def get(key, *args, **kwargs):
|
||||
return store.get(key, b"0") # b"0" -> download not cancelled
|
||||
|
||||
def put(key, value, *args, **kwargs):
|
||||
store[key] = value
|
||||
|
||||
params.get.side_effect = get
|
||||
params.put.side_effect = put
|
||||
return params, store
|
||||
|
||||
def test_download_writes_qcom_slot(self):
|
||||
"""A download resolved to the qcom source writes the qcom active bundle slot only."""
|
||||
def body():
|
||||
artifact = self.make_artifact(chunked=True)
|
||||
self._bundle.ref = "test-ref"
|
||||
self._bundle.minimumSelectorVersion = 18
|
||||
params, store = self._make_params_with_store()
|
||||
self.manager.params = params
|
||||
asyncio.run(self.manager._download_bundle(self._bundle, self.dest, "qcom"))
|
||||
|
||||
assert "ModelManager_ActiveBundle" in store, "qcom download must write the qcom slot"
|
||||
assert "ModelManager_ActiveBundleChestnut" not in store, "qcom download must not touch the chestnut slot"
|
||||
assert self.manager.selected_bundle.status == custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
assert self.manager.active_bundle is not None and self.manager.active_bundle.ref == "test-ref"
|
||||
assert self.manager.active_bundle.status == custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
chunk_names = [get_chunk_name(artifact.fileName, i, len(artifact.chunks)) for i in range(len(artifact.chunks))]
|
||||
missing = [c for c in chunk_names if not os.path.isfile(os.path.join(self.dest, c))]
|
||||
assert missing == [], f"chunks missing from the cache: {missing}"
|
||||
self.run_with_server(body)
|
||||
|
||||
def test_download_writes_chestnut_slot(self):
|
||||
"""A download resolved to the chestnut source writes the chestnut active bundle slot only."""
|
||||
def body():
|
||||
self.make_artifact(chunked=True)
|
||||
self._bundle.ref = "big-ref"
|
||||
self._bundle.minimumSelectorVersion = 18
|
||||
params, store = self._make_params_with_store()
|
||||
self.manager.params = params
|
||||
asyncio.run(self.manager._download_bundle(self._bundle, self.dest, "chestnut"))
|
||||
|
||||
assert "ModelManager_ActiveBundleChestnut" in store, "chestnut download must write the chestnut slot"
|
||||
assert "ModelManager_ActiveBundle" not in store, "chestnut download must not touch the qcom slot"
|
||||
assert self.manager.selected_bundle.status == custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
self.run_with_server(body)
|
||||
|
||||
|
||||
class TestManagerImports(OpenpilotTestCase):
|
||||
"""Catches undeclared dependencies. aiohttp lived only in the AGNOS venv; 19.6 dropped
|
||||
@@ -267,6 +434,352 @@ class TestManagerImports(OpenpilotTestCase):
|
||||
assert connect > 0 and read > 0, "requests defaults to no timeout; downloads would hang forever"
|
||||
|
||||
|
||||
class TestResolveBundleByRef(OpenpilotTestCase):
|
||||
"""A ref resolves to (bundle, source) across both hardware manifests. Refs are
|
||||
unique per manifest and never overlap across sources, so a ref maps to exactly
|
||||
one slot. Shared by the manager's download flow and the settings UI."""
|
||||
|
||||
@staticmethod
|
||||
def _bundle(ref: str):
|
||||
bundle = custom.ModelManagerSP.ModelBundle.new_message()
|
||||
bundle.ref = ref
|
||||
return bundle
|
||||
|
||||
def test_qcom_ref_resolves_to_qcom_slot(self):
|
||||
small = self._bundle("small")
|
||||
assert resolve_bundle_by_ref("small", {"qcom": [small], "chestnut": []}) == (small, "qcom")
|
||||
|
||||
def test_chestnut_ref_resolves_to_chestnut_slot(self):
|
||||
big = self._bundle("big")
|
||||
assert resolve_bundle_by_ref("big", {"qcom": [], "chestnut": [big]}) == (big, "chestnut")
|
||||
|
||||
def test_unknown_ref_returns_none(self):
|
||||
source_bundles = {"qcom": [self._bundle("small")], "chestnut": []}
|
||||
assert resolve_bundle_by_ref("nope", source_bundles) is None
|
||||
|
||||
|
||||
def manifest_bundle(short_name: str, ref: str, index: int = 0, is_big: bool = False) -> dict:
|
||||
"""Minimal manifest bundle dict, version-compatible (no chunks to avoid disk side effects).
|
||||
Big (chestnut) bundles carry `is_big: true` in the manifest JSON."""
|
||||
return {
|
||||
"index": index,
|
||||
"short_name": short_name,
|
||||
"display_name": short_name.upper(),
|
||||
"generation": 1,
|
||||
"environment": "release",
|
||||
"runner": "tinygrad",
|
||||
"is_big": is_big,
|
||||
"minimum_selector_version": "18",
|
||||
"ref": ref,
|
||||
"models": [{
|
||||
"type": "supercombo",
|
||||
"artifact": {
|
||||
"file_name": f"{short_name}.pkl",
|
||||
"download_uri": {"url": f"https://example.com/{short_name}.pkl", "sha256": "s"},
|
||||
},
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def fresh_sync_time() -> int:
|
||||
return int(time.monotonic() * 1e9)
|
||||
|
||||
|
||||
class TestModelFetcherSources(OpenpilotTestCase):
|
||||
"""Both manifests are always maintained: get_bundles_for_source exposes either
|
||||
source by name, and active_source picks which one matches the attached hardware."""
|
||||
|
||||
def _make_params(self, qcom_manifest, chestnut_manifest):
|
||||
params = mock.MagicMock()
|
||||
|
||||
def get(key):
|
||||
if key == "ModelManager_ModelsCache":
|
||||
return qcom_manifest
|
||||
if key == "ModelManager_ModelsCache_Chestnut":
|
||||
return chestnut_manifest
|
||||
if key in ("ModelManager_LastSyncTime", "ModelManager_LastSyncTime_Chestnut"):
|
||||
return fresh_sync_time()
|
||||
return None
|
||||
|
||||
params.get.side_effect = get
|
||||
return params
|
||||
|
||||
def test_active_source_follows_chestnut_presence(self):
|
||||
assert ModelFetcher.active_source(False) == "qcom"
|
||||
assert ModelFetcher.active_source(True) == "chestnut"
|
||||
|
||||
def test_get_bundles_for_source_returns_each_source(self):
|
||||
params = self._make_params({"bundles": [manifest_bundle("small", "aaa")]},
|
||||
{"bundles": [manifest_bundle("big", "bbb", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
assert [bundle.ref for bundle in fetcher.get_bundles_for_source("qcom")] == ["aaa"]
|
||||
assert [bundle.ref for bundle in fetcher.get_bundles_for_source("chestnut")] == ["bbb"]
|
||||
|
||||
def test_get_bundles_for_source_unknown(self):
|
||||
assert ModelFetcher(mock.MagicMock()).get_bundles_for_source("bogus") == []
|
||||
|
||||
def test_get_cached_bundles_parses_source(self):
|
||||
params = self._make_params({"bundles": [manifest_bundle("small", "aaa")]},
|
||||
{"bundles": [manifest_bundle("big", "bbb", is_big=True)]})
|
||||
qcom_bundles = get_cached_bundles(params, "qcom")
|
||||
chestnut_bundles = get_cached_bundles(params, "chestnut")
|
||||
assert [b.ref for b in qcom_bundles] == ["aaa"]
|
||||
assert [b.ref for b in chestnut_bundles] == ["bbb"]
|
||||
assert qcom_bundles[0].displayName == "SMALL"
|
||||
|
||||
def test_get_cached_bundles_empty_when_missing(self):
|
||||
params = mock.MagicMock()
|
||||
params.get.return_value = None
|
||||
assert get_cached_bundles(params, "qcom") == []
|
||||
assert get_cached_bundles(params, "chestnut") == []
|
||||
|
||||
def test_get_cached_bundles_unknown_source(self):
|
||||
assert get_cached_bundles(mock.MagicMock(), "bogus") == []
|
||||
|
||||
def test_active_json_has_both_urls(self):
|
||||
params = mock.MagicMock()
|
||||
ModelFetcher(params)
|
||||
active_json_calls = [call for call in params.put.call_args_list if call.args[0] == "ModelManager_ActiveJson"]
|
||||
assert active_json_calls, "expected ModelManager_ActiveJson to be written"
|
||||
assert active_json_calls[-1].args[1] == {
|
||||
"qcom": ModelFetcher.MODEL_URL,
|
||||
"chestnut": ModelFetcher.MODEL_URL_CHESTNUT,
|
||||
}
|
||||
|
||||
|
||||
|
||||
class TestSourceCacheIntegrity(OpenpilotTestCase):
|
||||
"""Each source's cached manifest must contain only that source's models; the
|
||||
`is_big` flag in the JSON marks the big (chestnut) models. A mismatched cache is
|
||||
legacy data from before the per-source split (the active manifest was cached
|
||||
under the unsuffixed key regardless of hardware) and is refetched. This
|
||||
replaces the old one-time bundle migration."""
|
||||
|
||||
def _make_params(self, qcom_manifest, chestnut_manifest):
|
||||
params = mock.MagicMock()
|
||||
|
||||
def get(key):
|
||||
if key == "ModelManager_ModelsCache":
|
||||
return qcom_manifest
|
||||
if key == "ModelManager_ModelsCache_Chestnut":
|
||||
return chestnut_manifest
|
||||
if key in ("ModelManager_LastSyncTime", "ModelManager_LastSyncTime_Chestnut"):
|
||||
return fresh_sync_time()
|
||||
return None
|
||||
|
||||
params.get.side_effect = get
|
||||
return params
|
||||
|
||||
def _fetched(self, *bundles):
|
||||
return ModelFetcher(mock.MagicMock()).model_parser.parse_models({"bundles": list(bundles)})
|
||||
|
||||
def test_qcom_cache_with_big_models_is_refetched(self):
|
||||
"""Legacy: the unsuffixed cache holds the big manifest. is_big confirms it is
|
||||
the wrong set for qcom, so a fresh fetch replaces it."""
|
||||
params = self._make_params({"bundles": [manifest_bundle("big", "bbb", is_big=True)]},
|
||||
{"bundles": [manifest_bundle("big2", "ccc", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
fetched = self._fetched(manifest_bundle("small", "aaa"))
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", return_value=fetched):
|
||||
bundles = fetcher.get_bundles_for_source("qcom")
|
||||
assert [bundle.ref for bundle in bundles] == ["aaa"]
|
||||
|
||||
def test_chestnut_cache_without_big_models_is_refetched(self):
|
||||
params = self._make_params({"bundles": [manifest_bundle("small", "aaa")]},
|
||||
{"bundles": [manifest_bundle("big2", "ccc")]})
|
||||
fetcher = ModelFetcher(params)
|
||||
fetched = self._fetched(manifest_bundle("big", "bbb", is_big=True))
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", return_value=fetched):
|
||||
bundles = fetcher.get_bundles_for_source("chestnut")
|
||||
assert [bundle.ref for bundle in bundles] == ["bbb"]
|
||||
|
||||
def test_matching_caches_are_used_without_fetch(self):
|
||||
params = self._make_params({"bundles": [manifest_bundle("small", "aaa")]},
|
||||
{"bundles": [manifest_bundle("big", "bbb", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", side_effect=AssertionError("cache should be used")):
|
||||
assert [bundle.ref for bundle in fetcher.get_bundles_for_source("qcom")] == ["aaa"]
|
||||
assert [bundle.ref for bundle in fetcher.get_bundles_for_source("chestnut")] == ["bbb"]
|
||||
|
||||
def test_stale_version_cache_is_refetched(self):
|
||||
"""A source-matching cache whose bundles are all filtered by the selector version
|
||||
check parses to zero valid bundles; it is stale (e.g. an old manifest) and must be
|
||||
refetched instead of silently returning an empty list forever."""
|
||||
stale = manifest_bundle("small", "aaa")
|
||||
stale["minimum_selector_version"] = "16"
|
||||
params = self._make_params({"bundles": [stale]},
|
||||
{"bundles": [manifest_bundle("big", "bbb", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
fetched = self._fetched(manifest_bundle("small2", "ddd"))
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", return_value=fetched) as fetch:
|
||||
bundles = fetcher.get_bundles_for_source("qcom")
|
||||
fetch.assert_called_once_with("qcom")
|
||||
assert [bundle.ref for bundle in bundles] == ["ddd"]
|
||||
|
||||
def test_mismatched_refetch_happens_once(self):
|
||||
"""If the fresh manifest still fails the source check, the URL is authoritative:
|
||||
trust it instead of refetching at 1 Hz forever."""
|
||||
params = self._make_params({"bundles": [manifest_bundle("big", "bbb", is_big=True)]},
|
||||
{"bundles": [manifest_bundle("big2", "ccc", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
fetched = self._fetched(manifest_bundle("big", "bbb", is_big=True))
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", return_value=fetched) as fetch:
|
||||
first = fetcher.get_bundles_for_source("qcom")
|
||||
second = fetcher.get_bundles_for_source("qcom")
|
||||
fetch.assert_called_once_with("qcom")
|
||||
assert [bundle.ref for bundle in first] == ["bbb"]
|
||||
assert [bundle.ref for bundle in second] == ["bbb"]
|
||||
|
||||
def test_corrupt_cache_is_refetched(self):
|
||||
"""A cache that fails to parse (e.g. truncated/foreign JSON) must trigger a
|
||||
refetch instead of raising every loop and never recovering."""
|
||||
corrupt = {"bundles": [{"short_name": "broken"}]} # missing required fields
|
||||
params = self._make_params(corrupt, {"bundles": [manifest_bundle("big", "bbb", is_big=True)]})
|
||||
fetcher = ModelFetcher(params)
|
||||
fetched = self._fetched(manifest_bundle("small", "aaa"))
|
||||
with mock.patch.object(fetcher, "_fetch_and_cache_models", return_value=fetched) as fetch:
|
||||
bundles = fetcher.get_bundles_for_source("qcom")
|
||||
fetch.assert_called_once_with("qcom")
|
||||
assert [bundle.ref for bundle in bundles] == ["aaa"]
|
||||
|
||||
|
||||
class TestActiveBundleValidation(OpenpilotTestCase):
|
||||
"""Validation is per-slot: a failed fetch (empty bundle list) must not reset a slot,
|
||||
and resetting one slot must not stomp the runner cache derived from the other."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
helpers._LAST_VALIDATED_RAW.clear()
|
||||
|
||||
@staticmethod
|
||||
def _raw_bundle(ref: str, runner: int | None = None) -> dict:
|
||||
bundle = custom.ModelManagerSP.ModelBundle.new_message()
|
||||
bundle.ref = ref
|
||||
bundle.minimumSelectorVersion = 18
|
||||
if runner is not None:
|
||||
bundle.runner = runner
|
||||
return bundle.to_dict()
|
||||
|
||||
def _params(self, qcom=None, chestnut=None):
|
||||
params = mock.MagicMock()
|
||||
|
||||
def get(key, *args, **kwargs):
|
||||
return {"ModelManager_ActiveBundle": qcom, "ModelManager_ActiveBundleChestnut": chestnut}.get(key)
|
||||
|
||||
params.get.side_effect = get
|
||||
return params
|
||||
|
||||
def test_empty_catalog_does_not_reset_slot(self):
|
||||
params = self._params(qcom=self._raw_bundle("small"))
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=False):
|
||||
validate_active_bundles(params, {"qcom": [], "chestnut": []})
|
||||
params.remove.assert_not_called()
|
||||
|
||||
def test_reset_recomputes_runner_from_surviving_slot(self):
|
||||
tinygrad = int(custom.ModelManagerSP.Runner.tinygrad)
|
||||
big_raw = self._raw_bundle("big", runner=tinygrad)
|
||||
params = self._params(qcom=self._raw_bundle("gone"), chestnut=big_raw)
|
||||
catalog = {"qcom": [custom.ModelManagerSP.ModelBundle(**self._raw_bundle("other"))],
|
||||
"chestnut": [custom.ModelManagerSP.ModelBundle(**big_raw)]}
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=True):
|
||||
validate_active_bundles(params, catalog)
|
||||
params.remove.assert_called_once_with("ModelManager_ActiveBundle")
|
||||
runner_puts = [call for call in params.put.call_args_list if call.args[0] == "ModelRunnerTypeCache"]
|
||||
assert [call.args[1] for call in runner_puts] == [tinygrad]
|
||||
|
||||
|
||||
class TestActiveBundleSelection(OpenpilotTestCase):
|
||||
"""The effective active bundle is the active source's slot: chestnut when a GPU is
|
||||
present, qcom otherwise. An empty active slot means the hardware default (stock
|
||||
runner), never the other slot's pick - modeld_v2 requires a real bundle."""
|
||||
|
||||
@staticmethod
|
||||
def _raw_bundle(ref: str) -> dict:
|
||||
bundle = custom.ModelManagerSP.ModelBundle.new_message()
|
||||
bundle.ref = ref
|
||||
bundle.minimumSelectorVersion = 18
|
||||
return bundle.to_dict()
|
||||
|
||||
def _params(self, qcom=None, chestnut=None):
|
||||
params = mock.MagicMock()
|
||||
|
||||
def get(key, *args, **kwargs):
|
||||
if key == "ModelManager_ActiveBundle":
|
||||
return qcom
|
||||
if key == "ModelManager_ActiveBundleChestnut":
|
||||
return chestnut
|
||||
return None
|
||||
|
||||
params.get.side_effect = get
|
||||
return params
|
||||
|
||||
def test_selected_bundle_is_per_slot(self):
|
||||
params = self._params(qcom=self._raw_bundle("small"), chestnut=self._raw_bundle("big"))
|
||||
assert get_selected_bundle(params, "qcom").ref == "small"
|
||||
assert get_selected_bundle(params, "chestnut").ref == "big"
|
||||
|
||||
def test_no_gpu_uses_qcom_slot(self):
|
||||
params = self._params(qcom=self._raw_bundle("small"), chestnut=self._raw_bundle("big"))
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=False):
|
||||
assert get_active_bundle(params).ref == "small"
|
||||
|
||||
def test_gpu_uses_chestnut_slot(self):
|
||||
params = self._params(qcom=self._raw_bundle("small"), chestnut=self._raw_bundle("big"))
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=True):
|
||||
assert get_active_bundle(params).ref == "big"
|
||||
|
||||
def test_gpu_without_big_selection_is_hardware_default(self):
|
||||
params = self._params(qcom=self._raw_bundle("small"), chestnut=None)
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=True):
|
||||
assert get_active_bundle(params) is None
|
||||
|
||||
|
||||
class TestEffectiveSource(OpenpilotTestCase):
|
||||
"""One gate decides the active source. With no flags it is runtime truth (GPU
|
||||
attached); display callers (mici) pass the ui_state flags, which additionally
|
||||
require the big model to be loading, active, or the device offroad. The active
|
||||
bundle is simply the selected bundle of that source."""
|
||||
|
||||
@staticmethod
|
||||
def _raw_bundle(ref: str) -> dict:
|
||||
bundle = custom.ModelManagerSP.ModelBundle.new_message()
|
||||
bundle.ref = ref
|
||||
bundle.minimumSelectorVersion = 18
|
||||
return bundle.to_dict()
|
||||
|
||||
def test_runtime_no_gpu(self):
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=False):
|
||||
assert get_active_source() == "qcom"
|
||||
|
||||
def test_runtime_gpu_present(self):
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=True):
|
||||
assert get_active_source() == "chestnut"
|
||||
|
||||
def test_display_offroad_gpu_present_shows_big(self):
|
||||
assert get_active_source(chestnut=True, chestnut_active=False, chestnut_loading=False, offroad=True) == "chestnut"
|
||||
|
||||
def test_display_onroad_gpu_loading_shows_big(self):
|
||||
assert get_active_source(chestnut=True, chestnut_active=False, chestnut_loading=True, offroad=False) == "chestnut"
|
||||
|
||||
def test_display_onroad_gpu_active_shows_big(self):
|
||||
assert get_active_source(chestnut=True, chestnut_active=True, chestnut_loading=False, offroad=False) == "chestnut"
|
||||
|
||||
def test_display_onroad_gpu_idle_shows_small(self):
|
||||
assert get_active_source(chestnut=True, chestnut_active=False, chestnut_loading=False, offroad=False) == "qcom"
|
||||
|
||||
def test_display_active_none_is_idle(self):
|
||||
assert get_active_source(chestnut=True, chestnut_active=None, chestnut_loading=False, offroad=False) == "qcom"
|
||||
|
||||
def test_active_bundle_follows_source(self):
|
||||
params = mock.MagicMock()
|
||||
params.get.side_effect = lambda key: {"ModelManager_ActiveBundle": self._raw_bundle("small"),
|
||||
"ModelManager_ActiveBundleChestnut": self._raw_bundle("big")}.get(key)
|
||||
with mock.patch("openpilot.sunnypilot.models.helpers.chestnut_present", return_value=False):
|
||||
assert get_active_bundle(params).ref == "small"
|
||||
assert get_selected_bundle(params, get_active_source(chestnut=True, chestnut_active=False,
|
||||
chestnut_loading=False, offroad=True)).ref == "big"
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('RUN_INTEGRATION_TESTS'), 'requires external network')
|
||||
class TestLiveModelManifest(OpenpilotTestCase):
|
||||
"""Every artifact and chunk URL in the published manifest must resolve."""
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import requests
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.sunnypilot.models.tinygrad_ref import get_tinygrad_ref
|
||||
from openpilot.sunnypilot.models.fetcher import ModelFetcher
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
|
||||
def fetch_tinygrad_ref():
|
||||
fetcher = ModelFetcher(Params())
|
||||
response = requests.get(fetcher.model_url, timeout=10)
|
||||
response = requests.get(ModelFetcher.MODEL_URL, timeout=10)
|
||||
response.raise_for_status()
|
||||
json_data = response.json()
|
||||
return json_data.get("tinygrad_ref")
|
||||
|
||||
|
After Width: | Height: | Size: 12 KiB |
@@ -10,29 +10,29 @@ void live_update_32(double *in_x, double *in_P, double *in_z, double *in_R, doub
|
||||
void live_update_13(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void live_update_14(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void live_update_33(double *in_x, double *in_P, double *in_z, double *in_R, double *in_ea);
|
||||
void live_H(double *in_vec, double *out_5926322025614992030);
|
||||
void live_err_fun(double *nom_x, double *delta_x, double *out_5043251176595415602);
|
||||
void live_inv_err_fun(double *nom_x, double *true_x, double *out_3360739843129809304);
|
||||
void live_H_mod_fun(double *state, double *out_8279386211598339514);
|
||||
void live_f_fun(double *state, double dt, double *out_6890687714462639744);
|
||||
void live_F_fun(double *state, double dt, double *out_7621965816561569981);
|
||||
void live_h_4(double *state, double *unused, double *out_3851734767229128263);
|
||||
void live_H_4(double *state, double *unused, double *out_5878769767090540838);
|
||||
void live_h_9(double *state, double *unused, double *out_2694197172040937469);
|
||||
void live_H_9(double *state, double *unused, double *out_1408449168173906632);
|
||||
void live_h_10(double *state, double *unused, double *out_7033125878671447195);
|
||||
void live_H_10(double *state, double *unused, double *out_65675330875969869);
|
||||
void live_h_12(double *state, double *unused, double *out_8799002316774637565);
|
||||
void live_H_12(double *state, double *unused, double *out_6186715929576277782);
|
||||
void live_h_35(double *state, double *unused, double *out_2868906334315872882);
|
||||
void live_H_35(double *state, double *unused, double *out_8932278961901291491);
|
||||
void live_h_32(double *state, double *unused, double *out_9199462926327450350);
|
||||
void live_H_32(double *state, double *unused, double *out_6730806947389842532);
|
||||
void live_h_13(double *state, double *unused, double *out_3826583407417889778);
|
||||
void live_H_13(double *state, double *unused, double *out_3672088104010170074);
|
||||
void live_h_14(double *state, double *unused, double *out_2694197172040937469);
|
||||
void live_H_14(double *state, double *unused, double *out_1408449168173906632);
|
||||
void live_h_33(double *state, double *unused, double *out_6802426037572342548);
|
||||
void live_H_33(double *state, double *unused, double *out_7684478583555780967);
|
||||
void live_H(double *in_vec, double *out_8536236811475430067);
|
||||
void live_err_fun(double *nom_x, double *delta_x, double *out_4614868058485758139);
|
||||
void live_inv_err_fun(double *nom_x, double *true_x, double *out_8573554928028298681);
|
||||
void live_H_mod_fun(double *state, double *out_6128852447133223565);
|
||||
void live_f_fun(double *state, double dt, double *out_7195534889995166041);
|
||||
void live_F_fun(double *state, double dt, double *out_9012508306389018670);
|
||||
void live_h_4(double *state, double *unused, double *out_2657657745771735915);
|
||||
void live_H_4(double *state, double *unused, double *out_1457735078816209632);
|
||||
void live_h_9(double *state, double *unused, double *out_181525824636861445);
|
||||
void live_H_9(double *state, double *unused, double *out_8744954014080657102);
|
||||
void live_h_10(double *state, double *unused, double *out_2940864223365932608);
|
||||
void live_H_10(double *state, double *unused, double *out_6591157835936482265);
|
||||
void live_h_12(double *state, double *unused, double *out_830811219903448800);
|
||||
void live_H_12(double *state, double *unused, double *out_4923523298226523364);
|
||||
void live_h_35(double *state, double *unused, double *out_1177115113523305926);
|
||||
void live_H_35(double *state, double *unused, double *out_2177960265901509655);
|
||||
void live_h_32(double *state, double *unused, double *out_8970203849717307468);
|
||||
void live_H_32(double *state, double *unused, double *out_5493453269239321848);
|
||||
void live_h_13(double *state, double *unused, double *out_1337448462981849436);
|
||||
void live_H_13(double *state, double *unused, double *out_2400089242629978824);
|
||||
void live_h_14(double *state, double *unused, double *out_181525824636861445);
|
||||
void live_H_14(double *state, double *unused, double *out_8744954014080657102);
|
||||
void live_h_33(double *state, double *unused, double *out_3078698583527751553);
|
||||
void live_H_33(double *state, double *unused, double *out_972596738737347949);
|
||||
void live_predict(double *in_x, double *in_P, double *in_Q, double dt);
|
||||
}
|
||||
@@ -252,4 +252,12 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
|
||||
AlertStatus.userPrompt, AlertSize.small,
|
||||
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
|
||||
},
|
||||
|
||||
EventNameSP.bigModelReady: {
|
||||
ET.PERMANENT: Alert(
|
||||
"Big Model Ready",
|
||||
"",
|
||||
AlertStatus.normal, AlertSize.small,
|
||||
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 2.),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ def getParamsMetadata() -> str:
|
||||
schema["capability_labels"] = CAPABILITY_LABELS
|
||||
schema["default_model"] = DEFAULT_MODEL
|
||||
schema["default_big_model"] = DEFAULT_BIG_MODEL
|
||||
schema["usbgpu_active"] = params.get_bool("UsbGpuActive")
|
||||
schema["chestnut_active"] = params.get_bool("ChestnutActive")
|
||||
raw = json.dumps(schema, separators=(",", ":")).encode("utf-8")
|
||||
return base64.b64encode(gzip.compress(raw)).decode("utf-8")
|
||||
except Exception:
|
||||
|
||||
@@ -65,6 +65,7 @@ def sp_stats(end_event):
|
||||
'MadsSteeringMode',
|
||||
'MadsUnifiedEngagementMode',
|
||||
'ModelManager_ActiveBundle',
|
||||
'ModelManager_ActiveBundleChestnut',
|
||||
'ModelManager_Favs',
|
||||
'EnableSunnylinkUploader',
|
||||
'SunnylinkEnabled',
|
||||
|
||||
@@ -84,6 +84,25 @@ def _migrate_tesla_mads_screen_button(_params):
|
||||
cloudlog.exception(f"Error migrating TeslaMadsScreenButton: {e}")
|
||||
|
||||
|
||||
def _migrate_model_bundle_slots(_params):
|
||||
# Pre-split, a chestnut user's big-model selection lived in the single
|
||||
# ActiveBundle. Seed both slots; validation drops whichever does not match
|
||||
# its own manifest.
|
||||
try:
|
||||
if _params.get("ModelManager_ActiveBundleChestnut") is not None:
|
||||
return
|
||||
if (chestnut_bundle := _params.get("ModelManager_ActiveBundleUSBGPU")) is not None:
|
||||
_params.put("ModelManager_ActiveBundleChestnut", chestnut_bundle, block=True)
|
||||
cloudlog.info("params_migration: seeded ModelManager_ActiveBundleChestnut from ModelManager_ActiveBundleUSBGPU")
|
||||
return
|
||||
if (bundle := _params.get("ModelManager_ActiveBundle")) is None:
|
||||
return
|
||||
_params.put("ModelManager_ActiveBundleChestnut", bundle, block=True)
|
||||
cloudlog.info("params_migration: seeded ModelManager_ActiveBundleChestnut from ModelManager_ActiveBundle")
|
||||
except Exception as e:
|
||||
cloudlog.exception(f"Error migrating model bundle slots: {e}")
|
||||
|
||||
|
||||
def run_migration(_params):
|
||||
# migrate OnroadScreenOffBrightness
|
||||
if _params.get("OnroadScreenOffBrightnessMigrated") != ONROAD_BRIGHTNESS_MIGRATION_VERSION:
|
||||
@@ -120,3 +139,6 @@ def run_migration(_params):
|
||||
|
||||
# seed TeslaMadsScreenButton for existing Tesla installs
|
||||
_migrate_tesla_mads_screen_button(_params)
|
||||
|
||||
# seed the chestnut model slot from the pre-split single slot
|
||||
_migrate_model_bundle_slots(_params)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.test import OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system.params_migration import _migrate_model_bundle_slots
|
||||
|
||||
|
||||
class TestModelBundleSlotMigration(OpenpilotTestCase):
|
||||
"""Pre-split, a chestnut user's big-model selection lived in the single ActiveBundle.
|
||||
The migration seeds both slots; per-source validation later drops whichever does not
|
||||
match its own manifest."""
|
||||
|
||||
def test_seeds_chestnut_slot_from_active_bundle(self):
|
||||
params = Params()
|
||||
bundle = {"ref": "big", "minimumSelectorVersion": 18}
|
||||
params.put("ModelManager_ActiveBundle", bundle, block=True)
|
||||
_migrate_model_bundle_slots(params)
|
||||
assert params.get("ModelManager_ActiveBundleChestnut") == bundle
|
||||
assert params.get("ModelManager_ActiveBundle") == bundle
|
||||
|
||||
def test_noop_when_chestnut_slot_already_set(self):
|
||||
params = Params()
|
||||
params.put("ModelManager_ActiveBundle", {"ref": "small"}, block=True)
|
||||
params.put("ModelManager_ActiveBundleChestnut", {"ref": "big"}, block=True)
|
||||
_migrate_model_bundle_slots(params)
|
||||
assert params.get("ModelManager_ActiveBundleChestnut") == {"ref": "big"}
|
||||
|
||||
def test_noop_when_no_selection(self):
|
||||
params = Params()
|
||||
_migrate_model_bundle_slots(params)
|
||||
assert params.get("ModelManager_ActiveBundleChestnut") is None
|
||||
@@ -16,7 +16,7 @@ from openpilot.common.utils import strip_deprecated_keys
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import DT_HW
|
||||
from openpilot.selfdrive.modeld.helpers import MODELS_DIR, usbgpu_compiled
|
||||
from openpilot.selfdrive.modeld.helpers import MODELS_DIR, chestnut_compiled
|
||||
from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert
|
||||
from openpilot.common.hardware import HARDWARE, COMMA_HARDWARE
|
||||
from openpilot.common.basedir import BASEDIR
|
||||
@@ -239,7 +239,7 @@ def hardware_thread(end_event, hw_queue) -> None:
|
||||
|
||||
fan_controller = FanController(int(1./DT_HW))
|
||||
chestnut = Chestnut()
|
||||
big_model_available = (MODELS_DIR / 'big_driving_supercombo.onnx').is_file() or usbgpu_compiled()
|
||||
big_model_available = (MODELS_DIR / 'big_driving_supercombo.onnx').is_file() or chestnut_compiled()
|
||||
|
||||
while not end_event.is_set():
|
||||
sm.update(PANDA_STATES_TIMEOUT)
|
||||
|
||||
@@ -8,12 +8,26 @@ from collections.abc import Callable
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.system.ui.lib.application import FontWeight
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.sunnypilot.lib.styles import style
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import ButtonActionSP
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.system.ui.widgets.label import ScrollState, UnifiedLabel
|
||||
from openpilot.system.ui.widgets.list_view import BUTTON_WIDTH, BUTTON_HEIGHT, TEXT_PADDING, _resolve_value
|
||||
|
||||
SCROLL_SPEED = 1.2 # stock is 0.8, boosted 50% to compensate for larger font (50 vs 32)
|
||||
SCROLL_REFERENCE_FPS = 60.
|
||||
|
||||
|
||||
class UnifiedLabelSP(UnifiedLabel):
|
||||
# stock scroll formula (0.8 / 60 * fps) is inverted — pre-correct so speed is constant px/sec
|
||||
def _render(self, _):
|
||||
if self._needs_scroll and self._scroll_state == ScrollState.SCROLLING:
|
||||
fps = gui_app.target_fps
|
||||
wrong_step = 0.8 / SCROLL_REFERENCE_FPS * fps
|
||||
correct_step = SCROLL_SPEED * SCROLL_REFERENCE_FPS / fps
|
||||
self._scroll_offset -= (correct_step - wrong_step)
|
||||
super()._render(_)
|
||||
|
||||
|
||||
class NoElideButtonAction(ButtonActionSP):
|
||||
def get_width_hint(self):
|
||||
@@ -21,14 +35,12 @@ class NoElideButtonAction(ButtonActionSP):
|
||||
|
||||
|
||||
class ScrollingButtonAction(ButtonActionSP):
|
||||
"""ButtonActionSP whose value scrolls instead of eliding when it doesn't fit."""
|
||||
|
||||
def __init__(self, text: str | Callable[[], str], width: int = style.BUTTON_ACTION_WIDTH,
|
||||
enabled: bool | Callable[[], bool] = True):
|
||||
super().__init__(text=text, width=width, enabled=enabled)
|
||||
self._value_label = UnifiedLabel("", font_size=style.ITEM_TEXT_FONT_SIZE, font_weight=FontWeight.NORMAL,
|
||||
text_color=self._value_color, scroll=True,
|
||||
alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE)
|
||||
self._value_label = UnifiedLabelSP("", font_size=style.ITEM_TEXT_FONT_SIZE, font_weight=FontWeight.NORMAL,
|
||||
text_color=self._value_color, scroll=True,
|
||||
alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE)
|
||||
|
||||
def set_value(self, value: str | Callable[[], str], color: rl.Color = style.ITEM_TEXT_VALUE_COLOR):
|
||||
if self.value != _resolve_value(value, ""):
|
||||
|
||||
@@ -16,6 +16,7 @@ from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.sunnypilot.lib.styles import style
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.system.ui.sunnypilot.lib.utils import UnifiedLabelSP
|
||||
from openpilot.system.ui.widgets.list_view import ItemAction
|
||||
|
||||
FONT_SIZE = style.ITEM_TEXT_FONT_SIZE
|
||||
@@ -24,6 +25,8 @@ ICON_PADDING = 12
|
||||
|
||||
BAR_WIDTH = 1100
|
||||
BAR_HEIGHT = 20
|
||||
SEGMENT_GAP = 24
|
||||
SEGMENT_NAME_MAX_WIDTH = 380
|
||||
BAR_GAP = 16
|
||||
BAR_RADIUS = BAR_HEIGHT / 2
|
||||
CAPSULE_POINTS = 24
|
||||
@@ -45,6 +48,8 @@ class DownloadStatusAction(ItemAction):
|
||||
super().__init__(width=BAR_WIDTH)
|
||||
self.name = ""
|
||||
self.status_text = ""
|
||||
self.segments: list[tuple[str, rl.Color, str | None, rl.Color | None]] | None = None
|
||||
self._segment_labels: list[UnifiedLabelSP] = []
|
||||
self.downloading = False
|
||||
self.text_color = rl.GRAY
|
||||
self.icon: str | None = None
|
||||
@@ -62,7 +67,8 @@ class DownloadStatusAction(ItemAction):
|
||||
alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT,
|
||||
alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE)
|
||||
|
||||
def update(self, name, downloading=False, progress=0.0, status_text="", text_color=rl.GRAY, icon=None, icon_color=None):
|
||||
def update(self, name, downloading=False, progress=0.0, status_text="", text_color=rl.GRAY, icon=None, icon_color=None, segments=None):
|
||||
self.segments = segments
|
||||
if downloading and not self.downloading:
|
||||
self._name_label.reset_shimmer()
|
||||
self._progress.x = progress
|
||||
@@ -85,11 +91,22 @@ class DownloadStatusAction(ItemAction):
|
||||
def get_width_hint(self) -> float:
|
||||
if self.downloading:
|
||||
return BAR_WIDTH
|
||||
if self.segments:
|
||||
return sum(total for _, _, total in self._measured_segments())
|
||||
width = measure_text_cached(self._font, self._idle_text, FONT_SIZE).x
|
||||
if self.icon:
|
||||
width += ICON_SIZE + ICON_PADDING
|
||||
return width
|
||||
|
||||
def _measured_segments(self):
|
||||
"""[(segment, text width, total width incl. icon and gap)]"""
|
||||
out = []
|
||||
for i, seg in enumerate(self.segments or []):
|
||||
text_width = min(measure_text_cached(self._font, seg[0], FONT_SIZE).x, SEGMENT_NAME_MAX_WIDTH)
|
||||
total = text_width + (ICON_PADDING + ICON_SIZE if seg[2] else 0) + (SEGMENT_GAP if i else 0)
|
||||
out.append((seg, text_width, total))
|
||||
return out
|
||||
|
||||
def _render(self, rect: rl.Rectangle):
|
||||
if self.downloading:
|
||||
self._render_downloading(rect)
|
||||
@@ -134,6 +151,8 @@ class DownloadStatusAction(ItemAction):
|
||||
|
||||
def _render_downloading(self, rect: rl.Rectangle):
|
||||
percent = f"{int(self._progress.x)}%"
|
||||
if self.status_text:
|
||||
percent = f"{self.status_text} {percent}"
|
||||
text_height = measure_text_cached(self._font, percent, FONT_SIZE).y
|
||||
top = rect.y + (rect.height - (text_height + BAR_GAP + BAR_HEIGHT)) / 2
|
||||
|
||||
@@ -148,6 +167,9 @@ class DownloadStatusAction(ItemAction):
|
||||
self._draw_fill(rail, max(0.0, min(rect.width, rect.width * (self._progress.x / 100.0))))
|
||||
|
||||
def _render_idle(self, rect: rl.Rectangle):
|
||||
if self.segments:
|
||||
self._render_segments(rect)
|
||||
return
|
||||
text = self._idle_text
|
||||
text_size = measure_text_cached(self._font, text, FONT_SIZE)
|
||||
right = rect.x + rect.width
|
||||
@@ -161,6 +183,29 @@ class DownloadStatusAction(ItemAction):
|
||||
rl.draw_text_ex(self._font, text, rl.Vector2(right - text_size.x, rect.y + (rect.height - text_size.y) / 2),
|
||||
FONT_SIZE, 0, self.text_color)
|
||||
|
||||
def _render_segments(self, rect: rl.Rectangle):
|
||||
measured = self._measured_segments()
|
||||
while len(self._segment_labels) < len(measured):
|
||||
self._segment_labels.append(UnifiedLabelSP("", font_size=FONT_SIZE, max_width=SEGMENT_NAME_MAX_WIDTH,
|
||||
scroll=True, wrap_text=False))
|
||||
x = rect.x + rect.width - sum(total for _, _, total in measured)
|
||||
for i, ((text, color, icon, icon_color), text_width, _) in enumerate(measured):
|
||||
if i:
|
||||
x += SEGMENT_GAP
|
||||
label = self._segment_labels[i]
|
||||
if label.text != text:
|
||||
label.set_text(text)
|
||||
label.set_text_color(color)
|
||||
text_height = measure_text_cached(self._font, text, FONT_SIZE).y
|
||||
label.set_position(x, rect.y + (rect.height - text_height) / 2)
|
||||
label.render()
|
||||
x += text_width
|
||||
if icon:
|
||||
texture = gui_app.texture(icon, ICON_SIZE, ICON_SIZE, keep_aspect_ratio=True)
|
||||
rl.draw_texture_v(texture, rl.Vector2(x + ICON_PADDING, rect.y + (rect.height - texture.height) / 2),
|
||||
icon_color or color)
|
||||
x += ICON_PADDING + ICON_SIZE
|
||||
|
||||
|
||||
def download_status_item(title):
|
||||
return ListItemSP(title=title, action_item=DownloadStatusAction(), title_color=style.ITEM_TEXT_COLOR)
|
||||
|
||||