mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-25 22:33:43 +08:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8a17afb21 | |||
| ff4b154609 |
@@ -16,8 +16,7 @@ from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus
|
||||
normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand)
|
||||
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology
|
||||
from opendbc.car.hyundai.discovery import normal_bus_topology
|
||||
from opendbc.car.honda.discovery import (eps_needs_obd as honda_eps_needs_obd, nidec_bus0_topology,
|
||||
normal_bus_topology as honda_normal_bus_topology)
|
||||
from opendbc.car.honda.discovery import nidec_bus0_topology, normal_bus_topology as honda_normal_bus_topology
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
|
||||
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
|
||||
@@ -216,12 +215,6 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
else:
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
|
||||
query_brand=normal_brand, normal_bus_only=True)
|
||||
if normal_brand == 'honda' and honda_eps_needs_obd(match_fw_to_car(car_fw, vin)[1], car_fw):
|
||||
# Read this car's VIN and EPS through the OBD port, as the generic path below does. Without the VIN
|
||||
# the result is never cached, so every start would repeat the query.
|
||||
set_obd_multiplexing(True)
|
||||
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, (0, 1))
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda')
|
||||
ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
|
||||
else:
|
||||
full_scan = True
|
||||
|
||||
@@ -375,7 +375,6 @@ FW_VERSIONS = {
|
||||
b'68402704AB',
|
||||
b'68402707AB',
|
||||
b'68402708AB',
|
||||
b'68402710AB',
|
||||
b'68402714AB',
|
||||
b'68402736AB',
|
||||
b'68402971AD',
|
||||
@@ -422,7 +421,6 @@ FW_VERSIONS = {
|
||||
b'68412635AH ',
|
||||
b'68412660AD ',
|
||||
b'68412660AF ',
|
||||
b'68422857AD',
|
||||
b'68422860AB',
|
||||
b'68449435AE ',
|
||||
b'68496223AA ',
|
||||
@@ -437,7 +435,6 @@ FW_VERSIONS = {
|
||||
b'68419675AC',
|
||||
b'68419678AB',
|
||||
b'68423905AB',
|
||||
b'68423907AB',
|
||||
b'68449258AC',
|
||||
b'68495807AA',
|
||||
b'68495807AB',
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""Recorded ECU identity for the EU 2019 Grand Cherokee, opendbc issue 4101."""
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.chrysler.interface import CarInterface
|
||||
from opendbc.car.chrysler.values import CAR, ChryslerFlags
|
||||
from opendbc.car.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.fw_versions import match_fw_to_car
|
||||
|
||||
Ecu = structs.CarParams.Ecu
|
||||
RECORDED = (
|
||||
(Ecu.combinationMeter, 0x742, b'68402710AB'),
|
||||
(Ecu.srs, 0x744, b'68355363AB'),
|
||||
(Ecu.abs, 0x747, b'68408639AC'),
|
||||
(Ecu.fwdRadar, 0x753, b'04672788AA'),
|
||||
(Ecu.eps, 0x75a, b'68417281AA'),
|
||||
(Ecu.engine, 0x7e0, b'68422857AD'),
|
||||
(Ecu.transmission, 0x7e1, b'68423907AB'),
|
||||
)
|
||||
ADDED = {b'68402710AB', b'68422857AD', b'68423907AB'}
|
||||
|
||||
|
||||
def firmware():
|
||||
return [structs.CarParams.CarFw(ecu=ecu, address=address, fwVersion=version, brand='chrysler', bus=0)
|
||||
for ecu, address, version in RECORDED]
|
||||
|
||||
|
||||
def test_recorded_eu_diesel_is_a_unique_exact_match():
|
||||
fw = firmware()
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
# The route also contains unrelated cross-brand responses at the engine's neighbor.
|
||||
fw.append(structs.CarParams.CarFw(ecu=Ecu.transmission, address=0x7e1, fwVersion=b'\xf1\0\0E\x01\x01', brand='hyundai', bus=1))
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('index', range(len(RECORDED)))
|
||||
def test_unknown_firmware_still_refuses_exact_match(index):
|
||||
fw = firmware()
|
||||
fw[index].fwVersion = b'UNRECOGNIZED'
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, set())
|
||||
|
||||
|
||||
def test_additions_are_scoped_to_the_existing_2019_jeep():
|
||||
for identity, ecus in FW_VERSIONS.items():
|
||||
found = {version for versions in ecus.values() for version in versions} & ADDED
|
||||
assert found == (ADDED if identity == CAR.JEEP_GRAND_CHEROKEE_2019 else set())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha_long', (False, True))
|
||||
def test_diesel_retains_stock_acc_pid_and_native_limits(alpha_long):
|
||||
cp = CarInterface.get_params(CAR.JEEP_GRAND_CHEROKEE_2019, {b: {} for b in range(8)}, firmware(), alpha_long, False, False)
|
||||
assert cp.pcmCruise and not cp.openpilotLongitudinalControl
|
||||
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.chrysler
|
||||
assert cp.safetyConfigs[0].safetyParam == 0
|
||||
assert cp.minSteerSpeed == 17.5 and cp.lateralTuning.which() == 'pid'
|
||||
assert cp.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED
|
||||
assert not cp.flags & ChryslerFlags.STEERING_SPEED_BYPASS
|
||||
@@ -1,5 +1,3 @@
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
from opendbc.car import ACCEL_MAX_TAKEOFF
|
||||
|
||||
@@ -12,12 +10,9 @@ from opendbc.car.honda.nidec_interceptor import NidecInterceptor, create_command
|
||||
from opendbc.car.honda.bosch_longitudinal import BoschLongitudinal, qualified as bosch_long_qualified
|
||||
from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams
|
||||
from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_delta_vm
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
|
||||
VisualAlert = structs.CarControl.HUDControl.VisualAlert
|
||||
LongCtrlState = structs.CarControl.Actuators.LongControlState
|
||||
SteerControlType = structs.CarParams.SteerControlType
|
||||
|
||||
|
||||
def compute_gb_honda_bosch(accel, speed):
|
||||
@@ -125,54 +120,6 @@ class CarController(CarControllerBase):
|
||||
self.brake = 0.0
|
||||
self.last_torque = 0.0
|
||||
|
||||
# Accord angle-loop EPS (interface.py sets steerControlType = angle)
|
||||
self.angle_mode = CP.steerControlType == SteerControlType.angle
|
||||
self.VM = VehicleModel(CP) if self.angle_mode else None
|
||||
self.apply_angle_last = None # None until the first frame seeds the limiter from the wheel
|
||||
self.angle_steer_req = False # STEER_TORQUE_REQUEST of the last angle frame
|
||||
|
||||
def _angle_hold_allowed(self, CC, CS) -> bool:
|
||||
# The panda blocks a nonzero 0xE4 field unless lateral_controls_allowed(). Without an AOL policy that is
|
||||
# controls_allowed (needs ACC main on and engagement); with one it is a session-acknowledged axis permission the
|
||||
# carcontroller cannot see, so the hold is sent only in the subset every policy allows: enabled with main on.
|
||||
return bool(CS.out.cruiseState.available) and bool(CC.enabled)
|
||||
|
||||
def _update_angle(self, CC, CS) -> tuple[float, int]:
|
||||
"""Angle setpoint (deg) and the 0xE4 STEER_TORQUE field."""
|
||||
p = self.params
|
||||
steering_angle = float(CS.out.steeringAngleDeg)
|
||||
angle_last = steering_angle if self.apply_angle_last is None else self.apply_angle_last
|
||||
desired = float(CC.actuators.steeringAngleDeg)
|
||||
if CC.latActive:
|
||||
# error clip first: it shapes the request, bounding the P torque the setpoint asks of the EPS
|
||||
error_max = float(np.interp(CS.out.vEgoRaw, p.ANGLE_ERROR_MAX_BP, p.ANGLE_ERROR_MAX_V))
|
||||
desired = float(np.clip(desired, steering_angle - error_max, steering_angle + error_max))
|
||||
# The lateral accel and jerk limits (3.589) are the last adjustment: applied to exactly what is sent and seeded
|
||||
# from the last value sent. The panda runs the same check on the frame (honda.h) and blocks one that exceeds it,
|
||||
# so nothing may change the setpoint after this line.
|
||||
apply_angle = apply_steer_angle_limits_vm(desired, angle_last, CS.out.vEgoRaw, steering_angle, CC.latActive, p, self.VM)
|
||||
self.angle_steer_req = bool(CC.latActive)
|
||||
if CC.latActive:
|
||||
v = max(float(CS.out.vEgoRaw), 1.0)
|
||||
max_delta = min(get_max_angle_delta_vm(v, self.VM, p), p.ANGLE_LIMITS.MAX_ANGLE_RATE)
|
||||
if abs(apply_angle - angle_last) > max_delta + 1e-6:
|
||||
# The accel limit is further from the last value sent than the jerk limit lets one frame move: the wheel is
|
||||
# past the limit as the request starts. No setpoint satisfies both, and the panda would drop the frame, so
|
||||
# the request waits at the wheel until the wheel is back inside.
|
||||
apply_angle = steering_angle
|
||||
self.angle_steer_req = False
|
||||
self.apply_angle_last = apply_angle
|
||||
|
||||
# raw = round(-10 * deg), half-up; left-positive degrees are negative raw
|
||||
if CC.latActive:
|
||||
raw = math.floor(-10.0 * apply_angle + 0.5)
|
||||
elif self._angle_hold_allowed(CC, CS):
|
||||
# idle hold: keep the setpoint at the wheel so engagement starts without a step
|
||||
raw = math.floor(-10.0 * steering_angle + 0.5)
|
||||
else:
|
||||
raw = 0 # the panda blocks a nonzero field here
|
||||
return apply_angle, int(np.clip(raw, -p.ANGLE_RAW_MAX, p.ANGLE_RAW_MAX))
|
||||
|
||||
def update(self, CC, CS, now_nanos):
|
||||
_projection = self.learning_projection_observer
|
||||
if _projection is not None:
|
||||
@@ -229,12 +176,7 @@ class CarController(CarControllerBase):
|
||||
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
|
||||
|
||||
# Send steering command.
|
||||
if self.angle_mode:
|
||||
apply_angle, angle_raw = self._update_angle(CC, CS)
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, angle_raw, self.angle_steer_req,
|
||||
self.tja_control, angle_arm=self.params.ANGLE_ARM))
|
||||
else:
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
|
||||
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
|
||||
if _projection is not None:
|
||||
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1])
|
||||
|
||||
@@ -344,9 +286,6 @@ class CarController(CarControllerBase):
|
||||
new_actuators.brake = self.brake
|
||||
new_actuators.torque = self.last_torque
|
||||
new_actuators.torqueOutputCan = apply_torque
|
||||
if self.angle_mode:
|
||||
new_actuators.steeringAngleDeg = apply_angle
|
||||
new_actuators.torqueOutputCan = angle_raw # the 0xE4 STEER_TORQUE field as sent (-10 x deg)
|
||||
|
||||
self.frame += 1
|
||||
if _projection is not None:
|
||||
|
||||
@@ -13,7 +13,6 @@ from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, honda_sig
|
||||
from opendbc.can.dbc import DBC as CANDBC
|
||||
|
||||
TransmissionType = structs.CarParams.TransmissionType
|
||||
SteerControlType = structs.CarParams.SteerControlType
|
||||
ButtonType = structs.CarState.ButtonEvent.Type
|
||||
|
||||
BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise,
|
||||
@@ -121,16 +120,6 @@ class CarState(CarStateBase):
|
||||
ret.steerFaultPermanent = False
|
||||
ret.steerFaultTemporary = False
|
||||
|
||||
if self.CP.flags & HondaFlags.EPS_FW_UNREAD:
|
||||
ret.steerFaultPermanent = True
|
||||
|
||||
if self.CP.steerControlType == SteerControlType.angle and self.CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW:
|
||||
# the angle-loop EPS's angle is a valid absolute angle only while all three sensor status bits read 1; outside
|
||||
# that the EPS would servo from a false angle, so do not steer
|
||||
sensors = cp.vl["STEERING_SENSORS"]
|
||||
if not all(sensors[f"STEER_SENSOR_STATUS_{i}"] == 1 for i in (1, 2, 3)):
|
||||
ret.steerFaultTemporary = True
|
||||
|
||||
# All Honda EPS cut off slightly above standstill, some much higher
|
||||
# Don't alert in the near-standstill range, but alert for per-vehicle configured minimums above that
|
||||
if CarControllerParams.STEER_GLOBAL_MIN_SPEED < ret.vEgo < (self.CP.minSteerSpeed + 0.5):
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from opendbc.car.honda.hondacan import honda_checksum
|
||||
from opendbc.car.honda.values import CAR
|
||||
|
||||
|
||||
# Classic Bosch: PT on bus 1 and the stock ACC camera on bus 2. This selects
|
||||
@@ -31,9 +30,3 @@ def normal_bus_topology(packets, *, layout=NORMAL_BUS_LAYOUT):
|
||||
|
||||
def nidec_bus0_topology(packets):
|
||||
return any(normal_bus_topology(packets, layout=layout) for layout in NIDEC_BUS0_LAYOUTS)
|
||||
|
||||
|
||||
def eps_needs_obd(candidates, car_fw) -> bool:
|
||||
"""The Accord's EPS answers only through the OBD port (never on the normal bus 1 wiring), and its firmware
|
||||
family decides between angle and torque steering. A normal-bus read that names the Accord is not complete."""
|
||||
return CAR.HONDA_ACCORD in candidates and not any(fw.ecu == "eps" and not fw.logging for fw in car_fw)
|
||||
|
||||
@@ -117,15 +117,11 @@ def create_acc_commands(packer, CAN, enabled, active, accel, gas, stopping_count
|
||||
return commands
|
||||
|
||||
|
||||
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control, angle_arm=None):
|
||||
# angle_arm (Accord angle-loop EPS only): STEER_TORQUE is the angle setpoint, sent with the request off too, and
|
||||
# STEER_CONTROL_ARM carries the arm the EPS lane requires. None = the torque frame, unchanged.
|
||||
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control):
|
||||
values = {
|
||||
"STEER_TORQUE": apply_torque if (lkas_active or angle_arm is not None) else 0,
|
||||
"STEER_TORQUE": apply_torque if lkas_active else 0,
|
||||
"STEER_TORQUE_REQUEST": lkas_active,
|
||||
}
|
||||
if angle_arm is not None:
|
||||
values["STEER_CONTROL_ARM"] = angle_arm
|
||||
|
||||
if tja_control:
|
||||
values["STEER_DOWN_TO_ZERO"] = lkas_active
|
||||
|
||||
@@ -7,9 +7,7 @@ from opendbc.car import Bus, get_safety_config, structs, uds
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.disable_ecu import disable_ecu
|
||||
from opendbc.car.honda.hondacan import CanBus
|
||||
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC, \
|
||||
is_accord_eps_angle_loop_fw
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL
|
||||
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.carstate import CarState
|
||||
from opendbc.car.honda.radar_interface import RadarInterface
|
||||
@@ -102,12 +100,7 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.longitudinalTuning.kiV = [1.2, 0.8, 0.5]
|
||||
|
||||
eps_observations = [fw for fw in car_fw if fw.ecu == "eps" and not fw.logging]
|
||||
# Accord angle-loop EPS firmware (39990-TVA,A16<letter>): the EPS closes the angle loop and openpilot sends the
|
||||
# setpoint. Not a torque-modified EPS, so it is kept out of the MODIFIED_EPS_FW allow-list check below (which would
|
||||
# otherwise make the car dashcam-only). Every EPS response must be the family; a mixed read falls through to it.
|
||||
eps_angle_loop_fw = (candidate == CAR.HONDA_ACCORD and len(eps_observations) > 0 and
|
||||
all(is_accord_eps_angle_loop_fw(fw.fwVersion) for fw in eps_observations))
|
||||
modified_eps = not eps_angle_loop_fw and any(b"," in fw.fwVersion for fw in eps_observations)
|
||||
modified_eps = any(b"," in fw.fwVersion for fw in eps_observations)
|
||||
eps_modified = bool(modified_eps) and all(
|
||||
fw.address == 0x18DA30F1 and fw.subAddress == 0 and
|
||||
fw.fwVersion in MODIFIED_EPS_FW.get(candidate, ()) for fw in eps_observations)
|
||||
@@ -128,21 +121,6 @@ class CarInterface(CarInterfaceBase):
|
||||
|
||||
elif candidate == CAR.HONDA_ACCORD:
|
||||
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = ([[0.3], [0.09]] if eps_modified else [[0.6], [0.18]])
|
||||
if eps_angle_loop_fw:
|
||||
# angle-loop EPS firmware: the EPS closes the angle loop, openpilot sends the setpoint
|
||||
ret.flags |= HondaFlags.EPS_ANGLE_LOOP_FW.value
|
||||
ret.safetyConfigs[-1].safetyParam |= HondaSafetyFlags.ACCORD_ANGLE.value
|
||||
ret.steerControlType = structs.CarParams.SteerControlType.angle
|
||||
ret.steerActuatorDelay = CarControllerParams.ANGLE_STEER_ACTUATOR_DELAY
|
||||
# The torque fit's MAX_LAT_ACCEL_MEASURED (0.32 m/s^2) means nothing to an angle setpoint; the onroad torque
|
||||
# bar divides by this, so normalise it by the angle limit instead (3.589 m/s^2, where the setpoint clamp binds).
|
||||
# Measured engaged hands-off over 35 routes: p99.9 3.46 m/s^2, per-route maxima 3.4-4.1. Only the bar and the
|
||||
# car docs read maxLateralAccel; no controller or torque tune does.
|
||||
ret.maxLateralAccel = MAX_LATERAL_ACCEL
|
||||
elif not docs and not eps_observations:
|
||||
# EPS fw unread: an angle-loop EPS would ignore torque frames (engaged, no steering, no alert), so fault instead.
|
||||
# Note: upstream lists this EPS as non-essential (lost without comma power); such an Accord faults here too.
|
||||
ret.flags |= HondaFlags.EPS_FW_UNREAD.value
|
||||
|
||||
elif candidate == CAR.HONDA_ACCORD_11G:
|
||||
ret.longitudinalActuatorDelay = 0.05
|
||||
|
||||
@@ -37,11 +37,8 @@ MANUAL_SELECTION_PORTS = CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_R
|
||||
# qualified() runs several times per 100 Hz frame in card and selfdrived, so
|
||||
# everything that depends only on this module is computed once, and its flag
|
||||
# tests use plain ints: IntFlag operators cost microseconds each in Python.
|
||||
# EPS_ANGLE_LOOP_FW / EPS_FW_UNREAD: Accord-only EPS-firmware detections (interface.py); the angle car keeps AOL, and
|
||||
# an unread EPS is already a permanent steer fault in carstate, so neither may drop the car out of these owners.
|
||||
_DETECTED = int(HondaFlags.BOSCH_EXT_HUD | HondaFlags.BOSCH_ALT_BRAKE | HondaFlags.HAS_BSM |
|
||||
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR |
|
||||
HondaFlags.EPS_ANGLE_LOOP_FW | HondaFlags.EPS_FW_UNREAD)
|
||||
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR)
|
||||
_ALLOWED_FLAGS = {str(car): int(car.config.flags) | _DETECTED
|
||||
for car in CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_RADAR_STOCK | {CAR.HONDA_ACCORD_11G}}
|
||||
_BOSCH, _BOSCH_RADARLESS, _BOSCH_ALT_BRAKE = int(HondaFlags.BOSCH), int(HondaFlags.BOSCH_RADARLESS), int(HondaFlags.BOSCH_ALT_BRAKE)
|
||||
@@ -105,8 +102,6 @@ def qualified(cp, *, marked_only=False):
|
||||
safety.safetyModel == _HONDA_NIDEC and safety.safetyParam == expected)
|
||||
if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS:
|
||||
expected = int(bool(flags & _BOSCH_ALT_BRAKE))
|
||||
if fingerprint == CAR.HONDA_ACCORD and flags & int(HondaFlags.EPS_ANGLE_LOOP_FW):
|
||||
expected |= int(HondaSafetyFlags.ACCORD_ANGLE)
|
||||
if cp.openpilotLongitudinalControl:
|
||||
expected |= int(HondaSafetyFlags.BOSCH_LONG)
|
||||
if fingerprint == CAR.ACURA_RDX_3G:
|
||||
|
||||
@@ -39,11 +39,9 @@ def test_mixed_nonlogging_eps_still_refuses_modified_profile(other):
|
||||
assert not cp.flags & HondaFlags.EPS_MODIFIED
|
||||
|
||||
|
||||
def test_recorded_custom_angle_eps_steers_by_angle():
|
||||
def test_recorded_custom_angle_eps_remains_unsupported_in_mainline():
|
||||
cp = params(CAR.HONDA_ACCORD, [eps(ANGLE), eps(SERIAL, logging=True)])
|
||||
assert not cp.dashcamOnly
|
||||
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
|
||||
assert cp.dashcamOnly
|
||||
assert not cp.flags & HondaFlags.EPS_MODIFIED
|
||||
|
||||
|
||||
|
||||
@@ -1,364 +0,0 @@
|
||||
"""Accord on the angle-loop EPS firmware (39990-TVA,A16<letter>): detection, the 0xE4 frame, the setpoint limits."""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from opendbc import get_generated_dbcs
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import Bus, gen_empty_fingerprint
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.carstate import CarState
|
||||
from opendbc.car.honda.hondacan import CanBus, create_steering_control
|
||||
from opendbc.car.honda.interface import CarInterface
|
||||
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaFlags, HondaSafetyFlags, is_accord_eps_angle_loop_fw, \
|
||||
accord_angle_steer_ratio, ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL, apply_steer_angle_limits_vm, get_max_angle_delta_vm, get_max_angle_vm
|
||||
from opendbc.car.toyota.interface import CarInterface as ToyotaInterface
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.structs import CarParams
|
||||
|
||||
P = CarControllerParams
|
||||
STEERING_CONTROL = 0xE4
|
||||
|
||||
|
||||
def _eps_fw(fw: bytes):
|
||||
return [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=fw, address=0x18DA30F1, subAddress=0)]
|
||||
|
||||
|
||||
def accord_cp(eps_fw: bytes | None):
|
||||
car_fw = [] if eps_fw is None else _eps_fw(eps_fw)
|
||||
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw, expected", [
|
||||
(b"39990-TVA,A16A\x00\x00", True), # V298, NUL-padded as the car reports it
|
||||
(b"39990-TVA,A16B\x00\x00", True), # V299
|
||||
(b"39990-TVA,A16C", True), # the release
|
||||
(b"39990-TVA,A160\x00\x00", False), # torque-map images
|
||||
(b"39990-TVA-A160\x00\x00", False), # stock
|
||||
(b"39990-TVA,A16", False),
|
||||
(b"39990-TVA,A16AB", False),
|
||||
(b"39990-TVA,A16a", False),
|
||||
(b"39990-TVB,A16A", False),
|
||||
])
|
||||
def test_fw_detection(fw, expected):
|
||||
assert is_accord_eps_angle_loop_fw(fw) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw", [b"39990-TVA,A16A\x00\x00", b"39990-TVA,A16B\x00\x00", b"39990-TVA,A16C\x00\x00"])
|
||||
def test_angle_fw_selects_angle_control(fw):
|
||||
CP = accord_cp(fw)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.angle
|
||||
assert CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert CP.steerActuatorDelay == pytest.approx(P.ANGLE_STEER_ACTUATOR_DELAY)
|
||||
# the angle fw carries a ',' but is not a torque-modified EPS: it must not hit the MODIFIED_EPS_FW dashcam fallback
|
||||
assert not CP.dashcamOnly
|
||||
assert not CP.flags & HondaFlags.EPS_MODIFIED
|
||||
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
|
||||
|
||||
|
||||
def test_angle_fw_on_another_honda_is_not_angle_control():
|
||||
# the family is Accord-only; on any other platform the ',' read is the upstream modified-EPS path
|
||||
CP = CarInterface.get_params(CAR.HONDA_CIVIC_BOSCH, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C\x00\x00"),
|
||||
False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
|
||||
|
||||
def test_mixed_eps_read_is_not_angle_control():
|
||||
car_fw = _eps_fw(b"39990-TVA,A16C\x00\x00") + _eps_fw(b"39990-TVA-A160\x00\x00")
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert CP.dashcamOnly # upstream: a ',' EPS outside MODIFIED_EPS_FW
|
||||
|
||||
|
||||
def test_angle_control_needs_no_params():
|
||||
"""A fresh install selects angle control from the EPS fw alone and keeps the pid tuning block untouched.
|
||||
|
||||
Old tree (83fa2e68c8) also pinned this against stale torque-era toggles (ForceTorqueController, NNFF, NNFF Lite)
|
||||
passed into get_params; this tree's get_params takes no toggles and has no ForceTorqueController conversion at all,
|
||||
so only the fw-alone half of that test still has an API to exercise."""
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C"), False, False, False)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.angle
|
||||
assert CP.lateralTuning.which() == "pid"
|
||||
assert CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw", [None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"])
|
||||
def test_other_fw_keeps_torque_control(fw):
|
||||
CP = accord_cp(fw)
|
||||
assert CP.steerControlType == CarParams.SteerControlType.torque
|
||||
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
|
||||
assert not CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
|
||||
|
||||
|
||||
def test_max_lateral_accel_is_the_angle_limit_only_on_the_angle_fw():
|
||||
# the onroad torque bar divides by CP.maxLateralAccel; the torque fit's 0.32 m/s^2 pegged it on every turn
|
||||
torque_fit = get_torque_params()[CAR.HONDA_ACCORD]['MAX_LAT_ACCEL_MEASURED']
|
||||
assert torque_fit == pytest.approx(0.3247, abs=1e-4)
|
||||
assert accord_cp(b"39990-TVA,A16C").maxLateralAccel == pytest.approx(MAX_LATERAL_ACCEL)
|
||||
assert MAX_LATERAL_ACCEL == pytest.approx(3.589, abs=1e-3)
|
||||
for fw in (None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"):
|
||||
assert accord_cp(fw).maxLateralAccel == pytest.approx(torque_fit)
|
||||
angle_fw = _eps_fw(b"39990-TVA,A16C")
|
||||
for car in (CAR.HONDA_CIVIC_BOSCH, CAR.HONDA_CRV_5G):
|
||||
CP = CarInterface.get_params(car, gen_empty_fingerprint(), angle_fw, False, False, False)
|
||||
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[car]['MAX_LAT_ACCEL_MEASURED'])
|
||||
CP = ToyotaInterface.get_params(TOYOTA.TOYOTA_RAV4_TSS2, gen_empty_fingerprint(), [], False, False, False)
|
||||
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[TOYOTA.TOYOTA_RAV4_TSS2]['MAX_LAT_ACCEL_MEASURED'])
|
||||
|
||||
|
||||
def _steer_faults(CP):
|
||||
# an unfed parser set: only the fault logic, not the bus contents, is under test
|
||||
CS = CarState(CP)
|
||||
ret = CS.update(CS.get_can_parsers(CP))
|
||||
return ret.steerFaultPermanent
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fw, angle, unread", [
|
||||
(b"39990-TVA,A16C\x00\x00", True, False), # angle EPS read -> angle mode
|
||||
(b"39990-TVA-A160\x00\x00", False, False), # stock EPS read -> torque mode, no fault
|
||||
(b"39990-TVA,A160\x00\x00", False, False), # torque-map EPS read -> torque mode, no fault
|
||||
(None, False, True), # no EPS fw at all -> permanent fault
|
||||
])
|
||||
def test_eps_fw_unread_faults(fw, angle, unread):
|
||||
CP = accord_cp(fw)
|
||||
assert (CP.steerControlType == CarParams.SteerControlType.angle) == angle
|
||||
assert bool(CP.flags & HondaFlags.EPS_FW_UNREAD) == unread
|
||||
if not angle:
|
||||
# same unfed bus for every case, so the fault is decided by the flag alone (the read cases are the control)
|
||||
assert _steer_faults(CP) == unread
|
||||
|
||||
|
||||
def test_docs_params_do_not_fault():
|
||||
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), [], False, False, True)
|
||||
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
|
||||
|
||||
|
||||
def _upstream_dbc(tmp_path):
|
||||
# the Accord DBC without STEER_CONTROL_ARM, i.e. as it was before the signal was added. The *_generated DBCs are
|
||||
# built in memory in this tree (opendbc.get_generated_dbcs), so the stripped copy is written out from that content.
|
||||
name = DBC[CAR.HONDA_ACCORD][Bus.pt]
|
||||
content = get_generated_dbcs()[name]
|
||||
assert "STEER_CONTROL_ARM" in content
|
||||
lines = [ln for ln in content.splitlines(keepends=True) if "STEER_CONTROL_ARM" not in ln]
|
||||
path = tmp_path / f"{name}.dbc"
|
||||
path.write_text("".join(lines), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_torque_frame_unchanged_by_the_dbc_signal(tmp_path):
|
||||
CP = accord_cp(None)
|
||||
new = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
|
||||
old = CANPacker(_upstream_dbc(tmp_path))
|
||||
can = CanBus(CP)
|
||||
for torque in range(-4096, 4097, 37):
|
||||
for active in (False, True):
|
||||
for tja in (False, True):
|
||||
assert create_steering_control(new, can, torque, active, tja) == create_steering_control(old, can, torque, active, tja)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("active", [False, True])
|
||||
def test_angle_frame_carries_the_arm_and_a_valid_checksum(active):
|
||||
packer = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
|
||||
can = CanBus(accord_cp(b"39990-TVA,A16C"))
|
||||
for raw in (-4000, -1234, -1, 0, 1, 987, 4000):
|
||||
addr, dat, _ = create_steering_control(packer, can, raw, active, False, angle_arm=P.ANGLE_ARM)
|
||||
assert addr == STEERING_CONTROL
|
||||
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM # byte 2 bits 3:2
|
||||
assert int.from_bytes(dat[0:2], "big", signed=True) == raw # setpoint sent with the request off too
|
||||
assert bool(dat[2] & 0x80) == active # STEER_TORQUE_REQUEST
|
||||
sig = packer.dbc.addr_to_msg[addr].sigs["CHECKSUM"]
|
||||
zeroed = bytearray(dat)
|
||||
zeroed[4] &= 0xF0
|
||||
assert sig.calc_checksum(addr, sig, zeroed) == dat[4] & 0xF # CHECKSUM 35|4 = byte 4 low nibble
|
||||
|
||||
|
||||
def _controller(aol=False):
|
||||
CP = accord_cp(b"39990-TVA,A16C")
|
||||
if aol:
|
||||
CP.alternativeExperience |= 32 # always-on lateral: the hold must NOT depend on it (the 7.0 panda predicate is a session grant)
|
||||
return CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP)
|
||||
|
||||
|
||||
def _cc_cs(desired, measured, v, lat_active, enabled=True, main_on=True):
|
||||
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired), latActive=lat_active, enabled=enabled)
|
||||
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=measured, vEgoRaw=v, cruiseState=SimpleNamespace(available=main_on)))
|
||||
return CC, CS
|
||||
|
||||
|
||||
def test_error_clip_then_the_accel_and_jerk_limits():
|
||||
# the error clip shapes the request, the accel/jerk limiter runs last on it, and what is sent is the limiter's output
|
||||
cc = _controller()
|
||||
assert cc.angle_mode
|
||||
v, measured = 20.0, 0.0
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
state = measured
|
||||
for _ in range(400):
|
||||
state = apply_steer_angle_limits_vm(min(90.0, measured + err), state, v, measured, True, cc.params, cc.VM)
|
||||
apply_angle, raw = cc._update_angle(*_cc_cs(90.0, measured, v, True))
|
||||
assert apply_angle == cc.apply_angle_last == state
|
||||
assert raw == math.floor(-10.0 * apply_angle + 0.5)
|
||||
assert apply_angle == pytest.approx(measured + err) # the wheel never moved: the send settles on the clip
|
||||
|
||||
|
||||
@pytest.mark.parametrize("v", [1.0, 5.0, 10.0, 17.5, 26.9, 35.0])
|
||||
def test_what_is_sent_never_exceeds_the_accel_and_jerk_limits(v):
|
||||
# whatever the wheel does (a driver holding it far past the limit, or yanking it), every frame sent stays inside
|
||||
# the 3.589 lateral accel angle and steps no further than the 3.589 jerk limit from the previous frame sent
|
||||
rng = np.random.default_rng(int(v * 10))
|
||||
cc = _controller()
|
||||
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
|
||||
max_delta = min(get_max_angle_delta_vm(v, cc.VM, cc.params), P.ANGLE_LIMITS.MAX_ANGLE_RATE)
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
wheel = min(max_angle + err + 10.0, 390.0) # held past the limit: the case the old order got wrong
|
||||
prev, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
|
||||
for i in range(600):
|
||||
if i > 200:
|
||||
wheel = float(np.clip(wheel + rng.normal(0.0, 3.0), -390.0, 390.0)) # then moving up to several hundred deg/s
|
||||
sent, raw = cc._update_angle(*_cc_cs(float(rng.uniform(-400.0, 400.0)), wheel, v, True))
|
||||
assert abs(sent) <= min(max_angle, P.ANGLE_LIMITS.STEER_ANGLE_MAX) + 1e-9
|
||||
assert abs(sent - prev) <= max_delta + 1e-9
|
||||
assert raw == math.floor(-10.0 * sent + 0.5)
|
||||
prev = sent
|
||||
|
||||
|
||||
def test_wheel_motion_inside_the_error_clip_does_not_feed_the_setpoint():
|
||||
# same command, different wheel paths that stay inside the clip: the setpoint must not depend on the wheel
|
||||
rng = np.random.default_rng(0)
|
||||
a, b = _controller(), _controller()
|
||||
a.apply_angle_last = b.apply_angle_last = 0.0
|
||||
err = float(np.interp(12.0, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
for i in range(300):
|
||||
desired = 20.0 * math.sin(i / 20.0)
|
||||
wheel = float(np.clip(rng.normal(0.0, 10.0), -(err - 21.0), err - 21.0))
|
||||
a._update_angle(*_cc_cs(desired, 0.0, 12.0, True))
|
||||
b._update_angle(*_cc_cs(desired, wheel, 12.0, True))
|
||||
assert a.apply_angle_last == b.apply_angle_last
|
||||
|
||||
|
||||
def test_setpoint_returns_to_the_request_at_the_jerk_limit_after_the_clip_releases():
|
||||
# wheel pushed away (clip binds), then let go: the setpoint walks back, it does not jump
|
||||
cc = _controller()
|
||||
v = 20.0
|
||||
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
|
||||
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
|
||||
cc.apply_angle_last = 0.0
|
||||
for _ in range(300):
|
||||
pushed, _ = cc._update_angle(*_cc_cs(0.0, err + 5.0, v, True))
|
||||
assert pushed == pytest.approx(5.0) # held at the clip edge, wheel - err
|
||||
back, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
|
||||
assert back == pytest.approx(5.0 - max_delta)
|
||||
|
||||
|
||||
def test_request_waits_at_the_wheel_while_the_wheel_is_past_the_accel_limit():
|
||||
# lateral goes active with the wheel past the accel-limit angle: the limit is more than one jerk step away, so no
|
||||
# setpoint is legal. The frame holds the wheel with the request off, and the request starts once the wheel is inside.
|
||||
cc = _controller()
|
||||
v = 26.9
|
||||
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
|
||||
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
|
||||
for wheel in (max_angle + 20.0, max_angle + 5.0, max_angle + max_delta + 0.1):
|
||||
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert not cc.angle_steer_req
|
||||
assert sent == wheel and raw == math.floor(-10.0 * wheel + 0.5)
|
||||
wheel = max_angle + 0.5 * max_delta
|
||||
cc._update_angle(*_cc_cs(0.0, wheel, v, True)) # the last value sent was the wheel further out: one more frame waits
|
||||
assert not cc.angle_steer_req
|
||||
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert cc.angle_steer_req
|
||||
assert sent == pytest.approx(wheel - max_delta) # one jerk step in from the wheel, inside the accel limit
|
||||
for _ in range(50): # and it stays on from there
|
||||
prev = sent
|
||||
sent, _ = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
|
||||
assert cc.angle_steer_req and abs(sent - prev) <= max_delta + 1e-9 and abs(sent) <= max_angle + 1e-9
|
||||
|
||||
|
||||
def test_request_bit_follows_lat_active_otherwise():
|
||||
cc = _controller()
|
||||
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, True))
|
||||
assert cc.angle_steer_req
|
||||
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, False))
|
||||
assert not cc.angle_steer_req
|
||||
|
||||
|
||||
def test_each_step_is_bounded_by_the_rate_limit():
|
||||
# MAX_ANGLE_RATE = 2.5 deg/frame (250 deg/s): no frame may step further than that
|
||||
cc = _controller()
|
||||
prev = 0.0
|
||||
for _ in range(5):
|
||||
a, _ = cc._update_angle(*_cc_cs(90.0, 0.0, 3.0, True))
|
||||
assert abs(a - prev) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
|
||||
prev = a
|
||||
|
||||
|
||||
def test_first_frame_seeds_from_the_wheel():
|
||||
cc = _controller()
|
||||
a, _ = cc._update_angle(*_cc_cs(30.0, 25.0, 10.0, True))
|
||||
assert abs(a - 25.0) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled, main_on, aol, holds", [
|
||||
(True, True, False, True),
|
||||
(False, True, True, False), # always-on lateral with ACC main on: the panda's grant is not visible here, so no hold
|
||||
(True, True, True, True),
|
||||
(False, True, False, False),
|
||||
(True, False, False, False), # the panda drops controls_allowed with main off
|
||||
(False, False, True, False),
|
||||
])
|
||||
def test_idle_hold(enabled, main_on, aol, holds):
|
||||
cc = _controller(aol)
|
||||
measured = -12.34
|
||||
apply_angle, raw = cc._update_angle(*_cc_cs(50.0, measured, 15.0, False, enabled, main_on))
|
||||
assert apply_angle == measured # lateral off: the limiter follows the wheel
|
||||
assert raw == (math.floor(-10.0 * measured + 0.5) if holds else 0)
|
||||
|
||||
|
||||
def test_raw_is_clipped():
|
||||
cc = _controller()
|
||||
cc.apply_angle_last = 399.0
|
||||
_, raw = cc._update_angle(*_cc_cs(400.0, 399.0, 1.0, True))
|
||||
assert raw == -P.ANGLE_RAW_MAX
|
||||
|
||||
|
||||
def test_steer_ratio_map_level():
|
||||
assert accord_angle_steer_ratio(0.0) == pytest.approx(16.84)
|
||||
for deg in (0.0, 45.0, 120.0, -200.0, 500.0):
|
||||
expected = float(np.interp(abs(deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V)) * 16.84 / 16.88
|
||||
assert accord_angle_steer_ratio(deg) == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_error_clip_is_the_p_room_under_the_firmware_sum_clamp():
|
||||
# Operator rule (2026-10-21): the clip is the angle error where the V300 firmware's P term alone equals
|
||||
# Kmax - Imax (sum clamp 15360 after the 254/256 taper, so 15481 before it; I cap 4096 / 6144 / 8192 by
|
||||
# speed). Integer mirror of the image: E = 16 * 10 * deg, E' = (E * G(v)) >> 8, P = (E' * 112) >> 8.
|
||||
g_v = {3.1: 1178, 8.0: 1465, 10.0: 760, 11.75: 560, 17.5: 1068, 26.9: 2188}
|
||||
for v, clip in zip(P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V, strict=True):
|
||||
imax = 4096 if v <= 6.0 else (6144 if v <= 12.5 else 8192)
|
||||
p_of = lambda deg, v=v: (((16 * round(10 * deg) * g_v[v]) >> 8) * 112) >> 8 # noqa: E731
|
||||
assert p_of(clip) >= 15481 - imax > p_of(clip - 0.1)
|
||||
|
||||
|
||||
def test_angle_frame_is_sent_by_the_controller():
|
||||
# the full update(): angle mode packs the setpoint with the arm; the projection observer is never installed on angle
|
||||
CP = accord_cp(b"39990-TVA,A16C")
|
||||
ci = CarInterface(CP)
|
||||
from opendbc.car import structs
|
||||
CC = structs.CarControl(enabled=True, latActive=True)
|
||||
CC.actuators.steeringAngleDeg = 5.0
|
||||
ci.update([])
|
||||
out, sends = ci.apply(CC.as_reader(), 1_000_000_000)
|
||||
steer = [s for s in sends if s[0] == STEERING_CONTROL]
|
||||
assert len(steer) == 1
|
||||
dat = steer[0][1]
|
||||
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM
|
||||
assert int.from_bytes(dat[0:2], "big", signed=True) == out.torqueOutputCan
|
||||
assert out.steeringAngleDeg == pytest.approx(-out.torqueOutputCan / 10.0, abs=0.05)
|
||||
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -34,32 +33,6 @@ class TestHondaNormalDiscovery(unittest.TestCase):
|
||||
generic_query.assert_not_called()
|
||||
self.assertIsNone(actual[0])
|
||||
|
||||
def _accord_discovery(self, normal_read, obd_read):
|
||||
from opendbc.car.honda.values import CAR
|
||||
switches = []
|
||||
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions', side_effect=[normal_read, obd_read]) as query, \
|
||||
patch('opendbc.car.car_helpers.match_fw_to_car', return_value=(True, {CAR.HONDA_ACCORD})), \
|
||||
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})):
|
||||
actual = fingerprint(lambda wait_for_one=False: [recorded_frames()], lambda frames: None, switches.append, None)
|
||||
return switches, vin, query, actual
|
||||
|
||||
def test_accord_without_an_eps_read_queries_the_obd_port(self):
|
||||
radar = SimpleNamespace(ecu="fwdRadar", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
switches, vin, query, actual = self._accord_discovery([radar], [radar, eps])
|
||||
self.assertEqual(switches, [False, True, False])
|
||||
self.assertEqual(vin.call_count, 2)
|
||||
self.assertEqual([call.kwargs for call in query.call_args_list],
|
||||
[{'query_brand': 'honda', 'normal_bus_only': True}, {'query_brand': 'honda'}])
|
||||
self.assertEqual(actual[3], [radar, eps])
|
||||
|
||||
def test_accord_with_an_eps_read_stays_on_normal_wiring(self):
|
||||
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
|
||||
switches, vin, query, _ = self._accord_discovery([eps], AssertionError("no second query"))
|
||||
self.assertFalse(any(switches))
|
||||
query.assert_called_once()
|
||||
|
||||
def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
|
||||
from opendbc.car.honda.discovery import normal_bus_topology
|
||||
frames = recorded_frames()
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, IntFlag
|
||||
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
from opendbc.car.docs_definitions import CarFootnote, CarHarness, CarDocs, CarParts, Column
|
||||
from opendbc.car.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16
|
||||
from opendbc.car.honda.firmware_validation import validate_fw_match
|
||||
from opendbc.car.lateral import AngleSteeringLimitsVM, MAX_LATERAL_ACCEL, MAX_LATERAL_JERK
|
||||
|
||||
Ecu = structs.CarParams.Ecu
|
||||
VisualAlert = structs.CarControl.HUDControl.VisualAlert
|
||||
@@ -44,27 +41,6 @@ class CarControllerParams:
|
||||
STEER_DELTA_DOWN = 3
|
||||
STEER_GLOBAL_MIN_SPEED = 3 * CV.MPH_TO_MS
|
||||
|
||||
# ---- Accord on the angle-loop EPS firmware (HondaFlags.EPS_ANGLE_LOOP_FW). 0xE4 STEER_TORQUE carries an angle
|
||||
# setpoint, raw = round(-10 * deg) in carState.steeringAngleDeg's frame, and the EPS closes a 1 kHz angle loop on it.
|
||||
# The panda checks every such frame (STEER_CONTROL_ARM == 2) against the same lateral accel and jerk limits with
|
||||
# the same vehicle model (honda.h, HONDA_ACCORD_ANGLE_PARAMS), and blocks one that exceeds them.
|
||||
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
|
||||
400, # deg; the EPS clamps its setpoint at raw +-4096
|
||||
MAX_LATERAL_ACCEL=MAX_LATERAL_ACCEL, # 3.589 m/s^2
|
||||
MAX_LATERAL_JERK=MAX_LATERAL_JERK, # 3.589 m/s^3
|
||||
MAX_ANGLE_RATE=2.5, # deg/frame = 250 deg/s (V299 drives ran 250; Tesla and Rivian run 250 deg/s too)
|
||||
)
|
||||
# Error clip |setpoint - measured angle| <= ANGLE_ERROR_MAX(v): bounds the P torque the setpoint can demand. Each
|
||||
# knot = the error at which the firmware's P term alone fills the room left under the PID sum clamp when the
|
||||
# integral sits at its cap (operator rule, 2026-10-21): P = Kmax - Imax, read from the V300 image:
|
||||
# P = ((16*10*deg * G(v)) >> 8) * 112 >> 8, Kmax = 15360 after the 254/256 taper (15481 before it),
|
||||
# Imax = 4096 (<= 6 m/s), 6144 (6-12.5 m/s), 8192 (above, the ICL), G(v) = 1178/1465/760/560/1068/2188 at the knots.
|
||||
ANGLE_ERROR_MAX_BP = [3.1, 8.0, 10.0, 11.75, 17.5, 26.9] # m/s, the firmware gain-table knots
|
||||
ANGLE_ERROR_MAX_V = [35.4, 23.4, 45.0, 61.0, 25.0, 12.2] # deg (was 17.0, 15.5, 19.5, 17.0, 8.5, 4.5, model-sized)
|
||||
ANGLE_RAW_MAX = 4000 # raw clip before packing
|
||||
ANGLE_ARM = 2 # 0xE4 STEER_CONTROL_ARM: the EPS lane runs only while it reads 2; sent on every frame
|
||||
ANGLE_STEER_ACTUATOR_DELAY = 0.15 # s, the inner angle loop's lag (model value; lagd learns the rest)
|
||||
|
||||
def __init__(self, CP):
|
||||
self.BOSCH_GAS_LOOKUP_BP = list(type(self).BOSCH_GAS_LOOKUP_BP)
|
||||
gas_max = {CAR.HONDA_CIVIC_BOSCH: 750, CAR.HONDA_ODYSSEY_5G_MMR: 2000,
|
||||
@@ -116,7 +92,6 @@ class HondaSafetyFlags(IntFlag):
|
||||
RADARLESS = 8
|
||||
BOSCH_CANFD = 16
|
||||
BOSCH_CANFD_MVL = 64
|
||||
ACCORD_ANGLE = 4096
|
||||
CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner.
|
||||
ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token.
|
||||
NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA.
|
||||
@@ -146,55 +121,6 @@ class HondaFlags(IntFlag):
|
||||
BOSCH_TJA_CONTROL = 4096
|
||||
EPS_MODIFIED = 8192
|
||||
GAS_INTERCEPTOR = 16384
|
||||
EPS_ANGLE_LOOP_FW = 32768 # the Accord EPS reports the angle-loop firmware (is_accord_eps_angle_loop_fw)
|
||||
EPS_FW_UNREAD = 65536 # Accord with no EPS fw response: the firmware family is unknown, so do not steer
|
||||
|
||||
|
||||
# Accord EPS angle-loop firmware family: 39990-TVA,A16 + exactly one capital letter (A16A, A16B, A16C ...). Torque
|
||||
# images read 39990-TVA,A160 (a digit) and stock 39990-TVA-A1x0, so neither matches.
|
||||
ACCORD_EPS_ANGLE_LOOP_FW_FAMILY = b"39990-TVA,A16"
|
||||
|
||||
|
||||
def is_accord_eps_angle_loop_fw(fw_version: bytes) -> bool:
|
||||
v = bytes(fw_version).rstrip(b"\x00") # the EPS pads fwVersion with NULs
|
||||
family = ACCORD_EPS_ANGLE_LOOP_FW_FAMILY
|
||||
return len(v) == len(family) + 1 and v.startswith(family) and ord("A") <= v[-1] <= ord("Z")
|
||||
|
||||
|
||||
# ---- Accord, angle mode only (steerControlType == angle): the variable-ratio rack map.
|
||||
# In angle mode sR turns the model's curvature 1:1 into the angle setpoint, so the ratio is a tune here and the learner
|
||||
# is ignored. SHAPE: absolute ratios measured over 82 routes, V[0] = the on-centre nominal. Not measurements:
|
||||
# 0-23 deg (pinned by convention, not identified), 31-61 deg (interpolated across two bins that failed the lag test),
|
||||
# 236+ deg (frozen; above 303 deg the data is parking speed). A compensation curve for calc_curvature's k = d/L,
|
||||
# not the rack's true geometry. Bands: shape +/-0.12, level +/-0.57.
|
||||
ACCORD_ANGLE_SR_BP = [0.0, 23.0, 31.0, 61.0, 76.0, 95.0, 116.0, 151.0, 178.0, 227.0, 236.0, 303.0, 380.0] # deg
|
||||
ACCORD_ANGLE_SR_V = [16.88, 16.88, 16.88, 16.25, 15.97, 15.45, 15.03, 14.68, 14.45, 14.09, 14.25, 12.98, 12.31] # :1
|
||||
# LEVEL: the served on-centre ratio; the whole shape is scaled by LEVEL / V[0]. 16.84 = the SteerRatio every angle
|
||||
# drive ran (V298/V299 configs).
|
||||
ACCORD_ANGLE_SR_LEVEL = 16.84
|
||||
|
||||
|
||||
def accord_angle_steer_ratio(steer_angle_deg: float) -> float:
|
||||
"""Local ratio of the Accord's rack at this wheel angle (deg, offset removed)."""
|
||||
ratio = float(np.interp(abs(steer_angle_deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V))
|
||||
return ratio * ACCORD_ANGLE_SR_LEVEL / ACCORD_ANGLE_SR_V[0]
|
||||
|
||||
|
||||
def accord_angle_at_own_ratio(angle_vm_deg: float, sr_vm: float, max_passes: int = 10) -> float:
|
||||
"""The angle setpoint with the map evaluated at the DESIRED angle instead of the measured one.
|
||||
|
||||
controlsd sets VM.sR = map(measured angle) and get_steer_from_curvature is linear in sR, so the consistent setpoint
|
||||
is the fixed point theta = angle_vm_deg * map(theta) / sr_vm. Each pass shrinks the error by <= 0.44 (worst on the
|
||||
236-303 deg knot); stops within 0.01 deg, a tenth of the EPS setpoint quantum.
|
||||
"""
|
||||
theta = float(angle_vm_deg)
|
||||
for _ in range(max_passes):
|
||||
nxt = float(angle_vm_deg) * accord_angle_steer_ratio(theta) / sr_vm
|
||||
done = abs(nxt - theta) < 0.01
|
||||
theta = nxt
|
||||
if done:
|
||||
break
|
||||
return theta
|
||||
|
||||
|
||||
# Car button codes
|
||||
|
||||
@@ -124,7 +124,6 @@ class CarController(CarControllerBase):
|
||||
self.apply_angle_last = 0.0
|
||||
self.angle_gain_last = 0.0
|
||||
self.angle_fault_driver_override = False
|
||||
self.stock_angle_lka_active = False
|
||||
self.angle_tx_recovery = (AngleTxRecovery(0xCB, self.CAN.ECAN)
|
||||
if pe_long_qualified(CP) or ev9_long_qualified(CP) else AngleTxRecovery(0x110, self.CAN.ACAN)
|
||||
if CP.carFingerprint in (CAR.HYUNDAI_IONIQ_5_PE, CAR.KIA_EV9) and
|
||||
@@ -545,9 +544,7 @@ class CarController(CarControllerBase):
|
||||
angle_active, self.params, self.angle_vm)
|
||||
self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
|
||||
angle_active, self.angle_gain_last)
|
||||
stock_angle_handoff = angle_aol and lka_steering and not ccnc_ev_stock
|
||||
if ((not ccnc_ev_stock or ccnc_ev_replacement) and
|
||||
(not stock_angle_handoff or angle_active or self.stock_angle_lka_active)):
|
||||
if not ccnc_ev_stock or ccnc_ev_replacement:
|
||||
can_sends.extend(
|
||||
hyundaicanfd.create_angle_steering_messages(
|
||||
self.packer,
|
||||
@@ -561,7 +558,6 @@ class CarController(CarControllerBase):
|
||||
CS.out.steeringAngleDeg,
|
||||
)
|
||||
)
|
||||
self.stock_angle_lka_active = stock_angle_handoff and angle_active
|
||||
else:
|
||||
steering_status_active = CC.enabled
|
||||
if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or
|
||||
|
||||
@@ -256,7 +256,7 @@ def test_ae0_physical_tracker_is_inactive_until_final_ae32(hda2):
|
||||
|
||||
@pytest.mark.parametrize('hda2', (False, True))
|
||||
@pytest.mark.parametrize('corruption', ('crc', 'replay', 'wrong_bus', 'inactive'))
|
||||
def test_real_controller_forwarding_requires_valid_replacement(hda2, corruption):
|
||||
def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, corruption):
|
||||
cp = params(hda2)
|
||||
cp.alternativeExperience = 32
|
||||
ci = CarInterface(cp)
|
||||
@@ -295,14 +295,7 @@ def test_real_controller_forwarding_requires_valid_replacement(hda2, corruption)
|
||||
elif corruption == 'wrong_bus':
|
||||
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data))
|
||||
else:
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if hda2:
|
||||
assert ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))
|
||||
if hda2:
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
safety.set_timer(((now // 1000) + 200_001) & 0xFFFFFFFF)
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
|
||||
|
||||
@@ -354,11 +347,7 @@ def test_real_controller_crc_fault_revokes_token_then_fresh_gesture_recovers(hda
|
||||
assert permission == 0 and not accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if 80 <= tick < 100:
|
||||
assert permission == 0
|
||||
if hda2:
|
||||
assert accepted and ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
assert safety.safety_fwd_hook(2, addr) == (-1 if hda2 else 0)
|
||||
assert permission == 0 and safety.safety_fwd_hook(2, addr) == 0
|
||||
if tick >= 115:
|
||||
assert permission == 1 and accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
from unittest.mock import Mock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -9,7 +8,7 @@ from opendbc.car.hyundai.canfd_owner import config_index
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff, independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
|
||||
CARS = (CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN)
|
||||
|
||||
@@ -227,12 +226,3 @@ def test_idle_handoff_omits_only_kona_steering_packet():
|
||||
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
|
||||
assert any(frame[0] == 0x12A for frame in before)
|
||||
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
|
||||
|
||||
@pytest.mark.parametrize('panda_type,faults,expected', [('cuatro', [], 0x1C0C), ('redPanda', [], 0x0C0C), ('cuatro', ['fault'], 0x0C0C)])
|
||||
def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faults, expected):
|
||||
cp = kona_params(CARS[0])
|
||||
cp.alternativeExperience = 32
|
||||
cp.safetyConfigs[0].safetyParam = 0x0C0C
|
||||
panda = SimpleNamespace(pandaType=panda_type, faults=faults, ignitionLine=True, ignitionCan=False, controlsAllowed=False)
|
||||
configure_kona_factory_handoff(cp, [panda])
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
|
||||
@@ -40,8 +40,7 @@ def card_publication_sequence(context):
|
||||
calls=[statement.value.func.attr for statement in statements if isinstance(statement,ast.Expr)]
|
||||
assert calls==['configure','finalize_aol_configuration','seal_publication']
|
||||
exec(compile(ast.Module(body=statements,type_ignores=[]),'actual-card-publication-order','exec'),
|
||||
{'self':context,'aol_policy':policy_for(context.CP), 'HYUNDAI_CAR':CAR,
|
||||
'hyundai_aol_safety_config':hyundai_aol_safety_config})
|
||||
{'self':context,'aol_policy':policy_for(context.CP), 'hyundai_aol_safety_config':hyundai_aol_safety_config})
|
||||
|
||||
|
||||
@pytest.fixture(params=[(CAR.KIA_EV6,EV6Startup),(CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,GV70Startup)])
|
||||
|
||||
@@ -30,19 +30,9 @@ AUTO_RESUME_CARS = frozenset((CAR.TOYOTA_HIGHLANDER, CAR.TOYOTA_PRIUS_V, CAR.TOY
|
||||
WORDS = frozenset(word | stock for word in PROFILES.values() for stock in (0, 0x200))
|
||||
|
||||
|
||||
def corolla_startup_mirror(candidate, fingerprint):
|
||||
if candidate != CAR.TOYOTA_COROLLA:
|
||||
return False
|
||||
pt = fingerprint.get(0, {})
|
||||
return pt == fingerprint.get(2, {}) and all(pt.get(address) == length for address, length in
|
||||
((0xAA, 8), (0x262, 5), (0x1D3, 8), (0x343, 8), (0x4CB, 8)))
|
||||
|
||||
|
||||
def hardware_supported(candidate, fingerprint, car_fw):
|
||||
if candidate not in PROFILES or any(address in frames for frames in fingerprint.values() for address in (0x201, 0x2FF, 0x2AA)):
|
||||
return False
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return False
|
||||
camera = fingerprint.get(2, {})
|
||||
if not any(camera.get(address) == 8 for address in (0x343, 0x4CB)) or any(camera.get(address, 8) != 8 for address in (0x343, 0x4CB)):
|
||||
return False
|
||||
|
||||
@@ -29,9 +29,6 @@ def hardware_supported(candidate, fingerprint):
|
||||
return False
|
||||
if 0x2FF in frames and not (candidate == CAR.TOYOTA_CAMRY and _cluster_radar_bus(candidate, bus, frames)):
|
||||
return False
|
||||
from opendbc.car.toyota.dsu_bypass import corolla_startup_mirror
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return True
|
||||
camera = fingerprint.get(2, {})
|
||||
if 0x4CB in camera:
|
||||
return False
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mirrored,expected', ((True, 0x5358), (False, 0x8958)))
|
||||
def test_corolla_camera_relay_mirror_is_not_a_dsu_bypass(mirrored, expected):
|
||||
car = CAR.TOYOTA_COROLLA
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0].update({0xAA: 8, 0x262: 5, 0x1D3: 8, 0x343: 8, 0x4CB: 8, 0x283: 7})
|
||||
fp[2].update(fp[0] if mirrored else {0x343: 8, 0x4CB: 8})
|
||||
fw = [structs.CarParams.CarFw(ecu=ecu, address=addr, subAddress=sub or 0, fwVersion=versions[0], brand='toyota', bus=0)
|
||||
for (ecu, addr, sub), versions in FW_VERSIONS[car].items()]
|
||||
|
||||
cp = CarInterface.get_params(car, fp, fw, False, True, False)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert cp.pcmCruise
|
||||
assert cp.openpilotLongitudinalControl is (not mirrored)
|
||||
@@ -2,7 +2,6 @@ BO_ 228 STEERING_CONTROL: 5 EON
|
||||
SG_ STEER_TORQUE : 7|16@0- (1,0) [-4096|4096] "" EPS
|
||||
SG_ DRIVER_OVERRIDE : 17|1@0+ (1,0) [0|1] "" XXX
|
||||
SG_ STEER_TORQUE_REQUEST : 23|1@0+ (1,0) [0|1] "" EPS
|
||||
SG_ STEER_CONTROL_ARM : 19|2@0+ (1,0) [0|3] "" EPS
|
||||
SG_ CONTROL_STATE : 26|3@0+ (1,0) [0|7] "" XXX
|
||||
SG_ CHECKSUM : 35|4@0+ (1,0) [0|15] "" EPS
|
||||
SG_ COUNTER : 37|2@0+ (1,0) [0|3] "" EPS
|
||||
@@ -207,7 +206,6 @@ BO_ 13275 LKAS_HUD_B: 8 ADAS
|
||||
SG_ COUNTER : 61|2@0+ (1,0) [0|3] "" BDY
|
||||
|
||||
CM_ SG_ 228 DRIVER_OVERRIDE "Appears to acknowledge STEER_STATUS.NO_TORQUE_ALERT_1";
|
||||
CM_ SG_ 228 STEER_CONTROL_ARM "Stock camera sends 0 or 1. The Accord angle-loop EPS firmware (39990-TVA,A16x) runs its lane only while this reads 2";
|
||||
CM_ SG_ 576 LINE_DISTANCE_VISIBLE "Length of line visible, undecoded";
|
||||
CM_ SG_ 577 LINE_FAR_EDGE_POSITION "Appears to be a measure of line thickness, indicates location of the portion of the line furthest from the car, undecoded";
|
||||
CM_ SG_ 577 LINE_PARAMETER "Unclear if this is low quality line curvature rate or if this is something else, but it is correlated with line curvature, undecoded";
|
||||
|
||||
@@ -232,8 +232,6 @@ typedef bool (*tx_hook)(const CANPacket_t *msg); // returns true if the message
|
||||
typedef bool (*fwd_hook)(int bus_num, int addr); // returns true if the message should be blocked from forwarding
|
||||
|
||||
typedef bool (*fwd_packet_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*stage_tx_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*fwd_output_hook)(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
|
||||
typedef struct {
|
||||
safety_hook_init init;
|
||||
@@ -242,8 +240,6 @@ typedef struct {
|
||||
tx_hook tx;
|
||||
fwd_hook fwd;
|
||||
fwd_packet_hook fwd_packet;
|
||||
stage_tx_hook stage_tx;
|
||||
fwd_output_hook fwd_output;
|
||||
get_checksum_t get_checksum;
|
||||
compute_checksum_t compute_checksum;
|
||||
get_counter_t get_counter;
|
||||
@@ -375,11 +371,6 @@ extern safety_config current_safety_config;
|
||||
|
||||
int safety_fwd_hook(int bus_num, int addr);
|
||||
int safety_fwd_packet_hook(const CANPacket_t *msg);
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg);
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg);
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
int set_safety_hooks(uint16_t mode, uint16_t param);
|
||||
|
||||
extern const safety_hooks body_hooks;
|
||||
|
||||
@@ -34,8 +34,6 @@ static bool honda_fwd_brake = false;
|
||||
static bool honda_bosch_long = false;
|
||||
static bool honda_bosch_radarless = false;
|
||||
static bool honda_bosch_canfd = false;
|
||||
static bool honda_accord_angle = false;
|
||||
#define HONDA_PARAM_ACCORD_ANGLE 4096U
|
||||
static bool honda_mvl_stock = false;
|
||||
static uint8_t honda_mvl_buttons_fresh = 0U;
|
||||
static bool honda_rdx_high_gas = false;
|
||||
@@ -103,23 +101,6 @@ static uint8_t honda_get_counter(const CANPacket_t *msg) {
|
||||
return (msg->data[counter_byte] >> 4U) & 0x3U;
|
||||
}
|
||||
|
||||
// The Accord angle-loop EPS firmware (39990-TVA,A16x) exists only on classic Bosch. On it a 0xE4 frame with
|
||||
// STEER_CONTROL_ARM == 2 carries an angle setpoint in bytes 0-1 (-0.1 deg); the EPS runs its angle lane on no other
|
||||
// frame, and the stock camera only ever sends 0 or 1 there.
|
||||
static bool honda_angle_setpoint_capable(void) {
|
||||
return (honda_hw == HONDA_BOSCH) && honda_accord_angle;
|
||||
}
|
||||
|
||||
// Wheel angle for the angle setpoint check: where a request may start from, and what a request-off frame may hold.
|
||||
// STEERING_SENSORS is not a required RX check on Honda, so it arrives here, and its checksum is verified here.
|
||||
static void honda_optional_rx_hook(const CANPacket_t *msg) {
|
||||
if (honda_angle_setpoint_capable() && msg_matches(msg, 0x14AU, honda_get_pt_bus(), 8U) &&
|
||||
(honda_get_checksum(msg) == honda_compute_checksum(msg))) {
|
||||
// STEER_ANGLE, -0.1 deg: the same units and sign as the 0xE4 setpoint
|
||||
update_sample(&angle_meas, to_signed((msg->data[0] << 8) | msg->data[1], 16));
|
||||
}
|
||||
}
|
||||
|
||||
static void honda_rx_hook(const CANPacket_t *msg) {
|
||||
const bool pcm_cruise = ((honda_hw == HONDA_BOSCH) && !honda_bosch_long) || ((honda_hw == HONDA_NIDEC) && !honda_interceptor);
|
||||
unsigned int pt_bus = honda_get_pt_bus();
|
||||
@@ -130,14 +111,6 @@ static void honda_rx_hook(const CANPacket_t *msg) {
|
||||
vehicle_moving = msg->data[0] | msg->data[1];
|
||||
}
|
||||
|
||||
// speed for the angle setpoint check (Accord angle-loop EPS)
|
||||
if (honda_angle_setpoint_capable()) {
|
||||
if (msg_matches(msg, 0x158U, pt_bus)) {
|
||||
// ENGINE_DATA XMISSION_SPEED, 0.01 kph
|
||||
UPDATE_VEHICLE_SPEED(((msg->data[0] << 8) | msg->data[1]) * 0.01 * KPH_TO_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// check ACC main state
|
||||
// 0x326 for all Bosch and some Nidec, 0x1A6 for some Nidec
|
||||
if ((!aol_honda_bosch_long && ((msg->addr == 0x326U) || (msg->addr == 0x1A6U))) ||
|
||||
@@ -344,40 +317,6 @@ static bool honda_tx_hook(const CANPacket_t *msg) {
|
||||
}
|
||||
}
|
||||
|
||||
// STEER: angle setpoint frames (STEER_CONTROL_ARM == 2, Accord angle-loop EPS) must stay inside the lateral
|
||||
// acceleration and jerk limits, checked with the vehicle model on the value as sent
|
||||
if ((msg->addr == 0xE4U) && (((msg->data[2] >> 2) & 0x3U) == 2U)) {
|
||||
const AngleSteeringLimits HONDA_ACCORD_ANGLE_LIMITS = {
|
||||
.max_angle = 4000, // 400 deg, the EPS clamps its setpoint just above this
|
||||
.angle_deg_to_can = 10,
|
||||
.frequency = 100U,
|
||||
};
|
||||
|
||||
// NOTE: HONDA_ACCORD, must match openpilot's VehicleModel
|
||||
const AngleSteeringParams HONDA_ACCORD_ANGLE_PARAMS = {
|
||||
.slip_factor = -0.0006999872680281922, // calc_slip_factor(VM)
|
||||
.steer_ratio = 16.33,
|
||||
.wheelbase = 2.83,
|
||||
};
|
||||
|
||||
const int desired_angle = to_signed((msg->data[0] << 8) | msg->data[1], 16);
|
||||
const bool steer_req = GET_BIT(msg, 23U); // STEER_TORQUE_REQUEST
|
||||
|
||||
bool violation = !honda_angle_setpoint_capable();
|
||||
if (!violation) {
|
||||
if (!steer_req && (desired_angle == 0)) {
|
||||
// request off with a zero field: nothing is commanded, the next request starts from the wheel
|
||||
desired_angle_last = SAFETY_CLAMP(angle_meas.values[0], -HONDA_ACCORD_ANGLE_LIMITS.max_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle);
|
||||
} else {
|
||||
violation |= steer_angle_cmd_checks_vm(desired_angle, steer_req, HONDA_ACCORD_ANGLE_LIMITS, HONDA_ACCORD_ANGLE_PARAMS);
|
||||
violation |= safety_max_limit_check(desired_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle, -HONDA_ACCORD_ANGLE_LIMITS.max_angle);
|
||||
}
|
||||
}
|
||||
if (violation) {
|
||||
tx = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Bosch supplemental control check
|
||||
if (msg->addr == 0xE5U) {
|
||||
if ((GET_BYTES_64_LE(msg, 0, 8) & 0x00FFFFFFFFFFFFFFULL) != 0x0000000010800004ULL) {
|
||||
@@ -442,7 +381,6 @@ static safety_config honda_nidec_init(uint16_t param) {
|
||||
const uint16_t HONDA_PARAM_NIDEC_ALT = 4;
|
||||
|
||||
honda_hw = HONDA_NIDEC;
|
||||
honda_accord_angle = false;
|
||||
honda_brake = 0;
|
||||
honda_brake_switch_prev = false;
|
||||
honda_fwd_brake = false;
|
||||
@@ -488,14 +426,7 @@ static safety_config honda_nidec_init(uint16_t param) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
static safety_config honda_bosch_init(uint16_t requested_param) {
|
||||
// Apply the Accord flag only to the classic Bosch base configurations the host can select.
|
||||
const uint16_t param = (uint16_t)(requested_param & ~HONDA_PARAM_ACCORD_ANGLE);
|
||||
bool accord_base = (param == 0U) || (param == 1U);
|
||||
#ifdef ALLOW_DEBUG
|
||||
accord_base = accord_base || (param == 2U) || (param == 3U) || (param == 2082U) || (param == 2083U);
|
||||
#endif
|
||||
honda_accord_angle = GET_FLAG(requested_param, HONDA_PARAM_ACCORD_ANGLE) && accord_base;
|
||||
static safety_config honda_bosch_init(uint16_t param) {
|
||||
honda_mvl_stock = ((param == 80U) || (param == 81U)) && ((alternative_experience == 0) || (alternative_experience == 32));
|
||||
honda_mvl_buttons_fresh = 0U;
|
||||
honda_interceptor_reset(false);
|
||||
@@ -683,7 +614,6 @@ const safety_hooks honda_bosch_hooks = {
|
||||
.fwd = honda_mvl_stock_fwd_hook,
|
||||
.init = honda_bosch_init,
|
||||
.rx = honda_rx_hook,
|
||||
.optional_rx = honda_optional_rx_hook,
|
||||
.tx = honda_tx_hook,
|
||||
.get_counter = honda_get_counter,
|
||||
.get_checksum = honda_get_checksum,
|
||||
|
||||
@@ -19,8 +19,6 @@ static bool blended_aol_token = false;
|
||||
static bool blended_aol_claimed = false;
|
||||
static bool blended_aol_session = false;
|
||||
static bool blended_aol_request_seen = false;
|
||||
static bool blended_aol_brake_continuation = false;
|
||||
static bool blended_aol_idle_owned[2] = {false, false};
|
||||
static bool blended_aol_neutral[3] = {false, false, false};
|
||||
static bool blended_aol_pressed[3] = {false, false, false};
|
||||
static uint32_t blended_aol_source_ts[3] = {0U, 0U, 0U};
|
||||
@@ -46,9 +44,6 @@ static void blended_aol_clear(void) {
|
||||
blended_aol_claimed = false;
|
||||
blended_aol_session = false;
|
||||
blended_aol_request_seen = false;
|
||||
blended_aol_brake_continuation = false;
|
||||
blended_aol_idle_owned[0] = false;
|
||||
blended_aol_idle_owned[1] = false;
|
||||
blended_aol_token_ts = 0U;
|
||||
blended_aol_token_source = 3U;
|
||||
aol_host_axis_mask = 0U;
|
||||
@@ -76,9 +71,6 @@ static void blended_aol_reset(void) {
|
||||
|
||||
static void blended_aol_host_request(uint8_t mask) {
|
||||
blended_aol_request_seen |= mask != 0U;
|
||||
if ((mask & 1U) == 0U) {
|
||||
blended_aol_brake_continuation = false;
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t blended_aol_request_mask(void) {
|
||||
@@ -115,7 +107,7 @@ static uint8_t blended_aol_permission_mask(void) {
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_source_ts[blended_aol_token_source]) <= 300000U);
|
||||
if (!aol_rx_healthy() || (blended_aol_token && !source_current)) {
|
||||
blended_aol_clear();
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token || blended_aol_brake_continuation)) {
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token)) {
|
||||
result = 1U;
|
||||
} else {
|
||||
}
|
||||
@@ -153,14 +145,6 @@ static void blended_aol_rx(const CANPacket_t *msg) {
|
||||
if (blended_aol_enabled) {
|
||||
const unsigned int pt = blended_aol_hda2 ? 1U : 0U;
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
if (blended_aol_hda2 && !blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
const bool brake = ((msg->data[5] >> 5U) & 3U) == 2U;
|
||||
if (brake && !brake_pressed && controls_allowed && blended_aol_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US) &&
|
||||
((blended_aol_request_mask() & 1U) != 0U) && aol_rx_healthy()) {
|
||||
blended_aol_brake_continuation = true;
|
||||
}
|
||||
}
|
||||
if (blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
blended_aol_main_seen = true;
|
||||
blended_aol_main = ((msg->data[5] >> 3U) & 3U) == 0U;
|
||||
@@ -339,19 +323,6 @@ static void blended_aol_tx(const CANPacket_t *msg, bool accepted) {
|
||||
}
|
||||
}
|
||||
accepted_current &= active;
|
||||
if (blended_aol_hda2) {
|
||||
const bool zero_torque = (((msg->data[6] & 0xFU) << 7U) | (msg->data[5] >> 1U)) == 1024U;
|
||||
blended_aol_idle_owned[0] = accepted && !active && zero_torque && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction;
|
||||
if (!blended_aol_idle_owned[0]) {
|
||||
blended_aol_idle_owned[1] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (blended_aol_hda2 && (msg->addr == 0x2A4U) && (msg->bus == 0U) && !retain_camera_ownership) {
|
||||
blended_aol_idle_owned[1] = accepted && blended_aol_idle_owned[0] && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction &&
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
}
|
||||
for (unsigned int i = 0U; i < count; i++) {
|
||||
const unsigned int bus = blended_aol_hda2 && (i >= 2U) ? 1U : 0U;
|
||||
@@ -368,16 +339,6 @@ static bool blended_aol_fwd(int bus, int addr) {
|
||||
bool blocked = blended_aol_long && !blended_aol_enabled && (bus == 2) &&
|
||||
((addr == (blended_aol_hda2 ? 0x50 : 0x340)) ||
|
||||
(addr == (blended_aol_hda2 ? 0x2A4 : 0x364)) || (!blended_aol_hda2 && (addr == 0x485)));
|
||||
if (blended_aol_enabled && blended_aol_hda2 && (bus == 2) &&
|
||||
aol_rx_healthy() && !safety_rx_checks_invalid && !relay_malfunction) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const bool primary_current = blended_aol_idle_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
if (primary_current) {
|
||||
blocked |= (addr == 0x50) || ((addr == 0x2A4) && blended_aol_idle_owned[1] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[1]) <= AOL_HOST_REQUEST_TIMEOUT_US));
|
||||
}
|
||||
}
|
||||
if (blended_aol_enabled && (bus == 2) && aol_rx_healthy() && (controls_allowed || (blended_aol_permission_mask() != 0U))) {
|
||||
const uint32_t addresses[4] = {blended_aol_hda2 ? 0x50U : 0x340U, blended_aol_hda2 ? 0x2A4U : 0x364U, 0x485U, 0x340U};
|
||||
const unsigned int count = blended_aol_hda2 ? 2U : 3U;
|
||||
|
||||
@@ -820,15 +820,12 @@ static safety_config hyundai_canfd_gv60_extend_tx(const safety_config original,
|
||||
}
|
||||
#endif
|
||||
|
||||
#define HYUNDAI_CANFD_STEER_MAX_TORQUE 409
|
||||
#define HYUNDAI_CANFD_STEER_MAX_RATE_UP 10
|
||||
|
||||
static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
static uint8_t hyundai_canfd_ioniq6_lfa_mirror[4] = {0};
|
||||
const TorqueSteeringLimits HYUNDAI_CANFD_STEERING_LIMITS = {
|
||||
.max_torque = HYUNDAI_CANFD_STEER_MAX_TORQUE,
|
||||
.max_torque = 409,
|
||||
.max_rt_delta = 375,
|
||||
.max_rate_up = HYUNDAI_CANFD_STEER_MAX_RATE_UP,
|
||||
.max_rate_up = 10,
|
||||
.max_rate_down = 3,
|
||||
.driver_torque_allowance = 250,
|
||||
.driver_torque_multiplier = 2,
|
||||
@@ -1231,7 +1228,7 @@ static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
return tx;
|
||||
}
|
||||
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
#ifdef ALLOW_DEBUG
|
||||
static bool hyundai_kona_idle_handoff = false;
|
||||
static bool hyundai_kona_camera_seen = false;
|
||||
static bool hyundai_kona_output_seen = false;
|
||||
@@ -1240,11 +1237,6 @@ static uint32_t hyundai_kona_camera_ts = 0U;
|
||||
static uint32_t hyundai_kona_output_ts = 0U;
|
||||
static uint8_t hyundai_kona_camera_counter = 0U;
|
||||
static uint8_t hyundai_kona_output_counter = 0U;
|
||||
static bool hyundai_kona_pending = false;
|
||||
static bool hyundai_kona_emitting = false;
|
||||
static bool hyundai_kona_slot_owned = false;
|
||||
static uint32_t hyundai_kona_pending_ts = 0U;
|
||||
static CANPacket_t hyundai_kona_pending_msg;
|
||||
|
||||
static bool hyundai_kona_host_steering(void) {
|
||||
return controls_allowed || ((aol_get_permission_mask() & 1U) != 0U);
|
||||
@@ -1270,107 +1262,26 @@ static void hyundai_kona_track_output(uint32_t now, bool host, uint8_t counter)
|
||||
hyundai_kona_output_counter = counter;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_without_slot(const CANPacket_t *msg) {
|
||||
return hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
return (msg->bus == 2U) && hyundai_kona_output_seen && hyundai_kona_host_output &&
|
||||
hyundai_kona_camera_seen && !relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy() &&
|
||||
!hyundai_kona_host_steering() && hyundai_kona_lfa_valid(msg) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_output_counter) == 1U) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_camera_counter) == 1U) &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 20000U);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_stage_tx(const CANPacket_t *msg) {
|
||||
bool staged = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && (msg->bus == 0U)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const uint8_t source_delta = (uint8_t)(hyundai_kona_camera_counter - msg->data[2]);
|
||||
staged = !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 20000U) && (source_delta <= 1U);
|
||||
if (staged) {
|
||||
hyundai_kona_pending_msg = *msg;
|
||||
hyundai_kona_pending_ts = now;
|
||||
hyundai_kona_pending = true;
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
}
|
||||
}
|
||||
return staged;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_output(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
static bool hyundai_kona_camera_fwd(const CANPacket_t *msg) {
|
||||
bool blocked = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const uint8_t counter = msg->data[2];
|
||||
const uint32_t camera_age = safety_get_ts_elapsed(now, hyundai_kona_camera_ts);
|
||||
const uint8_t delta = (uint8_t)(counter - hyundai_kona_camera_counter);
|
||||
const bool advancing = (delta > 0U) && (delta <= 127U);
|
||||
const bool consecutive = hyundai_kona_camera_seen && (delta == 1U) && (camera_age <= 20000U);
|
||||
blocked = !hyundai_kona_lfa_valid(msg) || safety_rx_checks_invalid || !aol_rx_healthy() ||
|
||||
(hyundai_kona_camera_seen && (camera_age <= 50000U) && !advancing);
|
||||
const bool valid = hyundai_kona_lfa_valid(msg);
|
||||
if (valid) {
|
||||
const uint8_t delta = (uint8_t)(msg->data[2] - hyundai_kona_camera_counter);
|
||||
if (!hyundai_kona_camera_seen ||
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) > 50000U) ||
|
||||
((delta > 0U) && (delta <= 127U))) {
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_counter = msg->data[2];
|
||||
hyundai_kona_camera_ts = now;
|
||||
}
|
||||
}
|
||||
blocked = !valid || safety_rx_checks_invalid || !aol_rx_healthy() || hyundai_kona_host_steering() ||
|
||||
(msg->data[2] != hyundai_kona_camera_counter) ||
|
||||
!hyundai_kona_output_ready(now, false, msg->data[2]);
|
||||
if (!blocked) {
|
||||
hyundai_kona_camera_counter = counter;
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_ts = now;
|
||||
|
||||
const bool authority = hyundai_kona_host_steering();
|
||||
if (!authority) {
|
||||
hyundai_kona_slot_owned = false;
|
||||
}
|
||||
if (authority && consecutive && hyundai_kona_pending &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_pending_ts) <= 20000U)) {
|
||||
CANPacket_t candidate = hyundai_kona_pending_msg;
|
||||
const uint8_t source_delta = (uint8_t)(counter - candidate.data[2]);
|
||||
const uint8_t camera_grade = (msg->data[4] >> 6U) | ((msg->data[5] & 1U) << 2U);
|
||||
const bool camera_warning = (camera_grade >= 4U) || ((msg->data[7] & 0xF0U) != 0U);
|
||||
if (camera_warning) {
|
||||
candidate.data[4] = (candidate.data[4] & 0x3FU) | (msg->data[4] & 0xC0U);
|
||||
candidate.data[5] = (candidate.data[5] & 0xFEU) | (msg->data[5] & 0x01U);
|
||||
candidate.data[7] = (candidate.data[7] & 0x0FU) | (msg->data[7] & 0xF0U);
|
||||
}
|
||||
const unsigned int raw_torque = (((unsigned int)candidate.data[6] & 0xFU) << 7U) | (candidate.data[5] >> 1U);
|
||||
const int torque = (int)raw_torque - 1024;
|
||||
if ((source_delta <= 2U) &&
|
||||
!safety_max_limit_check(torque, HYUNDAI_CANFD_STEER_MAX_TORQUE, -HYUNDAI_CANFD_STEER_MAX_TORQUE)) {
|
||||
if (GET_BIT(&candidate, 52U)) {
|
||||
const int max_torque = SAFETY_MAX(desired_torque_last, 0) + HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const int min_torque = SAFETY_MIN(desired_torque_last, 0) - HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const unsigned int raw = (unsigned int)(SAFETY_CLAMP(torque, min_torque, max_torque) + 1024);
|
||||
candidate.data[5] = (candidate.data[5] & 0x01U) | (uint8_t)((raw & 0x7FU) << 1U);
|
||||
candidate.data[6] = (candidate.data[6] & 0xF0U) | (uint8_t)(raw >> 7U);
|
||||
}
|
||||
candidate.data[2] = counter;
|
||||
const uint16_t checksum = hyundai_common_canfd_compute_checksum(&candidate) ^ 0x041DU;
|
||||
candidate.data[0] = (uint8_t)checksum;
|
||||
candidate.data[1] = (uint8_t)(checksum >> 8U);
|
||||
hyundai_kona_emitting = true;
|
||||
*replaced = safety_tx_hook(&candidate);
|
||||
hyundai_kona_emitting = false;
|
||||
if (*replaced) {
|
||||
*output = candidate;
|
||||
hyundai_kona_slot_owned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
hyundai_kona_pending = false;
|
||||
if (!*replaced) {
|
||||
const bool camera_neutral = ((msg->data[6] & 0x3FU) == 0x08U) && ((msg->data[5] & 0xFEU) == 0U);
|
||||
blocked = (hyundai_kona_slot_owned && !camera_neutral) ||
|
||||
!hyundai_kona_output_ready(now, false, counter);
|
||||
if (!blocked) {
|
||||
if (hyundai_kona_host_output) {
|
||||
desired_torque_last = 0;
|
||||
}
|
||||
hyundai_kona_track_output(now, false, counter);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
hyundai_kona_track_output(now, false, msg->data[2]);
|
||||
}
|
||||
}
|
||||
return blocked;
|
||||
@@ -1381,7 +1292,6 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
bool tx = false;
|
||||
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
|
||||
bool ordinary_angle_valid = true;
|
||||
const bool stock_angle_hda2 = hyundai_angle_aol_enabled && hyundai_canfd_lka_steer_msg && !hyundai_canfd_ccnc_ev_long;
|
||||
const bool independent_command = hyundai_angle_aol_enabled &&
|
||||
((msg->addr == 0x50U) || (msg->addr == 0x110U) ||
|
||||
((msg->addr == 0x12AU) && !hyundai_canfd_angle_observed_adas) || (msg->addr == 0xCBU));
|
||||
@@ -1398,18 +1308,9 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
ordinary_angle_valid &= (delta > 0U) && (delta <= 127U);
|
||||
}
|
||||
} else {
|
||||
if (stock_angle_hda2) {
|
||||
const uint32_t xor_out = (GET_LEN(msg) == 16U) ? 0x041DU : 0U;
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ xor_out));
|
||||
}
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
}
|
||||
if (stock_angle_hda2 && ((msg->addr == 0x2A4U) || (msg->addr == 0x362U))) {
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == hyundai_common_canfd_compute_checksum(msg));
|
||||
}
|
||||
if (hyundai_ordinary_angle_stock && !hyundai_angle_aol_enabled) {
|
||||
// Core whitelisting precedes this hook; relay is its only final denial.
|
||||
ordinary_angle_valid = !relay_malfunction;
|
||||
@@ -1447,7 +1348,7 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
if (hyundai_angle_aol_enabled && independent_command && !tx) {
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
#ifdef ALLOW_DEBUG
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && tx && !relay_malfunction) {
|
||||
hyundai_kona_track_output(microsecond_timer_get(), true, msg->data[2]);
|
||||
}
|
||||
@@ -1456,18 +1357,18 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
#ifdef ALLOW_DEBUG
|
||||
bool allowed = true;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
allowed = hyundai_kona_emitting && !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
allowed = !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 50000U) &&
|
||||
(msg->data[2] == hyundai_kona_camera_counter) && hyundai_kona_output_ready(now, true, msg->data[2]);
|
||||
}
|
||||
#endif
|
||||
return
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
#ifdef ALLOW_DEBUG
|
||||
allowed &&
|
||||
#endif
|
||||
hyundai_canfd_tx_hook_checked(msg);
|
||||
@@ -1972,8 +1873,8 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
|
||||
{0x1DA, 1, 32, .check_relay = false},
|
||||
};
|
||||
static const CanMsg ioniq6_long_lkas_alt_tx_msgs[] = {
|
||||
{0x110, 0, 32, .check_relay = true},
|
||||
{0x362, 0, 32, .check_relay = true},
|
||||
{0x110, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x362, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x12A, 1, 16, .check_relay = false},
|
||||
{0x1E0, 1, 16, .check_relay = false},
|
||||
{0x1A0, 1, 32, .check_relay = true, .check_relay_immediately = true},
|
||||
@@ -2424,13 +2325,10 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
|
||||
hyundai_daw_init(true, false);
|
||||
hyundai_canfd_reset_ioniq6_state();
|
||||
hyundai_ordinary_angle_reset();
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4) && !defined(PANDA_BODY)
|
||||
#ifdef ALLOW_DEBUG
|
||||
hyundai_kona_idle_handoff = (raw_param == 0x1C0CU) && (alternative_experience == 32);
|
||||
hyundai_kona_camera_seen = false;
|
||||
hyundai_kona_output_seen = false;
|
||||
hyundai_kona_pending = false;
|
||||
hyundai_kona_emitting = false;
|
||||
hyundai_kona_slot_owned = false;
|
||||
const bool kona_profile_valid = (raw_param != 0x1C0CU) || hyundai_kona_idle_handoff;
|
||||
const uint16_t param = hyundai_kona_idle_handoff ? 0x0C0CU : raw_param;
|
||||
const bool valid = !GET_FLAG(param, 32768U) || (param == 0x8015U) || (param == 0x8095U) ||
|
||||
@@ -2453,7 +2351,7 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
|
||||
const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) ||
|
||||
(param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U);
|
||||
ret = hyundai_daw_configure(ret, true, daw_profile);
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
#ifdef ALLOW_DEBUG
|
||||
if (hyundai_kona_idle_handoff) {
|
||||
static CanMsg kona_tx[64];
|
||||
if (hyundai_canfd_angle_aol_capacity(&ret)) {
|
||||
@@ -2477,10 +2375,8 @@ const safety_hooks hyundai_canfd_hooks = {
|
||||
.optional_rx = hyundai_canfd_optional_rx_hook,
|
||||
.tx = hyundai_canfd_tx_hook,
|
||||
.fwd = hyundai_canfd_fwd_hook,
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
.fwd_packet = hyundai_kona_camera_without_slot,
|
||||
.stage_tx = hyundai_kona_stage_tx,
|
||||
.fwd_output = hyundai_kona_camera_output,
|
||||
#ifdef ALLOW_DEBUG
|
||||
.fwd_packet = hyundai_kona_camera_fwd,
|
||||
#endif
|
||||
.get_counter = hyundai_canfd_get_counter,
|
||||
.get_checksum = hyundai_canfd_get_checksum,
|
||||
|
||||
@@ -366,55 +366,6 @@ int safety_fwd_packet_hook(const CANPacket_t *msg) {
|
||||
return destination_bus;
|
||||
}
|
||||
|
||||
#if !defined(STM32F4) && (defined(ALLOW_DEBUG) || !defined(STM32H7))
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return (current_safety_mode == SAFETY_HYUNDAI_CANFD) && hyundai_kona_idle_handoff && (msg->addr == 0x12AU);
|
||||
#else
|
||||
(void)msg;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return safety_uses_camera_slot(msg) && hyundai_kona_camera_release_current(msg, now);
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
const uint32_t age = safety_get_ts_elapsed(now, hyundai_kona_output_ts);
|
||||
return ((age >= 9000U) && (age < 10000U) && safety_camera_release_current(msg, now)) ? (10000U - age) : 0U;
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return 0U;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg) {
|
||||
return !relay_malfunction && (current_hooks->stage_tx != NULL) && current_hooks->stage_tx(msg);
|
||||
}
|
||||
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
int destination;
|
||||
if (current_hooks->fwd_output != NULL) {
|
||||
destination = safety_fwd_hook(msg->bus, msg->addr);
|
||||
if ((destination >= 0) && current_hooks->fwd_output(msg, output, replaced)) {
|
||||
destination = -1;
|
||||
}
|
||||
} else {
|
||||
destination = safety_fwd_packet_hook(msg);
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
#endif
|
||||
|
||||
// 1Hz safety function called by main. Now just a check for lagging safety messages
|
||||
void safety_tick(void) {
|
||||
const uint8_t MAX_MISSED_MSGS = 10U;
|
||||
|
||||
@@ -11,11 +11,6 @@ SAFETY_UNUSED(safety_rx_hook);
|
||||
SAFETY_UNUSED(safety_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_hook);
|
||||
SAFETY_UNUSED(safety_fwd_packet_hook);
|
||||
SAFETY_UNUSED(safety_uses_camera_slot);
|
||||
SAFETY_UNUSED(safety_camera_release_current);
|
||||
SAFETY_UNUSED(safety_camera_release_delay);
|
||||
SAFETY_UNUSED(safety_stage_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_output_hook);
|
||||
SAFETY_UNUSED(safety_tick);
|
||||
SAFETY_UNUSED(set_safety_hooks);
|
||||
// Exported to Panda's USB status handler and the native safety test library.
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Accord angle-loop EPS: the panda bounds the 0xE4 angle setpoint by the lateral accel and jerk limits."""
|
||||
import math
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car import Bus, gen_empty_fingerprint
|
||||
from opendbc.car.honda.carcontroller import CarController
|
||||
from opendbc.car.honda.interface import CarInterface
|
||||
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaSafetyFlags
|
||||
from opendbc.car.lateral import MAX_LATERAL_ACCEL, get_max_angle_delta_vm, get_max_angle_vm
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vehicle_model import VehicleModel, calc_slip_factor
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
from opendbc.safety.tests import test_honda # the module, so its test classes are not collected again here
|
||||
|
||||
P = CarControllerParams
|
||||
ARM = P.ANGLE_ARM
|
||||
DT_US = 10_000 # 0xE4 is sent at 100 Hz
|
||||
SPEEDS = (1.0, 3.0, 5.0, 8.0, 10.0, 12.0, 17.5, 22.0, 26.9, 31.0, 38.0)
|
||||
|
||||
|
||||
def accord_cp():
|
||||
fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=b"39990-TVA,A16C", address=0x18DA30F1, subAddress=0)]
|
||||
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), fw, False, False, False)
|
||||
|
||||
|
||||
class TestHondaAccordAngleSetpoint(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.fixture = test_honda.TestHondaBoschAltBrakeSafety('test_spam_cancel_safety_check')
|
||||
self.fixture.setUp()
|
||||
self.safety = self.fixture.safety
|
||||
self.packer = self.fixture.packer
|
||||
self.CP = accord_cp()
|
||||
self.angle_flag = self.CP.safetyConfigs[0].safetyParam
|
||||
self.assertNotEqual(self.angle_flag, 0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | 1), 0)
|
||||
self.safety.init_tests()
|
||||
self.VM = VehicleModel(self.CP)
|
||||
self.params = P(self.CP)
|
||||
self.t = 1_000_000
|
||||
self.safety.set_timer(self.t)
|
||||
|
||||
# ---- helpers
|
||||
def _angle_frame(self, raw, steer_req, arm=ARM, bus=None):
|
||||
values = {"STEER_TORQUE": raw, "STEER_TORQUE_REQUEST": steer_req, "STEER_CONTROL_ARM": arm}
|
||||
return self.packer.make_can_msg_safety("STEERING_CONTROL", self.fixture.STEER_BUS if bus is None else bus, values)
|
||||
|
||||
def _tx(self, raw, steer_req=True, arm=ARM, bus=None):
|
||||
self.t += DT_US
|
||||
self.safety.set_timer(self.t)
|
||||
return self.fixture._tx(self._angle_frame(raw, steer_req, arm, bus))
|
||||
|
||||
def _rx_speed(self, v_ms):
|
||||
self.fixture._rx(self.fixture._speed_msg(v_ms * 3.6))
|
||||
|
||||
def _rx_wheel(self, raw):
|
||||
# STEER_ANGLE is -0.1 deg per count: the raw count equals the 0xE4 raw for the same angle
|
||||
self.fixture._rx(self.packer.make_can_msg_safety("STEERING_SENSORS", self.fixture.PT_BUS, {"STEER_ANGLE": -raw / 10.0}))
|
||||
|
||||
def _settle(self, v_ms, wheel_raw=0):
|
||||
for _ in range(6):
|
||||
self._rx_speed(v_ms)
|
||||
self._rx_wheel(wheel_raw)
|
||||
|
||||
def _panda_max_angle_raw(self, v_ms):
|
||||
# the panda evaluates the model 1 m/s below its slowest speed sample and allows one count of rounding
|
||||
return int(get_max_angle_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
|
||||
|
||||
def _panda_max_delta_raw(self, v_ms):
|
||||
return int(get_max_angle_delta_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
|
||||
|
||||
def test_stock_profiles_and_incompatible_flag_combinations_reject_angle_frames(self):
|
||||
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
ordinary = (0, 1, 2, 3, 2082, 2083)
|
||||
invalid = (self.angle_flag | 8, self.angle_flag | 16, self.angle_flag | 128)
|
||||
if not is_debug:
|
||||
invalid += tuple(self.angle_flag | word for word in ordinary if word & 2)
|
||||
for word in ordinary + invalid:
|
||||
with self.subTest(word=word):
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, word), 0)
|
||||
self.safety.init_tests()
|
||||
self._settle(10.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
bus = int(bool(is_debug and word & 2))
|
||||
self.assertFalse(self._tx(10, bus=bus), word)
|
||||
self.assertFalse(self._tx(0, steer_req=False, bus=bus), word)
|
||||
if word in ordinary:
|
||||
self.assertTrue(self._tx(10, arm=0, bus=bus), word)
|
||||
|
||||
def test_flag_preserves_lateral_on_supported_classic_bosch_configurations(self):
|
||||
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
|
||||
base_words = (0, 1, 2, 3, 2082, 2083) if is_debug else (0, 1)
|
||||
for base in base_words:
|
||||
with self.subTest(base=base):
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | base), 0)
|
||||
self.safety.init_tests()
|
||||
self._settle(10.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(10, bus=int(bool(base & 2))), base)
|
||||
|
||||
# ---- the model the panda uses is the one openpilot uses
|
||||
def test_vehicle_model_constants_match_openpilot(self):
|
||||
src = (Path(__file__).parents[1] / "modes" / "honda.h").read_text(encoding="utf-8")
|
||||
block = src[src.index("HONDA_ACCORD_ANGLE_PARAMS = {"):]
|
||||
block = block[:block.index("};")]
|
||||
read = {k: float(v) for k, v in re.findall(r"\.(\w+)\s*=\s*(-?[\d.]+)", block)}
|
||||
self.assertAlmostEqual(read["slip_factor"], calc_slip_factor(self.VM), places=12)
|
||||
self.assertAlmostEqual(read["steer_ratio"], self.CP.steerRatio, places=5)
|
||||
self.assertAlmostEqual(read["wheelbase"], self.CP.wheelbase, places=5)
|
||||
self.assertAlmostEqual(MAX_LATERAL_ACCEL, 3.589, places=3)
|
||||
self.assertEqual(self.params.ANGLE_LIMITS.MAX_LATERAL_ACCEL, MAX_LATERAL_ACCEL)
|
||||
|
||||
# ---- lateral acceleration limit
|
||||
def test_setpoint_beyond_the_lateral_accel_limit_is_blocked(self):
|
||||
for v in SPEEDS:
|
||||
limit = self._panda_max_angle_raw(v)
|
||||
if limit > 4000:
|
||||
continue # below ~5 m/s the 400 deg ceiling binds first (covered below)
|
||||
for sign in (-1, 1):
|
||||
self._settle(v)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(sign * limit)
|
||||
self.assertTrue(self._tx(sign * limit), (v, sign))
|
||||
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
|
||||
# the first blocked frame resets the panda to the wheel; a setpoint this far out stays blocked
|
||||
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
|
||||
|
||||
def test_the_old_order_counterexample_is_blocked(self):
|
||||
# 26.9 m/s, wheel held at 42 deg: the old code sent 29.8 deg (5.4 m/s^2) against a 19.8 deg limit
|
||||
v = 26.9
|
||||
self._settle(v, wheel_raw=420)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(298)
|
||||
self.assertFalse(self._tx(298))
|
||||
self.assertGreater(298, self._panda_max_angle_raw(v))
|
||||
|
||||
def test_setpoint_beyond_400_deg_is_blocked(self):
|
||||
self._settle(1.0, wheel_raw=4000)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for raw, ok in ((4000, True), (4001, False), (-4000, True), (-4001, False), (4096, False)):
|
||||
self.safety.set_desired_angle_last(raw)
|
||||
self.assertEqual(ok, self._tx(raw), raw)
|
||||
|
||||
# ---- lateral jerk limit
|
||||
def test_step_beyond_the_lateral_jerk_limit_is_blocked(self):
|
||||
for v in SPEEDS:
|
||||
delta = self._panda_max_delta_raw(v)
|
||||
for sign in (-1, 1):
|
||||
for start in (0, 50):
|
||||
if start + delta + 1 > min(self._panda_max_angle_raw(v), 4000):
|
||||
continue
|
||||
self._settle(v, wheel_raw=sign * start)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(sign * start)
|
||||
self.assertTrue(self._tx(sign * (start + delta)), (v, sign, start))
|
||||
self.safety.set_desired_angle_last(sign * start)
|
||||
self.assertFalse(self._tx(sign * (start + delta + 1)), (v, sign, start))
|
||||
|
||||
def test_a_blocked_frame_restarts_from_the_wheel(self):
|
||||
v = 20.0
|
||||
self._settle(v, wheel_raw=30)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_desired_angle_last(30)
|
||||
self.assertFalse(self._tx(30 + self._panda_max_delta_raw(v) + 1))
|
||||
self.assertEqual(self.safety.get_desired_angle_last(), 30)
|
||||
self.assertTrue(self._tx(30 + self._panda_max_delta_raw(v)))
|
||||
|
||||
# ---- request off
|
||||
def test_request_off_frames(self):
|
||||
v = 15.0
|
||||
self._settle(v, wheel_raw=-234)
|
||||
for allowed in (True, False):
|
||||
self.safety.set_controls_allowed(allowed)
|
||||
self.assertTrue(self._tx(0, steer_req=False)) # nothing commanded
|
||||
self.assertEqual(self.safety.get_desired_angle_last(), -234)
|
||||
self.assertEqual(allowed, self._tx(-234, steer_req=False)) # hold at the wheel: only while lateral is allowed
|
||||
self.assertFalse(self._tx(-200, steer_req=False)) # anything else is not the wheel
|
||||
self.assertFalse(self._tx(100, steer_req=False))
|
||||
|
||||
def test_request_needs_controls_allowed(self):
|
||||
self._settle(15.0, wheel_raw=0)
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.assertFalse(self._tx(0, steer_req=True))
|
||||
self.assertFalse(self._tx(5, steer_req=True))
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.assertTrue(self._tx(0, steer_req=True))
|
||||
|
||||
def test_engage_from_a_zero_field_starts_at_the_wheel(self):
|
||||
# always-on lateral case: the carcontroller sends a zero field until the request, then starts from the wheel
|
||||
v = 25.0
|
||||
self._settle(v, wheel_raw=150)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for _ in range(5):
|
||||
self.assertTrue(self._tx(0, steer_req=False))
|
||||
self.assertTrue(self._tx(150 + self._panda_max_delta_raw(v), steer_req=True))
|
||||
|
||||
# ---- torque frames (arm 0 or 1) are not angle setpoints
|
||||
def test_torque_frames_are_unaffected(self):
|
||||
self._settle(30.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
for arm in (0, 1):
|
||||
for raw in (-4096, -1000, 0, 1000, 4096):
|
||||
self.assertTrue(self._tx(raw, steer_req=True, arm=arm), (arm, raw))
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.assertTrue(self._tx(0, steer_req=False, arm=0))
|
||||
self.assertFalse(self._tx(1000, steer_req=True, arm=0))
|
||||
|
||||
# ---- message rate
|
||||
def test_message_rate_limit(self):
|
||||
self._settle(20.0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
blocked = False
|
||||
for _ in range(40): # 40 frames inside one 250 ms window: more than 100 Hz allows
|
||||
blocked |= not self.fixture._tx(self._angle_frame(0, True))
|
||||
self.assertTrue(blocked)
|
||||
|
||||
# ---- the carcontroller's own output is what the panda checks, and it always passes
|
||||
def _controller_frames(self, v_of, wheel_of, desired_of, frames):
|
||||
cc = CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, self.CP)
|
||||
blocked = withheld = 0
|
||||
for i in range(frames):
|
||||
v, wheel = v_of(i), wheel_of(i)
|
||||
wheel_raw = math.floor(-10.0 * wheel + 0.5)
|
||||
self._rx_speed(v)
|
||||
self._rx_wheel(wheel_raw)
|
||||
active = i >= 12 # as on the road, request-off frames come first: they fill the panda's samples
|
||||
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired_of(i)), latActive=active, enabled=True)
|
||||
# carState reads the angle off the same STEER_ANGLE counts and the speed off the wheels
|
||||
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=-wheel_raw / 10.0, vEgoRaw=v,
|
||||
cruiseState=SimpleNamespace(available=True)))
|
||||
_, raw = cc._update_angle(CC, CS)
|
||||
withheld += active and not cc.angle_steer_req
|
||||
blocked += not self._tx(raw, steer_req=cc.angle_steer_req)
|
||||
return blocked, withheld
|
||||
|
||||
def test_carcontroller_output_is_never_blocked(self):
|
||||
self.safety.set_controls_allowed(True)
|
||||
rng = np.random.default_rng(1)
|
||||
cases = {
|
||||
"lane keeping": (lambda i: 28.0, lambda i: 2.0 * math.sin(i / 60.0), lambda i: 3.0 * math.sin(i / 50.0)),
|
||||
"saturating request": (lambda i: 20.0, lambda i: 0.0, lambda i: 300.0 * math.sin(i / 100.0)),
|
||||
"random request": (lambda i: 12.0, lambda i: 10.0 * math.sin(i / 40.0), lambda i: float(rng.uniform(-400, 400))),
|
||||
"tight turn": (lambda i: 4.0, lambda i: min(i * 2.0, 380.0), lambda i: 400.0),
|
||||
"driver past the limit": (lambda i: 26.9, lambda i: min(i * 0.3, 45.0), lambda i: 0.0),
|
||||
"driver yank": (lambda i: 17.5, lambda i: 60.0 * math.sin(i / 8.0), lambda i: 5.0),
|
||||
"braking": (lambda i: max(30.0 - i * 0.03, 2.0), lambda i: 5.0, lambda i: 400.0),
|
||||
"accelerating": (lambda i: min(3.0 + i * 0.03, 35.0), lambda i: 0.0, lambda i: -400.0),
|
||||
}
|
||||
for name, (v_of, wheel_of, desired_of) in cases.items():
|
||||
self.safety.set_controls_allowed(True)
|
||||
blocked, withheld = self._controller_frames(v_of, wheel_of, desired_of, 900)
|
||||
self.assertEqual(0, blocked, name)
|
||||
# the request is withheld only where the wheel is past the limit when it would start: the yank reaches 60 deg
|
||||
# against a 38 deg limit. Everywhere else every frame carries the request.
|
||||
self.assertEqual(name == "driver yank", withheld > 0, (name, withheld))
|
||||
|
||||
|
||||
class TestHondaAngleSetpointOnOtherBosch(unittest.TestCase):
|
||||
"""A radarless or CAN FD Honda has no angle-loop EPS: an armed frame is never sent, and is blocked if it is."""
|
||||
|
||||
def test_armed_frame_is_blocked(self):
|
||||
fixture = test_honda.TestHondaBoschRadarlessSafety('test_spam_cancel_safety_check')
|
||||
fixture.setUp()
|
||||
fixture.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, HondaSafetyFlags.RADARLESS)
|
||||
fixture.safety.init_tests()
|
||||
fixture.safety.set_controls_allowed(True)
|
||||
for arm, ok in ((0, True), (1, True), (ARM, False)):
|
||||
# bytes 0-1 zero, STEER_TORQUE_REQUEST set, STEER_CONTROL_ARM in byte 2 bits 3:2
|
||||
packet = libsafety_py.make_CANPacket(0xE4, fixture.STEER_BUS, bytes([0, 0, 0x80 | (arm << 2), 0, 0]))
|
||||
self.assertEqual(ok, fixture._tx(packet), arm)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -221,47 +221,3 @@ class TestHyundaiBlendedStock(unittest.TestCase):
|
||||
self.safety.safety_rx_hook(common.make_msg(0, 0x50, 16))
|
||||
self.assertTrue(self.safety.get_relay_malfunction())
|
||||
self.safety.set_alternative_experience(0)
|
||||
|
||||
def _start_hda2_aol(self):
|
||||
self.safety.init_tests()
|
||||
self.safety.set_alternative_experience(32)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hyundai, 0x2010), 0)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.steer_counter = 0
|
||||
self.bus = 1
|
||||
self._refresh_hda2_aol_rx(1_000_000)
|
||||
self.safety.aol_set_host_request(1)
|
||||
|
||||
def _refresh_hda2_aol_rx(self, now):
|
||||
self.safety.set_timer(now)
|
||||
for status in self.safety.rx_status:
|
||||
status.msg_seen = status.valid_checksum = status.valid_quality_flag = True
|
||||
status.last_timestamp = now
|
||||
|
||||
def test_hda2_brake_retains_aol_only_after_accepted_steering(self):
|
||||
for steering_before_brake in (False, True):
|
||||
self._start_hda2_aol()
|
||||
self.assertTrue(self.safety.safety_rx_hook(common.make_msg(1, 0x4F1, dat=bytes([1, 0, 0, 0]))))
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.scc(0, True)))
|
||||
self.assertTrue(self.safety.get_controls_allowed())
|
||||
if steering_before_brake:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(3)))
|
||||
self._refresh_hda2_aol_rx(1_010_000)
|
||||
brake = common.make_msg(1, 0x394, dat=bytes.fromhex('036c000003449798'))
|
||||
self.assertTrue(self.safety.safety_rx_hook(brake))
|
||||
self.assertFalse(self.safety.get_controls_allowed())
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(self.steer(3))), steering_before_brake)
|
||||
self.safety.aol_set_host_request(0)
|
||||
self.safety.aol_set_host_request(1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.steer(3)))
|
||||
|
||||
def test_hda2_idle_blocks_duplicate_only_while_host_steering_is_fresh(self):
|
||||
self._start_hda2_aol()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(0, False)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x421), 0)
|
||||
self._refresh_hda2_aol_rx(1_500_000)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
|
||||
@@ -249,26 +249,6 @@ class TestHyundaiBlendedAlphaAol(unittest.TestCase):
|
||||
for _ in range(8):
|
||||
self.feed()
|
||||
|
||||
def test_hda2_idle_steering_has_one_forwarding_owner(self):
|
||||
if self.release:
|
||||
self.skipTest("Mixed Alpha Long requires the debug safety build")
|
||||
self.reset(0x2014)
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
steering = self.packer.make_can_msg_safety('LKAS', 0, {'COUNTER': 1, 'TORQUE_REQUEST': 0})
|
||||
self.assertTrue(self.safety.safety_tx_hook(steering))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
camera = self.packer.make_can_msg_safety('CAM_0x2a4', 0, {'COUNTER': self.counter - 1})
|
||||
self.assertTrue(self.safety.safety_tx_hook(camera))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), -1)
|
||||
self.assertEqual(self.request(3), 0)
|
||||
self.now += 500_000
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
|
||||
def test_hdai_withdrawal_consumes_valid_counter_without_output_credit(self):
|
||||
from opendbc.car.hyundai.hyundaican import hyundai_checksum
|
||||
|
||||
|
||||
@@ -68,19 +68,6 @@ class TestHyundaiIoniq6Long(unittest.TestCase):
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.packet(lamp)))
|
||||
return corner, lamp
|
||||
|
||||
def test_replacement_steering_blocks_factory_copies_for_both_hda2_topologies(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
for words in (RAW_LONG, RAW_AOL):
|
||||
for topology, word in words.items():
|
||||
with self.subTest(topology=topology, word=hex(word)):
|
||||
self.mode(word)
|
||||
addresses = (0x110, 0x362) if topology == "lkas_alt" else (0x50, 0x2A4)
|
||||
for address in addresses:
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(0, address), 2)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), 0)
|
||||
|
||||
def test_bsm_all_sixteen_physical_states_and_exact_paired_frames(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
|
||||
@@ -25,84 +25,54 @@ class TestHyundaiKonaCcncHandoff(unittest.TestCase):
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
for experience in ((0,) if debug else (0, 32)):
|
||||
self.mode(0x1C0C, experience)
|
||||
self.assertFalse(self.safety.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(self.safety.safety_camera_release_current(camera, 0))
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(camera, 0), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), -1)
|
||||
|
||||
def test_release_library_camera_slot_helpers_are_inactive(self):
|
||||
release = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True))
|
||||
release.set_alternative_experience(32)
|
||||
self.assertEqual(release.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0x1C0C), 0)
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
self.assertFalse(release.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(release.safety_camera_release_current(camera, 10_000))
|
||||
self.assertEqual(release.safety_camera_release_delay(camera, 10_000), 0)
|
||||
self.assertEqual(release.safety_fwd_packet_hook(camera), -1)
|
||||
|
||||
def test_output_hook_preserves_default_forwarding(self):
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundai, 0), 0)
|
||||
for source, destination in ((0, 2), (1, -1), (2, 0)):
|
||||
packet = libsafety_py.make_CANPacket(0x123, source, bytes(8))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(packet), destination)
|
||||
self.assertEqual(self.forward(packet)[:2], (destination, False))
|
||||
|
||||
def forward(self, packet):
|
||||
output = libsafety_py.new_CANPacket()
|
||||
replaced = libsafety_py.ffi.new('bool *')
|
||||
bus = self.safety.safety_fwd_output_hook(packet, output, replaced)
|
||||
return bus, bool(replaced[0]), output
|
||||
|
||||
def test_handoff_requires_current_camera_and_one_output_owner(self):
|
||||
if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0:
|
||||
self.skipTest('Kona factory handoff is DEBUG only')
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
self.mode(0x0C0C)
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
|
||||
self.mode(0x1C0C)
|
||||
self.safety.set_timer(1_000_000)
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
for status in self.safety.rx_status:
|
||||
status.msg_seen = True
|
||||
status.valid_checksum = True
|
||||
status.valid_quality_flag = True
|
||||
status.last_timestamp = 1_000_000
|
||||
|
||||
self.assertEqual(self.forward(camera)[:2], (0, False))
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
corrupt = self.packet(2, 'a6770a1881001800000a000000900000')
|
||||
self.assertEqual(self.forward(corrupt)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(corrupt), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
warning = self.packet(2, '784d1400000108f0000a000000640000')
|
||||
self.assertEqual(self.forward(warning)[:2], (0, False))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(warning), 0)
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.safety.aol_set_host_request(3)
|
||||
following = self.packet(2, '110d1600000108f0000a000000640000')
|
||||
host = self.packet(0, 'a009150280001800000a000000900000')
|
||||
host[0].data[2] = 20
|
||||
from opendbc.car.hyundai.hyundaicanfd import hkg_can_fd_checksum
|
||||
crc = hkg_can_fd_checksum(0x12A, None, bytearray(host[0].data[0:16]))
|
||||
host[0].data[0], host[0].data[1] = crc & 255, crc >> 8
|
||||
self.safety.set_timer(1_005_000)
|
||||
self.safety.set_timer(1_009_999)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host)) # Require the matching camera counter first.
|
||||
camera_match = self.packet(2, '5ce51500000108f0000a000000640000')
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera_match), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
self.assertTrue(self.safety.safety_stage_tx_hook(host))
|
||||
self.safety.set_timer(1_010_000)
|
||||
match = self.packet(2, '5ce51500000108f0000a000000640000')
|
||||
bus, replaced, output = self.forward(match)
|
||||
self.assertEqual((bus, replaced, output[0].data[2]), (0, True, 21))
|
||||
self.assertEqual(output[0].data[7] & 0xF0, 0xF0)
|
||||
self.assertTrue(self.safety.safety_tx_hook(host))
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.safety.aol_set_host_request(0)
|
||||
following = self.packet(2, '110d1600000108f0000a000000640000')
|
||||
self.safety.set_timer(1_019_999)
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(following, 1_019_999), 1)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.safety.set_timer(1_020_000)
|
||||
self.assertEqual(self.forward(following)[:2], (0, False))
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(host))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
|
||||
@@ -4,7 +4,6 @@ import unittest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
|
||||
@@ -99,8 +98,6 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 3)))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 4, active=False)))
|
||||
if topology.startswith('lka'):
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 5, active=False)))
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 5)))
|
||||
self.safety.set_timer(1_300_001)
|
||||
@@ -108,38 +105,6 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertEqual(self.safety.aol_get_permission_mask(), 0)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 6)))
|
||||
|
||||
def test_hda2_controller_sends_only_one_inactive_release(self):
|
||||
car = angle_profiles.CARS[0]
|
||||
for topology, address, camera_name in (('lka', 0x50, 'CAM_0x2a4'), ('lka_alt', 0x110, 'CAM_0x362')):
|
||||
cp = angle_profiles.params(car, topology, hybrid=True)
|
||||
cp.alternativeExperience = 32
|
||||
word = cp.safetyConfigs[-1].safetyParam
|
||||
self.mode(word)
|
||||
self.sources(word)
|
||||
self.gesture(word)
|
||||
interface = CarInterface(cp)
|
||||
packer, frames = angle_profiles.source_frames(cp, topology)
|
||||
frames.append(packer.make_can_msg(camera_name, 2, {}))
|
||||
state = interface.update([(1_000_000_000, frames)])
|
||||
self.assertTrue(state.canValid)
|
||||
control = structs.CarControl()
|
||||
camera_frame = packer.make_can_msg(camera_name, 0, {})
|
||||
camera = self.packet(camera_frame)
|
||||
self.assertFalse(self.safety.safety_tx_hook(camera))
|
||||
for tick, (active, expected) in enumerate(((False, []), (True, [2]), (False, [1]), (False, []))):
|
||||
control.latActive = active
|
||||
_, sends = interface.apply(control.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
steering = [frame for frame in sends if frame[0] == address]
|
||||
self.assertEqual([(frame[1][9] >> 4) & 3 for frame in steering], expected)
|
||||
for frame in steering:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.packet(frame)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1 if active else 0)
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(camera)), active, (topology, tick))
|
||||
if active:
|
||||
bad_camera = self.packet(camera_frame)
|
||||
bad_camera[0].data[0] ^= 1
|
||||
self.assertFalse(self.safety.safety_tx_hook(bad_camera))
|
||||
|
||||
def test_non_angle_profile_rejects_cb_at_public_and_selected_hooks(self):
|
||||
self.safety.set_alternative_experience(0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0), 0)
|
||||
|
||||
@@ -380,9 +380,7 @@ def test_recorded_pe_stock_wheel_cutoff_withdraws_native_output_without_new_butt
|
||||
assert case.safety.aol_get_permission_mask() == int(moving)
|
||||
assert bool(case.safety.safety_tx_hook(case.command(word, counter))) is moving
|
||||
if not moving:
|
||||
inactive = case.command(word, counter, active=False)
|
||||
assert not case.safety.safety_tx_hook(inactive)
|
||||
assert case.safety.safety_fwd_hook(2, inactive[0].addr) == 0
|
||||
assert case.safety.safety_tx_hook(case.command(word, counter, active=False))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', ['HYUNDAI_IONIQ_5_PE', 'KIA_EV9'])
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.pandad import can_list_to_can_capnp
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
@@ -4,7 +4,6 @@ import os
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from importlib import import_module
|
||||
from typing import cast
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
@@ -17,13 +16,15 @@ from openpilot.common.realtime import config_realtime_process, Priority, Ratekee
|
||||
from openpilot.common.swaglog import cloudlog, ForwardingHandler
|
||||
|
||||
from opendbc.car import DT_CTRL, structs
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.carlog import carlog
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.car_helpers import get_car, interfaces
|
||||
from opendbc.car.gm.distance_button import GMDistanceButtons
|
||||
from opendbc.car.gm.interface import CarInterface as GMInterface
|
||||
from opendbc.car.gm.profiles import profiles_supported as gm_profiles_supported
|
||||
from opendbc.car.hyundai.ioniq6_handoff import (IONIQ6_LONG_PREARM_ENABLED, HandoffOutcome,
|
||||
build_ioniq6_hda2_long_candidate,
|
||||
TimestampedCanPacket, build_ioniq6_hda2_long_candidate,
|
||||
confirm_ioniq6_prepared_takeover, restore_ioniq6_adas,
|
||||
finalize_ioniq6_prepublication, Ioniq6StartupKeepalive,
|
||||
inspect_ioniq6_long_sources)
|
||||
@@ -32,7 +33,6 @@ from opendbc.car.hyundai.ioniq6_media import Ioniq6MediaButtons
|
||||
from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR
|
||||
from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase
|
||||
from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
|
||||
from openpilot.selfdrive.car.can_callbacks import can_comm_callbacks, obd_callback
|
||||
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelContext, VCruiseHelper, slc_target_kph
|
||||
from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card
|
||||
from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings
|
||||
@@ -95,6 +95,35 @@ DISTANCE_GESTURE_KEYS = {Press.SHORT: ('DistanceButtonControl', 0),
|
||||
carlog.addHandler(ForwardingHandler(cloudlog))
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
|
||||
|
||||
curve_press_receipt = slc_physical.curve_press_receipt
|
||||
|
||||
|
||||
@@ -365,11 +394,6 @@ class Car:
|
||||
raise RuntimeError('AOL requires the exact vehicle safety configuration')
|
||||
config.safetyParam |= aol_policy.safety_param_addition
|
||||
self.CP.alternativeExperience |= aol_policy.alternative_experience_addition
|
||||
if self.CP.carFingerprint == HYUNDAI_CAR.HYUNDAI_KONA_2ND_GEN and config.safetyParam == 0x0C0C and not is_release:
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff
|
||||
self.sm.update(0)
|
||||
if self.sm.valid['pandaStates'] and self.sm.alive['pandaStates']:
|
||||
configure_kona_factory_handoff(self.CP, self.sm['pandaStates'])
|
||||
self.vehicle_startup.finalize_aol_configuration(self.CI)
|
||||
from openpilot.starpilot.car.hyundai.redneck_cruise import configure
|
||||
self.redneck_cruise = configure(self, subscribed_services)
|
||||
@@ -377,14 +401,12 @@ class Car:
|
||||
self.learning_send_mono_ns = self.learning_send_committed_mono_ns = 0
|
||||
self.learning_car_state_source_ns = 0
|
||||
self.learning_applied_evidence = self.learning_previous_applied_evidence = None
|
||||
self.learning_feedback_factory = None
|
||||
try:
|
||||
from openpilot.starpilot.lateral.learning_preferences import read_preference
|
||||
preference = read_preference(self.params, self.CP)
|
||||
if preference.valid and preference.enabled:
|
||||
from opendbc.car.steering_projection import install_observer
|
||||
self.learning_stamp_observer = self.record_learning_send_stamp if install_observer(self.CI) else None
|
||||
self._prepare_feedback_capture()
|
||||
except Exception:
|
||||
pass # Optional learning setup cannot stop native startup.
|
||||
self.aol_transport_feedback = TransportPauseFeedback(self.CP) if self.aol_replay else None
|
||||
@@ -1140,9 +1162,10 @@ class Car:
|
||||
publication = getattr(self, 'learning_feedback_publication', None)
|
||||
if publication is not None:
|
||||
try:
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
feedback_companion = (companion.as_reader().as_builder() if companion is not None else
|
||||
messaging.new_message('starpilotCarState', valid=bool(cs_send.valid), logMonoTime=int(cs_send.logMonoTime)))
|
||||
self.learning_feedback_writer(feedback_companion.starpilotCarState, publication)
|
||||
write_publication(feedback_companion.starpilotCarState, publication)
|
||||
companion = feedback_companion
|
||||
except Exception:
|
||||
self.learning_feedback_publication = None
|
||||
@@ -1462,26 +1485,15 @@ class Car:
|
||||
(not ps.safetyRxChecksInvalid or inactive_keepalive and self.gm_startup_keepalive())
|
||||
for ps, cfg in zip(pandas, self.CP.safetyConfigs, strict=True)))
|
||||
|
||||
def _prepare_feedback_capture(self):
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest
|
||||
|
||||
# The first calibrated receipt can arrive after lateral is active.
|
||||
import_module('openpilot.starpilot.flm.learning_wire')
|
||||
import_module('openpilot.starpilot.flm.physical_input_observation')
|
||||
self._feedback_cp_sha256 = car_params_digest(self.CP)
|
||||
self.learning_feedback_writer = write_publication
|
||||
self.learning_feedback_factory = card_capture_for
|
||||
|
||||
def _feedback_capture(self, now_ns):
|
||||
# Default OFF performs no feedback-module import, digest or witness allocation.
|
||||
try:
|
||||
source = self.sm['autoSteeringLearning'].learning.sourceReceipt
|
||||
factory = self.learning_feedback_factory
|
||||
if factory is None or not source.enabled or source.manual:
|
||||
if not source.enabled or source.manual:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
return factory(self, now_ns)
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
return card_capture_for(self, now_ns)
|
||||
except Exception:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from opendbc.car import structs
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
from openpilot.starpilot.flm.learning_wire import write_source_receipt
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import SourceState
|
||||
|
||||
|
||||
def test_first_calibrated_feedback_uses_startup_preparation():
|
||||
card = Car.__new__(Car)
|
||||
card.CP = structs.CarParams.new_message(brand='gm', carFingerprint='CHEVROLET_BOLT_ACC_2022_2023')
|
||||
card.learning_feedback_factory = None
|
||||
card._prepare_feedback_capture()
|
||||
|
||||
stamp = 10_000_000_000
|
||||
service = 'autoSteeringLearning'
|
||||
packet = messaging.new_message(service, valid=True, logMonoTime=stamp)
|
||||
source = SourceState(True, False, 'boot', 'a' * 64, stamp, stamp + 500_000_000,
|
||||
card._feedback_cp_sha256, (0., 0., 0.))
|
||||
write_source_receipt(packet, source)
|
||||
sm = messaging.SubMaster([service])
|
||||
sm.update_msgs(stamp / 1e9, [packet.as_reader()])
|
||||
sm.alive[service] = sm.freq_ok[service] = True
|
||||
card.sm = sm
|
||||
|
||||
with patch('openpilot.starpilot.flm.runtime_adapter_registry.car_params_digest', side_effect=AssertionError):
|
||||
capture = card._feedback_capture(stamp)
|
||||
assert capture is not None
|
||||
output = messaging.new_message('carOutput', valid=True, logMonoTime=stamp)
|
||||
companion = messaging.new_message('starpilotCarState', valid=True, logMonoTime=stamp)
|
||||
card.learning_feedback_writer(companion.starpilotCarState, capture.publication(output))
|
||||
assert companion.starpilotCarState.feedbackPublication.version == 1
|
||||
assert not companion.starpilotCarState.feedbackPublication.outputKnown
|
||||
assert card._feedback_capture(stamp + 500_000_001) is None
|
||||
@@ -16,7 +16,6 @@ from openpilot.selfdrive.controls.lib.cycle_timing import ControlCycleTiming, PU
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
from opendbc.car.car_helpers import interfaces
|
||||
from opendbc.car.honda.values import CAR as HONDA_CAR, accord_angle_steer_ratio
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature
|
||||
from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, predicted_lateral_accels, read_gain
|
||||
@@ -358,9 +357,6 @@ class Controls:
|
||||
torque_extension = getattr(self.LaC, 'starpilot_extension', None)
|
||||
if torque_extension is not None:
|
||||
sr = torque_extension.vehicle_model_ratio(sr, CS.vEgo)
|
||||
if self.CP.carFingerprint == HONDA_CAR.HONDA_ACCORD and self.CP.steerControlType == car.CarParams.SteerControlType.angle:
|
||||
# angle-loop EPS: the variable-ratio rack map at the measured angle replaces the learner
|
||||
sr = accord_angle_steer_ratio(CS.steeringAngleDeg - lp.angleOffsetDeg)
|
||||
self.VM.update_params(x, sr)
|
||||
|
||||
steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import math
|
||||
|
||||
from openpilot.cereal import log
|
||||
from opendbc.car.honda.values import CAR as HONDA_CAR, HondaFlags, accord_angle_at_own_ratio
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
from openpilot.starpilot.car.subaru.angle_tune import _ascent_angle_tracking_target, _ascent_low_speed_angle_target
|
||||
|
||||
@@ -15,11 +14,7 @@ class LatControlAngle(LatControl):
|
||||
self.is_ascent = CP.brand == 'subaru' and CP.carFingerprint == 'SUBARU_ASCENT_2023'
|
||||
self.ascent_angle_target = None
|
||||
self.sat_check_min_speed = 5.
|
||||
# Accord on the angle-loop EPS: the EPS angle loop lags 0.3-0.6 s, so a raw angle-error rule flags ordinary turn
|
||||
# entries; its carcontroller limits the setpoint itself (lateral accel/jerk, error clip), so use carOutput instead
|
||||
self.is_accord_angle_loop = CP.brand == "honda" and bool(CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW)
|
||||
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai") or self.is_accord_angle_loop
|
||||
self.is_accord = CP.carFingerprint == HONDA_CAR.HONDA_ACCORD
|
||||
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai")
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
angle_log = log.ControlsState.LateralAngleState.new_message()
|
||||
@@ -31,9 +26,6 @@ class LatControlAngle(LatControl):
|
||||
else:
|
||||
angle_log.active = True
|
||||
angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll))
|
||||
if self.is_accord:
|
||||
# controlsd took sR from the rack map at the MEASURED angle; re-evaluate it at the desired angle
|
||||
angle_steers_des = accord_angle_at_own_ratio(angle_steers_des, VM.sR)
|
||||
angle_steers_des += params.angleOffsetDeg
|
||||
if self.is_ascent:
|
||||
if self.ascent_angle_target is None:
|
||||
|
||||
@@ -7,8 +7,6 @@ from openpilot.cereal import log
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction
|
||||
from opendbc.car.toyota import legacy_advert_filter
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA_CAR
|
||||
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY, CV
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
@@ -54,8 +52,6 @@ class LatControlTorque(LatControl):
|
||||
and not (CP.notCar or CP.passive or CP.dashcamOnly)
|
||||
)
|
||||
self.controller_mode = default_selection(CP).mode if controller_mode is None else ControllerMode(controller_mode)
|
||||
self.sienna_center_friction = (self.controller_mode == ControllerMode.STANDARD and
|
||||
CP.carFingerprint == TOYOTA_CAR.TOYOTA_SIENNA and legacy_advert_filter.enabled(CP))
|
||||
self.controller_policy = policy_for(CP)
|
||||
if self.controller_mode == ControllerMode.STARPILOT and self.controller_policy is None:
|
||||
raise ValueError('No StarPilot torque policy for CarParams')
|
||||
@@ -102,12 +98,7 @@ class LatControlTorque(LatControl):
|
||||
weight *= np.interp(abs(setpoint), [0.25, 0.65], [1.0, 0.0])
|
||||
threshold += max(np.interp(CS.vEgo, [65 * CV.MPH_TO_MS, 75 * CV.MPH_TO_MS], [0.65, 0.78]) - threshold, 0.0) * weight
|
||||
error = math.copysign(max(abs(error) - 0.04 * weight, 0.0), error)
|
||||
friction = get_friction(error, deadzone, threshold, self.torque_params)
|
||||
if self.sienna_center_friction and not CS.steeringPressed:
|
||||
speed_weight = np.interp(CS.vEgo * CV.MS_TO_MPH, [34., 39., 50., 56.], [0., 1., 1., 0.])
|
||||
center_weight = np.interp(abs(setpoint), [0.22, 0.58], [1., 0.])
|
||||
friction *= 1.0 - 0.5 * speed_weight * center_weight
|
||||
return friction
|
||||
return get_friction(error, deadzone, threshold, self.torque_params)
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
self.flm_surface = self.flm_source.sample(active=active, speed=CS.vEgo)
|
||||
|
||||
@@ -53,10 +53,8 @@ A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
|
||||
J_CRUISE_VALS = [1.6, 1.2, 0.8, 0.6]
|
||||
A_CRUISE_MIN = -0.5
|
||||
CRUISE_ACCEL_RESPONSE_TIME = 2.0
|
||||
MODEL_Y_HANDOFF_COAST_TOLERANCE = 0.2
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.25
|
||||
MODEL_Y_SPEED_STEP_LIFT_ACCEL = 0.15
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 4_000_000_000
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.45
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 2_000_000_000
|
||||
SLC_BRAKE_ONSET_JERK = 0.15 # m/s^3: how fast braking may build after an SLC overshoot
|
||||
SLC_BRAKE_ONSET_ACCEL = -0.3 # m/s^2: past this the brakes are engaged and normal jerk resumes
|
||||
CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N]
|
||||
@@ -114,7 +112,7 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
|
||||
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach
|
||||
target_accel = np.clip(speed_error, cruise_min, max_accel)
|
||||
j_cruise = np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS)
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= MODEL_Y_SPEED_STEP_LIFT_ACCEL):
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= 0.0):
|
||||
j_cruise = min(j_cruise, MODEL_Y_SPEED_STEP_JERK)
|
||||
decel_start = a_cruise_prev if a_target_prev is None else min(a_cruise_prev, a_target_prev)
|
||||
lower = decel_start - j_cruise * dt
|
||||
@@ -154,7 +152,6 @@ class LongitudinalPlanner:
|
||||
|
||||
self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt)
|
||||
self.a_cruise = init_a
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
self.previous_manual_cruise_kph: float | None = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.output_a_target = init_a
|
||||
@@ -464,38 +461,16 @@ class LongitudinalPlanner:
|
||||
if downhill_error is not None and navigation_ceiling(
|
||||
sm, self.CP, sample_now_ns, limit + .25, slowdown_percent=self.navigation_slowdown_percent) is not None:
|
||||
downhill_error = None
|
||||
cruise_seed = self.a_cruise
|
||||
speed_step = False
|
||||
if self.CP.carFingerprint == 'TESLA_MODEL_Y':
|
||||
cs = sm['carState']
|
||||
leads = (sm['radarState'].leadOne, sm['radarState'].leadTwo)
|
||||
recent_pedal_preview = 0 < self.model_y_handoff_preview_until_ns and sample_now_ns < self.model_y_handoff_preview_until_ns
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
if (reset_state and self.CP.openpilotLongitudinalControl and sm['selfdriveState'].enabled and
|
||||
not sm['carControl'].longActive and cs.cruiseState.enabled and (cs.gasPressed or recent_pedal_preview) and not cs.brakePressed and
|
||||
cs.canValid and not cs.canTimeout and not cs.standstill and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
-MODEL_Y_HANDOFF_COAST_TOLERANCE < cruise_seed <= 0.5 and v_cruise_initialized and v_cruise - v_ego > 1.0 and
|
||||
output_a_target_mpc > cruise_seed and self.mpc.solution_status == 0 and
|
||||
self.allow_throttle and not self.fcw and not sm['controlsState'].forceDecel and
|
||||
not self.force_stop_plan.should_stop and not self.force_stop_plan.forcing and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and downhill_error is None and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
not (coast_plan is not None and (coast_plan.force_decel or coast_plan.pulse_coasting or coast_plan.brake_floor is not None)) and
|
||||
all(not lead.present or (lead.vLead > v_ego and lead.dRel > max(15., 2. * v_ego)) for lead in leads)):
|
||||
# Preview one actuator delay while the pedal still owns acceleration. Lead and stop arbitration follow below.
|
||||
preview = min(0.25, action_t * np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS))
|
||||
# Taper through coast-down so a near-zero reading does not drop the entire preview.
|
||||
cruise_seed += preview * min(1.0, 1.0 + cruise_seed / MODEL_Y_HANDOFF_COAST_TOLERANCE)
|
||||
if cs.gasPressed:
|
||||
# The pedal state can clear a planner frame before longitudinal control resumes.
|
||||
self.model_y_handoff_preview_until_ns = sample_now_ns + 100_000_000
|
||||
manual_cruise = (
|
||||
profile_eligible and not reset_state and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
cs.canValid and not cs.canTimeout and not cs.gasPressed and not cs.brakePressed and not cs.standstill and
|
||||
not sm['controlsState'].forceDecel and self.allow_throttle and not self.fcw and
|
||||
not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and
|
||||
not any(lead.present for lead in leads) and
|
||||
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting or
|
||||
coast_plan.brake_floor is not None)) and self.mpc.solution_status == 0 and
|
||||
@@ -512,7 +487,7 @@ class LongitudinalPlanner:
|
||||
self.previous_manual_cruise_kph = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego,
|
||||
cruise_seed, steer_angle_without_offset, self.CP, self.dt,
|
||||
self.a_cruise, steer_angle_without_offset, self.CP, self.dt,
|
||||
accel_coast, self.allow_throttle, cruise_profile,
|
||||
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
|
||||
a_target_prev=self.output_a_target,
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
"""Accord on the angle-loop EPS: steerSaturated follows the carcontroller's limiter, not the raw angle error."""
|
||||
import pytest
|
||||
|
||||
from openpilot.cereal import log
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.honda import carcontroller as honda_carcontroller
|
||||
from opendbc.car.honda import interface as honda_interface
|
||||
from opendbc.car.honda.interface import CarInterface as HondaInterface
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.nissan.interface import CarInterface as NissanInterface
|
||||
from opendbc.car.nissan.values import CAR as NISSAN
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
|
||||
|
||||
DT = 0.01
|
||||
ERROR_DEG = 6.0 # an ordinary turn-entry error on the angle-loop EPS, above the 2.5 deg raw-error threshold
|
||||
|
||||
|
||||
class FakeParams:
|
||||
def get_bool(self, key, block=False, default=False):
|
||||
return default
|
||||
|
||||
def get_float(self, key, block=False, default=0.0):
|
||||
return default
|
||||
|
||||
def put_float(self, key, value):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_params(monkeypatch):
|
||||
# the Honda port may read Params in the interface/carcontroller; keep the test off the device store
|
||||
monkeypatch.setattr(honda_interface, "Params", FakeParams, raising=False)
|
||||
monkeypatch.setattr(honda_carcontroller, "Params", FakeParams, raising=False)
|
||||
|
||||
|
||||
def accord_cp(eps_fw: bytes):
|
||||
car_fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=eps_fw, address=0x18DA30F1, subAddress=0)]
|
||||
return HondaInterface.get_params(HONDA.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
|
||||
|
||||
|
||||
def angle_cp():
|
||||
return accord_cp(b"39990-TVA,A16C")
|
||||
|
||||
|
||||
def torque_honda_cp():
|
||||
return accord_cp(b"39990-TVA-A160\x00\x00")
|
||||
|
||||
|
||||
def nissan_cp():
|
||||
return NissanInterface.get_non_essential_params(NISSAN.NISSAN_LEAF)
|
||||
|
||||
|
||||
def run(cp, steer_limited_by_safety, seconds=2.0, v_ego=20.0):
|
||||
cp_reader = cp.as_reader()
|
||||
controller = LatControlAngle(cp_reader, None, DT)
|
||||
VM = VehicleModel(cp_reader)
|
||||
params = log.VehicleParameters.new_message()
|
||||
CS = car.CarState.new_message()
|
||||
CS.vEgo = v_ego
|
||||
CS.steeringPressed = False
|
||||
CS.steeringAngleDeg = 0.0
|
||||
# find the desired angle for a small curvature, then hold the wheel ERROR_DEG short of it
|
||||
_, angle_des, _ = controller.update(True, CS, VM, params, False, 0.002, False, 0.2)
|
||||
controller.reset()
|
||||
CS.steeringAngleDeg = angle_des - ERROR_DEG
|
||||
saturated = []
|
||||
for _ in range(round(seconds / DT)):
|
||||
_, des, lac_log = controller.update(True, CS, VM, params, steer_limited_by_safety, 0.002, False, 0.2)
|
||||
assert abs((des - CS.steeringAngleDeg) - ERROR_DEG) < 1e-6
|
||||
saturated.append(lac_log.saturated)
|
||||
return controller, saturated
|
||||
|
||||
|
||||
def test_accord_angle_cp_takes_the_carcontroller_path():
|
||||
cp = angle_cp()
|
||||
assert cp.steerControlType == CarParams.SteerControlType.angle
|
||||
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
|
||||
assert cp.steerLimitTimer == pytest.approx(0.8)
|
||||
|
||||
|
||||
def test_accord_angle_error_alone_does_not_saturate():
|
||||
controller, saturated = run(angle_cp(), steer_limited_by_safety=False)
|
||||
assert controller.use_steer_limited_by_safety
|
||||
assert not any(saturated)
|
||||
|
||||
|
||||
def test_accord_angle_limited_by_carcontroller_saturates():
|
||||
_, saturated = run(angle_cp(), steer_limited_by_safety=True)
|
||||
assert saturated[-1]
|
||||
# debounced by steerLimitTimer (0.8 s), not instantly
|
||||
assert not saturated[round(0.7 / DT)]
|
||||
|
||||
|
||||
def test_accord_angle_curvature_limited_still_saturates():
|
||||
cp = angle_cp().as_reader()
|
||||
controller = LatControlAngle(cp, None, DT)
|
||||
VM = VehicleModel(cp)
|
||||
CS = car.CarState.new_message()
|
||||
CS.vEgo = 20.0
|
||||
params = log.VehicleParameters.new_message()
|
||||
for _ in range(200):
|
||||
_, _, lac_log = controller.update(True, CS, VM, params, False, 0.0, True, 0.2)
|
||||
assert lac_log.saturated
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cp_fn", [torque_honda_cp, nissan_cp], ids=["honda_torque_fw", "nissan"])
|
||||
def test_other_cars_keep_the_angle_error_rule(cp_fn):
|
||||
controller, saturated = run(cp_fn(), steer_limited_by_safety=False)
|
||||
assert not controller.use_steer_limited_by_safety
|
||||
assert saturated[-1]
|
||||
|
||||
|
||||
def test_tesla_still_uses_carcontroller_path():
|
||||
from opendbc.car.tesla.interface import CarInterface as TeslaInterface
|
||||
from opendbc.car.tesla.values import CAR as TESLA
|
||||
controller, saturated = run(TeslaInterface.get_non_essential_params(TESLA.TESLA_MODEL_3), steer_limited_by_safety=False)
|
||||
assert controller.use_steer_limited_by_safety
|
||||
assert not any(saturated)
|
||||
Binary file not shown.
Binary file not shown.
@@ -607,13 +607,12 @@ int main() {
|
||||
unsupported.safety_param ^= 0x1U;
|
||||
assert(!aol_capable(unsupported, TEST_MODE, TEST_REGISTRY));
|
||||
|
||||
for (uint16_t word = 0U; word < 8192U; ++word) {
|
||||
for (uint16_t word = 0U; word < 4096U; ++word) {
|
||||
auto stock_honda = status();
|
||||
stock_honda.safety_mode = 20U;
|
||||
stock_honda.safety_param = word;
|
||||
const bool classic = word == 34U || word == 35U || word == 163U;
|
||||
const bool stock = word == 0U || word == 1U || word == 8U || word == 9U || word == 10U || word == 11U || word == 16U || word == 17U || word == 80U || word == 81U || word == 512U || word == 513U || word == 1058U || word == 1059U || word == 1570U || word == 1571U || word == 2082U || word == 2083U || word == 2211U ||
|
||||
word == 4096U || word == 4097U || word == 6178U || word == 6179U;
|
||||
const bool stock = word == 0U || word == 1U || word == 8U || word == 9U || word == 10U || word == 11U || word == 16U || word == 17U || word == 80U || word == 81U || word == 512U || word == 513U || word == 1058U || word == 1059U || word == 1570U || word == 1571U || word == 2082U || word == 2083U || word == 2211U;
|
||||
assert(aol_capable(stock_honda, 20U, VEHICLE_REGISTRY) == (classic || stock));
|
||||
assert(aol_runtime_enabled(false, stock_honda, VEHICLE_REGISTRY) == stock);
|
||||
stock_honda.safety_mode = 1U;
|
||||
|
||||
@@ -7,7 +7,7 @@ from types import SimpleNamespace
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.ui.appearance_preferences import format_lead_info
|
||||
from openpilot.starpilot.ui.rainbow_path import RainbowPath
|
||||
from openpilot.starpilot.ui.road_colors import lane_color, lead_marker_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.road_colors import lane_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.onroad_customization import ROAD_COLORS
|
||||
from openpilot.starpilot.lateral.lane_feedback import BLUE, direction as lane_centering_direction
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
@@ -216,8 +216,7 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
@staticmethod
|
||||
def _valid_lead_numbers(lead) -> bool:
|
||||
try:
|
||||
distance, lateral = float(lead.dRel), float(lead.yRel)
|
||||
relative_speed = float(lead.vRel) if lead.vRel is not None else 0.0
|
||||
distance, lateral, relative_speed = float(lead.dRel), float(lead.yRel), float(lead.vRel)
|
||||
return distance > 0 and all(math.isfinite(value) for value in (distance, lateral, relative_speed))
|
||||
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
@@ -228,9 +227,6 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
model = sm['modelV2']
|
||||
e2e = (sm.valid['longitudinalPlan'] and sm.valid['modelV2'] and
|
||||
plan.longitudinalPlanSource == log.LongitudinalPlan.LongitudinalPlanSource.e2e and len(model.leadsV3) > 1)
|
||||
ego_speed = sm['carState'].vEgo if e2e and sm.all_checks(['carState']) else None
|
||||
if ego_speed is not None and not math.isfinite(ego_speed):
|
||||
ego_speed = None
|
||||
leads = []
|
||||
for index in range(2):
|
||||
info = None
|
||||
@@ -238,8 +234,7 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
candidate = model.leadsV3[index]
|
||||
if candidate.x and candidate.y and candidate.v:
|
||||
info = SimpleNamespace(present=candidate.prob > 0.5, dRel=candidate.x[0] - RADAR_TO_CAMERA,
|
||||
yRel=-candidate.y[0], vRel=candidate.v[0] - ego_speed if ego_speed is not None else None,
|
||||
vLead=candidate.v[0])
|
||||
yRel=-candidate.y[0], vRel=0.0, vLead=candidate.v[0])
|
||||
elif sm.valid['radarState']:
|
||||
info = (sm['radarState'].leadOne, sm['radarState'].leadTwo)[index]
|
||||
valid = info is not None and info.present and self._valid_lead_numbers(info)
|
||||
@@ -493,8 +488,7 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
for lead in self._lead_vehicles:
|
||||
if not lead.bar.size or lead.fade_filter.x <= 0:
|
||||
continue
|
||||
color = lead_marker_color(self.road_style, lead.fade_filter.x)
|
||||
draw_polygon(self._rect, lead.bar + offset, color if color is not None else rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
|
||||
draw_polygon(self._rect, lead.bar + offset, rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.starpilot.ui.torque_feedback import accord_angle_error_bar, accord_angle_error_fraction
|
||||
|
||||
# TODO: arc_bar_pts doesn't consider rounded end caps part of the angle span
|
||||
TORQUE_ANGLE_SPAN = 12.7 # degrees on the default 476 px camera view; narrower views beside the navigation panel scale down
|
||||
@@ -163,18 +162,6 @@ class TorqueBar(Widget):
|
||||
if self._demo:
|
||||
return
|
||||
|
||||
# Accord on the angle-loop EPS firmware: the bar is the angle error the setpoint carries,
|
||||
# (setpoint sent - wheel angle) / the carcontroller's error clip at this speed, so full
|
||||
# scale means the clip is binding. Sign follows the torque branch: bar points the way the EPS pulls.
|
||||
if accord_angle_error_bar(ui_state.CP):
|
||||
car_state = ui_state.sm['carState']
|
||||
if not ui_state.sm['carControl'].latActive:
|
||||
self._torque_filter.update(0.0)
|
||||
else:
|
||||
setpoint = ui_state.sm['carOutput'].actuatorsOutput.steeringAngleDeg
|
||||
self._torque_filter.update(accord_angle_error_fraction(setpoint, car_state.steeringAngleDeg, car_state.vEgoRaw))
|
||||
return
|
||||
|
||||
# torque line
|
||||
if ui_state.sm['controlsState'].lateralControlState.which() in ('angleState', 'curvatureState'):
|
||||
controls_state = ui_state.sm['controlsState']
|
||||
|
||||
@@ -8,7 +8,7 @@ from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.ui.appearance_preferences import format_lead_info
|
||||
from openpilot.starpilot.ui.rainbow_path import RainbowPath
|
||||
from openpilot.starpilot.ui.road_colors import edge_gradient, lane_color, lead_marker_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.road_colors import edge_gradient, lane_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.onroad_customization import ROAD_COLORS
|
||||
from openpilot.starpilot.lateral.lane_feedback import BLUE, direction as lane_centering_direction
|
||||
from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT
|
||||
@@ -413,11 +413,8 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
if not lead.glow or not lead.chevron:
|
||||
continue
|
||||
|
||||
style = self.road_style
|
||||
glow = lead_marker_color(style, 1.0)
|
||||
fill = lead_marker_color(style, lead.fill_alpha / 255)
|
||||
rl.draw_triangle_fan(lead.glow, len(lead.glow), glow if glow is not None else rl.Color(218, 202, 37, 255))
|
||||
rl.draw_triangle_fan(lead.chevron, len(lead.chevron), fill if fill is not None else rl.Color(201, 34, 49, lead.fill_alpha))
|
||||
rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255))
|
||||
rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha))
|
||||
|
||||
def _draw_lead_info(self, lead: LeadVehicle, text: str) -> None:
|
||||
# Centered just above the chevron's glow, kept on screen.
|
||||
|
||||
@@ -186,71 +186,3 @@ def test_main_on_during_permanent_fault_does_not_queue_automatic_rearm(alpha):
|
||||
cs.steerFaultPermanent = False
|
||||
owner.update(cs, now_ns=1_020_000_000, fault_active=False)
|
||||
assert not owner.allowed_latch
|
||||
|
||||
|
||||
def test_stock_mqb_main_rearm_waits_only_for_the_current_native_receipt():
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.starpilot.aol.tests.test_gm_held_native import Peers
|
||||
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback
|
||||
from openpilot.starpilot.aol.wire import PandaSlot, SafetyState, encode_safety
|
||||
from openpilot.starpilot.car.volkswagen.aol import awaiting_initial_request, policy_for
|
||||
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0][0xAD] = 8
|
||||
cp = CarInterface.get_params(CAR.VOLKSWAGEN_ATLAS_MK1, fp, [], False, False, False)
|
||||
policy = policy_for(cp)
|
||||
cp.safetyConfigs[-1].safetyParam |= policy.safety_param_addition
|
||||
cp.alternativeExperience |= policy.alternative_experience_addition
|
||||
owner = VolkswagenStockCardIntent(cp, AolSettings(True, 5., 0, 0, (0, 0, 0), (0, 0, 0)))
|
||||
cs = structs.CarState(canValid=True, vEgo=8., vEgoRaw=8., gearShifter=structs.CarState.GearShifter.drive)
|
||||
cs.cruiseState.available = True
|
||||
arm = 2_000_000_000
|
||||
owner.update(cs, now_ns=arm - 300_000_000)
|
||||
cs.cruiseState.available = False
|
||||
owner.update(cs, now_ns=arm - 100_000_000)
|
||||
assert not owner.allowed_latch
|
||||
cs.cruiseState.available = True
|
||||
owner.update(cs, now_ns=arm)
|
||||
assert owner.allowed_latch
|
||||
|
||||
now = arm + 110_000_000
|
||||
stamp = now - 2_000_000
|
||||
event = messaging.new_message('onroadEvents', 1, valid=True, logMonoTime=stamp)
|
||||
event.onroadEvents[0].name = 'pcmDisable'
|
||||
event.onroadEvents[0].userDisable = True
|
||||
axis = messaging.new_message('aolAxisState', valid=True, logMonoTime=stamp)
|
||||
axis.aolAxisState.sessionId = axis.aolAxisState.faultSessionId = 'drive'
|
||||
axis.aolAxisState.intentProducerSessionId = 'card'
|
||||
axis.aolAxisState.sequence = 2
|
||||
axis.aolAxisState.faultReason = 'none'
|
||||
|
||||
axis.aolAxisState.qualified = True
|
||||
axis.aolAxisState.desiredLateral = True
|
||||
axis.aolAxisState.observedMonoTime = axis.aolAxisState.faultEventMonoTime = stamp
|
||||
axis.aolAxisState.sourceCarStateMonoTime = stamp - 3_000_000
|
||||
axis.aolAxisState.validUntilMonoTime = stamp + 30_000_000
|
||||
health = messaging.new_message('pandaStates', 1, valid=True, logMonoTime=stamp)
|
||||
health.pandaStates[0].safetyModel = 'volkswagen'
|
||||
health.pandaStates[0].safetyParam = 8
|
||||
health.pandaStates[0].alternativeExperience = 32
|
||||
native = SafetyState(1, True, stamp, stamp + 200_000_000, 15, 8, False, False, True, False, 'board', 'drive',
|
||||
stamp, (PandaSlot(0, 'board', 15, 8, 32),))
|
||||
wire = messaging.new_message('aolSafetyWire', 0, valid=True, logMonoTime=stamp)
|
||||
wire.aolSafetyWire = encode_safety(native)
|
||||
feedback = TransportPauseFeedback(cp)
|
||||
feedback.session, feedback.sequence, feedback.ever_lateral_active = 'drive', 1, True
|
||||
feedback.signature = (None,) * 14 + ('card', 0)
|
||||
def waiting():
|
||||
return awaiting_initial_request(cp, cs, Peers([axis, event, health, wire]), native, feedback,
|
||||
owner, now_ns=now, producer='card')
|
||||
assert waiting()
|
||||
assert owner.intent_publication(cs, now)[-1] == arm + 200_000_000
|
||||
event.onroadEvents[0].name = 'buttonCancel'
|
||||
assert not waiting()
|
||||
event.onroadEvents[0].name = 'pcmDisable'
|
||||
cs.cruiseState.enabled = True
|
||||
owner.update(cs, now_ns=now)
|
||||
cs.cruiseState.enabled = False
|
||||
assert not waiting()
|
||||
owner.update(cs, now_ns=arm + 200_000_001)
|
||||
assert not owner.allowed_latch
|
||||
|
||||
@@ -11,8 +11,7 @@ inline constexpr AolSafetyProfile HONDA_AOL_PROFILE{20U, honda_aol_param, false}
|
||||
|
||||
inline bool honda_stock_aol_param(uint16_t param) {
|
||||
return (param == 0U) || (param == 1U) || (param == 8U) || (param == 9U) || (param == 10U) || (param == 11U) || (param == 16U) || (param == 17U) || (param == 80U) || (param == 81U) || (param == 512U) || (param == 513U) ||
|
||||
(param == 1058U) || (param == 1059U) || (param == 1570U) || (param == 1571U) || (param == 2082U) || (param == 2083U) || (param == 2211U) ||
|
||||
(param == 4096U) || (param == 4097U) || (param == 6178U) || (param == 6179U);
|
||||
(param == 1058U) || (param == 1059U) || (param == 1570U) || (param == 1571U) || (param == 2082U) || (param == 2083U) || (param == 2211U);
|
||||
}
|
||||
|
||||
inline bool honda_nidec_aol_param(uint16_t param) {
|
||||
|
||||
@@ -26,7 +26,6 @@ from opendbc.car.hyundai.canfd_owner import config_index
|
||||
from opendbc.car.hyundai.canfd_stock_aol import (
|
||||
qualified as qualified_canfd_stock, qualified_long as qualified_canfd_long,
|
||||
LONG_AOL_WORDS as CANFD_LONG_AOL_WORDS, STOCK_AOL_MARKER, STOCK_AOL_WORDS,
|
||||
KONA_IDLE_AOL_WORD, kona_idle_handoff_profile,
|
||||
)
|
||||
from opendbc.car.hyundai.non_scc_aol import qualified as qualified_non_scc, aol_word, AOL_MARKER, AOL_EXPERIENCE, AOL_WORDS, SOFTWARE_CRUISE
|
||||
from opendbc.car.hyundai.kona_aol import allow_lateral_onset as kona_lateral_onset
|
||||
@@ -203,16 +202,6 @@ def aol_safety_config(CP):
|
||||
return CP.safetyConfigs[owner] if owner is not None else None
|
||||
|
||||
|
||||
|
||||
def configure_kona_factory_handoff(cp, pandas):
|
||||
if (not kona_idle_handoff_profile(cp) or cp.alternativeExperience != 32 or
|
||||
cp.safetyConfigs[0].safetyParam != 0x0C0C or len(pandas) != 1):
|
||||
return
|
||||
panda = pandas[0]
|
||||
if (str(panda.pandaType) == 'cuatro' and not panda.faults and
|
||||
(panda.ignitionCan or panda.ignitionLine) and not panda.controlsAllowed):
|
||||
cp.safetyConfigs[0].safetyParam = KONA_IDLE_AOL_WORD
|
||||
|
||||
def policy_for(CP) -> AolVehiclePolicy:
|
||||
policy = _policy_for(CP)
|
||||
if (CP.carFingerprint in IONIQ_5_CARS and has_left_paddle(CP) and
|
||||
|
||||
@@ -87,8 +87,6 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
self.main_available = False
|
||||
self.main_neutral = False
|
||||
self.main_pulse = False
|
||||
self.stock_main_rearm_ns = 0
|
||||
self.stock_main_rearm_cruise_seen = False
|
||||
self.startup_arm_ns = 0
|
||||
self.startup_deferred = False
|
||||
self.startup_release_ns = 0
|
||||
@@ -133,15 +131,6 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
else:
|
||||
events.append(structs.CarState.ButtonEvent(**event.to_dict()))
|
||||
available = bool(state.cruiseState.available)
|
||||
if (not self.allowed_latch or not available or
|
||||
any(event.type == ButtonType.cancel and event.pressed for event in state.buttonEvents)):
|
||||
self.stock_main_rearm_ns = 0
|
||||
if self.stock_main_rearm_ns and now_ns > self.stock_main_rearm_ns + SAFETY_MAX_AGE_NS:
|
||||
self.allowed_latch = False
|
||||
self.stock_main_rearm_ns = 0
|
||||
if self.stock_main_rearm_ns and state.cruiseState.enabled:
|
||||
self.stock_main_rearm_cruise_seen = True
|
||||
stock_main_rearm = self.main_neutral and not self.main_available and stock_qualified(self.cp, marked_only=True)
|
||||
if (not self.settings.enabled or self.settings.main_action == AOL_TOGGLE or self.settings.lkas_action == AOL_TOGGLE or
|
||||
(state.canValid and not state.canTimeout and (state.steerFaultPermanent or state.accFaulted)) or
|
||||
any(event.type == ButtonType.cancel and event.pressed for event in CS.buttonEvents) and
|
||||
@@ -205,9 +194,6 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
if not self.startup_release_ns:
|
||||
self.startup_release_ns = now_ns
|
||||
self.allowed_latch = True
|
||||
if stock_main_rearm:
|
||||
self.stock_main_rearm_ns = self._last_latch_edge_ns = now_ns
|
||||
self.stock_main_rearm_cruise_seen = bool(state.cruiseState.enabled)
|
||||
if self.main_startup_pending and not self.startup_arm_ns:
|
||||
self.startup_arm_ns = now_ns
|
||||
self.main_startup_pending = False
|
||||
@@ -221,9 +207,6 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
def observe_startup_readiness(self, sm, cs, *, native, panda_ready, now_ns, producer):
|
||||
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, current_axis
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native, cp_identity
|
||||
if (self.stock_main_rearm_ns and panda_ready and native is not None and native.requestedLateral and native.lateralAllowed and
|
||||
self.stock_main_rearm_ns <= native.observedMonoTime <= self.stock_main_rearm_ns + SAFETY_MAX_AGE_NS):
|
||||
self.stock_main_rearm_ns = 0
|
||||
self.startup_ready = False
|
||||
floor_pending = self.startup_floor_pending
|
||||
self.startup_floor_pending = False
|
||||
@@ -328,11 +311,8 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
def intent_publication(self, cs, source_ns):
|
||||
allowed, lateral, longitudinal = self.output(cs)
|
||||
armed, deadline = self.allowed_latch, source_ns + 200_000_000
|
||||
pending_arm_ns = self.stock_main_rearm_ns
|
||||
if self.startup_deferred and not self.startup_granted and not self.startup_aborted:
|
||||
pending_arm_ns = self.startup_arm_ns
|
||||
if pending_arm_ns:
|
||||
deadline = min(deadline, pending_arm_ns + 200_000_000)
|
||||
deadline = min(deadline, self.startup_arm_ns + 200_000_000)
|
||||
if source_ns > deadline:
|
||||
allowed = armed = False
|
||||
deadline = source_ns + 200_000_000 # Fresh withdrawal, never a renewed arm.
|
||||
@@ -462,7 +442,7 @@ def intent_disarming_fault(cp, events, state, **context):
|
||||
|
||||
|
||||
def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, producer):
|
||||
"""A fresh MAIN arm may await native steering permission without output."""
|
||||
"""A cold MAIN request may await its first native response, never output."""
|
||||
from openpilot.starpilot.aol.runtime import SAFETY_MAX_AGE_NS, AXIS_MAX_AGE_NS, current_axis
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native, cp_identity
|
||||
from openpilot.cereal import log
|
||||
@@ -470,17 +450,14 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
if not (stock_qualified(cp, marked_only=True) or long_qualified(cp, marked_only=True)):
|
||||
return False
|
||||
axis = current_axis(sm, now_ns=now_ns)
|
||||
stock_rearm = bool(intent.stock_main_rearm_ns and stock_qualified(cp, marked_only=True))
|
||||
arm = intent.stock_main_rearm_ns if stock_rearm else intent.startup_arm_ns
|
||||
arm = intent.startup_arm_ns
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
reverse_event_pending = bool(axis is not None and 0 < event_ns < arm <= axis.sourceCarStateMonoTime and
|
||||
event_ns < axis.faultEventMonoTime <= axis.observedMonoTime and
|
||||
any(event.name == log.OnroadEvent.EventName.reverseGear and event.userDisable for event in sm['onroadEvents']))
|
||||
joined_event = axis is not None and 0 < event_ns == axis.faultEventMonoTime
|
||||
# MAIN can republish the factory cruise-off event before this re-arm gets a native grant.
|
||||
stock_cruise_already_off = bool(stock_qualified(cp, marked_only=True) and not cs.cruiseState.enabled and joined_event and
|
||||
(not intent.stock_main_rearm_cruise_seen if stock_rearm else event_ns < arm))
|
||||
main_off_event_pending = stock_rearm and joined_event and event_ns < arm
|
||||
# Stock cruise may already be off when independent MAIN startup arms.
|
||||
stock_cruise_already_off = bool(stock_qualified(cp, marked_only=True) and not cs.cruiseState.enabled and
|
||||
axis is not None and 0 < event_ns < arm and axis.faultEventMonoTime == event_ns)
|
||||
drive_identity = getattr(intent, 'startup_drive_identity', None)
|
||||
identity = None if drive_identity is None or axis is None or native is None else (
|
||||
cp_identity(cp), str(axis.sessionId), producer, int(axis.intentIntegrityEpoch), native.pandaSerial,
|
||||
@@ -492,7 +469,7 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
0 < arm <= native.observedMonoTime <= arm + SAFETY_MAX_AGE_NS and
|
||||
0 <= now_ns - native.observedMonoTime <= AXIS_MAX_AGE_NS)
|
||||
return bool(intent.settings.enabled and intent.settings.main_action != AOL_TOGGLE and intent.settings.lkas_action != AOL_TOGGLE and
|
||||
intent.allowed_latch and not intent.pause_lateral and (stock_rearm or not feedback.ever_lateral_active) and
|
||||
intent.allowed_latch and not intent.pause_lateral and not feedback.ever_lateral_active and
|
||||
not feedback.failed and not feedback.paused and not feedback.pending_event and not feedback.retention_started_ns and
|
||||
feedback.cp == cp_identity(cp) and
|
||||
0 < arm <= now_ns and (now_ns <= arm + SAFETY_MAX_AGE_NS or granted_in_window) and
|
||||
@@ -521,8 +498,7 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
not any(event.immediateDisable or
|
||||
event.softDisable and not (reverse_event_pending and event.name == log.OnroadEvent.EventName.wrongGear) or
|
||||
event.userDisable and not (reverse_event_pending and event.name == log.OnroadEvent.EventName.reverseGear or
|
||||
stock_cruise_already_off and event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||
main_off_event_pending and event.name == log.OnroadEvent.EventName.wrongCarMode)
|
||||
stock_cruise_already_off and event.name == log.OnroadEvent.EventName.pcmDisable)
|
||||
for event in sm['onroadEvents']))
|
||||
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
|
||||
@@ -7,6 +7,7 @@ from itertools import islice
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
import struct
|
||||
import time
|
||||
@@ -95,22 +96,60 @@ def _button_capable(sysfs: Path) -> bool:
|
||||
any(ABS_HAT0X <= axis <= ABS_HAT3Y for axis in axes)
|
||||
|
||||
|
||||
def _inspect(path: Path) -> _Identity | None:
|
||||
if not EVENT_NAME.fullmatch(path.name):
|
||||
def _external(name: str) -> tuple[Path, re.Match[str]] | None:
|
||||
"""The sysfs device and modalias of a USB or Bluetooth event node."""
|
||||
if not EVENT_NAME.fullmatch(name):
|
||||
return None
|
||||
sysfs = SYS_ROOT / path.name / "device"
|
||||
sysfs = SYS_ROOT / name / "device"
|
||||
match = MODALIAS.match(_text(sysfs / "modalias"))
|
||||
if match is None:
|
||||
if match is None or int(match[1], 16) not in EXTERNAL_BUSES:
|
||||
return None
|
||||
return sysfs, match
|
||||
|
||||
|
||||
def _inspect(path: Path) -> _Identity | None:
|
||||
external = _external(path.name)
|
||||
if external is None or not _button_capable(external[0]):
|
||||
return None
|
||||
sysfs, match = external
|
||||
bus, vendor, product, _version = (int(token, 16) for token in match.groups())
|
||||
if bus not in EXTERNAL_BUSES or not _button_capable(sysfs):
|
||||
return None
|
||||
name = _text(sysfs / "name") or "External input"
|
||||
uniq = _text(sysfs / "uniq")
|
||||
identity = f"{bus:04x}:{vendor:04x}:{product:04x}:{name.casefold()}:{uniq.casefold()}"
|
||||
return _Identity(path, hashlib.sha256(identity.encode()).hexdigest()[:20], name[:80], bus)
|
||||
|
||||
|
||||
def controller_input_report() -> dict:
|
||||
"""Snapshot external input interfaces, including ones omitted from Attached Controllers; names are masked."""
|
||||
devices = []
|
||||
groups: dict[str, list[str]] = {}
|
||||
salt = secrets.token_bytes(8) # equal names match within one report only
|
||||
truncated = False
|
||||
for entry in sorted(SYS_ROOT.iterdir()):
|
||||
if (external := _external(entry.name)) is None:
|
||||
continue
|
||||
if len(devices) == MAX_CANDIDATES:
|
||||
truncated = True
|
||||
break
|
||||
device, match = external
|
||||
identity = _inspect(DEV_ROOT / entry.name)
|
||||
if identity is not None:
|
||||
groups.setdefault(identity.device_id, []).append(entry.name)
|
||||
name = _text(device / "name")
|
||||
devices.append({
|
||||
"event": entry.name, "name": f"masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}" if name else "", "inputId": match[0],
|
||||
"properties": _text(device / "properties"),
|
||||
"capabilities": {key: _text(device / "capabilities" / key) for key in ("ev", "key", "rel", "abs")},
|
||||
"discovery": "eligible" if identity else "filtered",
|
||||
"eventNodePresent": (DEV_ROOT / entry.name).exists(),
|
||||
})
|
||||
duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events}
|
||||
for row in devices:
|
||||
if row["event"] in duplicates:
|
||||
row.update(discovery="duplicate identity", matchingEvents=duplicates[row["event"]])
|
||||
return {"externalInputInterfaces": devices, "truncated": truncated}
|
||||
|
||||
|
||||
def _fresh(seconds: int, microseconds: int, now_ns: int) -> int | None:
|
||||
if seconds < 0 or not 0 <= microseconds < 1_000_000:
|
||||
return None
|
||||
|
||||
@@ -260,3 +260,41 @@ def test_device_and_scan_candidate_caps(kernel):
|
||||
reader.poll(NOW + source.RESCAN_NS)
|
||||
assert reader.devices() == []
|
||||
reader.close()
|
||||
|
||||
|
||||
def test_report_includes_filtered_and_duplicate_external_interfaces(monkeypatch, tmp_path):
|
||||
kernel = Kernel(monkeypatch, tmp_path)
|
||||
kernel.device(1, bus=5)
|
||||
kernel.device(2, bus=5)
|
||||
kernel.device(3, bus=5, keys=(115,), rel=(0, 1))
|
||||
kernel.device(4, bus=5, name="Media", keys=(115,))
|
||||
kernel.device(5, bus=1)
|
||||
report = source.controller_input_report()
|
||||
rows = report["externalInputInterfaces"]
|
||||
assert [row["discovery"] for row in rows] == ["duplicate identity", "duplicate identity", "filtered", "eligible"]
|
||||
assert rows[0]["matchingEvents"] == ["event1", "event2"]
|
||||
assert rows[2]["capabilities"]["rel"] == "3"
|
||||
assert not report["truncated"]
|
||||
assert not kernel.path_by_fd
|
||||
|
||||
|
||||
def test_report_masks_names(monkeypatch, tmp_path):
|
||||
kernel = Kernel(monkeypatch, tmp_path)
|
||||
kernel.device(1, bus=5, name="Danny's Pad")
|
||||
kernel.device(2, bus=5, name="Danny's Pad", uniq="02")
|
||||
kernel.device(3, bus=5, name="Media", keys=(115,))
|
||||
report = source.controller_input_report()
|
||||
names = [row["name"] for row in report["externalInputInterfaces"]]
|
||||
assert all(name.startswith("masked-") for name in names)
|
||||
assert names[0] == names[1] != names[2]
|
||||
assert "Danny" not in str(report) and "Media" not in str(report)
|
||||
assert source.controller_input_report()["externalInputInterfaces"][0]["name"] != names[0]
|
||||
|
||||
|
||||
def test_report_is_capped(monkeypatch, tmp_path):
|
||||
kernel = Kernel(monkeypatch, tmp_path)
|
||||
for index in range(source.MAX_CANDIDATES + 1):
|
||||
kernel.device(index, bus=5, uniq=str(index))
|
||||
report = source.controller_input_report()
|
||||
assert len(report["externalInputInterfaces"]) == source.MAX_CANDIDATES
|
||||
assert report["truncated"]
|
||||
|
||||
@@ -65,12 +65,8 @@ class StatusReport:
|
||||
'verifying_recorded_drive': 'verifying'}.get(value['reason'], 'checking')
|
||||
progress = value.get('analysis_progress', {'phase': phase,
|
||||
'completed': counts.get('original_segments_reviewed'), 'total': counts.get('original_segments_available')})
|
||||
# Later checking callbacks may omit progress, but belong to the same active recording.
|
||||
if phase == 'checking' and 'analysis_progress' not in value:
|
||||
prior_progress = self.current.get('analysis_progress', {})
|
||||
progress.update({key: prior_progress[key] for key in ('recording_position', 'recording_total') if key in prior_progress})
|
||||
self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous),
|
||||
'analysis_progress': progress}, diagnostic_value={**value, 'status': 'fitting'})
|
||||
'analysis_progress': progress}, diagnostic_value=value)
|
||||
|
||||
def restore(self, cache):
|
||||
"""Recover historical display data, never a current tune or permission."""
|
||||
@@ -138,9 +134,6 @@ class StatusReport:
|
||||
if not (type(completed) is int and type(total) is int and 0 <= completed <= total <= 180 and total > 0):
|
||||
completed = total = None
|
||||
details['Parked analysis progress'] = [progress['phase'], completed, total]
|
||||
position, recordings = progress.get('recording_position'), progress.get('recording_total')
|
||||
if type(position) is int and type(recordings) is int and 0 <= position <= recordings <= 8 and recordings > 0:
|
||||
details['Parked recording queue'] = [position, recordings]
|
||||
if value.get('vehicle_identity') == 'unavailable':
|
||||
details['Recorded vehicle identity'] = 'unavailable'
|
||||
if self.diagnostics is not None and self.diagnostics.error:
|
||||
|
||||
@@ -891,26 +891,18 @@ class OffroadWorker:
|
||||
raise ValueError('Logger identity changed during route selection')
|
||||
self.pending_latest = latest
|
||||
checkpoints = {row['input_fingerprint']: row['result'] for row in self.cache.checkpoints()}
|
||||
queue = pending_routes(self.root, latest, on_skip=self._skip_route)
|
||||
fingerprints = []
|
||||
for route in queue:
|
||||
for route in pending_routes(self.root, latest, on_skip=self._skip_route):
|
||||
fingerprint = self._snapshot(route)
|
||||
fingerprints.append(fingerprint)
|
||||
if fingerprint not in checkpoints:
|
||||
position = len(fingerprints)
|
||||
if (fingerprint not in checkpoints or self.evidence_bank is not None and route == latest
|
||||
and not checkpoints[fingerprint].get('route_skipped') and not checkpoints[fingerprint].get('partial_drive')
|
||||
and checkpoints[fingerprint].get('evidence_revision') != self.evidence_bank.revision()):
|
||||
break
|
||||
else:
|
||||
# Finish discovering the backlog before refreshing the newest review with the pooled evidence.
|
||||
fingerprint = fingerprints[0]
|
||||
completed = checkpoints[fingerprint]
|
||||
if (self.evidence_bank is not None and not completed.get('route_skipped') and not completed.get('partial_drive')
|
||||
and completed.get('analysis_counts', {}).get('active_lateral_request_rows') != 0
|
||||
and completed.get('evidence_revision') != self.evidence_bank.revision()):
|
||||
route, position = latest, 0
|
||||
else:
|
||||
result = reported_checkpoint(self.cache, [checkpoints[key] for key in fingerprints])
|
||||
source_is_latest = result['completed_route'] == latest['routeId'] if 'completed_route' in result else result.get('source_is_latest', True)
|
||||
return dict(result, source_is_latest=source_is_latest, skipped_routes=[*result.get('skipped_routes', ()), *self.skipped_routes][:16])
|
||||
result = reported_checkpoint(self.cache, [checkpoints[key] for key in fingerprints])
|
||||
source_is_latest = result['completed_route'] == latest['routeId'] if 'completed_route' in result else result.get('source_is_latest', True)
|
||||
return dict(result, source_is_latest=source_is_latest, skipped_routes=[*result.get('skipped_routes', ()), *self.skipped_routes][:16])
|
||||
self.pending_input = (route, fingerprint)
|
||||
revisions = source_revisions(self.root, route)
|
||||
state = {}
|
||||
@@ -939,16 +931,9 @@ class OffroadWorker:
|
||||
if self.on_analysis is not None:
|
||||
self.on_analysis()
|
||||
options: dict[str, Any] = {} if self.evidence_bank is None else {'evidence_bank': self.evidence_bank, 'history_identity': self._history_identity}
|
||||
def progress(value):
|
||||
if self.on_progress is not None:
|
||||
self.on_progress({**value, 'recording_position': position, 'recording_total': len(queue)})
|
||||
|
||||
if self.assessor is RECORDED_ASSESSOR:
|
||||
# The scheduler owns the backlog. The reader must not substitute an older route inside this attempt.
|
||||
options['selected_route'] = route
|
||||
if self.on_progress is not None:
|
||||
options['on_progress'] = progress
|
||||
elif route != latest:
|
||||
if self.on_progress is not None and self.assessor is RECORDED_ASSESSOR:
|
||||
options['on_progress'] = self.on_progress
|
||||
if route != latest:
|
||||
options['selected_route'] = route
|
||||
try:
|
||||
assessment = self.assessor(self.params, self.root, prior, permitted=self.permitted, **options)
|
||||
@@ -958,7 +943,7 @@ class OffroadWorker:
|
||||
from openpilot.starpilot.flm.offroad_partial import analyze_partial
|
||||
|
||||
try:
|
||||
assessment = analyze_partial(self.root, route['routeId'], prior, permitted=self.permitted, on_progress=options.get('on_progress'))
|
||||
assessment = analyze_partial(self.root, route['routeId'], prior, permitted=self.permitted, on_progress=self.on_progress)
|
||||
except RouteInputError:
|
||||
raise error from None
|
||||
self._skip_route(route['routeId'], error)
|
||||
@@ -1540,8 +1525,6 @@ class OffroadWorker:
|
||||
result['configuration_state'] = configured['state']
|
||||
result['recommendations'] = [r for r in result['recommendations'] if r['target'] is None or r['target'] != configured['values'][r['parameter']]]
|
||||
result['recommendation_count'] = len(result['recommendations'])
|
||||
if not result['recommendation_count'] and result['reason'] == 'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application':
|
||||
result['reason'] = 'no_consistent_adjustment_in_completed_drive'
|
||||
# A new started/changed source cannot be marked processed under its new ID.
|
||||
if not authorized():
|
||||
raise ValueError('Offroad source changed before checkpoint')
|
||||
|
||||
@@ -3,7 +3,6 @@ import bz2
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
import unittest
|
||||
|
||||
from openpilot.cereal import log
|
||||
@@ -103,83 +102,6 @@ class TestAnalysisProgress(unittest.TestCase):
|
||||
report.publish()
|
||||
self.assertNotIn('Parked analysis progress', json.loads(report.path.read_text())['current']['details'])
|
||||
|
||||
def test_real_backlog_reads_each_inactive_recording_once(self):
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.flm import offroad_processor as processor
|
||||
from openpilot.starpilot.flm.offroad_worker import OffroadWorker
|
||||
from openpilot.starpilot.flm.tests.test_offroad_backend import scope
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
routes = [recording(root / 'logs', counter)[0] for counter in (18, 17, 16)]
|
||||
params = Params(str(root / 'params'))
|
||||
params.put('CurrentRoute', routes[0], block=True)
|
||||
params.put('RouteCount', 19, block=True)
|
||||
progress = []
|
||||
worker = OffroadWorker(params, root / 'logs', root / 'cache', permitted=lambda: True,
|
||||
scope_for=lambda *_: scope(), on_progress=progress.append)
|
||||
with patch.object(processor, 'collect_route_inputs', wraps=processor.collect_route_inputs) as read:
|
||||
for name in routes:
|
||||
self.assertEqual(worker.run_once()['completed_route'], name)
|
||||
finished = worker.run_once()
|
||||
self.assertEqual(finished['completed_route'], routes[0])
|
||||
self.assertEqual([call.args[1]['routeId'] for call in read.call_args_list], routes)
|
||||
starts = [row for row in progress if row['phase'] == 'reading' and row['completed'] == 0]
|
||||
self.assertEqual([(row['recording_position'], row['recording_total']) for row in starts], [(1, 3), (2, 3), (3, 3)])
|
||||
self.assertEqual(finished['recommendations'], [])
|
||||
self.assertFalse(finished['configuration_changed'])
|
||||
|
||||
def test_pending_recordings_finish_before_one_cross_drive_refresh(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.flm import offroad_worker as module
|
||||
from openpilot.starpilot.flm.offroad_history import EvidenceBank
|
||||
from openpilot.starpilot.flm.offroad_route import RouteReceipt
|
||||
from openpilot.starpilot.flm.tests.test_offroad_backend import scope
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
routes = [{'routeId': f'{counter:08x}--aaaaaaaaaa'} for counter in (18, 17, 16)]
|
||||
reads = []
|
||||
revision = [0]
|
||||
|
||||
def assess(_, __, previous, *, permitted, selected_route=None, **kwargs):
|
||||
route = routes[0] if selected_route is None else selected_route
|
||||
reads.append(route)
|
||||
if route != routes[0]:
|
||||
revision[0] += 1
|
||||
cp = SimpleNamespace(carFingerprint='declared-queue-car')
|
||||
previous(cp)
|
||||
receipt = RouteReceipt(route['routeId'], 'd' * 64, (), 'a' * 64, 1, 2, 3, ())
|
||||
return module.CompletedAssessment(receipt, (), {'active_lateral_request_rows': 500}, cp, (), route)
|
||||
|
||||
with patch.object(module, 'latest_route', return_value=routes[0]), patch.object(module, 'pending_routes', return_value=routes), \
|
||||
patch.object(module, 'route_inventory', return_value={'scanIncomplete': False, 'routes': routes}):
|
||||
worker = module.OffroadWorker(Params(str(root / 'params')), root / 'logs', root / 'cache', permitted=lambda: True,
|
||||
assessor=assess, scope_for=lambda *_: scope())
|
||||
worker.evidence_bank = EvidenceBank(worker.cache.directory)
|
||||
with patch.object(worker.evidence_bank, 'revision', side_effect=lambda: f'{revision[0]:064x}'):
|
||||
for name in [*routes, routes[0], routes[0]]:
|
||||
self.assertEqual(worker.run_once()['completed_route'], name['routeId'])
|
||||
self.assertEqual(reads, [*routes, routes[0]])
|
||||
|
||||
def test_checking_callback_stays_active_and_retains_recording_queue(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.starpilot.flm.diagnostic_state import _stage
|
||||
|
||||
report = StatusReport(clock_ns=lambda: 10_000_000_000)
|
||||
observed = []
|
||||
report.diagnostics = SimpleNamespace(observe=observed.append)
|
||||
report.analyzing({'reason': 'analyzing_last_completed_drive', 'analysis_progress': {
|
||||
'phase': 'reading', 'completed': 6, 'total': 43, 'recording_position': 2, 'recording_total': 4}})
|
||||
report.analyzing({'reason': 'checking_recorded_steering_recommendations', 'completed_route': 'declared'})
|
||||
self.assertEqual(_stage(observed[-1]), 'checking_recommendations')
|
||||
self.assertEqual(report.current['analysis_progress']['recording_position'], 2)
|
||||
self.assertEqual(report.current['analysis_progress']['recording_total'], 4)
|
||||
report.set({'status': 'collecting', 'reason': 'no_consistent_adjustment_in_completed_drive', 'completed_route': 'declared'})
|
||||
self.assertEqual(_stage(observed[-1]), 'analysis_result')
|
||||
self.assertNotIn('analysis_progress', report.current)
|
||||
|
||||
def test_running_read_waits_for_fresh_device_state_but_never_through_an_onroad_transition(self):
|
||||
from types import SimpleNamespace as NS
|
||||
from openpilot.starpilot.flm.offroad_daemon import wait_for_parked
|
||||
|
||||
@@ -63,7 +63,7 @@ No docs build, sync, or network lookup is required; update this file when a wiki
|
||||
| Maps | Local map status and a parked catalog-region download, progress, or cancellation. A completed selection takes effect at the next map service start. |
|
||||
| Cameras and Sentry | Saved PiP and V-ASM settings and bounded Sentry event metadata. The crop editor uses a browser-local still image; it does not upload that image. |
|
||||
| Sound packs | Catalog status, verified download and cancellation through the local sound owner. |
|
||||
| Galaxy Access & Connections | Remote link pairing, Galaxy installation, Networks, Bluetooth, and support. Local addresses are on Home. |
|
||||
| Galaxy Access & Install | Remote link pairing, Galaxy installation, and an opt-in Wi-Fi hotspot. Local addresses are on Home. |
|
||||
|
||||
`Refresh` and branch changes request filtered
|
||||
history metadata in a separate Git cache and worker. They remain available during
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Send the controller input report to the developer's Discord forum, beside StarPort logs."""
|
||||
|
||||
import json
|
||||
|
||||
from openpilot.starpilot.controllers.input import controller_input_report
|
||||
from openpilot.starpilot.galaxy import starport_send
|
||||
from openpilot.starpilot.system.starport import identity as identity_store
|
||||
|
||||
TITLE = "Bluetooth Log"
|
||||
WEBHOOK_OVERRIDE_PATH = identity_store.DATA_DIR / "bluetooth_webhook_url"
|
||||
# Obfuscation only; device-local configuration overrides this built-in webhook.
|
||||
_WEBHOOK_KEY = b"bluetooth-log"
|
||||
_WEBHOOK_DATA = "".join(("ChgBFQdVQFsMRB8MCBAIWwYbAkAVGERDGAIABBoKHxxARV0aWFdTU11GVU1aVkZcFFhdXk0PFAMMNlgjG1",
|
||||
"RdDiMjOSVURjZaPTxjNStXJB0NExAhDgZZWi0cElEuRTUTHBotWmwqVyE0LkwjWVkoAQ9LVAIeJAFYSA=="))
|
||||
|
||||
|
||||
def webhook_url() -> str:
|
||||
return starport_send.webhook_url(WEBHOOK_OVERRIDE_PATH, _WEBHOOK_KEY, _WEBHOOK_DATA)
|
||||
|
||||
|
||||
def summary() -> dict:
|
||||
from openpilot.starpilot.system.starport.bugsink_transport import device_metadata
|
||||
result = device_metadata()
|
||||
try:
|
||||
result["car_fingerprint"] = starport_send.car_fingerprint()
|
||||
except Exception as error:
|
||||
result["car_fingerprint_error"] = str(error)
|
||||
return result
|
||||
|
||||
|
||||
def report(**_) -> tuple[str, bytes]:
|
||||
return "bluetooth-log.json", json.dumps(controller_input_report(), indent=2).encode()
|
||||
|
||||
|
||||
def send(data: bytes, name: str, note: str, details: dict, *, discord: str, url: str | None = None, post=None, thread_dir=None) -> str | None:
|
||||
return starport_send.send(data, name, note, details, url=webhook_url() if url is None else url, post=post, thread_dir=thread_dir,
|
||||
discord=discord, heading=TITLE, fields=(), content_type="application/json",
|
||||
title=f"{TITLE} {starport_send.thread_title(details)}"[:100])
|
||||
|
||||
|
||||
def sender() -> starport_send.StarPortLogSender:
|
||||
return starport_send.StarPortLogSender(report, sender=send, summary=summary, url=webhook_url,
|
||||
busy="The Bluetooth Log is already being sent.")
|
||||
@@ -1,56 +0,0 @@
|
||||
"""Capture the USB and Bluetooth input inventory without opening any event device."""
|
||||
|
||||
from base64 import b64encode
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
import secrets
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from openpilot.starpilot.controllers import input as controller_input
|
||||
|
||||
|
||||
def controller_input_report():
|
||||
"""Include interfaces filtered out of Attached Controllers and mask device names per report."""
|
||||
devices = []
|
||||
groups = {}
|
||||
salt = secrets.token_bytes(8)
|
||||
truncated = False
|
||||
for entry in sorted(controller_input.SYS_ROOT.iterdir()):
|
||||
if not controller_input.EVENT_NAME.fullmatch(entry.name):
|
||||
continue
|
||||
device = entry / 'device'
|
||||
match = controller_input.MODALIAS.match(controller_input._text(device / 'modalias'))
|
||||
if match is None or int(match[1], 16) not in controller_input.EXTERNAL_BUSES:
|
||||
continue
|
||||
if len(devices) == controller_input.MAX_CANDIDATES:
|
||||
truncated = True
|
||||
break
|
||||
node = controller_input.DEV_ROOT / entry.name
|
||||
identity = controller_input._inspect(node)
|
||||
if identity is not None:
|
||||
groups.setdefault(identity.device_id, []).append(entry.name)
|
||||
name = controller_input._text(device / 'name')
|
||||
devices.append({
|
||||
'event': entry.name,
|
||||
'name': f'masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}' if name else '',
|
||||
'inputId': match[0],
|
||||
'properties': controller_input._text(device / 'properties'),
|
||||
'capabilities': {key: controller_input._text(device / 'capabilities' / key) for key in ('ev', 'key', 'rel', 'abs')},
|
||||
'discovery': 'eligible' if identity else 'filtered',
|
||||
'eventNodePresent': node.exists(),
|
||||
})
|
||||
duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events}
|
||||
for row in devices:
|
||||
if row['event'] in duplicates:
|
||||
row.update(discovery='duplicate identity', matchingEvents=duplicates[row['event']])
|
||||
return {'externalInputInterfaces': devices, 'truncated': truncated}
|
||||
|
||||
|
||||
def controller_capture():
|
||||
report = {'schemaVersion': 1, 'capturedAt': datetime.now(UTC).isoformat(timespec='seconds'), **controller_input_report()}
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('bluetooth-log.json', json.dumps(report, indent=2) + '\n')
|
||||
return {'schemaVersion': 1, 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
@@ -246,7 +246,7 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
|
||||
if cookie is not None:
|
||||
self.send_header('Set-Cookie', cookie)
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
||||
self.end_headers()
|
||||
if self.command != 'HEAD':
|
||||
self.wfile.write(body)
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
"""Actual LAN addresses for direct Galaxy access, independent of the tunnel."""
|
||||
|
||||
from base64 import b64encode
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from io import BytesIO
|
||||
from datetime import UTC, datetime
|
||||
from ipaddress import IPv4Address, ip_network
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
|
||||
LAN = tuple(ip_network(value) for value in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16'))
|
||||
@@ -79,158 +73,3 @@ class LocalAccess:
|
||||
'reason': '' if addresses else reason}
|
||||
self.expiry = self.clock() + 5.0
|
||||
return self.cached
|
||||
|
||||
|
||||
DISCOVERY_UNIT = 'galaxy-lan-discovery.service'
|
||||
DISCOVERY_MESSAGE = re.compile(''.join((
|
||||
r'(Galaxy Wi-Fi discovery available on [0-9]{1,3} local interface\(s\)|',
|
||||
r'Wi-Fi discovery unavailable: [A-Za-z][A-Za-z0-9_]{0,63}|LAN publisher cleanup failed)\Z',
|
||||
)))
|
||||
|
||||
|
||||
BLE_UNIT = 'galaxy-ble-fork.service'
|
||||
BLE_MESSAGE = re.compile(''.join((
|
||||
r'(Pairing credentials changed; [0-9]{1,4} phone\(s\) paired|Phone claimed pairing window|',
|
||||
r'Galaxy BLE handshake challenge requested; active sessions=[0-9]{1,4}|',
|
||||
r'Rejected invalid or unauthenticated BLE message|Notification transfer interrupted \([A-Za-z0-9_]{1,64}\); reconnect to check request outcome|',
|
||||
r'BLE advertisement released by BlueZ; bridge will re-register after restart|Registering Galaxy BLE advertisement|',
|
||||
r'Starting Galaxy bridge pid=[0-9]{1,10} source=[0-9a-f]{12}|',
|
||||
r'Galaxy BLE bridge ready on /org/bluez/hci[0-9]{1,3}; forwarding to localhost:[0-9]{1,5}|',
|
||||
r'Stopping Galaxy bridge; clearing ready status and Bluetooth sessions)\Z',
|
||||
)))
|
||||
INTERFACE_NAME = re.compile(r'[A-Za-z0-9_.:-]{1,32}\Z')
|
||||
|
||||
|
||||
def _network_inventory(run):
|
||||
lines = []
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'address', 'show'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid network inventory')
|
||||
for row in rows[:64]:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = row.get('ifname')
|
||||
if not isinstance(name, str) or not INTERFACE_NAME.fullmatch(name):
|
||||
continue
|
||||
state = row.get('operstate')
|
||||
if state not in ('UNKNOWN', 'NOTPRESENT', 'DOWN', 'LOWERLAYERDOWN', 'TESTING', 'DORMANT', 'UP'):
|
||||
state = 'unknown'
|
||||
flags = row.get('flags', [])
|
||||
if not isinstance(flags, list):
|
||||
flags = []
|
||||
flags = ','.join(flag for flag in ('UP', 'LOWER_UP', 'RUNNING', 'MULTICAST', 'LOOPBACK') if flag in flags)
|
||||
addresses = []
|
||||
info_rows = row.get('addr_info', [])
|
||||
for info in info_rows[:16] if isinstance(info_rows, list) else []:
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
try:
|
||||
address, prefix = IPv4Address(info.get('local')), info.get('prefixlen')
|
||||
except ValueError:
|
||||
continue
|
||||
if any(address in network for network in LAN) and type(prefix) is int and 0 <= prefix <= 32:
|
||||
addresses.append(f'{address}/{prefix}')
|
||||
lines.append(f'{name}: state={state}; flags={flags or "none"}; private IPv4={", ".join(addresses) or "none"}')
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('Network interface inventory unavailable')
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'route', 'show', 'default'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid route inventory')
|
||||
interfaces = [row['dev'] for row in rows[:16] if isinstance(row, dict)
|
||||
and isinstance(row.get('dev'), str) and INTERFACE_NAME.fullmatch(row['dev'])]
|
||||
lines.append('IPv4 default route interfaces: ' + (', '.join(interfaces) or 'none'))
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('IPv4 default route inventory unavailable')
|
||||
try:
|
||||
result = run(['ss', '-H', '-lnt', 'sport = :8082'], capture_output=True, timeout=1, check=True)
|
||||
bindings = set()
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:32]:
|
||||
fields = line.split()
|
||||
if len(fields) < 5 or fields[0] != 'LISTEN' or not fields[3].endswith(':8082'):
|
||||
continue
|
||||
host = fields[3][:-5]
|
||||
if host in ('*', '0.0.0.0', '[::]'):
|
||||
bindings.add('all interfaces')
|
||||
elif host.startswith('127.') or host == '[::1]':
|
||||
bindings.add('loopback')
|
||||
else:
|
||||
bindings.add('specific interface')
|
||||
lines.append('TCP port 8082 listening: ' + (', '.join(sorted(bindings)) or 'no'))
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('TCP port 8082 listener state unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def _service_capture(run, unit, pattern, label):
|
||||
state = 'unavailable'
|
||||
details = []
|
||||
try:
|
||||
result = run(['systemctl', 'show', unit, '--property=ActiveState,SubState,Result,NRestarts,ExecMainStatus'],
|
||||
capture_output=True, timeout=1, check=True)
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:12]:
|
||||
if re.fullmatch(r'(?:ActiveState|SubState|Result)=[a-z][a-z0-9-]{0,39}|(?:NRestarts|ExecMainStatus)=[0-9]{1,10}', line):
|
||||
if line.startswith('ActiveState='):
|
||||
state = line.split('=', 1)[1]
|
||||
else:
|
||||
details.append(line)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
lines = [f'{label}: {state}', *details, 'Recent service events (last 2 hours, up to 120 journal records read)']
|
||||
try:
|
||||
result = run(['journalctl', '--no-pager', '--quiet', '-u', unit, '--since', '-2h',
|
||||
'-n', '120', '-o', 'json', '--output-fields=MESSAGE'],
|
||||
capture_output=True, timeout=2, check=True)
|
||||
events = []
|
||||
for raw in result.stdout.splitlines()[-120:]:
|
||||
if len(raw) > 8192:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
message = entry.get('MESSAGE') if isinstance(entry, dict) else None
|
||||
if isinstance(message, str) and pattern.fullmatch(message):
|
||||
stamp = entry.get('__REALTIME_TIMESTAMP', '')
|
||||
if isinstance(stamp, str) and re.fullmatch(r'[0-9]{1,16}', stamp):
|
||||
timestamp = datetime.fromtimestamp(int(stamp) / 1e6, UTC).isoformat(timespec='seconds')
|
||||
message = f'{timestamp} {message}'
|
||||
events.append(message)
|
||||
except (ValueError, OSError, OverflowError):
|
||||
continue
|
||||
lines.extend(events or ['No matching events'])
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('Advertiser journal unavailable' if unit == DISCOVERY_UNIT else 'BLE journal unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def connection_capture(addresses, *, configuration_allowed=None, run=subprocess.run):
|
||||
lines = ['StarPilot connection capture', 'Capture schema: 2',
|
||||
f'Captured at (UTC): {datetime.now(UTC).isoformat(timespec="seconds")}',
|
||||
'Galaxy endpoint: HTTP port 8082', 'Bonjour service: _sp-galaxy._tcp.local.']
|
||||
try:
|
||||
with open('/proc/uptime') as stream:
|
||||
lines.append(f'Comma uptime: {float(stream.read(128).split()[0]):.0f} seconds')
|
||||
except (OSError, ValueError, IndexError):
|
||||
lines.append('Comma uptime: unavailable')
|
||||
if configuration_allowed is not None:
|
||||
try:
|
||||
lines.append(f'Parked configuration allowed: {bool(configuration_allowed())}')
|
||||
except Exception:
|
||||
lines.append('Parked configuration allowed: unavailable')
|
||||
lines.extend(['', 'Advertisable local addresses'])
|
||||
lines.extend(f'{row["interface"]}: {row["url"]}' for row in addresses['addresses'])
|
||||
if not addresses['available']:
|
||||
lines.append(addresses['reason'] or 'No eligible local address')
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
network = pool.submit(_network_inventory, run)
|
||||
discovery = pool.submit(_service_capture, run, DISCOVERY_UNIT, DISCOVERY_MESSAGE, 'Bonjour advertiser')
|
||||
bluetooth = pool.submit(_service_capture, run, BLE_UNIT, BLE_MESSAGE, 'Bluetooth bridge')
|
||||
lines.extend(['', 'Network interfaces', *network.result(), '', *discovery.result(), '', *bluetooth.result()])
|
||||
report = '\n'.join(lines) + '\n'
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('connection-logs.txt', report)
|
||||
# Keep the original text field for browsers still running the previous page.
|
||||
return {'schemaVersion': 1, 'text': report[:16384], 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
"""Stage diagnostic log archives on the StarPilot log relay for one-click Discord confirmation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from urllib.parse import quote
|
||||
|
||||
from openpilot.starpilot.galaxy.starport_send import DISCORD_FILE_LIMIT, official_install
|
||||
|
||||
STAGE_URL = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/stage"
|
||||
CLAIM_RE = re.compile(r"^https://starpilot-log-relay\.nathan-g-hubbard\.workers\.dev/report/galaxy/claim/[a-f0-9]{64}$")
|
||||
NOTE_LIMIT = 200
|
||||
MODEL_LIMIT = 80
|
||||
KINDS = ("starport", "connection", "controller")
|
||||
PHONES = ("ios", "android")
|
||||
CONTROL = re.compile(r"[\x00-\x1f\x7f]+")
|
||||
|
||||
|
||||
class StageRejected(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class StageBusy(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _clean_text(value: object) -> str:
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
return CONTROL.sub(" ", value).strip()
|
||||
|
||||
|
||||
def clean_stage_request(payload: object) -> tuple[str, str, str]:
|
||||
"""Validate and normalize a staging request; return (kind, platform, formatted_note)."""
|
||||
if not isinstance(payload, dict):
|
||||
raise StageRejected("Invalid log report request.")
|
||||
kind = payload.get("kind")
|
||||
if kind not in KINDS:
|
||||
raise StageRejected("Choose what you are sending logs for.")
|
||||
allowed = {"kind", "note"} | ({"phone"} if kind == "connection" else {"model"} if kind == "controller" else set())
|
||||
if set(payload) - allowed:
|
||||
raise StageRejected("Invalid log report request.")
|
||||
note = payload.get("note")
|
||||
if not isinstance(note, str):
|
||||
raise StageRejected("Add a short note about what happened.")
|
||||
note = _clean_text(note)
|
||||
if not note:
|
||||
raise StageRejected("Add a short note about what happened.")
|
||||
if len(note) > NOTE_LIMIT:
|
||||
raise StageRejected(f"Keep the note to {NOTE_LIMIT} characters.")
|
||||
|
||||
if kind == "connection":
|
||||
phone = payload.get("phone")
|
||||
if phone not in PHONES:
|
||||
raise StageRejected("Choose iPhone or Android.")
|
||||
label = "iPhone" if phone == "ios" else "Android"
|
||||
return kind, phone, f"[{label}] {note}"
|
||||
|
||||
if kind == "controller":
|
||||
raw_model = payload.get("model")
|
||||
if not isinstance(raw_model, str):
|
||||
raise StageRejected("Enter your controller make and model.")
|
||||
model = _clean_text(raw_model)
|
||||
if not model:
|
||||
raise StageRejected("Enter your controller make and model.")
|
||||
if len(model) > MODEL_LIMIT:
|
||||
raise StageRejected(f"Keep the controller model to {MODEL_LIMIT} characters.")
|
||||
return kind, "ios", f"Controller ({model}): {note}"
|
||||
|
||||
return kind, "android", note
|
||||
|
||||
|
||||
def _response_error(response) -> str:
|
||||
try:
|
||||
body = response.json()
|
||||
except (AttributeError, ValueError):
|
||||
return ""
|
||||
if isinstance(body, dict) and isinstance(body.get("error"), str):
|
||||
return body["error"][:240]
|
||||
return ""
|
||||
|
||||
|
||||
class LogRelayStager:
|
||||
"""One diagnostic upload at a time, off the request thread; the page polls status()."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
starport_bundle: Callable[..., tuple[str, bytes]],
|
||||
connection_zip: Callable[[], bytes],
|
||||
controller_zip: Callable[[], bytes],
|
||||
*,
|
||||
post=None,
|
||||
stage_url: Callable[[], str] | str = STAGE_URL,
|
||||
official: Callable[[], bool] = official_install,
|
||||
):
|
||||
self._starport_bundle = starport_bundle
|
||||
self._connection_zip = connection_zip
|
||||
self._controller_zip = controller_zip
|
||||
self._post = post
|
||||
self._stage_url: Callable[[], str] | str = stage_url
|
||||
self._official = official
|
||||
self._lock = threading.Lock()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._state = {"state": "idle", "message": "", "claimUrl": "", "kind": ""}
|
||||
self._session = None
|
||||
self._fork: bool | None = None
|
||||
|
||||
def _url(self) -> str:
|
||||
stage_url = self._stage_url
|
||||
return stage_url if isinstance(stage_url, str) else stage_url()
|
||||
|
||||
def status(self, session=None) -> dict:
|
||||
with self._lock:
|
||||
if self._fork is None:
|
||||
self._fork = not self._official()
|
||||
return {
|
||||
**(self._state if session == self._session else {"state": "idle", "message": "", "claimUrl": "", "kind": ""}),
|
||||
"available": bool(self._url()),
|
||||
"fork": self._fork,
|
||||
"noteLimit": NOTE_LIMIT,
|
||||
"modelLimit": MODEL_LIMIT,
|
||||
}
|
||||
|
||||
def start(self, payload: object, session=None) -> dict:
|
||||
kind, platform, formatted_note = clean_stage_request(payload)
|
||||
if not self._url():
|
||||
raise StageRejected("Online log relay is unavailable. Use Download ZIP instead.")
|
||||
with self._lock:
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
raise StageBusy("Logs are already being prepared.")
|
||||
self._session = session
|
||||
self._state = {"state": "staging", "message": "Collecting logs", "claimUrl": "", "kind": kind}
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
args=(kind, platform, formatted_note),
|
||||
name="galaxy_log_stage",
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
return self.status(session)
|
||||
|
||||
def _set(self, **values) -> None:
|
||||
with self._lock:
|
||||
self._state.update(values)
|
||||
|
||||
def _build_zip(self, kind: str) -> bytes:
|
||||
if kind == "starport":
|
||||
_, data = self._starport_bundle()
|
||||
if len(data) > DISCORD_FILE_LIMIT:
|
||||
_, data = self._starport_bundle(system_snapshot=False)
|
||||
return data
|
||||
if kind == "connection":
|
||||
return self._connection_zip()
|
||||
return self._controller_zip()
|
||||
|
||||
def _run(self, kind: str, platform: str, formatted_note: str) -> None:
|
||||
try:
|
||||
data = self._build_zip(kind)
|
||||
if len(data) > DISCORD_FILE_LIMIT:
|
||||
raise StageRejected("The log archive exceeds the upload limit. Use Download ZIP instead.")
|
||||
self._set(message="Uploading bundle")
|
||||
if self._post is None:
|
||||
import requests
|
||||
post = requests.post
|
||||
else:
|
||||
post = self._post
|
||||
response = post(
|
||||
self._url(),
|
||||
data=data,
|
||||
headers={
|
||||
"Content-Type": "application/zip",
|
||||
"X-Galaxy-Kind": kind,
|
||||
"X-Galaxy-Platform": platform,
|
||||
"X-Galaxy-Note": quote(formatted_note, safe=""),
|
||||
},
|
||||
allow_redirects=False,
|
||||
timeout=(5, 60),
|
||||
)
|
||||
if response.status_code == 404:
|
||||
raise StageRejected("Online log relay is updating. Use Download ZIP instead.")
|
||||
if response.status_code == 413:
|
||||
raise StageRejected("The log archive exceeds the upload limit. Use Download ZIP instead.")
|
||||
if response.status_code != 200:
|
||||
detail = _response_error(response)
|
||||
raise StageRejected(detail or "Could not stage logs for Discord. Use Download ZIP instead.")
|
||||
try:
|
||||
body = response.json()
|
||||
except (AttributeError, ValueError) as error:
|
||||
raise StageRejected("Invalid response from log relay. Use Download ZIP instead.") from error
|
||||
claim_url = body.get("claimUrl") if isinstance(body, dict) else None
|
||||
if not isinstance(claim_url, str) or not CLAIM_RE.fullmatch(claim_url):
|
||||
raise StageRejected("Invalid relay claim link. Use Download ZIP instead.")
|
||||
self._set(state="ready", claimUrl=claim_url, message="Logs uploaded. Your report is not posted until you finish on Discord.")
|
||||
except StageRejected as error:
|
||||
self._set(state="failed", claimUrl="", message=str(error)[:400])
|
||||
except Exception:
|
||||
self._set(state="failed", claimUrl="", message="Your comma could not reach the internet. Use Download ZIP instead.")
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Galaxy settings, device services and software management."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
from contextlib import nullcontext
|
||||
from http.cookies import SimpleCookie
|
||||
@@ -52,7 +51,7 @@ from openpilot.starpilot.ui.layout_preview_transport import (request_profile)
|
||||
from openpilot.starpilot.favorites.owner import FavoritesChanged
|
||||
from openpilot.starpilot.galaxy.favorites import FavoritesGateway
|
||||
from openpilot.starpilot.galaxy.system_monitor import SystemMonitor
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive
|
||||
from openpilot.starpilot.galaxy.vehicle_selection import VehicleSelectionChanged, VehicleSelectionGateway, VehicleSelectionUnverified
|
||||
from openpilot.starpilot.bluetooth.owner import BluetoothOwner, BluetoothRejected, BluetoothUnavailable, normalized_address
|
||||
@@ -100,7 +99,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
sounds=None, software_operations=None, drive_stats=None, layout_preview_socket=None, controllers_socket=None,
|
||||
remote_pairing=None, parked=None, camera_snapshot=None, clock=time.monotonic, starport_setup=None,
|
||||
starport_client=None, navigation=None, offline_maps=None, drive_state=None, cloud_provider=None, cloud_offroad=None, projection_layout=None,
|
||||
local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, log_relay_stager=None, hotspot=None, toyota_tools=None,
|
||||
local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, bluetooth_log_sender=None, hotspot=None, toyota_tools=None,
|
||||
replay_client=None, replay_root=None,
|
||||
spotify_setup=None, companion=None, phone_location=None, reverse_proxy=None, local_hostnames=None, sound_preview=None):
|
||||
from openpilot.starpilot.galaxy.local_hostnames import LocalHostnames
|
||||
@@ -166,24 +165,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
source = starport_logs()
|
||||
starport_log_sender_source = StarPortLogSender(source.bundle, summary=lambda: device_summary(source.directory))
|
||||
return starport_log_sender_source
|
||||
bluetooth_log_sender_source = bluetooth_log_sender
|
||||
bluetooth_log_sender_lock = threading.Lock()
|
||||
|
||||
log_relay_stager_source = log_relay_stager
|
||||
log_relay_stager_lock = threading.Lock()
|
||||
|
||||
def log_stager():
|
||||
nonlocal log_relay_stager_source
|
||||
with log_relay_stager_lock:
|
||||
if log_relay_stager_source is None:
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import LogRelayStager
|
||||
from openpilot.starpilot.galaxy.starport_send import device_summary, with_summary
|
||||
source = starport_logs()
|
||||
log_relay_stager_source = LogRelayStager(
|
||||
with_summary(source.bundle, lambda: device_summary(source.directory)),
|
||||
lambda: base64.b64decode(connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)['zipBase64']),
|
||||
lambda: base64.b64decode(controller_capture()['zipBase64']),
|
||||
)
|
||||
return log_relay_stager_source
|
||||
def bluetooth_log_sender():
|
||||
nonlocal bluetooth_log_sender_source
|
||||
with bluetooth_log_sender_lock:
|
||||
if bluetooth_log_sender_source is None:
|
||||
from openpilot.starpilot.galaxy.bluetooth_send import sender
|
||||
bluetooth_log_sender_source = sender()
|
||||
return bluetooth_log_sender_source
|
||||
software_source = software
|
||||
software_operations_source = software_operations
|
||||
software_lock = threading.Lock()
|
||||
@@ -205,7 +196,6 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
summary_lock = threading.Lock()
|
||||
motion_events = sentry_events if sentry_events is not None else SentryEvents()
|
||||
sentry_events_lock = threading.Lock()
|
||||
simulation_busy = threading.Event()
|
||||
last_simulation = [float("-inf")]
|
||||
notification_owner = notifications
|
||||
snapshots = camera_snapshot if camera_snapshot is not None else CameraSnapshot()
|
||||
@@ -713,11 +703,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return False
|
||||
|
||||
def settings_session(self):
|
||||
return self.current_settings_session(self.session_token(), self.direct_local())
|
||||
|
||||
def current_settings_session(self, token, direct_local):
|
||||
token = self.session_token()
|
||||
with session_lock:
|
||||
if direct_local and sessions.valid(token, local_generation):
|
||||
if self.direct_local() and sessions.valid(token, local_generation):
|
||||
return token, local_generation
|
||||
generation = access.current_generation()
|
||||
if getattr(self.server, 'remote_transport', False):
|
||||
@@ -976,7 +964,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return
|
||||
from openpilot.starpilot.galaxy.pairing_ready import bridge_state, pairing_readiness
|
||||
self.json(200, pairing_readiness(parked=configuration_allowed, snapshot=lambda: bluetooth_owner().snapshot(), bridge=bridge_state))
|
||||
elif path in ('/api/local-access', '/api/local-access/capture', '/api/controllers/log/capture', '/api/tmux/live', '/api/troubleshoot'):
|
||||
elif path in ('/api/local-access', '/api/tmux/live', '/api/troubleshoot'):
|
||||
if not self.require_session():
|
||||
return
|
||||
identity = self.settings_session()
|
||||
@@ -986,11 +974,6 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
try:
|
||||
if path == '/api/local-access':
|
||||
result = address_source.snapshot()
|
||||
elif path == '/api/local-access/capture':
|
||||
result = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
|
||||
elif path == '/api/controllers/log/capture':
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
result = controller_capture()
|
||||
elif path == '/api/tmux/live':
|
||||
result = console_source.snapshot()
|
||||
else:
|
||||
@@ -1037,47 +1020,21 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
# immediately before sending potentially sensitive content.
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
elif path == '/api/logs/stage':
|
||||
if self.require_session():
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
else:
|
||||
self.json(200, log_stager().status(identity))
|
||||
elif path == '/api/starport/logs/send':
|
||||
if self.require_session():
|
||||
self.json(200, starport_log_sender().status())
|
||||
elif path == '/api/starport/logs' or path.startswith('/api/starport/logs/'):
|
||||
elif path == '/api/starport/logs':
|
||||
if not self.require_session():
|
||||
return
|
||||
from openpilot.starpilot.galaxy.starport_logs import LogMissing, LogsUnavailable
|
||||
name = unquote(path.removeprefix('/api/starport/logs/file/')) if path.startswith('/api/starport/logs/file/') else None
|
||||
if name is not None and not re.fullmatch(r'[\w.-]{1,128}', name):
|
||||
self.json(400, {'error': 'Invalid log name'})
|
||||
return
|
||||
if path not in ('/api/starport/logs', '/api/starport/logs/bundle') and name is None:
|
||||
self.json(404, {'error': 'Not found'})
|
||||
return
|
||||
from openpilot.starpilot.galaxy.starport_logs import LogsUnavailable
|
||||
try:
|
||||
if path == '/api/starport/logs':
|
||||
result = starport_logs().list()
|
||||
elif name is None:
|
||||
result = starport_logs().bundle()
|
||||
else:
|
||||
result = starport_logs().file(name)
|
||||
except LogMissing:
|
||||
self.json(404, {'error': 'That log is no longer kept; refresh the list'})
|
||||
result = starport_logs().list()
|
||||
except LogsUnavailable:
|
||||
self.json(503, {'error': 'Android Auto logs are unavailable'})
|
||||
else:
|
||||
# The session can be revoked while logs are read; check again right before sending them.
|
||||
if not self.require_session():
|
||||
return
|
||||
if path == '/api/starport/logs':
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
else:
|
||||
filename, body = result
|
||||
self.attachment(filename, body, 'application/zip' if filename.endswith('.zip') else 'text/plain; charset=utf-8')
|
||||
elif path.startswith('/api/navigation/map/tiles/'):
|
||||
if not self.require_session():
|
||||
return
|
||||
@@ -1267,6 +1224,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(200, {'valid': True})
|
||||
else:
|
||||
self.json(410, {'valid': False})
|
||||
elif path == '/api/controllers/log/send':
|
||||
if self.require_session():
|
||||
self.json(200, bluetooth_log_sender().status())
|
||||
elif path == '/api/controllers/status':
|
||||
if not self.require_session():
|
||||
return
|
||||
@@ -1491,9 +1451,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(400, {'error': 'Choose an event image'})
|
||||
return
|
||||
try:
|
||||
body = notification_owner.test_image(parts[0]) if parts[1] == 'test' else motion_events.image(parts[0], parts[1])
|
||||
if body is None:
|
||||
raise SentryEventsUnavailable
|
||||
body = motion_events.image(parts[0], parts[1])
|
||||
except SentryEventsUnavailable:
|
||||
self.json(404, {'error': 'Event image unavailable'})
|
||||
else:
|
||||
@@ -1779,7 +1737,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', '/api/galaxy/networks',
|
||||
'/api/cameras/snapshot', '/api/cameras/white-balance',
|
||||
'/api/starport/layout', '/api/starport/enable', '/api/starport/control', '/api/starport/pairing',
|
||||
'/api/starport/logs/send', '/api/logs/stage',
|
||||
'/api/starport/logs/send', '/api/controllers/log/send',
|
||||
'/api/starport/pairing/response', '/api/starport/pairing/cancel', '/api/starport/pairing/select',
|
||||
'/api/spotify/enable', '/api/spotify/key', '/api/spotify/preferences', '/api/spotify/control', '/api/spotify/maintenance',
|
||||
'/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots',
|
||||
@@ -1789,14 +1747,13 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
||||
'/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete',
|
||||
'/api/crash-reports/delete',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/events/delete', '/api/crash-reports/delete',
|
||||
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
|
||||
'/api/toyota-tools/action', '/api/vehicle-selection/preview', '/api/vehicle-selection/confirm'):
|
||||
self.json(405, {'error': 'Method unavailable'})
|
||||
return
|
||||
if (path.startswith(('/api/companion/', '/api/replay/', '/api/recordings/', '/api/connect/', '/api/cameras/', '/api/settings/', '/api/maps/',
|
||||
'/api/bluetooth/', '/api/logs/',
|
||||
'/api/bluetooth/',
|
||||
'/api/starport/', '/api/spotify/', '/api/controllers/', '/api/vehicle-selection/', '/api/toyota-tools/',
|
||||
'/api/models/', '/api/ui/', '/api/favorites/', '/api/sounds/', '/api/software/',
|
||||
'/api/drives/', '/api/navigation/', '/api/drive-state/', '/api/sentry/', '/api/crash-reports/')) and
|
||||
@@ -1854,24 +1811,6 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
else:
|
||||
self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/logs/stage':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import StageBusy, StageRejected
|
||||
try:
|
||||
result = log_stager().start(payload, identity)
|
||||
except StageRejected as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except StageBusy as error:
|
||||
self.json(409, {'error': str(error)})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(202, result)
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/settings/flm-finding/accept':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -1984,43 +1923,6 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
return
|
||||
if path == '/api/sentry/notifications/photo-test':
|
||||
if (type(payload) is not dict or set(payload) != {'camera', 'id'} or payload['camera'] not in ('wide', 'cabin') or
|
||||
not isinstance(payload['id'], str) or not re.fullmatch(r'[0-9a-f]{12}', payload['id'])):
|
||||
self.json(400, {'error': 'Choose a phone and camera'})
|
||||
return
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
|
||||
def permitted():
|
||||
readable, _, _ = select.select([self.connection], [], [], 0)
|
||||
if readable and not self.connection.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT):
|
||||
return False
|
||||
return self.settings_session() == identity and parked()
|
||||
|
||||
try:
|
||||
photo = snapshots.capture(payload['camera'], permitted=permitted, parked=True)
|
||||
notification_owner.photo_test(payload['id'], payload['camera'], photo, permitted=permitted)
|
||||
except (SnapshotDenied, PermissionError):
|
||||
if self.require_session():
|
||||
self.json(409, {'error': 'Park the car before sending a photo test'})
|
||||
except SnapshotUnavailable:
|
||||
if self.require_session():
|
||||
self.json(503, {'error': 'No fresh camera frame. Try again shortly.'})
|
||||
except LookupError:
|
||||
self.json(404, {'error': 'Phone subscription not found'})
|
||||
except ValueError as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except (NotificationUnavailable, OSError):
|
||||
self.json(503, {'error': 'Sentry phone push is unavailable. Check Galaxy Sentry settings.'})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(200, {'queued': True})
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/sentry/notifications':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -2034,32 +1936,11 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if not parked():
|
||||
self.json(403, {'error': 'Park the car before simulating an event'})
|
||||
return
|
||||
if simulation_busy.is_set() or clock() - last_simulation[0] < 10:
|
||||
if clock() - last_simulation[0] < 10:
|
||||
self.json(429, {'error': 'Wait ten seconds before simulating another event'})
|
||||
return
|
||||
from openpilot.starpilot.sentry_mode.capture import record_motion_event
|
||||
direct_local = self.direct_local()
|
||||
|
||||
def permitted():
|
||||
return self.current_settings_session(identity[0], direct_local) == identity and parked()
|
||||
|
||||
def capture_simulation():
|
||||
try:
|
||||
record_motion_event(notification_owner.store, snapshots, 'warning', time.monotonic_ns(),
|
||||
permitted, simulated=True)
|
||||
except SnapshotDenied:
|
||||
pass
|
||||
except Exception:
|
||||
cloudlog.exception("Sentry simulation could not record the event")
|
||||
finally:
|
||||
simulation_busy.clear()
|
||||
|
||||
simulation_busy.set()
|
||||
try:
|
||||
threading.Thread(target=capture_simulation, name='sentry-simulation', daemon=True).start()
|
||||
except RuntimeError as error:
|
||||
simulation_busy.clear()
|
||||
raise NotificationUnavailable("Could not start Sentry simulation") from error
|
||||
notification_owner.store.record('warning', time.monotonic_ns(), simulated=True,
|
||||
permitted=lambda: self.settings_session() == identity and parked())
|
||||
last_simulation[0] = clock()
|
||||
result = notification_owner.snapshot()
|
||||
else:
|
||||
@@ -2635,9 +2516,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/starport/logs/send':
|
||||
if type(payload) is not dict or set(payload) not in ({'message'}, {'message', 'discord'}):
|
||||
self.json(400, {'error': 'Invalid StarPort log send request'})
|
||||
if path in ('/api/starport/logs/send', '/api/controllers/log/send'):
|
||||
if type(payload) is not dict or set(payload) != {'message', 'discord'}:
|
||||
self.json(400, {'error': 'Invalid log send request'})
|
||||
return
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -2645,7 +2526,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return
|
||||
from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected
|
||||
try:
|
||||
result = starport_log_sender().start(payload['message'], payload.get('discord', ''))
|
||||
job = starport_log_sender() if path == '/api/starport/logs/send' else bluetooth_log_sender()
|
||||
result = job.start(payload['message'], payload['discord'])
|
||||
except SendRejected as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except SendBusy as error:
|
||||
|
||||
@@ -162,10 +162,10 @@ DESCRIPTIONS = {
|
||||
'EngageVolume': 'Sets the engagement-chime volume.',
|
||||
'DisengageVolume': 'Sets the disengagement-alert volume.',
|
||||
'PromptVolume': 'Sets the volume of general prompts.',
|
||||
'PIPPreviewEnabled': 'Shows the configured Adj Spot Camera preview when fresh camera frames are available.',
|
||||
'PIPPreviewShowOnBlinker': 'Shows the Adj Spot Camera preview while a turn signal is on.',
|
||||
'PIPPreviewShowOnBSM': 'Shows the Adj Spot Camera preview during a blind-spot warning.',
|
||||
'PIPPreviewInvert': 'Mirrors the Adj Spot Camera crop horizontally.',
|
||||
'PIPPreviewEnabled': 'Shows the configured blind-spot camera preview when fresh camera frames are available.',
|
||||
'PIPPreviewShowOnBlinker': 'Shows the blind-spot camera preview while a turn signal is on.',
|
||||
'PIPPreviewShowOnBSM': 'Shows the blind-spot camera preview during a blind-spot warning.',
|
||||
'PIPPreviewInvert': 'Mirrors the blind-spot camera crop horizontally.',
|
||||
'pip:mask:size': 'Sets the size of each camera-image crop shown in the preview.',
|
||||
'pip:mask:editor': 'Edits the source-image crop for the vehicle left and right camera views.',
|
||||
'pip:reset': 'Restores the default source-image camera crops.',
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"""Read-only access to the Android Auto logs under /data/starport/logs, for Logs & Diagnostics.
|
||||
|
||||
Lists the kept session logs with a one-line summary each, and serves one log or the shareable
|
||||
bundle (``compat_report.bundle``: every session with its report, the settings without Bluetooth
|
||||
addresses, and the renderer logs). Only names the log directory itself lists are served.
|
||||
Lists the kept session logs with a one-line summary each, and builds the bundle that is sent to Discord.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,17 +12,10 @@ from pathlib import Path
|
||||
from openpilot.starpilot.system.starport import compat_report
|
||||
from openpilot.starpilot.system.starport import identity as identity_store
|
||||
|
||||
MAX_FILE_BYTES = 8 << 20 # a session log is normally well under 1 MiB; the renderer logs rotate at 256 KiB
|
||||
|
||||
|
||||
class LogsUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class LogMissing(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _car(report: dict) -> str:
|
||||
car = report.get("car") or {}
|
||||
make = car.get("car_make") or car.get("head_unit_make") or ""
|
||||
@@ -60,17 +51,6 @@ class StarPortLogs:
|
||||
raise LogsUnavailable from None
|
||||
return {"schemaVersion": 1, "sessions": sessions, "others": others}
|
||||
|
||||
def file(self, name: str) -> tuple[str, bytes]:
|
||||
path = next((path for path in self._files() if path.name == name), None)
|
||||
if path is None or path.is_symlink():
|
||||
raise LogMissing
|
||||
try:
|
||||
return path.name, compat_report.read_log(path, MAX_FILE_BYTES)
|
||||
except FileNotFoundError:
|
||||
raise LogMissing from None
|
||||
except OSError:
|
||||
raise LogsUnavailable from None
|
||||
|
||||
def bundle(self, now: datetime | None = None, *, system_snapshot: bool = True) -> tuple[str, bytes]:
|
||||
try:
|
||||
data = compat_report.bundle(self.directory, self.config_path, **({} if system_snapshot else {"snapshot": None}))
|
||||
|
||||
@@ -4,12 +4,10 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||
@@ -28,6 +26,7 @@ _WEBHOOK_DATA = "".join(("GwAVAgNVXVtJBRwEHAEQTxEfAl0VXQVAEBYRHA4dGxxdRRhaWlJLRE
|
||||
DISCORD_FILE_LIMIT = 10 * 1024 * 1024 - 64 * 1024 # 10 MiB attachment limit, with room for the form fields
|
||||
THREAD_CACHE_WARNING = "The forum thread could not be remembered on this device. The next upload may create another post."
|
||||
CONTROL = re.compile(r"[\x00-\x1f\x7f]+")
|
||||
STARPORT_FIELDS = (("Head unit", "head_unit"), ("Setup", "setup"), ("Handshake", "handshake"))
|
||||
|
||||
|
||||
class SendRejected(Exception):
|
||||
@@ -43,17 +42,17 @@ def official_install() -> bool:
|
||||
return is_official_repo(device_metadata().get("repo"))
|
||||
|
||||
|
||||
def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH) -> str:
|
||||
def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH, key: bytes = _WEBHOOK_KEY, encoded: str = _WEBHOOK_DATA) -> str:
|
||||
try:
|
||||
override = override_path.read_text().strip()
|
||||
except (OSError, UnicodeError):
|
||||
override = ""
|
||||
if override:
|
||||
return override
|
||||
if not _WEBHOOK_DATA:
|
||||
if not encoded:
|
||||
return ""
|
||||
data = base64.b64decode(_WEBHOOK_DATA)
|
||||
return bytes(byte ^ _WEBHOOK_KEY[index % len(_WEBHOOK_KEY)] for index, byte in enumerate(data)).decode()
|
||||
data = base64.b64decode(encoded)
|
||||
return bytes(byte ^ key[index % len(key)] for index, byte in enumerate(data)).decode()
|
||||
|
||||
|
||||
def clean_message(value) -> str:
|
||||
@@ -68,16 +67,18 @@ def clean_message(value) -> str:
|
||||
|
||||
|
||||
def clean_discord(value) -> str:
|
||||
"""An optional Discord username for a follow-up, without the leading @; "" when none was given."""
|
||||
"""The required Discord username for a follow-up, without the leading @."""
|
||||
if not isinstance(value, str):
|
||||
raise SendRejected("The Discord username must be text.")
|
||||
handle = value.strip().removeprefix("@")
|
||||
if handle and not DISCORD_HANDLE.fullmatch(handle):
|
||||
if not handle:
|
||||
raise SendRejected("Add your Discord username so we can follow up.")
|
||||
if not DISCORD_HANDLE.fullmatch(handle):
|
||||
raise SendRejected("That doesn't look like a Discord username.")
|
||||
return handle
|
||||
|
||||
|
||||
def _car_fingerprint() -> str:
|
||||
def car_fingerprint() -> str:
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
raw, readable = read_saved(Params(), "CarParamsPersistent", 1 << 20)
|
||||
@@ -130,7 +131,7 @@ def _handshake(log_dir: Path | None, logs_to_check: int = 3) -> str:
|
||||
def device_summary(log_dir: Path | None = None) -> dict:
|
||||
from openpilot.starpilot.system.starport.bugsink_transport import device_metadata
|
||||
summary = device_metadata()
|
||||
for key, read in (("car_fingerprint", _car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)),
|
||||
for key, read in (("car_fingerprint", car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)),
|
||||
("handshake", lambda: _handshake(log_dir))):
|
||||
try:
|
||||
summary[key] = read()
|
||||
@@ -139,27 +140,6 @@ def device_summary(log_dir: Path | None = None) -> dict:
|
||||
return summary
|
||||
|
||||
|
||||
def device_lines(summary: dict) -> list[str]:
|
||||
return [f"Car: {summary.get('car_fingerprint') or 'unknown'}",
|
||||
f"Head unit: {summary.get('head_unit') or 'unknown'}",
|
||||
f"Setup: {summary.get('setup') or 'unknown'}",
|
||||
f"Handshake: {summary.get('handshake') or 'unknown'}",
|
||||
f"Repo {summary.get('repo', '?')} · Branch {summary.get('branch', '?')} @ {str(summary.get('commit', '?'))[:10]}"]
|
||||
|
||||
|
||||
def with_summary(bundle: Callable[..., tuple[str, bytes]], summary: Callable[[], dict]) -> Callable[..., tuple[str, bytes]]:
|
||||
"""The bundle with SUMMARY.txt at the root, so relay reports keep the car, head unit, setup and branch."""
|
||||
def build(**kwargs) -> tuple[str, bytes]:
|
||||
name, data = bundle(**kwargs)
|
||||
info = summary()
|
||||
text = "\n".join([f"Device {device_tag(info)}", *device_lines(info)]) + "\n"
|
||||
output = io.BytesIO(data)
|
||||
with zipfile.ZipFile(output, "a", zipfile.ZIP_DEFLATED) as archive:
|
||||
archive.writestr("SUMMARY.txt", text)
|
||||
return name, output.getvalue()
|
||||
return build
|
||||
|
||||
|
||||
def device_tag(summary: dict) -> str:
|
||||
"""8 characters of a hash of the dongle ID: tells devices apart without showing the ID."""
|
||||
dongle_id = summary.get("device_id") or ""
|
||||
@@ -186,21 +166,24 @@ def _save_thread_id(path: Path, key: str, thread_id: str) -> None:
|
||||
|
||||
|
||||
def send(data: bytes, name: str, note: str, summary: dict, url: str | None = None, post=None,
|
||||
thread_dir: Path | None = None, discord: str = "") -> str | None:
|
||||
thread_dir: Path | None = None, *, discord: str, heading: str = "StarPort logs", fields=STARPORT_FIELDS,
|
||||
content_type: str = "application/zip", title: str | None = None) -> str | None:
|
||||
"""Post the zip; return a cache warning after success, or raise SendRejected on an upload failure."""
|
||||
url = webhook_url() if url is None else url
|
||||
if not url:
|
||||
raise SendRejected("Sending isn't set up on this build. Use Download all logs and send the file instead.")
|
||||
raise SendRejected("Sending isn't set up on this build.")
|
||||
if len(data) > DISCORD_FILE_LIMIT:
|
||||
raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit. Use Download all logs instead.")
|
||||
raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit.")
|
||||
if post is None:
|
||||
import requests
|
||||
post = requests.post
|
||||
dongle_id = summary.get("device_id") or "device"
|
||||
lines = [f"**StarPort logs from {device_tag(summary)}**",
|
||||
*device_lines(summary),
|
||||
lines = [f"**{heading} from {device_tag(summary)}**",
|
||||
f"Car: {summary.get('car_fingerprint') or 'unknown'}",
|
||||
*(f"{label}: {summary.get(key) or 'unknown'}" for label, key in fields),
|
||||
f"Repo {summary.get('repo', '?')} · Branch {summary.get('branch', '?')} @ {str(summary.get('commit', '?'))[:10]}",
|
||||
f"Note: {note.strip() or '(none)'}",
|
||||
f"Follow-up: Discord `{discord}`" if discord else "Follow-up: not requested"]
|
||||
f"Follow-up: Discord `{discord}`"]
|
||||
payload = {"content": "\n".join(lines)[:1900], "username": "StarPilot diagnostics", "allowed_mentions": {"parse": []}}
|
||||
|
||||
parts = urlsplit(url)
|
||||
@@ -228,13 +211,13 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non
|
||||
query["thread_id"] = cached_id
|
||||
elif not explicit_thread:
|
||||
query.pop("thread_id", None)
|
||||
payload["thread_name"] = thread_title(summary)
|
||||
payload["thread_name"] = title or thread_title(summary)
|
||||
post_url = urlunsplit(parts._replace(query=urlencode(query)))
|
||||
|
||||
try:
|
||||
response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, "application/zip")}, timeout=120)
|
||||
response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, content_type)}, timeout=120)
|
||||
except Exception as error:
|
||||
raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection, or use Download all logs.") from error
|
||||
raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection.") from error
|
||||
|
||||
# Unknown Channel means the cached thread was deleted (Discord answers 400 for webhooks, 404 elsewhere).
|
||||
# Unknown Webhook does not.
|
||||
@@ -250,7 +233,7 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non
|
||||
if response.status_code not in (200, 204):
|
||||
reason = str(_response_json(response).get("message") or "")[:120]
|
||||
detail = f"HTTP {response.status_code}{f': {reason}' if reason else ''}"
|
||||
raise SendRejected(f"Discord refused the logs ({detail}). Use Download all logs instead.")
|
||||
raise SendRejected(f"Discord refused the logs ({detail}).")
|
||||
|
||||
if not explicit_thread and not cached_id:
|
||||
new_thread_id = _response_json(response).get("channel_id")
|
||||
@@ -268,8 +251,9 @@ class StarPortLogSender:
|
||||
|
||||
def __init__(self, bundle: Callable[..., tuple[str, bytes]], *, sender: Callable[..., str | None] = send,
|
||||
summary: Callable[[], dict] = device_summary, url: Callable[[], str] = webhook_url,
|
||||
official: Callable[[], bool] = official_install):
|
||||
official: Callable[[], bool] = official_install, busy: str = "StarPort logs are already being sent."):
|
||||
self._bundle, self._sender, self._summary, self._url, self._official = bundle, sender, summary, url, official
|
||||
self._busy = busy
|
||||
self._lock = threading.Lock()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._state = {"state": "idle", "message": ""}
|
||||
@@ -281,11 +265,11 @@ class StarPortLogSender:
|
||||
self._fork = not self._official()
|
||||
return {**self._state, "available": bool(self._url()), "fork": self._fork, "messageLimit": MESSAGE_LIMIT}
|
||||
|
||||
def start(self, message, discord="") -> dict:
|
||||
def start(self, message, discord) -> dict:
|
||||
note, handle = clean_message(message), clean_discord(discord)
|
||||
with self._lock:
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
raise SendBusy("StarPort logs are already being sent.")
|
||||
raise SendBusy(self._busy)
|
||||
self._state = {"state": "sending", "message": "Collecting logs"}
|
||||
self._thread = threading.Thread(target=self._run, args=(note, handle), name="starport_log_send", daemon=True)
|
||||
self._thread.start()
|
||||
@@ -310,4 +294,4 @@ class StarPortLogSender:
|
||||
except SendRejected as error:
|
||||
self._set(state="failed", message=str(error)[:400])
|
||||
except Exception as error:
|
||||
self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}. Use Download all logs instead.")
|
||||
self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}.")
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
|
||||
const assert = require('node:assert/strict')
|
||||
|
||||
;(async () => {
|
||||
const browser = await chromium.launch({ headless: true })
|
||||
const page = await browser.newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
const base = process.env.GALAXY_URL || 'http://127.0.0.1:8765/'
|
||||
const CLAIM_URL = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/' + 'a'.repeat(64)
|
||||
const stagedPayloads = []
|
||||
let stageState = { state: 'idle', message: '', claimUrl: '', kind: '', available: true, fork: false, noteLimit: 200, modelLimit: 80 }
|
||||
|
||||
await page.route('**/data/runtime.json', route => route.fulfill({
|
||||
json: { schemaVersion: 1, monitor: 'local' },
|
||||
}))
|
||||
await page.route('**/api/**', async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
if (path === '/api/auth/session') {
|
||||
return route.fulfill({ json: { state: 'configured', authenticated: true, localAccess: true } })
|
||||
}
|
||||
if (path === '/api/device/state') {
|
||||
return route.fulfill({ json: { state: 'parked', maxAgeMs: 3000 } })
|
||||
}
|
||||
if (path === '/api/logs/stage') {
|
||||
if (route.request().method() === 'POST') {
|
||||
const body = route.request().postDataJSON()
|
||||
stagedPayloads.push(body)
|
||||
stageState = {
|
||||
...stageState,
|
||||
state: 'ready',
|
||||
claimUrl: CLAIM_URL,
|
||||
kind: body.kind,
|
||||
message: 'Logs uploaded. Continue to post your report on Discord.',
|
||||
}
|
||||
return route.fulfill({ status: 202, json: stageState })
|
||||
}
|
||||
return route.fulfill({ json: stageState })
|
||||
}
|
||||
if (path === '/api/starport/logs') {
|
||||
return route.fulfill({
|
||||
json: {
|
||||
schemaVersion: 1,
|
||||
sessions: [
|
||||
{
|
||||
name: 'session-000003.jsonl',
|
||||
size: 51712,
|
||||
modifiedAt: 1791354093,
|
||||
outcome: "projected, then failed: finding android auto: Could not find the car's Android Auto service: [Errno 112] Host is down",
|
||||
car: 'Honda T20',
|
||||
transport: 'wireless',
|
||||
trigger: 'car_connected',
|
||||
},
|
||||
],
|
||||
others: [{ name: 'car_ui.log', size: 4096, modifiedAt: 1791354093 }],
|
||||
},
|
||||
})
|
||||
}
|
||||
return route.fulfill({ status: 503, json: { error: 'Device unavailable. Reconnect to read this tool.' } })
|
||||
})
|
||||
|
||||
// 1. Themes x responsive viewports across all log reporting and entry routes
|
||||
const paths = ['/logs', '/logs/help', '/logs/help/connection', '/logs/help/controller', '/logs/starport', '/networks', '/bluetooth']
|
||||
for (const theme of ['dark', 'light']) {
|
||||
for (const width of [320, 390, 1280, 3440]) {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
for (const path of paths) {
|
||||
await page.goto(base + '#' + path)
|
||||
await page.waitForTimeout(150)
|
||||
await page.evaluate(name => { document.documentElement.dataset.theme = name }, theme)
|
||||
await page.waitForTimeout(50)
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
|
||||
false,
|
||||
`${theme} ${width}px ${path}: no horizontal overflow`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. #/logs catalog: Get help present, duplicate StarPort Logs tile removed
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/logs')
|
||||
await page.locator('.gx-menu-tile').first().waitFor()
|
||||
const tileTitles = await page.locator('.gx-menu-tile').evaluateAll(tiles => tiles.map(t => t.textContent))
|
||||
assert.ok(tileTitles.some(text => text.includes('Get help')), '#/logs includes Get help tile')
|
||||
assert.ok(!tileTitles.some(text => text.includes('StarPort Logs')), '#/logs has no separate StarPort Logs tile')
|
||||
|
||||
// 3. #/networks and #/bluetooth Connection logs panel -> #/logs/help/connection
|
||||
for (const routePath of ['#/networks', '#/bluetooth']) {
|
||||
await page.goto(base + routePath)
|
||||
const sendBtn = page.locator('.gx-connection-logs').getByRole('button', { name: 'Send logs', exact: true })
|
||||
await sendBtn.waitFor()
|
||||
const box = await sendBtn.boundingBox()
|
||||
assert.ok(box.height >= 44, `${routePath} Send logs meets 44px touch target (${box.height}px)`)
|
||||
await sendBtn.click()
|
||||
await page.waitForFunction(() => location.hash === '#/logs/help/connection')
|
||||
}
|
||||
|
||||
// 4. Desktop centering, 3 tabs, touch targets, Discord footer, and StarPort session disclosure
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await page.goto(base + '#/logs/help')
|
||||
await page.locator('.gx-log-help__tab').first().waitFor()
|
||||
await page.waitForFunction(() => !document.querySelector('.gx-route-enter-active, .gx-route-leave-active'))
|
||||
const desktop = await page.locator('.gx-log-help').evaluate(section => {
|
||||
const bounds = section.getBoundingClientRect()
|
||||
const content = section.closest('.gx-content').getBoundingClientRect()
|
||||
return { width: bounds.width, center: bounds.left + bounds.width / 2, contentCenter: content.left + content.width / 2 }
|
||||
})
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'LogHelp is centered and bounded <=960px on desktop')
|
||||
|
||||
const tabTitles = await page.locator('.gx-log-help__tab strong').allTextContents()
|
||||
assert.deepEqual(tabTitles, ['StarPort / Car Screen', 'Phone App', 'Controller'])
|
||||
const discordHref = await page.locator('.gx-log-help__discord a').getAttribute('href')
|
||||
assert.equal(discordHref, 'https://firestar.link/discord')
|
||||
|
||||
// Touch targets >= 44px on StarPort tab + disclosure
|
||||
const starportTargets = await page.locator('.gx-log-help__tab, .gx-log-help__card button, .gx-log-help__card a.gx-btn, .gx-log-help__sessions > summary, .gx-log-help__discord a').evaluateAll(
|
||||
nodes => nodes.filter(n => n.offsetParent !== null).map(n => ({ text: n.textContent.trim(), height: n.getBoundingClientRect().height })),
|
||||
)
|
||||
assert.ok(starportTargets.every(item => item.height >= 43.5), `StarPort touch targets >=44px: ${JSON.stringify(starportTargets)}`)
|
||||
|
||||
await page.locator('.gx-log-help__sessions > summary').click()
|
||||
await page.locator('.gx-starport-log').first().waitFor()
|
||||
const dlBoxes = await page.locator('.gx-starport-log__download').evaluateAll(links => links.map(l => {
|
||||
const r = l.getBoundingClientRect()
|
||||
return { width: r.width, height: r.height, dl: l.getAttribute('download') }
|
||||
}))
|
||||
assert.ok(dlBoxes.every(b => b.width === 44 && b.height === 44), 'Session download links are 44x44px')
|
||||
assert.deepEqual(dlBoxes.map(b => b.dl), ['session-000003.jsonl', 'car_ui.log'])
|
||||
|
||||
// 5. Switch to Phone App on 390px, check chip targets, submit, claimUrl card, and reset
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.getByRole('tab', { name: /Phone App/ }).click()
|
||||
const androidChip = page.locator('.gx-log-help__pills').getByRole('button', { name: 'Android', exact: true })
|
||||
await androidChip.waitFor()
|
||||
const chipHeights = await page.locator('.gx-log-help__pills button.gx-chip').evaluateAll(btns => btns.map(b => b.getBoundingClientRect().height))
|
||||
assert.ok(chipHeights.every(h => h >= 43.5), `Phone chips meet 44px touch target (${chipHeights})`)
|
||||
await androidChip.click()
|
||||
await page.locator('#gx-log-help-note').fill('App keeps spinning on Wi-Fi')
|
||||
|
||||
// Block window.open popup side effect in headless run while still verifying claimUrl link renders
|
||||
await page.evaluate(() => { window.open = () => null })
|
||||
await page.getByRole('button', { name: 'Send phone app logs', exact: true }).click()
|
||||
const claimLink = page.locator('.gx-log-help__ready').getByRole('link', { name: /Continue on Discord support/ })
|
||||
await claimLink.waitFor()
|
||||
assert.equal(await claimLink.getAttribute('href'), CLAIM_URL)
|
||||
assert.deepEqual(stagedPayloads, [{ kind: 'connection', note: 'App keeps spinning on Wi-Fi', phone: 'android' }])
|
||||
|
||||
await page.getByRole('button', { name: 'Send another report', exact: true }).click()
|
||||
await page.locator('#gx-log-help-note').waitFor()
|
||||
assert.equal(await page.locator('.gx-log-help__ready').count(), 0)
|
||||
|
||||
assert.deepEqual(errors, [], 'LogHelp browser checks completed without runtime page errors')
|
||||
console.log('Passed LogHelp browser flow, responsiveness, touch targets, themes, and staging checks.')
|
||||
await browser.close()
|
||||
})().catch(error => { console.error(error); process.exit(1) })
|
||||
@@ -137,7 +137,7 @@ const layout = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c',
|
||||
await page.evaluate(()=>location.hash='/tools')
|
||||
await page.getByRole('heading',{name:'Tools',exact:true}).waitFor()
|
||||
const sidebar=page.locator('.gx-nav-section').filter({has:page.locator('.gx-nav-section__title',{hasText:/^Tools$/})})
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Connections'))
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Install'))
|
||||
assert.deepEqual(errors,[])
|
||||
console.log('Browser checks passed: VASM frame/default/reactive updates, PiP crop frame, widget registry, recordings and phone layout. Captures:',draws)
|
||||
await browser.close()
|
||||
|
||||
@@ -24,9 +24,6 @@ const { resolve } = require('node:path')
|
||||
json: { state: 'configured', authenticated: true, localAccess: true },
|
||||
})
|
||||
if (path === '/api/device/state') return route.fulfill({ json: { state: 'parked', maxAgeMs: 3000 } })
|
||||
if (path === '/api/logs/stage') return route.fulfill({
|
||||
json: { state: 'idle', message: '', claimUrl: '', kind: '', available: true, fork: false, noteLimit: 200, modelLimit: 80 },
|
||||
})
|
||||
if (path === '/api/starport/logs') return route.fulfill({ json: { schemaVersion: 1,
|
||||
sessions: [
|
||||
{ name: 'session-000003.jsonl', size: 51712, modifiedAt: 1791354093, outcome: "projected, then failed: finding android auto: Could not find the car's Android Auto service: [Errno 112] Host is down", car: 'Honda T20', transport: 'wireless', trigger: 'car_connected' },
|
||||
@@ -47,7 +44,6 @@ const { resolve } = require('node:path')
|
||||
|
||||
const paths = [...new Set(['/', '/tools', '/settings', '/developer/connect', '/cameras/events',
|
||||
'/cameras/sentry-settings', '/cameras/pip', '/cameras/vasm', '/theme_maker/starport',
|
||||
'/logs/help', '/logs/help/connection', '/logs/help/controller',
|
||||
'/logs/crashes', '/logs/starport', '/logs/monitor', '/logs/troubleshoot', '/logs/tmux', '/tuning/plots', '/tuning/flm',
|
||||
'/driving/longitudinal-curves', '/appearance', '/driving/conditional', '/driving/curve', '/driving/slc', '/driving/profiles', '/driving/traffic',
|
||||
...groups.filter(([page]) => page !== "standard").map(([page]) => '/driving/' + page), ...catalog.tools.map(tool => tool.path)])]
|
||||
@@ -85,33 +81,23 @@ const { resolve } = require('node:path')
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/logs/starport')
|
||||
await page.locator('.gx-log-help__sessions > summary').waitFor()
|
||||
await page.locator('.gx-log-help__sessions > summary').click()
|
||||
await page.locator('.gx-starport-log').first().waitFor()
|
||||
await page.waitForFunction(() => !document.querySelector('.gx-route-enter-active, .gx-route-leave-active'))
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, 'Android Auto logs fit a phone viewport')
|
||||
const phoneCards = await page.locator('.gx-starport-log').evaluateAll(cards => cards.map(card => {
|
||||
const row = card.getBoundingClientRect(), body = card.querySelector('.gx-starport-log__body').getBoundingClientRect()
|
||||
const download = card.querySelector('.gx-starport-log__download').getBoundingClientRect()
|
||||
return { leftInset: body.left - row.left, rightInset: row.right - download.right, width: download.width, height: download.height }
|
||||
return { leftInset: body.left - row.left }
|
||||
}))
|
||||
assert.ok(phoneCards.every(card => card.leftInset >= 11 && card.rightInset >= 11), 'log text and downloads are padded inside cards')
|
||||
assert.ok(phoneCards.every(card => card.width === 44 && card.height === 44), 'individual downloads remain compact touch targets')
|
||||
assert.deepEqual(await page.locator('.gx-starport-log__download').evaluateAll(links => links.map(link => link.getAttribute('download'))),
|
||||
['session-000003.jsonl', 'session-000002.jsonl', 'car_ui.log'])
|
||||
for (const label of ['Phone App', 'Controller']) {
|
||||
await page.getByRole('tab', { name: new RegExp(label) }).click()
|
||||
await page.waitForTimeout(50)
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `${label}: no phone overflow`)
|
||||
}
|
||||
assert.ok(phoneCards.every(card => card.leftInset >= 11), 'log text is padded inside cards')
|
||||
assert.equal(await page.locator('.gx-starport-logs a[download]').count(), 0, 'StarPort logs are sent, not downloaded')
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
|
||||
const desktop = await page.locator('.gx-log-help').evaluate(section => {
|
||||
const desktop = await page.locator('.gx-starport-logs').evaluate(section => {
|
||||
const bounds = section.getBoundingClientRect()
|
||||
const content = section.closest('.gx-content').getBoundingClientRect()
|
||||
return { width: bounds.width, center: bounds.left + bounds.width / 2, contentCenter: content.left + content.width / 2 }
|
||||
})
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'Log help is centered and readable on desktop')
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'StarPort logs are centered and readable on desktop')
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/settings')
|
||||
const manage = page.getByRole('button', { name: 'Manage', exact: true }).first()
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Fake Discord webhook responses shared by the log send tests."""
|
||||
|
||||
import json
|
||||
|
||||
URL = "https://discord.example/api/webhooks/1/token"
|
||||
SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio",
|
||||
"branch": "Dom", "commit": "abcdef1234567890"}
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status_code=200, body=None):
|
||||
self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"}
|
||||
|
||||
def json(self):
|
||||
return self.body
|
||||
|
||||
|
||||
class Poster:
|
||||
def __init__(self, *responses):
|
||||
self.responses, self.calls = list(responses), []
|
||||
|
||||
def __call__(self, url, data, files, timeout):
|
||||
self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files})
|
||||
return self.responses.pop(0)
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from "node:assert/strict"
|
||||
import { BluetoothFeed, BluetoothPage, validBluetoothStatus, validPairInput } from "../web/js/bluetooth.js"
|
||||
|
||||
@@ -112,6 +111,3 @@ assert.equal(validBluetoothStatus({ ...status, pairing: { address: "not-an-addre
|
||||
assert.equal(validBluetoothStatus({ ...status, adapterName: 5 }), false)
|
||||
assert.match(BluetoothPage.template, /Pair phone/)
|
||||
assert.match(BluetoothPage.template, /action\('accept_pair'\)/)
|
||||
|
||||
assert.equal(BluetoothPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(BluetoothPage.template.includes("<ConnectionLogs v-if=\"mode === 'local' && !unidenSettings\" panel"))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createRenderer, nextTick } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { BluetoothNotice, bluetoothConnection } from '../web/js/bluetooth-notice.js'
|
||||
import { BluetoothPage } from '../web/js/bluetooth.js'
|
||||
import { LocalHistoryFeed, LocalRecordingsPage } from '../web/js/record-history.js'
|
||||
import { CamerasPage, CameraSnapshotFeed, LiveCameraPreview } from '../web/js/cameras.js'
|
||||
import { PipPage } from '../web/js/pip.js'
|
||||
@@ -109,19 +108,11 @@ assert.equal(requests, 0)
|
||||
|
||||
window.StarPilotApp.bluetooth = () => false
|
||||
assert.equal(bluetoothConnection(), false)
|
||||
const detector = { address: 'AA:BB:CC:DD:EE:FF', name: 'Uniden R8', paired: true, connected: true, trusted: true }
|
||||
for (const [mode, unidenSettings] of [['local', false], ['local', true], ['preview', false], ['preview', true]]) {
|
||||
const view = mount(BluetoothPage, { mode, unidenSettings }, {
|
||||
...presentation,
|
||||
data: () => ({ ...BluetoothPage.data(), status: { powered: true, available: true, parked: true, devices: [detector] } }),
|
||||
components: { ...BluetoothPage.components, UnidenPanel: { props: ['devices'], template: '<p>Detector controls for {{ devices[0].name }}</p>' } },
|
||||
})
|
||||
try {
|
||||
const rendered = text(view.host)
|
||||
assert.equal(rendered.includes('Saved devices'), mode === 'local' && !unidenSettings)
|
||||
assert.equal(rendered.includes('Detector controls for Uniden R8'), mode === 'local' && unidenSettings)
|
||||
assert.equal(rendered.includes('No radio was checked in preview.'), mode !== 'local')
|
||||
} finally { view.unmount() }
|
||||
{
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const lines = readFileSync(new URL('../web/js/bluetooth.js', import.meta.url), 'utf8').split('\n')
|
||||
const chained = lines.findIndex((line) => line.trim() === '<template v-else-if="status">')
|
||||
assert.ok(chained > 0)
|
||||
assert.doesNotMatch(lines[chained - 1], /v-if="status"/, 'a notice before the device cards would swallow their v-else-if')
|
||||
}
|
||||
assert.equal(requests, 0)
|
||||
console.log('Bluetooth limits: blue notices, connection action, no blocked requests, supported settings and real errors verified')
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Bluetooth Log: the controller report sent to the developer's Discord forum and its routes."""
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from openpilot.starpilot.galaxy import bluetooth_send
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected
|
||||
from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response
|
||||
|
||||
|
||||
class BluetoothSendTest(unittest.TestCase):
|
||||
def test_posts_the_report_as_a_bluetooth_log_thread(self):
|
||||
post = Poster(Response(body={"channel_id": "777"}))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
self.assertIsNone(bluetooth_send.send(b"{}", "bluetooth-log.json", "Pad not found", SUMMARY, url=URL, post=post,
|
||||
thread_dir=Path(directory), discord="starfan_42"))
|
||||
call = post.calls[0]
|
||||
content = call["payload"]["content"]
|
||||
self.assertTrue(content.startswith("**Bluetooth Log from "))
|
||||
self.assertIn("Car: HONDA_CIVIC_2022", content)
|
||||
self.assertIn("Follow-up: Discord `starfan_42`", content)
|
||||
self.assertNotIn("Head unit", content)
|
||||
self.assertTrue(call["payload"]["thread_name"].startswith("Bluetooth Log HONDA_CIVIC_2022 "))
|
||||
self.assertEqual(call["files"]["files[0]"], ("bluetooth-log.json", b"{}", "application/json"))
|
||||
|
||||
def test_report_is_json(self):
|
||||
with mock.patch.object(bluetooth_send, "controller_input_report", return_value={"externalInputInterfaces": []}):
|
||||
name, data = bluetooth_send.report(system_snapshot=False)
|
||||
self.assertEqual((name, json.loads(data)), ("bluetooth-log.json", {"externalInputInterfaces": []}))
|
||||
|
||||
def test_unset_webhook_refuses_and_override_wins(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
override = Path(directory) / "bluetooth_webhook_url"
|
||||
with mock.patch.object(bluetooth_send, "WEBHOOK_OVERRIDE_PATH", override), mock.patch.object(bluetooth_send, "_WEBHOOK_DATA", ""):
|
||||
self.assertEqual(bluetooth_send.webhook_url(), "")
|
||||
with self.assertRaisesRegex(SendRejected, "isn't set up"):
|
||||
bluetooth_send.send(b"{}", "bluetooth-log.json", "hi", SUMMARY, post=Poster(), discord="starfan_42")
|
||||
override.write_text(URL + "\n")
|
||||
self.assertEqual(bluetooth_send.webhook_url(), URL)
|
||||
|
||||
|
||||
class BluetoothSendHTTPTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.owner = GalaxyAccessOwner(Path(temporary.name) / "access")
|
||||
self.job = mock.Mock()
|
||||
self.job.status.return_value = {"state": "idle", "message": "", "available": True, "messageLimit": 60}
|
||||
self.job.start.return_value = {"state": "sending", "message": "Collecting logs", "available": True, "messageLimit": 60}
|
||||
self.starport = mock.Mock()
|
||||
self.server = make_server(port=0, owner=self.owner, bluetooth_log_sender=self.job, starport_log_sender=self.starport)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
|
||||
self.thread.start()
|
||||
self.addCleanup(self.close_server)
|
||||
self.assertTrue(self.owner.configure("password123", lambda: True))
|
||||
|
||||
def close_server(self):
|
||||
self.server.shutdown()
|
||||
self.thread.join(timeout=2)
|
||||
self.server.server_close()
|
||||
|
||||
def request(self, path, *, method="GET", body=None, headers=None):
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2)
|
||||
try:
|
||||
origin = {"Origin": f"http://127.0.0.1:{self.server.server_port}"} if method == "POST" else {}
|
||||
connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **origin, **(headers or {})})
|
||||
response = connection.getresponse()
|
||||
return response.status, response.read(), dict(response.getheaders())
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def post(self, body, cookie=None):
|
||||
headers = {"Content-Type": "application/json", **({"Cookie": cookie} if cookie else {})}
|
||||
return self.request("/api/controllers/log/send", method="POST", body=json.dumps(body), headers=headers)
|
||||
|
||||
def login(self):
|
||||
status, _, headers = self.request("/api/auth/login", method="POST", body=json.dumps({"password": "password123"}),
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(status, 200)
|
||||
return headers["Set-Cookie"].split(";", 1)[0]
|
||||
|
||||
def test_requires_a_session(self):
|
||||
self.assertEqual(self.request("/api/controllers/log/send")[0], 401)
|
||||
self.assertEqual(self.post({"message": "hi"})[0], 401)
|
||||
self.job.start.assert_not_called()
|
||||
|
||||
def test_status_start_and_rejections(self):
|
||||
cookie = self.login()
|
||||
status, body, _ = self.request("/api/controllers/log/send", headers={"Cookie": cookie})
|
||||
self.assertEqual((status, json.loads(body)["state"]), (200, "idle"))
|
||||
status, body, _ = self.post({"message": "Pad not found", "discord": "starfan_42"}, cookie)
|
||||
self.assertEqual((status, json.loads(body)["state"]), (202, "sending"))
|
||||
self.job.start.assert_called_once_with("Pad not found", "starfan_42")
|
||||
self.starport.start.assert_not_called()
|
||||
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400)
|
||||
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400)
|
||||
self.job.start.side_effect = SendRejected("Keep the message to 60 characters.")
|
||||
self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400)
|
||||
self.job.start.side_effect = SendBusy("The Bluetooth Log is already being sent.")
|
||||
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,3 +1,4 @@
|
||||
from unittest.mock import Mock
|
||||
"""Authenticated diagnostics over the same local and remote HTTP handler."""
|
||||
|
||||
import http.client
|
||||
@@ -5,13 +6,10 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import LogRelayStager
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.settings import AuthorityContext, SettingsGateway
|
||||
|
||||
@@ -27,25 +25,12 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.console = SimpleNamespace(snapshot=lambda: self.record('console', {'available': True, 'text': 'actual console',
|
||||
'truncated': False, 'pane': 'comma:0.0', 'reason': ''}))
|
||||
self.settings = SimpleNamespace(diagnostics=lambda: self.record('settings', {'schemaVersion': 1, 'sections': []}))
|
||||
self.stage_posts = []
|
||||
self.stage_response = None
|
||||
self.stager = LogRelayStager(
|
||||
lambda **_kw: ('starport-logs.zip', b'PK\x03\x04' + b'0' * 32),
|
||||
lambda: b'PK\x03\x04' + b'1' * 32,
|
||||
lambda: b'PK\x03\x04' + b'2' * 32,
|
||||
post=self._stage_post,
|
||||
official=lambda: True,
|
||||
)
|
||||
self.server = make_server(port=0, owner=self.access, parked=lambda: True, local_access=self.addresses,
|
||||
tmux_live=self.console, settings=self.settings, log_relay_stager=self.stager)
|
||||
tmux_live=self.console, settings=self.settings)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
self.thread.start()
|
||||
self.cookie = ''
|
||||
|
||||
def _stage_post(self, url, **kwargs):
|
||||
self.stage_posts.append((url, kwargs))
|
||||
return self.stage_response
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.thread.join(2)
|
||||
@@ -72,15 +57,12 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
connection.close()
|
||||
|
||||
def test_real_http_routes_authentication_and_no_mutations(self):
|
||||
for path in ('/api/local-access', '/api/local-access/capture', '/api/tmux/live', '/api/troubleshoot', '/api/logs/stage'):
|
||||
for path in ('/api/local-access', '/api/tmux/live', '/api/troubleshoot'):
|
||||
self.assertEqual(self.request(path, remote=True)[0], 401)
|
||||
self.assertEqual(self.calls, [])
|
||||
status, _, self.cookie = self.request('/api/auth/session')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(self.request('/api/local-access')[1]['addresses'][0]['url'], 'http://192.168.4.2:8082/')
|
||||
status, capture, _ = self.request('/api/local-access/capture')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn('http://192.168.4.2:8082/', capture['text'])
|
||||
self.assertEqual(self.request('/api/tmux/live')[1]['text'], 'actual console')
|
||||
self.assertEqual(self.request('/api/troubleshoot')[1]['sections'], [])
|
||||
before = len(self.calls)
|
||||
@@ -88,36 +70,6 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.assertNotEqual(self.request('/api/tmux/live', method='POST', payload={})[0], 200)
|
||||
self.assertEqual(len(self.calls), before)
|
||||
|
||||
def test_log_stage_routes_require_session_and_stage_bundle(self):
|
||||
self.assertEqual(self.request('/api/logs/stage', method='POST', payload={'kind': 'starport', 'note': 'Blank'}, remote=True)[0], 401)
|
||||
_, _, self.cookie = self.request('/api/auth/session')
|
||||
claim_url = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/' + ('a' * 64)
|
||||
self.stage_response = Mock(status_code=200)
|
||||
self.stage_response.json.return_value = {'claimUrl': claim_url}
|
||||
status, idle, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(idle['state'], 'idle')
|
||||
self.assertTrue(idle['available'])
|
||||
|
||||
status, accepted, _ = self.request('/api/logs/stage', method='POST',
|
||||
payload={'kind': 'connection', 'phone': 'ios', 'note': 'Lost network'})
|
||||
self.assertEqual(status, 202)
|
||||
self.assertEqual(accepted['kind'], 'connection')
|
||||
|
||||
deadline = time.monotonic() + 2
|
||||
state = accepted
|
||||
while state['state'] == 'staging' and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
_, state, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(state['state'], 'ready')
|
||||
self.assertEqual(state['claimUrl'], claim_url)
|
||||
self.assertEqual(len(self.stage_posts), 1)
|
||||
_, kwargs = self.stage_posts[0]
|
||||
self.assertFalse(kwargs['allow_redirects'])
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Kind'], 'connection')
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Platform'], 'ios')
|
||||
self.assertIn('Lost%20network', kwargs['headers']['X-Galaxy-Note'])
|
||||
|
||||
def test_authenticated_forwarded_transport_uses_same_tools(self):
|
||||
status, _, self.cookie = self.request('/api/auth/login', method='POST', payload={'password': 'test-password-123'}, remote=True)
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
@@ -53,5 +53,5 @@ scrolls.length = 0
|
||||
delayedAlign()
|
||||
assert.deepEqual(scrolls, [], "a delayed alignment leaves the Widgets scroll position alone")
|
||||
|
||||
assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="state\.inspectorPanel === 'lead' \? revealEditPanel\(\) : openEditPanel\(\)"><span>Edit/)
|
||||
assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="openEditPanel\(\)"><span>Edit/)
|
||||
globalThis.setTimeout = realTimeout
|
||||
|
||||
@@ -275,7 +275,7 @@ assert(measuredText.includes('Recorded baseline') && measuredText.includes(measu
|
||||
assert.match(measuredText, /0\s+saved/)
|
||||
assert(measuredText.includes('No pending trial reported'))
|
||||
assert(!measuredText.includes('Awaiting next-drive measurement'), 'Recorded analysis without a saved trial must not invent a pending trial')
|
||||
assert(measuredText.includes('without interpolation or delay alignment'))
|
||||
assert(measuredText.includes('No interpolation or delay alignment'))
|
||||
assert(measuredText.includes('22 / 24 original controller and encoder windows passed'))
|
||||
assert(measuredText.includes('candidate triggered an encoder limiter'))
|
||||
ctx.report.current.details['Controller and encoder check windows']=[35,35]
|
||||
|
||||
@@ -251,15 +251,6 @@ for (const [phase, percent, detail] of [
|
||||
assert.equal(parkedAnalysisProgress(scan).percent, percent)
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, detail)
|
||||
}
|
||||
scan.current.details['Parked analysis progress'] = ['reading', 6, 43]
|
||||
scan.current.details['Parked recording queue'] = [2, 4]
|
||||
assert(validTrainingResults(scan))
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, 'Recording 2 of 4. 6 of 43 sections read in this recording')
|
||||
scan.current.details['Parked recording queue'] = [0, 4]
|
||||
assert.match(parkedAnalysisProgress(scan).detail, /^Rechecking with evidence from other drives/)
|
||||
scan.current.details['Parked recording queue'] = [8, 4]
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, '6 of 43 sections read in this recording')
|
||||
delete scan.current.details['Parked recording queue']
|
||||
scan.current.details['Parked analysis progress'] = ['reading', 3, 3]
|
||||
assert.equal(parkedAnalysisProgress(scan).percent, null)
|
||||
scan.current.reason = 'verifying_recorded_drive'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRenderer, nextTick } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { GalaxyPage } from '../web/js/galaxy.js'
|
||||
import { RemoteAccess } from '../web/js/remote-access.js'
|
||||
@@ -37,12 +36,10 @@ const all = item => [item, ...item.children.flatMap(all)]
|
||||
const text = item => [item.text, ...item.children.map(text)].join(' ')
|
||||
const flush = async () => { await new Promise(resolve => setImmediate(resolve)); await nextTick() }
|
||||
const host = node('host')
|
||||
const { tools } = JSON.parse(readFileSync(new URL('../web/data/catalog.json', import.meta.url)))
|
||||
const galaxy = tools.find(tool => tool.path === '/galaxy')
|
||||
const visits = []
|
||||
const app = renderer.createApp({ ...GalaxyPage, components: { ...GalaxyPage.components,
|
||||
GalaxyHotspot: { template: '<div>Hotspot settings</div>' },
|
||||
InstallApp: { props: ['url'], template: '<div class="web-link">{{ url }}</div>' },
|
||||
} }, { mode: 'local', tools: galaxy.children, go: path => visits.push(path), unauthorized() { unauthorized++ } })
|
||||
} }, { mode: 'local', unauthorized() { unauthorized++ } })
|
||||
app.config.compilerOptions.decodeEntities = value => value.replaceAll('&', '&')
|
||||
const vm = app.mount(host)
|
||||
await flush()
|
||||
@@ -56,16 +53,9 @@ try {
|
||||
const stepList = nodes.find(item => item.type === 'ol' && item.props.class === 'gx-steps')
|
||||
assert.equal(stepList.children.filter(item => item.type === 'li' && item.props.class?.includes('gx-step')).length, 2)
|
||||
assert.equal(nodes.filter(item => item.props.class === 'gx-step__head').length, 2)
|
||||
assert.match(text(host), /Galaxy Access & Connections/)
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|offline app version/)
|
||||
assert.ok(tools.some(tool => tool.path === '/starport'), 'StarPort remains a standalone tool')
|
||||
const tiles = nodes.filter(item => item.props.class === 'gx-menu-tile')
|
||||
assert.deepEqual(tiles.map(item => item.children.find(child => child.type === 'span').text), ['Networks', 'Bluetooth'])
|
||||
for (const tile of tiles) tile.props.onClick()
|
||||
nodes.find(item => item.type === 'button' && item.text === 'Get help').props.onClick()
|
||||
assert.deepEqual(visits, ['/networks', '/bluetooth', '/logs/help'])
|
||||
assert.deepEqual(requests.map(([path]) => path).sort(), ['./api/galaxy/qr.svg', './api/galaxy/status'],
|
||||
'A browser reads the pairing status and QR code without polling Android internet-sharing status')
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|Connections|offline app version/)
|
||||
assert.equal(requests.length, 1, 'A browser reads remote pairing status without polling Android internet-sharing status')
|
||||
assert.equal(requests[0][0], './api/galaxy/status')
|
||||
assert.equal(vm.url, link, 'Remote link reaches the web installer')
|
||||
const steps = vm.$.subTree.children.find(child => child.props?.class === 'gx-steps')
|
||||
const remote = steps.children.find(child => child.type === RemoteAccess).component.proxy
|
||||
|
||||
@@ -10,7 +10,7 @@ assert.ok(ids.every(id => recordArt(id).every(path => typeof path === "string" &
|
||||
assert.ok(recordArt("futureRecord").length)
|
||||
assert.ok(Home.template.includes('recordArt(record.id)'))
|
||||
assert.ok(Home.template.includes('aria-hidden="true"><svg'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Connections</h2>'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Install</h2>'))
|
||||
assert.ok(!GalaxyPage.template.includes('Galaxy & App Install'))
|
||||
assert.ok(!GalaxyPage.template.includes('Android users:'))
|
||||
assert.ok(!GalaxyPage.template.includes('Phone companion · Connections'))
|
||||
@@ -18,8 +18,8 @@ assert.ok(GalaxyPage.template.indexOf('<RemoteAccess') < GalaxyPage.template.ind
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
assert.ok(GalaxyPage.template.includes('<h3>Get the app</h3>'))
|
||||
assert.ok(GalaxyPage.template.includes('<InstallApp :url="url" />'))
|
||||
assert.ok(GalaxyPage.template.includes('Get help'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<MenuTile') < GalaxyPage.template.indexOf('<InstallApp'))
|
||||
assert.ok(GalaxyPage.template.includes('href="#/networks"'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<InstallApp') < GalaxyPage.template.indexOf('#/networks'))
|
||||
assert.ok(!GalaxyPage.template.includes('PWA'))
|
||||
assert.ok(DriveStatePanel.template.includes('gx-card gx-force-drive'))
|
||||
const css = readFileSync(new URL('../web/css/galaxy.css', import.meta.url), 'utf8')
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
import { ConnectionLogs, LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { Home } from "../web/js/home.js"
|
||||
import { RemoteQR } from "../web/js/remote-access.js"
|
||||
import { GalaxyPage } from "../web/js/galaxy.js"
|
||||
const snapshot = { available: true, addresses: [{ interface: 'wlan0', label: 'Wi-Fi', url: 'http://192.168.20.5:8082/' }], reason: '' }
|
||||
assert.equal(validLocalAccess(snapshot), true)
|
||||
@@ -68,62 +67,3 @@ assert.equal(GalaxyPage.components.LocalAccess, undefined)
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
compile(GalaxyPage.template, { decodeEntities: value => value.replaceAll('&', '&') })
|
||||
console.log('Galaxy local access remains independent of app installation')
|
||||
|
||||
const capture = { panel: false, controller: false, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalDocument = globalThis.document
|
||||
const downloads = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, 'a')
|
||||
return { href: '', download: '', click() { downloads.push({ href: this.href, download: this.download }) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/local-access/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await capture.downloadConnectionLogs()
|
||||
assert.equal(capture.captureBusy, false)
|
||||
assert.equal(capture.captureError, '')
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-connection-logs.zip')
|
||||
|
||||
const controllerCapture = { panel: true, controller: true, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/controllers/log/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await controllerCapture.downloadConnectionLogs()
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-controller-logs.zip')
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
assert.equal(LocalAccess.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(LocalAccess.template.includes("mode === 'local'"))
|
||||
compile(ConnectionLogs.template, { decodeEntities: value => value })
|
||||
assert.ok(ConnectionLogs.template.includes('Send logs'))
|
||||
assert.ok(ConnectionLogs.template.includes('Download connection ZIP'))
|
||||
assert.equal(ConnectionLogs.components.ReportingGuide, undefined)
|
||||
for (const endpoint of ['./api/galaxy/qr.svg', './api/galaxy/session/qr.svg']) {
|
||||
const qr = {endpoint, ...RemoteQR.data(), ...RemoteQR.methods}
|
||||
try {
|
||||
globalThis.fetch = async (path, options) => {
|
||||
assert.equal(path, endpoint)
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return new Response('<svg xmlns="http://www.w3.org/2000/svg"/>',{headers:{'Content-Type':'image/svg+xml'}})
|
||||
}
|
||||
await qr.load()
|
||||
assert.match(qr.image, /^blob:/)
|
||||
assert.equal(qr.failed, false)
|
||||
assert.equal((await originalFetch(qr.image)).headers.get('content-type'), 'image/svg+xml')
|
||||
RemoteQR.beforeUnmount.call(qr)
|
||||
await assert.rejects(originalFetch(qr.image))
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
}
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
|
||||
globalThis.location = { hash: "#/logs/help" }
|
||||
|
||||
const { LOG_TOPICS, LogHelp, LogStageClient, MODEL_LIMIT, NOTE_LIMIT, STAGE_URL, captureZip, downloadCaptureZip } = await import("../web/js/log-help.js")
|
||||
const { Logs } = await import("../web/js/logs.js")
|
||||
|
||||
// 1. Topic catalog & template verification (Option A: only 3 topics, zero legacy forms)
|
||||
assert.deepEqual(LOG_TOPICS.map(t => t.id), ["starport", "connection", "controller"])
|
||||
compile(LogHelp.template, { decodeEntities: v => v.replaceAll("&", "&") })
|
||||
compile(Logs.template, { decodeEntities: v => v.replaceAll("&", "&") })
|
||||
assert.ok(LogHelp.template.includes("https://firestar.link/discord"))
|
||||
assert.ok(LogHelp.template.includes("Individual session files"))
|
||||
assert.ok(!LogHelp.template.includes("Connecting via"))
|
||||
assert.ok(!LogHelp.template.includes("Driving behavior report"))
|
||||
|
||||
// 2. Logs route resolution for /logs/help, /logs/help/*, and /logs/starport
|
||||
for (const [path, expectedRoute, expectedTopic] of [
|
||||
["/logs", false, "starport"],
|
||||
["/logs/help", true, "starport"],
|
||||
["/logs/starport", true, "starport"],
|
||||
["/logs/help/connection", true, "connection"],
|
||||
["/logs/help/controller", true, "controller"],
|
||||
]) {
|
||||
assert.equal(Logs.computed.helpRoute.call({ path }), expectedRoute, `${path} helpRoute`)
|
||||
assert.equal(Logs.computed.helpTopic.call({ path }), expectedTopic, `${path} helpTopic`)
|
||||
}
|
||||
|
||||
// 3. LogStageClient lifecycle, validation, polling, ready callback, reset, and 401
|
||||
const CLAIM = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/" + "f".repeat(64)
|
||||
const state = { state: "idle", message: "", claimUrl: "", kind: "", error: "" }
|
||||
const readyUrls = []
|
||||
const scheduled = []
|
||||
const requests = []
|
||||
let unauthorizedCount = 0
|
||||
|
||||
let pollStep = 0
|
||||
const client = new LogStageClient({
|
||||
publish: update => Object.assign(state, update),
|
||||
unauthorized: () => { unauthorizedCount++ },
|
||||
schedule: (fn, ms) => { scheduled.push({ fn, ms }); return scheduled.length },
|
||||
cancel: () => {},
|
||||
onReady: url => readyUrls.push(url),
|
||||
fetcher: async (url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (options.method === "POST") {
|
||||
return { ok: true, status: 202, json: async () => ({ state: "staging", message: "Collecting logs", claimUrl: "", kind: JSON.parse(options.body).kind }) }
|
||||
}
|
||||
pollStep++
|
||||
if (pollStep === 1) {
|
||||
return { ok: true, status: 200, json: async () => ({ state: "idle", message: "", claimUrl: "", kind: "", available: true, fork: false, noteLimit: NOTE_LIMIT, modelLimit: MODEL_LIMIT }) }
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ state: "ready", message: "Logs uploaded", claimUrl: CLAIM, kind: "connection", available: true }) }
|
||||
},
|
||||
})
|
||||
|
||||
await client.start()
|
||||
assert.equal(requests[0].url, STAGE_URL)
|
||||
assert.equal(requests[0].options.cache, "no-store")
|
||||
assert.equal(requests[0].options.credentials, "same-origin")
|
||||
assert.equal(scheduled.length, 0, "idle state does not schedule polling")
|
||||
|
||||
assert.equal(await client.stage({ kind: "unknown", note: "hi" }), false)
|
||||
assert.match(state.error, /Choose what/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: " " }), false)
|
||||
assert.match(state.error, /short note/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: "a".repeat(NOTE_LIMIT + 1) }), false)
|
||||
assert.match(state.error, /200 characters/)
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "web", note: "hi" }), false)
|
||||
assert.match(state.error, /iPhone or Android/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: " ", note: "hi" }), false)
|
||||
assert.match(state.error, /make and model/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: "m".repeat(MODEL_LIMIT + 1), note: "hi" }), false)
|
||||
assert.match(state.error, /80 characters/)
|
||||
assert.equal(requests.length, 1, "client-side validation prevents network calls")
|
||||
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "ios", note: "Stuck connecting" }), true)
|
||||
const postBody = JSON.parse(requests.at(-1).options.body)
|
||||
assert.deepEqual(postBody, { kind: "connection", note: "Stuck connecting", phone: "ios" })
|
||||
assert.equal(state.state, "staging")
|
||||
assert.equal(scheduled.length, 1)
|
||||
|
||||
await client.poll()
|
||||
assert.equal(state.state, "ready")
|
||||
assert.equal(state.claimUrl, CLAIM)
|
||||
assert.deepEqual(readyUrls, [CLAIM])
|
||||
|
||||
client.reset(CLAIM)
|
||||
assert.equal(state.state, "idle")
|
||||
assert.equal(state.claimUrl, "")
|
||||
await client.poll()
|
||||
assert.equal(state.state, "idle", "dismissed claimUrl stays hidden on subsequent polls")
|
||||
assert.equal(readyUrls.length, 1)
|
||||
|
||||
client.fetcher = async () => ({ status: 401 })
|
||||
await client.poll()
|
||||
assert.equal(unauthorizedCount, 1)
|
||||
assert.equal(client.active, false)
|
||||
|
||||
// 4. captureZip and downloadCaptureZip contracts
|
||||
const originalDocument = globalThis.document
|
||||
const clicked = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, "a")
|
||||
return { href: "", download: "", click() { clicked.push(this.download) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
const validZip = "UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
const okConnection = await downloadCaptureZip("connection", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/local-access/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okConnection, true)
|
||||
const okController = await downloadCaptureZip("controller", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/controllers/log/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okController, true)
|
||||
assert.deepEqual(clicked, ["starpilot-connection-logs.zip", "starpilot-controller-logs.zip"])
|
||||
|
||||
await assert.rejects(
|
||||
() => captureZip("connection", { fetcher: async () => ({ ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: btoa("not-a-zip-header-at-all-123456") }) }) }),
|
||||
/Invalid diagnostic capture/,
|
||||
)
|
||||
} finally {
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
|
||||
console.log("LogHelp UI routing, LogStageClient, and captureZip checks passed")
|
||||
@@ -1,279 +0,0 @@
|
||||
"""Tests for one-way log relay staging and Galaxy /api/logs/stage endpoints."""
|
||||
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
from urllib.parse import unquote
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import (
|
||||
CLAIM_RE,
|
||||
MODEL_LIMIT,
|
||||
NOTE_LIMIT,
|
||||
STAGE_URL,
|
||||
LogRelayStager,
|
||||
StageBusy,
|
||||
StageRejected,
|
||||
clean_stage_request,
|
||||
)
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.starport_send import DISCORD_FILE_LIMIT
|
||||
|
||||
VALID_CLAIM = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/" + ("a1b2" * 16)
|
||||
SAMPLE_ZIP = b"PK\x03\x04" + b"\x00" * 32
|
||||
|
||||
|
||||
def wait_until(predicate, timeout=2.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.01)
|
||||
raise AssertionError("Timed out waiting for condition")
|
||||
|
||||
|
||||
class CleanStageRequestTest(unittest.TestCase):
|
||||
def test_valid_requests_per_kind(self):
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "starport", "note": " Black\nscreen\ton start "}),
|
||||
("starport", "android", "Black screen on start"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "connection", "phone": "ios", "note": "App keeps spinning"}),
|
||||
("connection", "ios", "[iPhone] App keeps spinning"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "connection", "phone": "android", "note": "Stuck on pairing"}),
|
||||
("connection", "android", "[Android] Stuck on pairing"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "controller", "model": " 8BitDo\tMicro ", "note": "No response"}),
|
||||
("controller", "ios", "Controller (8BitDo Micro): No response"),
|
||||
)
|
||||
|
||||
def test_rejects_invalid_payloads(self):
|
||||
invalid = [
|
||||
None,
|
||||
[],
|
||||
{},
|
||||
{"kind": "crash", "note": "nope"},
|
||||
{"kind": "starport", "note": " "},
|
||||
{"kind": "starport", "note": 123},
|
||||
{"kind": "starport", "note": "x" * (NOTE_LIMIT + 1)},
|
||||
{"kind": "starport", "note": "ok", "phone": "ios"},
|
||||
{"kind": "starport", "note": "ok", "extra": 1},
|
||||
{"kind": "connection", "note": "ok"},
|
||||
{"kind": "connection", "phone": "windows", "note": "ok"},
|
||||
{"kind": "controller", "note": "ok"},
|
||||
{"kind": "controller", "model": "\n\t ", "note": "ok"},
|
||||
{"kind": "controller", "model": "m" * (MODEL_LIMIT + 1), "note": "ok"},
|
||||
]
|
||||
for payload in invalid:
|
||||
with self.subTest(payload=payload):
|
||||
with self.assertRaises(StageRejected):
|
||||
clean_stage_request(payload)
|
||||
|
||||
|
||||
class LogRelayStagerTest(unittest.TestCase):
|
||||
def test_stages_starport_connection_and_controller_bundles(self):
|
||||
calls = []
|
||||
|
||||
def fake_post(url, data, headers, allow_redirects, timeout):
|
||||
calls.append({"url": url, "data": data, "headers": headers, "allow_redirects": allow_redirects, "timeout": timeout})
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(
|
||||
lambda **_kw: ("starport-logs.zip", b"starport-zip"),
|
||||
lambda: b"connection-zip",
|
||||
lambda: b"controller-zip",
|
||||
post=fake_post,
|
||||
official=lambda: False,
|
||||
)
|
||||
initial = stager.status()
|
||||
self.assertEqual(initial["state"], "idle")
|
||||
self.assertTrue(initial["available"])
|
||||
self.assertTrue(initial["fork"])
|
||||
self.assertEqual(initial["noteLimit"], NOTE_LIMIT)
|
||||
self.assertEqual(initial["modelLimit"], MODEL_LIMIT)
|
||||
|
||||
cases = [
|
||||
({"kind": "starport", "note": "Dropped after 2m"}, b"starport-zip", "starport", "android", "Dropped after 2m"),
|
||||
({"kind": "connection", "phone": "android", "note": "mDNS fail"}, b"connection-zip", "connection", "android", "[Android] mDNS fail"),
|
||||
({"kind": "controller", "model": "Xbox Series", "note": "D-pad dead"}, b"controller-zip", "controller", "ios", "Controller (Xbox Series): D-pad dead"),
|
||||
]
|
||||
for payload, expected_zip, expected_kind, expected_platform, expected_note in cases:
|
||||
with self.subTest(kind=expected_kind):
|
||||
started = stager.start(payload)
|
||||
self.assertEqual(started["state"], "staging")
|
||||
ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None)
|
||||
self.assertEqual(ready["claimUrl"], VALID_CLAIM)
|
||||
self.assertEqual(ready["kind"], expected_kind)
|
||||
self.assertTrue(CLAIM_RE.fullmatch(ready["claimUrl"]))
|
||||
call = calls[-1]
|
||||
self.assertEqual(call["url"], STAGE_URL)
|
||||
self.assertEqual(call["data"], expected_zip)
|
||||
self.assertFalse(call["allow_redirects"])
|
||||
self.assertEqual(call["headers"]["Content-Type"], "application/zip")
|
||||
self.assertEqual(call["headers"]["X-Galaxy-Kind"], expected_kind)
|
||||
self.assertEqual(call["headers"]["X-Galaxy-Platform"], expected_platform)
|
||||
self.assertEqual(unquote(call["headers"]["X-Galaxy-Note"]), expected_note)
|
||||
|
||||
def test_retries_starport_without_system_snapshot_when_oversize(self):
|
||||
seen_args = []
|
||||
posts = []
|
||||
|
||||
def build_starport(*, system_snapshot=True):
|
||||
seen_args.append(system_snapshot)
|
||||
return ("starport-logs.zip", b"x" * (DISCORD_FILE_LIMIT + 1) if system_snapshot else b"small-zip")
|
||||
|
||||
def fake_post(url, data, **_kwargs):
|
||||
posts.append(data)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(build_starport, lambda: b"c", lambda: b"k", post=fake_post, official=lambda: True)
|
||||
stager.start({"kind": "starport", "note": "Trim snapshot"})
|
||||
ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None)
|
||||
self.assertEqual(seen_args, [True, False])
|
||||
self.assertEqual(posts, [b"small-zip"])
|
||||
self.assertFalse(ready["fork"])
|
||||
|
||||
def test_failures_surface_clear_fallback_messages(self):
|
||||
def run_failure(response_or_exc, *, zip_bytes=b"zip"):
|
||||
def fake_post(*_args, **_kwargs):
|
||||
if isinstance(response_or_exc, Exception):
|
||||
raise response_or_exc
|
||||
return response_or_exc
|
||||
|
||||
stager = LogRelayStager(lambda **_kw: ("s.zip", zip_bytes), lambda: zip_bytes, lambda: zip_bytes, post=fake_post)
|
||||
stager.start({"kind": "connection", "phone": "ios", "note": "Fail test"})
|
||||
return wait_until(lambda: stager.status() if stager.status()["state"] == "failed" else None)
|
||||
|
||||
r404 = Mock(status_code=404)
|
||||
self.assertIn("updating", run_failure(r404)["message"])
|
||||
|
||||
r413 = Mock(status_code=413)
|
||||
self.assertIn("upload limit", run_failure(r413)["message"])
|
||||
self.assertIn("upload limit", run_failure(Mock(status_code=200), zip_bytes=b"x" * (DISCORD_FILE_LIMIT + 1))["message"])
|
||||
|
||||
r429 = Mock(status_code=429)
|
||||
r429.json.return_value = {"error": "Too many uploads from this IP"}
|
||||
self.assertEqual(run_failure(r429)["message"], "Too many uploads from this IP")
|
||||
|
||||
bad_claim = Mock(status_code=200)
|
||||
bad_claim.json.return_value = {"claimUrl": "https://evil.example/claim/" + ("a" * 64)}
|
||||
self.assertIn("Invalid relay claim link", run_failure(bad_claim)["message"])
|
||||
|
||||
bad_json = Mock(status_code=200)
|
||||
bad_json.json.side_effect = ValueError("not json")
|
||||
self.assertIn("Invalid response", run_failure(bad_json)["message"])
|
||||
|
||||
self.assertIn("internet", run_failure(RuntimeError("dns failed"))["message"])
|
||||
|
||||
def test_busy_and_unavailable_guards(self):
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_post(*_args, **_kwargs):
|
||||
entered.set()
|
||||
release.wait(2)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(lambda **_kw: ("s.zip", b"zip"), lambda: b"c", lambda: b"k", post=slow_post)
|
||||
stager.start({"kind": "starport", "note": "First"})
|
||||
self.assertTrue(entered.wait(2))
|
||||
try:
|
||||
with self.assertRaises(StageBusy):
|
||||
stager.start({"kind": "starport", "note": "Second"})
|
||||
finally:
|
||||
release.set()
|
||||
wait_until(lambda: stager.status()["state"] == "ready")
|
||||
|
||||
disabled = LogRelayStager(lambda **_kw: ("s.zip", b"zip"), lambda: b"c", lambda: b"k", stage_url="")
|
||||
self.assertFalse(disabled.status()["available"])
|
||||
with self.assertRaises(StageRejected):
|
||||
disabled.start({"kind": "starport", "note": "Disabled"})
|
||||
|
||||
|
||||
class LogStageHTTPTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.access = GalaxyAccessOwner(Path(self.temp.name))
|
||||
self.access.configure("test-password-123", lambda: True)
|
||||
self.release = threading.Event()
|
||||
self.entered = threading.Event()
|
||||
|
||||
def slow_or_fast_post(*_args, **_kwargs):
|
||||
self.entered.set()
|
||||
self.release.wait(2)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
self.stager = LogRelayStager(
|
||||
lambda **_kw: ("starport-logs.zip", SAMPLE_ZIP),
|
||||
lambda: SAMPLE_ZIP,
|
||||
lambda: SAMPLE_ZIP,
|
||||
post=slow_or_fast_post,
|
||||
official=lambda: True,
|
||||
)
|
||||
self.server = make_server(port=0, owner=self.access, parked=lambda: True, log_relay_stager=self.stager)
|
||||
self.addCleanup(self.server.server_close)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
|
||||
self.thread.start()
|
||||
self.addCleanup(lambda: (self.server.shutdown(), self.thread.join(2)))
|
||||
self.cookie = ""
|
||||
|
||||
def request(self, path, *, method="GET", payload=None, origin=None, remote=False):
|
||||
headers = {"Origin": origin or f"http://127.0.0.1:{self.server.server_port}", "Content-Type": "application/json"}
|
||||
if self.cookie:
|
||||
headers["Cookie"] = self.cookie
|
||||
if remote:
|
||||
headers["Forwarded"] = "for=203.0.113.9"
|
||||
conn = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=4)
|
||||
try:
|
||||
conn.request(method, path, None if payload is None else json.dumps(payload), headers)
|
||||
resp = conn.getresponse()
|
||||
cookie = resp.getheader("Set-Cookie")
|
||||
return resp.status, json.loads(resp.read()), cookie.split(";")[0] if cookie else ""
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def test_http_validation_busy_status_and_auth(self):
|
||||
self.assertEqual(self.request("/api/logs/stage", remote=True)[0], 401)
|
||||
_, _, self.cookie = self.request("/api/auth/session")
|
||||
self.assertEqual(self.request("/api/logs/stage", origin="https://other.example")[0], 403)
|
||||
self.assertEqual(self.request("/api/logs/stage", method="POST", payload={"kind": "starport", "note": ""})[0], 400)
|
||||
|
||||
status, body, _ = self.request("/api/logs/stage", method="POST", payload={"kind": "controller", "model": "DualSense", "note": "Not detected"})
|
||||
self.assertEqual(status, 202)
|
||||
self.assertEqual(body["state"], "staging")
|
||||
self.assertTrue(self.entered.wait(2))
|
||||
self.assertEqual(self.request("/api/logs/stage", method="POST", payload={"kind": "starport", "note": "Busy"})[0], 409)
|
||||
self.release.set()
|
||||
|
||||
ready = wait_until(lambda: res if (res := self.request("/api/logs/stage")[1])["state"] == "ready" else None)
|
||||
self.assertEqual(ready["claimUrl"], VALID_CLAIM)
|
||||
first_cookie, self.cookie = self.cookie, ""
|
||||
_, _, self.cookie = self.request("/api/auth/session")
|
||||
self.assertNotEqual(self.cookie, first_cookie)
|
||||
self.assertEqual(self.request("/api/logs/stage")[1]["claimUrl"], "")
|
||||
self.cookie = first_cookie
|
||||
self.assertEqual(self.request("/api/logs/stage")[1]["claimUrl"], VALID_CLAIM)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -27,8 +27,8 @@ print(json.dumps(documents))
|
||||
`], { encoding: "utf8" }))
|
||||
for (const document of signalEdges) assert.equal(validDocument(document, data.metadata), true)
|
||||
assert.equal(validSnapshot(data), true)
|
||||
assert.equal(data.document.version, 17)
|
||||
for (const version of [9, 10, 15, 16, 18]) {
|
||||
assert.equal(data.document.version, 16)
|
||||
for (const version of [9, 10, 15, 17]) {
|
||||
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false)
|
||||
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
"""Pure bounded network/launcher readers; never imports native vehicle modules."""
|
||||
|
||||
import ast
|
||||
from base64 import b64decode
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import json
|
||||
@@ -11,7 +8,7 @@ import subprocess
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive, MAX_BYTES
|
||||
|
||||
|
||||
@@ -69,56 +66,6 @@ class TestNetworkDiagnostics(unittest.TestCase):
|
||||
for run in [lambda *_a, **_k: SimpleNamespace(stdout=b'x' * 65537), lambda *_a, **_k: (_ for _ in ()).throw(subprocess.TimeoutExpired('ip', 1))]:
|
||||
self.assertFalse(LocalAccess(run=run).snapshot()['available'])
|
||||
|
||||
def test_connection_capture_includes_only_known_advertiser_events(self):
|
||||
source, _ = self.addresses([interface()])
|
||||
commands = []
|
||||
|
||||
def run(args, **_kwargs):
|
||||
commands.append(args)
|
||||
if args[0] == 'systemctl':
|
||||
return SimpleNamespace(stdout=b'ActiveState=active\nSubState=running\nNRestarts=3\n')
|
||||
if args[0] == 'ip':
|
||||
state = [{'dev': 'wlan0', 'gateway': '192.168.50.1'}] if 'route' in args else [
|
||||
{'ifname': 'wlan0', 'operstate': 'UP', 'address': 'de:ad:be:ef:00:01',
|
||||
'addr_info': [{'local': '192.168.50.21', 'prefixlen': 24}, {'local': '8.8.8.8', 'prefixlen': 32}]}]
|
||||
return SimpleNamespace(stdout=json.dumps(state).encode())
|
||||
if args[0] == 'ss':
|
||||
return SimpleNamespace(stdout=b'LISTEN 0 20 0.0.0.0:8082 0.0.0.0:*')
|
||||
if 'galaxy-ble-fork.service' in args:
|
||||
return SimpleNamespace(stdout=b'{"MESSAGE":"Phone claimed pairing window"}')
|
||||
rows = [{'MESSAGE': 'Galaxy Wi-Fi discovery available on 1 local interface(s)'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: TimeoutExpired'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: cookie=private'},
|
||||
{'MESSAGE': 'Tunnel password: private'}]
|
||||
return SimpleNamespace(stdout='\n'.join(map(json.dumps, rows)).encode())
|
||||
|
||||
capture = connection_capture(source.snapshot(), run=run)
|
||||
self.assertEqual(capture['schemaVersion'], 1)
|
||||
self.assertIn('http://192.168.50.21:8082/', capture['text'])
|
||||
self.assertIn('Bonjour advertiser: active', capture['text'])
|
||||
self.assertIn('Galaxy Wi-Fi discovery available on 1 local interface(s)', capture['text'])
|
||||
self.assertIn('Wi-Fi discovery unavailable: TimeoutExpired', capture['text'])
|
||||
self.assertNotIn('Tunnel password:', capture['text'])
|
||||
self.assertTrue(any('galaxy-lan-discovery.service' in args for args in commands))
|
||||
with ZipFile(BytesIO(b64decode(capture['zipBase64']))) as archive:
|
||||
self.assertEqual(archive.namelist(), ['connection-logs.txt'])
|
||||
report = archive.read('connection-logs.txt').decode()
|
||||
self.assertIn('192.168.50.21/24', report)
|
||||
self.assertIn('IPv4 default route interfaces: wlan0', report)
|
||||
self.assertIn('TCP port 8082 listening: all interfaces', report)
|
||||
self.assertIn('NRestarts=3', report)
|
||||
self.assertIn('Phone claimed pairing window', report)
|
||||
for private_value in ('de:ad:be:ef:00:01', '192.168.50.1', '8.8.8.8', 'cookie=private'):
|
||||
self.assertNotIn(private_value, report)
|
||||
|
||||
def missing(*_args, **_kwargs):
|
||||
raise FileNotFoundError()
|
||||
|
||||
partial = connection_capture(source.snapshot(), run=missing)['text']
|
||||
self.assertIn('Bonjour advertiser: unavailable', partial)
|
||||
self.assertIn('Advertiser journal unavailable', partial)
|
||||
self.assertIn('192.168.50.21', partial)
|
||||
|
||||
def test_console_uses_exact_readonly_launcher_pane_and_cache(self):
|
||||
source, calls = self.console(b'first\nsecond\n')
|
||||
result = source.snapshot()
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from 'node:assert/strict'
|
||||
import { compile } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { NetworksPage, validNetworks } from '../web/js/networks.js'
|
||||
@@ -67,6 +66,3 @@ const before = sent.length
|
||||
assert.equal(await vm.send({ action: 'cellular', value: false }), false)
|
||||
assert.equal(sent.length, before)
|
||||
vm.stop()
|
||||
|
||||
assert.equal(NetworksPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(NetworksPage.template.includes("<ConnectionLogs v-if=\"mode === 'local'\" panel"))
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
import * as documentHelpers from "../web/js/onroad-layout-document.js"
|
||||
import * as layoutModule from "../web/js/onroad-layout.js"
|
||||
import { ONROAD_LAYOUT_TEMPLATE } from "../web/js/onroad-layout-template.js"
|
||||
@@ -55,7 +54,7 @@ export function snapshot() {
|
||||
metadata.roadColorFields = [{ id: 'path', label: 'Path', default: '#30FF9CFF' },
|
||||
{ id: 'pathEdge', label: 'Path edges', default: '#00FF40FF' }, { id: 'laneLines', label: 'Lane lines', default: '#FFFFFFFF' }]
|
||||
metadata.profiles.compact.widgets.speed_limit.visualInsetTop = 32
|
||||
const document = { version: 17, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
|
||||
const document = { version: 16, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
|
||||
layouts: Object.fromEntries(Object.entries(metadata.profiles).map(([id, profile]) => [id,
|
||||
Object.fromEntries(Object.entries(profile.widgets).map(([key, definition]) => [key,
|
||||
{ ...definition.default, ...(definition.resizable ? { size: definition.resizable.default } : {}) }]))])) }
|
||||
@@ -365,11 +364,6 @@ try {
|
||||
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: {
|
||||
getItem: key => preferences.get(key) ?? null, setItem: (key, value) => preferences.set(key, value)
|
||||
} })
|
||||
assert.equal(editor().vm.state.hiddenPreviewWidgets.compact.pip_left, true)
|
||||
assert.equal(OnroadLayoutPage.setup({ projection: true }).state.hiddenPreviewWidgets.compact.pip_left, undefined)
|
||||
preferences.set("gx-layout-preview-visibility-v2:comma", JSON.stringify({ compact: { pip_left: false } }))
|
||||
assert.equal(editor().vm.state.hiddenPreviewWidgets.compact.pip_left, false)
|
||||
preferences.delete("gx-layout-preview-visibility-v2:comma")
|
||||
const preference = editor().vm
|
||||
assert.equal(preference.state.snapEnabled, true)
|
||||
preference.toggleSnap()
|
||||
@@ -1167,7 +1161,7 @@ const displayRows = [
|
||||
{ key: "DeveloperSidebar", label: "Developer Sidebar", group: "Big layout", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "ShowBrakeStatus", label: "Wheel brake and acceleration colors", group: "widget", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "HideLeadMarker", label: "Lead Indicator", group: "Lead car", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "LeadInfo", label: "Lead Info", group: "Lead car", choices: ["Off", "Distance", "Speed", "Relative speed"], available: true, reason: "", requires: "HideLeadMarker" },
|
||||
{ key: "LeadInfo", label: "Lead Info", group: "Lead car", choices: ["Off", "Distance", "Speed"], available: true, reason: "", requires: "HideLeadMarker" },
|
||||
{ key: "SignalMetrics", label: "C4 amber signal border", group: "Alerts and borders", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
]
|
||||
const withDisplayData = () => ({ ...snapshot(), display: { rows: copy(displayRows),
|
||||
@@ -1185,7 +1179,7 @@ assert.equal(validDocument({ ...merged.document, showMaxSpeed: "no" }, merged.me
|
||||
const display = editor()
|
||||
display.vm.state.data = merged; display.vm.state.draft = copy(merged.document)
|
||||
assert.deepEqual(display.vm.displayGroups.map(group => [group.name, group.rows.map(row => row.key)]),
|
||||
[["Big layout", ["DeveloperSidebar"]], ["Alerts and borders", ["SignalMetrics"]]])
|
||||
[["Big layout", ["DeveloperSidebar"]], ["Lead car", ["HideLeadMarker", "LeadInfo"]], ["Alerts and borders", ["SignalMetrics"]]])
|
||||
display.vm.setDisplay("DeveloperSidebar", "Off")
|
||||
assert.equal(display.vm.displaySettingRow(display.vm.displayRow("DeveloperSidebar")).value, "Off")
|
||||
assert.equal(display.vm.dirty, true)
|
||||
@@ -1269,26 +1263,6 @@ assert.equal(display.vm.displayValue("LeadInfo"), "Distance")
|
||||
assert.equal(display.vm.dirty, true)
|
||||
display.vm.undo(); display.vm.undo()
|
||||
assert.equal(display.vm.dirty, false)
|
||||
display.vm.openLeadEditor()
|
||||
assert.equal(display.vm.state.inspectorPanel, "lead")
|
||||
assert.equal(display.vm.leadRows.length, 2)
|
||||
display.vm.setDisplay("HideLeadMarker", "On")
|
||||
display.vm.setDisplay("LeadInfo", "Relative speed")
|
||||
assert.equal(display.vm.leadPreviewLabel, "+4 mph")
|
||||
display.vm.roadColor("leadMarker", "#22CCFFFF")
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
assert.equal(validDocument(display.vm.state.draft, display.vm.state.data.metadata), true)
|
||||
display.vm.resetRoad()
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
display.vm.state.data.supportedProfiles = ["large", "compact"]
|
||||
display.vm.selectProfile("compact")
|
||||
assert.equal(display.vm.leadColor, "#FFFFFFFF")
|
||||
display.vm.selectProfile("large")
|
||||
display.vm.resetLeadColor()
|
||||
assert.equal(display.vm.leadColor, "#C92231FF")
|
||||
display.vm.undo()
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
display.vm.resetToStock()
|
||||
display.vm.state.selected = "cruise_limits"
|
||||
display.vm.setShowMaxSpeed({ target: { checked: false } })
|
||||
assert.equal(display.vm.state.draft.showMaxSpeed, false)
|
||||
@@ -1392,11 +1366,11 @@ console.log("Ford rear fog: make visibility, saved placement and strict metadata
|
||||
assert.equal(clampPlacement(profile, 'speed_limit', 330, 16, sample.document.layouts.compact).x, 320)
|
||||
}
|
||||
|
||||
// The device writes version 17 with full-panel C4 side cameras.
|
||||
// The device writes version 16 once the speed limit actions widget is folded into the sign.
|
||||
{
|
||||
const sample = snapshot()
|
||||
assert.equal(validDocument(sample.document, sample.metadata), true)
|
||||
sample.document.version = 16
|
||||
sample.document.version = 15
|
||||
assert.equal(validDocument(sample.document, sample.metadata), false)
|
||||
}
|
||||
|
||||
@@ -1409,45 +1383,3 @@ for (const invalidOffset of [true, null, "1", NaN, Infinity, -5.1, 5.1]) {
|
||||
assert.equal(validDocument(document, speedAdjustment.metadata), false)
|
||||
}
|
||||
assert.ok(SETTINGS_SECTIONS.find(section => section.id === "developer").pages.includes("developer"))
|
||||
|
||||
|
||||
// C4 has one locked camera widget covering the road panel.
|
||||
{
|
||||
const sample = snapshot()
|
||||
const profile = sample.metadata.profiles.compact
|
||||
for (const side of ["left"]) {
|
||||
const id = `pip_${side}`
|
||||
profile.widgets[id] = widget("Adj Spot Camera", "pip_camera", 476, 240, 0, 0)
|
||||
sample.document.layouts.compact[id] = { x: 0, y: 0, enabled: side === "left" }
|
||||
assert.deepEqual(clampPlacement(profile, id, 300, 100, sample.document.layouts.compact), { x: 0, y: 0 })
|
||||
assert.deepEqual(documentHelpers.widgetSize(profile.widgets[id], sample.document.layouts.compact[id]), [476, 240])
|
||||
}
|
||||
assert.equal(validDocument(sample.document, sample.metadata), true)
|
||||
const vm = editor().vm
|
||||
vm.state.data = sample; vm.state.draft = copy(sample.document); vm.state.profile = "compact"
|
||||
assert.deepEqual(vm.cameraIds, ["pip_left"])
|
||||
assert.deepEqual(vm.lockedCameraIds, ["pip_left"])
|
||||
const original = copy(vm.state.draft)
|
||||
assert.equal(vm.previewHidden("pip_left"), true)
|
||||
assert.equal(vm.renderWidgets.some(widget => widget.id === "pip_left"), false)
|
||||
vm.togglePreviewVisibility("pip_left")
|
||||
assert.equal(vm.previewHidden("pip_left"), false)
|
||||
assert.equal(vm.renderWidgets.some(widget => widget.id === "pip_left"), true)
|
||||
assert.deepEqual(vm.state.draft, original)
|
||||
assert.equal(vm.dirty, false)
|
||||
}
|
||||
|
||||
|
||||
// The actual Vue preview uses the same device-specific silhouettes as onroad.
|
||||
{
|
||||
const render = compile(LayoutWidgetPreview.template, { decodeEntities: value => value.replaceAll("&", "&") })
|
||||
const nodes = vnode => [vnode, ...(Array.isArray(vnode.children) ? vnode.children.flatMap(nodes) : [])]
|
||||
for (const [profile, width, height, shape] of [["large", 600, 600, "circle"], ["compact", 476, 240, "rect"]]) {
|
||||
const tree = render({ widget: widget("Adj Spot Camera", "pip_camera", width, height, 0, 0),
|
||||
palette: {}, sprite: null, native: false, profile }, [])
|
||||
const camera = nodes(tree).find(node => node.type === shape)
|
||||
assert.ok(camera, `${profile} renders a ${shape}`)
|
||||
assert.equal(nodes(tree).some(node => node.type === (shape === "rect" ? "circle" : "rect")), false)
|
||||
if (shape === "rect") assert.deepEqual([camera.props.width, camera.props.height, camera.props.rx], [476, 240, 52.8])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,8 @@ class PreviewContractTest(unittest.TestCase):
|
||||
self.assertTrue(all(path.startswith("/") and path != "/tools" for path in paths))
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "partial-preview"], ["/logs"])
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "local-only"],
|
||||
["/cameras", "/galaxy", "/manage_models", "/navigation", "/system", "/theme_maker", "/tuning", "/starport"])
|
||||
galaxy = next(tool for tool in catalog["tools"] if tool["path"] == "/galaxy")
|
||||
self.assertEqual([(tool["path"], tool["availability"]) for tool in galaxy["children"]],
|
||||
[("/networks", "local-only"), ("/bluetooth", "local-only")])
|
||||
["/bluetooth", "/cameras", "/galaxy", "/manage_models", "/navigation", "/networks", "/system",
|
||||
"/theme_maker", "/tuning", "/starport"])
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "always"], [])
|
||||
self.assertTrue(all(tool["availability"] in {"always", "unavailable", "partial-preview", "local-only"} for tool in catalog["tools"]))
|
||||
self.assertTrue(all(tool["name"] and tool["description"] and tool["icon"] for tool in catalog["tools"]))
|
||||
@@ -29,8 +27,8 @@ class PreviewContractTest(unittest.TestCase):
|
||||
def test_static_preview_and_read_only_runtime_are_explicit(self):
|
||||
scripts = "\n".join(path.read_text() for path in (WEB / "js").glob("*.js"))
|
||||
self.assertEqual(sorted(re.findall(r"\bfetch\s*\(\s*[\"']([^\"']+)", scripts)),
|
||||
['./api/auth/session', './api/bluetooth/uniden', './api/drive-state/action',
|
||||
'./api/drive-state/status', '/_gateway/devices'])
|
||||
['./api/auth/session', './api/drive-state/action', './api/drive-state/status',
|
||||
'/_gateway/devices'])
|
||||
config = json.loads((WEB / 'data/runtime.json').read_text())
|
||||
self.assertEqual(config, {'schemaVersion': 1, 'monitor': 'sample'})
|
||||
self.assertIn('./api/ui/layout', scripts)
|
||||
|
||||
@@ -4,11 +4,9 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import SnapshotDenied
|
||||
from openpilot.starpilot.galaxy.server import make_remote_server, make_server
|
||||
from openpilot.starpilot.sentry_mode.notifications import NotificationOwner
|
||||
|
||||
@@ -21,28 +19,16 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
from openpilot.starpilot.sentry_mode.storage import EventStore
|
||||
owner.store = EventStore(root / 'events')
|
||||
parked = [True]
|
||||
photos = []
|
||||
jpeg = b'\xff\xd8\xff\xd9'
|
||||
class Camera:
|
||||
def capture_many(self, cameras, **options):
|
||||
return {camera: self.capture(camera, **options) for camera in cameras}
|
||||
def capture(self, camera, *, permitted, parked):
|
||||
if not parked or not permitted():
|
||||
raise SnapshotDenied
|
||||
photos.append(camera)
|
||||
return jpeg
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0],
|
||||
camera_snapshot=Camera())
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0])
|
||||
thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
thread.start()
|
||||
def request(payload=None, cookie='', path=None):
|
||||
def request(payload=None, cookie=''):
|
||||
connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3)
|
||||
headers = {'Cookie': cookie, 'Origin': f'http://127.0.0.1:{server.server_port}', 'Content-Type': 'application/json'}
|
||||
connection.request('POST' if payload is not None else 'GET', path or ('/api/sentry/notifications' if payload is not None else '/api/auth/session'),
|
||||
connection.request('POST' if payload is not None else 'GET', '/api/sentry/notifications' if payload is not None else '/api/auth/session',
|
||||
json.dumps(payload) if payload is not None else None, headers)
|
||||
reply = connection.getresponse()
|
||||
raw = reply.read()
|
||||
result = reply.status, raw if reply.getheader('Content-Type') == 'image/jpeg' else json.loads(raw), dict(reply.getheaders())
|
||||
result = reply.status, json.loads(reply.read()), dict(reply.getheaders())
|
||||
connection.close()
|
||||
return result
|
||||
try:
|
||||
@@ -52,33 +38,11 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
self.assertNotIn('test-token', json.dumps(result))
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': 'missing'}, cookie)[0], 404)
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': result['appSubscriptions'][0]['id']}, cookie)[0], 200)
|
||||
test_route = '/api/sentry/notifications/photo-test'
|
||||
test = {'camera': 'cabin', 'id': result['appSubscriptions'][0]['id']}
|
||||
self.assertEqual(request(test, path=test_route)[0], 401)
|
||||
parked[0] = False
|
||||
self.assertEqual(request(test, cookie, test_route)[0], 409)
|
||||
self.assertEqual(photos, [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 403)
|
||||
parked[0] = True
|
||||
self.assertEqual(request(test, cookie, test_route)[0], 503)
|
||||
self.assertEqual(request({'action': 'configure', 'channel': 'appPush', 'enabled': True,
|
||||
'url': 'https://relay.example.test', 'token': ''}, cookie)[0], 200)
|
||||
photos.clear()
|
||||
self.assertEqual(request(test, cookie, test_route)[:2], (200, {'queued': True}))
|
||||
self.assertEqual(photos, ['cabin'])
|
||||
event_id = next(iter(owner.test_photos))
|
||||
image_path = f'/api/sentry/image/{event_id}/test'
|
||||
self.assertEqual(request(path=image_path)[0], 401)
|
||||
self.assertEqual(request(cookie=cookie, path=image_path)[:2], (200, jpeg))
|
||||
self.assertEqual(owner.store.snapshot()['events'], [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 200)
|
||||
deadline = time.monotonic() + 3
|
||||
while not owner.store.snapshot()['events'] and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
event = owner.store.snapshot()['events'][0]
|
||||
self.assertTrue(event['simulated'])
|
||||
for camera in ('wide', 'cabin'):
|
||||
self.assertEqual(owner.store.image(event['eventId'], camera), jpeg)
|
||||
self.assertTrue(owner.store.snapshot()['events'][0]['simulated'])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 429)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -3,7 +3,7 @@ import { validDocument } from "../web/js/onroad-layout.js"
|
||||
const metadata = { profiles: Object.fromEntries(["large", "compact"].map(name => [name, {
|
||||
bounds: {x:0,y:0,width:100,height:100}, widgets:{}, reservedZones:[]
|
||||
}])) }
|
||||
const document = { version:17, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
|
||||
const document = { version:16, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
|
||||
layouts:{large:{},compact:{}},widgetColors:{large:{},compact:{}},roadColors:{large:{},compact:{}} }
|
||||
assert.equal(validDocument(document, metadata), true)
|
||||
for (const flag of [true, false]) assert.equal(validDocument({...document,speedSources:flag},metadata),true)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { StarPortLogsFeed, BUNDLE_URL, fileUrl, outcomeLabel } from "../web/js/starport-logs.js"
|
||||
import { StarPortLogsFeed, outcomeLabel } from "../web/js/starport-logs.js"
|
||||
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
|
||||
function fixture() {
|
||||
@@ -14,9 +14,6 @@ function fixture() {
|
||||
return { feed, requests, states, reply, get unauthorized() { return unauthorized } }
|
||||
}
|
||||
|
||||
assert.equal(BUNDLE_URL, "./api/starport/logs/bundle")
|
||||
assert.equal(fileUrl("session-000002-20261005-094551.jsonl"), "./api/starport/logs/file/session-000002-20261005-094551.jsonl")
|
||||
assert.equal(fileUrl("a b/c"), "./api/starport/logs/file/a%20b%2Fc")
|
||||
assert.equal(outcomeLabel("failed: RFCOMM: timed out"), "Failed: RFCOMM: timed out")
|
||||
assert.equal(outcomeLabel(""), "Unknown")
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated download routes."""
|
||||
"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated list route."""
|
||||
|
||||
import http.client
|
||||
import io
|
||||
@@ -11,9 +11,8 @@ from unittest import mock
|
||||
import zipfile
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.starport_logs import StarPortLogs, LogMissing
|
||||
from openpilot.starpilot.galaxy.starport_logs import StarPortLogs
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.system.starport import system_snapshot
|
||||
|
||||
SESSION = "\n".join(json.dumps(event) for event in (
|
||||
{"t": "2026-10-05T16:45:51.000+00:00", "event": "session_start", "receiver": "Honda CIVIC", "trigger": "auto"},
|
||||
@@ -51,14 +50,8 @@ class StarPortLogsReaderTest(unittest.TestCase):
|
||||
self.assertEqual(session["trigger"], "auto")
|
||||
self.assertEqual([item["name"] for item in listing["others"]], ["car_ui.log"])
|
||||
|
||||
def test_serves_only_listed_logs(self):
|
||||
self.assertEqual(self.reader.file("car_ui.log"), ("car_ui.log", b"car view pipeline: nv12, async readback\n"))
|
||||
for name in ("notes.txt", "../config.json", "missing.jsonl", ""):
|
||||
with self.assertRaises(LogMissing):
|
||||
self.reader.file(name)
|
||||
def test_symlinked_logs_are_not_listed(self):
|
||||
(self.logs / "render_profile.txt").symlink_to(self.config)
|
||||
with self.assertRaises(LogMissing):
|
||||
self.reader.file("render_profile.txt")
|
||||
self.assertNotIn("render_profile.txt", [item["name"] for item in self.reader.list()["others"]])
|
||||
|
||||
def test_bundle_is_a_zip_without_bluetooth_addresses(self):
|
||||
@@ -98,9 +91,7 @@ class StarPortLogsHTTPTest(unittest.TestCase):
|
||||
self.server.server_close()
|
||||
|
||||
def request(self, path, *, method="GET", body=None, headers=None):
|
||||
# Bundles include the real bounded system report; allow cleanup and ZIP/HTTP delivery.
|
||||
timeout = system_snapshot.DEADLINE_SECONDS + 3 if path == "/api/starport/logs/bundle" else 2
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=timeout)
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2)
|
||||
try:
|
||||
connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **(headers or {})})
|
||||
response = connection.getresponse()
|
||||
@@ -116,14 +107,11 @@ class StarPortLogsHTTPTest(unittest.TestCase):
|
||||
|
||||
def test_requires_a_session_before_reading_anything(self):
|
||||
self.assertTrue(self.owner.configure("password123", lambda: True))
|
||||
with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing, \
|
||||
mock.patch.object(self.reader, "bundle", wraps=self.reader.bundle) as bundle:
|
||||
for path in ("/api/starport/logs", "/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"):
|
||||
self.assertEqual(self.request(path)[0], 401)
|
||||
with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing:
|
||||
self.assertEqual(self.request("/api/starport/logs")[0], 401)
|
||||
listing.assert_not_called()
|
||||
bundle.assert_not_called()
|
||||
|
||||
def test_list_file_and_bundle_downloads(self):
|
||||
def test_list(self):
|
||||
self.assertTrue(self.owner.configure("password123", lambda: True))
|
||||
cookie = {"Cookie": self.login()}
|
||||
status, body, headers = self.request("/api/starport/logs", headers=cookie)
|
||||
@@ -131,24 +119,13 @@ class StarPortLogsHTTPTest(unittest.TestCase):
|
||||
self.assertEqual(headers["Cache-Control"], "no-store")
|
||||
self.assertEqual(len(json.loads(body)["sessions"]), 2)
|
||||
|
||||
status, body, headers = self.request("/api/starport/logs/file/session-000001-20261004-221339.jsonl", headers=cookie)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(headers["Content-Disposition"], 'attachment; filename="session-000001-20261004-221339.jsonl"')
|
||||
self.assertEqual(body.decode(), SESSION)
|
||||
|
||||
status, body, headers = self.request("/api/starport/logs/bundle", headers=cookie)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(headers["Content-Type"], "application/zip")
|
||||
self.assertRegex(headers["Content-Disposition"], r'^attachment; filename="starpilot-starport-logs-\d{8}-\d{6}\.zip"$')
|
||||
with zipfile.ZipFile(io.BytesIO(body)) as archive:
|
||||
self.assertIn("REPORT.txt", archive.namelist())
|
||||
|
||||
def test_unknown_and_invalid_names(self):
|
||||
def test_logs_cannot_be_downloaded(self):
|
||||
self.assertTrue(self.owner.configure("password123", lambda: True))
|
||||
cookie = {"Cookie": self.login()}
|
||||
self.assertEqual(self.request("/api/starport/logs/file/notes.txt", headers=cookie)[0], 404)
|
||||
self.assertEqual(self.request("/api/starport/logs/file/..%2Fconfig.json", headers=cookie)[0], 400)
|
||||
self.assertEqual(self.request("/api/starport/logs/other", headers=cookie)[0], 404)
|
||||
with mock.patch.object(self.reader, "bundle") as bundle:
|
||||
for path in ("/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"):
|
||||
self.assertEqual(self.request(path, headers=cookie)[0], 404)
|
||||
bundle.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { StarPortLogSend, SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js"
|
||||
import { StarPortLogSend, SEND_URL, BLUETOOTH_SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js"
|
||||
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
|
||||
function fixture() {
|
||||
@@ -24,10 +24,10 @@ normal.client.start()
|
||||
assert.equal(normal.requests[0].url, SEND_URL)
|
||||
await normal.reply(0, { state: "idle", message: "", available: true })
|
||||
assert.equal(normal.states.at(-1).state, "idle")
|
||||
const sending = normal.client.send(" Black screen ")
|
||||
const sending = normal.client.send(" Black screen ", "starfan_42")
|
||||
assert.equal(normal.states.at(-1).state, "sending")
|
||||
assert.equal(normal.requests[1].options.method, "POST")
|
||||
assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen" })
|
||||
assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen", discord: "starfan_42" })
|
||||
await normal.reply(1, { state: "sending", message: "Collecting logs" }, 202)
|
||||
assert.equal(await sending, true)
|
||||
assert.equal(normal.timers.length, 1)
|
||||
@@ -40,13 +40,16 @@ assert.equal(normal.timers.length, 1)
|
||||
const limited = fixture()
|
||||
limited.client.start()
|
||||
await limited.reply(0, { state: "idle" })
|
||||
assert.equal(await limited.client.send("x".repeat(61)), false)
|
||||
assert.equal(await limited.client.send("x".repeat(61), "starfan_42"), false)
|
||||
assert.equal(limited.requests.length, 1)
|
||||
assert.match(limited.states.at(-1).error, /60 characters/)
|
||||
assert.equal(await limited.client.send(" "), false)
|
||||
assert.equal(await limited.client.send(" ", "starfan_42"), false)
|
||||
assert.equal(limited.requests.length, 1)
|
||||
assert.match(limited.states.at(-1).error, /short note/)
|
||||
const busy = limited.client.send("hi")
|
||||
assert.equal(await limited.client.send("hi", " @ "), false)
|
||||
assert.equal(limited.requests.length, 1)
|
||||
assert.match(limited.states.at(-1).error, /Discord username/)
|
||||
const busy = limited.client.send("hi", "starfan_42")
|
||||
await limited.reply(1, { error: "StarPort logs are already being sent." }, 409)
|
||||
assert.equal(await busy, false)
|
||||
assert.equal(limited.states.at(-1).error, "StarPort logs are already being sent.")
|
||||
@@ -56,7 +59,7 @@ const signedOut = fixture()
|
||||
signedOut.client.start()
|
||||
await signedOut.reply(0, {}, 401)
|
||||
assert.equal(signedOut.unauthorized, 1)
|
||||
assert.equal(await signedOut.client.send("hi"), false)
|
||||
assert.equal(await signedOut.client.send("hi", "starfan_42"), false)
|
||||
|
||||
// Sending unavailable on this build hides the card.
|
||||
const unset = fixture()
|
||||
@@ -88,7 +91,7 @@ assert.ok(interrupted.requests.every(({ options }) => options.method !== "POST")
|
||||
// An older status read cannot replace a send's newer status, even across navigation.
|
||||
const stale = fixture()
|
||||
stale.client.start()
|
||||
const pendingSend = stale.client.send("hello")
|
||||
const pendingSend = stale.client.send("hello", "starfan_42")
|
||||
await stale.reply(1, { state: "sending" }, 202)
|
||||
assert.equal(await pendingSend, true)
|
||||
await stale.reply(0, { state: "idle" })
|
||||
@@ -100,7 +103,7 @@ assert.equal(stale.unauthorized, 0)
|
||||
await stale.reply(3, { state: "sent" })
|
||||
assert.equal(stale.states.at(-1).state, "sent")
|
||||
|
||||
// A Discord username for a follow-up rides along only when given.
|
||||
// The Discord username is sent as typed; the device strips the @.
|
||||
{
|
||||
const followUp = fixture()
|
||||
followUp.client.start()
|
||||
@@ -108,4 +111,47 @@ assert.equal(stale.states.at(-1).state, "sent")
|
||||
followUp.client.send("No video", " @star.fan_42 ")
|
||||
assert.deepEqual(JSON.parse(followUp.requests[1].options.body), { message: "No video", discord: "@star.fan_42" })
|
||||
}
|
||||
|
||||
// The Bluetooth Log uses the same client with its own route and wording.
|
||||
{
|
||||
const requests = [], states = []
|
||||
const client = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable",
|
||||
publish: (state) => states.push(state), fetcher: (url) => { requests.push(url); return Promise.reject(new TypeError("offline")) },
|
||||
schedule: () => 1, cancel: () => {} })
|
||||
client.start()
|
||||
await flush()
|
||||
assert.equal(requests[0], "./api/controllers/log/send")
|
||||
assert.equal(states.at(-1).error, "offline")
|
||||
const failing = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable",
|
||||
publish: (state) => states.push(state), fetcher: () => Promise.resolve({ ok: false, status: 503, json: async () => ({}) }),
|
||||
schedule: () => 1, cancel: () => {} })
|
||||
failing.start()
|
||||
await flush()
|
||||
assert.equal(states.at(-1).error, "Sending the Bluetooth Log is unavailable")
|
||||
}
|
||||
|
||||
// Clicking Send with an empty field outlines it like the theme maker's save prompt, without sending.
|
||||
{
|
||||
const { LogSendCard } = await import("../web/js/starport-logs.js")
|
||||
const sent = [], focused = []
|
||||
const card = { ...LogSendCard.data(), feed: { send: async (...args) => { sent.push(args); return true } },
|
||||
$refs: { note: { focus: () => focused.push("note") }, discord: { focus: () => focused.push("discord") } } }
|
||||
const submit = LogSendCard.methods.submit.bind(card)
|
||||
await submit()
|
||||
assert.deepEqual(card.missing, ["note", "discord"])
|
||||
assert.deepEqual(focused, ["note"])
|
||||
card.note = "No pad"
|
||||
LogSendCard.watch.note.call(card, card.note)
|
||||
assert.deepEqual(card.missing, ["discord"])
|
||||
card.discord = "@"
|
||||
await submit()
|
||||
assert.deepEqual(card.missing, ["discord"])
|
||||
assert.equal(sent.length, 0)
|
||||
card.discord = "starfan_42"
|
||||
await submit()
|
||||
assert.deepEqual(card.missing, [])
|
||||
assert.deepEqual(sent, [["No pad", "starfan_42"]])
|
||||
assert.equal(card.note, "")
|
||||
assert.match(LogSendCard.template, /gx-field--required/)
|
||||
}
|
||||
console.log("StarPort log send: Discord follow-up passed")
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
"""Send StarPort Logs: the Discord upload, its per-device thread cache, the background job and its routes."""
|
||||
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
@@ -18,45 +16,7 @@ from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.starport_send import (DISCORD_FILE_LIMIT, MESSAGE_LIMIT, SendBusy, SendRejected, StarPortLogSender,
|
||||
clean_discord, clean_message, send, thread_title)
|
||||
|
||||
URL = "https://discord.example/api/webhooks/1/token"
|
||||
SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio",
|
||||
"branch": "Dom", "commit": "abcdef1234567890"}
|
||||
|
||||
|
||||
class WithSummaryTest(unittest.TestCase):
|
||||
def test_adds_summary_to_bundle(self):
|
||||
source = io.BytesIO()
|
||||
with zipfile.ZipFile(source, "w") as archive:
|
||||
archive.writestr("REPORT.txt", "report")
|
||||
seen = []
|
||||
|
||||
def bundle(**kwargs):
|
||||
seen.append(kwargs)
|
||||
return "logs.zip", source.getvalue()
|
||||
name, data = starport_send.with_summary(bundle, lambda: {**SUMMARY, "setup": "adapter", "repo": "starpilothq/openpilot"})(system_snapshot=False)
|
||||
self.assertEqual((name, seen), ("logs.zip", [{"system_snapshot": False}]))
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
self.assertEqual(archive.read("REPORT.txt"), b"report")
|
||||
text = archive.read("SUMMARY.txt").decode()
|
||||
for line in ("Car: HONDA_CIVIC_2022", "Head unit: Honda Display Audio", "Setup: adapter", "Branch Dom @ abcdef1234"):
|
||||
self.assertIn(line, text)
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status_code=200, body=None):
|
||||
self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"}
|
||||
|
||||
def json(self):
|
||||
return self.body
|
||||
|
||||
|
||||
class Poster:
|
||||
def __init__(self, *responses):
|
||||
self.responses, self.calls = list(responses), []
|
||||
|
||||
def __call__(self, url, data, files, timeout):
|
||||
self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files})
|
||||
return self.responses.pop(0)
|
||||
from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response
|
||||
|
||||
|
||||
def query(call):
|
||||
@@ -70,7 +30,7 @@ class SendTest(unittest.TestCase):
|
||||
self.threads = Path(temporary.name)
|
||||
|
||||
def send(self, post, note="Dropped at the light", data=b"zip"):
|
||||
return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads)
|
||||
return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads, discord="starfan_42")
|
||||
|
||||
def test_first_send_opens_a_device_thread_and_later_sends_reuse_it(self):
|
||||
first = Poster(Response(body={"channel_id": "555"}))
|
||||
@@ -112,7 +72,7 @@ class SendTest(unittest.TestCase):
|
||||
self.send(poster, data=b"x" * (DISCORD_FILE_LIMIT + 1))
|
||||
self.assertEqual(poster.calls, [])
|
||||
with self.assertRaisesRegex(SendRejected, "isn't set up"):
|
||||
send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads)
|
||||
send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads, discord="starfan_42")
|
||||
|
||||
def test_message_is_limited_and_single_line(self):
|
||||
self.assertEqual(MESSAGE_LIMIT, 60)
|
||||
@@ -154,7 +114,7 @@ class SenderJobTest(unittest.TestCase):
|
||||
|
||||
job = StarPortLogSender(bundle, sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
|
||||
try:
|
||||
self.assertEqual(job.start("hello")["state"], "sending")
|
||||
self.assertEqual(job.start("hello", "starfan_42")["state"], "sending")
|
||||
self.assertTrue(sending.wait(2))
|
||||
self.assertEqual(job.status()["state"], "sending")
|
||||
self.assertEqual(sent, [])
|
||||
@@ -167,7 +127,7 @@ class SenderJobTest(unittest.TestCase):
|
||||
self.assertEqual(status["state"], "sent")
|
||||
self.assertIn("snapshot was left out", status["message"])
|
||||
self.assertEqual(bundles, [True, False])
|
||||
self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": ""})])
|
||||
self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": "starfan_42"})])
|
||||
|
||||
def test_one_send_at_a_time_and_failures_are_reported(self):
|
||||
release = threading.Event()
|
||||
@@ -177,9 +137,9 @@ class SenderJobTest(unittest.TestCase):
|
||||
raise SendRejected("Discord refused the logs (HTTP 500).")
|
||||
|
||||
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
|
||||
job.start("first")
|
||||
job.start("first", "starfan_42")
|
||||
with self.assertRaises(SendBusy):
|
||||
job.start("again")
|
||||
job.start("again", "starfan_42")
|
||||
release.set()
|
||||
self.assertEqual(self.wait(job), {"state": "failed", "message": "Discord refused the logs (HTTP 500).", "available": True,
|
||||
"fork": False, "messageLimit": 60})
|
||||
@@ -237,26 +197,25 @@ class SendHTTPTest(unittest.TestCase):
|
||||
status, body, _ = self.request("/api/starport/logs/send", headers={"Cookie": cookie})
|
||||
self.assertEqual((status, json.loads(body)["state"]), (200, "idle"))
|
||||
|
||||
status, body, _ = self.post({"message": "Black screen after unlock"}, cookie)
|
||||
status, body, _ = self.post({"message": "Black screen after unlock", "discord": "starfan_42"}, cookie)
|
||||
self.assertEqual((status, json.loads(body)["state"]), (202, "sending"))
|
||||
self.job.start.assert_called_once_with("Black screen after unlock", "")
|
||||
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 202)
|
||||
self.job.start.assert_called_with("hi", "starfan_42")
|
||||
self.job.start.assert_called_once_with("Black screen after unlock", "starfan_42")
|
||||
|
||||
self.assertEqual(self.post({"message": "hi", "extra": 1}, cookie)[0], 400)
|
||||
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400)
|
||||
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400)
|
||||
self.assertEqual(self.job.start.call_count, 1)
|
||||
self.job.start.side_effect = SendRejected("Keep the message to 60 characters.")
|
||||
self.assertEqual(self.post({"message": "x" * 61}, cookie)[0], 400)
|
||||
self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400)
|
||||
self.job.start.side_effect = SendBusy("StarPort logs are already being sent.")
|
||||
self.assertEqual(self.post({"message": "hi"}, cookie)[0], 409)
|
||||
self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409)
|
||||
|
||||
|
||||
|
||||
class DiscordFollowUpTest(unittest.TestCase):
|
||||
def test_a_handle_is_optional_and_checked(self):
|
||||
self.assertEqual(clean_discord(""), "")
|
||||
def test_a_handle_is_required_and_checked(self):
|
||||
self.assertEqual(clean_discord(" @star.fan_42 "), "star.fan_42")
|
||||
self.assertEqual(clean_discord("OldName#1234"), "OldName#1234")
|
||||
for bad in ("x", "has space", "<@123>", "a" * 33, 5):
|
||||
for bad in ("", " ", "@", "x", "has space", "<@123>", "a" * 33, 5):
|
||||
with self.assertRaises(SendRejected):
|
||||
clean_discord(bad)
|
||||
|
||||
@@ -267,14 +226,12 @@ class DiscordFollowUpTest(unittest.TestCase):
|
||||
payload = post.calls[0]["payload"]
|
||||
self.assertIn("Follow-up: Discord `star.fan_42`", payload["content"])
|
||||
self.assertEqual(payload["allowed_mentions"], {"parse": []})
|
||||
post = Poster(Response())
|
||||
send(b"zip", "logs.zip", "", SUMMARY, url=URL, post=post, thread_dir=Path(directory))
|
||||
self.assertIn("Follow-up: not requested", post.calls[0]["payload"]["content"])
|
||||
|
||||
def test_a_bad_handle_is_refused_before_anything_is_sent(self):
|
||||
def test_a_missing_or_bad_handle_is_refused_before_anything_is_sent(self):
|
||||
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=mock.Mock(), summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
|
||||
with self.assertRaises(SendRejected):
|
||||
job.start("hi", "not a handle")
|
||||
for handle in ("not a handle", ""):
|
||||
with self.assertRaises(SendRejected):
|
||||
job.start("hi", handle)
|
||||
self.assertIsNone(job._thread)
|
||||
|
||||
def test_a_failed_fork_check_is_raised_and_retried(self):
|
||||
@@ -292,7 +249,6 @@ class DiscordFollowUpTest(unittest.TestCase):
|
||||
("https://evil.com/github.com/StarPilotHQ/StarPilot", "other"), ("", "unknown"), (None, "unknown")):
|
||||
self.assertEqual(repo_name(origin), repo, origin)
|
||||
self.assertTrue(is_official_repo("StarPilotHQ/StarPilot"))
|
||||
self.assertTrue(is_official_repo("starpilothq/openpilot"))
|
||||
self.assertFalse(is_official_repo("dirwin31/openpilot"))
|
||||
|
||||
sender = mock.Mock(return_value=None)
|
||||
@@ -300,7 +256,7 @@ class DiscordFollowUpTest(unittest.TestCase):
|
||||
official=lambda: False)
|
||||
self.assertEqual(job.status()["fork"], True)
|
||||
self.assertEqual(job.status()["available"], True)
|
||||
job.start("hi")
|
||||
job.start("hi", "starfan_42")
|
||||
job._thread.join(2)
|
||||
self.assertEqual(job.status()["state"], "sent")
|
||||
sender.assert_called_once()
|
||||
|
||||
@@ -65,7 +65,7 @@ try {
|
||||
|
||||
// Compile the changed page templates to catch invalid nesting or Vue directives.
|
||||
for (const name of ['models', 'settings', 'navigation', 'starport', 'spotify', 'bluetooth', 'cameras',
|
||||
'home', 'system-monitor', 'sentry', 'vasm', 'pip', 'galaxy', 'networks', 'tools', 'logs', 'log-help', 'software-status', 'driving',
|
||||
'home', 'system-monitor', 'sentry', 'vasm', 'pip', 'galaxy', 'networks', 'tools', 'logs', 'software-status', 'driving',
|
||||
'longitudinal-curves', 'flm', 'record-history', 'onroad-layout-template', 'settings-recovery', 'diagnostic-tools']) {
|
||||
const source = readFileSync(new URL(`../web/js/${name}.js`, import.meta.url), 'utf8')
|
||||
const templates = [...source.matchAll(/(?:template:\s*|ONROAD_LAYOUT_TEMPLATE = )`([\s\S]*?)`/g)]
|
||||
|
||||
@@ -939,14 +939,11 @@ background: var(--glass-bg-hover);
|
||||
.gx-crash-preview { margin-top: var(--sp-3); }
|
||||
.gx-crash-preview__head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); overflow-wrap: anywhere; }
|
||||
.gx-starport-logs { width: min(100%, 960px); margin-inline: auto; }
|
||||
.gx-starport-logs__format { padding: 2px 7px; border-radius: var(--radius-full); background: rgba(255, 255, 255, .16); font-size: var(--fs-xs); letter-spacing: .04em; }
|
||||
.gx-starport-log-list { display: grid; gap: var(--sp-3); }
|
||||
.gx-starport-log { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--sp-4); margin: 0; padding: var(--sp-4); cursor: default; }
|
||||
.gx-starport-log__body { display: grid; gap: var(--sp-1); min-width: 0; }
|
||||
.gx-starport-log__body strong { line-height: 1.35; overflow-wrap: anywhere; }
|
||||
.gx-starport-log__body span { color: var(--text-muted); font-size: var(--fs-sm); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.gx-starport-log__download { flex: none; width: var(--touch-target); height: var(--touch-target); border: 1px solid var(--glass-border); background: var(--primary-container); color: var(--on-primary-container); }
|
||||
.gx-starport-log__download:hover { background: var(--primary); color: var(--on-primary); }
|
||||
.gx-starport-logs__section-title { margin: var(--sp-6) 0 var(--sp-3); }
|
||||
.gx-starport-send__fork { justify-content: center; text-align: center; margin-block: var(--sp-4); }
|
||||
.gx-starport-send__fork .gx-alert__body { flex: 0 1 auto; }
|
||||
@@ -1474,9 +1471,9 @@ background: var(--surface-container-high); color: var(--on-surface-variant); bor
|
||||
.gx-starport-wiki[open] > summary::before { transform: rotate(90deg); }
|
||||
.gx-starport-wiki > summary:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; border-radius: var(--radius-sm); }
|
||||
.gx-starport-wiki p, .gx-starport-wiki ol, .gx-starport-wiki ul { margin: var(--sp-3) 0 0; }
|
||||
.gx-starport-wiki ol, .gx-starport-wiki ul, .gx-starport-mirror-steps, .gx-log-help__claim-steps { padding-left: 1.3em; display: grid; gap: var(--sp-1); }
|
||||
.gx-starport-wiki ol, .gx-starport-wiki ul, .gx-starport-mirror-steps { padding-left: 1.3em; display: grid; gap: var(--sp-1); }
|
||||
.gx-starport-wiki ul { list-style: disc; }
|
||||
.gx-starport-mirror-steps, .gx-log-help__claim-steps { margin: 0; }
|
||||
.gx-starport-mirror-steps { margin: 0; }
|
||||
.gx-card.gx-starport-sheet__dialog {
|
||||
position: fixed;
|
||||
inset: max(20px, env(safe-area-inset-top, 0px)) 0 max(20px, env(safe-area-inset-bottom, 0px));
|
||||
@@ -1590,14 +1587,6 @@ border-top: 1px solid var(--outline-variant);
|
||||
@media (prefers-reduced-motion: reduce) { .gx-update-progress__fill--indeterminate { width: 100%; animation: none; opacity: .6; } }
|
||||
.gx-panel { padding: var(--panel-padding); min-width: 0; }
|
||||
.gx-card.gx-panel > .gx-section__header { margin: calc(-1 * var(--panel-padding)) calc(-1 * var(--panel-padding)) var(--sp-4); }
|
||||
.gx-connection-logs.gx-panel > .gx-section__header { margin-bottom: 0; }
|
||||
.gx-connection-logs .gx-log-form { display: grid; gap: var(--sp-3); margin-top: var(--sp-3); }
|
||||
.gx-log-form .gx-field { width: 100%; box-sizing: border-box; }
|
||||
.gx-log-form p { margin: 0; }
|
||||
.gx-log-form .gx-btn { justify-self: start; }
|
||||
@media (max-width: 600px) {
|
||||
.gx-connection-logs .gx-log-form .gx-btn, .gx-connection-logs details > summary.gx-btn { width: 100%; box-sizing: border-box; }
|
||||
}
|
||||
.gx-panel > :first-child { margin-top: 0; }
|
||||
.gx-panel > :last-child { margin-bottom: 0; }
|
||||
.gx-panel-footer { padding: 0 var(--panel-padding) var(--panel-padding); }
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
.gx-log-help { width: min(100%, 960px); margin-inline: auto; }
|
||||
.gx-log-help__tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--sp-3); }
|
||||
@media (max-width: 720px) {
|
||||
.gx-log-help__tabs { grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); }
|
||||
}
|
||||
.gx-card.gx-log-help__tab {
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--on-surface);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
min-height: 64px;
|
||||
min-width: 0;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border: 1px solid var(--glass-border);
|
||||
transition: background-color var(--motion-fast), border-color var(--motion-fast);
|
||||
}
|
||||
.gx-card.gx-log-help__tab:hover { background: var(--glass-bg-hover); }
|
||||
.gx-card.gx-log-help__tab--active { background: var(--primary-container); border-color: var(--primary); }
|
||||
.gx-log-help__tab-icon {
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--radius-sm);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--surface-container-high);
|
||||
color: var(--primary);
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
.gx-log-help__tab--active .gx-log-help__tab-icon { background: var(--primary); color: var(--on-primary); }
|
||||
.gx-log-help__tab-text { display: grid; gap: 2px; min-width: 0; }
|
||||
.gx-log-help__tab-text strong { font-size: var(--fs-base); line-height: 1.3; overflow-wrap: anywhere; }
|
||||
.gx-log-help__tab-text small { color: var(--text-muted); font-size: var(--fs-xs); line-height: 1.35; overflow-wrap: anywhere; }
|
||||
.gx-log-help__card > .gx-section__header > div { flex: 1 1 12rem; min-width: 0; }
|
||||
.gx-log-help__card > .gx-section__header p { margin: 2px 0 0; }
|
||||
.gx-connection-logs > .gx-section__header > .gx-btn { margin-left: auto; flex: none; }
|
||||
.gx-log-help__callout {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--sp-3);
|
||||
align-items: start;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--glass-border);
|
||||
background: var(--surface-container);
|
||||
}
|
||||
.gx-log-help__callout > i { color: var(--primary); font-size: 1.1rem; margin-top: 2px; }
|
||||
.gx-log-help__callout p { margin: 0; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.gx-log-help__group { display: grid; gap: var(--sp-2); min-width: 0; }
|
||||
.gx-log-help__group .gx-field { width: 100%; box-sizing: border-box; }
|
||||
.gx-log-help__label { font-size: var(--fs-sm); font-weight: var(--fw-bold); color: var(--on-surface); }
|
||||
.gx-log-help__pills { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
|
||||
.gx-log-help__pills > button.gx-chip { min-height: var(--touch-target); padding: 0 var(--sp-4); font-size: var(--fs-sm); }
|
||||
.gx-log-help__pills > button.gx-chip.gx-chip--selected { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
|
||||
.gx-log-help__attaches {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-2);
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.gx-log-help__attaches > i { color: var(--secondary); flex: none; margin-top: 2px; }
|
||||
.gx-log-help__ready {
|
||||
padding: var(--sp-4);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--primary);
|
||||
background: var(--primary-container);
|
||||
}
|
||||
.gx-log-help__ready p { margin: 0; }
|
||||
.gx-log-help__sessions { border-top: 1px solid var(--outline); padding-top: var(--sp-2); }
|
||||
.gx-log-help__sessions > summary {
|
||||
cursor: pointer;
|
||||
min-height: var(--touch-target);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
font-weight: var(--fw-medium);
|
||||
color: var(--on-surface-variant);
|
||||
}
|
||||
.gx-log-help__sessions-body { padding-top: var(--sp-3); }
|
||||
.gx-log-help__discord { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); flex-wrap: wrap; }
|
||||
.gx-log-help__discord-copy { display: flex; align-items: flex-start; gap: var(--sp-3); flex: 1 1 16rem; min-width: 0; }
|
||||
.gx-log-help__discord-copy > i { color: var(--primary); font-size: 1.35rem; flex: none; margin-top: 2px; }
|
||||
.gx-log-help__discord-copy h3 { margin: 0 0 4px; font-size: var(--fs-base); }
|
||||
.gx-log-help__discord-copy p { margin: 0; overflow-wrap: anywhere; }
|
||||
@media (max-width: 560px) {
|
||||
.gx-log-help__card > .gx-actions > .gx-btn,
|
||||
.gx-log-help__ready > .gx-actions > .gx-btn,
|
||||
.gx-log-help__discord > .gx-btn { flex: 1 1 100%; justify-content: center; }
|
||||
}
|
||||
@@ -554,7 +554,7 @@ input[type="range"].gx-slider:active::-moz-range-thumb {
|
||||
.gx-layout__color-values input[type="text"] { min-width: 0; width: 100%; font-family: ui-monospace, monospace; }
|
||||
.gx-layout__color input[type="range"] { width: 100%; accent-color: var(--primary); min-height: 36px; }
|
||||
.gx-layout__color > label { color: var(--on-surface-variant); }
|
||||
.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); }
|
||||
.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog, .gx-field.gx-field--required { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); }
|
||||
/* One workspace structure at every size; panels replace long stacked controls. */
|
||||
.gx-layout { max-width: 1440px; margin-inline: auto; gap: 12px; }
|
||||
.gx-layout__workspace { grid-template-columns: minmax(0, 1.4fr) minmax(320px, 1fr); gap: 16px; }
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
{
|
||||
"mode": "offline-preview",
|
||||
"tools": [
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Cameras & Monitoring",
|
||||
"path": "/cameras",
|
||||
@@ -32,27 +39,11 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Galaxy Access & Connections",
|
||||
"name": "Galaxy Access & Install",
|
||||
"path": "/galaxy",
|
||||
"icon": "bi-globe2",
|
||||
"description": "Remote access, app setup, networks, Bluetooth, and support",
|
||||
"availability": "local-only",
|
||||
"children": [
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
}
|
||||
]
|
||||
"description": "Pair for remote access, install Galaxy, or set up a Wi-Fi hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Logs & Diagnostics",
|
||||
@@ -76,6 +67,20 @@
|
||||
"description": "Read local reports",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Bluetooth Log",
|
||||
"path": "/logs/bluetooth",
|
||||
"icon": "bi-controller",
|
||||
"description": "Send a USB and Bluetooth controller report",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "StarPort Logs",
|
||||
"path": "/logs/starport",
|
||||
"icon": "bi-phone",
|
||||
"description": "Session logs and a download for bug reports",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "tmux Live View",
|
||||
"path": "/logs/tmux",
|
||||
@@ -98,10 +103,10 @@
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Get help",
|
||||
"name": "Help & Community",
|
||||
"path": "/logs/help",
|
||||
"icon": "bi-life-preserver",
|
||||
"description": "Send StarPort, phone app, or controller logs, or ask on Discord",
|
||||
"description": "Guides and community help",
|
||||
"availability": "always"
|
||||
}
|
||||
]
|
||||
@@ -143,6 +148,13 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "System Tools",
|
||||
"path": "/system",
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
<link rel="manifest" href="./manifest.webmanifest" crossorigin="use-credentials">
|
||||
<link rel="stylesheet" href="./vendor/bootstrap-icons/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="./css/galaxy.css">
|
||||
<link rel="stylesheet" href="./css/log-help.css">
|
||||
<link rel="stylesheet" href="./css/setup.css">
|
||||
<link rel="stylesheet" href="./css/settings.css">
|
||||
<link rel="stylesheet" href="./css/navigation.css">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user