From 544b9c0d6c6d51d366ed511ae648d109d1bde0eb Mon Sep 17 00:00:00 2001 From: ryan Date: Sun, 15 Nov 2026 17:28:58 +0100 Subject: [PATCH] leapmotor: add the Leapmotor B10 port to Dom Car code, DBC, fingerprints and panda safety from the opendbc Leapmotor port (commaai/opendbc#3936), with alpha openpilot longitudinal and the low-speed ramp boost to 56 steps. Adapted to Dom: - safety mode 40 (39 is Tesla pre-AP here) - CRC-8H2F through crc8_update, rx checks const - CarSpecs mass (Dom still uses it) - no steering-wheel button events for wheel_actions --- opendbc_repo/opendbc/can/dbc.py | 3 + opendbc_repo/opendbc/car/car.capnp | 1 + .../opendbc/car/leapmotor/__init__.py | 0 .../opendbc/car/leapmotor/carcontroller.py | 96 +++++ .../opendbc/car/leapmotor/carstate.py | 107 ++++++ .../opendbc/car/leapmotor/fingerprints.py | 19 + .../opendbc/car/leapmotor/interface.py | 34 ++ .../opendbc/car/leapmotor/leapmotorcan.py | 143 ++++++++ .../opendbc/car/leapmotor/tests/__init__.py | 0 .../car/leapmotor/tests/test_leapmotor.py | 308 ++++++++++++++++ opendbc_repo/opendbc/car/leapmotor/values.py | 112 ++++++ opendbc_repo/opendbc/car/tests/routes.py | 3 + .../opendbc/car/tests/test_fw_fingerprint.py | 3 +- .../opendbc/car/torque_data/override.toml | 3 + opendbc_repo/opendbc/car/values.py | 3 +- opendbc_repo/opendbc/dbc/leapmotor_b10.dbc | 213 +++++++++++ opendbc_repo/opendbc/safety/declarations.h | 2 + opendbc_repo/opendbc/safety/modes/leapmotor.h | 222 ++++++++++++ opendbc_repo/opendbc/safety/safety.h | 2 + opendbc_repo/opendbc/safety/tests/common.py | 4 + .../opendbc/safety/tests/test_leapmotor.py | 335 ++++++++++++++++++ .../starpilot/controllers/wheel_actions.py | 2 +- 22 files changed, 1612 insertions(+), 3 deletions(-) create mode 100644 opendbc_repo/opendbc/car/leapmotor/__init__.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/carcontroller.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/carstate.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/fingerprints.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/interface.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/leapmotorcan.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/tests/__init__.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/tests/test_leapmotor.py create mode 100644 opendbc_repo/opendbc/car/leapmotor/values.py create mode 100644 opendbc_repo/opendbc/dbc/leapmotor_b10.dbc create mode 100644 opendbc_repo/opendbc/safety/modes/leapmotor.h create mode 100644 opendbc_repo/opendbc/safety/tests/test_leapmotor.py diff --git a/opendbc_repo/opendbc/can/dbc.py b/opendbc_repo/opendbc/can/dbc.py index ba1d62e488..274f961516 100644 --- a/opendbc_repo/opendbc/can/dbc.py +++ b/opendbc_repo/opendbc/can/dbc.py @@ -26,6 +26,7 @@ from opendbc.car.psa.psacan import psa_checksum from opendbc.car.rivian.riviancan import rivian_checksum from opendbc.car.ford.fordcan import FORD_CHECKSUM_FIELDS, ford_checksum from opendbc.car.mg.mgcan import mg_checksum +from opendbc.car.leapmotor.leapmotorcan import leapmotor_checksum class SignalType: @@ -281,6 +282,8 @@ def get_checksum_state(dbc_name: str) -> ChecksumState | None: return ChecksumState(SignalType.BODY_CHECKSUM, body_checksum) elif dbc_name.startswith("tesla_model3_party"): return ChecksumState(SignalType.TESLA_CHECKSUM, tesla_checksum, tesla_setup_signal) + elif dbc_name.startswith("leapmotor_"): + return ChecksumState(SignalType.VOLKSWAGEN_MQB_MEB_CHECKSUM, leapmotor_checksum) elif dbc_name.startswith("psa_"): return ChecksumState(SignalType.PSA_CHECKSUM, psa_checksum) elif dbc_name.startswith("byd_"): diff --git a/opendbc_repo/opendbc/car/car.capnp b/opendbc_repo/opendbc/car/car.capnp index f1013236aa..2e4998a538 100644 --- a/opendbc_repo/opendbc/car/car.capnp +++ b/opendbc_repo/opendbc/car/car.capnp @@ -651,6 +651,7 @@ struct CarParams { bmw @37; mg @38; teslaPreap @39; + leapmotor @40; } enum SteerControlType { diff --git a/opendbc_repo/opendbc/car/leapmotor/__init__.py b/opendbc_repo/opendbc/car/leapmotor/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/car/leapmotor/carcontroller.py b/opendbc_repo/opendbc/car/leapmotor/carcontroller.py new file mode 100644 index 0000000000..4b733975e0 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/carcontroller.py @@ -0,0 +1,96 @@ +import math +import numpy as np + +from opendbc.can import CANPacker +from opendbc.car import Bus +from opendbc.car.interfaces import CarControllerBase +from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_vm +from opendbc.car.leapmotor import leapmotorcan +from opendbc.car.leapmotor.values import CarControllerParams +from opendbc.car.vehicle_model import VehicleModel + + +def get_safety_CP(): + # the safety model's vehicle-model limits are computed for this platform + from opendbc.car.leapmotor.interface import CarInterface + return CarInterface.get_non_essential_params("LEAPMOTOR_B10") + + +class CarController(CarControllerBase): + """Replaces the camera's ADAS_LKA (0x83) with a copy carrying openpilot's angle request, and cancels the + stock ACC through the camera's copy of POWERTRAIN_STATE when openpilot disengages.""" + + def __init__(self, dbc_names, CP): + super().__init__(dbc_names, CP) + self.packer = CANPacker(dbc_names[Bus.pt]) + self.apply_angle_last = 0. + self.lcc_ramp = leapmotorcan.LCC_RAMP_IDLE + self.lat_active_last = False + self.VM = VehicleModel(get_safety_CP()) + self.adas_lka_idle = leapmotorcan.decode_adas_lka_idle() + self.ramp_boost = 0 + + def update_ramp_boost(self, lat_active: bool, CS) -> int: + """Extra LCC_RAMP steps: one more per frame while the wheel lags the command at low speed, one fewer once it is + back (see CarControllerParams.RAMP_BOOST_LAG).""" + if not lat_active or CS.out.vEgoRaw * 3.6 > CarControllerParams.RAMP_BOOST_MAX_SPEED: + return 0 + behind = abs(self.apply_angle_last - CS.out.steeringAngleDeg) + boost = self.ramp_boost + if behind > CarControllerParams.RAMP_BOOST_LAG: + boost += 1 + elif behind < CarControllerParams.RAMP_BOOST_CAUGHT_UP: + boost -= 1 + return min(max(boost, 0), leapmotorcan.LCC_RAMP_STEPS_BOOST_MAX - leapmotorcan.LCC_RAMP_STEPS_MIN) + + def long_accel(self, CC, camera_lka: dict) -> float | None: + """openpilot's acceleration request for ADAS_LKA, or None to send the camera's. + + Only while the stock ACC is engaged (ACC_STATE 3): the camera keeps engagement, the standstill hold and the + accelerator override (ACC_STATE 1), and its request goes through unchanged then. When the camera asks for hard + braking, openpilot never asks for less. + """ + if not (self.CP.openpilotLongitudinalControl and CC.longActive and int(camera_lka["ACC_STATE"]) == 3): + return None + accel = float(np.clip(CC.actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)) + camera_accel = float(camera_lka["ACC_ACCEL_REQ"]) + if camera_accel <= CarControllerParams.STOCK_BRAKE_PASSTHROUGH: + accel = min(accel, camera_accel) + return accel + + def update(self, CC, CS, now_nanos): + actuators = CC.actuators + can_sends = [] + # like the stock LCC, let go while the driver steers (the EPS flags it), then ramp back in + lat_active = CC.latActive and not CS.driver_override + # take the wheel back only once it is near the angle openpilot wants: after the driver let go mid-turn at walking + # pace with the wheel at +308 deg and the model at +24, the EPS swung it to -203 deg in 3 s + if lat_active and not self.lat_active_last: + lat_active = abs(actuators.steeringAngleDeg - CS.out.steeringAngleDeg) < CarControllerParams.TAKE_BACK_MAX_ANGLE_ERROR + # and within the angle openpilot may command at this speed: otherwise the first frame jumps to that limit, the + # panda blocks it, and the missing frame cancels ACC + if CS.out.vEgoRaw > 1.: + max_angle = get_max_angle_vm(CS.out.vEgoRaw, self.VM, CarControllerParams) + lat_active = lat_active and abs(CS.out.steeringAngleDeg) < max_angle - 1.0 + + if self.frame % CarControllerParams.STEER_STEP == 0: + camera_lka = CS.adas_lka if CS.adas_lka is not None else self.adas_lka_idle + self.apply_angle_last = apply_steer_angle_limits_vm(actuators.steeringAngleDeg, self.apply_angle_last, CS.out.vEgoRaw, + CS.out.steeringAngleDeg, lat_active, CarControllerParams, self.VM) + lat_accel = self.VM.calc_curvature(math.radians(self.apply_angle_last), CS.out.vEgoRaw, 0.) * CS.out.vEgoRaw ** 2 + self.ramp_boost = self.update_ramp_boost(lat_active, CS) + self.lcc_ramp = leapmotorcan.lcc_ramp_next(self.lcc_ramp, lat_active, + leapmotorcan.lcc_ramp_target(lat_accel, CS.out.vEgoRaw * 3.6, self.ramp_boost)) + can_sends.append(leapmotorcan.create_steering_control(self.packer, camera_lka, self.apply_angle_last, lat_active, + self.lcc_ramp, self.long_accel(CC, camera_lka))) + + # cancel stock ACC when openpilot asks (it is engaged with ACC, so it cancels ACC whenever it disengages) + if CC.cruiseControl.cancel and self.frame % CarControllerParams.STEER_STEP == 0 and CS.powertrain_state is not None: + can_sends.append(leapmotorcan.create_cancel(self.packer, CS.powertrain_state)) + + self.lat_active_last = lat_active + new_actuators = actuators.as_builder() + new_actuators.steeringAngleDeg = self.apply_angle_last + + self.frame += 1 + return new_actuators, can_sends diff --git a/opendbc_repo/opendbc/car/leapmotor/carstate.py b/opendbc_repo/opendbc/car/leapmotor/carstate.py new file mode 100644 index 0000000000..554af0e732 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/carstate.py @@ -0,0 +1,107 @@ +from opendbc.car import DT_CTRL, Bus, structs +from opendbc.can.parser import CANParser +from opendbc.car.common.conversions import Conversions as CV +from opendbc.car.common.filter_simple import FirstOrderFilter +from opendbc.car.interfaces import CarStateBase +from opendbc.car.leapmotor.values import DBC, CarControllerParams + +GearShifter = structs.CarState.GearShifter +GEARS = {0: GearShifter.park, 1: GearShifter.reverse, 2: GearShifter.neutral, 3: GearShifter.drive} + + +class CarState(CarStateBase): + def __init__(self, CP): + super().__init__(CP) + self.steering_angle_last = 0.0 + self.adas_lka: dict | None = None + self.lka_received_seen = False + self.driver_override_frames = 0 + self.driver_override = False + # the EPS's own effort as it shows up in the driver-torque reading, which lags it (see EPS_TORQUE_LAG) + self.eps_torque_lagged = FirstOrderFilter(0., CarControllerParams.EPS_TORQUE_LAG, DT_CTRL) + self.powertrain_state: dict | None = None + + def update(self, can_parsers) -> structs.CarState: + cp = can_parsers[Bus.pt] + cp_cam = can_parsers[Bus.cam] + ret = structs.CarState() + + # speed + self.parse_wheel_speeds(ret, + cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_FL'], + cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_FR'], + cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_RL'], + cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_RR'], + ) + ret.vEgoCluster = cp.vl['CLUSTER']['DISPLAY_SPEED'] * CV.KPH_TO_MS + ret.standstill = ret.vEgoRaw < 0.01 + ret.yawRate = cp.vl['IMU']['YAW_RATE'] * CV.DEG_TO_RAD + + # pedals + ret.gasPressed = cp.vl['VEHICLE_STATE']['ACCEL_PEDAL'] > 0 + ret.brakePressed = bool(cp.vl['VEHICLE_STATE']['BRAKE_PRESSED']) + + # steering: the EPS speed field has no sign, so take the sign from the angle change + angle = cp.vl['EPS_STEERING']['STEER_ANGLE'] + sign = 1.0 if angle > self.steering_angle_last else (-1.0 if angle < self.steering_angle_last else 0.0) + ret.steeringAngleDeg = angle + ret.steeringRateDeg = sign * cp.vl['EPS_STEERING']['STEER_SPEED_ABS'] + self.steering_angle_last = angle + ret.steeringTorqueEps = cp.vl['EPS_STEERING']['STEER_TORQUE_EPS'] + # the driver's torque: the reading minus the share that follows the EPS's own effort + ret.steeringTorque = cp.vl['EPS_STEERING']['STEER_TORQUE_DRIVER'] + \ + self.eps_torque_lagged.update(ret.steeringTorqueEps) / CarControllerParams.EPS_TORQUE_PER_DRIVER_TORQUE + # the torque reading is coarse: during an LCC override it only reached 2-3, but the EPS flagged the override itself. + # The EPS also sets that flag whenever the car is above about 121 km/h, with or without the driver (99% of frames + # above 121 km/h on a stock drive, and openpilot's own drive at 125 km/h), so above 118 km/h only the torque counts. + eps_override = cp.vl['EPS_STEERING']['DRIVER_OVERRIDE'] and ret.vEgoRaw < 118 * CV.KPH_TO_MS + self.driver_override_frames = self.driver_override_frames + 1 if eps_override else 0 + torque_pressed = self.update_steering_pressed(abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE, 5) + ret.steeringPressed = torque_pressed or self.driver_override_frames >= 2 + # When to let go of the wheel: on the EPS's own flag, like stock LCC, or on the driver's torque. Not on the raw + # reading, which read 5-7 whenever the EPS pushed 65-95 in a curve: letting go on it dropped the EPS to 0 and back + # every 0.7 s (41 times in 14 min). The flag alone is not enough: above 118 km/h it is always set, and at walking + # pace it stayed off while openpilot pulled the wheel from +324 to -203 deg through the driver's hands. + self.driver_override = self.driver_override_frames >= 2 or torque_pressed + # The EPS reports whether it receives ADAS_LKA (0x83): losing it after it was received means our steering frame is + # missing or rejected (camera-unplug test). Not set before the camera's first frame after ignition. + lka_received = bool(cp.vl['EPS_STEERING']['ADAS_LKA_RECEIVED']) + self.lka_received_seen = self.lka_received_seen or lka_received + ret.steerFaultTemporary = self.lka_received_seen and not lka_received + + # gear + ret.gearShifter = GEARS.get(int(cp.vl['VEHICLE_STATE']['GEAR']), GearShifter.unknown) + + # body + ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp(50, cp.vl['BODY_CONTROL']['BLINKER_LEFT'] == 1, + cp.vl['BODY_CONTROL']['BLINKER_RIGHT'] == 1) + ret.doorOpen = bool(cp.vl['BODY_CONTROL']['DRIVER_DOOR_OPEN']) + ret.seatbeltUnlatched = bool(cp.vl['SEATBELT']['DRIVER_SEATBELT_UNLATCHED']) + + # blind-spot radars: silent when stopped, so they are not timeout-checked (see get_can_parsers) + ret.leftBlindspot = bool(cp.vl['BSD_LEFT']['OBJECT_DETECTED']) + ret.rightBlindspot = bool(cp.vl['BSD_RIGHT']['OBJECT_DETECTED']) + + # stock ACC / LCC, read from the camera side + ret.cruiseState.enabled = bool(cp.vl['POWERTRAIN_STATE']['ASSIST_ENGAGED']) + # latest VCU frame, copied by the controller to cancel ACC; None until received + self.powertrain_state = dict(cp.vl['POWERTRAIN_STATE']) if cp.ts_nanos['POWERTRAIN_STATE']['COUNTER'] > 0 else None + # ACC_STATE: 1 not ready (Park, brake, accelerator override), 2 ready, 3 engaged. Engaged also counts as + # available so that an accelerator override (state 1 while engaged) does not raise wrongCarMode + ret.cruiseState.available = ret.cruiseState.enabled or int(cp_cam.vl['ADAS_LKA']['ACC_STATE']) in (2, 3) + ret.cruiseState.speed = cp_cam.vl['ADAS_LKA']['ACC_SET_SPEED'] * CV.KPH_TO_MS + ret.cruiseState.speedCluster = ret.cruiseState.speed + ret.cruiseState.standstill = ret.cruiseState.enabled and ret.standstill + # the camera's forward collision warning, shown by openpilot too + ret.stockFcw = bool(cp_cam.vl['ROAD_SIGNS']['FCW']) + # latest camera frame, rebuilt by the controller; None until the camera's 0x83 has been received + self.adas_lka = dict(cp_cam.vl['ADAS_LKA']) if cp_cam.ts_nanos['ADAS_LKA']['COUNTER'] > 0 else None + + return ret + + @staticmethod + def get_can_parsers(CP): + return { + Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], [("BSD_LEFT", float('nan')), ("BSD_RIGHT", float('nan'))], 0), + Bus.cam: CANParser(DBC[CP.carFingerprint][Bus.pt], [], 2), + } diff --git a/opendbc_repo/opendbc/car/leapmotor/fingerprints.py b/opendbc_repo/opendbc/car/leapmotor/fingerprints.py new file mode 100644 index 0000000000..7285b7f469 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/fingerprints.py @@ -0,0 +1,19 @@ +""" AUTO-FORMATTED USING opendbc/car/debug/format_fingerprints.py, EDIT STRUCTURE THERE.""" +from opendbc.car.structs import CarParams +from opendbc.car.leapmotor.values import CAR + +Ecu = CarParams.Ecu + +FW_VERSIONS = { + CAR.LEAPMOTOR_B10: { + (Ecu.eps, 0x735, None): [ + b'3401100-AG01\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x736, None): [ + b'3565101-AG03\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x756, None): [ + b'8021010-AH01\x00\x00\x00\x00\x00\x00\x00', + ], + }, +} diff --git a/opendbc_repo/opendbc/car/leapmotor/interface.py b/opendbc_repo/opendbc/car/leapmotor/interface.py new file mode 100644 index 0000000000..32a18e0142 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/interface.py @@ -0,0 +1,34 @@ +from opendbc.car import structs, get_safety_config +from opendbc.car.interfaces import CarInterfaceBase +from opendbc.car.leapmotor.carcontroller import CarController +from opendbc.car.leapmotor.carstate import CarState +from opendbc.car.leapmotor.values import LeapmotorSafetyFlags + + +class CarInterface(CarInterfaceBase): + CarState = CarState + CarController = CarController + + @staticmethod + def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams: + ret.brand = 'leapmotor' + + ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.leapmotor)] + # The camera's angle request (ADAS_LKA.STEER_ANGLE_REQ) leads the measured angle by 70-100 ms during LCC + ret.steerControlType = structs.CarParams.SteerControlType.angle + ret.steerActuatorDelay = 0.15 + ret.steerLimitTimer = 0.4 + ret.steerAtStandstill = False + + ret.radarUnavailable = True + + # Alpha longitudinal: the stock ACC keeps engagement, set speed (knob), cancel and the standstill hold; openpilot + # only replaces its acceleration request in ADAS_LKA, which openpilot already sends for steering. + ret.alphaLongitudinalAvailable = True + if alpha_long: + ret.openpilotLongitudinalControl = True + ret.safetyConfigs[0].safetyParam |= LeapmotorSafetyFlags.LONG_CONTROL.value + # the stock request leads the measured acceleration by about 0.2-0.25 s + ret.longitudinalActuatorDelay = 0.25 + + return ret diff --git a/opendbc_repo/opendbc/car/leapmotor/leapmotorcan.py b/opendbc_repo/opendbc/car/leapmotor/leapmotorcan.py new file mode 100644 index 0000000000..32ee085b3a --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/leapmotorcan.py @@ -0,0 +1,143 @@ +from opendbc.car.crc import CRC8H2F + +# AUTOSAR E2E Profile 2 constants, one per counter value, for each message: the same algorithm as +# opendbc's volkswagen_mqb_meb_checksum. Learned from logs of a 2025 global-market Leapmotor B10 and +# exact on every frame tested from 3 other routes on 2 other days. +LEAPMOTOR_E2E_CONSTANTS: dict[int, list[int]] = { + 0x083: [0xCD, 0x81, 0x0A, 0xC1, 0x99, 0x7F, 0x8D, 0x05, 0x3B, 0xA2, 0x43, 0xD2, 0xB6, 0x72, 0x2A, 0xD9], + 0x084: [0x5A, 0x77, 0x5F, 0xEA, 0x3F, 0xCD, 0xF9, 0x2E, 0x34, 0xF1, 0x2C, 0x81, 0x60, 0x37, 0xC6, 0x5B], + 0x0B1: [0x49, 0x56, 0x0E, 0x67, 0x81, 0x1E, 0x76, 0x9F, 0xBF, 0xC1, 0xE5, 0x6C, 0x96, 0x83, 0x7F, 0xC2], + 0x0B6: [0x71, 0x0D, 0x0B, 0xC2, 0x08, 0xC6, 0x63, 0x4B, 0x3F, 0x2B, 0x06, 0x10, 0xF0, 0xD2, 0x87, 0x0D], + 0x0B7: [0xEB, 0x4E, 0xAE, 0xCE, 0x79, 0x7C, 0x52, 0x03, 0x6A, 0x84, 0xC2, 0x3A, 0x0A, 0x64, 0x2F, 0x17], + 0x0B8: [0xB9, 0x24, 0xDD, 0x54, 0x98, 0xE5, 0xB7, 0x87, 0x51, 0xDB, 0x71, 0x31, 0xF9, 0x26, 0x43, 0x6D], + 0x0CB: [0x44, 0x73, 0x30, 0x2E, 0xA7, 0xAE, 0x40, 0x96, 0x33, 0x58, 0x84, 0x36, 0xF1, 0x43, 0xBF, 0x0A], + 0x0CD: [0x93, 0x33, 0x70, 0x1A, 0x9A, 0xB5, 0xEA, 0x04, 0x7E, 0xD4, 0xB6, 0x9D, 0x8A, 0x2E, 0x18, 0x41], + 0x0FA: [0x96, 0x97, 0x8B, 0x02, 0x69, 0xBB, 0x54, 0xE6, 0x4E, 0x46, 0x8D, 0x7B, 0xEA, 0x87, 0xE9, 0xB3], + 0x0FD: [0x53, 0x58, 0x37, 0xDA, 0x94, 0x57, 0x79, 0x27, 0x8D, 0xDD, 0xD0, 0x39, 0x16, 0x84, 0x07, 0xAF], + 0x134: [0x1A, 0x04, 0x9D, 0x41, 0xAB, 0x01, 0x5B, 0x2A, 0x8F, 0x6E, 0x46, 0xD0, 0xD8, 0xA8, 0x47, 0x2D], + 0x138: [0xC1, 0x05, 0xD2, 0xD9, 0xAE, 0x93, 0xB1, 0x90, 0x42, 0x7C, 0x60, 0x33, 0x46, 0xB8, 0x6A, 0xE1], + 0x142: [0x0E, 0x1E, 0xBF, 0x6C, 0x7F, 0xFA, 0xC0, 0x14, 0x8A, 0xD2, 0x52, 0x3C, 0x8B, 0xA6, 0x92, 0xAD], + 0x182: [0xE8, 0x40, 0x60, 0xDE, 0xC2, 0xAC, 0xE3, 0xA4, 0x3D, 0x88, 0xD1, 0xEE, 0x51, 0x16, 0xAD, 0x49], + 0x183: [0xF7, 0xC0, 0x40, 0xA6, 0xA5, 0xDE, 0x62, 0x1C, 0xAC, 0x5A, 0x4F, 0xA4, 0xE5, 0x18, 0x88, 0x08], + 0x184: [0xD9, 0x90, 0x33, 0xE1, 0x3A, 0x1A, 0xDF, 0xC6, 0xB5, 0xDC, 0xEE, 0x04, 0xFA, 0xD7, 0xD4, 0x99], + 0x185: [0x5D, 0x96, 0x82, 0x97, 0xB6, 0x8B, 0x24, 0x02, 0xEB, 0x69, 0x20, 0xBB, 0x77, 0x54, 0x86, 0xE6], + 0x186: [0xD3, 0xE0, 0x75, 0x85, 0x83, 0x55, 0x33, 0xE3, 0x4C, 0x9C, 0x91, 0x1D, 0x23, 0x1A, 0xA6, 0x16], + 0x18C: [0x0F, 0xD1, 0x6B, 0x63, 0x9E, 0x74, 0x22, 0x94, 0xD7, 0xA1, 0xE7, 0x6F, 0x9C, 0xCF, 0x96, 0xDD], + 0x18D: [0x61, 0x4B, 0x17, 0xE4, 0x78, 0x0B, 0xA1, 0xB4, 0xBC, 0xD8, 0xEA, 0xF5, 0xD9, 0x21, 0xCA, 0x86], + 0x227: [0x66, 0xF4, 0xA8, 0xC8, 0xBB, 0xA7, 0xAF, 0x2B, 0xD9, 0x7B, 0xC0, 0x50, 0x56, 0x0F, 0xCE, 0xED], + 0x228: [0xC5, 0x9E, 0x5D, 0xA1, 0xAC, 0x96, 0x1B, 0x21, 0x82, 0xEE, 0xF9, 0x97, 0xB1, 0xCB, 0xB6, 0x13], + 0x22A: [0xD5, 0xEB, 0xA2, 0x4E, 0x35, 0xAE, 0x51, 0xCE, 0x2D, 0x79, 0x9F, 0x7C, 0x34, 0x52, 0x09, 0x03], + 0x233: [0xA5, 0xE9, 0x85, 0x04, 0xFB, 0x6C, 0xDF, 0xF1, 0xDE, 0x90, 0xA8, 0xCB, 0xDD, 0x3B, 0x80, 0x87], + 0x241: [0x3F, 0xF7, 0x25, 0x5E, 0xAA, 0x47, 0x62, 0x61, 0x5B, 0x3C, 0xDC, 0xE5, 0x73, 0xB4, 0xED, 0x0D], + 0x243: [0xAC, 0xEE, 0xB6, 0x68, 0x4D, 0x69, 0x1F, 0x0E, 0x86, 0x34, 0x6F, 0x46, 0xED, 0x38, 0x11, 0x1E], + 0x24D: [0x0B, 0xC6, 0x3F, 0x10, 0x87, 0xF7, 0x42, 0xC5, 0x25, 0xDA, 0x40, 0x5E, 0x69, 0x4A, 0xAA, 0xA5], + 0x25A: [0x64, 0x5D, 0x7D, 0x96, 0x3D, 0x82, 0xB9, 0x97, 0xD5, 0xB6, 0xAA, 0x8B, 0x5A, 0x24, 0xB4, 0x02], + 0x290: [0x5C, 0x09, 0x71, 0x2F, 0x23, 0x73, 0x61, 0x25, 0x15, 0x48, 0x93, 0x65, 0x01, 0x4B, 0xAF, 0xF8], + 0x2A3: [0x14, 0x99, 0x49, 0x0B, 0x04, 0xD5, 0x74, 0xC6, 0x17, 0xF1, 0xE1, 0x3F, 0x50, 0x9B, 0xCB, 0x10], + 0x2D1: [0x0D, 0x28, 0xB8, 0x6B, 0x64, 0xDF, 0xEC, 0x74, 0xEA, 0x5D, 0x16, 0xD7, 0xC0, 0xC4, 0x7D, 0x6F], + 0x2D5: [0xB1, 0xB8, 0x77, 0xDF, 0xED, 0xEA, 0x53, 0xD7, 0xCD, 0x7D, 0x44, 0x2E, 0x40, 0x58, 0xF1, 0x66], + 0x2E1: [0x0E, 0x4D, 0xEE, 0x19, 0x73, 0x03, 0xAF, 0x8F, 0x32, 0x2E, 0x70, 0x31, 0x0B, 0xB3, 0xAE, 0x0E], + 0x2E5: [0x15, 0xB9, 0xD1, 0xC1, 0x72, 0x93, 0x8C, 0x60, 0x12, 0xE1, 0x01, 0x77, 0xC4, 0xBF, 0x1F, 0x11], + 0x331: [0x42, 0x4A, 0x62, 0xCD, 0x1B, 0xB4, 0xA0, 0x16, 0x14, 0xE8, 0x0A, 0x71, 0xEF, 0x24, 0x7C, 0xDF], + 0x332: [0x23, 0xC8, 0x53, 0x83, 0xD9, 0x64, 0xD5, 0x0F, 0x89, 0xC7, 0xAB, 0xB7, 0x65, 0x3F, 0x9A, 0x2D], + 0x3B0: [0x6D, 0x69, 0x44, 0xAC, 0x7A, 0x73, 0x06, 0x9C, 0x30, 0x17, 0x12, 0x2E, 0x8B, 0xEF, 0xA7, 0xCF], + 0x3B2: [0xA1, 0x21, 0x97, 0x13, 0x68, 0x02, 0x10, 0x43, 0xBB, 0x0E, 0x57, 0xE6, 0xDF, 0xBD, 0x46, 0x8E], + 0x3CE: [0x6C, 0x14, 0x3C, 0xAD, 0x93, 0x59, 0x1C, 0x4D, 0xD8, 0x33, 0x5D, 0x89, 0x7B, 0x08, 0x70, 0x34], +} + + +def leapmotor_checksum(address: int, sig, d: bytearray) -> int: + constants = LEAPMOTOR_E2E_CONSTANTS.get(address) + if constants is None: + return -1 # unknown message: never matches, so the frame is rejected rather than trusted + crc = 0xFF + for b in d[1:]: + crc = CRC8H2F[crc ^ b] + crc = CRC8H2F[crc ^ constants[d[1] & 0x0F]] + return crc ^ 0xFF + + +# LCC_RAMP (bytes 16-17 of ADAS_LKA): 0x7801 when LCC is not steering. While stock LCC steers it moves down a ladder of +# 254 per step, one step per frame: from idle to about 31 steps when LCC starts, then deeper with more lateral +# acceleration and speed, and back to idle at once when LCC stops. The step count sets how much torque the EPS may use +# (about +/-10 early in the ramp, +/-45 at 30-31 steps, +/-70 at 42-46). Stock LCC on 3 routes (142,234 frames): +# steps = 19.1 + 9.94 * |lateral accel| + 0.112 * speed (km/h), R^2 0.83, always 25-46. With the idle word the EPS only +# applied torque to the right; with a fixed 30 steps (0x5A3D) it could not hold a curve at 75 km/h (torque flat at 61). +LCC_RAMP_IDLE = 0x7801 +LCC_RAMP_STEP = 254 +LCC_RAMP_STEPS_MIN = 25 +LCC_RAMP_STEPS_MAX = 46 +# TEST: how deep the low-speed boost (CarControllerParams.RAMP_BOOST_LAG) may take the ramp, past the deepest stock value. +# On route 270 all 7 steerSaturated episodes (25-41 km/h) had the ramp at 46 steps with the wheel 2-6 deg behind the +# command. At 52 steps (route 273, 35 min engaged) the EPS used more torque, the wheel's mean lag in roundabouts fell +# from 6-15 to about 4 deg, and nothing faulted. 56 is the deepest value whose top 4 bits stay 4, as at 42-46 steps. +LCC_RAMP_STEPS_BOOST_MAX = 56 +# Ramp-in speed below LCC_RAMP_STEPS_MIN: stock moves one step per frame (0.5 s to 25 steps), and 50-68% of the frames +# where the wheel fell > 5 deg behind were in that ramp-in. Two steps per frame reaches 25 steps in 0.25 s; deeper than +# that, one step per frame as stock. Not seen from stock: the EPS's response to skipped ladder steps is untested. +LCC_RAMP_IN_STEPS_PER_FRAME = 2 + + +def lcc_ramp_target(lat_accel: float, v_ego_kph: float, extra_steps: int = 0) -> int: + """LCC_RAMP word that stock LCC would send for this lateral acceleration (m/s^2) and speed, extra_steps deeper, + never beyond LCC_RAMP_STEPS_BOOST_MAX (the stock formula alone stays within LCC_RAMP_STEPS_MAX).""" + steps = min(max(round(19.1 + 9.94 * abs(lat_accel) + 0.112 * v_ego_kph), LCC_RAMP_STEPS_MIN), LCC_RAMP_STEPS_MAX) + return LCC_RAMP_IDLE - LCC_RAMP_STEP * min(steps + max(extra_steps, 0), LCC_RAMP_STEPS_BOOST_MAX) + + +def lcc_ramp_next(word: int, lat_active: bool, target: int) -> int: + """Next LCC_RAMP value while steering: toward target, LCC_RAMP_IN_STEPS_PER_FRAME ladder steps per frame while ramping + in (shallower than LCC_RAMP_STEPS_MIN), one step per frame otherwise; straight back to idle when not steering.""" + if not lat_active: + return LCC_RAMP_IDLE + if word > target: + ramping_in = word > LCC_RAMP_IDLE - LCC_RAMP_STEP * LCC_RAMP_STEPS_MIN + return max(word - LCC_RAMP_STEP * (LCC_RAMP_IN_STEPS_PER_FRAME if ramping_in else 1), target) + if word < target: + return word + LCC_RAMP_STEP + return word + + +def create_steering_control(packer, camera_lka: dict, apply_angle: float, lat_active: bool, lcc_ramp: int = LCC_RAMP_IDLE, + accel: float | None = None): + """Rebuild ADAS_LKA (0x83) from the camera's latest frame, replacing only the steering fields. + + Every other field (ACC state, acceleration request, set speed, constants) is copied unchanged, so the + stock ACC keeps working while openpilot steers. The packer recomputes the E2E checksum and runs its own + counter, since the EPS only ever sees openpilot's frames once the camera's are blocked. + While steering, LCC_RAMP carries lcc_ramp (see lcc_ramp_next); otherwise it is the camera's. + With openpilot longitudinal, accel (m/s^2) replaces the camera's ACC_ACCEL_REQ; None keeps the camera's. + """ + values = {k: v for k, v in camera_lka.items() if k not in ("CHECKSUM", "COUNTER")} + if accel is not None: + values["ACC_ACCEL_REQ"] = accel + values["STEER_ANGLE_REQ"] = apply_angle + values["LCC_STEERING_ACTIVE_COPY"] = 1 if lat_active else 0 + if lat_active: + values["LCC_RAMP"] = lcc_ramp + return packer.make_can_msg("ADAS_LKA", 0, values) + + +STALK_PUSH_UP_CANCEL = 3 + +# A real ADAS_LKA frame from the camera with ACC and LCC off, used until the camera's first frame is received +ADAS_LKA_IDLE = bytes.fromhex("260500446411E100007D00700043E4000178007D000000000000000000000000") + + +def decode_adas_lka_idle() -> dict: + from opendbc.can.dbc import DBC # imported here: opendbc.can.dbc imports this module for the checksum + msg = DBC("leapmotor_b10").addr_to_msg[0x83] + return {name: sig.get_raw_value(ADAS_LKA_IDLE) * sig.factor + sig.offset for name, sig in msg.sigs.items()} + + +def create_cancel(packer, powertrain_state: dict): + """Copy of the VCU's latest POWERTRAIN_STATE (0xB7) with the right stalk pushed up, sent to the camera (bus 2). + + The camera runs ACC and reads the stalk from this frame; pushing the stalk up cancels ACC and LCC (14 of 14 logged + pushes ended assist within 0.25 s). The copy uses the next counter value, so it takes the place of the next real + frame. The safety model only allows this frame with the stalk pushed up. + """ + values = {k: v for k, v in powertrain_state.items() if k != "CHECKSUM"} + values["STALK_PUSH"] = STALK_PUSH_UP_CANCEL + values["COUNTER"] = (int(powertrain_state["COUNTER"]) + 1) % 16 + return packer.make_can_msg("POWERTRAIN_STATE", 2, values) diff --git a/opendbc_repo/opendbc/car/leapmotor/tests/__init__.py b/opendbc_repo/opendbc/car/leapmotor/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/car/leapmotor/tests/test_leapmotor.py b/opendbc_repo/opendbc/car/leapmotor/tests/test_leapmotor.py new file mode 100644 index 0000000000..771c3cbd18 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/tests/test_leapmotor.py @@ -0,0 +1,308 @@ +import unittest + +from opendbc.can import CANPacker +from opendbc.can.dbc import DBC +from opendbc.car import Bus, structs +from opendbc.car.leapmotor import leapmotorcan +from opendbc.car.leapmotor.carcontroller import CarController, get_safety_CP +from opendbc.car.leapmotor.leapmotorcan import leapmotor_checksum +from opendbc.car.leapmotor.values import DBC as LEAPMOTOR_DBC, CarControllerParams + +DBC_NAMES = LEAPMOTOR_DBC["LEAPMOTOR_B10"] + +# Real ADAS_LKA (0x83) frames from a 2025 global-market B10: stock LCC steering, ACC only, and assist off +REAL_ADAS_LKA = { + "lcc": [ + "6D0C004666007D00007D007009E87E00375D007D000000000000000000000000", + "600D004664007D00007D007008A67F004D53007D000000000000000000000000", + "A808004664808900007D007008E87E004158007D000000000000000000000000", + ], + "acc": [ + "B90A005A64005F00007D007000A47F000178007D000008000000000000000000", + "B40200465F802500007D007000087F000178007D000000000000000000000000", + "BA03004A64C07100007D0070004F7E000178007D000008000000000000000000", + ], + "off": [ + "260500446411E100007D00700043E4000178007D000000000000000000000000", + "4B0700446411E100007D007000A05A000178007D000000000000000000000000", + "4008004464918900007D0070002D7E000178007D000000000000000000000000", + ], +} +STEERING_BYTES = {12, 13, 14, 16, 17} # LCC_STEERING_ACTIVE_COPY (bit 99), STEER_ANGLE_REQ (104|16), LCC_RAMP (128|16) + +# Real POWERTRAIN_STATE (0xB7) frames while driving with ACC engaged +REAL_POWERTRAIN_STATE = [ + "450B04401004B42C000000800000000055E2048D5E2013000000000000000000", + "070C04401004B42C000000800000000055E204855E2A13000000000000000000", +] + +# Real frames from the filmed figure-eights at the moments of hardest right and left turn, as measured by the +# comma's own gyro (livePose.angularVelocityDevice.z: +36.6 deg/s right, -44.6 deg/s left) +HARD_RIGHT = {0x18D: "0B0602CAE4009EC5869A5E012C2C0000D5128658A3E803000000000000000000", 0x233: "4C06C88947811100"} +HARD_LEFT = {0x18D: "130E02BA1D0F644386C24D010001000004128702A3E803000000000000000000", 0x233: "7E0A43A647AD3100"} + +# Real ROAD_SIGNS (0x142) frames from the camera just before and during a forward collision warning the driver reported +FCW_FRAMES = {False: "F204F4F14002001C8032120000000000", True: "050E310D4402001C8032120000000000"} + + +class TestLeapmotorCan(unittest.TestCase): + def setUp(self): + self.msg = DBC("leapmotor_b10").addr_to_msg[0x83] + + def unpack(self, dat: bytes) -> dict: + return {n: s.get_raw_value(dat) * s.factor + s.offset for n, s in self.msg.sigs.items()} + + def test_fcw(self): + sig = DBC("leapmotor_b10").addr_to_msg[0x142].sigs["FCW"] + for fcw, hexdata in FCW_FRAMES.items(): + dat = bytes.fromhex(hexdata) + self.assertEqual(sig.get_raw_value(dat), int(fcw)) + self.assertEqual(dat[0], leapmotor_checksum(0x142, None, bytearray(dat))) + + def test_sign_convention(self): + # openpilot expects positive = left for steering angle and yaw rate + dbc = DBC("leapmotor_b10") + + def decode(addr, hexdata, name): + sig = dbc.addr_to_msg[addr].sigs[name] + return sig.get_raw_value(bytes.fromhex(hexdata)) * sig.factor + sig.offset + self.assertLess(decode(0x18D, HARD_RIGHT[0x18D], "STEER_ANGLE"), -400) + self.assertLess(decode(0x233, HARD_RIGHT[0x233], "YAW_RATE"), -30) + self.assertGreater(decode(0x18D, HARD_LEFT[0x18D], "STEER_ANGLE"), 400) + self.assertGreater(decode(0x233, HARD_LEFT[0x233], "YAW_RATE"), 30) + + def test_dbc_covers_every_used_bit(self): + # unpacking then packing a real frame (with its own counter) must reproduce it exactly + packer = CANPacker("leapmotor_b10") + for frames in REAL_ADAS_LKA.values(): + for hexdata in frames: + dat = bytes.fromhex(hexdata) + values = {k: v for k, v in self.unpack(dat).items() if k != "CHECKSUM"} + self.assertEqual(bytes(packer.pack(0x83, values)), dat) + + def test_cancel_changes_only_stalk_and_counter(self): + msg = DBC("leapmotor_b10").addr_to_msg[0xB7] + for hexdata in REAL_POWERTRAIN_STATE: + dat = bytes.fromhex(hexdata) + vals = {n: s.get_raw_value(dat) * s.factor + s.offset for n, s in msg.sigs.items()} + addr, out, bus = leapmotorcan.create_cancel(CANPacker("leapmotor_b10"), vals) + self.assertEqual((addr, bus), (0xB7, 2)) + self.assertEqual(out[0], leapmotor_checksum(0xB7, None, bytearray(out))) + self.assertEqual(out[1] & 0xF, (dat[1] + 1) & 0xF) + self.assertEqual(out[5] & 0x3, 3) + for i in range(2, len(dat)): + if i != 5: + self.assertEqual(out[i], dat[i], f"byte {i}") + self.assertEqual(out[5] & ~0x3, dat[5] & ~0x3) + + def test_rebuild_changes_only_steering(self): + for kind, frames in REAL_ADAS_LKA.items(): + for hexdata in frames: + dat = bytes.fromhex(hexdata) + camera = self.unpack(dat) + for lat_active, angle in ((False, camera["STEER_ANGLE_REQ"]), (True, -123.46), (True, 456.78)): + with self.subTest(kind=kind, lat_active=lat_active, angle=angle): + packer = CANPacker("leapmotor_b10") + ramp = 0x6B0F # a value in the middle of the stock ramp + addr, out, bus = leapmotorcan.create_steering_control(packer, camera, angle, lat_active, ramp) + self.assertEqual((addr, bus), (0x83, 0)) + self.assertEqual(out[0], leapmotor_checksum(0x83, None, bytearray(out))) + for i in range(2, len(dat)): + if i not in STEERING_BYTES: + self.assertEqual(out[i], dat[i], f"byte {i}") + got = self.unpack(bytes(out)) + self.assertAlmostEqual(got["STEER_ANGLE_REQ"], angle, delta=0.011) + self.assertEqual(got["LCC_STEERING_ACTIVE_COPY"], int(lat_active)) + # LCC_RAMP: openpilot's ramp while steering, the camera's otherwise + self.assertEqual(got["LCC_RAMP"], ramp if lat_active else camera["LCC_RAMP"]) + # the ACC fields pass through untouched + for sig in ("ACC_STATE", "ACC_ACCEL_REQ", "ACC_SET_SPEED", "ASSIST_OFF", "CONSTANT_72", "CONSTANT_152"): + self.assertEqual(got[sig], camera[sig], sig) + + def test_lcc_ramp_matches_stock(self): + # stock LCC engagement: LCC_RAMP goes 0x7801, 0x7703, 0x7605, ... one 254 step per frame, then jumps back + straight_90 = leapmotorcan.lcc_ramp_target(0.15, 90.0) # a typical straight road: stock median there is 31 steps + self.assertEqual(straight_90, 0x593F) + word, seen = leapmotorcan.LCC_RAMP_IDLE, [] + for _ in range(40): + word = leapmotorcan.lcc_ramp_next(word, True, straight_90) + seen.append(word) + # two ladder steps per frame up to 25 steps (stock: one), then one per frame as stock + self.assertEqual(seen[:3], [0x7605, 0x7409, 0x720D]) + steps_seen = [(leapmotorcan.LCC_RAMP_IDLE - w) // leapmotorcan.LCC_RAMP_STEP for w in seen] + self.assertTrue(all((leapmotorcan.LCC_RAMP_IDLE - w) % leapmotorcan.LCC_RAMP_STEP == 0 for w in seen)) # on the ladder + self.assertEqual(steps_seen.index(26), 12) # 25 steps passed in 13 frames, about 0.26 s + self.assertTrue(all(b - a == 1 for a, b in zip(steps_seen[12:], steps_seen[13:], strict=False) if b != a)) + self.assertEqual(seen.index(straight_90), 17) # 18 frames instead of stock's 31 + self.assertEqual(seen[-1], straight_90) + # never past the target, even when a double step would overshoot it + shallow = leapmotorcan.LCC_RAMP_IDLE - 24 * leapmotorcan.LCC_RAMP_STEP + target_25 = leapmotorcan.LCC_RAMP_IDLE - 25 * leapmotorcan.LCC_RAMP_STEP + self.assertEqual(leapmotorcan.lcc_ramp_next(shallow, True, target_25), target_25) + self.assertEqual(leapmotorcan.lcc_ramp_next(seen[-1], False, straight_90), leapmotorcan.LCC_RAMP_IDLE) + # one step per frame toward a new target, both ways + deeper = leapmotorcan.lcc_ramp_target(1.5, 75.0) + self.assertEqual(leapmotorcan.lcc_ramp_next(straight_90, True, deeper), straight_90 - leapmotorcan.LCC_RAMP_STEP) + self.assertEqual(leapmotorcan.lcc_ramp_next(deeper, True, straight_90), deeper + leapmotorcan.LCC_RAMP_STEP) + # stock medians per lateral-acceleration band (about 90 km/h), within 2 steps, and the stock range 25-46 steps + for alat, stock in ((0.15, 0x593F), (0.45, 0x5547), (0.8, 0x534B), (1.25, 0x4F53)): + self.assertLessEqual(abs(leapmotorcan.lcc_ramp_target(alat, 90.0) - stock), 2 * leapmotorcan.LCC_RAMP_STEP, alat) + for alat, v in ((0.0, 0.0), (5.0, 150.0)): + steps = (leapmotorcan.LCC_RAMP_IDLE - leapmotorcan.lcc_ramp_target(alat, v)) // leapmotorcan.LCC_RAMP_STEP + self.assertTrue(leapmotorcan.LCC_RAMP_STEPS_MIN <= steps <= leapmotorcan.LCC_RAMP_STEPS_MAX) + # the real stock frames agree: idle when not steering, on the ladder within the stock range while steering + for hexdata in REAL_ADAS_LKA["acc"] + REAL_ADAS_LKA["off"]: + self.assertEqual(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"], leapmotorcan.LCC_RAMP_IDLE) + for hexdata in REAL_ADAS_LKA["lcc"]: + # stock occasionally sits 2 off the ladder (steps of -2/+2 also appear between frames) + steps = round((leapmotorcan.LCC_RAMP_IDLE - int(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"])) / leapmotorcan.LCC_RAMP_STEP) + self.assertLessEqual(abs(leapmotorcan.LCC_RAMP_IDLE - steps * leapmotorcan.LCC_RAMP_STEP - int(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"])), 2) + self.assertTrue(leapmotorcan.LCC_RAMP_STEPS_MIN <= steps <= leapmotorcan.LCC_RAMP_STEPS_MAX) + + def test_ramp_boost(self): + deepest = leapmotorcan.LCC_RAMP_IDLE - leapmotorcan.LCC_RAMP_STEP * leapmotorcan.LCC_RAMP_STEPS_BOOST_MAX + # extra steps go deeper, never beyond the boost maximum; the top 4 bits stay as at the deepest stock value + self.assertEqual(deepest >> 12, (leapmotorcan.LCC_RAMP_IDLE - leapmotorcan.LCC_RAMP_STEP * leapmotorcan.LCC_RAMP_STEPS_MAX) >> 12) + base = leapmotorcan.lcc_ramp_target(0.1, 15.0) + self.assertEqual(leapmotorcan.lcc_ramp_target(0.1, 15.0, 3), base - 3 * leapmotorcan.LCC_RAMP_STEP) + self.assertEqual(leapmotorcan.lcc_ramp_target(0.1, 15.0, 100), deepest) + self.assertEqual(leapmotorcan.lcc_ramp_target(3.0, 120.0, 20), deepest) + + from types import SimpleNamespace + from opendbc.car.leapmotor.carcontroller import CarController, get_safety_CP + from opendbc.car.leapmotor.values import CarControllerParams, DBC as LEAPMOTOR_DBC + controller = CarController(LEAPMOTOR_DBC["LEAPMOTOR_B10"], get_safety_CP()) + + def cs(angle, kph): + return SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=angle, vEgoRaw=kph / 3.6)) + controller.apply_angle_last = 90. + boost_max = leapmotorcan.LCC_RAMP_STEPS_BOOST_MAX - leapmotorcan.LCC_RAMP_STEPS_MIN + for i in range(40): # wheel 10 deg behind at 15 km/h: one step deeper per frame, up to the boost maximum + controller.ramp_boost = controller.update_ramp_boost(True, cs(80., 15.)) + self.assertEqual(controller.ramp_boost, min(i + 1, boost_max)) + controller.ramp_boost = controller.update_ramp_boost(True, cs(88., 15.)) # 2 deg behind: hold + self.assertEqual(controller.ramp_boost, boost_max) + controller.ramp_boost = controller.update_ramp_boost(True, cs(89.5, 15.)) # caught up: one step back + self.assertEqual(controller.ramp_boost, boost_max - 1) + self.assertEqual(controller.update_ramp_boost(False, cs(80., 15.)), 0) # not steering + self.assertEqual(controller.update_ramp_boost(True, cs(80., CarControllerParams.RAMP_BOOST_MAX_SPEED + 1)), 0) # fast + + def test_driver_torque_lags_the_eps(self): + from opendbc.car.leapmotor.carstate import CarState + from opendbc.car.leapmotor.interface import CarInterface + + def pressed(driver, eps): + CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10") + CS = CarState(CP) + parsers = CS.get_can_parsers(CP) + packer = CANPacker("leapmotor_b10") + out = [] + for i, (d, e) in enumerate(zip(driver, eps, strict=True)): + dat = packer.make_can_msg("EPS_STEERING", 0, {"STEER_TORQUE_DRIVER": d, "STEER_TORQUE_EPS": e, "COUNTER": i % 16})[1] + parsers[Bus.pt].update([(int((i + 1) * 1e7), [(0x18D, dat, 0)])]) + parsers[Bus.cam].update([(int((i + 1) * 1e7), [])]) + CS.update(parsers) + out.append(CS.driver_override) + return out + + # hands off in a roundabout at 28 km/h (route 264): the EPS swings -99 -> +98 within 0.1 s while the reading barely + # moves; subtracting the EPS's share without its lag read above 3 for 8 of these frames and let go of the wheel + driver = [2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0] + eps = [9, 1, -16, -14, -22, -28, -31, -38, -44, -37, -18, -1, 15, 25, 27, 20, 17, 13, 8, -9, -37, -73, -99, -84, -52, + -4, 58, 78, 98, 96, 75, 53, 35, 16, 0, -15] + self.assertFalse(any(pressed(driver, eps))) + # the driver's lane-change nudge at 126 km/h (route 25c): the EPS holds -57 against the hands, the reading stays at 0 + driver = [1, 1, 1, 1, 1, 0, 0, 0, 0, 1] + [0] * 20 + eps = [-12, -7, -7, -6, -8, -14, -28, -47, -57, -56] + [-57] * 20 + self.assertTrue(any(pressed(driver, eps))) + + def test_accel_replaces_only_the_request(self): + # with openpilot longitudinal, only ACC_ACCEL_REQ changes besides the steering fields + for hexdata in REAL_ADAS_LKA["acc"]: + dat = bytes.fromhex(hexdata) + camera = self.unpack(dat) + for accel in (-3.5, -0.75, 0.0, 1.2): + _, out, _ = leapmotorcan.create_steering_control(CANPacker("leapmotor_b10"), camera, camera["STEER_ANGLE_REQ"], False, + accel=accel) + got = self.unpack(bytes(out)) + self.assertAlmostEqual(got["ACC_ACCEL_REQ"], accel, delta=0.026) + for i in range(2, len(dat)): + if i not in STEERING_BYTES | {4}: + self.assertEqual(out[i], dat[i], f"byte {i}") + + def test_long_accel(self): + CP = get_safety_CP() + CP.openpilotLongitudinalControl = True + CC = structs.CarControl() + controller = CarController(DBC_NAMES, CP) + limits = CarControllerParams + cases = [ + # longActive, ACC_STATE, camera request, openpilot request -> sent (None = the camera's) + (False, 3, -1.0, -0.5, None), # openpilot not in control + (True, 2, 0.0, -0.5, None), # stock ACC not engaged + (True, 1, 1.5, -0.5, None), # accelerator override + (True, 3, -1.0, -0.5, -0.5), # openpilot may brake less than stock ACC's normal braking + (True, 3, -1.0, 5.0, limits.ACCEL_MAX), + (True, 3, -1.0, -9.0, limits.ACCEL_MIN), + (True, 3, -2.0, -0.5, -2.0), # but never less than the camera's hard braking + (True, 3, -2.6, -3.0, -3.0), + ] + for long_active, acc_state, camera_accel, accel, expected in cases: + with self.subTest(long_active=long_active, acc_state=acc_state, camera_accel=camera_accel, accel=accel): + CC.longActive = long_active + CC.actuators.accel = accel + self.assertEqual(controller.long_accel(CC, {"ACC_STATE": acc_state, "ACC_ACCEL_REQ": camera_accel}), expected) + # without openpilot longitudinal the camera's request always goes through + CP.openpilotLongitudinalControl = False + CC.longActive = True + self.assertIsNone(CarController(DBC_NAMES, CP).long_accel(CC, {"ACC_STATE": 3, "ACC_ACCEL_REQ": -1.0})) + + def test_take_back(self): + from types import SimpleNamespace + from opendbc.car import structs as car_structs + from opendbc.car.leapmotor.carcontroller import CarController as Controller, get_safety_CP as safety_CP + from opendbc.car.leapmotor.values import DBC as CAR_DBC + + def steering_after_let_go(wanted, wheel, kph=25.): + controller = Controller(CAR_DBC["LEAPMOTOR_B10"], safety_CP()) + CC = car_structs.CarControl() + CC.latActive = True + CC.actuators.steeringAngleDeg = wanted + CS = SimpleNamespace(driver_override=False, adas_lka=None, powertrain_state=None, + out=SimpleNamespace(steeringAngleDeg=wheel, vEgoRaw=kph / 3.6)) + controller.update(CC.as_reader(), CS, 0) + return controller.lat_active_last + + # right after the driver lets go in a bend the wheel is 11-27 deg from the model's angle: take it back at once + self.assertTrue(steering_after_let_go(100., 73.)) + self.assertTrue(steering_after_let_go(100., 100. - 44.)) + # the case the check was made for: wheel at +308 deg, model at +24, at walking pace + self.assertFalse(steering_after_let_go(24., 308., kph=5.)) + + def test_eps_status_bit_is_not_torque(self): + # Real EPS_STEERING frames from route 26e (22:19:39, openpilot steering at 60 km/h): bit 180 turns on for 1 s. Read + # as part of the torque it added 4096, which looked like a driver torque of +264 and let go of the wheel mid-turn. + frames = ["350B0265810000448EF25001070700002B02870FA30904000000000000000000", + "5E0C0265810103448EF75001070700002B02870FA30814000000000000000000"] + sigs = DBC("leapmotor_b10").addr_to_msg[0x18D].sigs + for hexdata, (torque, status) in zip(frames, ((33, 0), (32, 1)), strict=True): + dat = bytes.fromhex(hexdata) + self.assertEqual(dat[0], leapmotor_checksum(0x18D, None, bytearray(dat))) + eps = sigs["STEER_TORQUE_EPS"] + self.assertEqual(eps.get_raw_value(dat) * eps.factor + eps.offset, torque) + self.assertEqual(sigs["EPS_STATUS_180"].get_raw_value(dat), status) + + from opendbc.car.leapmotor.carstate import CarState + from opendbc.car.leapmotor.interface import CarInterface + CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10") + CS = CarState(CP) + parsers = CS.get_can_parsers(CP) + for i in range(20): + parsers[Bus.pt].update([(int((i + 1) * 1e7), [(0x18D, bytes.fromhex(frames[min(i, 1)]), 0)])]) + parsers[Bus.cam].update([(int((i + 1) * 1e7), [])]) + ret = CS.update(parsers) + self.assertLess(abs(ret.steeringTorqueEps), 100) + self.assertFalse(CS.driver_override) + +if __name__ == "__main__": + unittest.main() diff --git a/opendbc_repo/opendbc/car/leapmotor/values.py b/opendbc_repo/opendbc/car/leapmotor/values.py new file mode 100644 index 0000000000..7f3c0f0195 --- /dev/null +++ b/opendbc_repo/opendbc/car/leapmotor/values.py @@ -0,0 +1,112 @@ +from dataclasses import dataclass, field +from enum import IntFlag + +from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms +from opendbc.car.docs_definitions import CarDocs, CarHarness, CarParts +from opendbc.car.lateral import AngleSteeringLimitsVM +from opendbc.car.fw_query_definitions import FwQueryConfig, Request +from opendbc.car.structs import CarParams + +Ecu = CarParams.Ecu + + +class CarControllerParams: + STEER_STEP = 2 # ADAS_LKA (0x83) is sent at 50 Hz + + # Must match opendbc/safety/modes/leapmotor.h. openpilot's standard vehicle-model limits: lateral accel and + # lateral jerk of about 3.6 (m/s^2, m/s^3), so near-full lock is allowed up to about 15 km/h (U-turns) and + # about 50 deg at 50 km/h. Stock LCC stays below 2.3 m/s^2 on every recorded route. + ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM( + 500, # deg; mechanical lock is about 522 deg, keep a margin so the EPS never drives into the end stop + MAX_ANGLE_RATE=5, # deg per 20 ms frame (250 deg/s): lock to lock in about 4 s. EPS fault rate untested + ) + # EPS_STEERING.STEER_TORQUE_DRIVER (unit unknown) also follows the EPS's own effort: while openpilot steered and the + # EPS flagged no override it read -1 per 16.8 of STEER_TORQUE_EPS (r -0.88, 317k frames on 2 drives). Adding that + # share back leaves the driver's torque: above 3 on 0.14% of those frames but on 75% of frames the EPS flagged as + # overrides. With the 5-frame debounce in carstate it caught all 3 of the driver's lane-change nudges at 125 km/h, + # where the raw reading stayed at 1, and nothing else above 118 km/h over the 2 drives. + # The reading lags the EPS by a few frames: when the EPS swung its torque quickly in roundabouts (e.g. +76 to -120 in + # 0.1 s), subtracting the unlagged share left 4-6 with the driver's hands off and let go of the wheel mid-turn. + # Refitted on 665k hands-off frames of 7 drives as a first-order lag of 0.04 s and 1 per 15.5: frames above 3 during + # such swings fell from 18% to 2.6%. Replayed on the same drives, the false let-gos right after the EPS pushed 90 or + # more fell from 56 to 17; every takeover that lasted 0.5 s or more was still caught (35 of 35, at most 40 ms later), + # and so was every let-go above 110 km/h, including all of the 125 km/h nudges. + EPS_TORQUE_PER_DRIVER_TORQUE = 15.5 + EPS_TORQUE_LAG = 0.04 # s + STEER_DRIVER_ALLOWANCE = 3 + # Largest gap (deg) between openpilot's angle and the wheel's at which it takes the wheel back. It stops the case it was + # made for: at walking pace the driver let go with the wheel at +308 deg and the model at +24, and the EPS swung it to + # -203 deg. 10 deg was too tight: right after the driver lets go in a bend the gap is 11-27 deg, and on route 26b + # openpilot then did not steer for 0.8-1.7 s mid-turn (5 times), drifting wide. The command still starts from the + # wheel's angle and is rate limited, and the LCC ramp builds up the torque. + TAKE_BACK_MAX_ANGLE_ERROR = 45. + # The stock ramp depth follows lateral acceleration, which stays small in sharp turns at low speed: there the wheel + # fell > 5 deg behind with the EPS near its torque ceiling (25d, 260). While the wheel is RAMP_BOOST_LAG behind the + # command below RAMP_BOOST_MAX_SPEED, the ramp goes one step deeper per frame (deepest stock value 46 steps, about + # +/-70 torque; TEST: up to LCC_RAMP_STEPS_BOOST_MAX), and back one step per frame once within RAMP_BOOST_CAUGHT_UP. Replayed on 3 drives: active + # 23-31% of the time below 30 km/h, 3-7% at 30-80 km/h. Not at speed, where such a lag was the driver's own nudge. + RAMP_BOOST_LAG = 3. # deg + RAMP_BOOST_CAUGHT_UP = 1.5 # deg + RAMP_BOOST_MAX_SPEED = 60. # km/h + + # Longitudinal (alpha): ADAS_LKA.ACC_ACCEL_REQ, 0.05 m/s^2 per bit, raw 100 = 0. Must match opendbc/safety/modes/leapmotor.h. + # Stock ACC never asked for less than -2.7 m/s^2 in about 5 h of engaged driving; the car follows the request + # (-2.6 asked, -2.69 measured) and blends regen with light friction braking itself. + ACCEL_MIN = -3.5 # m/s^2 + ACCEL_MAX = 2.0 # m/s^2 + # When the camera asks for this much braking or more, openpilot never asks for less: the camera's emergency braking + # path is not yet known and may use this field. Stock ACC went below it on 0.02% of engaged frames. + STOCK_BRAKE_PASSTHROUGH = -2.0 # m/s^2 + + +class LeapmotorSafetyFlags(IntFlag): + LONG_CONTROL = 1 + + +@dataclass +class LeapmotorCarDocs(CarDocs): + package: str = "Adaptive Cruise Control (ACC) & Lane Centering Control (LCC)" + car_parts: CarParts = field(default_factory=CarParts.common([CarHarness.custom])) + + +@dataclass +class LeapmotorPlatformConfig(PlatformConfig): + dbc_dict: DbcDict = field(default_factory=lambda: { + Bus.pt: 'leapmotor_b10', + }) + + +class CAR(Platforms): + # wheelbase: Italian brochure, B10 Life with the 56.2 kWh Pro battery. + # steerRatio 15.2 is measured from slow figure-eights (steering angle vs. yaw rate / speed). + LEAPMOTOR_B10 = LeapmotorPlatformConfig( + [LeapmotorCarDocs("Leapmotor B10 2025")], + CarSpecs(mass=1885, wheelbase=2.735, steerRatio=15.2), + ) + + +# Part number (F187), physical request = reply minus 8: EPS 0x735, brake 0x736, front camera 0x756, all confirmed by a +# read-only UDS probe on the car. No tester present first: the camera did not answer openpilot's query when it led with +# one, but answers F187 directly. At ignition, before READY, only the brake answers (the EPS stays silent until READY, +# the camera is slow), so the EPS and camera are non-essential; their part numbers are still checked when present. +PART_NUMBER_REQUEST = bytes([0x22, 0xF1, 0x87]) +PART_NUMBER_RESPONSE = bytes([0x62, 0xF1, 0x87]) + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [PART_NUMBER_REQUEST], + [PART_NUMBER_RESPONSE], + whitelist_ecus=[Ecu.eps, Ecu.abs, Ecu.fwdCamera], + bus=0, + ), + ], + non_essential_ecus={ + Ecu.eps: [CAR.LEAPMOTOR_B10], + Ecu.fwdCamera: [CAR.LEAPMOTOR_B10], + }, + # part numbers such as 3401100-AG01, zero-padded to 19 bytes + fw_version_regex=br"\d{7}-[A-Z]{2}\d{2}\x00{7}", +) + +DBC = CAR.create_dbc_map() diff --git a/opendbc_repo/opendbc/car/tests/routes.py b/opendbc_repo/opendbc/car/tests/routes.py index 9fc3d8fd67..aa3270edd5 100644 --- a/opendbc_repo/opendbc/car/tests/routes.py +++ b/opendbc_repo/opendbc/car/tests/routes.py @@ -19,6 +19,7 @@ from opendbc.car.body.values import CAR as COMMA from opendbc.car.byd.values import CAR as BYD from opendbc.car.psa.values import CAR as PSA from opendbc.car.mg.values import CAR as MG +from opendbc.car.leapmotor.values import CAR as LEAPMOTOR # Configurations with source tests but no matching recorded route. unrecorded_route_gaps = { @@ -484,6 +485,8 @@ routes = [ CarTestRoute("5d61e2f6e1f247f3/00000054--d3dfb01b34", MG.MG_5_EV), + CarTestRoute("8ae32b57e2f9d13c/0000025f--a58bd2c2f5", LEAPMOTOR.LEAPMOTOR_B10), + # Segments that test specific issues # Controls mismatch due to standstill threshold CarTestRoute("bec2dcfde6a64235/2022-04-08--14-21-32", HONDA.HONDA_CRV_HYBRID, segment=22), diff --git a/opendbc_repo/opendbc/car/tests/test_fw_fingerprint.py b/opendbc_repo/opendbc/car/tests/test_fw_fingerprint.py index f9ad1ab4ea..4aee6bc260 100644 --- a/opendbc_repo/opendbc/car/tests/test_fw_fingerprint.py +++ b/opendbc_repo/opendbc/car/tests/test_fw_fingerprint.py @@ -337,7 +337,7 @@ class TestFwFingerprintTiming(unittest.TestCase): assert first.whitelist_ecus == second.whitelist_ecus def test_fw_query_timing(self): - total_ref_time = 8.5 + total_ref_time = 8.6 brand_ref_times = { 'gm': 1.0, 'body': 0.1, @@ -355,6 +355,7 @@ class TestFwFingerprintTiming(unittest.TestCase): 'rivian': 0.3, 'psa': 0.1, 'mg': 0.1, + 'leapmotor': 0.1, 'volvo': 0.1, } diff --git a/opendbc_repo/opendbc/car/torque_data/override.toml b/opendbc_repo/opendbc/car/torque_data/override.toml index e58fe9ab69..7dddfb1cd9 100644 --- a/opendbc_repo/opendbc/car/torque_data/override.toml +++ b/opendbc_repo/opendbc/car/torque_data/override.toml @@ -13,6 +13,9 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"] # BYD angle based controllers "BYD_ATTO_3" = [nan, 2.0, nan] +# Leapmotor angle based controllers +"LEAPMOTOR_B10" = [nan, 2.0, nan] + # New subarus angle based controllers "SUBARU_FORESTER_2022" = [nan, 3.0, nan] "SUBARU_OUTBACK_2023" = [nan, 3.0, nan] diff --git a/opendbc_repo/opendbc/car/values.py b/opendbc_repo/opendbc/car/values.py index db27ea878b..61344db782 100644 --- a/opendbc_repo/opendbc/car/values.py +++ b/opendbc_repo/opendbc/car/values.py @@ -9,6 +9,7 @@ from opendbc.car.hyundai.values import CAR as HYUNDAI from opendbc.car.mazda.values import CAR as MAZDA from opendbc.car.mock.values import CAR as MOCK from opendbc.car.nissan.values import CAR as NISSAN +from opendbc.car.leapmotor.values import CAR as LEAPMOTOR from opendbc.car.psa.values import CAR as PSA from opendbc.car.rivian.values import CAR as RIVIAN from opendbc.car.mg.values import CAR as MG @@ -18,7 +19,7 @@ from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.volvo.values import CAR as VOLVO from opendbc.car.volkswagen.values import CAR as VOLKSWAGEN -Platform = BODY | BYD | CHRYSLER | FORD | GM | HONDA | HYUNDAI | MAZDA | MOCK | MG | NISSAN | PSA | RIVIAN | SUBARU | TESLA | TOYOTA | VOLVO | VOLKSWAGEN +Platform = BODY | BYD | CHRYSLER | FORD | GM | HONDA | HYUNDAI | LEAPMOTOR | MAZDA | MOCK | MG | NISSAN | PSA | RIVIAN | SUBARU | TESLA | TOYOTA | VOLVO | VOLKSWAGEN BRANDS = get_args(Platform) PLATFORMS: dict[str, Platform] = {str(platform): platform for brand in BRANDS for platform in brand} diff --git a/opendbc_repo/opendbc/dbc/leapmotor_b10.dbc b/opendbc_repo/opendbc/dbc/leapmotor_b10.dbc new file mode 100644 index 0000000000..55d6494eba --- /dev/null +++ b/opendbc_repo/opendbc/dbc/leapmotor_b10.dbc @@ -0,0 +1,213 @@ +VERSION "" + +NS_ : + +BS_: + +BU_: XXX + +BO_ 388 WHEEL_SPEEDS: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ WHEEL_SPEED_FL : 16|16@1+ (0.01,0) [0|0] "km/h" XXX + SG_ WHEEL_SPEED_FR : 32|16@1+ (0.01,0) [0|0] "km/h" XXX + SG_ WHEEL_SPEED_RL : 48|16@1+ (0.01,0) [0|0] "km/h" XXX + SG_ WHEEL_SPEED_RR : 64|16@1+ (0.01,0) [0|0] "km/h" XXX + +BO_ 563 IMU: 8 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ YAW_RATE : 41|13@1+ (0.02,-81.92) [0|0] "deg/s" XXX + +BO_ 397 EPS_STEERING: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ STEER_ANGLE : 24|16@1+ (-0.02,649.8) [-661|650] "deg" XXX + SG_ STEER_SPEED_ABS : 40|8@1+ (4,0) [0|1020] "deg/s" XXX + SG_ DRIVER_OVERRIDE : 63|1@1+ (1,0) [0|1] "" XXX + SG_ ADAS_LKA_RECEIVED : 66|1@1+ (1,0) [0|1] "" XXX + SG_ LCC_STEERING_ACTIVE : 67|1@1+ (1,0) [0|1] "" XXX + SG_ ADAS_LKA_TIMEOUT : 120|2@1+ (1,0) [0|3] "" XXX + SG_ STEER_TORQUE_DRIVER : 80|8@1+ (-1,78) [0|0] "raw" XXX + SG_ STEER_TORQUE_EPS : 168|12@1+ (1,-1000) [0|0] "raw" XXX + SG_ EPS_STATUS_180 : 180|1@1+ (1,0) [0|1] "" XXX + +BO_ 131 ADAS_LKA: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ ACC_STATE : 25|2@1+ (1,0) [0|3] "" XXX + SG_ UNKNOWN_27 : 27|3@1+ (1,0) [0|7] "" XXX + SG_ UNKNOWN_30 : 30|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_31 : 31|1@1+ (1,0) [0|1] "" XXX + SG_ ACC_ACCEL_REQ : 32|8@1+ (0.05,-5) [-5|7.75] "m/s^2" XXX + SG_ ASSIST_OFF : 40|1@1+ (1,0) [0|1] "" XXX + SG_ ASSIST_OFF_2 : 44|1@1+ (1,0) [0|1] "" XXX + SG_ ACC_SET_SPEED : 46|11@1+ (0.2,0) [0|409.4] "km/h" XXX + SG_ UNKNOWN_60 : 60|1@1+ (1,0) [0|1] "" XXX + SG_ CONSTANT_72 : 72|8@1+ (1,0) [0|255] "" XXX + SG_ UNKNOWN_81 : 81|4@1+ (1,0) [0|15] "" XXX + SG_ UNKNOWN_88 : 88|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_90 : 90|5@1+ (1,0) [0|31] "" XXX + SG_ UNKNOWN_96 : 96|3@1+ (1,0) [0|7] "" XXX + SG_ LCC_STEERING_ACTIVE_COPY : 99|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_100 : 100|2@1+ (1,0) [0|3] "" XXX + SG_ STEER_ANGLE_REQ : 104|16@1+ (-0.02,649.8) [-661|650] "deg" XXX + SG_ LCC_RAMP : 128|16@1+ (1,0) [0|65535] "" XXX + SG_ UNKNOWN_147 : 147|1@1+ (1,0) [0|1] "" XXX + SG_ CONSTANT_152 : 152|8@1+ (1,0) [0|255] "" XXX + SG_ UNKNOWN_176 : 176|1@1+ (1,0) [0|1] "" XXX + SG_ ACC_OVERRIDE : 179|1@1+ (1,0) [0|1] "" XXX + +BO_ 389 VEHICLE_ACCEL: 16 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ LONG_ACCEL : 48|10@1+ (0.03125,-16) [-16|15.97] "m/s^2" XXX + SG_ SEATBELT_REMINDER : 83|1@1+ (1,0) [0|1] "" XXX + +BO_ 656 BODY_CONTROL: 8 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ BLINKER_LEFT : 24|1@1+ (1,0) [0|0] "" XXX + SG_ BLINKER_RIGHT : 25|1@1+ (1,0) [0|0] "" XXX + SG_ DRIVER_DOOR_OPEN : 44|1@1+ (1,0) [0|1] "" XXX + +BO_ 183 POWERTRAIN_STATE: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ ASSIST_ENGAGED : 30|1@1+ (1,0) [0|1] "" XXX + SG_ STALK_PUSH : 40|2@1+ (1,0) [0|3] "" XXX + SG_ TORQUE_DEMAND : 56|8@1+ (1,0) [0|0] "raw" XXX + SG_ UNKNOWN_18 : 18|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_26 : 26|4@1+ (1,0) [0|15] "" XXX + SG_ UNKNOWN_33 : 33|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_36 : 36|2@1+ (1,0) [0|3] "" XXX + SG_ UNKNOWN_42 : 42|3@1+ (1,0) [0|7] "" XXX + SG_ UNKNOWN_50 : 50|4@1+ (1,0) [0|15] "" XXX + SG_ UNKNOWN_55 : 55|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_64 : 64|11@1+ (1,0) [0|2047] "" XXX + SG_ UNKNOWN_80 : 80|11@1+ (1,0) [0|2047] "" XXX + SG_ UNKNOWN_95 : 95|1@1+ (1,0) [0|1] "" XXX + SG_ UNKNOWN_97 : 97|10@1+ (1,0) [0|1023] "" XXX + SG_ UNKNOWN_112 : 112|11@1+ (1,0) [0|2047] "" XXX + SG_ UNKNOWN_128 : 128|7@1+ (1,0) [0|127] "" XXX + SG_ UNKNOWN_136 : 136|11@1+ (1,0) [0|2047] "" XXX + SG_ UNKNOWN_151 : 151|2@1+ (1,0) [0|3] "" XXX + SG_ UNKNOWN_154 : 154|14@1+ (1,0) [0|16383] "" XXX + SG_ UNKNOWN_169 : 169|12@1+ (1,0) [0|4095] "" XXX + +BO_ 182 VEHICLE_STATE: 16 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ ACCEL_PEDAL : 88|8@1+ (0.4,0) [0|102] "%" XXX + SG_ BRAKE_PRESSED : 99|1@1+ (1,0) [0|1] "" XXX + SG_ GEAR : 101|2@1+ (1,0) [0|3] "" XXX + +BO_ 390 BRAKE_PRESSURE: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ BRAKE_PRESSURE : 16|8@1+ (1,0) [0|0] "raw" XXX + +BO_ 322 ROAD_SIGNS: 16 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ FCW : 34|1@1+ (1,0) [0|1] "" XXX + SG_ SPEED_LIMIT : 72|8@1+ (1,0) [0|255] "km/h" XXX + +BO_ 552 BSD_LEFT: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ OBJECT_DETECTED : 17|1@1+ (1,0) [0|1] "" XXX + +BO_ 554 BSD_RIGHT: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ OBJECT_DETECTED : 17|1@1+ (1,0) [0|1] "" XXX + +BO_ 675 SEATBELT: 16 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ DRIVER_SEATBELT_UNLATCHED : 31|1@1+ (1,0) [0|1] "" XXX + +BO_ 589 CLUSTER: 32 XXX + SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX + SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX + SG_ DISPLAY_SPEED : 80|8@1+ (1,0) [0|255] "km/h" XXX + SG_ ASSIST_ENGAGED_COPY : 131|1@1+ (1,0) [0|1] "" XXX + SG_ LCC_ENGAGED : 132|1@1+ (1,0) [0|1] "" XXX + +CM_ "Leapmotor B10 (2025, global market), reverse engineered from comma rlogs. Checksums are AUTOSAR E2E Profile 2 with per-message constants (see CHECKSUM comments). Each signal comment says CONFIRMED (matched filmed actions or a dedicated test), INFERRED or WEAK."; +CM_ SG_ 388 WHEEL_SPEED_FL "CONFIRMED: positions from filmed figure-eights: front/rear rises from 1.02 straight to 1.27 near lock, and the left wheels run faster when steering right. Scale matches GPS within 0.1 km/h at a filmed steady 30 km/h. within about 1% of GPS above 60 km/h up to 126 km/h. Width at least 14 bits; no wrap in about 11 hours of logs."; +CM_ SG_ 388 WHEEL_SPEED_FR "CONFIRMED: positions from filmed figure-eights: front/rear rises from 1.02 straight to 1.27 near lock, and the left wheels run faster when steering right. Scale matches GPS within 0.1 km/h at a filmed steady 30 km/h. within about 1% of GPS above 60 km/h up to 126 km/h. Width at least 14 bits; no wrap in about 11 hours of logs."; +CM_ SG_ 388 WHEEL_SPEED_RL "CONFIRMED: positions from filmed figure-eights: front/rear rises from 1.02 straight to 1.27 near lock, and the left wheels run faster when steering right. Scale matches GPS within 0.1 km/h at a filmed steady 30 km/h. within about 1% of GPS above 60 km/h up to 126 km/h. Width at least 14 bits; no wrap in about 11 hours of logs."; +CM_ SG_ 388 WHEEL_SPEED_RR "CONFIRMED: positions from filmed figure-eights: front/rear rises from 1.02 straight to 1.27 near lock, and the left wheels run faster when steering right. Scale matches GPS within 0.1 km/h at a filmed steady 30 km/h. within about 1% of GPS above 60 km/h up to 126 km/h. Width at least 14 bits; no wrap in about 11 hours of logs."; +CM_ SG_ 563 YAW_RATE "INFERRED scale, sign CONFIRMED: positive = turning left (openpilot convention); raw rises when turning right, r +0.994 to +1.000 against the comma gyro (livePose.angularVelocityDevice.z, positive right) on 3 traces. R2 0.993-0.999 against livePose on 5 datasets. Fit gives 0.0196; 0.02 assumed."; +CM_ SG_ 389 LONG_ACCEL "INFERRED: R2 0.70-0.95 against livePose on 5 datasets. Same encoding as the Leapmotor T03 DBC (10 bits, offset -16), which matches the earlier 9-bit signed reading over the logged range. No wrap down to -6.8 m/s^2."; +CM_ SG_ 589 DISPLAY_SPEED "CONFIRMED: equal to the filmed dashboard speed in 6 of 6 checks (50, 70, 100 km/h). Reads about 3.5 percent above the wheel speeds, as dashboards do."; +CM_ SG_ 675 DRIVER_SEATBELT_UNLATCHED "CONFIRMED: 1 when the driver belt is unbuckled. Followed 4 of 4 buckle actions in a live capture (cluster warning 0x24D bit 146 0.5 s later), the filmed belt step of recording 1, and read 0 (buckled) at every seatbeltNotLatched refusal caused by the old signal. Constant over whole drives with the belt on."; +CM_ BO_ 552 "Rear-left blind-spot radar (20 Hz, silent when stopped). Bytes 8-15 carry object data when something is detected."; +CM_ SG_ 552 OBJECT_DETECTED "CONFIRMED on video: on 3 of 3 checked episodes a car appeared in the left lane beside the B10 in the road camera within 1 s of the flag clearing. Set in 8.5% of driving above 50 km/h, less often while signalling left (drivers wait for a clear lane)."; +CM_ BO_ 554 "Rear-right blind-spot radar, same layout as BSD_LEFT (0x228)."; +CM_ SG_ 554 OBJECT_DETECTED "INFERRED by symmetry with BSD_LEFT: same layout, set in 0.7% of driving above 50 km/h (in right-hand traffic you are rarely overtaken on the right). The one checked episode was not conclusive on video."; +CM_ SG_ 397 DRIVER_OVERRIDE "INFERRED: the EPS flags strong driver input. Set during both filmed driver overrides of LCC (0.4-0.5 s before LCC released) even though STEER_TORQUE_DRIVER only reached 2-3; otherwise set 66% of the time when |STEER_TORQUE_DRIVER| >= 15 and under 0.4% below 8. Short bursts. Also set whenever the car is above about 121 km/h, with or without the driver (on at 121.5, off at 120.1 km/h; 99% of frames above 121 km/h on a stock drive), so it only means driver input below that. The EPS still follows the steering request up there: openpilot steered at up to 134 km/h with it set."; +CM_ SG_ 397 ADAS_LKA_RECEIVED "CONFIRMED by the camera-unplug test: 1 while the EPS receives ADAS_LKA (0x83) from the camera, 0 with the camera unplugged (and for the first 0.2 s after ignition, before the camera starts). Bit 60 sets at the same time. Used as a temporary steering fault: the EPS is not receiving a valid steering frame."; +CM_ SG_ 397 ADAS_LKA_TIMEOUT "CONFIRMED by the camera-unplug test: 3 with the camera unplugged (no ADAS_LKA), 0 when it is received; also 3 for the first second after ignition."; +CM_ SG_ 397 STEER_ANGLE "CONFIRMED by filmed holds: raw moves about 4450 per 90 deg and 9000 per 180 deg. Sign CONFIRMED: positive = left (openpilot convention); raw rises to the right (r +0.98 against the comma gyro in the figure-eights). Factor is negative so openpilot reads left-positive. Lock is about -515/+522 deg, or 2.9 turns, which the driver confirmed. Centre 32490 from the filmed centre holds; a few counts may remain."; +CM_ SG_ 397 STEER_SPEED_ABS "INFERRED: one count is about 202 raw per second, or 4.04 deg/s, R2 0.99 or better on 5 datasets; 4 assumed, the same as the Leapmotor T03 DBC. Magnitude only, no sign."; +CM_ SG_ 397 STEER_TORQUE_DRIVER "INFERRED: driver steering torque, positive = left (openpilot convention). Raw 57 and 100 while held still at left and right lock, exactly 78 hands off; raw rises when steering right (r +0.54 to +0.81 with the steering rate on 3 traces). Hands-off LCC never exceeds 3, manual steering while moving reaches 7 (p90) to 20. Unit unknown."; +CM_ BO_ 131 "Layout INFERRED from 396,908 frames on 16 traces (5 days): 166 of 256 bits never change; every bit that is not always zero is defined here, so unpack-then-pack reproduces recorded frames exactly. 50 Hz, sent by the ADAS unit."; +CM_ SG_ 131 ACC_STATE "INFERRED, strong: 3 while ACC/LCC engaged, 2 when ACC is ready, 1 when not ready (Park, brake pressed) or overridden by the accelerator while engaged (96-100% of those frames have the pedal pressed, on 8 traces)."; +CM_ SG_ 131 ACC_ACCEL_REQ "INFERRED, strong: the ACC acceleration request. Leads the measured acceleration (0x185 LONG_ACCEL) by about 250 ms, r +0.85 to +0.96 on 8 traces; fit gives zero at raw 99.9 and 0.045 m/s^2 per step (0.05 used, residual 0.08 m/s^2). Raw 100 (0) whenever not engaged."; +CM_ SG_ 131 ACC_OVERRIDE "INFERRED: set exactly when ACC_STATE drops to 1 while engaged, i.e. accelerator override (frame-for-frame match on 8 traces)."; +CM_ SG_ 131 ASSIST_OFF_2 "INFERRED: identical to ASSIST_OFF on every frame."; +CM_ SG_ 131 CONSTANT_72 "CONSTANT: 125 (0x7D) on every recorded frame. Meaning unknown; must be sent as-is."; +CM_ SG_ 131 CONSTANT_152 "CONSTANT: 125 (0x7D) on every recorded frame. Meaning unknown; must be sent as-is."; +CM_ SG_ 131 UNKNOWN_90 "UNKNOWN: 28 on nearly every frame; a handful of other values. Copied from the camera frame."; +CM_ SG_ 131 STEER_ANGLE_REQ "INFERRED, strong: the LCC steering angle request, same encoding as STEER_ANGLE (positive = left; r 1.000 with it). On 5 routes it leads the measured angle (0x18D) by 70-100 ms while LCC steers, and the request-minus-measured gap tracks the LCC torque (r +0.35 to +0.59). In manual driving it lags by 20-30 ms, so it echoes the measured angle when not steering. Sent by the ADAS unit (its own clock, with 0x142/0x229/0x2D1/0x2D5). No torque request found in this frame. The camera sends it (it vanished with the camera unplugged), and the EPS followed openpilot's copy both ways with LCC_STEERING_ACTIVE_COPY set and the LCC_RAMP word."; +CM_ SG_ 389 SEATBELT_REMINDER "INFERRED, NOT the belt state: matches the belt only before READY. While driving it follows standstill (0 when stopped, 1 when moving) with the belt buckled, which made openpilot refuse to engage from a stop. Use SEATBELT.DRIVER_SEATBELT_UNLATCHED."; +CM_ SG_ 656 BLINKER_LEFT "CONFIRMED by filmed step order: left, right, then hazards. Flips every 0.40 s. Both blinker bits on means hazards."; +CM_ SG_ 656 BLINKER_RIGHT "CONFIRMED by filmed step order: left, right, then hazards. Flips every 0.40 s."; +CM_ SG_ 656 DRIVER_DOOR_OPEN "CONFIRMED once by filmed door opening; 1 for 11.5 s. Bit 46 did the same, so one may be another door or a lamp."; +CM_ BO_ 183 "Bits 16 and 28 set when the camera is unplugged (probably ADAS unavailable). Every bit that is not always zero is defined (UNKNOWN_* fields copied as-is), so unpack-then-pack reproduces recorded frames exactly; needed to send the camera a cancel copy of this frame."; +CM_ SG_ 183 STALK_PUSH "CONFIRMED by stated order, parked: 1 is a single push (ACC), 2 is a double push (LCC, passing through 1 first), each held about 1 s. INFERRED: 3 is pushing the stalk up, which the driver says cancels assist. All 14 logged value-3 pushes during assist ended it within about 0.25 s."; +CM_ SG_ 183 TORQUE_DEMAND "WEAK: rises with acceleration (r 0.78-0.84), but stayed at 0 during 3 filmed accelerator presses in Park. Probably torque demand. Drops to 0 whenever the accelerator is released, even while slowing at -1.5 m/s^2, so it carries no regen."; +CM_ SG_ 182 ACCEL_PEDAL "CONFIRMED by 3 filmed presses in Park, peak 254 each. Scale 0.4 percent per count as in the Leapmotor T03 DBC, so 254 is about 100 percent. One-pedal mode was off for this test."; +CM_ SG_ 182 BRAKE_PRESSED "CONFIRMED by 3 filmed presses in Park. Ends assist, as the driver says: both logged cases within 0.01 s. One-pedal mode was off for this test. Rarely on while slowing on earlier routes, which the driver says were almost always in one-pedal mode."; +CM_ SG_ 182 GEAR "CONFIRMED by filmed shifts and the dashboard. Earlier routes agree: 1 moves only backward, 0 and 2 never move, 3 only forward."; +CM_ SG_ 390 BRAKE_PRESSURE "INFERRED: bytes 2-5 are identical, peaks 51-57 on 3 filmed presses, near 0 otherwise. In filmed braking tests it stayed near 0 for much of the time the pedal was pressed, which suggests blended braking (regen first, friction later). Unit unknown."; +CM_ SG_ 183 ASSIST_ENGAGED "INFERRED: 1 in all 15 assist periods on 5 routes, including 1 ACC-only period, 0 elsewhere while driving. Also matched a route not used in the search: on 0.6 s after the push, off 0.6 s after the cancel."; +CM_ SG_ 589 ASSIST_ENGAGED_COPY "INFERRED: same behaviour as 0xB7 bit 30."; +CM_ SG_ 131 ASSIST_OFF "INFERRED: exact inverse of ASSIST_ENGAGED on 5 routes. Bit 44 behaves the same."; +CM_ SG_ 589 LCC_ENGAGED "INFERRED: on 95-100% of LCC periods, off in the ACC-only period and when not engaged. Only 1 ACC-only period tested."; +CM_ SG_ 397 LCC_STEERING_ACTIVE "INFERRED: never on outside LCC, on for 54-100% of it, so possibly when LCC is steering. Not checked against the dashboard."; +CM_ SG_ 131 LCC_STEERING_ACTIVE_COPY "INFERRED: same behaviour as 0x18D bit 67."; +CM_ SG_ 397 STEER_TORQUE_EPS "INFERRED, 12 bits (bit 180 is EPS_STATUS_180): exactly 1000 raw when LCC is not steering on most routes, 939-1074 when it is, follows byte 10 (r 0.82-0.91). Possibly the torque applied by LCC. Unit unknown. Sign INFERRED: positive pushes the wheel right, negative left (stock LCC, 90,000 samples on 3 routes: the angle moves the opposite way to the value, r -0.20 to -0.37; confirmed by the stage-2 steering steps). Also moved during a probable lane-departure correction with assist off."; +CM_ SG_ 397 EPS_STATUS_180 "INFERRED, meaning unknown: was read as bit 12 of STEER_TORQUE_EPS, which then jumped by 4096 and looked like a huge driver torque. Never set on 7 drives (1.3M frames); set twice on route 26e, for exactly 1.0 s each, while openpilot steered at 60-64 km/h with about 30-60 torque. Not a fixed hands-off timer (117 s and 68 s of steering before it)."; +CM_ SG_ 322 FCW "INFERRED, strong: forward collision warning from the front camera. On for 1.5-3.3 s at the driver's reported warnings (2 of 2, route 00000261), each time about 2 s before the driver braked hard; ACC was off. About 13 rising edges per drive on 29 earlier drives. 0x229 bit 110 switches with it."; +CM_ SG_ 322 SPEED_LIMIT "CONFIRMED against filmed road-sign icons (90, 110): matches once a 1-2 s video timing difference is allowed. Values 20-130 in tens. A brief 50 lasting 0.6 s was not seen on the dashboard. 0 and 255 appear rarely and may mean none or invalid."; +CM_ SG_ 131 LCC_RAMP "CONFIRMED on the car (needed to steer left, and sets the EPS torque authority), meaning INFERRED: bytes 16-17 as one word. 0x7801 on every frame without LCC steering. While LCC steers it moves along a ladder of 254 per step (one step per frame): about 31 steps when it starts (0.5-0.6 s), deeper with lateral acceleration and speed, always 25-46 steps; steps = 19.1 + 9.94 * |lateral accel m/s^2| + 0.112 * speed km/h fits 142,234 stock frames (R^2 0.83). It jumps back to 0x7801 when LCC stops. The EPS torque range grows with the step count (about +/-10 early in the ramp, +/-45 at 30, +/-70 at 42-46). Earlier read as three fields; the top 4 bits are what looked like an LCC state (7 off, 6 engaging, 5 active, 4 curve). With the idle word plus the steering bit, the EPS followed openpilot's angle to the right only; with a fixed 30 steps it steered both ways but could not hold a curve at 75 km/h (torque flat at 61)."; +CM_ SG_ 131 ACC_SET_SPEED "CONFIRMED: equal to the filmed green ACC badge in 6 of 6 checks (50, 70, 100 km/h), steps with knob rotation. Scale 0.2 km/h, unlike the 0.1 of the Leapmotor T03."; +CM_ SG_ 388 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 388 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 563 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 563 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 397 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 397 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 131 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 131 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 389 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 389 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 656 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 656 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 183 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 183 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 182 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 182 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 390 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 390 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 322 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 322 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +CM_ SG_ 589 CHECKSUM "CONFIRMED: AUTOSAR E2E Profile 2, as opendbc volkswagen_mqb_meb_checksum: crc=0xFF; for bytes 1..end: crc=CRC8H2F[crc^b]; crc^=K[counter]; crc=CRC8H2F[crc]; checksum=crc^0xFF. K is a 16-entry table per message in checksum_constants.json, learned on route 0000022d and exact on every tested frame of 3 other routes from 2 other days."; +CM_ SG_ 589 COUNTER "CONFIRMED: rolling 0-15, one step per frame."; +VAL_ 182 GEAR 0 "P" 1 "R" 2 "N" 3 "D" ; +VAL_ 183 STALK_PUSH 0 "NONE" 1 "SINGLE" 2 "DOUBLE" 3 "UP_CANCEL" ; +VAL_ 131 ACC_STATE 1 "NOT_READY_INFERRED" 2 "READY_INFERRED" 3 "ENGAGED_INFERRED" ; diff --git a/opendbc_repo/opendbc/safety/declarations.h b/opendbc_repo/opendbc/safety/declarations.h index 015fd073ca..a8e5c08b18 100644 --- a/opendbc_repo/opendbc/safety/declarations.h +++ b/opendbc_repo/opendbc/safety/declarations.h @@ -38,6 +38,7 @@ #define SAFETY_VOLVO 36U #define SAFETY_MG 38U #define SAFETY_TESLA_PREAP 39U +#define SAFETY_LEAPMOTOR 40U #define GET_BIT(msg, b) ((bool)!!(((msg)->data[((b) / 8U)] >> ((b) % 8U)) & 0x1U)) #define GET_FLAG(value, mask) (((value) & (mask)) == (mask)) @@ -402,6 +403,7 @@ extern const safety_hooks rivian_hooks; extern const safety_hooks psa_hooks; extern const safety_hooks byd_hooks; extern const safety_hooks mg_hooks; +extern const safety_hooks leapmotor_hooks; extern const safety_hooks volvo_cma_hooks; extern const safety_hooks volvo_c1_hooks; diff --git a/opendbc_repo/opendbc/safety/modes/leapmotor.h b/opendbc_repo/opendbc/safety/modes/leapmotor.h new file mode 100644 index 0000000000..239105918e --- /dev/null +++ b/opendbc_repo/opendbc/safety/modes/leapmotor.h @@ -0,0 +1,222 @@ +#pragma once + +#include "opendbc/safety/declarations.h" + +// Leapmotor B10 (2025, global market). The front camera's ADAS_LKA (0x83) carries the LCC steering angle request; +// openpilot replaces it through a camera harness. Stock ACC stays in control of longitudinal, unless the longitudinal +// flag is set: then openpilot may also replace ADAS_LKA.ACC_ACCEL_REQ while stock ACC stays engaged. + +#define LEAPMOTOR_ADAS_LKA 0x83U // TX from openpilot (stock: front camera), steering angle request +#define LEAPMOTOR_VEHICLE_STATE 0xB6U // RX from VCU, accelerator pedal, brake pressed, gear +#define LEAPMOTOR_POWERTRAIN_STATE 0xB7U // RX from VCU, stock ACC/LCC engaged; TX to camera: stalk-up cancel only +#define LEAPMOTOR_WHEEL_SPEEDS 0x184U // RX from ESC, wheel speeds +#define LEAPMOTOR_EPS_STEERING 0x18DU // RX from EPS, steering angle + +#define LEAPMOTOR_MAIN_BUS 0U +#define LEAPMOTOR_CAM_BUS 2U + +// Steering angle is 0.02 deg per bit with the center at raw 32490. Raw rises to the right, so the angle is +// negated to match openpilot's convention (positive = left) +#define LEAPMOTOR_ANGLE_CENTER 32490 + +// ADAS_LKA.ACC_ACCEL_REQ: byte 4, 0.05 m/s^2 per bit, raw 100 = 0 m/s^2. Must match CarControllerParams. +#define LEAPMOTOR_ACCEL_INACTIVE 100 +// The camera's request at or below this (-2.0 m/s^2) is passed on: openpilot may ask for more braking, not less +#define LEAPMOTOR_ACCEL_STOCK_BRAKE 60 +#define LEAPMOTOR_FLAG_LONGITUDINAL_CONTROL 1U +// openpilot builds its frame from a camera frame that can be older than the latest one the panda has seen: on 6 log +// segments by 0 (88%), 1 (10%), 2 to 6 frames (0.4%). So the camera's last 8 requests (160 ms at 50 Hz) count. +#define LEAPMOTOR_CAMERA_ACCEL_HISTORY 8U + +static bool leapmotor_longitudinal = false; +static int leapmotor_camera_accel[LEAPMOTOR_CAMERA_ACCEL_HISTORY]; // the camera's ADAS_LKA.ACC_ACCEL_REQ, raw +static uint8_t leapmotor_camera_accel_idx = 0U; + +static void leapmotor_reset_camera_accel(void) { + for (uint8_t i = 0U; i < LEAPMOTOR_CAMERA_ACCEL_HISTORY; i++) { + leapmotor_camera_accel[i] = LEAPMOTOR_ACCEL_INACTIVE; + } + leapmotor_camera_accel_idx = 0U; +} + +// was this request among the camera's recent ones? +static bool leapmotor_is_camera_accel(int accel) { + bool found = false; + for (uint8_t i = 0U; i < LEAPMOTOR_CAMERA_ACCEL_HISTORY; i++) { + found = found || (leapmotor_camera_accel[i] == accel); + } + return found; +} + +// the least braking (highest raw) among the camera's recent requests +static int leapmotor_camera_accel_max(void) { + int max_accel = leapmotor_camera_accel[0]; + for (uint8_t i = 1U; i < LEAPMOTOR_CAMERA_ACCEL_HISTORY; i++) { + max_accel = SAFETY_MAX(max_accel, leapmotor_camera_accel[i]); + } + return max_accel; +} + +typedef struct { + uint32_t addr; + uint8_t constants[16]; +} LeapmotorE2EConstants; + +static uint32_t leapmotor_get_checksum(const CANPacket_t *msg) { + return (uint8_t)msg->data[0]; +} + +static uint8_t leapmotor_get_counter(const CANPacket_t *msg) { + return (uint8_t)msg->data[1] & 0xFU; +} + +// AUTOSAR E2E Profile 2, as volkswagen_mqb_meb_compute_crc: CRC-8H2F over bytes 1..end, then a +// per-message constant chosen by the counter. Constants learned from logs; exact on held-out routes. +#define LEAPMOTOR_E2E_COUNT 5U + +static uint32_t leapmotor_compute_checksum(const CANPacket_t *msg) { + static const LeapmotorE2EConstants E2E[LEAPMOTOR_E2E_COUNT] = { + {LEAPMOTOR_WHEEL_SPEEDS, {0xD9U, 0x90U, 0x33U, 0xE1U, 0x3AU, 0x1AU, 0xDFU, 0xC6U, 0xB5U, 0xDCU, 0xEEU, 0x04U, 0xFAU, 0xD7U, 0xD4U, 0x99U}}, + {LEAPMOTOR_EPS_STEERING, {0x61U, 0x4BU, 0x17U, 0xE4U, 0x78U, 0x0BU, 0xA1U, 0xB4U, 0xBCU, 0xD8U, 0xEAU, 0xF5U, 0xD9U, 0x21U, 0xCAU, 0x86U}}, + {LEAPMOTOR_VEHICLE_STATE, {0x71U, 0x0DU, 0x0BU, 0xC2U, 0x08U, 0xC6U, 0x63U, 0x4BU, 0x3FU, 0x2BU, 0x06U, 0x10U, 0xF0U, 0xD2U, 0x87U, 0x0DU}}, + {LEAPMOTOR_POWERTRAIN_STATE, {0xEBU, 0x4EU, 0xAEU, 0xCEU, 0x79U, 0x7CU, 0x52U, 0x03U, 0x6AU, 0x84U, 0xC2U, 0x3AU, 0x0AU, 0x64U, 0x2FU, 0x17U}}, + {LEAPMOTOR_ADAS_LKA, {0xCDU, 0x81U, 0x0AU, 0xC1U, 0x99U, 0x7FU, 0x8DU, 0x05U, 0x3BU, 0xA2U, 0x43U, 0xD2U, 0xB6U, 0x72U, 0x2AU, 0xD9U}}, + }; + + uint8_t constant = 0U; + for (uint8_t i = 0U; i < LEAPMOTOR_E2E_COUNT; i++) { + constant = (E2E[i].addr == msg->addr) ? E2E[i].constants[leapmotor_get_counter(msg)] : constant; + } + + int len = GET_LEN(msg); + uint8_t crc = 0xFFU; + for (int i = 1; i < len; i++) { + crc = crc8_update(crc, (uint8_t)msg->data[i], 0x2FU); + } + crc = crc8_update(crc, constant, 0x2FU); + return (uint8_t)(crc ^ 0xFFU); +} + +static void leapmotor_rx_hook(const CANPacket_t *msg) { + if (msg->bus == LEAPMOTOR_MAIN_BUS) { + if (msg->addr == LEAPMOTOR_WHEEL_SPEEDS) { + // four 16-bit little-endian wheel speeds at 0.01 km/h: FL, FR, RL, RR + uint32_t sum = GET_BYTES_LE(msg, 2, 2) + GET_BYTES_LE(msg, 4, 2) + GET_BYTES_LE(msg, 6, 2) + GET_BYTES_LE(msg, 8, 2); + vehicle_moving = sum > 0U; + UPDATE_VEHICLE_SPEED((sum / 4.0) * 0.01 * KPH_TO_MS); + } + + if (msg->addr == LEAPMOTOR_EPS_STEERING) { + int angle_meas_new = LEAPMOTOR_ANGLE_CENTER - (int)GET_BYTES_LE(msg, 3, 2); + update_sample(&angle_meas, angle_meas_new); + } + + if (msg->addr == LEAPMOTOR_VEHICLE_STATE) { + gas_pressed = msg->data[11] > 0U; // ACCEL_PEDAL + brake_pressed = GET_BIT(msg, 99U); // BRAKE_PRESSED + } + + if (msg->addr == LEAPMOTOR_POWERTRAIN_STATE) { + pcm_cruise_check(GET_BIT(msg, 30U)); // ASSIST_ENGAGED + } + } + + // only in rx_checks with the longitudinal flag + if ((msg->bus == LEAPMOTOR_CAM_BUS) && (msg->addr == LEAPMOTOR_ADAS_LKA)) { + leapmotor_camera_accel[leapmotor_camera_accel_idx] = msg->data[4]; // ACC_ACCEL_REQ + leapmotor_camera_accel_idx = (leapmotor_camera_accel_idx + 1U) % LEAPMOTOR_CAMERA_ACCEL_HISTORY; + } +} + +static bool leapmotor_tx_hook(const CANPacket_t *msg) { + // Must match LEAPMOTOR_B10 CarControllerParams.ANGLE_LIMITS: lateral accel and jerk limited through a vehicle model + static const AngleSteeringLimits LEAPMOTOR_STEERING_LIMITS = { + .max_angle = 25000, // 500 deg at 50 per deg; mechanical lock is about 522 deg + .angle_deg_to_can = 50, + .frequency = 50U, + }; + + static const AngleSteeringParams LEAPMOTOR_STEERING_PARAMS = { + .slip_factor = -0.0006132659333604452, // calc_slip_factor(VM) for LEAPMOTOR_B10 + .steer_ratio = 15.2, + .wheelbase = 2.735, + }; + + bool tx = true; + + // Only a cancel may be sent to the camera: STALK_PUSH (bits 40-41) must be 3, stalk pushed up + if (msg->addr == LEAPMOTOR_POWERTRAIN_STATE) { + if (((msg->data[5]) & 0x3U) != 3U) { + tx = false; + } + } + + if (msg->addr == LEAPMOTOR_ADAS_LKA) { + int desired_angle = LEAPMOTOR_ANGLE_CENTER - (int)GET_BYTES_LE(msg, 13, 2); // STEER_ANGLE_REQ + bool lka_active = GET_BIT(msg, 99U); // LCC_STEERING_ACTIVE_COPY + if (steer_angle_cmd_checks_vm(desired_angle, lka_active, LEAPMOTOR_STEERING_LIMITS, LEAPMOTOR_STEERING_PARAMS)) { + tx = false; + } + + if (leapmotor_longitudinal) { + int accel = msg->data[4]; // ACC_ACCEL_REQ + // The camera's own request may always be passed on: that is what the stock ACC sends when openpilot is not in + // control. openpilot's own request must be within -3.5..2.0 m/s^2 (raw 30..140) with controls allowed. Not also + // with the accelerator released, as longitudinal_accel_checks() wants: the panda sees a press one frame before + // openpilot can hand back to the stock ACC, and a blocked ADAS_LKA cancels the stock ACC. The car follows the + // pedal over any ACC request anyway, as with the camera's own requests, which it keeps sending for a few frames. + bool own_accel_ok = controls_allowed && !safety_max_limit_check(accel, 140, 30); + bool inactive = accel == LEAPMOTOR_ACCEL_INACTIVE; + if (!leapmotor_is_camera_accel(accel) && !own_accel_ok && !inactive) { + tx = false; + } + // never less braking than the camera asks for while all its recent requests are hard braking + int camera_floor = leapmotor_camera_accel_max(); + if ((camera_floor <= LEAPMOTOR_ACCEL_STOCK_BRAKE) && (accel > camera_floor)) { + tx = false; + } + } + } + return tx; +} + +static safety_config leapmotor_init(uint16_t param) { + leapmotor_longitudinal = GET_FLAG(param, LEAPMOTOR_FLAG_LONGITUDINAL_CONTROL); + leapmotor_reset_camera_accel(); + + static const CanMsg LEAPMOTOR_TX_MSGS[] = { + {LEAPMOTOR_ADAS_LKA, LEAPMOTOR_MAIN_BUS, 32, .check_relay = true}, + {LEAPMOTOR_POWERTRAIN_STATE, LEAPMOTOR_CAM_BUS, 32, .check_relay = false}, + }; + + safety_config ret; + if (leapmotor_longitudinal) { + // with openpilot longitudinal, the camera's own ADAS_LKA is also checked: its acceleration request is passed on + static const RxCheck leapmotor_long_rx_checks[] = { + {.msg = {{LEAPMOTOR_WHEEL_SPEEDS, LEAPMOTOR_MAIN_BUS, 32, 50U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_EPS_STEERING, LEAPMOTOR_MAIN_BUS, 32, 100U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_VEHICLE_STATE, LEAPMOTOR_MAIN_BUS, 16, 100U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_POWERTRAIN_STATE, LEAPMOTOR_MAIN_BUS, 32, 50U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_ADAS_LKA, LEAPMOTOR_CAM_BUS, 32, 50U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + }; + ret = BUILD_SAFETY_CFG(leapmotor_long_rx_checks, LEAPMOTOR_TX_MSGS); + } else { + static const RxCheck leapmotor_rx_checks[] = { + {.msg = {{LEAPMOTOR_WHEEL_SPEEDS, LEAPMOTOR_MAIN_BUS, 32, 50U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_EPS_STEERING, LEAPMOTOR_MAIN_BUS, 32, 100U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_VEHICLE_STATE, LEAPMOTOR_MAIN_BUS, 16, 100U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{LEAPMOTOR_POWERTRAIN_STATE, LEAPMOTOR_MAIN_BUS, 32, 50U, .max_counter = 15U, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + }; + ret = BUILD_SAFETY_CFG(leapmotor_rx_checks, LEAPMOTOR_TX_MSGS); + } + return ret; +} + +const safety_hooks leapmotor_hooks = { + .init = leapmotor_init, + .rx = leapmotor_rx_hook, + .tx = leapmotor_tx_hook, + .get_counter = leapmotor_get_counter, + .get_checksum = leapmotor_get_checksum, + .compute_checksum = leapmotor_compute_checksum, +}; diff --git a/opendbc_repo/opendbc/safety/safety.h b/opendbc_repo/opendbc/safety/safety.h index 1b7fa364f1..4a73456344 100644 --- a/opendbc_repo/opendbc/safety/safety.h +++ b/opendbc_repo/opendbc/safety/safety.h @@ -33,6 +33,7 @@ #include "opendbc/safety/modes/body.h" #include "opendbc/safety/modes/psa.h" #include "opendbc/safety/modes/byd.h" +#include "opendbc/safety/modes/leapmotor.h" #include "opendbc/safety/modes/hyundai_canfd.h" uint32_t GET_BYTES_LE(const CANPacket_t *msg, int start, int len) { @@ -470,6 +471,7 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { {SAFETY_CHRYSLER_CUSW, &chrysler_cusw_hooks}, {SAFETY_PSA, &psa_hooks}, {SAFETY_BYD, &byd_hooks}, + {SAFETY_LEAPMOTOR, &leapmotor_hooks}, {SAFETY_VOLKSWAGEN_MLB, &volkswagen_mlb_hooks}, {SAFETY_VOLKSWAGEN_PQ, &volkswagen_pq_hooks}, {SAFETY_ALLOUTPUT, &alloutput_hooks}, diff --git a/opendbc_repo/opendbc/safety/tests/common.py b/opendbc_repo/opendbc/safety/tests/common.py index 64cf33b564..93a43c4157 100644 --- a/opendbc_repo/opendbc/safety/tests/common.py +++ b/opendbc_repo/opendbc/safety/tests/common.py @@ -1010,6 +1010,10 @@ class SafetyTest(SafetyTestBase): if attr == 'TestVolkswagenMqbLongSafety' and current_test.startswith('TestHondaBoschRadarless'): tx = list(filter(lambda m: m[0] not in [0x30c, ], tx)) + # Leapmotor's steering angle request overlaps Ford's Steering_Data_FD1 (buttons, not actuating) + if attr.startswith('TestLeapmotor') and current_test.startswith('TestFord'): + tx = list(filter(lambda m: m[0] not in [0x83, ], tx)) + # TODO: Temporary, should be fixed in panda firmware, safety_honda.h if attr.startswith('TestHonda'): # exceptions for common msgs across different hondas diff --git a/opendbc_repo/opendbc/safety/tests/test_leapmotor.py b/opendbc_repo/opendbc/safety/tests/test_leapmotor.py new file mode 100644 index 0000000000..b5ada0122b --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_leapmotor.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +import math +import unittest +import numpy as np + +from opendbc.car.lateral import get_max_angle_delta_vm, get_max_angle_vm +from opendbc.car.leapmotor.carcontroller import get_safety_CP +from opendbc.car.leapmotor.values import CarControllerParams, LeapmotorSafetyFlags +from opendbc.car.structs import CarParams +from opendbc.car.vehicle_model import VehicleModel +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 + +ADAS_LKA = 0x83 +POWERTRAIN_STATE = 0xB7 + + +def round_angle(apply_angle, can_offset=0): + # STEER_ANGLE_REQ is -0.02 deg per bit, offset 649.8 deg, so 0 deg is exactly representable (raw 32490). + # can_offset is in angle units of 0.02 deg (positive = larger angle) + raw = math.floor((apply_angle - 649.8) / -0.02 + 0.5) - can_offset + return raw * -0.02 + 649.8 + +REAL_FRAMES = { # 20 consecutive frames per message from a 2025 global B10, route 00000232 (driving with ACC/LCC) + 0x184: [ + "14044E1E7D1EF41D061E55201CF3004FEB02CE59A8DE808888000800000000F0", + "BF056B1E881EF41D021E55601D063150FE021C2678DF878888000800000000F0", + "06066E1E801EF81DFB1D55901E1A615112030302C8217C8888000800000000F0", + "2607521E791E111EED1D55D01F2DA1522503EAF597E0798888000800000000F0", + "AA08671E801E0A1EFB1D55002141D153380310EA479E778888000800000000F0", + "AB098F1E791EF41D111E5540225401554B03065A08DF808888000800000000F0", + "6D0A601E791EFF1D1F1E5570236831565F03D41998A18C8888000800000000F0", + "B40B591E961E0D1EE21D55B0247B6157720313EA27E2758888000800000000F0", + "B40C801E921EFB1DED1D55E0258FA1588503221AA85E7F8888000800000000F0", + "5D0D841E8B1E061E0A1E552027A2D159980303C2D79E778888000800000000F0", + "8B0E791E8B1E061EFF1D555028B6015BAB03002638E07D8888000800000000F0", + "0A0F6E1E881EF01D0D1E559029CA315CBF03ED01481F878888000800000000F0", + "9300641E8F1EED1DF41D55C02ADD615DD203FAF5C7A2778888000800000000F0", + "B301761E8F1E111EFF1D55002CF1A15EE503133638617F8888000800000000F0", + "B802791E801E0A1EFB1D55302D04D25FF80309D2E71D758888000800000000F0", + "7C03761E791EE91D021E55702E1802610B040926B85D838888000800000000F0", + "B104591E791EED1DFB1D55A02F2B32621F04E70DA81F848888000800000000F0", + "4505591E801EE91DF41D55E0303F6263320413F6C7217D8888000800000000F0", + "1406671E761E0A1EF81D55103252A26445040DDE67E0798888000800000000F0", + "F0076E1E641E061EF81D55503366D2655804FD7947DE768888000800000000F0", + ], + 0x18D: [ + "300A02717E01F7438EAF4C0104030000F6018807A3D403000000000000000000", + "4F0B026E7E00F5438E834C0104040000F4018808A3D503000000000000000000", + "440C026E7E00F5438E8B4C0103040000F5018808A3D303000000000000000000", + "490D026B7E00F8438EB24C0104030000F7018807A3D403000000000000000000", + "A40E026B7E00FB438E984C0103040000F5018808A3D203000000000000000000", + "A80F02687E00F9438E924C0104040000F5018808A3D203000000000000000000", + "B90002687E01F6438E634C0104040000F3018809A3D303000000000000000000", + "530102657E00F6438E9A4C0104040000F5018808A3D003000000000000000000", + "840202627E00FB438EA34C0103040000F6018808A3D403000000000000000000", + "A20302627E00FC438E694C0104040000F3018809A3CE03000000000000000000", + "2704025E7E00F8438E6F4C0104040000F3018809A3D103000000000000000000", + "EB05025E7E00F3438E2F4C0105050000F001880AA3CF03000000000000000000", + "A606025B7E01F2438E4C4C0104040000F2018809A3D303000000000000000000", + "5707025B7E00F9438E7E4C0104040000F4018808A3D103000000000000000000", + "930802587E00FE438E824C0103040000F4018808A3D103000000000000000000", + "7B0902587E00FC438E514C0105040000F2018809A3CE03000000000000000000", + "060A02557E00F7438E454C0104050000F101880AA3D103000000000000000000", + "650B02557E00F4438E1C4C0105050000EF01880AA3CD03000000000000000000", + "F50C02527E00F6438E604C0104040000F3018809A3D003000000000000000000", + "C50D02527E00FB438E3C4C0104050000F101880AA3CC03000000000000000000", + ], + 0xB6: [ + "7C0E2C142C1488138813000060000000", + "7C0F2B142B1488138813000060000000", + "B2002B142B1488138813000060000000", + "60012B142B1488138813000060000000", + "84022B142B1488138813000060000000", + "FB032B142B1488138813000060000000", + "11042C142C1488138813000060000000", + "E2052D142D1488138813000060000000", + "E7062D142D1488138813000060000000", + "C1072D142D1488138813000060000000", + "58082D142D1488138813000060000000", + "09092C142C1488138813000060000000", + "500A2B142B1488138813000060000000", + "1E0B2B142B1488138813000060000000", + "270C2A142A1488138813000060000000", + "490D2B142B1488138813000060000000", + "940E2B142B1488138813000060000000", + "940F2C142C1488138813000060000000", + "5A002C142C1488138813000060000000", + "88012C142C1488138813000060000000", + ], + 0xB7: [ + "450B04401004B42C000000800000000055E2048D5E2013000000000000000000", + "070C04401004B42C000000800000000055E204855E2A13000000000000000000", + "230D04401004B42C000000800000000055E204855E2A13000000000000000000", + "A30E04401004B42C000000800000000055E204955E2C13000000000000000000", + "370F04401004B42C000000800000000055E204955E2813000000000000000000", + "460004401004B42C000000800000000055E204915E2613000000000000000000", + "A00104401004B42C000000800000000055E204895E2613000000000000000000", + "BC0204401004B42C000000800000000055E204855E1C13000000000000000000", + "5A0304401004B42C000000800000000055E204795E2C13000000000000000000", + "E50404401004B42C000000800000000055E2047D5E2E13000000000000000000", + "240504401004B42C000000800000000055E204895E2013000000000000000000", + "130604401004B42C000000800000000055E204855E2413000000000000000000", + "2B0704401004B42C000000800000000055E204715E2813000000000000000000", + "A60804401004B42C000000800000000055E204715E3013000000000000000000", + "E30904401004B42C000000800000000055E2047D5E2213000000000000000000", + "890A04401004B42C000000800000000055E204895E2413000000000000000000", + "810B04401004B42C000000800000000055E204815E2E13000000000000000000", + "8F0C04401004B42C000000800000000055E2047D5E2E13000000000000000000", + "7F0D04401004B42C000000800000000055E204855E3213000000000000000000", + "260E04401004B42C000000800000000055E204895E2613000000000000000000", + ], +} + + +class TestLeapmotorSafety(common.CarSafetyTest, common.AngleSteeringSafetyTest): + RELAY_MALFUNCTION_ADDRS = {0: (ADAS_LKA,)} + FWD_BLACKLISTED_ADDRS = {2: [ADAS_LKA]} + TX_MSGS = [[ADAS_LKA, 0], [POWERTRAIN_STATE, 2]] + + MAIN_BUS = 0 + + STEER_ANGLE_MAX = 500 + # the 16-bit request field only spans -661..649.8 deg, so test within it + STEER_ANGLE_TEST_MAX = 645 + DEG_TO_CAN = 50 + + # lateral accel and jerk are limited through a vehicle model, tested below as for Tesla + ANGLE_RATE_BP = None + ANGLE_RATE_UP = None + ANGLE_RATE_DOWN = None + + LATERAL_FREQUENCY = 50 # Hz + + cnt_angle_cmd = 0 + + def _get_steer_cmd_angle_max(self, speed): + return get_max_angle_vm(max(speed, 1), self.VM, CarControllerParams) + + SAFETY_PARAM = 0 + + def setUp(self): + self.VM = VehicleModel(get_safety_CP()) + self.packer = CANPackerSafety("leapmotor_b10") + self.safety = libsafety_py.libsafety + self.safety.set_safety_hooks(CarParams.SafetyModel.leapmotor, self.SAFETY_PARAM) + self.safety.init_tests() + + def _angle_cmd_msg(self, angle: float, enabled: bool, increment_timer: bool = True): + values = {"STEER_ANGLE_REQ": angle, "LCC_STEERING_ACTIVE_COPY": enabled, "ACC_ACCEL_REQ": 0} + if increment_timer: + self.safety.set_timer(self.cnt_angle_cmd * int(1e6 / self.LATERAL_FREQUENCY)) + self.__class__.cnt_angle_cmd += 1 + return self.packer.make_can_msg_safety("ADAS_LKA", self.MAIN_BUS, values) + + def _angle_meas_msg(self, angle: float): + return self.packer.make_can_msg_safety("EPS_STEERING", self.MAIN_BUS, {"STEER_ANGLE": angle}) + + def _pcm_status_msg(self, enable): + return self.packer.make_can_msg_safety("POWERTRAIN_STATE", self.MAIN_BUS, {"ASSIST_ENGAGED": enable}) + + def _speed_msg(self, speed): + kph = speed * 3.6 + values = {"WHEEL_SPEED_FL": kph, "WHEEL_SPEED_FR": kph, "WHEEL_SPEED_RL": kph, "WHEEL_SPEED_RR": kph} + return self.packer.make_can_msg_safety("WHEEL_SPEEDS", self.MAIN_BUS, values) + + def _user_brake_msg(self, brake): + return self.packer.make_can_msg_safety("VEHICLE_STATE", self.MAIN_BUS, {"BRAKE_PRESSED": brake}) + + def _user_gas_msg(self, gas): + return self.packer.make_can_msg_safety("VEHICLE_STATE", self.MAIN_BUS, {"ACCEL_PEDAL": gas * 100}) + + def test_angle_cmd_when_enabled(self): + # lateral acceleration and jerk are tested below + pass + + @staticmethod + def _can_speed(speed): + # match WHEEL_SPEEDS rounding (0.01 km/h) + return round_speed(away_round(speed * 3.6 / 0.01) * 0.01 / 3.6) + + def test_lateral_accel_limit(self): + for speed in np.linspace(0, 40, 100): + speed = self._can_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 the limit: safety truncates the limit to CAN units and adds 1 unit of tolerance + limit_raw = int(get_max_angle_vm(speed, self.VM, CarControllerParams) * self.DEG_TO_CAN) + 1 + max_angle = np.clip(sign * limit_raw / self.DEG_TO_CAN, -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))) + + # one unit above the limit, unless the limit is above the EPS maximum (low speed) + max_angle_raw = sign * (limit_raw + 1) / self.DEG_TO_CAN + max_angle = np.clip(max_angle_raw, -self.STEER_ANGLE_MAX, self.STEER_ANGLE_MAX) + self._tx(self._angle_cmd_msg(max_angle, True)) + should_tx = abs(max_angle_raw) >= self.STEER_ANGLE_MAX + self.assertEqual(should_tx, self._tx(self._angle_cmd_msg(max_angle, True))) + + def test_lateral_jerk_limit(self): + for speed in np.linspace(0, 40, 100): + speed = self._can_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 + self._tx(self._angle_cmd_msg(0, True)) + + # within limits: up, hold, down + max_angle_delta = round_angle(get_max_angle_delta_vm(speed, self.VM, CarControllerParams) * sign) + self.assertTrue(self._tx(self._angle_cmd_msg(max_angle_delta, True))) + self.assertTrue(self._tx(self._angle_cmd_msg(max_angle_delta, True))) + self.assertTrue(self._tx(self._angle_cmd_msg(0, True))) + + # too fast: up, then down + max_angle_delta = round_angle(get_max_angle_delta_vm(speed, self.VM, CarControllerParams) * sign, 2 * sign) + self.assertFalse(self._tx(self._angle_cmd_msg(max_angle_delta, True))) + 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))) + self.assertFalse(self._tx(self._angle_cmd_msg(0, True))) + + # recover + self.assertTrue(self._tx(self._angle_cmd_msg(0, True))) + + def test_cancel_only(self): + # the camera copy of POWERTRAIN_STATE may only carry the stalk-up cancel, at any time + for allowed in (False, True): + self.safety.set_controls_allowed(allowed) + for stalk in range(4): + msg = self.packer.make_can_msg_safety("POWERTRAIN_STATE", 2, {"STALK_PUSH": stalk}) + self.assertEqual(stalk == 3, self._tx(msg), stalk) + + def test_rx_hook(self): + # a valid frame passes; a bad checksum or a skipped counter is rejected + for _ in range(10): + self.assertTrue(self._rx(self._speed_msg(0))) + msg = self._speed_msg(0) + msg[0].data[0] ^= 0xFF + self.assertFalse(self._rx(msg)) + + def test_angle_sign_matches_dbc(self): + # a real frame at right lock must give a negative measured angle in C, as in the DBC (positive = left) + right_lock = "0B0602CAE4009EC5869A5E012C2C0000D5128658A3E803000000000000000000" # raw 58570, about -521.6 deg + self.assertTrue(self._rx(libsafety_py.make_CANPacket(0x18D, self.MAIN_BUS, bytes.fromhex(right_lock)))) + # one frame into an empty sample history: the new value is the minimum, the old zeros are the maximum + self.assertEqual(self.safety.get_angle_meas_min(), 32490 - 58570) + + def test_real_frames(self): + # unmodified frames from a real car must pass the C checksum and counter checks + for addr, frames in REAL_FRAMES.items(): + for hexdata in frames: + self.assertTrue(self._rx(libsafety_py.make_CANPacket(addr, self.MAIN_BUS, bytes.fromhex(hexdata))), hex(addr)) + bad = bytearray.fromhex(frames[-1]) + bad[0] ^= 0x01 + self.assertFalse(self._rx(libsafety_py.make_CANPacket(addr, self.MAIN_BUS, bytes(bad))), hex(addr)) + + +class TestLeapmotorLongitudinalSafety(TestLeapmotorSafety, common.LongitudinalAccelSafetyTest): + SAFETY_PARAM = LeapmotorSafetyFlags.LONG_CONTROL + MAX_ACCEL = CarControllerParams.ACCEL_MAX + MIN_ACCEL = CarControllerParams.ACCEL_MIN + + def _accel_msg(self, accel: float, bus: int = 0): + # steering inactive, so only the acceleration request is checked + values = {"STEER_ANGLE_REQ": 0, "LCC_STEERING_ACTIVE_COPY": 0, "ACC_ACCEL_REQ": accel} + return self.packer.make_can_msg_safety("ADAS_LKA", bus, values) + + CAMERA_ACCEL_HISTORY = 8 # LEAPMOTOR_CAMERA_ACCEL_HISTORY + + def _camera_accel(self, *accels): + for accel in accels: + self.assertTrue(self._rx(self._accel_msg(accel, bus=2))) + + def test_camera_accel_passthrough(self): + # without controls allowed, only the camera's own request (or 0) may be sent + self.safety.set_controls_allowed(False) + self._camera_accel(-1.0) + self.assertTrue(self._tx(self._accel_msg(-1.0))) + self.assertTrue(self._tx(self._accel_msg(0))) + self.assertFalse(self._tx(self._accel_msg(-1.5))) + self.assertFalse(self._tx(self._accel_msg(0.5))) + + def test_camera_accel_passthrough_lags(self): + # openpilot's frame can carry a camera request a few frames older than the panda's latest: any of the last 8 passes + self.safety.set_controls_allowed(False) + self._camera_accel(0.55) + self._camera_accel(*[0.6] * (self.CAMERA_ACCEL_HISTORY - 1)) + self.assertTrue(self._tx(self._accel_msg(0.55))) + self._camera_accel(0.6) + self.assertFalse(self._tx(self._accel_msg(0.55))) + + def test_camera_accel_beyond_limits(self): + # the camera's emergency braking (beyond openpilot's -3.5) is passed on, also as it releases + self.safety.set_controls_allowed(True) + self._camera_accel(-4.5, -3.6) + self.assertTrue(self._tx(self._accel_msg(-4.5))) + self._camera_accel(-1.3) + self.assertTrue(self._tx(self._accel_msg(-3.6))) + self.assertFalse(self._tx(self._accel_msg(-4.0))) + + def test_accel_with_gas_pressed(self): + # the panda sees an accelerator press a frame before openpilot hands back to the stock ACC: its own request stays allowed + self.safety.set_controls_allowed(True) + self._rx(self._user_gas_msg(1)) + self._rx(self._user_gas_msg(1)) + self.assertTrue(self._tx(self._accel_msg(-1.15))) + self.assertFalse(self._tx(self._accel_msg(-3.6))) + + def test_stock_brake_floor(self): + # while all the camera's recent requests are hard braking, openpilot may not ask for less than the least of them + self.safety.set_controls_allowed(True) + for camera_accel in (-1.95, -2.0, -2.5, -3.0): + self._camera_accel(*[camera_accel] * self.CAMERA_ACCEL_HISTORY) + hard = camera_accel <= CarControllerParams.STOCK_BRAKE_PASSTHROUGH + self.assertTrue(self._tx(self._accel_msg(camera_accel))) + self.assertTrue(self._tx(self._accel_msg(-3.5))) + self.assertEqual(not hard, self._tx(self._accel_msg(camera_accel + 0.05)), camera_accel) + self.assertEqual(not hard, self._tx(self._accel_msg(1.0)), camera_accel) + + def test_stock_brake_floor_ramp(self): + # the camera starts braking hard: openpilot, a frame behind, still sent its own request when it saw -1.95 + self.safety.set_controls_allowed(True) + self._camera_accel(*[-1.5] * self.CAMERA_ACCEL_HISTORY) + self._camera_accel(-1.95, -2.0) + self.assertTrue(self._tx(self._accel_msg(-0.7))) + # once every recent request is hard braking, the floor holds + self._camera_accel(*[-2.6] * self.CAMERA_ACCEL_HISTORY) + self.assertFalse(self._tx(self._accel_msg(-0.7))) + self.assertTrue(self._tx(self._accel_msg(-2.6))) + + +if __name__ == "__main__": + unittest.main() diff --git a/openpilot/starpilot/controllers/wheel_actions.py b/openpilot/starpilot/controllers/wheel_actions.py index 73ab5002e5..2eb243d475 100644 --- a/openpilot/starpilot/controllers/wheel_actions.py +++ b/openpilot/starpilot/controllers/wheel_actions.py @@ -45,7 +45,7 @@ def button_reported(cp, key): brand = cp.brand if key not in KEYS[:8]: return True # Physical media rows have their separate receiver contract. - if brand in ('body', 'byd', 'mg', 'mock', 'psa', 'rivian', 'subaru'): + if brand in ('body', 'byd', 'leapmotor', 'mg', 'mock', 'psa', 'rivian', 'subaru'): return False if brand == 'toyota': from opendbc.car.toyota import legacy_advert_filter, camera_2aa_filter