Compare commits

...

17 Commits

Author SHA1 Message Date
natehuby76 944e513e9f add official testing instructions to comma support 2026-11-25 01:16:59 -05:00
natehuby76 13ab471cc5 open private staff actions in older report threads 2026-11-25 01:02:49 -05:00
firestar5683 72aa8b89e1 Test Galaxy layout schema version 17 2026-11-25 00:01:06 -06:00
natehuby76 14babc867a open staff actions from the saved referral 2026-11-25 00:45:41 -05:00
natehuby76 69acfbb085 open staff actions privately from a ticket command 2026-11-25 00:41:25 -05:00
natehuby76 d4ddf420a5 match ticket colors and link fixes to testing requests 2026-11-25 00:33:35 -05:00
Raymond Nguyen 73eb7961d7 Honda Accord: angle steering for the modified EPS firmware 2026-11-24 23:29:49 -06:00
natehuby76 273f8b12e8 explain moved tickets to the reporter 2026-11-25 00:28:03 -05:00
natehuby76 cc36b77b65 share referral replies in the companion bot thread 2026-11-25 00:27:22 -05:00
natehuby76 3ab9f67c83 register the companion referral message command 2026-11-25 00:20:37 -05:00
firestar5683 df47158568 Fix Galaxy and C4 static analysis regressions 2026-11-24 23:11:51 -06:00
natehuby76 bc68e381ae recover companion referrals and confirm phone platform 2026-11-25 00:07:39 -05:00
Prabhaav Pillai f15af75c3a Adj Spot Monitoring for C4 2026-11-25 00:02:35 -05:00
natehuby76 1868dd0b90 update galaxy reporting and companion bot 2026-11-25 00:01:25 -05:00
Raymond Nguyen b51d18fd56 honda: tidy the Accord carcontroller
Drop an extra blank line and a comment about an older tree; the prebuilt
receipt is refreshed for the source change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:44:47 -08:00
Raymond Nguyen ac77f9a20c honda: rebuild the panda firmware for the Accord angle setpoint check
Built from 25323cef46 with the ARM64 device build container (DEBUG cert, as the
tracked images are), and the prebuilt receipt refreshed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:26:38 -08:00
Raymond Nguyen 25323cef46 Honda Accord: angle steering for the modified EPS firmware
The 2020 Accord with EPS firmware 39990-TVA,A16C takes an angle setpoint in the
steering message. openpilot sends the setpoint, limited last by the 3.589 m/s^2
lateral acceleration and jerk limits, and the panda blocks any angle frame that
exceeds them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:22:01 -08:00
117 changed files with 5020 additions and 391 deletions
+8 -1
View File
@@ -16,7 +16,8 @@ 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 nidec_bus0_topology, normal_bus_topology as honda_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.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
@@ -215,6 +216,12 @@ 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
@@ -1,3 +1,5 @@
import math
import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF
@@ -10,9 +12,12 @@ 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):
@@ -120,6 +125,54 @@ 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:
@@ -176,7 +229,12 @@ class CarController(CarControllerBase):
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
# Send steering command.
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
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))
if _projection is not None:
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1])
@@ -286,6 +344,9 @@ 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,6 +13,7 @@ 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,
@@ -120,6 +121,16 @@ 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,4 +1,5 @@
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
@@ -30,3 +31,9 @@ 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)
+6 -2
View File
@@ -117,11 +117,15 @@ 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):
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.
values = {
"STEER_TORQUE": apply_torque if lkas_active else 0,
"STEER_TORQUE": apply_torque if (lkas_active or angle_arm is not None) 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
+24 -2
View File
@@ -7,7 +7,9 @@ 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
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.carcontroller import CarController
from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.radar_interface import RadarInterface
@@ -100,7 +102,12 @@ 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]
modified_eps = any(b"," in fw.fwVersion for fw in eps_observations)
# 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)
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)
@@ -121,6 +128,21 @@ 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
+6 -1
View File
@@ -37,8 +37,11 @@ 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_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR |
HondaFlags.EPS_ANGLE_LOOP_FW | HondaFlags.EPS_FW_UNREAD)
_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)
@@ -102,6 +105,8 @@ 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,9 +39,11 @@ def test_mixed_nonlogging_eps_still_refuses_modified_profile(other):
assert not cp.flags & HondaFlags.EPS_MODIFIED
def test_recorded_custom_angle_eps_remains_unsupported_in_mainline():
def test_recorded_custom_angle_eps_steers_by_angle():
cp = params(CAR.HONDA_ACCORD, [eps(ANGLE), eps(SERIAL, logging=True)])
assert cp.dashcamOnly
assert not cp.dashcamOnly
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
assert not cp.flags & HondaFlags.EPS_MODIFIED
@@ -0,0 +1,364 @@
"""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,5 +1,6 @@
import json
from pathlib import Path
from types import SimpleNamespace
import unittest
from unittest.mock import patch
@@ -33,6 +34,32 @@ 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()
+74
View File
@@ -1,11 +1,14 @@
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
@@ -41,6 +44,27 @@ 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,
@@ -92,6 +116,7 @@ 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.
@@ -121,6 +146,55 @@ 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
@@ -2,6 +2,7 @@ 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
@@ -206,6 +207,7 @@ 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";
+71 -1
View File
@@ -34,6 +34,8 @@ 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;
@@ -101,6 +103,23 @@ 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();
@@ -111,6 +130,14 @@ 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))) ||
@@ -317,6 +344,40 @@ 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) {
@@ -381,6 +442,7 @@ 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;
@@ -426,7 +488,14 @@ static safety_config honda_nidec_init(uint16_t param) {
return ret;
}
static safety_config honda_bosch_init(uint16_t param) {
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;
honda_mvl_stock = ((param == 80U) || (param == 81U)) && ((alternative_experience == 0) || (alternative_experience == 32));
honda_mvl_buttons_fresh = 0U;
honda_interceptor_reset(false);
@@ -614,6 +683,7 @@ 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,
@@ -0,0 +1,279 @@
#!/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()
@@ -16,6 +16,7 @@ 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
@@ -357,6 +358,9 @@ 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,6 +1,7 @@
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
@@ -14,7 +15,11 @@ 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.
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai")
# 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
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
angle_log = log.ControlsState.LateralAngleState.new_message()
@@ -26,6 +31,9 @@ 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:
@@ -0,0 +1,121 @@
"""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,12 +607,13 @@ int main() {
unsupported.safety_param ^= 0x1U;
assert(!aol_capable(unsupported, TEST_MODE, TEST_REGISTRY));
for (uint16_t word = 0U; word < 4096U; ++word) {
for (uint16_t word = 0U; word < 8192U; ++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;
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;
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;
@@ -12,6 +12,7 @@ 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
@@ -162,6 +163,18 @@ 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']
+2 -1
View File
@@ -11,7 +11,8 @@ 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 == 1058U) || (param == 1059U) || (param == 1570U) || (param == 1571U) || (param == 2082U) || (param == 2083U) || (param == 2211U) ||
(param == 4096U) || (param == 4097U) || (param == 6178U) || (param == 6179U);
}
inline bool honda_nidec_aol_param(uint16_t param) {
+1 -1
View File
@@ -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 https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/")
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
self.end_headers()
if self.command != 'HEAD':
self.wfile.write(body)
@@ -0,0 +1,199 @@
"""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. Continue to post your report 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.")
+38 -40
View File
@@ -1,6 +1,7 @@
"""Galaxy settings, device services and software management."""
import argparse
import base64
import hashlib
from contextlib import nullcontext
from http.cookies import SimpleCookie
@@ -99,7 +100,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, hotspot=None, toyota_tools=None,
local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, log_relay_stager=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
@@ -165,6 +166,23 @@ 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
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
source = starport_logs()
log_relay_stager_source = LogRelayStager(
source.bundle,
lambda: base64.b64decode(connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)['zipBase64']),
lambda: base64.b64decode(controller_capture()['zipBase64']),
)
return log_relay_stager_source
software_source = software
software_operations_source = software_operations
software_lock = threading.Lock()
@@ -1018,6 +1036,13 @@ 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())
@@ -1753,7 +1778,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/companion/support-ticket',
'/api/starport/logs/send', '/api/logs/stage',
'/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',
@@ -1770,7 +1795,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
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/bluetooth/', '/api/logs/',
'/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
@@ -1828,50 +1853,23 @@ 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/companion/support-ticket':
import requests
if path == '/api/logs/stage':
identity = self.settings_session()
if identity is None:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if (not isinstance(payload, dict) or not isinstance(payload.get('code'), str) or
not re.fullmatch(r'[0-9a-f]{16}', payload['code']) or payload.get('action') not in ('check', 'send')):
self.json(400, {'error': 'Enter the code from the Discord request.'})
return
relay = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/device'
def relay_post(body):
response = requests.post(relay, json=body, allow_redirects=False, timeout=(5, 30))
if response.status_code == 410:
raise LookupError()
response.raise_for_status()
if response.status_code != 200:
raise ValueError()
return response.json()
from openpilot.starpilot.galaxy.log_relay_stage import StageBusy, StageRejected
try:
code = payload['code']
ticket = relay_post({'action': 'check', 'code': code})
kind = ticket['kind']
if kind not in ('controller', 'connection'):
raise ValueError()
if payload['action'] == 'check':
self.json(200, {'kind': kind, 'title': ticket['title']})
return
if kind == 'controller':
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
capture = controller_capture()
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:
capture = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
if self.settings_session() != identity:
self.json(401, {'error': 'Sign in to Galaxy'})
return
result = relay_post({'action': 'send', 'code': code, 'archive': capture['zipBase64']})
if result.get('sent') is not True:
raise ValueError()
self.json(200, {'sent': True})
except LookupError:
self.json(410, {'error': 'Code expired or incorrect. Reopen the request in Discord.'})
except (requests.RequestException, OSError, RuntimeError, TypeError, ValueError):
self.json(503, {'error': 'Could not confirm delivery. Check the comma internet connection and your Discord thread.'})
return
if path == '/api/settings/flm-finding/accept':
identity = self.settings_session()
@@ -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 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.',
'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.',
'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.',
@@ -0,0 +1,157 @@
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) })
@@ -24,6 +24,9 @@ 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' },
@@ -44,6 +47,7 @@ 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)])]
@@ -81,6 +85,8 @@ 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')
@@ -93,14 +99,19 @@ const { resolve } = require('node:path')
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`)
}
await page.setViewportSize({ width: 1280, height: 900 })
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
const desktop = await page.locator('.gx-starport-logs').evaluate(section => {
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, 'StarPort logs are centered and readable on desktop')
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'Log help is 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()
@@ -5,11 +5,13 @@ import json
from pathlib import Path
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
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
@@ -25,12 +27,25 @@ 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)
tmux_live=self.console, settings=self.settings, log_relay_stager=self.stager)
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)
@@ -57,7 +72,7 @@ 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'):
for path in ('/api/local-access', '/api/local-access/capture', '/api/tmux/live', '/api/troubleshoot', '/api/logs/stage'):
self.assertEqual(self.request(path, remote=True)[0], 401)
self.assertEqual(self.calls, [])
status, _, self.cookie = self.request('/api/auth/session')
@@ -73,21 +88,35 @@ class DiagnosticHTTPTest(unittest.TestCase):
self.assertNotEqual(self.request('/api/tmux/live', method='POST', payload={})[0], 200)
self.assertEqual(len(self.calls), before)
def test_support_code_captures_on_device_and_confirms_delivery(self):
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')
code = 'ab12' * 4
path = '/api/companion/support-ticket'
def post(action):
return self.request(path, method='POST', payload={'code': code, 'action': action})
ticket = Mock(status_code=200)
ticket.json.return_value = {'title': 'Lost network', 'kind': 'connection'}
receipt = Mock(status_code=200)
receipt.json.return_value = {'sent': True}
with patch('requests.post', side_effect=[ticket, ticket, receipt]) as relay:
self.assertEqual(post('check')[:2], (200, {'kind': 'connection', 'title': 'Lost network'}))
self.assertEqual(post('send')[:2], (200, {'sent': True}))
self.assertTrue(relay.call_args.kwargs['json']['archive'].startswith('UEsD'))
self.assertFalse(relay.call_args.kwargs['allow_redirects'])
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)
@@ -69,43 +69,48 @@ assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
compile(GalaxyPage.template, { decodeEntities: value => value.replaceAll('&amp;', '&') })
console.log('Galaxy local access remains independent of app installation')
const capture = { onUnauthorized() { assert.fail('unexpected sign-in request') },
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.captureConnectionLogs()
assert.equal(capture.capture.type, 'application/zip')
assert.equal(capture.captureRequest, null)
capture.resetCapture()
assert.equal(capture.capture, null)
} finally { globalThis.fetch = originalFetch }
const thread = { ...ConnectionLogs.data(), ...ConnectionLogs.methods, supportCode: 'AB12 CD34-EF56' }
try {
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/companion/support-ticket')
const { action, code } = JSON.parse(options.body)
assert.equal(code, 'ab12cd34ef56')
const body = action === 'check' ? { title: 'Lost network', kind: 'connection' } : { sent: true }
return { ok: true, json: async () => body }
assert.equal(url, './api/controllers/log/capture')
assert.equal(options.credentials, 'same-origin')
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
}
await thread.threadAction('check')
assert.equal(thread.supportTicket.title, 'Lost network')
assert.equal(thread.supportSent, false)
await thread.threadAction('send')
assert.equal(thread.supportSent, true)
} finally { globalThis.fetch = originalFetch }
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 to existing Discord thread'))
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#submit-logs-through-discord'))
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#report-a-problem-through-discord'))
assert.match(ConnectionLogs.template, /<details[^>]*><summary><small>Manual ZIP download<\/small><\/summary>[\s\S]*Download ZIP<\/button>\s*<\/details>/)
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 {
@@ -0,0 +1,137 @@
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("&amp;", "&") })
compile(Logs.template, { decodeEntities: v => v.replaceAll("&amp;", "&") })
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")
@@ -0,0 +1,279 @@
"""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, 16)
for (const version of [9, 10, 15, 17]) {
assert.equal(data.document.version, 17)
for (const version of [9, 10, 15, 16, 18]) {
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false)
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false)
}
@@ -1,4 +1,5 @@
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"
@@ -54,7 +55,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: 16, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
const document = { version: 17, 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 } : {}) }]))])) }
@@ -364,6 +365,11 @@ 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()
@@ -1386,11 +1392,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 16 once the speed limit actions widget is folded into the sign.
// The device writes version 17 with full-panel C4 side cameras.
{
const sample = snapshot()
assert.equal(validDocument(sample.document, sample.metadata), true)
sample.document.version = 15
sample.document.version = 16
assert.equal(validDocument(sample.document, sample.metadata), false)
}
@@ -1403,3 +1409,45 @@ 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("&amp;", "&") })
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])
}
}
@@ -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:16, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
const document = { version:17, 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)
@@ -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', 'software-status', 'driving',
'home', 'system-monitor', 'sentry', 'vasm', 'pip', 'galaxy', 'networks', 'tools', 'logs', 'log-help', '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)]
@@ -0,0 +1,97 @@
.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; }
}
@@ -76,13 +76,6 @@
"description": "Read local reports",
"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",
@@ -108,7 +101,7 @@
"name": "Get help",
"path": "/logs/help",
"icon": "bi-life-preserver",
"description": "Driving, phone connection, controllers, and StarPort support",
"description": "Send StarPort, phone app, or controller logs, or ask on Discord",
"availability": "always"
}
]
@@ -13,6 +13,7 @@
<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">
@@ -1,4 +1,4 @@
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
import { ConnectionLogs } from "./local-access.js"
import { WikiHelp } from './wiki-help.js'
import { UnidenPanel } from './uniden.js'
import { GxState } from "./state.js"
@@ -170,7 +170,7 @@ export class BluetoothFeed {
}
export const BluetoothPage = {
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog, ConnectionLogs, ReportingGuide },
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog, ConnectionLogs },
props: { go: { type: Function, default: path => { location.hash = path } }, unidenSettings: Boolean, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
data: () => ({ status: null, busy: false, error: "", pairValue: "", now: Date.now(), claimAt: Date.now(), forgetting: null, adding: false, dismissedPairing: null }),
mounted() {
@@ -323,7 +323,6 @@ export const BluetoothPage = {
<button class="gx-btn gx-btn--danger" :disabled="forgetting.state === 'working'" @click="confirmForget">{{ forgetting.state === 'working' ? 'Forgetting…' : forgetting.state === 'failed' ? 'Try again' : 'Forget' }}</button></div>
</template>
</GxDialog>
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel show-controller :on-unauthorized="unauthorized" @help="go('/logs/help')" />
<ReportingGuide v-if="mode === 'local' && !unidenSettings" />
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel :on-unauthorized="unauthorized" @help="go('/logs/help/connection')" />
</section>`,
}
@@ -1,5 +1,6 @@
import { PollTimer, connectionError } from "./polling.js"
import { requestJson } from "./startup.js"
import { downloadCaptureZip } from "./log-help.js"
import { reactive } from "../vendor/vue/vue.esm-browser.js"
import { GxNotice } from "./notice.js"
@@ -49,117 +50,43 @@ export class LocalAccessFeed {
}
}
export const ReportingGuide = {
template: `<p class="gx-note">Reporting a new companion app issue? Read the instructions for
<a href="https://wiki.firestar.link/usage/companion-apps/ios/#submit-logs-through-discord" target="_blank" rel="noopener noreferrer">iPhone</a> or
<a href="https://wiki.firestar.link/usage/companion-apps/android/#report-a-problem-through-discord" target="_blank" rel="noopener noreferrer">Android</a>.</p>`,
}
export const ConnectionLogs = {
components: { GxNotice, ReportingGuide },
props: { ticket: String, panel: Boolean, controller: Boolean, showController: Boolean, onUnauthorized: { type: Function, default: () => {} } },
components: { GxNotice },
props: { panel: Boolean, controller: Boolean, onUnauthorized: { type: Function, default: () => {} } },
emits: ["help"],
data: () => ({ supportCode: "", supportTicket: null, supportBusy: false, supportSent: false, capture: null, captureError: "", captureRequest: null }),
beforeUnmount() { this.resetCapture() },
data: () => ({ captureBusy: false, captureError: "", captureSignal: null }),
beforeUnmount() { this.captureSignal?.abort() },
methods: {
resetCapture() {
this.captureRequest?.abort()
this.captureRequest = null
this.capture = null
this.captureError = ""
},
async threadAction(action) {
if (this.supportBusy) return
this.supportBusy = true
async downloadConnectionLogs() {
if (this.captureBusy) return
const controller = new AbortController()
this.captureSignal = controller
this.captureBusy = true
this.captureError = ""
try {
const result = await requestJson("./api/companion/support-ticket", { timeout: 90000, request: {
method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({action, code: this.supportCode.replace(/[\s-]/g, "").toLowerCase()})
}})
if (action === "check") this.supportTicket = result
else this.supportSent = result.sent === true
await downloadCaptureZip(this.controller ? "controller" : "connection", {
unauthorized: this.onUnauthorized,
request: { signal: controller.signal },
})
} catch (error) {
if (error.status === 401) this.onUnauthorized()
else this.captureError = error.message
} finally { this.supportBusy = false }
},
async captureConnectionLogs() {
if (this.captureRequest) return
const request = new AbortController()
this.captureRequest = request
this.capture = null
this.captureError = ""
try {
const endpoint = this.controller ? "./api/controllers/log/capture" : "./api/local-access/capture"
const data = await requestJson(endpoint, { request: { signal: request.signal } })
if (this.captureRequest !== request) return
if (data?.schemaVersion !== 1 || typeof data.zipBase64 !== "string" || data.zipBase64.length > 131072)
throw new Error("Invalid diagnostic capture")
const bytes = Uint8Array.from(atob(data.zipBase64), character => character.charCodeAt(0))
if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4)
throw new Error("Invalid diagnostic capture")
this.capture = new Blob([bytes], { type: "application/zip" })
if (this.ticket && /^[a-f0-9]{64}$/.test(this.ticket)) {
const form = document.createElement("form")
form.method = "post"
form.action = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/" + this.ticket
const input = document.createElement("input")
input.type = "hidden"
input.name = "archive"
input.value = data.zipBase64
form.appendChild(input)
document.body.appendChild(form)
form.submit()
form.remove()
}
} catch (error) {
if (this.captureRequest !== request) return
if (error.status === 401 || ["setup_required", "access_unavailable"].includes(error.code)) this.onUnauthorized()
else this.captureError = connectionError(error)
if (error?.name !== "AbortError") this.captureError = error?.message || "Could not prepare diagnostic ZIP."
} finally {
if (this.captureRequest === request) this.captureRequest = null
if (this.captureSignal === controller) {
this.captureSignal = null
this.captureBusy = false
}
}
},
downloadConnectionLogs() {
if (!this.capture) return
const url = URL.createObjectURL(this.capture)
const link = document.createElement("a")
link.href = url
link.download = this.controller ? "starpilot-controller-logs.zip" : "starpilot-connection-logs.zip"
document.body.appendChild(link)
link.click()
link.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
},
},
template: `<div class="gx-stack gx-connection-logs" :class="{ 'gx-card gx-panel': panel }">
<div v-if="panel" class="gx-section__header"><i class="bi bi-file-earmark-text" aria-hidden="true"></i><span class="gx-section__title">Connection logs</span>
<button type="button" class="gx-btn gx-btn--tonal" @click="$emit('help')">Get help</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="$emit('help')">Send logs</button>
</div>
<div v-if="panel" class="gx-actions"><a class="gx-btn gx-btn--tonal" href="https://wiki.firestar.link/usage/companion-apps/#pair-your-phone" target="_blank" rel="noopener noreferrer">App connection help</a></div>
<details v-if="!ticket"><summary class="gx-btn">Send to existing Discord thread</summary>
<p v-if="supportSent" role="status">Support received the logs. Your Discord thread has the receipt.</p>
<form v-else class="gx-log-form" @submit.prevent="threadAction(supportTicket ? 'send' : 'check')">
<label class="gx-field-group">Discord request code<input class="gx-field" v-model="supportCode" :disabled="supportBusy" @input="supportTicket = null; captureError = ''" maxlength="24" autocomplete="off" spellcheck="false"></label>
<button v-if="!supportTicket" class="gx-btn" type="submit" :disabled="supportBusy || !supportCode.trim()">{{ supportBusy ? 'Finding report…' : 'Find report' }}</button>
<template v-else><p>{{ supportTicket.title }}</p><p>Only support staff receive the {{ supportTicket.kind }} logs.</p>
<button class="gx-btn" type="submit" :disabled="supportBusy">{{ supportBusy ? 'Sending…' : 'Capture and send' }}</button>
</template>
</form>
</details>
<details v-if="!ticket"><summary><small>Manual ZIP download</small></summary>
<p v-if="showController" class="gx-note">For controller ZIPs, open Get help and choose Bluetooth Controller Support.</p>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture logs' }}</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!capture" @click="downloadConnectionLogs">Download ZIP</button>
</details>
<div v-else class="gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture and send' }}</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="captureBusy" @click="downloadConnectionLogs">{{ captureBusy ? 'Preparing ZIP…' : 'Download connection ZIP' }}</button>
</div>
<p class="gx-note">Before collecting fresh logs, park and update your comma to the latest testing build from StarPilotHQ/StarPilot. Try the connection again.</p>
<GxNotice v-if="captureError" tone="danger">{{ captureError }}</GxNotice>
<p v-if="capture && !ticket" class="gx-note" role="status">Capture ready. Download it to share with support.</p>
<ReportingGuide v-if="!panel && !ticket" />
</div>`,
}
@@ -0,0 +1,530 @@
import { WikiHelp } from "./wiki-help.js"
import { GxState } from "./state.js"
import { GxNotice } from "./notice.js"
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
import { StarPortLogsFeed, BUNDLE_URL, fileUrl, outcomeLabel } from "./starport-logs.js"
import { requestJson } from "./startup.js"
import { connectionError } from "./polling.js"
export const STAGE_URL = "./api/logs/stage"
export const NOTE_LIMIT = 200
export const MODEL_LIMIT = 80
const POLL_MS = 1200
const KINDS = ["starport", "connection", "controller"]
const PHONES = ["ios", "android"]
export const LOG_TOPICS = [
{
id: "starport",
title: "StarPort / Car Screen",
subtitle: "Android Auto, wireless adapter, or black screen",
icon: "bi-display",
cta: "Send StarPort logs",
placeholder: "What happened on the car screen?",
whatWeNeed: "Try connecting to your car once first so the attempt is recorded, then describe what happened on your car screen.",
extraHint: "",
attaches: "Last 20 StarPort sessions, StarPort settings, renderer logs, and masked device snapshot.",
},
{
id: "connection",
title: "Phone App",
subtitle: "Pairing or connecting the StarPilot phone app",
icon: "bi-phone",
cta: "Send phone app logs",
placeholder: "What happened in the phone app?",
whatWeNeed: "Pick whether you're on iPhone or Android and tell us what happened in the StarPilot app.",
extraHint: "Can't reach Galaxy on your comma at all? You can also send logs from the phone app's Logs & support screen.",
attaches: "Local network interfaces, Bonjour discovery, and Bluetooth bridge events (passwords & MACs masked).",
},
{
id: "controller",
title: "Controller",
subtitle: "USB or Bluetooth gamepad / button inputs",
icon: "bi-controller",
cta: "Send controller logs",
placeholder: "What went wrong with the controller?",
whatWeNeed: "1. Turn on and wake your USB or Bluetooth controller right now so the comma detects it. 2. Enter the controller model below (hardware names are masked in the log).",
extraHint: "",
attaches: "USB & Bluetooth input interface report (bluetooth-log.json, device names masked).",
},
]
export class LogStageClient {
constructor({
publish,
unauthorized = () => {},
fetcher = (...args) => fetch(...args),
schedule = (fn, ms) => setTimeout(fn, ms),
cancel = (id) => clearTimeout(id),
onReady = () => {},
}) {
Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel, onReady })
this.active = false
this.timer = null
this.generation = 0
this.dismissedUrl = ""
this.initiated = false
}
stop() {
this.generation++
this.active = false
this.initiated = false
if (this.timer !== null) this.cancel(this.timer)
this.timer = null
}
start() {
this.stop()
this.active = true
return this.poll()
}
reset(currentUrl = "") {
if (currentUrl) this.dismissedUrl = currentUrl
this.initiated = false
this.publish({ state: "idle", message: "", claimUrl: "", kind: "", error: "" })
}
async call(options, generation) {
const response = await this.fetcher(STAGE_URL, { cache: "no-store", credentials: "same-origin", ...options })
if (!this.active || generation !== this.generation) return null
if (response.status === 401) {
this.stop()
this.unauthorized()
return null
}
const body = await response.json().catch(() => null)
if (!this.active || generation !== this.generation) return null
if (!response.ok) throw new Error(body?.error || "Sending logs is unavailable")
return body
}
apply(body) {
if (!this.active || !body) return
const dismissed = body.state === "ready" && !!body.claimUrl && body.claimUrl === this.dismissedUrl
const nextState = dismissed ? "idle" : (body.state || "idle")
const claimUrl = dismissed ? "" : (body.claimUrl || "")
const message = dismissed ? "" : (body.message || "")
const kind = dismissed ? "" : (body.kind || "")
this.publish({
state: nextState,
message,
claimUrl,
kind,
available: body.available !== false,
fork: body.fork === true,
noteLimit: body.noteLimit || NOTE_LIMIT,
modelLimit: body.modelLimit || MODEL_LIMIT,
error: "",
})
if (this.initiated && nextState === "ready" && claimUrl) {
this.initiated = false
this.onReady(claimUrl)
}
this.queuePoll(nextState === "staging")
}
queuePoll(pending = true) {
if (this.timer !== null) this.cancel(this.timer)
this.timer = this.active && pending ? this.schedule(() => { this.timer = null; this.poll() }, POLL_MS) : null
}
async poll() {
if (!this.active) return
const generation = this.generation
try {
this.apply(await this.call({}, generation))
} catch (error) {
if (this.active && generation === this.generation) {
this.publish({ error: error?.message || "Sending logs is unavailable" })
this.queuePoll(false)
}
}
}
async stage(payload) {
if (!this.active) return false
const kind = payload?.kind
if (!KINDS.includes(kind)) {
this.publish({ error: "Choose what you are sending logs for." })
return false
}
const note = String(payload?.note ?? "").trim()
if (!note) {
this.publish({ error: "Add a short note about what happened." })
return false
}
if (note.length > NOTE_LIMIT) {
this.publish({ error: `Keep the note to ${NOTE_LIMIT} characters.` })
return false
}
const bodyPayload = { kind, note }
if (kind === "connection") {
if (!PHONES.includes(payload?.phone)) {
this.publish({ error: "Choose iPhone or Android." })
return false
}
bodyPayload.phone = payload.phone
} else if (kind === "controller") {
const model = String(payload?.model ?? "").trim()
if (!model) {
this.publish({ error: "Enter your controller make and model." })
return false
}
if (model.length > MODEL_LIMIT) {
this.publish({ error: `Keep the controller model to ${MODEL_LIMIT} characters.` })
return false
}
bodyPayload.model = model
}
this.dismissedUrl = ""
this.initiated = true
const generation = ++this.generation
this.queuePoll(false)
this.publish({ state: "staging", message: "Collecting logs", claimUrl: "", kind, error: "" })
try {
const body = await this.call({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(bodyPayload),
}, generation)
if (body === null) return false
this.apply(body)
return true
} catch (error) {
if (this.active && generation === this.generation) {
this.initiated = false
this.publish({ state: "idle", error: error?.message || "Sending logs is unavailable" })
this.queuePoll(false)
}
return false
}
}
}
export async function captureZip(kind, { fetcher = (...args) => fetch(...args), unauthorized = () => {}, request = {} } = {}) {
const controller = kind === "controller"
const endpoint = controller ? "./api/controllers/log/capture" : "./api/local-access/capture"
try {
const data = await requestJson(endpoint, { fetcher, request })
if (data?.schemaVersion !== 1 || typeof data.zipBase64 !== "string" || data.zipBase64.length > 131072) {
throw new Error("Invalid diagnostic capture")
}
const bytes = Uint8Array.from(atob(data.zipBase64), character => character.charCodeAt(0))
if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4) {
throw new Error("Invalid diagnostic capture")
}
return {
blob: new Blob([bytes], { type: "application/zip" }),
filename: controller ? "starpilot-controller-logs.zip" : "starpilot-connection-logs.zip",
}
} catch (error) {
if (error.status === 401 || ["setup_required", "access_unavailable"].includes(error.code)) {
unauthorized()
return null
}
throw new Error(connectionError(error))
}
}
export async function downloadCaptureZip(kind, options = {}) {
const result = await captureZip(kind, options)
if (!result) return false
const url = URL.createObjectURL(result.blob)
const link = document.createElement("a")
link.href = url
link.download = result.filename
document.body.appendChild(link)
link.click()
link.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
return true
}
export const LogHelp = {
name: "LogHelp",
components: { WikiHelp, GxState, GxNotice, BluetoothNotice },
props: {
mode: { type: String, required: true },
unauthorized: { type: Function, required: true },
topic: { type: String, default: "starport" },
},
data() {
return {
selected: KINDS.includes(this.topic) ? this.topic : "starport",
stage: { state: "idle", message: "", claimUrl: "", kind: "", available: true, fork: false, noteLimit: NOTE_LIMIT, modelLimit: MODEL_LIMIT, error: "" },
starportLogs: { sessions: [], others: [], status: "idle", error: "" },
sessionsOpen: false,
bluetooth: bluetoothConnection(),
notes: { starport: "", connection: "", controller: "" },
phone: "ios",
controllerModel: "",
zipBusy: false,
zipError: "",
zipSignal: null,
}
},
computed: {
topics() { return LOG_TOPICS },
currentTopic() { return LOG_TOPICS.find(item => item.id === this.selected) || LOG_TOPICS[0] },
bundleUrl() { return BUNDLE_URL },
currentNote() { return this.notes[this.selected] || "" },
canSend() {
if (!this.currentNote.trim()) return false
if (this.selected === "controller" && !this.controllerModel.trim()) return false
return true
},
claimReady() {
return this.stage.state === "ready" && !!this.stage.claimUrl && this.stage.kind === this.selected
},
missingHint() {
if (this.selected === "controller") return "Enter your controller model and a short note above to send."
return "Add a short note about what happened above to send."
},
},
created() {
this.stageClient = new LogStageClient({
publish: update => Object.assign(this.stage, update),
unauthorized: this.unauthorized,
onReady: url => {
try { window.open(url, "_blank", "noopener,noreferrer") } catch {}
},
})
this.starportFeed = new StarPortLogsFeed({
publish: update => Object.assign(this.starportLogs, update),
unauthorized: this.unauthorized,
})
},
mounted() {
if (this.mode === "local") this.stageClient.start()
},
beforeUnmount() {
this.zipSignal?.abort()
this.stageClient.stop()
this.starportFeed.stop()
},
watch: {
topic(next) {
if (KINDS.includes(next)) this.selected = next
},
mode(next) {
if (next === "local") {
this.stageClient.start()
if (this.sessionsOpen && this.selected === "starport") this.starportFeed.start()
} else {
this.stageClient.stop()
this.starportFeed.stop()
}
},
selected(next) {
this.zipError = ""
this.stage.error = ""
if (next !== "starport") this.starportFeed.stop()
else if (this.sessionsOpen && this.mode === "local") this.starportFeed.start()
},
},
methods: {
fileUrl,
outcomeLabel,
reportDate(seconds) { return new Date(seconds * 1000).toLocaleString() },
reportSize(bytes) { return `${(bytes / 1024).toFixed(1)} KiB` },
selectTopic(id) {
this.selected = id
},
updateNote(value) {
this.notes[this.selected] = value
if (this.stage.error) this.stage.error = ""
},
resetStage() {
this.stageClient.reset(this.stage.claimUrl)
},
async submitReport() {
if (!this.canSend || this.stage.state === "staging" || this.zipBusy) return
const payload = { kind: this.selected, note: this.currentNote }
if (this.selected === "connection") payload.phone = this.phone
if (this.selected === "controller") payload.model = this.controllerModel
await this.stageClient.stage(payload)
},
async saveZip() {
if (this.zipBusy || this.selected === "starport") return
this.zipSignal?.abort()
const controller = new AbortController()
this.zipSignal = controller
this.zipBusy = true
this.zipError = ""
try {
await downloadCaptureZip(this.selected, { unauthorized: this.unauthorized, request: { signal: controller.signal } })
} catch (error) {
if (error?.name !== "AbortError") this.zipError = error?.message || "Could not prepare diagnostic ZIP."
} finally {
if (this.zipSignal === controller) {
this.zipSignal = null
this.zipBusy = false
}
}
},
onSessionsToggle(event) {
this.sessionsOpen = !!event.target?.open
if (this.sessionsOpen && this.mode === "local" && this.selected === "starport") this.starportFeed.start()
else this.starportFeed.stop()
},
},
template: `
<section class="gx-settings gx-log-help" aria-labelledby="gx-log-help-title">
<header class="gx-settings__header gx-page-header">
<div>
<h2 id="gx-log-help-title">Send logs &amp; get help</h2>
<p>Choose what you're sending logs for. Your comma prepares the logs and hands off once to Discord.</p>
</div>
<WikiHelp path="/logs/help" />
</header>
<div class="gx-log-help__tabs" role="tablist" aria-label="Log report type">
<button v-for="item in topics" :key="item.id" type="button" role="tab"
class="gx-card gx-log-help__tab"
:class="{ 'gx-log-help__tab--active': selected === item.id }"
:aria-selected="selected === item.id"
@click="selectTopic(item.id)">
<span class="gx-log-help__tab-icon" aria-hidden="true"><i class="bi" :class="item.icon"></i></span>
<span class="gx-log-help__tab-text">
<strong>{{ item.title }}</strong>
<small>{{ item.subtitle }}</small>
</span>
</button>
</div>
<section class="gx-card gx-panel gx-stack gx-log-help__card" :aria-label="currentTopic.title">
<div class="gx-section__header">
<i class="bi" :class="currentTopic.icon" aria-hidden="true"></i>
<div>
<h3 class="gx-section__title">{{ currentTopic.title }}</h3>
<p class="gx-note">{{ currentTopic.subtitle }}</p>
</div>
</div>
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to send or download diagnostic logs.</p>
<template v-else>
<GxNotice v-if="selected === 'starport' && stage.fork" class="gx-starport-send__fork" tone="warn" title="This device is running a StarPilot fork">
Custom forks may have changed StarPort or be out of date. Make sure your branch is up to date with StarPilotHQ before sending, or share the logs with your branch's maintainer or in the StarPilot Discord.
</GxNotice>
<BluetoothNotice v-if="bluetooth" feature="ZIP downloads">Direct log sending from the comma remains available.</BluetoothNotice>
<div v-if="claimReady" class="gx-log-help__ready gx-stack" role="status">
<strong>Logs uploaded from your comma</strong>
<p class="gx-note">Continue to StarPilot Support to sign in with Discord and post to a new or existing thread. Only staff receive the diagnostic ZIP.</p>
<div class="gx-actions">
<a class="gx-btn" :href="stage.claimUrl" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right" aria-hidden="true"></i><span>Continue on Discord support</span></a>
<button type="button" class="gx-btn gx-btn--tonal" @click="resetStage">Send another report</button>
</div>
</div>
<template v-else>
<div class="gx-log-help__callout" role="note">
<i class="bi bi-info-circle" aria-hidden="true"></i>
<div class="gx-stack">
<strong>What we need</strong>
<p>Before collecting fresh logs, park and update your comma to the latest testing build from StarPilotHQ/StarPilot. Try the connection again.</p>
<p>{{ currentTopic.whatWeNeed }}</p>
<p v-if="currentTopic.extraHint" class="gx-note">{{ currentTopic.extraHint }}</p>
</div>
</div>
<div v-if="selected === 'connection'" class="gx-log-help__group" role="group" aria-label="Phone type">
<label class="gx-log-help__label">Phone</label>
<div class="gx-log-help__pills">
<button type="button" class="gx-chip" :class="{ 'gx-chip--selected': phone === 'ios' }" :aria-pressed="phone === 'ios'" @click="phone = 'ios'">iPhone</button>
<button type="button" class="gx-chip" :class="{ 'gx-chip--selected': phone === 'android' }" :aria-pressed="phone === 'android'" @click="phone = 'android'">Android</button>
</div>
</div>
<div v-if="selected === 'controller'" class="gx-log-help__group">
<label class="gx-log-help__label" for="gx-log-help-model">Controller make &amp; model</label>
<input id="gx-log-help-model" class="gx-field" type="text" v-model="controllerModel" :maxlength="stage.modelLimit"
placeholder="e.g. 8BitDo Micro, Xbox Wireless, PS5 DualSense" :disabled="stage.state === 'staging'" @keydown.enter="submitReport">
</div>
<div class="gx-log-help__group">
<label class="gx-log-help__label" for="gx-log-help-note">What happened?</label>
<div class="gx-starport-send__field">
<input id="gx-log-help-note" class="gx-field" type="text" :value="currentNote" :maxlength="stage.noteLimit"
:placeholder="currentTopic.placeholder" :disabled="stage.state === 'staging'"
@input="updateNote($event.target.value)" @keydown.enter="submitReport">
<span class="gx-starport-send__count" aria-live="polite">{{ currentNote.length }}/{{ stage.noteLimit }}</span>
</div>
</div>
<p class="gx-log-help__attaches">
<i class="bi bi-check-circle" aria-hidden="true"></i>
<span><strong>Automatically attaches:</strong> {{ currentTopic.attaches }}</span>
</p>
<div class="gx-actions">
<button v-if="stage.available" type="button" class="gx-btn"
:disabled="!canSend || stage.state === 'staging' || zipBusy" @click="submitReport">
<i class="bi bi-send" aria-hidden="true"></i>
<span>{{ stage.state === 'staging' ? (stage.message || 'Uploading logs') + '…' : currentTopic.cta }}</span>
</button>
<template v-if="!bluetooth">
<a v-if="selected === 'starport'" class="gx-btn gx-btn--tonal" :href="bundleUrl" download>
<i class="bi bi-download" aria-hidden="true"></i><span>Download ZIP instead</span>
</a>
<button v-else type="button" class="gx-btn gx-btn--tonal" :disabled="zipBusy || stage.state === 'staging'" @click="saveZip">
<i class="bi bi-download" aria-hidden="true"></i><span>{{ zipBusy ? 'Preparing ZIP…' : 'Download ZIP instead' }}</span>
</button>
</template>
</div>
<p v-if="!bluetooth" class="gx-note">Comma offline? Save the ZIP on your phone and send it when you have internet. Include the branch and version you captured.</p>
<p v-if="stage.available && !canSend && stage.state !== 'staging'" class="gx-note">{{ missingHint }}</p>
<GxState v-if="stage.state === 'staging'" loading>{{ stage.message || 'Uploading logs' }}…</GxState>
<GxNotice v-if="stage.state === 'failed' || stage.error || zipError" tone="danger">{{ stage.error || stage.message || zipError }}</GxNotice>
</template>
<details v-if="selected === 'starport'" class="gx-log-help__sessions" @toggle="onSessionsToggle">
<summary>Individual session files</summary>
<div class="gx-stack gx-log-help__sessions-body">
<div class="gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="starportFeed.load()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i><span>Refresh</span></button>
</div>
<GxState v-if="starportLogs.status === 'loading'" loading>Loading StarPort logs…</GxState>
<GxNotice v-else-if="starportLogs.status === 'unavailable'" tone="danger">{{ starportLogs.error || 'StarPort logs are unavailable.' }}</GxNotice>
<GxState v-else-if="starportLogs.status === 'ready' && !starportLogs.sessions.length">No StarPort sessions have been logged yet.</GxState>
<div v-if="starportLogs.status === 'ready'" class="gx-starport-log-list">
<article v-for="log in starportLogs.sessions" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body">
<strong>{{ outcomeLabel(log.outcome) }}</strong>
<span>{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}</span>
<span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span>
</div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
<template v-if="starportLogs.status === 'ready' && starportLogs.others.length">
<h4 class="gx-starport-logs__section-title">Renderer logs</h4>
<div class="gx-starport-log-list">
<article v-for="log in starportLogs.others" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body"><strong>{{ log.name }}</strong><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
</template>
</div>
</details>
</template>
</section>
<section class="gx-card gx-panel gx-log-help__discord" aria-label="Discord community support">
<div class="gx-log-help__discord-copy">
<i class="bi bi-discord" aria-hidden="true"></i>
<div>
<h3>Driving behavior or general questions?</h3>
<p class="gx-note">Log uploads here are only for StarPort, the phone app, and controllers. For driving behavior, alerts, or anything else, ask in the StarPilot Discord (if it's about a drive, share your car model and route link).</p>
</div>
</div>
<a class="gx-btn gx-btn--tonal" href="https://firestar.link/discord" target="_blank" rel="noopener noreferrer">Join Discord</a>
</section>
</section>
`,
}
+12 -97
View File
@@ -1,6 +1,5 @@
import { DrivingHelp } from "./driving-help.js"
import { ConnectionLogs } from "./local-access.js"
import { WikiHelp } from './wiki-help.js'
import { LogHelp } from "./log-help.js"
import { WikiHelp } from "./wiki-help.js"
import { GxState } from "./state.js"
import { GxNotice } from "./notice.js"
import { TroubleshootPage, TmuxPage } from "./diagnostic-tools.js"
@@ -8,56 +7,45 @@ import { navigate } from "./router.js"
import { SystemMonitor } from "./system-monitor.js"
import { CrashReportsFeed } from "./crash-reports.js"
import { storedSize } from "./record-deletion.js"
import { StarPortLogsFeed, StarPortLogSend, BUNDLE_URL, MESSAGE_LIMIT, fileUrl, outcomeLabel } from "./starport-logs.js"
import { MenuTile } from "./menu-tile.js"
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
export const Logs = {
name: "Logs",
components: { WikiHelp, GxState, GxNotice, BluetoothNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile, DrivingHelp, ConnectionLogs },
components: { LogHelp, WikiHelp, GxState, GxNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile },
props: {
path: { type: String, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
tools: { type: Array, required: true }, localRoutes: Boolean
},
data: () => ({
crashes: { reports: [], scanIncomplete: false, listLimited: false, status: "idle", error: "", selected: null, preview: null, previewStatus: "idle", deleting: false, storageBytes: 0, reportCount: 0 }, search: "",
starportLogs: { sessions: [], others: [], status: "idle", error: "" }, bluetooth: bluetoothConnection(),
logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT
}),
computed: {
freshRequest() {
const match = /^\/logs\/help\/fresh\/(connection|controller)\/([a-f0-9]{64})$/.exec(this.path)
return match && { controller: match[1] === "controller", token: match[2] }
helpRoute() {
return this.path === "/logs/help" || this.path.startsWith("/logs/help/") || this.path === "/logs/starport"
},
helpTopic() {
if (this.path === "/logs/help/connection") return "connection"
if (this.path === "/logs/help/controller") return "controller"
return "starport"
},
visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) },
},
created() {
this.crashFeed = new CrashReportsFeed({ publish: (update) => Object.assign(this.crashes, update), unauthorized: this.unauthorized })
this.starportFeed = new StarPortLogsFeed({ publish: (update) => Object.assign(this.starportLogs, update), unauthorized: this.unauthorized })
this.sendFeed = new StarPortLogSend({ publish: (update) => Object.assign(this.logSend, update), unauthorized: this.unauthorized })
},
mounted() {
if (this.path === "/logs/crashes" && this.mode === "local") this.crashFeed.start()
if (this.path === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() }
},
beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop() },
beforeUnmount() { this.crashFeed.stop() },
watch: {
path(next, previous) {
if (next === "/logs/crashes" && this.mode === "local") this.crashFeed.start()
else if (previous === "/logs/crashes") { this.crashFeed.stop(); this.search = "" }
if (next === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() }
else if (previous === "/logs/starport") { this.starportFeed.stop(); this.sendFeed.stop() }
},
},
methods: {
storedSize,
go: navigate,
bundleUrl: () => BUNDLE_URL,
fileUrl,
outcomeLabel,
async sendLogs() {
if (await this.sendFeed.send(this.sendNote, this.sendDiscord)) this.sendNote = ""
},
reportDate(seconds) { return new Date(seconds * 1000).toLocaleString() },
reportSize(bytes) { return `${(bytes / 1024).toFixed(1)} KiB` },
async copyPreview() {
@@ -76,41 +64,7 @@ export const Logs = {
:availability="mode !== 'local' && tool.availability === 'local-only' ? 'Unavailable in preview' : ''"
:disabled="mode !== 'local' && tool.availability === 'local-only'" @select="go(tool.path)" />
</div>
<section v-else-if="freshRequest" class="gx-settings">
<header class="gx-settings__header"><h2>Requested {{ freshRequest.controller ? 'controller' : 'connection' }} logs</h2></header>
<p class="gx-note">Capture fresh diagnostics for your support report. Only support staff receive the log file.</p>
<ConnectionLogs v-if="mode === 'local'" :key="freshRequest.token" :ticket="freshRequest.token" :controller="freshRequest.controller" :on-unauthorized="unauthorized" />
<p v-else class="gx-note">Connect to your comma to capture these logs.</p>
</section>
<section v-else-if="path === '/logs/help'" class="gx-settings">
<header class="gx-settings__header gx-page-header"><div><h2>Get help</h2><p>Choose what went wrong.</p></div><WikiHelp path="/logs/help" /></header>
<section class="gx-card gx-panel gx-stack" aria-label="Driving behavior or a specific drive">
<div class="gx-section__header"><i class="bi bi-car-front" aria-hidden="true"></i><h3 class="gx-section__title">Driving behavior or a specific drive</h3></div>
<DrivingHelp :routes-available="localRoutes" @routes="go('/recordings')" />
</section>
<section class="gx-card gx-panel gx-stack" aria-label="Mobile App Support">
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">Mobile App Support</h3></div>
<p class="gx-note">For Wi-Fi, Bluetooth pairing, or Galaxy Tunnel issues. Send connection logs privately with your Discord account. If you use StarPilot on iPhone, you can also report from Logs &amp; support.</p>
<ConnectionLogs v-if="mode === 'local'" :on-unauthorized="unauthorized" />
<p v-else class="gx-note">Connect to your comma to capture its connection logs.</p>
</section>
<section class="gx-card gx-panel gx-stack" aria-label="Bluetooth Controller Support">
<div class="gx-section__header"><i class="bi bi-controller" aria-hidden="true"></i><h3 class="gx-section__title">Bluetooth Controller Support</h3></div>
<p class="gx-note">Connect and wake your USB or Bluetooth controller before capturing its input report. Include the controller model and what went wrong when you send it.</p>
<ConnectionLogs v-if="mode === 'local'" controller :on-unauthorized="unauthorized" />
<p v-else class="gx-note">Connect to your comma to capture a controller log.</p>
<div class="gx-actions">
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/bluetooth/controllers')">Open Controllers</button>
</div>
</section>
<section class="gx-card gx-panel gx-stack" aria-label="StarPort / Android Auto Support">
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">StarPort / Android Auto Support</h3></div>
<p class="gx-note">Open StarPort Logs to download your session bundle or send it to the developer.</p>
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/starport')">Open StarPort Logs</button>
</section>
</section>
<LogHelp v-else-if="helpRoute" :mode="mode" :unauthorized="unauthorized" :topic="helpTopic" />
<TroubleshootPage v-else-if="path === '/logs/troubleshoot'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
<TmuxPage v-else-if="path === '/logs/tmux'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
<template v-else-if="path === '/logs/monitor'"><SystemMonitor :mode="mode" :unauthorized="unauthorized" /></template>
@@ -131,45 +85,6 @@ export const Logs = {
<GxState v-if="crashes.previewStatus === 'loading'" loading>Loading report…</GxState>
<section v-else-if="crashes.preview" class="gx-card gx-crash-preview gx-panel"><div class="gx-crash-preview__head"><strong>{{ crashes.preview.name }}</strong><button type="button" class="gx-btn gx-btn--tonal" @click="copyPreview">Copy visible text</button></div><p v-if="crashes.preview.truncated" class="gx-note">Preview truncated to the first 256 KiB.</p><pre>{{ crashes.preview.text }}</pre></section>
</template>
<section v-else-if="path === '/logs/starport' && mode === 'local'" class="gx-settings gx-starport-logs" aria-labelledby="gx-starport-logs-title">
<header class="gx-settings__header gx-page-header"><div><h2 id="gx-starport-logs-title">StarPort Logs</h2>
<p>The last 20 connection sessions, newest first. The archive includes every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.</p></div><WikiHelp /></header>
<BluetoothNotice v-if="bluetooth" feature="Log downloads">Log summaries remain available.</BluetoothNotice>
<div class="gx-settings__controls gx-actions"><a v-if="!bluetooth" class="gx-btn" :href="bundleUrl()" download><i class="bi bi-file-earmark-zip" aria-hidden="true"></i><span>Download all logs</span><span class="gx-starport-logs__format">ZIP</span></a><button type="button" class="gx-btn gx-btn--tonal" @click="starportFeed.load()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i><span>Refresh</span></button></div>
<GxNotice v-if="logSend.fork" class="gx-starport-send__fork" tone="warn" title="This device is running a StarPilot fork">Custom forks may have changed StarPort or be out of date. Make sure your branch is up to date with StarPilotHQ before sending, or share the logs with your branch's maintainer or in the StarPilot Discord.</GxNotice>
<section v-if="logSend.available" class="gx-card gx-panel gx-starport-send" aria-labelledby="gx-starport-send-title">
<div class="gx-section__header"><i class="bi bi-send" aria-hidden="true"></i><span id="gx-starport-send-title" class="gx-section__title">Send StarPort logs</span></div>
<p class="gx-note">Only for StarPort issues. For anything else, ask in the Discord. Sends the same archive as Download all logs straight from the device. A short note about what happened is required.</p>
<div class="gx-starport-send__row">
<div class="gx-starport-send__field"><input class="gx-field" type="text" v-model="sendNote" :maxlength="messageLimit" placeholder="What happened?" aria-label="Note for the developer" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs"><span class="gx-starport-send__count" aria-live="polite">{{ sendNote.length }}/{{ messageLimit }}</span></div>
<input class="gx-field" type="text" v-model="sendDiscord" maxlength="40" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Discord username (optional)" aria-label="Discord username for a follow-up" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs">
<button type="button" class="gx-btn" :disabled="logSend.state === 'sending' || !sendNote.trim()" @click="sendLogs"><i class="bi bi-send" aria-hidden="true"></i><span>Send StarPort logs</span></button>
</div>
<GxState v-if="logSend.state === 'sending'" loading>{{ logSend.message || 'Sending logs' }}…</GxState>
<GxNotice v-else-if="logSend.state === 'sent'" tone="success">{{ logSend.message }}</GxNotice>
<GxNotice v-else-if="logSend.state === 'failed'" tone="danger">{{ logSend.message }}</GxNotice>
<GxNotice v-if="logSend.error" tone="danger">{{ logSend.error }}</GxNotice>
</section>
<GxState v-if="starportLogs.status === 'loading'" loading>Loading StarPort logs…</GxState>
<GxNotice v-else-if="starportLogs.status === 'unavailable'" tone="danger">{{ starportLogs.error || 'StarPort logs are unavailable.' }}</GxNotice>
<GxState v-else-if="starportLogs.status === 'ready' && !starportLogs.sessions.length">No StarPort sessions have been logged yet.</GxState>
<div v-if="starportLogs.status === 'ready'" class="gx-starport-log-list">
<article v-for="log in starportLogs.sessions" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body"><strong>{{ outcomeLabel(log.outcome) }}</strong><span>{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}</span><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
<template v-if="starportLogs.status === 'ready' && starportLogs.others.length">
<h3 class="gx-starport-logs__section-title">Renderer logs</h3>
<div class="gx-starport-log-list">
<article v-for="log in starportLogs.others" :key="log.name" class="gx-card gx-starport-log">
<div class="gx-starport-log__body"><strong>{{ log.name }}</strong><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
</article>
</div>
</template>
</section>
<GxState v-else>This Logs & Diagnostics page is unavailable in the offline preview.</GxState>
</div>`,
}
@@ -1,4 +1,4 @@
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
import { ConnectionLogs } from "./local-access.js"
import { WikiHelp } from './wiki-help.js'
import { requestJson } from "./startup.js"
import { GxNotice } from "./notice.js"
@@ -29,7 +29,7 @@ export const choiceRow = (label, value, choices, reason = '') => ({ label, value
export const NetworksPage = {
name: "NetworksPage",
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog, ConnectionLogs, ReportingGuide },
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog, ConnectionLogs },
props: { go: { type: Function, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, adding: false, joiningSsid: '', joinPassword: '',
hiddenOpen: false, hiddenSsid: '', showJoinPassword: false, forgetUuid: null, timer: null, controller: null, generation: 0, active: false }),
@@ -262,7 +262,6 @@ export const NetworksPage = {
</template>
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
<GalaxyHotspot v-if="mode === 'local'" :mode="mode" :unauthorized="unauthorized" />
<ConnectionLogs v-if="mode === 'local'" panel :on-unauthorized="unauthorized" @help="go('/logs/help')" />
<ReportingGuide v-if="mode === 'local'" />
<ConnectionLogs v-if="mode === 'local'" panel :on-unauthorized="unauthorized" @help="go('/logs/help/connection')" />
</section>`,
}
@@ -145,7 +145,7 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
export function validDocument(document, metadata) {
if (!object(document)) return false
const profiles = metadata?.projection === true ? ["large"] : PROFILES
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 16) ||
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 17) ||
(Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") ||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
@@ -207,7 +207,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<div ref="widgetsHelp" class="gx-layout__subhead gx-layout__help-anchor"><h3>Widgets</h3><span>{{ activeWidgets.length }} active</span>
<button class="gx-icon-btn gx-layout__info" type="button" :aria-expanded="state.widgetsHelpOpen" aria-controls="gx-layout-widgets-help" aria-label="How the widget list works" title="How the widget list works" @click="toggleFloating('widgetsHelpOpen', 'widgetsHelp')"><i class="bi bi-info-circle" aria-hidden="true"></i></button>
<GxCollapse><div v-show="state.widgetsHelpOpen" id="gx-layout-widgets-help" class="gx-layout__popover" @click="closeFloating('widgetsHelpOpen')" @keydown.esc="closeFloating('widgetsHelpOpen')">
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front, and alerts stay above all widgets. Each side camera can be locked to the front; unlock it to move widgets above.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front, and alerts stay above all widgets. Each Adj Spot Camera can be locked to the front; unlock it to move widgets above.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
</div></GxCollapse>
</div>
<div v-if="!projection && leadRows.length" class="gx-actions">
@@ -443,7 +443,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<h5 class="gx-layout__display-group">Camera</h5>
<GalaxySettingRow feedback="draft" :row="switchRow('Show Camera on Blind-Spot Warning', state.draft.blindSpotCamera === true)" :index="0"
:disabled="!editable || !!state.drag || !!state.layerDrag || !projectionHasPipWidget" :save-value="(index, value) => setProjectionDisplay('blindSpotCamera', value)" />
<p v-if="!projectionHasPipWidget" class="gx-note">Add a left or right blind-spot camera widget to enable this option.</p>
<p v-if="!projectionHasPipWidget" class="gx-note">Add a left or right Adj Spot Camera widget to enable this option.</p>
<GalaxySettingRow feedback="draft" :row="switchRow('Large UI Gamma Effect', state.draft.largeUiGammaTrial)" :index="1"
:disabled="!editable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setLargeUiGammaTrial(value)" />
<p class="gx-note">The large UI road-camera color effect on StarPort (not shown in the preview).</p>
@@ -471,7 +471,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
</GxDialog>
<GxDialog v-if="state.pipUnlockConfirm" labelledby="gx-layout-pip-unlock-title" describedby="gx-layout-pip-unlock-body" alert @close="cancelCameraUnlock">
<div><h3 id="gx-layout-pip-unlock-title">Unlock {{ profile?.widgets[state.pipUnlockConfirm]?.label }}?</h3>
<p id="gx-layout-pip-unlock-body">Warning: moving other widgets on top of this side camera may block your view of the blind-spot camera. Are you sure?</p></div>
<p id="gx-layout-pip-unlock-body">Warning: moving other widgets on top of this Adj Spot Camera may block your view of the Adj Spot Camera. Are you sure?</p></div>
<div class="gx-settings__controls gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="cancelCameraUnlock">Cancel</button>
<button type="button" class="gx-btn gx-btn--danger" @click="confirmCameraUnlock">Unlock</button>
@@ -21,7 +21,7 @@ export { layoutDocument, previewDocument, withDisplay, orderedWidgetIds, widgetP
const previewVisibilityKey = projection => "gx-layout-preview-visibility-v2:" + (projection ? "starport" : "comma")
const oldProjectionVisibilityKey = "gx-layout-preview-visibility-v2:android-auto"
function loadPreviewVisibility(projection) {
const hidden = { large: {}, compact: {} }
const hidden = { large: {}, compact: projection ? {} : { pip_left: true } }
try {
const currentKey = previewVisibilityKey(projection)
const raw = localStorage.getItem(currentKey) ?? (projection ? localStorage.getItem(oldProjectionVisibilityKey) : null)
@@ -377,7 +377,8 @@ export const LayoutWidgetPreview = {
<path :d="'M ' + widget.width / 2 + ' ' + widget.height * .68 + ' Q ' + widget.width * .65 + ' ' + widget.height * .68 + ' ' + widget.width * .8 + ' ' + widget.height * .74" :stroke-width="widget.height * .18" opacity=".9" />
</g>
<g v-else-if="widget.kind === 'pip_camera'">
<circle :cx="widget.width / 2" :cy="widget.height / 2" :r="widget.width / 2 - 3" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<rect v-if="widget.width !== widget.height" x="0" y="0" :width="widget.width" :height="widget.height" :rx="Math.min(widget.width, widget.height) * .22" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<circle v-else :cx="widget.width / 2" :cy="widget.height / 2" :r="widget.width / 2 - 3" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<text :x="widget.width / 2" :y="widget.height / 2" text-anchor="middle" :font-size="widget.height / 10">{{ widget.label }}</text>
</g>
<g v-else-if="['nav_home', 'nav_work', 'bookmark'].includes(widget.kind)" :opacity="(widget.opacity ?? 100) / 100">
+6 -6
View File
@@ -175,22 +175,22 @@ export const PipPage = {
},
},
template: `
<section class="gx-settings gx-pip" aria-label="Blind Spot Camera & Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Blind Spot Camera & Preview</h2>
<section class="gx-settings gx-pip" aria-label="Adj Spot Camera & Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Adj Spot Camera & Preview</h2>
<p>Shows a close-up of the cabin window as you drive. Whether it appears on your turn signal or when a car is in your blind spot depends on your settings. Choose which window each side covers and how much to zoom in.</p></div>
<div class="gx-actions"><WikiHelp />
<button type="button" class="gx-btn gx-btn--tonal" :disabled="bluetooth || state.cameraWarming" @click="liveCamera.refresh()"><i class="bi bi-camera" aria-hidden="true"></i> Take new snapshot</button><button type="button" class="gx-icon-btn" aria-label="Position side cameras" title="Position side cameras" @click="go('/theme_maker')"><i class="bi bi-layout-wtf" aria-hidden="true"></i></button></div></header>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="bluetooth || state.cameraWarming" @click="liveCamera.refresh()"><i class="bi bi-camera" aria-hidden="true"></i> Take new snapshot</button><button type="button" class="gx-icon-btn" aria-label="Position Adj Spot Cameras" title="Position Adj Spot Cameras" @click="go('/theme_maker')"><i class="bi bi-layout-wtf" aria-hidden="true"></i></button></div></header>
<GxState v-if="mode !== 'local'">Local saved settings are unavailable in preview.</GxState>
<template v-else>
<GxNotice v-if="state.data && !state.data.parked" tone="warn">Turn the vehicle off to change these settings.</GxNotice>
<GxState v-if="state.status === 'loading'" loading>Reading blind-spot camera preferences and crop positions…</GxState>
<GxNotice tone="danger" v-else-if="state.status === 'unavailable' && !state.error">The device could not read blind-spot camera preferences or crop positions. Reconnecting automatically…</GxNotice>
<GxState v-if="state.status === 'loading'" loading>Reading Adj Spot Camera preferences and crop positions…</GxState>
<GxNotice tone="danger" v-else-if="state.status === 'unavailable' && !state.error">The device could not read Adj Spot Camera preferences or crop positions. Reconnecting automatically…</GxNotice>
<GxNotice tone="danger" v-if="state.error">{{ state.error }}</GxNotice>
<BluetoothNotice v-if="bluetooth" feature="Cabin camera preview">Saved settings remain available.</BluetoothNotice>
<GxNotice tone="danger" v-else-if="state.cameraError">{{ state.cameraError }}</GxNotice>
<div v-if="state.data" class="gx-settings__body">
<section class="gx-card gx-vasm__editor" aria-label="Blind Spot Camera crop editor">
<section class="gx-card gx-vasm__editor" aria-label="Adj Spot Camera crop editor">
<div class="gx-section__header"><i class="bi bi-crop" aria-hidden="true"></i><span class="gx-section__title">Camera Crop</span></div>
<p class="gx-note">Drag a circle onto the cabin window you want to watch. Both crops share one size.</p>
<p v-if="!bluetooth" class="gx-note gx-camera-status" role="status">{{ state.cameraWarming ? "Warming up the camera · about 10 seconds…" : state.imageName ? "Snapshot ready" : "Take a cabin snapshot while parked." }}</p>
@@ -34,7 +34,7 @@ export const SETTINGS_SECTIONS = Object.freeze([
])
// Crop numeric rows and the inline editor row are controlled from the dedicated
// Blind Spot Camera page; they stay writable through the settings API for the
// Adj Spot Camera page; they stay writable through the settings API for the
// widget/VASM editor but must not surface in the generic toggles list.
export const isPipCropRow = (row) => ["Visual camera crop editor", "Camera crop size", "Restore default camera crop"].includes(row.label) ||
/^Vehicle (left|right) crop/.test(row.label || "")
@@ -51,7 +51,7 @@ const SECTION_LINKS = {
{ label: "Display", page: "display", value: "Adjust screen brightness and display timing" },
{ label: "Driving Screen Widgets, Colors & Layout", page: "ui_layout" },
{ label: "Quick Select", page: "favorites" },
{ label: "Blind Spot Camera & Preview", page: "pip" },
{ label: "Adj Spot Camera & Preview", page: "pip" },
],
}
@@ -1018,7 +1018,7 @@ export const StarPortPage = {
</div>
<div class="gx-step__body">
<div class="gx-driving__actions gx-actions">
<a class="gx-btn gx-btn--tonal" href="#/logs/starport"><i class="bi bi-journal-text"></i> Connection Logs</a>
<a class="gx-btn gx-btn--tonal" href="#/logs/help/starport"><i class="bi bi-journal-text"></i> Send StarPort logs</a>
</div>
</div>
</section>
+8 -4
View File
@@ -317,7 +317,7 @@ class Compositor:
from openpilot.starpilot.ui.pip_render import PiPRenderer
self.pip_saved = read_pip(ui_state.params)
self.pip_stream = ReplayCameraStream(ui_state)
self.pip = PiPRenderer('bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.pip = PiPRenderer('curved' if self.profile == 'compact' else 'bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.resources.callback(lambda: self.pip.close())
self._new_view()
self.resources.callback(lambda: self.view.close())
@@ -443,15 +443,19 @@ class Compositor:
signals = Signals(car is not None, bool(car.leftBlinker) if car else False, bool(car.rightBlinker) if car else False,
bool(car.leftBlindspot) if car else False, bool(car.rightBlindspot) if car else False)
positions = {}
for side, key in zip(('left', 'right'), CAMERA_WIDGETS, strict=True):
for side, key in zip(('left', 'right'), CAMERA_WIDGETS if self.profile == 'large' else ('pip_left', 'pip_left'), strict=True):
position = placement(state.customization, self.profile, key)
if position['enabled']:
width, height = widget_size(state.customization, self.profile, key)
positions[side] = Rect(position['x'], position['y'], width, height)
if submit is not None and self.profile == 'compact':
submit_widget = submit
def submit(_key, draw):
submit_widget('pip_left', draw)
status = self.pip.render(rect, saved.mask, signals, enabled=self.cabin, on_blinker=saved.on_blinker,
on_bsm=saved.on_bsm, invert=saved.invert, now=now / 1e9, placements=positions, submit=submit)
if not self.cabin or status not in ('rendered', 'inactive'):
self.fonts.draw('RECORDED SIDE CAMERA UNAVAILABLE', FontRole.MEDIUM, 18 if self.profile == 'compact' else 25,
self.fonts.draw('RECORDED ADJ SPOT CAMERA UNAVAILABLE', FontRole.MEDIUM, 18 if self.profile == 'compact' else 25,
18 if self.profile == 'compact' else rect.x + 30,
180 if self.profile == 'compact' else rect.y + rect.height - 62, self.rl.Color(245, 200, 155, 255))
@@ -517,7 +521,7 @@ class Compositor:
self.pip_stream._client = pip_client
self.pip_stream.release_retired()
self.pip_stream.reset()
self.pip = PiPRenderer('bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.pip = PiPRenderer('curved' if self.profile == 'compact' else 'bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.view.close()
self.adapter = RuntimeSnapshotAdapter(self.ui)
self._new_view()
@@ -574,12 +574,14 @@ def test_published_readiness_survives_buffering_but_rejects_seeks_and_old_epochs
assert sleeps == [.01] * len(times) # Native playback keeps its original idle wait.
@pytest.mark.parametrize('profile', ('compact', 'large'))
@pytest.mark.parametrize('matching_frame', (False, True))
@pytest.mark.parametrize('streams,expected_streams', (({0, 2}, [0, 2]), ([2, 0], [2, 0])))
def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(monkeypatch, matching_frame, streams, expected_streams):
def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(monkeypatch, matching_frame, streams, expected_streams, profile):
monkeypatch.setattr('openpilot.starpilot.ui.runtime_snapshot.RuntimeSnapshotAdapter', Mock())
monkeypatch.setattr('openpilot.starpilot.ui.pip_render.PiPRenderer', Mock())
core: Any = object.__new__(Compositor)
core.profile = profile
client = Mock(frame_id=5 if matching_frame else 4, timestamp_sof=9_000_000_000, timestamp_eof=9_010_000_000)
client.is_connected.return_value = True
frame = SimpleNamespace(frame_id=5)
@@ -607,6 +609,8 @@ def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(mo
_offroad_transition_callbacks=callbacks)
core.render_receipts = {'modelV2': 1}
core.reset_epoch(3)
from openpilot.starpilot.ui.pip_render import PiPRenderer
assert PiPRenderer.call_args.args[0] == ('curved' if profile == 'compact' else 'bubble')
for callback in callbacks:
callback()
assert core.render_receipts == {}
@@ -18,7 +18,7 @@ from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.ui.layout_preview_transport import SCENES, validate_preview_document
from openpilot.starpilot.ui.developer_preview import OnroadVisualPreview
from openpilot.starpilot.ui.onroad_customization import (CAMERA_WIDGETS, PROFILES, ROAD_BASE_WIDTH, RUNTIME_PREVIEW_WIDGETS, fit_to_road, placement,
from openpilot.starpilot.ui.onroad_customization import (camera_widgets, PROFILES, ROAD_BASE_WIDTH, RUNTIME_PREVIEW_WIDGETS, fit_to_road, placement,
validate_document, widget_size)
from openpilot.starpilot.ui.onroad_widget_style import draw_widget_frame
from openpilot.starpilot.curve_speed.status import CurveObservation
@@ -276,17 +276,21 @@ class _Canvas:
if submit is None:
self._render_side_cameras(state)
return
for key in CAMERA_WIDGETS:
for key in camera_widgets(self.profile):
submit(key, lambda key=key: self._render_side_cameras(state, only=key))
def _render_side_cameras(self, state: OnroadState, only=None) -> None:
for key in CAMERA_WIDGETS:
for key in camera_widgets(self.profile):
if only is not None and key != only:
continue
position = placement(state.customization, self.profile, key)
if not position["enabled"]:
continue
widget = PROFILES[str(self.profile)]["widgets"][key]
if self.profile == Profile.COMPACT:
target = rl.Rectangle(position["x"], position["y"], widget["width"], widget["height"])
rl.draw_rectangle_rounded(target, 0.44, 16, rl.Color(21, 44, 57, 90))
continue
radius = widget["width"] / 2
shift = state.viewport_width - 1860 if self.profile == Profile.LARGE and key == "pip_right" and self.viewport is None else 0
center = rl.Vector2(position["x"] + shift + radius, position["y"] + radius)
+44 -12
View File
@@ -152,13 +152,19 @@ for _index, (_key, _label) in enumerate(zip(RAIL_WIDGETS, ("Model confidence", "
# Keep layouts saved before camera widgets valid when the registry grows.
CAMERALESS_WIDGETS = {profile: set(data["widgets"]) for profile, data in PROFILES.items()}
CAMERA_WIDGETS = ("pip_left", "pip_right")
for _profile, (_size, _margin) in {"large": (600, 24), "compact": (80, 16)}.items():
def camera_widgets(profile):
return CAMERA_WIDGETS[:1] if str(profile) == "compact" else CAMERA_WIDGETS
for _profile, (_width, _height, _margin) in {"large": (600, 600, 24), "compact": (476, 240, 0)}.items():
_bounds = PROFILES[_profile]["bounds"]
for _side, _key in zip(("left", "right"), CAMERA_WIDGETS, strict=True):
_x = _bounds["x"] + (_margin if _side == "left" else _bounds["width"] - _margin - _size)
_y = _bounds["y"] + _bounds["height"] - _margin - _size
for _side, _key in zip(("left", "right"), camera_widgets(_profile), strict=False):
_x = _bounds["x"] + (_margin if _side == "left" else _bounds["width"] - _margin - _width)
_y = _bounds["y"] + _bounds["height"] - _margin - _height
PROFILES[_profile]["widgets"][_key] = {
**_widget(f"PiP {_side} side camera", "pip_camera", _size, _size, _x, _y), "layer": "underlay"}
**_widget((f"Adj Spot Camera {_side.title()}" if _profile == "large" else "Adj Spot Camera"), "pip_camera", _width, _height, _x, _y), "layer": "underlay"}
MODE_WIDGET = "driving_mode_descriptions"
for _profile, _geometry in {"large": (580, 68, 640, 344), "compact": (168, 44, 154, 0)}.items():
@@ -372,7 +378,7 @@ DEFAULT_WIDGET_ORDER = {
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, "rear_fog", "pip_left", "pip_right"),
"compact": ("speed_limit", "max_speed", "steering_wheel", "torque_bar",
"driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left", "pip_right"),
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left"),
}
@@ -427,7 +433,7 @@ def customization_metadata():
def default_document():
return {"version": 16, "clock24Hour": False, "reduceMotion": False, "palette": dict(PALETTE), "roadColors": {profile: {} for profile in PROFILES},
return {"version": 17, "clock24Hour": False, "reduceMotion": False, "palette": dict(PALETTE), "roadColors": {profile: {} for profile in PROFILES},
"widgetColors": {profile: {} for profile in PROFILES}, "layouts": {
profile: {key: {**widget["default"], **({"size": WIDGET_SIZES[key][profile][1]} if key in WIDGET_SIZES else {})}
for key, widget in data["widgets"].items()}
@@ -509,7 +515,7 @@ def migrate_confirmation_layout(layout, profile, widgets, bounds, *, extra_heigh
def validate_document(value):
if type(value) is not dict or type(value.get("version")) is not int or value["version"] not in range(1, 17):
if type(value) is not dict or type(value.get("version")) is not int or value["version"] not in range(1, 18):
raise ValueError("Invalid customization version")
if value["version"] < 16:
# Version 16 folded the separate speed limit actions widget into the speed limit sign.
@@ -521,6 +527,23 @@ def validate_document(value):
if type(value.get("widgetOrder")) is dict:
value["widgetOrder"] = {profile: [key for key in order if key != "speed_limit_actions"] if type(order) is list else order
for profile, order in value["widgetOrder"].items()}
# C4 has one shared camera panel; accept the old pair without changing C3.
compact = value.get("layouts", {}).get("compact") if type(value.get("layouts")) is dict else None
if type(compact) is dict and "pip_right" in compact:
value = copy.deepcopy(value)
compact = value["layouts"]["compact"]
right = compact.pop("pip_right")
left = compact.get("pip_left")
if any(type(item) is not dict or set(item) != {"x", "y", "enabled"} or type(item["enabled"]) is not bool or
any(type(item[axis]) not in (int, float) or not math.isfinite(item[axis]) for axis in ("x", "y")) for item in (left, right)):
raise ValueError("Invalid legacy camera placement")
left["enabled"] = left["enabled"] or right["enabled"]
colors = value.get("widgetColors", {}).get("compact") if type(value.get("widgetColors")) is dict else None
if type(colors) is dict and colors.get("pip_right") == {}:
colors.pop("pip_right")
order = value.get("widgetOrder", {}).get("compact") if type(value.get("widgetOrder")) is dict else None
if type(order) is list:
value["widgetOrder"]["compact"] = [key for key in order if key != "pip_right"]
fields = {"version", "palette", "layouts"} | ({"widgetColors"} if value["version"] >= 2 else set())
if value["version"] >= 3:
fields.add("roadColors")
@@ -587,13 +610,14 @@ def validate_document(value):
type(legacy["enabled"]) is not bool or
any(type(legacy[axis]) not in (int, float) or not math.isfinite(legacy[axis]) for axis in ("x", "y"))):
raise ValueError("Invalid legacy camera placement")
for side, key in enumerate(CAMERA_WIDGETS):
for side, key in enumerate(camera_widgets(profile)):
widget = PROFILES[profile]["widgets"][key]
position = dict(widget["default"])
if legacy is not None:
bounds = widget_bounds(profile, key)
shift = side * widget["width"] if profile == "large" else 0
position.update(enabled=legacy["enabled"],
x=max(bounds["x"], min(legacy["x"], bounds["x"] + bounds["width"] - 2 * widget["width"])) + side * widget["width"],
x=max(bounds["x"], min(legacy["x"], bounds["x"] + bounds["width"] - 2 * widget["width"])) + shift,
y=max(bounds["y"], min(legacy["y"], bounds["y"] + bounds["height"] - widget["height"])))
layouts[profile][key] = position
layouts = copy.deepcopy(layouts)
@@ -670,6 +694,14 @@ def validate_document(value):
bounds = data['bounds']
if legacy_signal:
_fit_legacy_signal(placement, bounds)
if value["version"] < 17 and profile == "compact" and key in CAMERA_WIDGETS and type(placement) is dict:
# Move the legacy 80px widget into the shared C4 panel.
if any(type(placement.get(axis)) not in (int, float) or not math.isfinite(placement[axis]) for axis in ("x", "y")):
raise ValueError("Invalid widget position")
if key in value["layouts"][profile] and not (0 <= placement["x"] <= bounds["width"] - 80 and
0 <= placement["y"] <= bounds["height"] - 80):
raise ValueError("Invalid legacy camera position")
placement = layout[key] = {**placement, "x": 0, "y": 0}
if (key == JETLINK_WIDGET and type(placement) is dict and type(placement.get('y')) in (int, float) and
math.isfinite(placement['y']) and
bounds['y'] + bounds['height'] - JETLINK_SIZE[1] < placement['y'] <= bounds['y'] + bounds['height'] - 84):
@@ -712,9 +744,9 @@ def validate_document(value):
size = WHEEL_SIZES[profile][1]
if scalable:
minimum, _, maximum = WIDGET_SIZES[key][profile]
if type(placement["size"]) is not int or not minimum <= cast(int, placement["size"]) <= maximum:
if type(placement["size"]) is not int or not minimum <= placement["size"] <= maximum:
raise ValueError("Invalid widget size")
size = cast(int, placement["size"])
size = placement["size"]
# Only a gauge the saved layout actually placed moves; one filled in from defaults is already in the new box.
saved_layout = value.get("layouts", {}).get(profile) if type(value.get("layouts")) is dict else None
old_gauge = key == CEM_GAUGE_WIDGET and value["version"] < 7 and type(saved_layout) is dict and key in saved_layout
+2 -2
View File
@@ -24,7 +24,7 @@ RESET = "pip:reset"
EDITOR = "pip:mask:editor"
FORMAT_PREFIX = "pip:format:"
MASK_PREFIX = "pip:mask:"
LABELS = {ENABLED: "Use blind spot camera", BLINKER: "Show on turn signal",
LABELS = {ENABLED: "Use Adj Spot Camera", BLINKER: "Show on turn signal",
BSM: "Show on blind spot warning", INVERT: "Mirror camera crop"}
@@ -230,7 +230,7 @@ class PiPOwner:
reason="" if live else "Open the live crop preview while parked to check the camera."))
defaults = dict.fromkeys(BOOL_KEYS, 'Off')
rows = [replace(row, default_value=defaults[row.key]) if row.key in defaults else row for row in rows]
return FeatureSettingsState(page="pip", title="Blind Spot Camera & Preview",
return FeatureSettingsState(page="pip", title="Adj Spot Camera & Preview",
subtitle="Choose when to show the camera and adjust its crop from the live preview. " +
"Resolution follows the camera automatically.",
rows=tuple(rows), parked=parked)
+1 -1
View File
@@ -122,7 +122,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
elif scene == "settings_pip":
rows = (boolean("pip:enabled", "On"), boolean("pip:blinker", "Off"), number, reset,
FeatureRow("", "Camera availability", "No fresh cabin frame", reason="Check the live crop preview while parked"))
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Blind Spot Camera & Preview"
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Adj Spot Camera & Preview"
else:
rows = (boolean("enabled_off", "Off"), boolean("enabled_on", "On"),
boolean("disabled_off", "Off", available=False), boolean("disabled_on", "On", available=False),
+6 -4
View File
@@ -170,7 +170,7 @@ class StarShellSession(TeslaSpeedActions):
self.network_layer = network_layer
self.settings_layer = settings_layer
self.fonts = BitmapFonts(profile, Path(font_dir) if font_dir else default_font_directory())
self.pip_renderer = PiPRenderer("bubble")
self.pip_renderer = PiPRenderer("curved" if profile == Profile.COMPACT else "bubble")
self.pip_warning = PiPWarningSource()
self._pip_saved = None
self._vasm_saved = None
@@ -905,7 +905,7 @@ class StarShellSession(TeslaSpeedActions):
self.pip_renderer.deactivate()
return
camera_positions = {}
for side, key in zip(("left", "right"), CAMERA_WIDGETS, strict=True):
for side, key in zip(("left", "right"), CAMERA_WIDGETS if self.profile == Profile.LARGE else ("pip_left", "pip_left"), strict=True):
position = placement(state.customization, self.profile, key)
if position["enabled"]:
width, height = widget_size(state.customization, self.profile, key)
@@ -913,9 +913,11 @@ class StarShellSession(TeslaSpeedActions):
camera_positions[side] = Rect(position["x"] + shift, position["y"], width, height)
status = self.pip_renderer.render(rect, saved.mask, signals, enabled=True,
on_blinker=saved.on_blinker, on_bsm=saved.on_bsm, invert=saved.invert,
placements=camera_positions, **({"submit": submit} if submit is not None else {}))
placements=camera_positions,
**({"submit": (lambda _key, draw: submit("pip_left", draw)) if self.profile == Profile.COMPACT else submit}
if submit is not None else {}))
if status not in ("rendered", "inactive") and state.alert.size == AlertSize.NONE:
self.fonts.draw("SIDE CAMERA UNAVAILABLE", FontRole.MEDIUM,
self.fonts.draw("ADJ SPOT CAMERA UNAVAILABLE", FontRole.MEDIUM,
18 if self.profile == Profile.COMPACT else 25,
18 if self.profile == Profile.COMPACT else rect.x + 30,
180 if self.profile == Profile.COMPACT else rect.y + rect.height - 62,
@@ -287,3 +287,9 @@ def test_large_shell_forwards_the_saved_camera_and_temporary_reverse(monkeypatch
session.view.camera_layer(rl.Rectangle(0, 0, 2160, 1080), state)
kwargs = camera.render_camera_model_layer.call_args.kwargs
assert kwargs['camera_view'] is choice and kwargs['reverse_driver'] is reverse
@pytest.mark.parametrize('profile,shape', [(runtime_app.Profile.COMPACT, 'curved'), (runtime_app.Profile.LARGE, 'bubble')])
def test_side_camera_shape_follows_device_profile(lifecycle, monkeypatch, request, profile, shape):
make_session(monkeypatch, request, profile, Mock())
runtime_app.PiPRenderer.assert_called_once_with(shape)
@@ -751,7 +751,7 @@ def test_v5_geometry_migrates_the_card():
doc['layouts']['large']['cruise_limits'].update(x=1550, y=638)
doc['layouts']['large']['speed_limit_actions'] = {'x': 1550, 'y': 954, 'enabled': True}
migrated = validate_document(doc)
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['layouts']['large']['cruise_limits'] == default_document()['layouts']['large']['cruise_limits']
assert 'speed_limit_actions' not in migrated['layouts']['large']
assert migrated['speedSources'] is True
@@ -319,15 +319,22 @@ if __name__ == "__main__":
unittest.main()
def test_native_preview_draws_independent_camera_circles_without_camera_input():
def test_native_preview_matches_camera_geometry_without_camera_input():
for profile, width in ((Profile.COMPACT, 536), (Profile.LARGE, 1860), (Profile.LARGE, 2160)):
canvas = _Canvas.__new__(_Canvas)
canvas.profile, canvas.viewport = profile, None
document = default_document()
state = replace(sample_state('engaged', document), viewport_width=width)
with patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_circle_v') as circle, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring:
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_rectangle_rounded') as panel:
canvas._render_side_cameras(state)
if profile == Profile.COMPACT:
assert panel.call_count == 1
assert circle.call_count == ring.call_count == 0
target = panel.call_args.args[0]
assert (target.x, target.y, target.width, target.height) == (0, 0, 476, 240)
continue
assert circle.call_count == ring.call_count == 2
right_center, radius = circle.call_args.args[:2]
assert right_center.x + radius == (width - 54 if profile == Profile.LARGE else 460)
@@ -13,7 +13,7 @@ import pytest
from openpilot.starpilot.ui.appearance_preferences import OnroadAppearance
from openpilot.starpilot.ui.onroad_customization import (
CLOCK_WIDGET, DEFAULT_WIDGET_ORDER, MAX_BYTES, STOPPED_TIMER_WIDGET, customization_metadata, default_document, offset, read_customization,
validate_document, decode_document, widget_palette, rgba, widget_size)
validate_document, camera_widgets, decode_document, widget_palette, rgba, widget_size)
from openpilot.starpilot.ui.onroad_compact_widgets import CompactHudRenderer
from openpilot.starpilot.ui.onroad_large_widgets import CurrentSpeedHud, UnifiedSpeedWidget, SteeringWheelWidget
from openpilot.starpilot.ui.onroad_state import (
@@ -69,7 +69,7 @@ def test_v12_portrait_upgrade_preserves_preferences_and_is_idempotent():
before = copy.deepcopy(old)
updated = validate_document(old)
expected = copy.deepcopy(old)
expected['version'] = 16
expected['version'] = 17
expected['layouts']['compact']['speed_limit'].update(x=320, y=16)
assert old == before and updated == expected
assert validate_document(updated) == updated
@@ -120,7 +120,7 @@ def test_v13_notice_upgrade_preserves_preferences_and_only_moves_a_conflicting_s
before = copy.deepcopy(old)
updated = validate_document(old)
expected = copy.deepcopy(old)
expected['version'] = 16
expected['version'] = 17
expected['layouts']['compact']['speed_limit']['y'] = min(sign_y, 16)
assert old == before and updated == expected
assert validate_document(updated) == updated
@@ -206,7 +206,7 @@ def test_v7_speed_layout_migration_is_bounded_non_mutating_and_idempotent():
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large']['cruise_limits']['x'] == 1391
assert migrated['layouts']['large']['current_speed'] == original['layouts']['large']['current_speed']
assert migrated['layouts']['large']['cem_gauge'] == {'x': 56, 'y': 536, 'enabled': True}
@@ -235,7 +235,7 @@ def test_v8_restores_only_compact_speed_defaults_and_preserves_customizations(cu
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large'] == document['layouts']['large']
assert migrated['widgetColors'] == document['widgetColors']
assert migrated['widgetOrder'] == document['widgetOrder']
@@ -274,7 +274,7 @@ def test_v8_layout_without_rails_preserves_customizations():
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large'] == original['layouts']['large']
assert migrated['layouts']['compact']['speed_limit'] == default_document()['layouts']['compact']['speed_limit']
assert migrated['palette'] == original['palette']
@@ -387,7 +387,7 @@ def test_v3_layout_migrates_wheel_size_without_changing_saved_placement_or_color
for profile in ("large", "compact"):
del document["layouts"][profile]["steering_wheel"]["size"]
migrated = validate_document(document)
assert migrated["version"] == 16
assert migrated["version"] == 17
assert migrated["palette"] == document["palette"]
assert migrated["layouts"]["large"]["steering_wheel"] == {"x": 1300, "y": 100, "enabled": False, "size": 192}
assert migrated["layouts"]["compact"]["steering_wheel"] == {"x": 90, "y": 130, "enabled": True, "size": 50}
@@ -425,7 +425,7 @@ def test_pre_action_saved_layout_migrates_without_losing_positions_or_palette(re
def test_duplicate_key_cannot_apply_otherwise_valid_placement():
document = default_document()
document["layouts"]["large"]["current_speed"]["x"] = 100
raw = json.dumps(document).replace('"version": 16', '"version": 11, "version": 11').encode()
raw = json.dumps(document).replace('"version": 17', '"version": 11, "version": 11').encode()
with patch("openpilot.starpilot.ui.onroad_customization.read_saved", return_value=(raw, True)):
assert read_customization(Mock()) == default_document()
@@ -440,7 +440,7 @@ def test_v9_large_sign_migration_preserves_customizations_and_clamps_bottom_edge
before = deepcopy(old)
updated = validate_document(old)
assert old == before
assert updated['version'] == 16
assert updated['version'] == 17
assert updated['layouts']['large']['cruise_limits']['y'] == default_document()['layouts']['large']['cruise_limits']['y']
assert updated['layouts']['compact'] == before['layouts']['compact']
assert validate_document(updated) == updated
@@ -680,7 +680,7 @@ def test_v1_palette_positions_and_visibility_migrate_without_mutating_source():
original = copy.deepcopy(old)
result = decode_document(json.dumps(old).encode())
assert old == original
assert result['version'] == 16
assert result['version'] == 17
assert result['palette'] == old['palette']
for profile, layout in old['layouts'].items():
for key, position in layout.items():
@@ -836,28 +836,30 @@ def test_overlapping_sign_stays_visible_and_chooser_keeps_exact_input():
@pytest.mark.parametrize('profile', ['large', 'compact'])
def test_pip_circles_are_independent_widgets_and_migrate_old_camera_pair(profile):
def test_pip_widgets_match_device_geometry_and_migrate_old_camera_pair(profile):
import copy
document = default_document()
metadata = customization_metadata()['profiles'][profile]['widgets']
assert 'vasm' not in metadata
for key in ('pip_left', 'pip_right'):
for key in camera_widgets(profile):
assert metadata[key]['kind'] == 'pip_camera'
assert metadata[key]['width'] == metadata[key]['height']
right = copy.deepcopy(document['layouts'][profile]['pip_right'])
assert metadata[key]['label'] == (f"Adj Spot Camera {key.removeprefix('pip_').title()}" if profile == 'large' else 'Adj Spot Camera')
assert (metadata[key]['width'], metadata[key]['height']) == ((600, 600) if profile == 'large' else (476, 240))
right = copy.deepcopy(document['layouts']['large']['pip_right'])
document['layouts'][profile]['pip_left']['enabled'] = False
assert validate_document(document)['layouts'][profile]['pip_right'] == right
assert validate_document(document)['layouts']['large']['pip_right'] == right
legacy = copy.deepcopy(document)
for name, layout in legacy['layouts'].items():
layout.pop('pip_left')
layout.pop('pip_right')
layout.pop('pip_right', None)
layout['vasm'] = {'x': 1200 if name == 'large' else 300, 'y': 650 if name == 'large' else 30, 'enabled': False}
migrated = validate_document(legacy)
for name, layout in migrated['layouts'].items():
assert 'vasm' not in layout
assert not layout['pip_left']['enabled'] and not layout['pip_right']['enabled']
assert layout['pip_left']['x'] <= layout['pip_right']['x']
assert all(not layout[key]['enabled'] for key in camera_widgets(name))
if name == 'large':
assert layout['pip_left']['x'] <= layout['pip_right']['x']
assert layout['current_speed' if name == 'large' else 'max_speed'] == document['layouts'][name]['current_speed' if name == 'large' else 'max_speed']
assert validate_document(migrated) == migrated
@@ -1053,3 +1055,18 @@ def test_compact_navigation_upgrade_preserves_saved_layout_and_order():
assert upgraded['layouts']['compact']['nav_card'] == default_document()['layouts']['compact']['nav_card']
assert upgraded['widgetOrder']['compact'] == older['widgetOrder']['compact'] + ['nav_card']
assert {k: v for k, v in upgraded['layouts']['compact'].items() if k != 'nav_card'} == older['layouts']['compact']
def test_c4_camera_upgrade_preserves_visibility_and_other_widgets():
document = default_document()
document["version"] = 16
document["layouts"]["compact"]["pip_left"].update(x=16, y=144, enabled=False)
document["layouts"]["compact"]["pip_right"] = {"x": 380, "y": 144, "enabled": True}
document["widgetColors"]["compact"]["pip_right"] = {}
document["widgetOrder"] = {profile: list(widgets) for profile, widgets in document["layouts"].items()}
migrated = validate_document(document)
assert migrated["layouts"]["compact"]["pip_left"] == {"x": 0, "y": 0, "enabled": True}
assert "pip_right" not in migrated["layouts"]["compact"]
assert migrated["layouts"]["large"] == document["layouts"]["large"]
assert migrated["layouts"]["compact"]["max_speed"] == document["layouts"]["compact"]["max_speed"]
assert validate_document(migrated) == migrated
@@ -45,7 +45,7 @@ class PiPSettingsTests(unittest.TestCase):
from openpilot.starpilot.ui.onroad_customization import PARAM_KEY, default_document, read_customization
document = default_document()
document["layouts"]["large"]["pip_left"]["enabled"] = False
document["layouts"]["compact"]["pip_right"]["enabled"] = False
document["layouts"]["compact"]["pip_left"]["enabled"] = False
layout = Path(self.params.get_param_path(PARAM_KEY))
layout.write_bytes(json.dumps(document).encode())
from openpilot.starpilot.system.starport.projection_layout import (ProjectionLayoutSource, decode_layout_for_viewport,
@@ -61,7 +61,7 @@ class PiPSettingsTests(unittest.TestCase):
self.assertTrue(self.owner.apply(action))
saved = read_customization(self.params)
self.assertTrue(all(saved["layouts"][profile][key]["enabled"]
for profile in ("large", "compact") for key in ("pip_left", "pip_right")))
for profile in ("large", "compact") for key in (("pip_left", "pip_right") if profile == "large" else ("pip_left",))))
projected = decode_layout_for_viewport(projection_path.read_bytes(), viewport)
self.assertTrue(projected["widgets"]["pip_left"]["enabled"] and projected["widgets"]["pip_right"]["enabled"])
# A camera removed while PiP is on stays removed; turning PiP off does not touch the layout.
@@ -111,7 +111,7 @@ class PiPSettingsTests(unittest.TestCase):
path = Path(self.params.get_param_path(MASK))
path.write_bytes(original)
page = self.owner.snapshot(include_editor=True)
self.assertEqual(page.title, 'Blind Spot Camera & Preview')
self.assertEqual(page.title, 'Adj Spot Camera & Preview')
self.assertFalse(any(row.key.startswith(FORMAT_PREFIX) for row in page.rows))
self.assertEqual(path.read_bytes(), original)
editor, source = self.owner.editor_with_source()
@@ -237,7 +237,7 @@ class PiPSettingsTests(unittest.TestCase):
session._pip_request_epoch = 0
session.input = Mock()
session._unavailable = Mock()
link = FeatureRow("", "Blind Spot Camera", "", page="pip", available=True)
link = FeatureRow("", "Adj Spot Camera", "", page="pip", available=True)
session._appearance_ui(FeatureUiAction("open", link))
self.assertEqual(session.appearance_page, "appearance")
session.appearance_page = "pip"
@@ -312,7 +312,7 @@ class PiPSettingsTests(unittest.TestCase):
patch.object(appearance_compact.gui_app, "texture", return_value=None):
appearance_compact.AppearanceCompact(Session()).entry_button().click()
parent = shown[-1]
self.assertFalse(any(item.label == "blind spot camera" for item in parent.items))
self.assertFalse(any(item.label == "Adj Spot Camera" for item in parent.items))
appearance_compact.AppearanceCompact(Session()).open("pip")
child = shown[-1]
next(item for item in child.items if item.label == "show on turn signal").click()
@@ -814,3 +814,28 @@ def test_white_balance_switch_follows_saved_choice(monkeypatch):
FakeParams.value = False
assert switch.enabled(0.5)
assert not switch.enabled(1.5)
def test_c4_shell_passes_full_panel_placements_and_saved_triggers():
from openpilot.starpilot.ui.runtime_app import StarShellSession
from openpilot.starpilot.ui.presentation import Profile
shell = StarShellSession.__new__(StarShellSession)
shell.profile = Profile.COMPACT
shell._pip_saved = SavedPiP((), enabled=True, mask=starting_mask(1928, 1208),
on_blinker=False, on_bsm=True, invert=True)
shell._pip_signals_cache = Signals(True, False, False, True, False)
shell.pip_renderer = Mock()
shell.pip_renderer.render.return_value = "rendered"
document = default_document()
state = SimpleNamespace(customization=document)
shell._render_pip(Rect(0, 0, 476, 240), state)
options = shell.pip_renderer.render.call_args.kwargs
assert options["placements"] == {"left": Rect(0, 0, 476, 240), "right": Rect(0, 0, 476, 240)}
assert options["on_blinker"] is False and options["on_bsm"] is True and options["invert"] is True
submit, draw = Mock(), Mock()
shell._render_pip(Rect(0, 0, 476, 240), state, submit=submit)
shell.pip_renderer.render.call_args.kwargs["submit"]("pip_right", draw)
submit.assert_called_once_with("pip_left", draw)
document["layouts"]["compact"]["pip_left"]["enabled"] = False
shell._render_pip(Rect(0, 0, 476, 240), state)
assert shell.pip_renderer.render.call_args.kwargs["placements"] == {}
@@ -156,7 +156,7 @@ def test_new_layouts_reject_torque_overlap_and_legacy_migration_is_targeted(prof
original = deepcopy(doc)
migrated = validate_document(doc)
assert doc == original
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['palette'] == doc['palette']
assert migrated['layouts']['large']['current_speed'] == doc['layouts']['large']['current_speed']
assert migrated['layouts'][str(profile)][owner]['y'] == default_document()['layouts'][str(profile)][owner]['y']
@@ -48,7 +48,7 @@ def test_v4_migration_preserves_settings_and_clamps_only_enlarged_widgets():
doc['layouts']['large']['cruise_limits'].update(x=1654, y=75)
old_speed = dict(doc['layouts']['large']['current_speed'])
migrated = validate_document(doc)
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['layouts']['large']['cruise_limits']['x'] == 1391
assert migrated['layouts']['large']['current_speed'] == old_speed
assert migrated['speedSources'] is True
@@ -4,6 +4,7 @@ from copy import deepcopy
from types import SimpleNamespace as NS
import unittest
from opendbc.car.honda.values import HondaFlags
from openpilot.starpilot.ui.torque_feedback import observe_torque_feedback
@@ -128,6 +129,27 @@ class TorqueFeedbackTests(unittest.TestCase):
output.lateralControlMode = "newUnknownChannel"
self.assertIsNone(observe(sm, cp).utilization)
def test_accord_angle_loop_shows_angle_error_not_roll(self):
sm = Messages("angleState")
cp = NS(brand="honda", flags=HondaFlags.EPS_ANGLE_LOOP_FW.value, maxLateralAccel=3.5886)
sm["carState"].steeringAngleDeg = 1.0
sm["carState"].vEgo = sm["carState"].vEgoRaw = 26.9
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0
sm["vehicleParameters"].roll = 0.0326 # the device's standing +1.87 deg roll bias
sm["controlsState"].curvature = sm["controlsState"].desiredCurvature = 0.0
self.assertEqual((observe(sm, cp).utilization, observe(sm, cp).source), (0.0, "angle_error"))
self.assertEqual(observe(sm, NS(brand="honda", flags=0, maxLateralAccel=3.5886)).source, "lateral_acceleration_demand",
"without the angle-loop flag the bar shows the lateral-acceleration demand")
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0 + 6.1 # left of the wheel by half the 12.2 deg clip
self.assertAlmostEqual(observe(sm, cp).utilization, -0.5)
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0 - 50.0
self.assertEqual(observe(sm, cp).utilization, 1.0)
sm["carControl"].latActive = False
self.assertEqual(observe(sm, cp).utilization, 0.0)
sm["carControl"].latActive = True
del sm["carOutput"]
self.assertIsNone(observe(sm, cp).utilization)
def test_read_only(self):
sm = Messages("angleState")
before = deepcopy(vars(sm)), repr(sm)
+29 -1
View File
@@ -4,6 +4,9 @@ from dataclasses import dataclass
import math
from typing import Any, Literal
import numpy as np
from opendbc.car.honda.values import CarControllerParams as HondaParams, HondaFlags
DEFAULT_MAX_LATERAL_ACCELERATION = 3.0
LATERAL_STATES = frozenset(("pidState", "angleState", "debugState", "torqueState", "curvatureState",
@@ -13,10 +16,26 @@ LATERAL_STATES = frozenset(("pidState", "angleState", "debugState", "torqueState
@dataclass(frozen=True)
class TorqueFeedback:
utilization: float | None = None
source: Literal["unavailable", "actuator_output", "lateral_acceleration_demand"] = "unavailable"
source: Literal["unavailable", "actuator_output", "lateral_acceleration_demand", "angle_error"] = "unavailable"
reason: str = "car_state_unavailable"
def accord_angle_error_bar(car_params: Any) -> bool:
try:
return car_params.brand == "honda" and bool(car_params.flags & HondaFlags.EPS_ANGLE_LOOP_FW)
except (AttributeError, TypeError):
return False
def accord_angle_error_fraction(setpoint_deg: float, angle_deg: float, v_ego: float) -> float:
"""(setpoint - wheel) over the Accord error clip at this speed, clipped to +-1.
Negated like the torque branch: openpilot angles are left-positive and the bar draws +x to the
right, so the bar must point the way the EPS is pulling the wheel (left pull = bar left)."""
error_max = float(np.interp(v_ego, HondaParams.ANGLE_ERROR_MAX_BP, HondaParams.ANGLE_ERROR_MAX_V))
return float(np.clip(-(setpoint_deg - angle_deg) / error_max, -1.0, 1.0))
def _finite(value: Any) -> float | None:
if type(value) not in (int, float):
return None
@@ -63,6 +82,15 @@ def observe_torque_feedback(car_state: Any, car_control: Any, controls_state: An
return TorqueFeedback(reason="lateral_activity_unavailable")
if not control.latActive:
return TorqueFeedback(0.0, "lateral_acceleration_demand", "lateral_inactive")
# Accord on the angle-loop EPS: show the angle error the setpoint carries, not the lateral-acceleration demand
# (the estimate this replaced subtracted road roll, so the device's standing roll bias drew as a constant pull).
if accord_angle_error_bar(car_params):
setpoint = _finite(getattr(getattr(output, "actuatorsOutput", None), "steeringAngleDeg", None))
angle = _finite(getattr(car, "steeringAngleDeg", None))
speed = _finite(getattr(car, "vEgoRaw", None))
if setpoint is None or angle is None or speed is None:
return TorqueFeedback(reason="actuator_output_unavailable")
return TorqueFeedback(accord_angle_error_fraction(setpoint, angle, speed), "angle_error", "observed")
parameters = vehicle_parameters
if parameters is None or getattr(parameters, "valid", None) is not True:
return TorqueFeedback(reason="vehicle_parameters_unavailable")
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,4 +1,4 @@
#pragma once
extern const uint8_t gitversion[29];
const uint8_t gitversion[29] = "DEV-82f431d8-Pf38f504f-DEBUG";
const uint8_t gitversion[29] = "DEV-b666318e-Pf38f504f-DEBUG";
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More