mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-25 14:23:45 +08:00
Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c14810edd | |||
| 5b21a4ba70 | |||
| 6d5466a32f | |||
| 947bc2026d | |||
| 5dbc1d51b6 | |||
| 48971bc6f9 | |||
| 6a958352e2 | |||
| bf8efea392 | |||
| 88d9b60a13 | |||
| 7392d42e9e | |||
| 8f40396736 | |||
| b094bcb4f7 | |||
| ca16979a38 | |||
| fa0914406f | |||
| c02a563a59 | |||
| 5ef8ef1009 | |||
| f86381d823 | |||
| f6d3829470 | |||
| 00486de7ad | |||
| 206a8554db | |||
| b32fc5ec98 | |||
| 22d4d34405 | |||
| 0b18c93532 | |||
| 0f8f2a5ace | |||
| a1084ad630 | |||
| 6509fa1a00 | |||
| f06a781387 | |||
| 5c20480f13 | |||
| 13b4344a06 | |||
| be196c0baa | |||
| bf0344ffd7 | |||
| 24b5235ed5 | |||
| 725a530d8e | |||
| 1a53844575 | |||
| eaeb680b0a | |||
| 7e9e2b43b3 | |||
| d0a212be98 |
@@ -375,6 +375,7 @@ FW_VERSIONS = {
|
||||
b'68402704AB',
|
||||
b'68402707AB',
|
||||
b'68402708AB',
|
||||
b'68402710AB',
|
||||
b'68402714AB',
|
||||
b'68402736AB',
|
||||
b'68402971AD',
|
||||
@@ -421,6 +422,7 @@ FW_VERSIONS = {
|
||||
b'68412635AH ',
|
||||
b'68412660AD ',
|
||||
b'68412660AF ',
|
||||
b'68422857AD',
|
||||
b'68422860AB',
|
||||
b'68449435AE ',
|
||||
b'68496223AA ',
|
||||
@@ -435,6 +437,7 @@ FW_VERSIONS = {
|
||||
b'68419675AC',
|
||||
b'68419678AB',
|
||||
b'68423905AB',
|
||||
b'68423907AB',
|
||||
b'68449258AC',
|
||||
b'68495807AA',
|
||||
b'68495807AB',
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Recorded ECU identity for the EU 2019 Grand Cherokee, opendbc issue 4101."""
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.chrysler.interface import CarInterface
|
||||
from opendbc.car.chrysler.values import CAR, ChryslerFlags
|
||||
from opendbc.car.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.fw_versions import match_fw_to_car
|
||||
|
||||
Ecu = structs.CarParams.Ecu
|
||||
RECORDED = (
|
||||
(Ecu.combinationMeter, 0x742, b'68402710AB'),
|
||||
(Ecu.srs, 0x744, b'68355363AB'),
|
||||
(Ecu.abs, 0x747, b'68408639AC'),
|
||||
(Ecu.fwdRadar, 0x753, b'04672788AA'),
|
||||
(Ecu.eps, 0x75a, b'68417281AA'),
|
||||
(Ecu.engine, 0x7e0, b'68422857AD'),
|
||||
(Ecu.transmission, 0x7e1, b'68423907AB'),
|
||||
)
|
||||
ADDED = {b'68402710AB', b'68422857AD', b'68423907AB'}
|
||||
|
||||
|
||||
def firmware():
|
||||
return [structs.CarParams.CarFw(ecu=ecu, address=address, fwVersion=version, brand='chrysler', bus=0)
|
||||
for ecu, address, version in RECORDED]
|
||||
|
||||
|
||||
def test_recorded_eu_diesel_is_a_unique_exact_match():
|
||||
fw = firmware()
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
# The route also contains unrelated cross-brand responses at the engine's neighbor.
|
||||
fw.append(structs.CarParams.CarFw(ecu=Ecu.transmission, address=0x7e1, fwVersion=b'\xf1\0\0E\x01\x01', brand='hyundai', bus=1))
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('index', range(len(RECORDED)))
|
||||
def test_unknown_firmware_still_refuses_exact_match(index):
|
||||
fw = firmware()
|
||||
fw[index].fwVersion = b'UNRECOGNIZED'
|
||||
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, set())
|
||||
|
||||
|
||||
def test_additions_are_scoped_to_the_existing_2019_jeep():
|
||||
for identity, ecus in FW_VERSIONS.items():
|
||||
found = {version for versions in ecus.values() for version in versions} & ADDED
|
||||
assert found == (ADDED if identity == CAR.JEEP_GRAND_CHEROKEE_2019 else set())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha_long', (False, True))
|
||||
def test_diesel_retains_stock_acc_pid_and_native_limits(alpha_long):
|
||||
cp = CarInterface.get_params(CAR.JEEP_GRAND_CHEROKEE_2019, {b: {} for b in range(8)}, firmware(), alpha_long, False, False)
|
||||
assert cp.pcmCruise and not cp.openpilotLongitudinalControl
|
||||
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.chrysler
|
||||
assert cp.safetyConfigs[0].safetyParam == 0
|
||||
assert cp.minSteerSpeed == 17.5 and cp.lateralTuning.which() == 'pid'
|
||||
assert cp.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED
|
||||
assert not cp.flags & ChryslerFlags.STEERING_SPEED_BYPASS
|
||||
@@ -124,6 +124,7 @@ class CarController(CarControllerBase):
|
||||
self.apply_angle_last = 0.0
|
||||
self.angle_gain_last = 0.0
|
||||
self.angle_fault_driver_override = False
|
||||
self.stock_angle_lka_active = False
|
||||
self.angle_tx_recovery = (AngleTxRecovery(0xCB, self.CAN.ECAN)
|
||||
if pe_long_qualified(CP) or ev9_long_qualified(CP) else AngleTxRecovery(0x110, self.CAN.ACAN)
|
||||
if CP.carFingerprint in (CAR.HYUNDAI_IONIQ_5_PE, CAR.KIA_EV9) and
|
||||
@@ -544,7 +545,9 @@ class CarController(CarControllerBase):
|
||||
angle_active, self.params, self.angle_vm)
|
||||
self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
|
||||
angle_active, self.angle_gain_last)
|
||||
if not ccnc_ev_stock or ccnc_ev_replacement:
|
||||
stock_angle_handoff = angle_aol and lka_steering and not ccnc_ev_stock
|
||||
if ((not ccnc_ev_stock or ccnc_ev_replacement) and
|
||||
(not stock_angle_handoff or angle_active or self.stock_angle_lka_active)):
|
||||
can_sends.extend(
|
||||
hyundaicanfd.create_angle_steering_messages(
|
||||
self.packer,
|
||||
@@ -558,6 +561,7 @@ class CarController(CarControllerBase):
|
||||
CS.out.steeringAngleDeg,
|
||||
)
|
||||
)
|
||||
self.stock_angle_lka_active = stock_angle_handoff and angle_active
|
||||
else:
|
||||
steering_status_active = CC.enabled
|
||||
if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or
|
||||
|
||||
@@ -256,7 +256,7 @@ def test_ae0_physical_tracker_is_inactive_until_final_ae32(hda2):
|
||||
|
||||
@pytest.mark.parametrize('hda2', (False, True))
|
||||
@pytest.mark.parametrize('corruption', ('crc', 'replay', 'wrong_bus', 'inactive'))
|
||||
def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, corruption):
|
||||
def test_real_controller_forwarding_requires_valid_replacement(hda2, corruption):
|
||||
cp = params(hda2)
|
||||
cp.alternativeExperience = 32
|
||||
ci = CarInterface(cp)
|
||||
@@ -295,7 +295,14 @@ def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, c
|
||||
elif corruption == 'wrong_bus':
|
||||
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data))
|
||||
else:
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if hda2:
|
||||
assert ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))
|
||||
if hda2:
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
safety.set_timer(((now // 1000) + 200_001) & 0xFFFFFFFF)
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
|
||||
|
||||
@@ -347,7 +354,11 @@ def test_real_controller_crc_fault_revokes_token_then_fresh_gesture_recovers(hda
|
||||
assert permission == 0 and not accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == 0
|
||||
if 80 <= tick < 100:
|
||||
assert permission == 0 and safety.safety_fwd_hook(2, addr) == 0
|
||||
assert permission == 0
|
||||
if hda2:
|
||||
assert accepted and ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
|
||||
assert safety.safety_fwd_hook(2, 0x2A4) == 0
|
||||
assert safety.safety_fwd_hook(2, addr) == (-1 if hda2 else 0)
|
||||
if tick >= 115:
|
||||
assert permission == 1 and accepted
|
||||
assert safety.safety_fwd_hook(2, addr) == -1
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
from unittest.mock import Mock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -8,7 +9,7 @@ from opendbc.car.hyundai.canfd_owner import config_index
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff, independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
|
||||
CARS = (CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN)
|
||||
|
||||
@@ -226,3 +227,12 @@ def test_idle_handoff_omits_only_kona_steering_packet():
|
||||
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
|
||||
assert any(frame[0] == 0x12A for frame in before)
|
||||
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
|
||||
|
||||
@pytest.mark.parametrize('panda_type,faults,expected', [('cuatro', [], 0x1C0C), ('redPanda', [], 0x0C0C), ('cuatro', ['fault'], 0x0C0C)])
|
||||
def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faults, expected):
|
||||
cp = kona_params(CARS[0])
|
||||
cp.alternativeExperience = 32
|
||||
cp.safetyConfigs[0].safetyParam = 0x0C0C
|
||||
panda = SimpleNamespace(pandaType=panda_type, faults=faults, ignitionLine=True, ignitionCan=False, controlsAllowed=False)
|
||||
configure_kona_factory_handoff(cp, [panda])
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
|
||||
@@ -30,9 +30,19 @@ AUTO_RESUME_CARS = frozenset((CAR.TOYOTA_HIGHLANDER, CAR.TOYOTA_PRIUS_V, CAR.TOY
|
||||
WORDS = frozenset(word | stock for word in PROFILES.values() for stock in (0, 0x200))
|
||||
|
||||
|
||||
def corolla_startup_mirror(candidate, fingerprint):
|
||||
if candidate != CAR.TOYOTA_COROLLA:
|
||||
return False
|
||||
pt = fingerprint.get(0, {})
|
||||
return pt == fingerprint.get(2, {}) and all(pt.get(address) == length for address, length in
|
||||
((0xAA, 8), (0x262, 5), (0x1D3, 8), (0x343, 8), (0x4CB, 8)))
|
||||
|
||||
|
||||
def hardware_supported(candidate, fingerprint, car_fw):
|
||||
if candidate not in PROFILES or any(address in frames for frames in fingerprint.values() for address in (0x201, 0x2FF, 0x2AA)):
|
||||
return False
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return False
|
||||
camera = fingerprint.get(2, {})
|
||||
if not any(camera.get(address) == 8 for address in (0x343, 0x4CB)) or any(camera.get(address, 8) != 8 for address in (0x343, 0x4CB)):
|
||||
return False
|
||||
|
||||
@@ -29,6 +29,9 @@ def hardware_supported(candidate, fingerprint):
|
||||
return False
|
||||
if 0x2FF in frames and not (candidate == CAR.TOYOTA_CAMRY and _cluster_radar_bus(candidate, bus, frames)):
|
||||
return False
|
||||
from opendbc.car.toyota.dsu_bypass import corolla_startup_mirror
|
||||
if corolla_startup_mirror(candidate, fingerprint):
|
||||
return True
|
||||
camera = fingerprint.get(2, {})
|
||||
if 0x4CB in camera:
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.fingerprints import FW_VERSIONS
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mirrored,expected', ((True, 0x5358), (False, 0x8958)))
|
||||
def test_corolla_camera_relay_mirror_is_not_a_dsu_bypass(mirrored, expected):
|
||||
car = CAR.TOYOTA_COROLLA
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0].update({0xAA: 8, 0x262: 5, 0x1D3: 8, 0x343: 8, 0x4CB: 8, 0x283: 7})
|
||||
fp[2].update(fp[0] if mirrored else {0x343: 8, 0x4CB: 8})
|
||||
fw = [structs.CarParams.CarFw(ecu=ecu, address=addr, subAddress=sub or 0, fwVersion=versions[0], brand='toyota', bus=0)
|
||||
for (ecu, addr, sub), versions in FW_VERSIONS[car].items()]
|
||||
|
||||
cp = CarInterface.get_params(car, fp, fw, False, True, False)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert cp.pcmCruise
|
||||
assert cp.openpilotLongitudinalControl is (not mirrored)
|
||||
@@ -232,6 +232,8 @@ typedef bool (*tx_hook)(const CANPacket_t *msg); // returns true if the message
|
||||
typedef bool (*fwd_hook)(int bus_num, int addr); // returns true if the message should be blocked from forwarding
|
||||
|
||||
typedef bool (*fwd_packet_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*stage_tx_hook)(const CANPacket_t *msg);
|
||||
typedef bool (*fwd_output_hook)(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
|
||||
typedef struct {
|
||||
safety_hook_init init;
|
||||
@@ -240,6 +242,8 @@ typedef struct {
|
||||
tx_hook tx;
|
||||
fwd_hook fwd;
|
||||
fwd_packet_hook fwd_packet;
|
||||
stage_tx_hook stage_tx;
|
||||
fwd_output_hook fwd_output;
|
||||
get_checksum_t get_checksum;
|
||||
compute_checksum_t compute_checksum;
|
||||
get_counter_t get_counter;
|
||||
@@ -371,6 +375,11 @@ extern safety_config current_safety_config;
|
||||
|
||||
int safety_fwd_hook(int bus_num, int addr);
|
||||
int safety_fwd_packet_hook(const CANPacket_t *msg);
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg);
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now);
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg);
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
|
||||
int set_safety_hooks(uint16_t mode, uint16_t param);
|
||||
|
||||
extern const safety_hooks body_hooks;
|
||||
|
||||
@@ -19,6 +19,8 @@ static bool blended_aol_token = false;
|
||||
static bool blended_aol_claimed = false;
|
||||
static bool blended_aol_session = false;
|
||||
static bool blended_aol_request_seen = false;
|
||||
static bool blended_aol_brake_continuation = false;
|
||||
static bool blended_aol_idle_owned[2] = {false, false};
|
||||
static bool blended_aol_neutral[3] = {false, false, false};
|
||||
static bool blended_aol_pressed[3] = {false, false, false};
|
||||
static uint32_t blended_aol_source_ts[3] = {0U, 0U, 0U};
|
||||
@@ -44,6 +46,9 @@ static void blended_aol_clear(void) {
|
||||
blended_aol_claimed = false;
|
||||
blended_aol_session = false;
|
||||
blended_aol_request_seen = false;
|
||||
blended_aol_brake_continuation = false;
|
||||
blended_aol_idle_owned[0] = false;
|
||||
blended_aol_idle_owned[1] = false;
|
||||
blended_aol_token_ts = 0U;
|
||||
blended_aol_token_source = 3U;
|
||||
aol_host_axis_mask = 0U;
|
||||
@@ -71,6 +76,9 @@ static void blended_aol_reset(void) {
|
||||
|
||||
static void blended_aol_host_request(uint8_t mask) {
|
||||
blended_aol_request_seen |= mask != 0U;
|
||||
if ((mask & 1U) == 0U) {
|
||||
blended_aol_brake_continuation = false;
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t blended_aol_request_mask(void) {
|
||||
@@ -107,7 +115,7 @@ static uint8_t blended_aol_permission_mask(void) {
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_source_ts[blended_aol_token_source]) <= 300000U);
|
||||
if (!aol_rx_healthy() || (blended_aol_token && !source_current)) {
|
||||
blended_aol_clear();
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token)) {
|
||||
} else if (((blended_aol_request_mask() & 1U) != 0U) && (controls_allowed || blended_aol_token || blended_aol_brake_continuation)) {
|
||||
result = 1U;
|
||||
} else {
|
||||
}
|
||||
@@ -145,6 +153,14 @@ static void blended_aol_rx(const CANPacket_t *msg) {
|
||||
if (blended_aol_enabled) {
|
||||
const unsigned int pt = blended_aol_hda2 ? 1U : 0U;
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
if (blended_aol_hda2 && !blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
const bool brake = ((msg->data[5] >> 5U) & 3U) == 2U;
|
||||
if (brake && !brake_pressed && controls_allowed && blended_aol_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US) &&
|
||||
((blended_aol_request_mask() & 1U) != 0U) && aol_rx_healthy()) {
|
||||
blended_aol_brake_continuation = true;
|
||||
}
|
||||
}
|
||||
if (blended_aol_long && msg_matches(msg, 0x394U, pt, 8U)) {
|
||||
blended_aol_main_seen = true;
|
||||
blended_aol_main = ((msg->data[5] >> 3U) & 3U) == 0U;
|
||||
@@ -323,6 +339,19 @@ static void blended_aol_tx(const CANPacket_t *msg, bool accepted) {
|
||||
}
|
||||
}
|
||||
accepted_current &= active;
|
||||
if (blended_aol_hda2) {
|
||||
const bool zero_torque = (((msg->data[6] & 0xFU) << 7U) | (msg->data[5] >> 1U)) == 1024U;
|
||||
blended_aol_idle_owned[0] = accepted && !active && zero_torque && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction;
|
||||
if (!blended_aol_idle_owned[0]) {
|
||||
blended_aol_idle_owned[1] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (blended_aol_hda2 && (msg->addr == 0x2A4U) && (msg->bus == 0U) && !retain_camera_ownership) {
|
||||
blended_aol_idle_owned[1] = accepted && blended_aol_idle_owned[0] && aol_rx_healthy() &&
|
||||
!safety_rx_checks_invalid && !relay_malfunction &&
|
||||
(safety_get_ts_elapsed(microsecond_timer_get(), blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
}
|
||||
for (unsigned int i = 0U; i < count; i++) {
|
||||
const unsigned int bus = blended_aol_hda2 && (i >= 2U) ? 1U : 0U;
|
||||
@@ -339,6 +368,16 @@ static bool blended_aol_fwd(int bus, int addr) {
|
||||
bool blocked = blended_aol_long && !blended_aol_enabled && (bus == 2) &&
|
||||
((addr == (blended_aol_hda2 ? 0x50 : 0x340)) ||
|
||||
(addr == (blended_aol_hda2 ? 0x2A4 : 0x364)) || (!blended_aol_hda2 && (addr == 0x485)));
|
||||
if (blended_aol_enabled && blended_aol_hda2 && (bus == 2) &&
|
||||
aol_rx_healthy() && !safety_rx_checks_invalid && !relay_malfunction) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const bool primary_current = blended_aol_idle_owned[0] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US);
|
||||
if (primary_current) {
|
||||
blocked |= (addr == 0x50) || ((addr == 0x2A4) && blended_aol_idle_owned[1] &&
|
||||
(safety_get_ts_elapsed(now, blended_aol_tx_ts[1]) <= AOL_HOST_REQUEST_TIMEOUT_US));
|
||||
}
|
||||
}
|
||||
if (blended_aol_enabled && (bus == 2) && aol_rx_healthy() && (controls_allowed || (blended_aol_permission_mask() != 0U))) {
|
||||
const uint32_t addresses[4] = {blended_aol_hda2 ? 0x50U : 0x340U, blended_aol_hda2 ? 0x2A4U : 0x364U, 0x485U, 0x340U};
|
||||
const unsigned int count = blended_aol_hda2 ? 2U : 3U;
|
||||
|
||||
@@ -820,12 +820,15 @@ static safety_config hyundai_canfd_gv60_extend_tx(const safety_config original,
|
||||
}
|
||||
#endif
|
||||
|
||||
#define HYUNDAI_CANFD_STEER_MAX_TORQUE 409
|
||||
#define HYUNDAI_CANFD_STEER_MAX_RATE_UP 10
|
||||
|
||||
static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
static uint8_t hyundai_canfd_ioniq6_lfa_mirror[4] = {0};
|
||||
const TorqueSteeringLimits HYUNDAI_CANFD_STEERING_LIMITS = {
|
||||
.max_torque = 409,
|
||||
.max_torque = HYUNDAI_CANFD_STEER_MAX_TORQUE,
|
||||
.max_rt_delta = 375,
|
||||
.max_rate_up = 10,
|
||||
.max_rate_up = HYUNDAI_CANFD_STEER_MAX_RATE_UP,
|
||||
.max_rate_down = 3,
|
||||
.driver_torque_allowance = 250,
|
||||
.driver_torque_multiplier = 2,
|
||||
@@ -1228,7 +1231,7 @@ static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
|
||||
return tx;
|
||||
}
|
||||
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
static bool hyundai_kona_idle_handoff = false;
|
||||
static bool hyundai_kona_camera_seen = false;
|
||||
static bool hyundai_kona_output_seen = false;
|
||||
@@ -1237,6 +1240,11 @@ static uint32_t hyundai_kona_camera_ts = 0U;
|
||||
static uint32_t hyundai_kona_output_ts = 0U;
|
||||
static uint8_t hyundai_kona_camera_counter = 0U;
|
||||
static uint8_t hyundai_kona_output_counter = 0U;
|
||||
static bool hyundai_kona_pending = false;
|
||||
static bool hyundai_kona_emitting = false;
|
||||
static bool hyundai_kona_slot_owned = false;
|
||||
static uint32_t hyundai_kona_pending_ts = 0U;
|
||||
static CANPacket_t hyundai_kona_pending_msg;
|
||||
|
||||
static bool hyundai_kona_host_steering(void) {
|
||||
return controls_allowed || ((aol_get_permission_mask() & 1U) != 0U);
|
||||
@@ -1262,26 +1270,107 @@ static void hyundai_kona_track_output(uint32_t now, bool host, uint8_t counter)
|
||||
hyundai_kona_output_counter = counter;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_fwd(const CANPacket_t *msg) {
|
||||
static bool hyundai_kona_camera_without_slot(const CANPacket_t *msg) {
|
||||
return hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
return (msg->bus == 2U) && hyundai_kona_output_seen && hyundai_kona_host_output &&
|
||||
hyundai_kona_camera_seen && !relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy() &&
|
||||
!hyundai_kona_host_steering() && hyundai_kona_lfa_valid(msg) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_output_counter) == 1U) &&
|
||||
((uint8_t)(msg->data[2] - hyundai_kona_camera_counter) == 1U) &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 20000U);
|
||||
}
|
||||
|
||||
static bool hyundai_kona_stage_tx(const CANPacket_t *msg) {
|
||||
bool staged = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && (msg->bus == 0U)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const uint8_t source_delta = (uint8_t)(hyundai_kona_camera_counter - msg->data[2]);
|
||||
staged = !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 20000U) && (source_delta <= 1U);
|
||||
if (staged) {
|
||||
hyundai_kona_pending_msg = *msg;
|
||||
hyundai_kona_pending_ts = now;
|
||||
hyundai_kona_pending = true;
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
}
|
||||
}
|
||||
return staged;
|
||||
}
|
||||
|
||||
static bool hyundai_kona_camera_output(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
bool blocked = false;
|
||||
if (hyundai_kona_idle_handoff && (msg->bus == 2U) && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
const bool valid = hyundai_kona_lfa_valid(msg);
|
||||
if (valid) {
|
||||
const uint8_t delta = (uint8_t)(msg->data[2] - hyundai_kona_camera_counter);
|
||||
if (!hyundai_kona_camera_seen ||
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) > 50000U) ||
|
||||
((delta > 0U) && (delta <= 127U))) {
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_counter = msg->data[2];
|
||||
hyundai_kona_camera_ts = now;
|
||||
}
|
||||
}
|
||||
blocked = !valid || safety_rx_checks_invalid || !aol_rx_healthy() || hyundai_kona_host_steering() ||
|
||||
(msg->data[2] != hyundai_kona_camera_counter) ||
|
||||
!hyundai_kona_output_ready(now, false, msg->data[2]);
|
||||
const uint8_t counter = msg->data[2];
|
||||
const uint32_t camera_age = safety_get_ts_elapsed(now, hyundai_kona_camera_ts);
|
||||
const uint8_t delta = (uint8_t)(counter - hyundai_kona_camera_counter);
|
||||
const bool advancing = (delta > 0U) && (delta <= 127U);
|
||||
const bool consecutive = hyundai_kona_camera_seen && (delta == 1U) && (camera_age <= 20000U);
|
||||
blocked = !hyundai_kona_lfa_valid(msg) || safety_rx_checks_invalid || !aol_rx_healthy() ||
|
||||
(hyundai_kona_camera_seen && (camera_age <= 50000U) && !advancing);
|
||||
if (!blocked) {
|
||||
hyundai_kona_track_output(now, false, msg->data[2]);
|
||||
hyundai_kona_camera_counter = counter;
|
||||
hyundai_kona_camera_seen = true;
|
||||
hyundai_kona_camera_ts = now;
|
||||
|
||||
const bool authority = hyundai_kona_host_steering();
|
||||
if (!authority) {
|
||||
hyundai_kona_slot_owned = false;
|
||||
}
|
||||
if (authority && consecutive && hyundai_kona_pending &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_pending_ts) <= 20000U)) {
|
||||
CANPacket_t candidate = hyundai_kona_pending_msg;
|
||||
const uint8_t source_delta = (uint8_t)(counter - candidate.data[2]);
|
||||
const uint8_t camera_grade = (msg->data[4] >> 6U) | ((msg->data[5] & 1U) << 2U);
|
||||
const bool camera_warning = (camera_grade >= 4U) || ((msg->data[7] & 0xF0U) != 0U);
|
||||
if (camera_warning) {
|
||||
candidate.data[4] = (candidate.data[4] & 0x3FU) | (msg->data[4] & 0xC0U);
|
||||
candidate.data[5] = (candidate.data[5] & 0xFEU) | (msg->data[5] & 0x01U);
|
||||
candidate.data[7] = (candidate.data[7] & 0x0FU) | (msg->data[7] & 0xF0U);
|
||||
}
|
||||
const unsigned int raw_torque = (((unsigned int)candidate.data[6] & 0xFU) << 7U) | (candidate.data[5] >> 1U);
|
||||
const int torque = (int)raw_torque - 1024;
|
||||
if ((source_delta <= 2U) &&
|
||||
!safety_max_limit_check(torque, HYUNDAI_CANFD_STEER_MAX_TORQUE, -HYUNDAI_CANFD_STEER_MAX_TORQUE)) {
|
||||
if (GET_BIT(&candidate, 52U)) {
|
||||
const int max_torque = SAFETY_MAX(desired_torque_last, 0) + HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const int min_torque = SAFETY_MIN(desired_torque_last, 0) - HYUNDAI_CANFD_STEER_MAX_RATE_UP;
|
||||
const unsigned int raw = (unsigned int)(SAFETY_CLAMP(torque, min_torque, max_torque) + 1024);
|
||||
candidate.data[5] = (candidate.data[5] & 0x01U) | (uint8_t)((raw & 0x7FU) << 1U);
|
||||
candidate.data[6] = (candidate.data[6] & 0xF0U) | (uint8_t)(raw >> 7U);
|
||||
}
|
||||
candidate.data[2] = counter;
|
||||
const uint16_t checksum = hyundai_common_canfd_compute_checksum(&candidate) ^ 0x041DU;
|
||||
candidate.data[0] = (uint8_t)checksum;
|
||||
candidate.data[1] = (uint8_t)(checksum >> 8U);
|
||||
hyundai_kona_emitting = true;
|
||||
*replaced = safety_tx_hook(&candidate);
|
||||
hyundai_kona_emitting = false;
|
||||
if (*replaced) {
|
||||
*output = candidate;
|
||||
hyundai_kona_slot_owned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
hyundai_kona_pending = false;
|
||||
if (!*replaced) {
|
||||
const bool camera_neutral = ((msg->data[6] & 0x3FU) == 0x08U) && ((msg->data[5] & 0xFEU) == 0U);
|
||||
blocked = (hyundai_kona_slot_owned && !camera_neutral) ||
|
||||
!hyundai_kona_output_ready(now, false, counter);
|
||||
if (!blocked) {
|
||||
if (hyundai_kona_host_output) {
|
||||
desired_torque_last = 0;
|
||||
}
|
||||
hyundai_kona_track_output(now, false, counter);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hyundai_kona_pending = false;
|
||||
}
|
||||
}
|
||||
return blocked;
|
||||
@@ -1292,6 +1381,7 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
bool tx = false;
|
||||
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
|
||||
bool ordinary_angle_valid = true;
|
||||
const bool stock_angle_hda2 = hyundai_angle_aol_enabled && hyundai_canfd_lka_steer_msg && !hyundai_canfd_ccnc_ev_long;
|
||||
const bool independent_command = hyundai_angle_aol_enabled &&
|
||||
((msg->addr == 0x50U) || (msg->addr == 0x110U) ||
|
||||
((msg->addr == 0x12AU) && !hyundai_canfd_angle_observed_adas) || (msg->addr == 0xCBU));
|
||||
@@ -1308,9 +1398,18 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
ordinary_angle_valid &= (delta > 0U) && (delta <= 127U);
|
||||
}
|
||||
} else {
|
||||
if (stock_angle_hda2) {
|
||||
const uint32_t xor_out = (GET_LEN(msg) == 16U) ? 0x041DU : 0U;
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ xor_out));
|
||||
}
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
}
|
||||
if (stock_angle_hda2 && ((msg->addr == 0x2A4U) || (msg->addr == 0x362U))) {
|
||||
ordinary_angle_valid = hyundai_ordinary_angle_owner_current() &&
|
||||
(hyundai_canfd_get_checksum(msg) == hyundai_common_canfd_compute_checksum(msg));
|
||||
}
|
||||
if (hyundai_ordinary_angle_stock && !hyundai_angle_aol_enabled) {
|
||||
// Core whitelisting precedes this hook; relay is its only final denial.
|
||||
ordinary_angle_valid = !relay_malfunction;
|
||||
@@ -1348,7 +1447,7 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
if (hyundai_angle_aol_enabled && independent_command && !tx) {
|
||||
hyundai_ordinary_angle_release();
|
||||
}
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU) && tx && !relay_malfunction) {
|
||||
hyundai_kona_track_output(microsecond_timer_get(), true, msg->data[2]);
|
||||
}
|
||||
@@ -1357,18 +1456,18 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
|
||||
}
|
||||
|
||||
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
bool allowed = true;
|
||||
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
|
||||
const uint32_t now = microsecond_timer_get();
|
||||
allowed = !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
allowed = hyundai_kona_emitting && !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() &&
|
||||
hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen &&
|
||||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 50000U) &&
|
||||
(msg->data[2] == hyundai_kona_camera_counter) && hyundai_kona_output_ready(now, true, msg->data[2]);
|
||||
}
|
||||
#endif
|
||||
return
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
allowed &&
|
||||
#endif
|
||||
hyundai_canfd_tx_hook_checked(msg);
|
||||
@@ -1873,8 +1972,8 @@ static safety_config hyundai_canfd_init_validated(uint16_t supplied_param) {
|
||||
{0x1DA, 1, 32, .check_relay = false},
|
||||
};
|
||||
static const CanMsg ioniq6_long_lkas_alt_tx_msgs[] = {
|
||||
{0x110, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x362, 0, 32, .check_relay = true, .disable_static_blocking = true},
|
||||
{0x110, 0, 32, .check_relay = true},
|
||||
{0x362, 0, 32, .check_relay = true},
|
||||
{0x12A, 1, 16, .check_relay = false},
|
||||
{0x1E0, 1, 16, .check_relay = false},
|
||||
{0x1A0, 1, 32, .check_relay = true, .check_relay_immediately = true},
|
||||
@@ -2325,10 +2424,13 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
|
||||
hyundai_daw_init(true, false);
|
||||
hyundai_canfd_reset_ioniq6_state();
|
||||
hyundai_ordinary_angle_reset();
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4) && !defined(PANDA_BODY)
|
||||
hyundai_kona_idle_handoff = (raw_param == 0x1C0CU) && (alternative_experience == 32);
|
||||
hyundai_kona_camera_seen = false;
|
||||
hyundai_kona_output_seen = false;
|
||||
hyundai_kona_pending = false;
|
||||
hyundai_kona_emitting = false;
|
||||
hyundai_kona_slot_owned = false;
|
||||
const bool kona_profile_valid = (raw_param != 0x1C0CU) || hyundai_kona_idle_handoff;
|
||||
const uint16_t param = hyundai_kona_idle_handoff ? 0x0C0CU : raw_param;
|
||||
const bool valid = !GET_FLAG(param, 32768U) || (param == 0x8015U) || (param == 0x8095U) ||
|
||||
@@ -2351,7 +2453,7 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
|
||||
const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) ||
|
||||
(param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U);
|
||||
ret = hyundai_daw_configure(ret, true, daw_profile);
|
||||
#ifdef ALLOW_DEBUG
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
if (hyundai_kona_idle_handoff) {
|
||||
static CanMsg kona_tx[64];
|
||||
if (hyundai_canfd_angle_aol_capacity(&ret)) {
|
||||
@@ -2375,8 +2477,10 @@ const safety_hooks hyundai_canfd_hooks = {
|
||||
.optional_rx = hyundai_canfd_optional_rx_hook,
|
||||
.tx = hyundai_canfd_tx_hook,
|
||||
.fwd = hyundai_canfd_fwd_hook,
|
||||
#ifdef ALLOW_DEBUG
|
||||
.fwd_packet = hyundai_kona_camera_fwd,
|
||||
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
|
||||
.fwd_packet = hyundai_kona_camera_without_slot,
|
||||
.stage_tx = hyundai_kona_stage_tx,
|
||||
.fwd_output = hyundai_kona_camera_output,
|
||||
#endif
|
||||
.get_counter = hyundai_canfd_get_counter,
|
||||
.get_checksum = hyundai_canfd_get_checksum,
|
||||
|
||||
@@ -366,6 +366,55 @@ int safety_fwd_packet_hook(const CANPacket_t *msg) {
|
||||
return destination_bus;
|
||||
}
|
||||
|
||||
#if !defined(STM32F4) && (defined(ALLOW_DEBUG) || !defined(STM32H7))
|
||||
bool safety_uses_camera_slot(const CANPacket_t *msg) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return (current_safety_mode == SAFETY_HYUNDAI_CANFD) && hyundai_kona_idle_handoff && (msg->addr == 0x12AU);
|
||||
#else
|
||||
(void)msg;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_camera_release_current(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
return safety_uses_camera_slot(msg) && hyundai_kona_camera_release_current(msg, now);
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint32_t safety_camera_release_delay(const CANPacket_t *msg, uint32_t now) {
|
||||
#ifdef ALLOW_DEBUG
|
||||
const uint32_t age = safety_get_ts_elapsed(now, hyundai_kona_output_ts);
|
||||
return ((age >= 9000U) && (age < 10000U) && safety_camera_release_current(msg, now)) ? (10000U - age) : 0U;
|
||||
#else
|
||||
(void)msg;
|
||||
(void)now;
|
||||
return 0U;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool safety_stage_tx_hook(const CANPacket_t *msg) {
|
||||
return !relay_malfunction && (current_hooks->stage_tx != NULL) && current_hooks->stage_tx(msg);
|
||||
}
|
||||
|
||||
int safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
|
||||
int destination;
|
||||
if (current_hooks->fwd_output != NULL) {
|
||||
destination = safety_fwd_hook(msg->bus, msg->addr);
|
||||
if ((destination >= 0) && current_hooks->fwd_output(msg, output, replaced)) {
|
||||
destination = -1;
|
||||
}
|
||||
} else {
|
||||
destination = safety_fwd_packet_hook(msg);
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
#endif
|
||||
|
||||
// 1Hz safety function called by main. Now just a check for lagging safety messages
|
||||
void safety_tick(void) {
|
||||
const uint8_t MAX_MISSED_MSGS = 10U;
|
||||
|
||||
@@ -11,6 +11,11 @@ SAFETY_UNUSED(safety_rx_hook);
|
||||
SAFETY_UNUSED(safety_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_hook);
|
||||
SAFETY_UNUSED(safety_fwd_packet_hook);
|
||||
SAFETY_UNUSED(safety_uses_camera_slot);
|
||||
SAFETY_UNUSED(safety_camera_release_current);
|
||||
SAFETY_UNUSED(safety_camera_release_delay);
|
||||
SAFETY_UNUSED(safety_stage_tx_hook);
|
||||
SAFETY_UNUSED(safety_fwd_output_hook);
|
||||
SAFETY_UNUSED(safety_tick);
|
||||
SAFETY_UNUSED(set_safety_hooks);
|
||||
// Exported to Panda's USB status handler and the native safety test library.
|
||||
|
||||
@@ -221,3 +221,47 @@ class TestHyundaiBlendedStock(unittest.TestCase):
|
||||
self.safety.safety_rx_hook(common.make_msg(0, 0x50, 16))
|
||||
self.assertTrue(self.safety.get_relay_malfunction())
|
||||
self.safety.set_alternative_experience(0)
|
||||
|
||||
def _start_hda2_aol(self):
|
||||
self.safety.init_tests()
|
||||
self.safety.set_alternative_experience(32)
|
||||
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hyundai, 0x2010), 0)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.steer_counter = 0
|
||||
self.bus = 1
|
||||
self._refresh_hda2_aol_rx(1_000_000)
|
||||
self.safety.aol_set_host_request(1)
|
||||
|
||||
def _refresh_hda2_aol_rx(self, now):
|
||||
self.safety.set_timer(now)
|
||||
for status in self.safety.rx_status:
|
||||
status.msg_seen = status.valid_checksum = status.valid_quality_flag = True
|
||||
status.last_timestamp = now
|
||||
|
||||
def test_hda2_brake_retains_aol_only_after_accepted_steering(self):
|
||||
for steering_before_brake in (False, True):
|
||||
self._start_hda2_aol()
|
||||
self.assertTrue(self.safety.safety_rx_hook(common.make_msg(1, 0x4F1, dat=bytes([1, 0, 0, 0]))))
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.scc(0, True)))
|
||||
self.assertTrue(self.safety.get_controls_allowed())
|
||||
if steering_before_brake:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(3)))
|
||||
self._refresh_hda2_aol_rx(1_010_000)
|
||||
brake = common.make_msg(1, 0x394, dat=bytes.fromhex('036c000003449798'))
|
||||
self.assertTrue(self.safety.safety_rx_hook(brake))
|
||||
self.assertFalse(self.safety.get_controls_allowed())
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(self.steer(3))), steering_before_brake)
|
||||
self.safety.aol_set_host_request(0)
|
||||
self.safety.aol_set_host_request(1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.steer(3)))
|
||||
|
||||
def test_hda2_idle_blocks_duplicate_only_while_host_steering_is_fresh(self):
|
||||
self._start_hda2_aol()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.steer(0, False)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x421), 0)
|
||||
self._refresh_hda2_aol_rx(1_500_000)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
|
||||
@@ -249,6 +249,26 @@ class TestHyundaiBlendedAlphaAol(unittest.TestCase):
|
||||
for _ in range(8):
|
||||
self.feed()
|
||||
|
||||
def test_hda2_idle_steering_has_one_forwarding_owner(self):
|
||||
if self.release:
|
||||
self.skipTest("Mixed Alpha Long requires the debug safety build")
|
||||
self.reset(0x2014)
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
steering = self.packer.make_can_msg_safety('LKAS', 0, {'COUNTER': 1, 'TORQUE_REQUEST': 0})
|
||||
self.assertTrue(self.safety.safety_tx_hook(steering))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
camera = self.packer.make_can_msg_safety('CAM_0x2a4', 0, {'COUNTER': self.counter - 1})
|
||||
self.assertTrue(self.safety.safety_tx_hook(camera))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), -1)
|
||||
self.assertEqual(self.request(3), 0)
|
||||
self.now += 500_000
|
||||
self.warm()
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x50), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x2A4), 0)
|
||||
|
||||
def test_hdai_withdrawal_consumes_valid_counter_without_output_credit(self):
|
||||
from opendbc.car.hyundai.hyundaican import hyundai_checksum
|
||||
|
||||
|
||||
@@ -68,6 +68,19 @@ class TestHyundaiIoniq6Long(unittest.TestCase):
|
||||
self.assertTrue(self.safety.safety_rx_hook(self.packet(lamp)))
|
||||
return corner, lamp
|
||||
|
||||
def test_replacement_steering_blocks_factory_copies_for_both_hda2_topologies(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
for words in (RAW_LONG, RAW_AOL):
|
||||
for topology, word in words.items():
|
||||
with self.subTest(topology=topology, word=hex(word)):
|
||||
self.mode(word)
|
||||
addresses = (0x110, 0x362) if topology == "lkas_alt" else (0x50, 0x2A4)
|
||||
for address in addresses:
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(0, address), 2)
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), 0)
|
||||
|
||||
def test_bsm_all_sixteen_physical_states_and_exact_paired_frames(self):
|
||||
if self.release:
|
||||
self.skipTest("RELEASE denies all four exact Ioniq 6 LONG profiles")
|
||||
|
||||
@@ -25,54 +25,84 @@ class TestHyundaiKonaCcncHandoff(unittest.TestCase):
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
for experience in ((0,) if debug else (0, 32)):
|
||||
self.mode(0x1C0C, experience)
|
||||
self.assertFalse(self.safety.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(self.safety.safety_camera_release_current(camera, 0))
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(camera, 0), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, 0x123), -1)
|
||||
|
||||
def test_release_library_camera_slot_helpers_are_inactive(self):
|
||||
release = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True))
|
||||
release.set_alternative_experience(32)
|
||||
self.assertEqual(release.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0x1C0C), 0)
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
self.assertFalse(release.safety_uses_camera_slot(camera))
|
||||
self.assertFalse(release.safety_camera_release_current(camera, 10_000))
|
||||
self.assertEqual(release.safety_camera_release_delay(camera, 10_000), 0)
|
||||
self.assertEqual(release.safety_fwd_packet_hook(camera), -1)
|
||||
|
||||
def test_output_hook_preserves_default_forwarding(self):
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundai, 0), 0)
|
||||
for source, destination in ((0, 2), (1, -1), (2, 0)):
|
||||
packet = libsafety_py.make_CANPacket(0x123, source, bytes(8))
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(packet), destination)
|
||||
self.assertEqual(self.forward(packet)[:2], (destination, False))
|
||||
|
||||
def forward(self, packet):
|
||||
output = libsafety_py.new_CANPacket()
|
||||
replaced = libsafety_py.ffi.new('bool *')
|
||||
bus = self.safety.safety_fwd_output_hook(packet, output, replaced)
|
||||
return bus, bool(replaced[0]), output
|
||||
|
||||
def test_handoff_requires_current_camera_and_one_output_owner(self):
|
||||
if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0:
|
||||
self.skipTest('Kona factory handoff is DEBUG only')
|
||||
camera = self.packet(2, 'a6770a1880001800000a000000900000')
|
||||
self.mode(0x0C0C)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
|
||||
self.mode(0x1C0C)
|
||||
self.safety.set_timer(1_000_000)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
for status in self.safety.rx_status:
|
||||
status.msg_seen = True
|
||||
status.valid_checksum = True
|
||||
status.valid_quality_flag = True
|
||||
status.last_timestamp = 1_000_000
|
||||
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera), -1)
|
||||
self.assertEqual(self.forward(camera)[:2], (0, False))
|
||||
self.assertEqual(self.forward(camera)[0], -1)
|
||||
corrupt = self.packet(2, 'a6770a1881001800000a000000900000')
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(corrupt), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
self.assertEqual(self.forward(corrupt)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(self.packet(0, 'a6770a1880001800000a000000900000')))
|
||||
warning = self.packet(2, '784d1400000108f0000a000000640000')
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(warning), 0)
|
||||
self.assertEqual(self.forward(warning)[:2], (0, False))
|
||||
self.safety.set_controls_allowed(True)
|
||||
self.safety.set_aol_test_heartbeat(True)
|
||||
self.safety.aol_set_host_request(3)
|
||||
following = self.packet(2, '110d1600000108f0000a000000640000')
|
||||
host = self.packet(0, 'a009150280001800000a000000900000')
|
||||
self.safety.set_timer(1_009_999)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host)) # Require the matching camera counter first.
|
||||
camera_match = self.packet(2, '5ce51500000108f0000a000000640000')
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(camera_match), -1)
|
||||
host[0].data[2] = 20
|
||||
from opendbc.car.hyundai.hyundaicanfd import hkg_can_fd_checksum
|
||||
crc = hkg_can_fd_checksum(0x12A, None, bytearray(host[0].data[0:16]))
|
||||
host[0].data[0], host[0].data[1] = crc & 255, crc >> 8
|
||||
self.safety.set_timer(1_005_000)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
self.assertTrue(self.safety.safety_stage_tx_hook(host))
|
||||
self.safety.set_timer(1_010_000)
|
||||
self.assertTrue(self.safety.safety_tx_hook(host))
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
match = self.packet(2, '5ce51500000108f0000a000000640000')
|
||||
bus, replaced, output = self.forward(match)
|
||||
self.assertEqual((bus, replaced, output[0].data[2]), (0, True, 21))
|
||||
self.assertEqual(output[0].data[7] & 0xF0, 0xF0)
|
||||
|
||||
self.safety.set_controls_allowed(False)
|
||||
self.safety.aol_set_host_request(0)
|
||||
following = self.packet(2, '110d1600000108f0000a000000640000')
|
||||
self.safety.set_timer(1_019_999)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.assertEqual(self.safety.safety_camera_release_delay(following, 1_019_999), 1)
|
||||
self.safety.set_timer(1_020_000)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), 0)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.assertEqual(self.forward(following)[:2], (0, False))
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.safety.set_relay_malfunction(True)
|
||||
self.assertEqual(self.safety.safety_fwd_packet_hook(following), -1)
|
||||
self.assertFalse(self.safety.safety_tx_hook(host))
|
||||
self.assertEqual(self.forward(following)[0], -1)
|
||||
self.assertFalse(self.safety.safety_stage_tx_hook(host))
|
||||
|
||||
@@ -4,6 +4,7 @@ import unittest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
|
||||
@@ -98,6 +99,8 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 3)))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 4, active=False)))
|
||||
if topology.startswith('lka'):
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 5, active=False)))
|
||||
self.assertFalse(self.safety.safety_test_selected_fwd(2, address))
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.command(word, 5)))
|
||||
self.safety.set_timer(1_300_001)
|
||||
@@ -105,6 +108,38 @@ class TestHyundaiStockAngleAol(unittest.TestCase):
|
||||
self.assertEqual(self.safety.aol_get_permission_mask(), 0)
|
||||
self.assertFalse(self.safety.safety_tx_hook(self.command(word, 6)))
|
||||
|
||||
def test_hda2_controller_sends_only_one_inactive_release(self):
|
||||
car = angle_profiles.CARS[0]
|
||||
for topology, address, camera_name in (('lka', 0x50, 'CAM_0x2a4'), ('lka_alt', 0x110, 'CAM_0x362')):
|
||||
cp = angle_profiles.params(car, topology, hybrid=True)
|
||||
cp.alternativeExperience = 32
|
||||
word = cp.safetyConfigs[-1].safetyParam
|
||||
self.mode(word)
|
||||
self.sources(word)
|
||||
self.gesture(word)
|
||||
interface = CarInterface(cp)
|
||||
packer, frames = angle_profiles.source_frames(cp, topology)
|
||||
frames.append(packer.make_can_msg(camera_name, 2, {}))
|
||||
state = interface.update([(1_000_000_000, frames)])
|
||||
self.assertTrue(state.canValid)
|
||||
control = structs.CarControl()
|
||||
camera_frame = packer.make_can_msg(camera_name, 0, {})
|
||||
camera = self.packet(camera_frame)
|
||||
self.assertFalse(self.safety.safety_tx_hook(camera))
|
||||
for tick, (active, expected) in enumerate(((False, []), (True, [2]), (False, [1]), (False, []))):
|
||||
control.latActive = active
|
||||
_, sends = interface.apply(control.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
steering = [frame for frame in sends if frame[0] == address]
|
||||
self.assertEqual([(frame[1][9] >> 4) & 3 for frame in steering], expected)
|
||||
for frame in steering:
|
||||
self.assertTrue(self.safety.safety_tx_hook(self.packet(frame)))
|
||||
self.assertEqual(self.safety.safety_fwd_hook(2, address), -1 if active else 0)
|
||||
self.assertEqual(bool(self.safety.safety_tx_hook(camera)), active, (topology, tick))
|
||||
if active:
|
||||
bad_camera = self.packet(camera_frame)
|
||||
bad_camera[0].data[0] ^= 1
|
||||
self.assertFalse(self.safety.safety_tx_hook(bad_camera))
|
||||
|
||||
def test_non_angle_profile_rejects_cb_at_public_and_selected_hooks(self):
|
||||
self.safety.set_alternative_experience(0)
|
||||
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, 0), 0)
|
||||
|
||||
@@ -380,7 +380,9 @@ def test_recorded_pe_stock_wheel_cutoff_withdraws_native_output_without_new_butt
|
||||
assert case.safety.aol_get_permission_mask() == int(moving)
|
||||
assert bool(case.safety.safety_tx_hook(case.command(word, counter))) is moving
|
||||
if not moving:
|
||||
assert case.safety.safety_tx_hook(case.command(word, counter, active=False))
|
||||
inactive = case.command(word, counter, active=False)
|
||||
assert not case.safety.safety_tx_hook(inactive)
|
||||
assert case.safety.safety_fwd_hook(2, inactive[0].addr) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', ['HYUNDAI_IONIQ_5_PE', 'KIA_EV9'])
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.pandad import can_list_to_can_capnp
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from importlib import import_module
|
||||
from typing import cast
|
||||
|
||||
import openpilot.cereal.messaging as messaging
|
||||
@@ -16,15 +17,13 @@ from openpilot.common.realtime import config_realtime_process, Priority, Ratekee
|
||||
from openpilot.common.swaglog import cloudlog, ForwardingHandler
|
||||
|
||||
from opendbc.car import DT_CTRL, structs
|
||||
from opendbc.car.can_definitions import CanData, CanRecvCallable, CanSendCallable
|
||||
from opendbc.car.carlog import carlog
|
||||
from opendbc.car.fw_versions import ObdCallback
|
||||
from opendbc.car.car_helpers import get_car, interfaces
|
||||
from opendbc.car.gm.distance_button import GMDistanceButtons
|
||||
from opendbc.car.gm.interface import CarInterface as GMInterface
|
||||
from opendbc.car.gm.profiles import profiles_supported as gm_profiles_supported
|
||||
from opendbc.car.hyundai.ioniq6_handoff import (IONIQ6_LONG_PREARM_ENABLED, HandoffOutcome,
|
||||
TimestampedCanPacket, build_ioniq6_hda2_long_candidate,
|
||||
build_ioniq6_hda2_long_candidate,
|
||||
confirm_ioniq6_prepared_takeover, restore_ioniq6_adas,
|
||||
finalize_ioniq6_prepublication, Ioniq6StartupKeepalive,
|
||||
inspect_ioniq6_long_sources)
|
||||
@@ -33,6 +32,7 @@ from opendbc.car.hyundai.ioniq6_media import Ioniq6MediaButtons
|
||||
from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR
|
||||
from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase
|
||||
from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp
|
||||
from openpilot.selfdrive.car.can_callbacks import can_comm_callbacks, obd_callback
|
||||
from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelContext, VCruiseHelper, slc_target_kph
|
||||
from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card
|
||||
from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings
|
||||
@@ -95,35 +95,6 @@ DISTANCE_GESTURE_KEYS = {Press.SHORT: ('DistanceButtonControl', 0),
|
||||
carlog.addHandler(ForwardingHandler(cloudlog))
|
||||
|
||||
|
||||
def obd_callback(params: Params) -> ObdCallback:
|
||||
def set_obd_multiplexing(obd_multiplexing: bool):
|
||||
if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing:
|
||||
cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}")
|
||||
params.remove("ObdMultiplexingChanged")
|
||||
params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True)
|
||||
params.get_bool("ObdMultiplexingChanged", block=True)
|
||||
cloudlog.warning("OBD multiplexing set successfully")
|
||||
return set_obd_multiplexing
|
||||
|
||||
|
||||
def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket) -> tuple[CanRecvCallable, CanSendCallable]:
|
||||
def can_recv(wait_for_one: bool = False) -> list[list[CanData]]:
|
||||
"""
|
||||
wait_for_one: wait the normal logcan socket timeout for a CAN packet, may return empty list if nothing comes
|
||||
|
||||
Returns: CAN packets comprised of CanData objects for easy access
|
||||
"""
|
||||
ret = []
|
||||
for can in messaging.drain_sock(logcan, wait_for_one=wait_for_one):
|
||||
ret.append(TimestampedCanPacket([CanData(msg.address, msg.dat, msg.src) for msg in can.can], int(can.logMonoTime)))
|
||||
return ret
|
||||
|
||||
def can_send(msgs: list[CanData]) -> None:
|
||||
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
|
||||
|
||||
return can_recv, can_send
|
||||
|
||||
|
||||
curve_press_receipt = slc_physical.curve_press_receipt
|
||||
|
||||
|
||||
@@ -394,6 +365,11 @@ class Car:
|
||||
raise RuntimeError('AOL requires the exact vehicle safety configuration')
|
||||
config.safetyParam |= aol_policy.safety_param_addition
|
||||
self.CP.alternativeExperience |= aol_policy.alternative_experience_addition
|
||||
if self.CP.carFingerprint == HYUNDAI_CAR.HYUNDAI_KONA_2ND_GEN and config.safetyParam == 0x0C0C and not is_release:
|
||||
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff
|
||||
self.sm.update(0)
|
||||
if self.sm.valid['pandaStates'] and self.sm.alive['pandaStates']:
|
||||
configure_kona_factory_handoff(self.CP, self.sm['pandaStates'])
|
||||
self.vehicle_startup.finalize_aol_configuration(self.CI)
|
||||
from openpilot.starpilot.car.hyundai.redneck_cruise import configure
|
||||
self.redneck_cruise = configure(self, subscribed_services)
|
||||
@@ -401,12 +377,14 @@ class Car:
|
||||
self.learning_send_mono_ns = self.learning_send_committed_mono_ns = 0
|
||||
self.learning_car_state_source_ns = 0
|
||||
self.learning_applied_evidence = self.learning_previous_applied_evidence = None
|
||||
self.learning_feedback_factory = None
|
||||
try:
|
||||
from openpilot.starpilot.lateral.learning_preferences import read_preference
|
||||
preference = read_preference(self.params, self.CP)
|
||||
if preference.valid and preference.enabled:
|
||||
from opendbc.car.steering_projection import install_observer
|
||||
self.learning_stamp_observer = self.record_learning_send_stamp if install_observer(self.CI) else None
|
||||
self._prepare_feedback_capture()
|
||||
except Exception:
|
||||
pass # Optional learning setup cannot stop native startup.
|
||||
self.aol_transport_feedback = TransportPauseFeedback(self.CP) if self.aol_replay else None
|
||||
@@ -1162,10 +1140,9 @@ class Car:
|
||||
publication = getattr(self, 'learning_feedback_publication', None)
|
||||
if publication is not None:
|
||||
try:
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
feedback_companion = (companion.as_reader().as_builder() if companion is not None else
|
||||
messaging.new_message('starpilotCarState', valid=bool(cs_send.valid), logMonoTime=int(cs_send.logMonoTime)))
|
||||
write_publication(feedback_companion.starpilotCarState, publication)
|
||||
self.learning_feedback_writer(feedback_companion.starpilotCarState, publication)
|
||||
companion = feedback_companion
|
||||
except Exception:
|
||||
self.learning_feedback_publication = None
|
||||
@@ -1485,15 +1462,26 @@ class Car:
|
||||
(not ps.safetyRxChecksInvalid or inactive_keepalive and self.gm_startup_keepalive())
|
||||
for ps, cfg in zip(pandas, self.CP.safetyConfigs, strict=True)))
|
||||
|
||||
def _prepare_feedback_capture(self):
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
from openpilot.starpilot.flm.feedback_wire import write_publication
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import car_params_digest
|
||||
|
||||
# The first calibrated receipt can arrive after lateral is active.
|
||||
import_module('openpilot.starpilot.flm.learning_wire')
|
||||
import_module('openpilot.starpilot.flm.physical_input_observation')
|
||||
self._feedback_cp_sha256 = car_params_digest(self.CP)
|
||||
self.learning_feedback_writer = write_publication
|
||||
self.learning_feedback_factory = card_capture_for
|
||||
|
||||
def _feedback_capture(self, now_ns):
|
||||
# Default OFF performs no feedback-module import, digest or witness allocation.
|
||||
try:
|
||||
source = self.sm['autoSteeringLearning'].learning.sourceReceipt
|
||||
if not source.enabled or source.manual:
|
||||
factory = self.learning_feedback_factory
|
||||
if factory is None or not source.enabled or source.manual:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
from openpilot.starpilot.flm.feedback_observation import card_capture_for
|
||||
return card_capture_for(self, now_ns)
|
||||
return factory(self, now_ns)
|
||||
except Exception:
|
||||
self.learning_feedback_capture = None
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from opendbc.car import structs
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
from openpilot.starpilot.flm.learning_wire import write_source_receipt
|
||||
from openpilot.starpilot.flm.runtime_adapter_registry import SourceState
|
||||
|
||||
|
||||
def test_first_calibrated_feedback_uses_startup_preparation():
|
||||
card = Car.__new__(Car)
|
||||
card.CP = structs.CarParams.new_message(brand='gm', carFingerprint='CHEVROLET_BOLT_ACC_2022_2023')
|
||||
card.learning_feedback_factory = None
|
||||
card._prepare_feedback_capture()
|
||||
|
||||
stamp = 10_000_000_000
|
||||
service = 'autoSteeringLearning'
|
||||
packet = messaging.new_message(service, valid=True, logMonoTime=stamp)
|
||||
source = SourceState(True, False, 'boot', 'a' * 64, stamp, stamp + 500_000_000,
|
||||
card._feedback_cp_sha256, (0., 0., 0.))
|
||||
write_source_receipt(packet, source)
|
||||
sm = messaging.SubMaster([service])
|
||||
sm.update_msgs(stamp / 1e9, [packet.as_reader()])
|
||||
sm.alive[service] = sm.freq_ok[service] = True
|
||||
card.sm = sm
|
||||
|
||||
with patch('openpilot.starpilot.flm.runtime_adapter_registry.car_params_digest', side_effect=AssertionError):
|
||||
capture = card._feedback_capture(stamp)
|
||||
assert capture is not None
|
||||
output = messaging.new_message('carOutput', valid=True, logMonoTime=stamp)
|
||||
companion = messaging.new_message('starpilotCarState', valid=True, logMonoTime=stamp)
|
||||
card.learning_feedback_writer(companion.starpilotCarState, capture.publication(output))
|
||||
assert companion.starpilotCarState.feedbackPublication.version == 1
|
||||
assert not companion.starpilotCarState.feedbackPublication.outputKnown
|
||||
assert card._feedback_capture(stamp + 500_000_001) is None
|
||||
@@ -7,6 +7,8 @@ from openpilot.cereal import log
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction
|
||||
from opendbc.car.toyota import legacy_advert_filter
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA_CAR
|
||||
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY, CV
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
|
||||
@@ -52,6 +54,8 @@ class LatControlTorque(LatControl):
|
||||
and not (CP.notCar or CP.passive or CP.dashcamOnly)
|
||||
)
|
||||
self.controller_mode = default_selection(CP).mode if controller_mode is None else ControllerMode(controller_mode)
|
||||
self.sienna_center_friction = (self.controller_mode == ControllerMode.STANDARD and
|
||||
CP.carFingerprint == TOYOTA_CAR.TOYOTA_SIENNA and legacy_advert_filter.enabled(CP))
|
||||
self.controller_policy = policy_for(CP)
|
||||
if self.controller_mode == ControllerMode.STARPILOT and self.controller_policy is None:
|
||||
raise ValueError('No StarPilot torque policy for CarParams')
|
||||
@@ -98,7 +102,12 @@ class LatControlTorque(LatControl):
|
||||
weight *= np.interp(abs(setpoint), [0.25, 0.65], [1.0, 0.0])
|
||||
threshold += max(np.interp(CS.vEgo, [65 * CV.MPH_TO_MS, 75 * CV.MPH_TO_MS], [0.65, 0.78]) - threshold, 0.0) * weight
|
||||
error = math.copysign(max(abs(error) - 0.04 * weight, 0.0), error)
|
||||
return get_friction(error, deadzone, threshold, self.torque_params)
|
||||
friction = get_friction(error, deadzone, threshold, self.torque_params)
|
||||
if self.sienna_center_friction and not CS.steeringPressed:
|
||||
speed_weight = np.interp(CS.vEgo * CV.MS_TO_MPH, [34., 39., 50., 56.], [0., 1., 1., 0.])
|
||||
center_weight = np.interp(abs(setpoint), [0.22, 0.58], [1., 0.])
|
||||
friction *= 1.0 - 0.5 * speed_weight * center_weight
|
||||
return friction
|
||||
|
||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||
self.flm_surface = self.flm_source.sample(active=active, speed=CS.vEgo)
|
||||
|
||||
@@ -53,8 +53,10 @@ A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
|
||||
J_CRUISE_VALS = [1.6, 1.2, 0.8, 0.6]
|
||||
A_CRUISE_MIN = -0.5
|
||||
CRUISE_ACCEL_RESPONSE_TIME = 2.0
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.45
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 2_000_000_000
|
||||
MODEL_Y_HANDOFF_COAST_TOLERANCE = 0.2
|
||||
MODEL_Y_SPEED_STEP_JERK = 0.25
|
||||
MODEL_Y_SPEED_STEP_LIFT_ACCEL = 0.15
|
||||
MODEL_Y_SPEED_STEP_DURATION_NS = 4_000_000_000
|
||||
SLC_BRAKE_ONSET_JERK = 0.15 # m/s^3: how fast braking may build after an SLC overshoot
|
||||
SLC_BRAKE_ONSET_ACCEL = -0.3 # m/s^2: past this the brakes are engaged and normal jerk resumes
|
||||
CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N]
|
||||
@@ -112,7 +114,7 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
|
||||
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach
|
||||
target_accel = np.clip(speed_error, cruise_min, max_accel)
|
||||
j_cruise = np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS)
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= 0.0):
|
||||
if speed_step and (v_cruise > v_ego or a_cruise_prev <= MODEL_Y_SPEED_STEP_LIFT_ACCEL):
|
||||
j_cruise = min(j_cruise, MODEL_Y_SPEED_STEP_JERK)
|
||||
decel_start = a_cruise_prev if a_target_prev is None else min(a_cruise_prev, a_target_prev)
|
||||
lower = decel_start - j_cruise * dt
|
||||
@@ -152,6 +154,7 @@ class LongitudinalPlanner:
|
||||
|
||||
self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt)
|
||||
self.a_cruise = init_a
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
self.previous_manual_cruise_kph: float | None = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.output_a_target = init_a
|
||||
@@ -461,16 +464,38 @@ class LongitudinalPlanner:
|
||||
if downhill_error is not None and navigation_ceiling(
|
||||
sm, self.CP, sample_now_ns, limit + .25, slowdown_percent=self.navigation_slowdown_percent) is not None:
|
||||
downhill_error = None
|
||||
cruise_seed = self.a_cruise
|
||||
speed_step = False
|
||||
if self.CP.carFingerprint == 'TESLA_MODEL_Y':
|
||||
cs = sm['carState']
|
||||
leads = (sm['radarState'].leadOne, sm['radarState'].leadTwo)
|
||||
recent_pedal_preview = 0 < self.model_y_handoff_preview_until_ns and sample_now_ns < self.model_y_handoff_preview_until_ns
|
||||
self.model_y_handoff_preview_until_ns = 0
|
||||
if (reset_state and self.CP.openpilotLongitudinalControl and sm['selfdriveState'].enabled and
|
||||
not sm['carControl'].longActive and cs.cruiseState.enabled and (cs.gasPressed or recent_pedal_preview) and not cs.brakePressed and
|
||||
cs.canValid and not cs.canTimeout and not cs.standstill and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
-MODEL_Y_HANDOFF_COAST_TOLERANCE < cruise_seed <= 0.5 and v_cruise_initialized and v_cruise - v_ego > 1.0 and
|
||||
output_a_target_mpc > cruise_seed and self.mpc.solution_status == 0 and
|
||||
self.allow_throttle and not self.fcw and not sm['controlsState'].forceDecel and
|
||||
not self.force_stop_plan.should_stop and not self.force_stop_plan.forcing and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and downhill_error is None and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
not (coast_plan is not None and (coast_plan.force_decel or coast_plan.pulse_coasting or coast_plan.brake_floor is not None)) and
|
||||
all(not lead.present or (lead.vLead > v_ego and lead.dRel > max(15., 2. * v_ego)) for lead in leads)):
|
||||
# Preview one actuator delay while the pedal still owns acceleration. Lead and stop arbitration follow below.
|
||||
preview = min(0.25, action_t * np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS))
|
||||
# Taper through coast-down so a near-zero reading does not drop the entire preview.
|
||||
cruise_seed += preview * min(1.0, 1.0 + cruise_seed / MODEL_Y_HANDOFF_COAST_TOLERANCE)
|
||||
if cs.gasPressed:
|
||||
# The pedal state can clear a planner frame before longitudinal control resumes.
|
||||
self.model_y_handoff_preview_until_ns = sample_now_ns + 100_000_000
|
||||
manual_cruise = (
|
||||
profile_eligible and not reset_state and v_ego > MIN_ALLOW_THROTTLE_SPEED and
|
||||
cs.canValid and not cs.canTimeout and not cs.gasPressed and not cs.brakePressed and not cs.standstill and
|
||||
not sm['controlsState'].forceDecel and self.allow_throttle and not self.fcw and
|
||||
not self.force_stop_plan.forcing and not self.force_stop_plan.should_stop and
|
||||
not output_should_stop_mpc and not sm['modelV2'].action.shouldStop and
|
||||
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
|
||||
not any(lead.present for lead in leads) and
|
||||
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and
|
||||
(coast_plan is None or not (coast_plan.force_decel or coast_plan.pulse_coasting or
|
||||
coast_plan.brake_floor is not None)) and self.mpc.solution_status == 0 and
|
||||
@@ -487,7 +512,7 @@ class LongitudinalPlanner:
|
||||
self.previous_manual_cruise_kph = None
|
||||
self.manual_cruise_step_until_ns = 0
|
||||
self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego,
|
||||
self.a_cruise, steer_angle_without_offset, self.CP, self.dt,
|
||||
cruise_seed, steer_angle_without_offset, self.CP, self.dt,
|
||||
accel_coast, self.allow_throttle, cruise_profile,
|
||||
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
|
||||
a_target_prev=self.output_a_target,
|
||||
|
||||
Binary file not shown.
@@ -7,7 +7,7 @@ from types import SimpleNamespace
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.ui.appearance_preferences import format_lead_info
|
||||
from openpilot.starpilot.ui.rainbow_path import RainbowPath
|
||||
from openpilot.starpilot.ui.road_colors import lane_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.road_colors import lane_color, lead_marker_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.onroad_customization import ROAD_COLORS
|
||||
from openpilot.starpilot.lateral.lane_feedback import BLUE, direction as lane_centering_direction
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
@@ -216,7 +216,8 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
@staticmethod
|
||||
def _valid_lead_numbers(lead) -> bool:
|
||||
try:
|
||||
distance, lateral, relative_speed = float(lead.dRel), float(lead.yRel), float(lead.vRel)
|
||||
distance, lateral = float(lead.dRel), float(lead.yRel)
|
||||
relative_speed = float(lead.vRel) if lead.vRel is not None else 0.0
|
||||
return distance > 0 and all(math.isfinite(value) for value in (distance, lateral, relative_speed))
|
||||
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
@@ -227,6 +228,9 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
model = sm['modelV2']
|
||||
e2e = (sm.valid['longitudinalPlan'] and sm.valid['modelV2'] and
|
||||
plan.longitudinalPlanSource == log.LongitudinalPlan.LongitudinalPlanSource.e2e and len(model.leadsV3) > 1)
|
||||
ego_speed = sm['carState'].vEgo if e2e and sm.all_checks(['carState']) else None
|
||||
if ego_speed is not None and not math.isfinite(ego_speed):
|
||||
ego_speed = None
|
||||
leads = []
|
||||
for index in range(2):
|
||||
info = None
|
||||
@@ -234,7 +238,8 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
candidate = model.leadsV3[index]
|
||||
if candidate.x and candidate.y and candidate.v:
|
||||
info = SimpleNamespace(present=candidate.prob > 0.5, dRel=candidate.x[0] - RADAR_TO_CAMERA,
|
||||
yRel=-candidate.y[0], vRel=0.0, vLead=candidate.v[0])
|
||||
yRel=-candidate.y[0], vRel=candidate.v[0] - ego_speed if ego_speed is not None else None,
|
||||
vLead=candidate.v[0])
|
||||
elif sm.valid['radarState']:
|
||||
info = (sm['radarState'].leadOne, sm['radarState'].leadTwo)[index]
|
||||
valid = info is not None and info.present and self._valid_lead_numbers(info)
|
||||
@@ -488,7 +493,8 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
for lead in self._lead_vehicles:
|
||||
if not lead.bar.size or lead.fade_filter.x <= 0:
|
||||
continue
|
||||
draw_polygon(self._rect, lead.bar + offset, rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
|
||||
color = lead_marker_color(self.road_style, lead.fade_filter.x)
|
||||
draw_polygon(self._rect, lead.bar + offset, color if color is not None else rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.ui.appearance_preferences import format_lead_info
|
||||
from openpilot.starpilot.ui.rainbow_path import RainbowPath
|
||||
from openpilot.starpilot.ui.road_colors import edge_gradient, lane_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.road_colors import edge_gradient, lane_color, lead_marker_color, path_mode, solid_gradient
|
||||
from openpilot.starpilot.ui.onroad_customization import ROAD_COLORS
|
||||
from openpilot.starpilot.lateral.lane_feedback import BLUE, direction as lane_centering_direction
|
||||
from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT
|
||||
@@ -413,8 +413,11 @@ class ModelRenderer(ModelGeometry, Widget):
|
||||
if not lead.glow or not lead.chevron:
|
||||
continue
|
||||
|
||||
rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255))
|
||||
rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha))
|
||||
style = self.road_style
|
||||
glow = lead_marker_color(style, 1.0)
|
||||
fill = lead_marker_color(style, lead.fill_alpha / 255)
|
||||
rl.draw_triangle_fan(lead.glow, len(lead.glow), glow if glow is not None else rl.Color(218, 202, 37, 255))
|
||||
rl.draw_triangle_fan(lead.chevron, len(lead.chevron), fill if fill is not None else rl.Color(201, 34, 49, lead.fill_alpha))
|
||||
|
||||
def _draw_lead_info(self, lead: LeadVehicle, text: str) -> None:
|
||||
# Centered just above the chevron's glow, kept on screen.
|
||||
|
||||
@@ -186,3 +186,71 @@ def test_main_on_during_permanent_fault_does_not_queue_automatic_rearm(alpha):
|
||||
cs.steerFaultPermanent = False
|
||||
owner.update(cs, now_ns=1_020_000_000, fault_active=False)
|
||||
assert not owner.allowed_latch
|
||||
|
||||
|
||||
def test_stock_mqb_main_rearm_waits_only_for_the_current_native_receipt():
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.starpilot.aol.tests.test_gm_held_native import Peers
|
||||
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback
|
||||
from openpilot.starpilot.aol.wire import PandaSlot, SafetyState, encode_safety
|
||||
from openpilot.starpilot.car.volkswagen.aol import awaiting_initial_request, policy_for
|
||||
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[0][0xAD] = 8
|
||||
cp = CarInterface.get_params(CAR.VOLKSWAGEN_ATLAS_MK1, fp, [], False, False, False)
|
||||
policy = policy_for(cp)
|
||||
cp.safetyConfigs[-1].safetyParam |= policy.safety_param_addition
|
||||
cp.alternativeExperience |= policy.alternative_experience_addition
|
||||
owner = VolkswagenStockCardIntent(cp, AolSettings(True, 5., 0, 0, (0, 0, 0), (0, 0, 0)))
|
||||
cs = structs.CarState(canValid=True, vEgo=8., vEgoRaw=8., gearShifter=structs.CarState.GearShifter.drive)
|
||||
cs.cruiseState.available = True
|
||||
arm = 2_000_000_000
|
||||
owner.update(cs, now_ns=arm - 300_000_000)
|
||||
cs.cruiseState.available = False
|
||||
owner.update(cs, now_ns=arm - 100_000_000)
|
||||
assert not owner.allowed_latch
|
||||
cs.cruiseState.available = True
|
||||
owner.update(cs, now_ns=arm)
|
||||
assert owner.allowed_latch
|
||||
|
||||
now = arm + 110_000_000
|
||||
stamp = now - 2_000_000
|
||||
event = messaging.new_message('onroadEvents', 1, valid=True, logMonoTime=stamp)
|
||||
event.onroadEvents[0].name = 'pcmDisable'
|
||||
event.onroadEvents[0].userDisable = True
|
||||
axis = messaging.new_message('aolAxisState', valid=True, logMonoTime=stamp)
|
||||
axis.aolAxisState.sessionId = axis.aolAxisState.faultSessionId = 'drive'
|
||||
axis.aolAxisState.intentProducerSessionId = 'card'
|
||||
axis.aolAxisState.sequence = 2
|
||||
axis.aolAxisState.faultReason = 'none'
|
||||
|
||||
axis.aolAxisState.qualified = True
|
||||
axis.aolAxisState.desiredLateral = True
|
||||
axis.aolAxisState.observedMonoTime = axis.aolAxisState.faultEventMonoTime = stamp
|
||||
axis.aolAxisState.sourceCarStateMonoTime = stamp - 3_000_000
|
||||
axis.aolAxisState.validUntilMonoTime = stamp + 30_000_000
|
||||
health = messaging.new_message('pandaStates', 1, valid=True, logMonoTime=stamp)
|
||||
health.pandaStates[0].safetyModel = 'volkswagen'
|
||||
health.pandaStates[0].safetyParam = 8
|
||||
health.pandaStates[0].alternativeExperience = 32
|
||||
native = SafetyState(1, True, stamp, stamp + 200_000_000, 15, 8, False, False, True, False, 'board', 'drive',
|
||||
stamp, (PandaSlot(0, 'board', 15, 8, 32),))
|
||||
wire = messaging.new_message('aolSafetyWire', 0, valid=True, logMonoTime=stamp)
|
||||
wire.aolSafetyWire = encode_safety(native)
|
||||
feedback = TransportPauseFeedback(cp)
|
||||
feedback.session, feedback.sequence, feedback.ever_lateral_active = 'drive', 1, True
|
||||
feedback.signature = (None,) * 14 + ('card', 0)
|
||||
def waiting():
|
||||
return awaiting_initial_request(cp, cs, Peers([axis, event, health, wire]), native, feedback,
|
||||
owner, now_ns=now, producer='card')
|
||||
assert waiting()
|
||||
assert owner.intent_publication(cs, now)[-1] == arm + 200_000_000
|
||||
event.onroadEvents[0].name = 'buttonCancel'
|
||||
assert not waiting()
|
||||
event.onroadEvents[0].name = 'pcmDisable'
|
||||
cs.cruiseState.enabled = True
|
||||
owner.update(cs, now_ns=now)
|
||||
cs.cruiseState.enabled = False
|
||||
assert not waiting()
|
||||
owner.update(cs, now_ns=arm + 200_000_001)
|
||||
assert not owner.allowed_latch
|
||||
|
||||
@@ -26,6 +26,7 @@ from opendbc.car.hyundai.canfd_owner import config_index
|
||||
from opendbc.car.hyundai.canfd_stock_aol import (
|
||||
qualified as qualified_canfd_stock, qualified_long as qualified_canfd_long,
|
||||
LONG_AOL_WORDS as CANFD_LONG_AOL_WORDS, STOCK_AOL_MARKER, STOCK_AOL_WORDS,
|
||||
KONA_IDLE_AOL_WORD, kona_idle_handoff_profile,
|
||||
)
|
||||
from opendbc.car.hyundai.non_scc_aol import qualified as qualified_non_scc, aol_word, AOL_MARKER, AOL_EXPERIENCE, AOL_WORDS, SOFTWARE_CRUISE
|
||||
from opendbc.car.hyundai.kona_aol import allow_lateral_onset as kona_lateral_onset
|
||||
@@ -202,6 +203,16 @@ def aol_safety_config(CP):
|
||||
return CP.safetyConfigs[owner] if owner is not None else None
|
||||
|
||||
|
||||
|
||||
def configure_kona_factory_handoff(cp, pandas):
|
||||
if (not kona_idle_handoff_profile(cp) or cp.alternativeExperience != 32 or
|
||||
cp.safetyConfigs[0].safetyParam != 0x0C0C or len(pandas) != 1):
|
||||
return
|
||||
panda = pandas[0]
|
||||
if (str(panda.pandaType) == 'cuatro' and not panda.faults and
|
||||
(panda.ignitionCan or panda.ignitionLine) and not panda.controlsAllowed):
|
||||
cp.safetyConfigs[0].safetyParam = KONA_IDLE_AOL_WORD
|
||||
|
||||
def policy_for(CP) -> AolVehiclePolicy:
|
||||
policy = _policy_for(CP)
|
||||
if (CP.carFingerprint in IONIQ_5_CARS and has_left_paddle(CP) and
|
||||
|
||||
@@ -87,6 +87,8 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
self.main_available = False
|
||||
self.main_neutral = False
|
||||
self.main_pulse = False
|
||||
self.stock_main_rearm_ns = 0
|
||||
self.stock_main_rearm_cruise_seen = False
|
||||
self.startup_arm_ns = 0
|
||||
self.startup_deferred = False
|
||||
self.startup_release_ns = 0
|
||||
@@ -131,6 +133,15 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
else:
|
||||
events.append(structs.CarState.ButtonEvent(**event.to_dict()))
|
||||
available = bool(state.cruiseState.available)
|
||||
if (not self.allowed_latch or not available or
|
||||
any(event.type == ButtonType.cancel and event.pressed for event in state.buttonEvents)):
|
||||
self.stock_main_rearm_ns = 0
|
||||
if self.stock_main_rearm_ns and now_ns > self.stock_main_rearm_ns + SAFETY_MAX_AGE_NS:
|
||||
self.allowed_latch = False
|
||||
self.stock_main_rearm_ns = 0
|
||||
if self.stock_main_rearm_ns and state.cruiseState.enabled:
|
||||
self.stock_main_rearm_cruise_seen = True
|
||||
stock_main_rearm = self.main_neutral and not self.main_available and stock_qualified(self.cp, marked_only=True)
|
||||
if (not self.settings.enabled or self.settings.main_action == AOL_TOGGLE or self.settings.lkas_action == AOL_TOGGLE or
|
||||
(state.canValid and not state.canTimeout and (state.steerFaultPermanent or state.accFaulted)) or
|
||||
any(event.type == ButtonType.cancel and event.pressed for event in CS.buttonEvents) and
|
||||
@@ -194,6 +205,9 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
if not self.startup_release_ns:
|
||||
self.startup_release_ns = now_ns
|
||||
self.allowed_latch = True
|
||||
if stock_main_rearm:
|
||||
self.stock_main_rearm_ns = self._last_latch_edge_ns = now_ns
|
||||
self.stock_main_rearm_cruise_seen = bool(state.cruiseState.enabled)
|
||||
if self.main_startup_pending and not self.startup_arm_ns:
|
||||
self.startup_arm_ns = now_ns
|
||||
self.main_startup_pending = False
|
||||
@@ -207,6 +221,9 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
def observe_startup_readiness(self, sm, cs, *, native, panda_ready, now_ns, producer):
|
||||
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, current_axis
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native, cp_identity
|
||||
if (self.stock_main_rearm_ns and panda_ready and native is not None and native.requestedLateral and native.lateralAllowed and
|
||||
self.stock_main_rearm_ns <= native.observedMonoTime <= self.stock_main_rearm_ns + SAFETY_MAX_AGE_NS):
|
||||
self.stock_main_rearm_ns = 0
|
||||
self.startup_ready = False
|
||||
floor_pending = self.startup_floor_pending
|
||||
self.startup_floor_pending = False
|
||||
@@ -311,8 +328,11 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
def intent_publication(self, cs, source_ns):
|
||||
allowed, lateral, longitudinal = self.output(cs)
|
||||
armed, deadline = self.allowed_latch, source_ns + 200_000_000
|
||||
pending_arm_ns = self.stock_main_rearm_ns
|
||||
if self.startup_deferred and not self.startup_granted and not self.startup_aborted:
|
||||
deadline = min(deadline, self.startup_arm_ns + 200_000_000)
|
||||
pending_arm_ns = self.startup_arm_ns
|
||||
if pending_arm_ns:
|
||||
deadline = min(deadline, pending_arm_ns + 200_000_000)
|
||||
if source_ns > deadline:
|
||||
allowed = armed = False
|
||||
deadline = source_ns + 200_000_000 # Fresh withdrawal, never a renewed arm.
|
||||
@@ -442,7 +462,7 @@ def intent_disarming_fault(cp, events, state, **context):
|
||||
|
||||
|
||||
def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, producer):
|
||||
"""A cold MAIN request may await its first native response, never output."""
|
||||
"""A fresh MAIN arm may await native steering permission without output."""
|
||||
from openpilot.starpilot.aol.runtime import SAFETY_MAX_AGE_NS, AXIS_MAX_AGE_NS, current_axis
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native, cp_identity
|
||||
from openpilot.cereal import log
|
||||
@@ -450,14 +470,17 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
if not (stock_qualified(cp, marked_only=True) or long_qualified(cp, marked_only=True)):
|
||||
return False
|
||||
axis = current_axis(sm, now_ns=now_ns)
|
||||
arm = intent.startup_arm_ns
|
||||
stock_rearm = bool(intent.stock_main_rearm_ns and stock_qualified(cp, marked_only=True))
|
||||
arm = intent.stock_main_rearm_ns if stock_rearm else intent.startup_arm_ns
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
reverse_event_pending = bool(axis is not None and 0 < event_ns < arm <= axis.sourceCarStateMonoTime and
|
||||
event_ns < axis.faultEventMonoTime <= axis.observedMonoTime and
|
||||
any(event.name == log.OnroadEvent.EventName.reverseGear and event.userDisable for event in sm['onroadEvents']))
|
||||
# Stock cruise may already be off when independent MAIN startup arms.
|
||||
stock_cruise_already_off = bool(stock_qualified(cp, marked_only=True) and not cs.cruiseState.enabled and
|
||||
axis is not None and 0 < event_ns < arm and axis.faultEventMonoTime == event_ns)
|
||||
joined_event = axis is not None and 0 < event_ns == axis.faultEventMonoTime
|
||||
# MAIN can republish the factory cruise-off event before this re-arm gets a native grant.
|
||||
stock_cruise_already_off = bool(stock_qualified(cp, marked_only=True) and not cs.cruiseState.enabled and joined_event and
|
||||
(not intent.stock_main_rearm_cruise_seen if stock_rearm else event_ns < arm))
|
||||
main_off_event_pending = stock_rearm and joined_event and event_ns < arm
|
||||
drive_identity = getattr(intent, 'startup_drive_identity', None)
|
||||
identity = None if drive_identity is None or axis is None or native is None else (
|
||||
cp_identity(cp), str(axis.sessionId), producer, int(axis.intentIntegrityEpoch), native.pandaSerial,
|
||||
@@ -469,7 +492,7 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
0 < arm <= native.observedMonoTime <= arm + SAFETY_MAX_AGE_NS and
|
||||
0 <= now_ns - native.observedMonoTime <= AXIS_MAX_AGE_NS)
|
||||
return bool(intent.settings.enabled and intent.settings.main_action != AOL_TOGGLE and intent.settings.lkas_action != AOL_TOGGLE and
|
||||
intent.allowed_latch and not intent.pause_lateral and not feedback.ever_lateral_active and
|
||||
intent.allowed_latch and not intent.pause_lateral and (stock_rearm or not feedback.ever_lateral_active) and
|
||||
not feedback.failed and not feedback.paused and not feedback.pending_event and not feedback.retention_started_ns and
|
||||
feedback.cp == cp_identity(cp) and
|
||||
0 < arm <= now_ns and (now_ns <= arm + SAFETY_MAX_AGE_NS or granted_in_window) and
|
||||
@@ -498,7 +521,8 @@ def awaiting_initial_request(cp, cs, sm, native, feedback, intent, *, now_ns, pr
|
||||
not any(event.immediateDisable or
|
||||
event.softDisable and not (reverse_event_pending and event.name == log.OnroadEvent.EventName.wrongGear) or
|
||||
event.userDisable and not (reverse_event_pending and event.name == log.OnroadEvent.EventName.reverseGear or
|
||||
stock_cruise_already_off and event.name == log.OnroadEvent.EventName.pcmDisable)
|
||||
stock_cruise_already_off and event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||
main_off_event_pending and event.name == log.OnroadEvent.EventName.wrongCarMode)
|
||||
for event in sm['onroadEvents']))
|
||||
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
|
||||
@@ -65,8 +65,12 @@ class StatusReport:
|
||||
'verifying_recorded_drive': 'verifying'}.get(value['reason'], 'checking')
|
||||
progress = value.get('analysis_progress', {'phase': phase,
|
||||
'completed': counts.get('original_segments_reviewed'), 'total': counts.get('original_segments_available')})
|
||||
# Later checking callbacks may omit progress, but belong to the same active recording.
|
||||
if phase == 'checking' and 'analysis_progress' not in value:
|
||||
prior_progress = self.current.get('analysis_progress', {})
|
||||
progress.update({key: prior_progress[key] for key in ('recording_position', 'recording_total') if key in prior_progress})
|
||||
self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous),
|
||||
'analysis_progress': progress}, diagnostic_value=value)
|
||||
'analysis_progress': progress}, diagnostic_value={**value, 'status': 'fitting'})
|
||||
|
||||
def restore(self, cache):
|
||||
"""Recover historical display data, never a current tune or permission."""
|
||||
@@ -134,6 +138,9 @@ class StatusReport:
|
||||
if not (type(completed) is int and type(total) is int and 0 <= completed <= total <= 180 and total > 0):
|
||||
completed = total = None
|
||||
details['Parked analysis progress'] = [progress['phase'], completed, total]
|
||||
position, recordings = progress.get('recording_position'), progress.get('recording_total')
|
||||
if type(position) is int and type(recordings) is int and 0 <= position <= recordings <= 8 and recordings > 0:
|
||||
details['Parked recording queue'] = [position, recordings]
|
||||
if value.get('vehicle_identity') == 'unavailable':
|
||||
details['Recorded vehicle identity'] = 'unavailable'
|
||||
if self.diagnostics is not None and self.diagnostics.error:
|
||||
|
||||
@@ -891,18 +891,26 @@ class OffroadWorker:
|
||||
raise ValueError('Logger identity changed during route selection')
|
||||
self.pending_latest = latest
|
||||
checkpoints = {row['input_fingerprint']: row['result'] for row in self.cache.checkpoints()}
|
||||
queue = pending_routes(self.root, latest, on_skip=self._skip_route)
|
||||
fingerprints = []
|
||||
for route in pending_routes(self.root, latest, on_skip=self._skip_route):
|
||||
for route in queue:
|
||||
fingerprint = self._snapshot(route)
|
||||
fingerprints.append(fingerprint)
|
||||
if (fingerprint not in checkpoints or self.evidence_bank is not None and route == latest
|
||||
and not checkpoints[fingerprint].get('route_skipped') and not checkpoints[fingerprint].get('partial_drive')
|
||||
and checkpoints[fingerprint].get('evidence_revision') != self.evidence_bank.revision()):
|
||||
if fingerprint not in checkpoints:
|
||||
position = len(fingerprints)
|
||||
break
|
||||
else:
|
||||
result = reported_checkpoint(self.cache, [checkpoints[key] for key in fingerprints])
|
||||
source_is_latest = result['completed_route'] == latest['routeId'] if 'completed_route' in result else result.get('source_is_latest', True)
|
||||
return dict(result, source_is_latest=source_is_latest, skipped_routes=[*result.get('skipped_routes', ()), *self.skipped_routes][:16])
|
||||
# Finish discovering the backlog before refreshing the newest review with the pooled evidence.
|
||||
fingerprint = fingerprints[0]
|
||||
completed = checkpoints[fingerprint]
|
||||
if (self.evidence_bank is not None and not completed.get('route_skipped') and not completed.get('partial_drive')
|
||||
and completed.get('analysis_counts', {}).get('active_lateral_request_rows') != 0
|
||||
and completed.get('evidence_revision') != self.evidence_bank.revision()):
|
||||
route, position = latest, 0
|
||||
else:
|
||||
result = reported_checkpoint(self.cache, [checkpoints[key] for key in fingerprints])
|
||||
source_is_latest = result['completed_route'] == latest['routeId'] if 'completed_route' in result else result.get('source_is_latest', True)
|
||||
return dict(result, source_is_latest=source_is_latest, skipped_routes=[*result.get('skipped_routes', ()), *self.skipped_routes][:16])
|
||||
self.pending_input = (route, fingerprint)
|
||||
revisions = source_revisions(self.root, route)
|
||||
state = {}
|
||||
@@ -931,9 +939,16 @@ class OffroadWorker:
|
||||
if self.on_analysis is not None:
|
||||
self.on_analysis()
|
||||
options: dict[str, Any] = {} if self.evidence_bank is None else {'evidence_bank': self.evidence_bank, 'history_identity': self._history_identity}
|
||||
if self.on_progress is not None and self.assessor is RECORDED_ASSESSOR:
|
||||
options['on_progress'] = self.on_progress
|
||||
if route != latest:
|
||||
def progress(value):
|
||||
if self.on_progress is not None:
|
||||
self.on_progress({**value, 'recording_position': position, 'recording_total': len(queue)})
|
||||
|
||||
if self.assessor is RECORDED_ASSESSOR:
|
||||
# The scheduler owns the backlog. The reader must not substitute an older route inside this attempt.
|
||||
options['selected_route'] = route
|
||||
if self.on_progress is not None:
|
||||
options['on_progress'] = progress
|
||||
elif route != latest:
|
||||
options['selected_route'] = route
|
||||
try:
|
||||
assessment = self.assessor(self.params, self.root, prior, permitted=self.permitted, **options)
|
||||
@@ -943,7 +958,7 @@ class OffroadWorker:
|
||||
from openpilot.starpilot.flm.offroad_partial import analyze_partial
|
||||
|
||||
try:
|
||||
assessment = analyze_partial(self.root, route['routeId'], prior, permitted=self.permitted, on_progress=self.on_progress)
|
||||
assessment = analyze_partial(self.root, route['routeId'], prior, permitted=self.permitted, on_progress=options.get('on_progress'))
|
||||
except RouteInputError:
|
||||
raise error from None
|
||||
self._skip_route(route['routeId'], error)
|
||||
@@ -1525,6 +1540,8 @@ class OffroadWorker:
|
||||
result['configuration_state'] = configured['state']
|
||||
result['recommendations'] = [r for r in result['recommendations'] if r['target'] is None or r['target'] != configured['values'][r['parameter']]]
|
||||
result['recommendation_count'] = len(result['recommendations'])
|
||||
if not result['recommendation_count'] and result['reason'] == 'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application':
|
||||
result['reason'] = 'no_consistent_adjustment_in_completed_drive'
|
||||
# A new started/changed source cannot be marked processed under its new ID.
|
||||
if not authorized():
|
||||
raise ValueError('Offroad source changed before checkpoint')
|
||||
|
||||
@@ -3,6 +3,7 @@ import bz2
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
import unittest
|
||||
|
||||
from openpilot.cereal import log
|
||||
@@ -102,6 +103,83 @@ class TestAnalysisProgress(unittest.TestCase):
|
||||
report.publish()
|
||||
self.assertNotIn('Parked analysis progress', json.loads(report.path.read_text())['current']['details'])
|
||||
|
||||
def test_real_backlog_reads_each_inactive_recording_once(self):
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.flm import offroad_processor as processor
|
||||
from openpilot.starpilot.flm.offroad_worker import OffroadWorker
|
||||
from openpilot.starpilot.flm.tests.test_offroad_backend import scope
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
routes = [recording(root / 'logs', counter)[0] for counter in (18, 17, 16)]
|
||||
params = Params(str(root / 'params'))
|
||||
params.put('CurrentRoute', routes[0], block=True)
|
||||
params.put('RouteCount', 19, block=True)
|
||||
progress = []
|
||||
worker = OffroadWorker(params, root / 'logs', root / 'cache', permitted=lambda: True,
|
||||
scope_for=lambda *_: scope(), on_progress=progress.append)
|
||||
with patch.object(processor, 'collect_route_inputs', wraps=processor.collect_route_inputs) as read:
|
||||
for name in routes:
|
||||
self.assertEqual(worker.run_once()['completed_route'], name)
|
||||
finished = worker.run_once()
|
||||
self.assertEqual(finished['completed_route'], routes[0])
|
||||
self.assertEqual([call.args[1]['routeId'] for call in read.call_args_list], routes)
|
||||
starts = [row for row in progress if row['phase'] == 'reading' and row['completed'] == 0]
|
||||
self.assertEqual([(row['recording_position'], row['recording_total']) for row in starts], [(1, 3), (2, 3), (3, 3)])
|
||||
self.assertEqual(finished['recommendations'], [])
|
||||
self.assertFalse(finished['configuration_changed'])
|
||||
|
||||
def test_pending_recordings_finish_before_one_cross_drive_refresh(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.flm import offroad_worker as module
|
||||
from openpilot.starpilot.flm.offroad_history import EvidenceBank
|
||||
from openpilot.starpilot.flm.offroad_route import RouteReceipt
|
||||
from openpilot.starpilot.flm.tests.test_offroad_backend import scope
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
routes = [{'routeId': f'{counter:08x}--aaaaaaaaaa'} for counter in (18, 17, 16)]
|
||||
reads = []
|
||||
revision = [0]
|
||||
|
||||
def assess(_, __, previous, *, permitted, selected_route=None, **kwargs):
|
||||
route = routes[0] if selected_route is None else selected_route
|
||||
reads.append(route)
|
||||
if route != routes[0]:
|
||||
revision[0] += 1
|
||||
cp = SimpleNamespace(carFingerprint='declared-queue-car')
|
||||
previous(cp)
|
||||
receipt = RouteReceipt(route['routeId'], 'd' * 64, (), 'a' * 64, 1, 2, 3, ())
|
||||
return module.CompletedAssessment(receipt, (), {'active_lateral_request_rows': 500}, cp, (), route)
|
||||
|
||||
with patch.object(module, 'latest_route', return_value=routes[0]), patch.object(module, 'pending_routes', return_value=routes), \
|
||||
patch.object(module, 'route_inventory', return_value={'scanIncomplete': False, 'routes': routes}):
|
||||
worker = module.OffroadWorker(Params(str(root / 'params')), root / 'logs', root / 'cache', permitted=lambda: True,
|
||||
assessor=assess, scope_for=lambda *_: scope())
|
||||
worker.evidence_bank = EvidenceBank(worker.cache.directory)
|
||||
with patch.object(worker.evidence_bank, 'revision', side_effect=lambda: f'{revision[0]:064x}'):
|
||||
for name in [*routes, routes[0], routes[0]]:
|
||||
self.assertEqual(worker.run_once()['completed_route'], name['routeId'])
|
||||
self.assertEqual(reads, [*routes, routes[0]])
|
||||
|
||||
def test_checking_callback_stays_active_and_retains_recording_queue(self):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.starpilot.flm.diagnostic_state import _stage
|
||||
|
||||
report = StatusReport(clock_ns=lambda: 10_000_000_000)
|
||||
observed = []
|
||||
report.diagnostics = SimpleNamespace(observe=observed.append)
|
||||
report.analyzing({'reason': 'analyzing_last_completed_drive', 'analysis_progress': {
|
||||
'phase': 'reading', 'completed': 6, 'total': 43, 'recording_position': 2, 'recording_total': 4}})
|
||||
report.analyzing({'reason': 'checking_recorded_steering_recommendations', 'completed_route': 'declared'})
|
||||
self.assertEqual(_stage(observed[-1]), 'checking_recommendations')
|
||||
self.assertEqual(report.current['analysis_progress']['recording_position'], 2)
|
||||
self.assertEqual(report.current['analysis_progress']['recording_total'], 4)
|
||||
report.set({'status': 'collecting', 'reason': 'no_consistent_adjustment_in_completed_drive', 'completed_route': 'declared'})
|
||||
self.assertEqual(_stage(observed[-1]), 'analysis_result')
|
||||
self.assertNotIn('analysis_progress', report.current)
|
||||
|
||||
def test_running_read_waits_for_fresh_device_state_but_never_through_an_onroad_transition(self):
|
||||
from types import SimpleNamespace as NS
|
||||
from openpilot.starpilot.flm.offroad_daemon import wait_for_parked
|
||||
|
||||
@@ -63,7 +63,7 @@ No docs build, sync, or network lookup is required; update this file when a wiki
|
||||
| Maps | Local map status and a parked catalog-region download, progress, or cancellation. A completed selection takes effect at the next map service start. |
|
||||
| Cameras and Sentry | Saved PiP and V-ASM settings and bounded Sentry event metadata. The crop editor uses a browser-local still image; it does not upload that image. |
|
||||
| Sound packs | Catalog status, verified download and cancellation through the local sound owner. |
|
||||
| Galaxy Access & Install | Remote link pairing, Galaxy installation, and an opt-in Wi-Fi hotspot. Local addresses are on Home. |
|
||||
| Galaxy Access & Connections | Remote link pairing, Galaxy installation, Networks, Bluetooth, and support. Local addresses are on Home. |
|
||||
|
||||
`Refresh` and branch changes request filtered
|
||||
history metadata in a separate Git cache and worker. They remain available during
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Capture the USB and Bluetooth input inventory without opening any event device."""
|
||||
|
||||
from base64 import b64encode
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
import secrets
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from openpilot.starpilot.controllers import input as controller_input
|
||||
|
||||
|
||||
def controller_input_report():
|
||||
"""Include interfaces filtered out of Attached Controllers and mask device names per report."""
|
||||
devices = []
|
||||
groups = {}
|
||||
salt = secrets.token_bytes(8)
|
||||
truncated = False
|
||||
for entry in sorted(controller_input.SYS_ROOT.iterdir()):
|
||||
if not controller_input.EVENT_NAME.fullmatch(entry.name):
|
||||
continue
|
||||
device = entry / 'device'
|
||||
match = controller_input.MODALIAS.match(controller_input._text(device / 'modalias'))
|
||||
if match is None or int(match[1], 16) not in controller_input.EXTERNAL_BUSES:
|
||||
continue
|
||||
if len(devices) == controller_input.MAX_CANDIDATES:
|
||||
truncated = True
|
||||
break
|
||||
node = controller_input.DEV_ROOT / entry.name
|
||||
identity = controller_input._inspect(node)
|
||||
if identity is not None:
|
||||
groups.setdefault(identity.device_id, []).append(entry.name)
|
||||
name = controller_input._text(device / 'name')
|
||||
devices.append({
|
||||
'event': entry.name,
|
||||
'name': f'masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}' if name else '',
|
||||
'inputId': match[0],
|
||||
'properties': controller_input._text(device / 'properties'),
|
||||
'capabilities': {key: controller_input._text(device / 'capabilities' / key) for key in ('ev', 'key', 'rel', 'abs')},
|
||||
'discovery': 'eligible' if identity else 'filtered',
|
||||
'eventNodePresent': node.exists(),
|
||||
})
|
||||
duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events}
|
||||
for row in devices:
|
||||
if row['event'] in duplicates:
|
||||
row.update(discovery='duplicate identity', matchingEvents=duplicates[row['event']])
|
||||
return {'externalInputInterfaces': devices, 'truncated': truncated}
|
||||
|
||||
|
||||
def controller_capture():
|
||||
report = {'schemaVersion': 1, 'capturedAt': datetime.now(UTC).isoformat(timespec='seconds'), **controller_input_report()}
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('bluetooth-log.json', json.dumps(report, indent=2) + '\n')
|
||||
return {'schemaVersion': 1, 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
@@ -246,7 +246,7 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
|
||||
if cookie is not None:
|
||||
self.send_header('Set-Cookie', cookie)
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
||||
"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)
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
"""Actual LAN addresses for direct Galaxy access, independent of the tunnel."""
|
||||
|
||||
from base64 import b64encode
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from io import BytesIO
|
||||
from datetime import UTC, datetime
|
||||
from ipaddress import IPv4Address, ip_network
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
|
||||
LAN = tuple(ip_network(value) for value in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16'))
|
||||
@@ -73,3 +79,158 @@ class LocalAccess:
|
||||
'reason': '' if addresses else reason}
|
||||
self.expiry = self.clock() + 5.0
|
||||
return self.cached
|
||||
|
||||
|
||||
DISCOVERY_UNIT = 'galaxy-lan-discovery.service'
|
||||
DISCOVERY_MESSAGE = re.compile(''.join((
|
||||
r'(Galaxy Wi-Fi discovery available on [0-9]{1,3} local interface\(s\)|',
|
||||
r'Wi-Fi discovery unavailable: [A-Za-z][A-Za-z0-9_]{0,63}|LAN publisher cleanup failed)\Z',
|
||||
)))
|
||||
|
||||
|
||||
BLE_UNIT = 'galaxy-ble-fork.service'
|
||||
BLE_MESSAGE = re.compile(''.join((
|
||||
r'(Pairing credentials changed; [0-9]{1,4} phone\(s\) paired|Phone claimed pairing window|',
|
||||
r'Galaxy BLE handshake challenge requested; active sessions=[0-9]{1,4}|',
|
||||
r'Rejected invalid or unauthenticated BLE message|Notification transfer interrupted \([A-Za-z0-9_]{1,64}\); reconnect to check request outcome|',
|
||||
r'BLE advertisement released by BlueZ; bridge will re-register after restart|Registering Galaxy BLE advertisement|',
|
||||
r'Starting Galaxy bridge pid=[0-9]{1,10} source=[0-9a-f]{12}|',
|
||||
r'Galaxy BLE bridge ready on /org/bluez/hci[0-9]{1,3}; forwarding to localhost:[0-9]{1,5}|',
|
||||
r'Stopping Galaxy bridge; clearing ready status and Bluetooth sessions)\Z',
|
||||
)))
|
||||
INTERFACE_NAME = re.compile(r'[A-Za-z0-9_.:-]{1,32}\Z')
|
||||
|
||||
|
||||
def _network_inventory(run):
|
||||
lines = []
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'address', 'show'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid network inventory')
|
||||
for row in rows[:64]:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = row.get('ifname')
|
||||
if not isinstance(name, str) or not INTERFACE_NAME.fullmatch(name):
|
||||
continue
|
||||
state = row.get('operstate')
|
||||
if state not in ('UNKNOWN', 'NOTPRESENT', 'DOWN', 'LOWERLAYERDOWN', 'TESTING', 'DORMANT', 'UP'):
|
||||
state = 'unknown'
|
||||
flags = row.get('flags', [])
|
||||
if not isinstance(flags, list):
|
||||
flags = []
|
||||
flags = ','.join(flag for flag in ('UP', 'LOWER_UP', 'RUNNING', 'MULTICAST', 'LOOPBACK') if flag in flags)
|
||||
addresses = []
|
||||
info_rows = row.get('addr_info', [])
|
||||
for info in info_rows[:16] if isinstance(info_rows, list) else []:
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
try:
|
||||
address, prefix = IPv4Address(info.get('local')), info.get('prefixlen')
|
||||
except ValueError:
|
||||
continue
|
||||
if any(address in network for network in LAN) and type(prefix) is int and 0 <= prefix <= 32:
|
||||
addresses.append(f'{address}/{prefix}')
|
||||
lines.append(f'{name}: state={state}; flags={flags or "none"}; private IPv4={", ".join(addresses) or "none"}')
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('Network interface inventory unavailable')
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'route', 'show', 'default'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid route inventory')
|
||||
interfaces = [row['dev'] for row in rows[:16] if isinstance(row, dict)
|
||||
and isinstance(row.get('dev'), str) and INTERFACE_NAME.fullmatch(row['dev'])]
|
||||
lines.append('IPv4 default route interfaces: ' + (', '.join(interfaces) or 'none'))
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('IPv4 default route inventory unavailable')
|
||||
try:
|
||||
result = run(['ss', '-H', '-lnt', 'sport = :8082'], capture_output=True, timeout=1, check=True)
|
||||
bindings = set()
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:32]:
|
||||
fields = line.split()
|
||||
if len(fields) < 5 or fields[0] != 'LISTEN' or not fields[3].endswith(':8082'):
|
||||
continue
|
||||
host = fields[3][:-5]
|
||||
if host in ('*', '0.0.0.0', '[::]'):
|
||||
bindings.add('all interfaces')
|
||||
elif host.startswith('127.') or host == '[::1]':
|
||||
bindings.add('loopback')
|
||||
else:
|
||||
bindings.add('specific interface')
|
||||
lines.append('TCP port 8082 listening: ' + (', '.join(sorted(bindings)) or 'no'))
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('TCP port 8082 listener state unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def _service_capture(run, unit, pattern, label):
|
||||
state = 'unavailable'
|
||||
details = []
|
||||
try:
|
||||
result = run(['systemctl', 'show', unit, '--property=ActiveState,SubState,Result,NRestarts,ExecMainStatus'],
|
||||
capture_output=True, timeout=1, check=True)
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:12]:
|
||||
if re.fullmatch(r'(?:ActiveState|SubState|Result)=[a-z][a-z0-9-]{0,39}|(?:NRestarts|ExecMainStatus)=[0-9]{1,10}', line):
|
||||
if line.startswith('ActiveState='):
|
||||
state = line.split('=', 1)[1]
|
||||
else:
|
||||
details.append(line)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
lines = [f'{label}: {state}', *details, 'Recent service events (last 2 hours, up to 120 journal records read)']
|
||||
try:
|
||||
result = run(['journalctl', '--no-pager', '--quiet', '-u', unit, '--since', '-2h',
|
||||
'-n', '120', '-o', 'json', '--output-fields=MESSAGE'],
|
||||
capture_output=True, timeout=2, check=True)
|
||||
events = []
|
||||
for raw in result.stdout.splitlines()[-120:]:
|
||||
if len(raw) > 8192:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
message = entry.get('MESSAGE') if isinstance(entry, dict) else None
|
||||
if isinstance(message, str) and pattern.fullmatch(message):
|
||||
stamp = entry.get('__REALTIME_TIMESTAMP', '')
|
||||
if isinstance(stamp, str) and re.fullmatch(r'[0-9]{1,16}', stamp):
|
||||
timestamp = datetime.fromtimestamp(int(stamp) / 1e6, UTC).isoformat(timespec='seconds')
|
||||
message = f'{timestamp} {message}'
|
||||
events.append(message)
|
||||
except (ValueError, OSError, OverflowError):
|
||||
continue
|
||||
lines.extend(events or ['No matching events'])
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('Advertiser journal unavailable' if unit == DISCOVERY_UNIT else 'BLE journal unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def connection_capture(addresses, *, configuration_allowed=None, run=subprocess.run):
|
||||
lines = ['StarPilot connection capture', 'Capture schema: 2',
|
||||
f'Captured at (UTC): {datetime.now(UTC).isoformat(timespec="seconds")}',
|
||||
'Galaxy endpoint: HTTP port 8082', 'Bonjour service: _sp-galaxy._tcp.local.']
|
||||
try:
|
||||
with open('/proc/uptime') as stream:
|
||||
lines.append(f'Comma uptime: {float(stream.read(128).split()[0]):.0f} seconds')
|
||||
except (OSError, ValueError, IndexError):
|
||||
lines.append('Comma uptime: unavailable')
|
||||
if configuration_allowed is not None:
|
||||
try:
|
||||
lines.append(f'Parked configuration allowed: {bool(configuration_allowed())}')
|
||||
except Exception:
|
||||
lines.append('Parked configuration allowed: unavailable')
|
||||
lines.extend(['', 'Advertisable local addresses'])
|
||||
lines.extend(f'{row["interface"]}: {row["url"]}' for row in addresses['addresses'])
|
||||
if not addresses['available']:
|
||||
lines.append(addresses['reason'] or 'No eligible local address')
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
network = pool.submit(_network_inventory, run)
|
||||
discovery = pool.submit(_service_capture, run, DISCOVERY_UNIT, DISCOVERY_MESSAGE, 'Bonjour advertiser')
|
||||
bluetooth = pool.submit(_service_capture, run, BLE_UNIT, BLE_MESSAGE, 'Bluetooth bridge')
|
||||
lines.extend(['', 'Network interfaces', *network.result(), '', *discovery.result(), '', *bluetooth.result()])
|
||||
report = '\n'.join(lines) + '\n'
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('connection-logs.txt', report)
|
||||
# Keep the original text field for browsers still running the previous page.
|
||||
return {'schemaVersion': 1, 'text': report[:16384], 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""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 = 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:
|
||||
return self._stage_url() if callable(self._stage_url) else self._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.")
|
||||
@@ -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
|
||||
@@ -51,7 +52,7 @@ from openpilot.starpilot.ui.layout_preview_transport import (request_profile)
|
||||
from openpilot.starpilot.favorites.owner import FavoritesChanged
|
||||
from openpilot.starpilot.galaxy.favorites import FavoritesGateway
|
||||
from openpilot.starpilot.galaxy.system_monitor import SystemMonitor
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive
|
||||
from openpilot.starpilot.galaxy.vehicle_selection import VehicleSelectionChanged, VehicleSelectionGateway, VehicleSelectionUnverified
|
||||
from openpilot.starpilot.bluetooth.owner import BluetoothOwner, BluetoothRejected, BluetoothUnavailable, normalized_address
|
||||
@@ -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()
|
||||
@@ -186,6 +204,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
summary_lock = threading.Lock()
|
||||
motion_events = sentry_events if sentry_events is not None else SentryEvents()
|
||||
sentry_events_lock = threading.Lock()
|
||||
simulation_busy = threading.Event()
|
||||
last_simulation = [float("-inf")]
|
||||
notification_owner = notifications
|
||||
snapshots = camera_snapshot if camera_snapshot is not None else CameraSnapshot()
|
||||
@@ -693,9 +712,11 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return False
|
||||
|
||||
def settings_session(self):
|
||||
token = self.session_token()
|
||||
return self.current_settings_session(self.session_token(), self.direct_local())
|
||||
|
||||
def current_settings_session(self, token, direct_local):
|
||||
with session_lock:
|
||||
if self.direct_local() and sessions.valid(token, local_generation):
|
||||
if direct_local and sessions.valid(token, local_generation):
|
||||
return token, local_generation
|
||||
generation = access.current_generation()
|
||||
if getattr(self.server, 'remote_transport', False):
|
||||
@@ -954,7 +975,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return
|
||||
from openpilot.starpilot.galaxy.pairing_ready import bridge_state, pairing_readiness
|
||||
self.json(200, pairing_readiness(parked=configuration_allowed, snapshot=lambda: bluetooth_owner().snapshot(), bridge=bridge_state))
|
||||
elif path in ('/api/local-access', '/api/tmux/live', '/api/troubleshoot'):
|
||||
elif path in ('/api/local-access', '/api/local-access/capture', '/api/controllers/log/capture', '/api/tmux/live', '/api/troubleshoot'):
|
||||
if not self.require_session():
|
||||
return
|
||||
identity = self.settings_session()
|
||||
@@ -964,6 +985,11 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
try:
|
||||
if path == '/api/local-access':
|
||||
result = address_source.snapshot()
|
||||
elif path == '/api/local-access/capture':
|
||||
result = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
|
||||
elif path == '/api/controllers/log/capture':
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
result = controller_capture()
|
||||
elif path == '/api/tmux/live':
|
||||
result = console_source.snapshot()
|
||||
else:
|
||||
@@ -1010,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())
|
||||
@@ -1457,7 +1490,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(400, {'error': 'Choose an event image'})
|
||||
return
|
||||
try:
|
||||
body = motion_events.image(parts[0], parts[1])
|
||||
body = notification_owner.test_image(parts[0]) if parts[1] == 'test' else motion_events.image(parts[0], parts[1])
|
||||
if body is None:
|
||||
raise SentryEventsUnavailable
|
||||
except SentryEventsUnavailable:
|
||||
self.json(404, {'error': 'Event image unavailable'})
|
||||
else:
|
||||
@@ -1743,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/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',
|
||||
@@ -1753,13 +1788,14 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
||||
'/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/events/delete', '/api/crash-reports/delete',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete',
|
||||
'/api/crash-reports/delete',
|
||||
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
|
||||
'/api/toyota-tools/action', '/api/vehicle-selection/preview', '/api/vehicle-selection/confirm'):
|
||||
self.json(405, {'error': 'Method unavailable'})
|
||||
return
|
||||
if (path.startswith(('/api/companion/', '/api/replay/', '/api/recordings/', '/api/connect/', '/api/cameras/', '/api/settings/', '/api/maps/',
|
||||
'/api/bluetooth/',
|
||||
'/api/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
|
||||
@@ -1817,6 +1853,24 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
else:
|
||||
self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/logs/stage':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import StageBusy, StageRejected
|
||||
try:
|
||||
result = log_stager().start(payload, identity)
|
||||
except StageRejected as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except StageBusy as error:
|
||||
self.json(409, {'error': str(error)})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(202, result)
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/settings/flm-finding/accept':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -1929,6 +1983,43 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
return
|
||||
if path == '/api/sentry/notifications/photo-test':
|
||||
if (type(payload) is not dict or set(payload) != {'camera', 'id'} or payload['camera'] not in ('wide', 'cabin') or
|
||||
not isinstance(payload['id'], str) or not re.fullmatch(r'[0-9a-f]{12}', payload['id'])):
|
||||
self.json(400, {'error': 'Choose a phone and camera'})
|
||||
return
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
|
||||
def permitted():
|
||||
readable, _, _ = select.select([self.connection], [], [], 0)
|
||||
if readable and not self.connection.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT):
|
||||
return False
|
||||
return self.settings_session() == identity and parked()
|
||||
|
||||
try:
|
||||
photo = snapshots.capture(payload['camera'], permitted=permitted, parked=True)
|
||||
notification_owner.photo_test(payload['id'], payload['camera'], photo, permitted=permitted)
|
||||
except (SnapshotDenied, PermissionError):
|
||||
if self.require_session():
|
||||
self.json(409, {'error': 'Park the car before sending a photo test'})
|
||||
except SnapshotUnavailable:
|
||||
if self.require_session():
|
||||
self.json(503, {'error': 'No fresh camera frame. Try again shortly.'})
|
||||
except LookupError:
|
||||
self.json(404, {'error': 'Phone subscription not found'})
|
||||
except ValueError as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except (NotificationUnavailable, OSError):
|
||||
self.json(503, {'error': 'Sentry phone push is unavailable. Check Galaxy Sentry settings.'})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(200, {'queued': True})
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/sentry/notifications':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -1942,11 +2033,32 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if not parked():
|
||||
self.json(403, {'error': 'Park the car before simulating an event'})
|
||||
return
|
||||
if clock() - last_simulation[0] < 10:
|
||||
if simulation_busy.is_set() or clock() - last_simulation[0] < 10:
|
||||
self.json(429, {'error': 'Wait ten seconds before simulating another event'})
|
||||
return
|
||||
notification_owner.store.record('warning', time.monotonic_ns(), simulated=True,
|
||||
permitted=lambda: self.settings_session() == identity and parked())
|
||||
from openpilot.starpilot.sentry_mode.capture import record_motion_event
|
||||
direct_local = self.direct_local()
|
||||
|
||||
def permitted():
|
||||
return self.current_settings_session(identity[0], direct_local) == identity and parked()
|
||||
|
||||
def capture_simulation():
|
||||
try:
|
||||
record_motion_event(notification_owner.store, snapshots, 'warning', time.monotonic_ns(),
|
||||
permitted, simulated=True)
|
||||
except SnapshotDenied:
|
||||
pass
|
||||
except Exception:
|
||||
cloudlog.exception("Sentry simulation could not record the event")
|
||||
finally:
|
||||
simulation_busy.clear()
|
||||
|
||||
simulation_busy.set()
|
||||
try:
|
||||
threading.Thread(target=capture_simulation, name='sentry-simulation', daemon=True).start()
|
||||
except RuntimeError as error:
|
||||
simulation_busy.clear()
|
||||
raise NotificationUnavailable("Could not start Sentry simulation") from error
|
||||
last_simulation[0] = clock()
|
||||
result = notification_owner.snapshot()
|
||||
else:
|
||||
|
||||
@@ -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) })
|
||||
@@ -137,7 +137,7 @@ const layout = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c',
|
||||
await page.evaluate(()=>location.hash='/tools')
|
||||
await page.getByRole('heading',{name:'Tools',exact:true}).waitFor()
|
||||
const sidebar=page.locator('.gx-nav-section').filter({has:page.locator('.gx-nav-section__title',{hasText:/^Tools$/})})
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Install'))
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Connections'))
|
||||
assert.deepEqual(errors,[])
|
||||
console.log('Browser checks passed: VASM frame/default/reactive updates, PiP crop frame, widget registry, recordings and phone layout. Captures:',draws)
|
||||
await browser.close()
|
||||
|
||||
@@ -24,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()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from "node:assert/strict"
|
||||
import { BluetoothFeed, BluetoothPage, validBluetoothStatus, validPairInput } from "../web/js/bluetooth.js"
|
||||
|
||||
@@ -111,3 +112,6 @@ assert.equal(validBluetoothStatus({ ...status, pairing: { address: "not-an-addre
|
||||
assert.equal(validBluetoothStatus({ ...status, adapterName: 5 }), false)
|
||||
assert.match(BluetoothPage.template, /Pair phone/)
|
||||
assert.match(BluetoothPage.template, /action\('accept_pair'\)/)
|
||||
|
||||
assert.equal(BluetoothPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(BluetoothPage.template.includes("<ConnectionLogs v-if=\"mode === 'local' && !unidenSettings\" panel"))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createRenderer, nextTick } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { BluetoothNotice, bluetoothConnection } from '../web/js/bluetooth-notice.js'
|
||||
import { BluetoothPage } from '../web/js/bluetooth.js'
|
||||
import { LocalHistoryFeed, LocalRecordingsPage } from '../web/js/record-history.js'
|
||||
import { CamerasPage, CameraSnapshotFeed, LiveCameraPreview } from '../web/js/cameras.js'
|
||||
import { PipPage } from '../web/js/pip.js'
|
||||
@@ -108,11 +109,19 @@ assert.equal(requests, 0)
|
||||
|
||||
window.StarPilotApp.bluetooth = () => false
|
||||
assert.equal(bluetoothConnection(), false)
|
||||
{
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const lines = readFileSync(new URL('../web/js/bluetooth.js', import.meta.url), 'utf8').split('\n')
|
||||
const chained = lines.findIndex((line) => line.trim() === '<template v-else-if="status">')
|
||||
assert.ok(chained > 0)
|
||||
assert.doesNotMatch(lines[chained - 1], /v-if="status"/, 'a notice before the device cards would swallow their v-else-if')
|
||||
const detector = { address: 'AA:BB:CC:DD:EE:FF', name: 'Uniden R8', paired: true, connected: true, trusted: true }
|
||||
for (const [mode, unidenSettings] of [['local', false], ['local', true], ['preview', false], ['preview', true]]) {
|
||||
const view = mount(BluetoothPage, { mode, unidenSettings }, {
|
||||
...presentation,
|
||||
data: () => ({ ...BluetoothPage.data(), status: { powered: true, available: true, parked: true, devices: [detector] } }),
|
||||
components: { ...BluetoothPage.components, UnidenPanel: { props: ['devices'], template: '<p>Detector controls for {{ devices[0].name }}</p>' } },
|
||||
})
|
||||
try {
|
||||
const rendered = text(view.host)
|
||||
assert.equal(rendered.includes('Saved devices'), mode === 'local' && !unidenSettings)
|
||||
assert.equal(rendered.includes('Detector controls for Uniden R8'), mode === 'local' && unidenSettings)
|
||||
assert.equal(rendered.includes('No radio was checked in preview.'), mode !== 'local')
|
||||
} finally { view.unmount() }
|
||||
}
|
||||
assert.equal(requests, 0)
|
||||
console.log('Bluetooth limits: blue notices, connection action, no blocked requests, supported settings and real errors verified')
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from unittest.mock import Mock
|
||||
"""Authenticated diagnostics over the same local and remote HTTP handler."""
|
||||
|
||||
import http.client
|
||||
@@ -6,10 +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 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,12 +72,15 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
connection.close()
|
||||
|
||||
def test_real_http_routes_authentication_and_no_mutations(self):
|
||||
for path in ('/api/local-access', '/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')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(self.request('/api/local-access')[1]['addresses'][0]['url'], 'http://192.168.4.2:8082/')
|
||||
status, capture, _ = self.request('/api/local-access/capture')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn('http://192.168.4.2:8082/', capture['text'])
|
||||
self.assertEqual(self.request('/api/tmux/live')[1]['text'], 'actual console')
|
||||
self.assertEqual(self.request('/api/troubleshoot')[1]['sections'], [])
|
||||
before = len(self.calls)
|
||||
@@ -70,6 +88,36 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.assertNotEqual(self.request('/api/tmux/live', method='POST', payload={})[0], 200)
|
||||
self.assertEqual(len(self.calls), before)
|
||||
|
||||
def test_log_stage_routes_require_session_and_stage_bundle(self):
|
||||
self.assertEqual(self.request('/api/logs/stage', method='POST', payload={'kind': 'starport', 'note': 'Blank'}, remote=True)[0], 401)
|
||||
_, _, self.cookie = self.request('/api/auth/session')
|
||||
claim_url = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/' + ('a' * 64)
|
||||
self.stage_response = Mock(status_code=200)
|
||||
self.stage_response.json.return_value = {'claimUrl': claim_url}
|
||||
status, idle, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(idle['state'], 'idle')
|
||||
self.assertTrue(idle['available'])
|
||||
|
||||
status, accepted, _ = self.request('/api/logs/stage', method='POST',
|
||||
payload={'kind': 'connection', 'phone': 'ios', 'note': 'Lost network'})
|
||||
self.assertEqual(status, 202)
|
||||
self.assertEqual(accepted['kind'], 'connection')
|
||||
|
||||
deadline = time.monotonic() + 2
|
||||
state = accepted
|
||||
while state['state'] == 'staging' and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
_, state, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(state['state'], 'ready')
|
||||
self.assertEqual(state['claimUrl'], claim_url)
|
||||
self.assertEqual(len(self.stage_posts), 1)
|
||||
_, kwargs = self.stage_posts[0]
|
||||
self.assertFalse(kwargs['allow_redirects'])
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Kind'], 'connection')
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Platform'], 'ios')
|
||||
self.assertIn('Lost%20network', kwargs['headers']['X-Galaxy-Note'])
|
||||
|
||||
def test_authenticated_forwarded_transport_uses_same_tools(self):
|
||||
status, _, self.cookie = self.request('/api/auth/login', method='POST', payload={'password': 'test-password-123'}, remote=True)
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
@@ -53,5 +53,5 @@ scrolls.length = 0
|
||||
delayedAlign()
|
||||
assert.deepEqual(scrolls, [], "a delayed alignment leaves the Widgets scroll position alone")
|
||||
|
||||
assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="openEditPanel\(\)"><span>Edit/)
|
||||
assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="state\.inspectorPanel === 'lead' \? revealEditPanel\(\) : openEditPanel\(\)"><span>Edit/)
|
||||
globalThis.setTimeout = realTimeout
|
||||
|
||||
@@ -275,7 +275,7 @@ assert(measuredText.includes('Recorded baseline') && measuredText.includes(measu
|
||||
assert.match(measuredText, /0\s+saved/)
|
||||
assert(measuredText.includes('No pending trial reported'))
|
||||
assert(!measuredText.includes('Awaiting next-drive measurement'), 'Recorded analysis without a saved trial must not invent a pending trial')
|
||||
assert(measuredText.includes('No interpolation or delay alignment'))
|
||||
assert(measuredText.includes('without interpolation or delay alignment'))
|
||||
assert(measuredText.includes('22 / 24 original controller and encoder windows passed'))
|
||||
assert(measuredText.includes('candidate triggered an encoder limiter'))
|
||||
ctx.report.current.details['Controller and encoder check windows']=[35,35]
|
||||
|
||||
@@ -251,6 +251,15 @@ for (const [phase, percent, detail] of [
|
||||
assert.equal(parkedAnalysisProgress(scan).percent, percent)
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, detail)
|
||||
}
|
||||
scan.current.details['Parked analysis progress'] = ['reading', 6, 43]
|
||||
scan.current.details['Parked recording queue'] = [2, 4]
|
||||
assert(validTrainingResults(scan))
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, 'Recording 2 of 4. 6 of 43 sections read in this recording')
|
||||
scan.current.details['Parked recording queue'] = [0, 4]
|
||||
assert.match(parkedAnalysisProgress(scan).detail, /^Rechecking with evidence from other drives/)
|
||||
scan.current.details['Parked recording queue'] = [8, 4]
|
||||
assert.equal(parkedAnalysisProgress(scan).detail, '6 of 43 sections read in this recording')
|
||||
delete scan.current.details['Parked recording queue']
|
||||
scan.current.details['Parked analysis progress'] = ['reading', 3, 3]
|
||||
assert.equal(parkedAnalysisProgress(scan).percent, null)
|
||||
scan.current.reason = 'verifying_recorded_drive'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRenderer, nextTick } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { GalaxyPage } from '../web/js/galaxy.js'
|
||||
import { RemoteAccess } from '../web/js/remote-access.js'
|
||||
@@ -36,10 +37,12 @@ const all = item => [item, ...item.children.flatMap(all)]
|
||||
const text = item => [item.text, ...item.children.map(text)].join(' ')
|
||||
const flush = async () => { await new Promise(resolve => setImmediate(resolve)); await nextTick() }
|
||||
const host = node('host')
|
||||
const { tools } = JSON.parse(readFileSync(new URL('../web/data/catalog.json', import.meta.url)))
|
||||
const galaxy = tools.find(tool => tool.path === '/galaxy')
|
||||
const visits = []
|
||||
const app = renderer.createApp({ ...GalaxyPage, components: { ...GalaxyPage.components,
|
||||
GalaxyHotspot: { template: '<div>Hotspot settings</div>' },
|
||||
InstallApp: { props: ['url'], template: '<div class="web-link">{{ url }}</div>' },
|
||||
} }, { mode: 'local', unauthorized() { unauthorized++ } })
|
||||
} }, { mode: 'local', tools: galaxy.children, go: path => visits.push(path), unauthorized() { unauthorized++ } })
|
||||
app.config.compilerOptions.decodeEntities = value => value.replaceAll('&', '&')
|
||||
const vm = app.mount(host)
|
||||
await flush()
|
||||
@@ -53,9 +56,16 @@ try {
|
||||
const stepList = nodes.find(item => item.type === 'ol' && item.props.class === 'gx-steps')
|
||||
assert.equal(stepList.children.filter(item => item.type === 'li' && item.props.class?.includes('gx-step')).length, 2)
|
||||
assert.equal(nodes.filter(item => item.props.class === 'gx-step__head').length, 2)
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|Connections|offline app version/)
|
||||
assert.equal(requests.length, 1, 'A browser reads remote pairing status without polling Android internet-sharing status')
|
||||
assert.equal(requests[0][0], './api/galaxy/status')
|
||||
assert.match(text(host), /Galaxy Access & Connections/)
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|offline app version/)
|
||||
assert.ok(tools.some(tool => tool.path === '/starport'), 'StarPort remains a standalone tool')
|
||||
const tiles = nodes.filter(item => item.props.class === 'gx-menu-tile')
|
||||
assert.deepEqual(tiles.map(item => item.children.find(child => child.type === 'span').text), ['Networks', 'Bluetooth'])
|
||||
for (const tile of tiles) tile.props.onClick()
|
||||
nodes.find(item => item.type === 'button' && item.text === 'Get help').props.onClick()
|
||||
assert.deepEqual(visits, ['/networks', '/bluetooth', '/logs/help'])
|
||||
assert.deepEqual(requests.map(([path]) => path).sort(), ['./api/galaxy/qr.svg', './api/galaxy/status'],
|
||||
'A browser reads the pairing status and QR code without polling Android internet-sharing status')
|
||||
assert.equal(vm.url, link, 'Remote link reaches the web installer')
|
||||
const steps = vm.$.subTree.children.find(child => child.props?.class === 'gx-steps')
|
||||
const remote = steps.children.find(child => child.type === RemoteAccess).component.proxy
|
||||
|
||||
@@ -10,7 +10,7 @@ assert.ok(ids.every(id => recordArt(id).every(path => typeof path === "string" &
|
||||
assert.ok(recordArt("futureRecord").length)
|
||||
assert.ok(Home.template.includes('recordArt(record.id)'))
|
||||
assert.ok(Home.template.includes('aria-hidden="true"><svg'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Install</h2>'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Connections</h2>'))
|
||||
assert.ok(!GalaxyPage.template.includes('Galaxy & App Install'))
|
||||
assert.ok(!GalaxyPage.template.includes('Android users:'))
|
||||
assert.ok(!GalaxyPage.template.includes('Phone companion · Connections'))
|
||||
@@ -18,8 +18,8 @@ assert.ok(GalaxyPage.template.indexOf('<RemoteAccess') < GalaxyPage.template.ind
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
assert.ok(GalaxyPage.template.includes('<h3>Get the app</h3>'))
|
||||
assert.ok(GalaxyPage.template.includes('<InstallApp :url="url" />'))
|
||||
assert.ok(GalaxyPage.template.includes('href="#/networks"'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<InstallApp') < GalaxyPage.template.indexOf('#/networks'))
|
||||
assert.ok(GalaxyPage.template.includes('Get help'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<MenuTile') < GalaxyPage.template.indexOf('<InstallApp'))
|
||||
assert.ok(!GalaxyPage.template.includes('PWA'))
|
||||
assert.ok(DriveStatePanel.template.includes('gx-card gx-force-drive'))
|
||||
const css = readFileSync(new URL('../web/css/galaxy.css', import.meta.url), 'utf8')
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
import { LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { ConnectionLogs, LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { Home } from "../web/js/home.js"
|
||||
import { RemoteQR } from "../web/js/remote-access.js"
|
||||
import { GalaxyPage } from "../web/js/galaxy.js"
|
||||
const snapshot = { available: true, addresses: [{ interface: 'wlan0', label: 'Wi-Fi', url: 'http://192.168.20.5:8082/' }], reason: '' }
|
||||
assert.equal(validLocalAccess(snapshot), true)
|
||||
@@ -67,3 +68,62 @@ assert.equal(GalaxyPage.components.LocalAccess, undefined)
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
compile(GalaxyPage.template, { decodeEntities: value => value.replaceAll('&', '&') })
|
||||
console.log('Galaxy local access remains independent of app installation')
|
||||
|
||||
const capture = { panel: false, controller: false, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalDocument = globalThis.document
|
||||
const downloads = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, 'a')
|
||||
return { href: '', download: '', click() { downloads.push({ href: this.href, download: this.download }) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/local-access/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await capture.downloadConnectionLogs()
|
||||
assert.equal(capture.captureBusy, false)
|
||||
assert.equal(capture.captureError, '')
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-connection-logs.zip')
|
||||
|
||||
const controllerCapture = { panel: true, controller: true, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/controllers/log/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await controllerCapture.downloadConnectionLogs()
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-controller-logs.zip')
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
assert.equal(LocalAccess.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(LocalAccess.template.includes("mode === 'local'"))
|
||||
compile(ConnectionLogs.template, { decodeEntities: value => value })
|
||||
assert.ok(ConnectionLogs.template.includes('Send logs'))
|
||||
assert.ok(ConnectionLogs.template.includes('Download connection ZIP'))
|
||||
assert.equal(ConnectionLogs.components.ReportingGuide, undefined)
|
||||
for (const endpoint of ['./api/galaxy/qr.svg', './api/galaxy/session/qr.svg']) {
|
||||
const qr = {endpoint, ...RemoteQR.data(), ...RemoteQR.methods}
|
||||
try {
|
||||
globalThis.fetch = async (path, options) => {
|
||||
assert.equal(path, endpoint)
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return new Response('<svg xmlns="http://www.w3.org/2000/svg"/>',{headers:{'Content-Type':'image/svg+xml'}})
|
||||
}
|
||||
await qr.load()
|
||||
assert.match(qr.image, /^blob:/)
|
||||
assert.equal(qr.failed, false)
|
||||
assert.equal((await originalFetch(qr.image)).headers.get('content-type'), 'image/svg+xml')
|
||||
RemoteQR.beforeUnmount.call(qr)
|
||||
await assert.rejects(originalFetch(qr.image))
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
}
|
||||
|
||||
@@ -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("&", "&") })
|
||||
compile(Logs.template, { decodeEntities: v => v.replaceAll("&", "&") })
|
||||
assert.ok(LogHelp.template.includes("https://firestar.link/discord"))
|
||||
assert.ok(LogHelp.template.includes("Individual session files"))
|
||||
assert.ok(!LogHelp.template.includes("Connecting via"))
|
||||
assert.ok(!LogHelp.template.includes("Driving behavior report"))
|
||||
|
||||
// 2. Logs route resolution for /logs/help, /logs/help/*, and /logs/starport
|
||||
for (const [path, expectedRoute, expectedTopic] of [
|
||||
["/logs", false, "starport"],
|
||||
["/logs/help", true, "starport"],
|
||||
["/logs/starport", true, "starport"],
|
||||
["/logs/help/connection", true, "connection"],
|
||||
["/logs/help/controller", true, "controller"],
|
||||
]) {
|
||||
assert.equal(Logs.computed.helpRoute.call({ path }), expectedRoute, `${path} helpRoute`)
|
||||
assert.equal(Logs.computed.helpTopic.call({ path }), expectedTopic, `${path} helpTopic`)
|
||||
}
|
||||
|
||||
// 3. LogStageClient lifecycle, validation, polling, ready callback, reset, and 401
|
||||
const CLAIM = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/" + "f".repeat(64)
|
||||
const state = { state: "idle", message: "", claimUrl: "", kind: "", error: "" }
|
||||
const readyUrls = []
|
||||
const scheduled = []
|
||||
const requests = []
|
||||
let unauthorizedCount = 0
|
||||
|
||||
let pollStep = 0
|
||||
const client = new LogStageClient({
|
||||
publish: update => Object.assign(state, update),
|
||||
unauthorized: () => { unauthorizedCount++ },
|
||||
schedule: (fn, ms) => { scheduled.push({ fn, ms }); return scheduled.length },
|
||||
cancel: () => {},
|
||||
onReady: url => readyUrls.push(url),
|
||||
fetcher: async (url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (options.method === "POST") {
|
||||
return { ok: true, status: 202, json: async () => ({ state: "staging", message: "Collecting logs", claimUrl: "", kind: JSON.parse(options.body).kind }) }
|
||||
}
|
||||
pollStep++
|
||||
if (pollStep === 1) {
|
||||
return { ok: true, status: 200, json: async () => ({ state: "idle", message: "", claimUrl: "", kind: "", available: true, fork: false, noteLimit: NOTE_LIMIT, modelLimit: MODEL_LIMIT }) }
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ state: "ready", message: "Logs uploaded", claimUrl: CLAIM, kind: "connection", available: true }) }
|
||||
},
|
||||
})
|
||||
|
||||
await client.start()
|
||||
assert.equal(requests[0].url, STAGE_URL)
|
||||
assert.equal(requests[0].options.cache, "no-store")
|
||||
assert.equal(requests[0].options.credentials, "same-origin")
|
||||
assert.equal(scheduled.length, 0, "idle state does not schedule polling")
|
||||
|
||||
assert.equal(await client.stage({ kind: "unknown", note: "hi" }), false)
|
||||
assert.match(state.error, /Choose what/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: " " }), false)
|
||||
assert.match(state.error, /short note/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: "a".repeat(NOTE_LIMIT + 1) }), false)
|
||||
assert.match(state.error, /200 characters/)
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "web", note: "hi" }), false)
|
||||
assert.match(state.error, /iPhone or Android/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: " ", note: "hi" }), false)
|
||||
assert.match(state.error, /make and model/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: "m".repeat(MODEL_LIMIT + 1), note: "hi" }), false)
|
||||
assert.match(state.error, /80 characters/)
|
||||
assert.equal(requests.length, 1, "client-side validation prevents network calls")
|
||||
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "ios", note: "Stuck connecting" }), true)
|
||||
const postBody = JSON.parse(requests.at(-1).options.body)
|
||||
assert.deepEqual(postBody, { kind: "connection", note: "Stuck connecting", phone: "ios" })
|
||||
assert.equal(state.state, "staging")
|
||||
assert.equal(scheduled.length, 1)
|
||||
|
||||
await client.poll()
|
||||
assert.equal(state.state, "ready")
|
||||
assert.equal(state.claimUrl, CLAIM)
|
||||
assert.deepEqual(readyUrls, [CLAIM])
|
||||
|
||||
client.reset(CLAIM)
|
||||
assert.equal(state.state, "idle")
|
||||
assert.equal(state.claimUrl, "")
|
||||
await client.poll()
|
||||
assert.equal(state.state, "idle", "dismissed claimUrl stays hidden on subsequent polls")
|
||||
assert.equal(readyUrls.length, 1)
|
||||
|
||||
client.fetcher = async () => ({ status: 401 })
|
||||
await client.poll()
|
||||
assert.equal(unauthorizedCount, 1)
|
||||
assert.equal(client.active, false)
|
||||
|
||||
// 4. captureZip and downloadCaptureZip contracts
|
||||
const originalDocument = globalThis.document
|
||||
const clicked = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, "a")
|
||||
return { href: "", download: "", click() { clicked.push(this.download) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
const validZip = "UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
const okConnection = await downloadCaptureZip("connection", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/local-access/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okConnection, true)
|
||||
const okController = await downloadCaptureZip("controller", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/controllers/log/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okController, true)
|
||||
assert.deepEqual(clicked, ["starpilot-connection-logs.zip", "starpilot-controller-logs.zip"])
|
||||
|
||||
await assert.rejects(
|
||||
() => captureZip("connection", { fetcher: async () => ({ ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: btoa("not-a-zip-header-at-all-123456") }) }) }),
|
||||
/Invalid diagnostic capture/,
|
||||
)
|
||||
} finally {
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
|
||||
console.log("LogHelp UI routing, LogStageClient, and captureZip checks passed")
|
||||
@@ -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()
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Pure bounded network/launcher readers; never imports native vehicle modules."""
|
||||
|
||||
import ast
|
||||
from base64 import b64decode
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import json
|
||||
@@ -8,7 +11,7 @@ import subprocess
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive, MAX_BYTES
|
||||
|
||||
|
||||
@@ -66,6 +69,56 @@ class TestNetworkDiagnostics(unittest.TestCase):
|
||||
for run in [lambda *_a, **_k: SimpleNamespace(stdout=b'x' * 65537), lambda *_a, **_k: (_ for _ in ()).throw(subprocess.TimeoutExpired('ip', 1))]:
|
||||
self.assertFalse(LocalAccess(run=run).snapshot()['available'])
|
||||
|
||||
def test_connection_capture_includes_only_known_advertiser_events(self):
|
||||
source, _ = self.addresses([interface()])
|
||||
commands = []
|
||||
|
||||
def run(args, **_kwargs):
|
||||
commands.append(args)
|
||||
if args[0] == 'systemctl':
|
||||
return SimpleNamespace(stdout=b'ActiveState=active\nSubState=running\nNRestarts=3\n')
|
||||
if args[0] == 'ip':
|
||||
state = [{'dev': 'wlan0', 'gateway': '192.168.50.1'}] if 'route' in args else [
|
||||
{'ifname': 'wlan0', 'operstate': 'UP', 'address': 'de:ad:be:ef:00:01',
|
||||
'addr_info': [{'local': '192.168.50.21', 'prefixlen': 24}, {'local': '8.8.8.8', 'prefixlen': 32}]}]
|
||||
return SimpleNamespace(stdout=json.dumps(state).encode())
|
||||
if args[0] == 'ss':
|
||||
return SimpleNamespace(stdout=b'LISTEN 0 20 0.0.0.0:8082 0.0.0.0:*')
|
||||
if 'galaxy-ble-fork.service' in args:
|
||||
return SimpleNamespace(stdout=b'{"MESSAGE":"Phone claimed pairing window"}')
|
||||
rows = [{'MESSAGE': 'Galaxy Wi-Fi discovery available on 1 local interface(s)'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: TimeoutExpired'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: cookie=private'},
|
||||
{'MESSAGE': 'Tunnel password: private'}]
|
||||
return SimpleNamespace(stdout='\n'.join(map(json.dumps, rows)).encode())
|
||||
|
||||
capture = connection_capture(source.snapshot(), run=run)
|
||||
self.assertEqual(capture['schemaVersion'], 1)
|
||||
self.assertIn('http://192.168.50.21:8082/', capture['text'])
|
||||
self.assertIn('Bonjour advertiser: active', capture['text'])
|
||||
self.assertIn('Galaxy Wi-Fi discovery available on 1 local interface(s)', capture['text'])
|
||||
self.assertIn('Wi-Fi discovery unavailable: TimeoutExpired', capture['text'])
|
||||
self.assertNotIn('Tunnel password:', capture['text'])
|
||||
self.assertTrue(any('galaxy-lan-discovery.service' in args for args in commands))
|
||||
with ZipFile(BytesIO(b64decode(capture['zipBase64']))) as archive:
|
||||
self.assertEqual(archive.namelist(), ['connection-logs.txt'])
|
||||
report = archive.read('connection-logs.txt').decode()
|
||||
self.assertIn('192.168.50.21/24', report)
|
||||
self.assertIn('IPv4 default route interfaces: wlan0', report)
|
||||
self.assertIn('TCP port 8082 listening: all interfaces', report)
|
||||
self.assertIn('NRestarts=3', report)
|
||||
self.assertIn('Phone claimed pairing window', report)
|
||||
for private_value in ('de:ad:be:ef:00:01', '192.168.50.1', '8.8.8.8', 'cookie=private'):
|
||||
self.assertNotIn(private_value, report)
|
||||
|
||||
def missing(*_args, **_kwargs):
|
||||
raise FileNotFoundError()
|
||||
|
||||
partial = connection_capture(source.snapshot(), run=missing)['text']
|
||||
self.assertIn('Bonjour advertiser: unavailable', partial)
|
||||
self.assertIn('Advertiser journal unavailable', partial)
|
||||
self.assertIn('192.168.50.21', partial)
|
||||
|
||||
def test_console_uses_exact_readonly_launcher_pane_and_cache(self):
|
||||
source, calls = self.console(b'first\nsecond\n')
|
||||
result = source.snapshot()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from 'node:assert/strict'
|
||||
import { compile } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { NetworksPage, validNetworks } from '../web/js/networks.js'
|
||||
@@ -66,3 +67,6 @@ const before = sent.length
|
||||
assert.equal(await vm.send({ action: 'cellular', value: false }), false)
|
||||
assert.equal(sent.length, before)
|
||||
vm.stop()
|
||||
|
||||
assert.equal(NetworksPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(NetworksPage.template.includes("<ConnectionLogs v-if=\"mode === 'local'\" panel"))
|
||||
|
||||
@@ -1161,7 +1161,7 @@ const displayRows = [
|
||||
{ key: "DeveloperSidebar", label: "Developer Sidebar", group: "Big layout", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "ShowBrakeStatus", label: "Wheel brake and acceleration colors", group: "widget", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "HideLeadMarker", label: "Lead Indicator", group: "Lead car", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
{ key: "LeadInfo", label: "Lead Info", group: "Lead car", choices: ["Off", "Distance", "Speed"], available: true, reason: "", requires: "HideLeadMarker" },
|
||||
{ key: "LeadInfo", label: "Lead Info", group: "Lead car", choices: ["Off", "Distance", "Speed", "Relative speed"], available: true, reason: "", requires: "HideLeadMarker" },
|
||||
{ key: "SignalMetrics", label: "C4 amber signal border", group: "Alerts and borders", choices: ["Off", "On"], available: true, reason: "", requires: "" },
|
||||
]
|
||||
const withDisplayData = () => ({ ...snapshot(), display: { rows: copy(displayRows),
|
||||
@@ -1179,7 +1179,7 @@ assert.equal(validDocument({ ...merged.document, showMaxSpeed: "no" }, merged.me
|
||||
const display = editor()
|
||||
display.vm.state.data = merged; display.vm.state.draft = copy(merged.document)
|
||||
assert.deepEqual(display.vm.displayGroups.map(group => [group.name, group.rows.map(row => row.key)]),
|
||||
[["Big layout", ["DeveloperSidebar"]], ["Lead car", ["HideLeadMarker", "LeadInfo"]], ["Alerts and borders", ["SignalMetrics"]]])
|
||||
[["Big layout", ["DeveloperSidebar"]], ["Alerts and borders", ["SignalMetrics"]]])
|
||||
display.vm.setDisplay("DeveloperSidebar", "Off")
|
||||
assert.equal(display.vm.displaySettingRow(display.vm.displayRow("DeveloperSidebar")).value, "Off")
|
||||
assert.equal(display.vm.dirty, true)
|
||||
@@ -1263,6 +1263,26 @@ assert.equal(display.vm.displayValue("LeadInfo"), "Distance")
|
||||
assert.equal(display.vm.dirty, true)
|
||||
display.vm.undo(); display.vm.undo()
|
||||
assert.equal(display.vm.dirty, false)
|
||||
display.vm.openLeadEditor()
|
||||
assert.equal(display.vm.state.inspectorPanel, "lead")
|
||||
assert.equal(display.vm.leadRows.length, 2)
|
||||
display.vm.setDisplay("HideLeadMarker", "On")
|
||||
display.vm.setDisplay("LeadInfo", "Relative speed")
|
||||
assert.equal(display.vm.leadPreviewLabel, "+4 mph")
|
||||
display.vm.roadColor("leadMarker", "#22CCFFFF")
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
assert.equal(validDocument(display.vm.state.draft, display.vm.state.data.metadata), true)
|
||||
display.vm.resetRoad()
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
display.vm.state.data.supportedProfiles = ["large", "compact"]
|
||||
display.vm.selectProfile("compact")
|
||||
assert.equal(display.vm.leadColor, "#FFFFFFFF")
|
||||
display.vm.selectProfile("large")
|
||||
display.vm.resetLeadColor()
|
||||
assert.equal(display.vm.leadColor, "#C92231FF")
|
||||
display.vm.undo()
|
||||
assert.equal(display.vm.leadColor, "#22CCFFFF")
|
||||
display.vm.resetToStock()
|
||||
display.vm.state.selected = "cruise_limits"
|
||||
display.vm.setShowMaxSpeed({ target: { checked: false } })
|
||||
assert.equal(display.vm.state.draft.showMaxSpeed, false)
|
||||
|
||||
@@ -18,8 +18,10 @@ class PreviewContractTest(unittest.TestCase):
|
||||
self.assertTrue(all(path.startswith("/") and path != "/tools" for path in paths))
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "partial-preview"], ["/logs"])
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "local-only"],
|
||||
["/bluetooth", "/cameras", "/galaxy", "/manage_models", "/navigation", "/networks", "/system",
|
||||
"/theme_maker", "/tuning", "/starport"])
|
||||
["/cameras", "/galaxy", "/manage_models", "/navigation", "/system", "/theme_maker", "/tuning", "/starport"])
|
||||
galaxy = next(tool for tool in catalog["tools"] if tool["path"] == "/galaxy")
|
||||
self.assertEqual([(tool["path"], tool["availability"]) for tool in galaxy["children"]],
|
||||
[("/networks", "local-only"), ("/bluetooth", "local-only")])
|
||||
self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "always"], [])
|
||||
self.assertTrue(all(tool["availability"] in {"always", "unavailable", "partial-preview", "local-only"} for tool in catalog["tools"]))
|
||||
self.assertTrue(all(tool["name"] and tool["description"] and tool["icon"] for tool in catalog["tools"]))
|
||||
@@ -27,8 +29,8 @@ class PreviewContractTest(unittest.TestCase):
|
||||
def test_static_preview_and_read_only_runtime_are_explicit(self):
|
||||
scripts = "\n".join(path.read_text() for path in (WEB / "js").glob("*.js"))
|
||||
self.assertEqual(sorted(re.findall(r"\bfetch\s*\(\s*[\"']([^\"']+)", scripts)),
|
||||
['./api/auth/session', './api/drive-state/action', './api/drive-state/status',
|
||||
'/_gateway/devices'])
|
||||
['./api/auth/session', './api/bluetooth/uniden', './api/drive-state/action',
|
||||
'./api/drive-state/status', '/_gateway/devices'])
|
||||
config = json.loads((WEB / 'data/runtime.json').read_text())
|
||||
self.assertEqual(config, {'schemaVersion': 1, 'monitor': 'sample'})
|
||||
self.assertIn('./api/ui/layout', scripts)
|
||||
|
||||
@@ -4,9 +4,11 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import SnapshotDenied
|
||||
from openpilot.starpilot.galaxy.server import make_remote_server, make_server
|
||||
from openpilot.starpilot.sentry_mode.notifications import NotificationOwner
|
||||
|
||||
@@ -19,16 +21,28 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
from openpilot.starpilot.sentry_mode.storage import EventStore
|
||||
owner.store = EventStore(root / 'events')
|
||||
parked = [True]
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0])
|
||||
photos = []
|
||||
jpeg = b'\xff\xd8\xff\xd9'
|
||||
class Camera:
|
||||
def capture_many(self, cameras, **options):
|
||||
return {camera: self.capture(camera, **options) for camera in cameras}
|
||||
def capture(self, camera, *, permitted, parked):
|
||||
if not parked or not permitted():
|
||||
raise SnapshotDenied
|
||||
photos.append(camera)
|
||||
return jpeg
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0],
|
||||
camera_snapshot=Camera())
|
||||
thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
thread.start()
|
||||
def request(payload=None, cookie=''):
|
||||
def request(payload=None, cookie='', path=None):
|
||||
connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3)
|
||||
headers = {'Cookie': cookie, 'Origin': f'http://127.0.0.1:{server.server_port}', 'Content-Type': 'application/json'}
|
||||
connection.request('POST' if payload is not None else 'GET', '/api/sentry/notifications' if payload is not None else '/api/auth/session',
|
||||
connection.request('POST' if payload is not None else 'GET', path or ('/api/sentry/notifications' if payload is not None else '/api/auth/session'),
|
||||
json.dumps(payload) if payload is not None else None, headers)
|
||||
reply = connection.getresponse()
|
||||
result = reply.status, json.loads(reply.read()), dict(reply.getheaders())
|
||||
raw = reply.read()
|
||||
result = reply.status, raw if reply.getheader('Content-Type') == 'image/jpeg' else json.loads(raw), dict(reply.getheaders())
|
||||
connection.close()
|
||||
return result
|
||||
try:
|
||||
@@ -38,11 +52,33 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
self.assertNotIn('test-token', json.dumps(result))
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': 'missing'}, cookie)[0], 404)
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': result['appSubscriptions'][0]['id']}, cookie)[0], 200)
|
||||
test_route = '/api/sentry/notifications/photo-test'
|
||||
test = {'camera': 'cabin', 'id': result['appSubscriptions'][0]['id']}
|
||||
self.assertEqual(request(test, path=test_route)[0], 401)
|
||||
parked[0] = False
|
||||
self.assertEqual(request(test, cookie, test_route)[0], 409)
|
||||
self.assertEqual(photos, [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 403)
|
||||
parked[0] = True
|
||||
self.assertEqual(request(test, cookie, test_route)[0], 503)
|
||||
self.assertEqual(request({'action': 'configure', 'channel': 'appPush', 'enabled': True,
|
||||
'url': 'https://relay.example.test', 'token': ''}, cookie)[0], 200)
|
||||
photos.clear()
|
||||
self.assertEqual(request(test, cookie, test_route)[:2], (200, {'queued': True}))
|
||||
self.assertEqual(photos, ['cabin'])
|
||||
event_id = next(iter(owner.test_photos))
|
||||
image_path = f'/api/sentry/image/{event_id}/test'
|
||||
self.assertEqual(request(path=image_path)[0], 401)
|
||||
self.assertEqual(request(cookie=cookie, path=image_path)[:2], (200, jpeg))
|
||||
self.assertEqual(owner.store.snapshot()['events'], [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 200)
|
||||
self.assertTrue(owner.store.snapshot()['events'][0]['simulated'])
|
||||
deadline = time.monotonic() + 3
|
||||
while not owner.store.snapshot()['events'] and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
event = owner.store.snapshot()['events'][0]
|
||||
self.assertTrue(event['simulated'])
|
||||
for camera in ('wide', 'cabin'):
|
||||
self.assertEqual(owner.store.image(event['eventId'], camera), jpeg)
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 429)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -1590,6 +1590,14 @@ border-top: 1px solid var(--outline-variant);
|
||||
@media (prefers-reduced-motion: reduce) { .gx-update-progress__fill--indeterminate { width: 100%; animation: none; opacity: .6; } }
|
||||
.gx-panel { padding: var(--panel-padding); min-width: 0; }
|
||||
.gx-card.gx-panel > .gx-section__header { margin: calc(-1 * var(--panel-padding)) calc(-1 * var(--panel-padding)) var(--sp-4); }
|
||||
.gx-connection-logs.gx-panel > .gx-section__header { margin-bottom: 0; }
|
||||
.gx-connection-logs .gx-log-form { display: grid; gap: var(--sp-3); margin-top: var(--sp-3); }
|
||||
.gx-log-form .gx-field { width: 100%; box-sizing: border-box; }
|
||||
.gx-log-form p { margin: 0; }
|
||||
.gx-log-form .gx-btn { justify-self: start; }
|
||||
@media (max-width: 600px) {
|
||||
.gx-connection-logs .gx-log-form .gx-btn, .gx-connection-logs details > summary.gx-btn { width: 100%; box-sizing: border-box; }
|
||||
}
|
||||
.gx-panel > :first-child { margin-top: 0; }
|
||||
.gx-panel > :last-child { margin-bottom: 0; }
|
||||
.gx-panel-footer { padding: 0 var(--panel-padding) var(--panel-padding); }
|
||||
@@ -1909,3 +1917,101 @@ progress { max-width: 100%; accent-color: var(--primary); }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gx-select-menu { transition: none; }
|
||||
}
|
||||
|
||||
.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; }
|
||||
}
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
{
|
||||
"mode": "offline-preview",
|
||||
"tools": [
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Cameras & Monitoring",
|
||||
"path": "/cameras",
|
||||
@@ -39,11 +32,27 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Galaxy Access & Install",
|
||||
"name": "Galaxy Access & Connections",
|
||||
"path": "/galaxy",
|
||||
"icon": "bi-globe2",
|
||||
"description": "Pair for remote access, install Galaxy, or set up a Wi-Fi hotspot",
|
||||
"availability": "local-only"
|
||||
"description": "Remote access, app setup, networks, Bluetooth, and support",
|
||||
"availability": "local-only",
|
||||
"children": [
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Logs & Diagnostics",
|
||||
@@ -67,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",
|
||||
@@ -96,10 +98,10 @@
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Help & Community",
|
||||
"name": "Get help",
|
||||
"path": "/logs/help",
|
||||
"icon": "bi-life-preserver",
|
||||
"description": "Guides and community help",
|
||||
"description": "Send StarPort, phone app, or controller logs, or ask on Discord",
|
||||
"availability": "always"
|
||||
}
|
||||
]
|
||||
@@ -141,13 +143,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "System Tools",
|
||||
"path": "/system",
|
||||
|
||||
@@ -154,7 +154,11 @@ createApp({
|
||||
state.drawerOpen = state.navPinned
|
||||
save(PIN_KEY, String(state.navPinned))
|
||||
},
|
||||
isActive(path) { return route.path === path || route.path.startsWith(path + "/") || (path === "/manage_models" && route.path === "/model_laboratory") },
|
||||
isActive(path) {
|
||||
if (path === "/galaxy" && ["/networks", "/bluetooth"].some(child =>
|
||||
route.path === child || route.path.startsWith(child + "/"))) return true
|
||||
return route.path === path || route.path.startsWith(path + "/") || (path === "/manage_models" && route.path === "/model_laboratory")
|
||||
},
|
||||
async signIn() {
|
||||
const password = authForm.password
|
||||
authForm.password = ""
|
||||
@@ -224,7 +228,7 @@ createApp({
|
||||
|
||||
</div>
|
||||
<div class="gx-nav-footer"><DevicePicker />
|
||||
<button type="button" class="gx-nav-item" :class="{active:isActive('/galaxy')}" @click="goFromMenu('/galaxy')"><i class="bi bi-globe"></i><span>Galaxy Access & Install</span></button>
|
||||
<button type="button" class="gx-nav-item" :class="{active:isActive('/galaxy')}" @click="goFromMenu('/galaxy')"><i class="bi bi-globe"></i><span>Galaxy Access & Connections</span></button>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="gx-content" :style="{'--route-direction': routeDirection}"><div class="gx-route-stage">
|
||||
@@ -254,11 +258,11 @@ createApp({
|
||||
<VasmPage v-else-if="route.path === '/cameras/vasm'" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" />
|
||||
<Tools v-else-if="route.path === '/tools'" :tools="visibleTools" :mode="state.monitorMode" />
|
||||
<SettingsPage @nested="ensureBackEntry" ref="activeSettings" v-else-if="route.path === '/developer/connect'" :mode="state.monitorMode" :unauthorized="sessionExpired" initial-section="developer" />
|
||||
<GalaxyPage v-else-if="route.path === '/galaxy'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<NetworksPage v-else-if="route.path === '/networks'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<GalaxyPage v-else-if="route.path === '/galaxy'" :mode="state.monitorMode" :tools="currentTool?.children || []" :unauthorized="sessionExpired" :go="go" />
|
||||
<NetworksPage v-else-if="route.path === '/networks'" :go="go" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<OnroadLayoutPage ref="activeLayout" v-else-if="['/theme_maker', '/theme_maker/starport', '/appearance'].includes(route.path)" :key="route.path" :projection="route.path === '/theme_maker/starport'" :initial-panel="route.path === '/appearance' ? 'display' : 'widgets'" :mode="state.monitorMode" :unauthorized="sessionExpired" @target="go($event === 'projection' ? '/theme_maker/starport' : '/theme_maker')" @close="routeBack" />
|
||||
<SettingsRecoveryPage v-else-if="route.path === '/settings/recovery'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<Logs v-else-if="route.path === '/logs' || route.path.startsWith('/logs/') || ['/troubleshoot', '/manage_tmux'].includes(route.path)" :path="route.path === '/troubleshoot' ? '/logs/troubleshoot' : route.path === '/manage_tmux' ? '/logs/tmux' : route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :tools="currentTool?.children || []" />
|
||||
<Logs v-else-if="route.path === '/logs' || route.path.startsWith('/logs/') || ['/troubleshoot', '/manage_tmux'].includes(route.path)" :path="route.path === '/troubleshoot' ? '/logs/troubleshoot' : route.path === '/manage_tmux' ? '/logs/tmux' : route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :local-routes="state.monitorMode === 'local' && authState.localAccess" :tools="currentTool?.children || []" />
|
||||
<SoftwarePage v-else-if="route.path === '/system'" :mode="state.monitorMode" :unauthorized="sessionExpired" :restarting="baseline => updateRestart.start({ ...baseline, instance: deviceRestart.instance })"
|
||||
:preparing="baseline => updateRestart.prepare({ ...baseline, instance: deviceRestart.instance })" :cancel-preparation="() => updateRestart.cancelPreparation()" />
|
||||
<NavigationPage v-else-if="['/navigation', '/navigation/maps', '/navigation/setup'].includes(route.path)" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" :tabs="currentTool?.children || []"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { UnidenPanel } from './uniden.js'
|
||||
import { GxState } from "./state.js"
|
||||
@@ -169,7 +170,7 @@ export class BluetoothFeed {
|
||||
}
|
||||
|
||||
export const BluetoothPage = {
|
||||
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog },
|
||||
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() {
|
||||
@@ -322,5 +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>
|
||||
</section>`,
|
||||
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel :on-unauthorized="unauthorized" @help="go('/logs/help/connection')" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
export const DrivingHelp = {
|
||||
props: {
|
||||
routeId: { type: String, default: "" },
|
||||
segment: { type: Number, default: null },
|
||||
connect: { type: String, default: "" },
|
||||
routesAvailable: Boolean,
|
||||
},
|
||||
emits: ["routes"],
|
||||
data: () => ({ copied: false }),
|
||||
computed: {
|
||||
routeDetails() {
|
||||
return this.routeId + (this.segment === null ? "" : " · Segment " + this.segment)
|
||||
},
|
||||
},
|
||||
watch: { routeDetails() { this.copied = false } },
|
||||
methods: {
|
||||
async copyDetails() {
|
||||
this.copied = false
|
||||
const details = this.routeDetails
|
||||
try {
|
||||
await navigator.clipboard.writeText(details)
|
||||
if (details === this.routeDetails) this.copied = true
|
||||
} catch {
|
||||
// Local Galaxy commonly runs on HTTP, where the Clipboard API is unavailable.
|
||||
this.$refs.details?.select()
|
||||
}
|
||||
},
|
||||
},
|
||||
template: `<div class="gx-stack">
|
||||
<p class="gx-note">Find the drive, then share the route link and approximate timestamp or segment. Describe what the car did and what you expected.</p>
|
||||
<div v-if="routeId" class="gx-actions">
|
||||
<input ref="details" class="gx-field" aria-label="Route and segment for support" :value="routeDetails" readonly @focus="$event.target.select()">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="copyDetails">{{ copied ? 'Copied' : 'Copy route details' }}</button>
|
||||
</div>
|
||||
<div class="gx-actions">
|
||||
<button v-if="!routeId && routesAvailable" type="button" class="gx-btn gx-btn--tonal" @click="$emit('routes')">Open Galaxy Routes</button>
|
||||
<a class="gx-btn gx-btn--tonal" :href="connect || 'https://connect.comma.ai/'" target="_blank" rel="noopener noreferrer">{{ connect ? 'Open this route online' : 'Open comma connect' }}</a>
|
||||
<a class="gx-btn gx-btn--tonal" href="https://discord.com/channels/1387432184121393333/1506463404863389806" target="_blank" rel="noopener noreferrer">Driving support on Discord</a>
|
||||
</div>
|
||||
<p v-if="!routeId && !routesAvailable" class="gx-note">Connect directly to your comma to browse saved Galaxy routes.</p>
|
||||
</div>`,
|
||||
}
|
||||
@@ -417,9 +417,14 @@ export function parkedAnalysisProgress(report) {
|
||||
const counted = Array.isArray(value) && value.length === 3 && Object.hasOwn(labels, value[0]) && Number.isSafeInteger(done) && Number.isSafeInteger(total) && done >= 0 && total > 0 && done <= total && total <= 180
|
||||
const steps = { preparing: 'Starting the parked analyzer.', reading: 'Reading the recording sections.',
|
||||
verifying: 'Checking that the recording is unchanged.', checking: 'Checking the suggested changes.' }
|
||||
const detail = counted && phase === 'reading' ? `${done} of ${total} sections read in this recording` : steps[phase]
|
||||
const queue = current.details?.['Parked recording queue']
|
||||
const [position, recordings] = Array.isArray(queue) && queue.length === 2 ? queue : []
|
||||
const queued = Number.isSafeInteger(position) && Number.isSafeInteger(recordings) && position >= 0 && position <= recordings && recordings > 0 && recordings <= 8
|
||||
const recording = queued && position === 0 ? 'Rechecking with evidence from other drives. ' :
|
||||
queued && recordings > 1 ? `Recording ${position} of ${recordings}. ` : ''
|
||||
return { phase, label: labels[phase], completed: counted ? done : null, total: counted ? total : null,
|
||||
percent: counted && phase === 'reading' && done < total ? done / total * 100 : null,
|
||||
detail: counted && phase === 'reading' ? `${done} of ${total} sections read in this recording` : steps[phase] }
|
||||
percent: counted && phase === 'reading' && done < total ? done / total * 100 : null, detail: recording + detail }
|
||||
}
|
||||
|
||||
export function tunerStatus(report, live = false, choiceLive = false, error = "", reportFresh = live) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MenuTile } from './menu-tile.js'
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { AppStoreLinks } from './app-downloads.js'
|
||||
import { InstallApp } from './install-app.js'
|
||||
@@ -6,12 +7,25 @@ import { CompanionUpdates } from './companion-updates.js'
|
||||
|
||||
export const GalaxyPage = {
|
||||
name: 'GalaxyPage',
|
||||
components: { WikiHelp, AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates },
|
||||
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
components: { WikiHelp, AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates, MenuTile },
|
||||
props: {
|
||||
mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
|
||||
tools: { type: Array, default: () => [] }, go: { type: Function, default: path => { location.hash = path } },
|
||||
},
|
||||
data: () => ({ url: '' }),
|
||||
template: `<div class="gx-settings gx-tunnel">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Galaxy Access & Install</h2>
|
||||
<p>Set up your link, then choose how to open Galaxy.</p></div><WikiHelp /></header>
|
||||
<header class="gx-settings__header gx-page-header">
|
||||
<div><h2>Galaxy Access & Connections</h2></div>
|
||||
<div class="gx-actions">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/help')">Get help</button>
|
||||
<WikiHelp />
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="tools.length" class="gx-grid">
|
||||
<MenuTile v-for="tool in tools" :key="tool.path" :icon="tool.icon" :title="tool.name"
|
||||
:description="tool.description" :disabled="mode !== 'local'" :availability="mode !== 'local' ? 'Connect to your comma' : ''"
|
||||
@select="go(tool.path)" />
|
||||
</div>
|
||||
<ol class="gx-steps">
|
||||
<RemoteAccess title="Set up remote access" :mode="mode" :unauthorized="unauthorized" @link="url = $event" />
|
||||
<li class="gx-card gx-step" aria-label="Get the app">
|
||||
@@ -24,8 +38,5 @@ export const GalaxyPage = {
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<section class="gx-card gx-panel gx-stack"><div class="gx-section__header"><i class="bi bi-wifi" aria-hidden="true"></i><span class="gx-section__title">Galaxy Wi-Fi Hotspot</span></div>
|
||||
<p>The hotspot, preferred Wi-Fi networks and cellular data are on the Networks page.</p>
|
||||
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" href="#/networks">Open Networks</a></div></section>
|
||||
</div>`,
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ export const Home = {
|
||||
template: `
|
||||
<div class="gx-view gx-home">
|
||||
<div class="gx-home__hero gx-page-header">
|
||||
<div><h1>Dashboard</h1><p class="gx-note">Your saved drives and current device</p></div><WikiHelp />
|
||||
<div><h1>Dashboard</h1><p class="gx-note">Your saved drives and current device</p></div><div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/help')">Get help</button><WikiHelp /></div>
|
||||
</div>
|
||||
<GxState v-if="mode !== 'local'">Dashboard information is available on your device.</GxState>
|
||||
<template v-else>
|
||||
|
||||
@@ -13,7 +13,7 @@ export function isAndroidDevice(agent = typeof navigator === 'undefined' ? '' :
|
||||
}
|
||||
|
||||
export function installHelp({ secure = window.isSecureContext, agent = navigator.userAgent } = {}) {
|
||||
if (!secure) return 'Bookmark this local address for hotspot or Wi-Fi access without Internet. To install Galaxy as a web app (PWA), open your device-specific https://galaxy.firestar.link link from Galaxy Access & Install; this remote link needs Internet.'
|
||||
if (!secure) return 'Bookmark this local address for hotspot or Wi-Fi access without Internet. To install Galaxy as a web app (PWA), open your device-specific https://galaxy.firestar.link link from Galaxy Access & Connections; this remote link needs Internet.'
|
||||
if (/iPhone|iPad|iPod/.test(agent)) return 'Open Galaxy in Safari, tap Share, then Add to Home Screen. Turn on Open as Web App if shown.'
|
||||
return 'This browser cannot install Galaxy automatically. Open the browser menu and choose Install app or Add to Home Screen. On a Mac in Safari, choose File → Add to Dock.'
|
||||
}
|
||||
|
||||
@@ -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,8 +50,47 @@ export class LocalAccessFeed {
|
||||
}
|
||||
}
|
||||
|
||||
export const LocalAccess = {
|
||||
export const ConnectionLogs = {
|
||||
components: { GxNotice },
|
||||
props: { panel: Boolean, controller: Boolean, onUnauthorized: { type: Function, default: () => {} } },
|
||||
emits: ["help"],
|
||||
data: () => ({ captureBusy: false, captureError: "", captureSignal: null }),
|
||||
beforeUnmount() { this.captureSignal?.abort() },
|
||||
methods: {
|
||||
async downloadConnectionLogs() {
|
||||
if (this.captureBusy) return
|
||||
const controller = new AbortController()
|
||||
this.captureSignal = controller
|
||||
this.captureBusy = true
|
||||
this.captureError = ""
|
||||
try {
|
||||
await downloadCaptureZip(this.controller ? "controller" : "connection", {
|
||||
unauthorized: this.onUnauthorized,
|
||||
request: { signal: controller.signal },
|
||||
})
|
||||
} catch (error) {
|
||||
if (error?.name !== "AbortError") this.captureError = error?.message || "Could not prepare diagnostic ZIP."
|
||||
} finally {
|
||||
if (this.captureSignal === controller) {
|
||||
this.captureSignal = null
|
||||
this.captureBusy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
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')">Send logs</button>
|
||||
</div>
|
||||
<div v-else class="gx-actions">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="captureBusy" @click="downloadConnectionLogs">{{ captureBusy ? 'Preparing ZIP…' : 'Download connection ZIP' }}</button>
|
||||
</div>
|
||||
<GxNotice v-if="captureError" tone="danger">{{ captureError }}</GxNotice>
|
||||
</div>`,
|
||||
}
|
||||
|
||||
export const LocalAccess = {
|
||||
components: { GxNotice, ConnectionLogs },
|
||||
props: { mode: { type: String, required: true }, onUnauthorized: { type: Function, default: () => {} } },
|
||||
setup(props) {
|
||||
const state = reactive({ loading: false, data: null, error: "" })
|
||||
@@ -69,5 +109,6 @@ export const LocalAccess = {
|
||||
<p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p>
|
||||
</template>
|
||||
<p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :on-unauthorized="onUnauthorized" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
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 & 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>{{ 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 & 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="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>
|
||||
`,
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
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"
|
||||
@@ -6,52 +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 },
|
||||
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 }
|
||||
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: {
|
||||
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() {
|
||||
@@ -70,12 +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="path === '/logs/help'" class="gx-settings">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Help & Community</h2><p>Guides and help from the community.</p></div><WikiHelp path="/logs/help" /></header>
|
||||
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-discord" aria-hidden="true"></i><span class="gx-section__title">Discord</span></div>
|
||||
<div class="gx-panel"><p class="gx-note">Ask the community for help, share what you have tried, and follow StarPilot announcements.</p>
|
||||
<a class="gx-btn gx-btn--tonal" href="https://firestar.link/discord" target="_blank" rel="noopener noreferrer">Join Discord</a></div></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>
|
||||
@@ -96,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,3 +1,4 @@
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { requestJson } from "./startup.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
@@ -28,8 +29,8 @@ export const choiceRow = (label, value, choices, reason = '') => ({ label, value
|
||||
|
||||
export const NetworksPage = {
|
||||
name: "NetworksPage",
|
||||
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog },
|
||||
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
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 }),
|
||||
computed: {
|
||||
@@ -261,5 +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/connection')" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -168,7 +168,8 @@ export function validDocument(document, metadata) {
|
||||
const profile = metadata.profiles[name], layout = document.layouts[name]
|
||||
const road = document.roadColors[name]
|
||||
if (!object(road) || !Object.entries(road).every(([key, value]) => key === "pathMode" ? PATH_MODES.includes(value) :
|
||||
ROAD_COLORS.includes(key) && typeof value === "string" && HEX.test(value))) return false
|
||||
(ROAD_COLORS.includes(key) || key === "leadMarker") &&
|
||||
typeof value === "string" && HEX.test(value))) return false
|
||||
const colors = document.widgetColors[name]
|
||||
if (!object(colors) || !Object.entries(colors).every(([id, overrides]) => {
|
||||
const fields = profile.widgets[id]?.colors
|
||||
|
||||
@@ -132,6 +132,20 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<text :x="zone.x + zone.width / 2" :y="zone.y + zone.height - 8" text-anchor="middle" :font-size="state.profile === 'large' ? 20 : 10" fill="#d8c8ff">{{ zone.label }}</text>
|
||||
</g>
|
||||
</g>
|
||||
<g v-if="!projection && leadRows.length && !artLoading" class="gx-layout__widget" role="button" tabindex="0" style="cursor: pointer"
|
||||
:class="{'is-editing': state.inspectorPanel === 'lead'}"
|
||||
aria-label="Edit Lead Indicator" :aria-pressed="state.inspectorPanel === 'lead'"
|
||||
:transform="'translate(' + (roadBounds.x + roadBounds.width * .48) + ' ' + (roadBounds.y + roadBounds.height * .53) + ') scale(' + (state.profile === 'compact' ? 1 : 3) + ')'"
|
||||
@pointerdown.stop @click="openLeadEditor" @keydown.enter.prevent="openLeadEditor" @keydown.space.prevent="openLeadEditor">
|
||||
<rect x="-32" y="-29" width="64" height="53" fill="transparent" />
|
||||
<path v-if="state.profile === 'compact'" d="M-25 4 L25 4 L23 9 L-23 9 Z" :fill="leadColor"
|
||||
:opacity="displayValue('HideLeadMarker') === 'On' ? 1 : .45" />
|
||||
<path v-else d="M0 15 L-15 -9 L0 -4 L15 -9 Z" :fill="leadColor"
|
||||
:opacity="displayValue('HideLeadMarker') === 'On' ? 1 : .45" />
|
||||
<text v-if="leadPreviewLabel" y="-14" text-anchor="middle" font-size="12" font-weight="600" fill="white"
|
||||
stroke="#101014" stroke-width="2" paint-order="stroke">{{ leadPreviewLabel }}</text>
|
||||
<rect class="gx-layout__selection" x="-29" y="-29" width="58" height="50" rx="4" fill="none" stroke="#b799ff" stroke-dasharray="3 2" />
|
||||
</g>
|
||||
<text v-if="artLoading" :x="profile.width / 2" :y="profile.height / 2" text-anchor="middle" dominant-baseline="middle"
|
||||
:font-size="state.profile === 'compact' ? 16 : 40" font-weight="600" fill="#d8c8ff" role="status">Loading Widgets</text>
|
||||
<g v-for="widget in artLoading ? [] : renderWidgets" :key="widget.id" class="gx-layout__widget" :class="{'is-selected': state.drag?.id === widget.id, 'is-armed': state.touchArmed === widget.id, 'is-editing': state.showEditingAids && state.inspectorPanel === 'edit' && state.selected === widget.id}"
|
||||
@@ -185,7 +199,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<section class="gx-card gx-layout__inspector" aria-label="Widget placement" @focusin="revealField"> <!-- codespell:ignore focusin -->
|
||||
<nav ref="sections" class="gx-layout__switcher gx-layout__sections gx-settings-tabs" :class="{'is-stuck': state.stuck.sections}" aria-label="Editor sections">
|
||||
<button class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === 'widgets'" :disabled="!!state.drag || !!state.layerDrag" @click="state.inspectorPanel = 'widgets'">Widgets</button>
|
||||
<button class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === 'edit'" :disabled="!!state.drag || !!state.layerDrag" @click="openEditPanel()"><span>Edit<span class="gx-layout__long"> widget</span></span></button>
|
||||
<button class="gx-btn gx-btn--tonal" :aria-pressed="['edit', 'lead'].includes(state.inspectorPanel)" :disabled="!!state.drag || !!state.layerDrag" @click="state.inspectorPanel === 'lead' ? revealEditPanel() : openEditPanel()"><span>Edit<span class="gx-layout__long"> widget</span></span></button>
|
||||
<button v-if="!projection" class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === 'road'" :disabled="!!state.drag || !!state.layerDrag" @click="state.inspectorPanel = 'road'"><span>Road<span class="gx-layout__long"> colors</span></span></button>
|
||||
<button v-if="projection || displayGroups.length" class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === 'display'" :disabled="!!state.drag || !!state.layerDrag" @click="state.inspectorPanel = 'display'">Options</button>
|
||||
</nav>
|
||||
@@ -196,6 +210,9 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<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>
|
||||
</div></GxCollapse>
|
||||
</div>
|
||||
<div v-if="!projection && leadRows.length" class="gx-actions">
|
||||
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!!state.drag || !!state.layerDrag" @click="openLeadEditor">Lead Indicator</button>
|
||||
</div>
|
||||
<div class="gx-layout__widget-list"><div v-for="widget in listWidgets" :key="widget.id" class="gx-layout__layer" :data-layer-id="widget.id"
|
||||
:class="{'is-dragging': state.layerDrag?.id === widget.id && state.layerDrag?.moved, 'is-drop-target': state.layerDrag?.target === widget.id && state.layerDrag?.id !== widget.id, 'is-drop-after': state.layerDrag?.after}">
|
||||
<button class="gx-layout__row-grip gx-icon-btn" type="button"
|
||||
@@ -369,6 +386,17 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<p v-if="!projection && !colorFields.length" class="gx-note">This widget uses its original status colors.</p>
|
||||
</div>
|
||||
</div>
|
||||
<section v-if="!projection && state.inspectorPanel === 'lead'" ref="leadPanel" class="gx-layout__panel gx-layout__edit" aria-label="Edit Lead Indicator">
|
||||
<div class="gx-layout__subhead"><h4>Lead Indicator</h4></div>
|
||||
<GalaxySettingRow feedback="draft" v-for="(row, index) in leadRows" :key="row.key" :row="displaySettingRow(row)" :index="index"
|
||||
:disabled="!editable || !!state.drag || !!state.layerDrag || !displayAvailable(row)" :save-value="(_, value) => setDisplay(row.key, value)" />
|
||||
<div class="gx-actions">
|
||||
<label for="layout-lead-color">Marker color</label>
|
||||
<input id="layout-lead-color" type="color" :value="leadColor.slice(0, 7)" :disabled="!editable || !!state.drag || !!state.layerDrag"
|
||||
@input="roadColor('leadMarker', $event.target.value + 'FF', 'leadMarker')" @change="finishColorEdit" @blur="finishColorEdit" />
|
||||
<button class="gx-btn gx-btn--tonal" type="button" :disabled="!editable || !roadStyle.leadMarker" @click="resetLeadColor">Reset color</button>
|
||||
</div>
|
||||
</section>
|
||||
<section v-if="!projection" v-show="state.inspectorPanel === 'road'" class="gx-layout__colors" aria-label="Path and lane colors">
|
||||
<div class="gx-layout__subhead"><h4>Path & Lane Colors</h4><button class="gx-btn gx-btn--tonal" type="button" :disabled="!editAvailable || !!state.drag" @click="resetRoad" aria-label="Reset road colors" title="Reset road colors">Reset</button></div>
|
||||
<label>Path style<GalaxySelect class="gx-field gx-field--full" :value="roadMode" :disabled="!editAvailable || !!state.drag" @change="setRoadMode($event.target.value)">
|
||||
|
||||
@@ -784,10 +784,16 @@ export const OnroadLayoutPage = {
|
||||
{ offset: 1, color: '#0df87a', alpha: 102 / 255 }]
|
||||
},
|
||||
limits() { return this.selectedWidget ? placementLimits(this.limitProfile, this.state.selected, this.layout) : null },
|
||||
leadRows() { return ["HideLeadMarker", "LeadInfo"].map(key => this.displayRow(key)).filter(Boolean) },
|
||||
leadColor() { return this.roadStyle.leadMarker || (this.state.profile === "compact" ? "#FFFFFFFF" : "#C92231FF") },
|
||||
leadPreviewLabel() {
|
||||
return this.displayValue("HideLeadMarker") === "On" ?
|
||||
({ Distance: "82 ft", Speed: "42 mph", "Relative speed": "+4 mph" }[this.displayValue("LeadInfo")] || "") : ""
|
||||
},
|
||||
displayGroups() {
|
||||
const groups = []
|
||||
for (const row of this.state.data?.display || []) {
|
||||
if (row.group === "widget") continue
|
||||
if (row.group === "widget" || ["HideLeadMarker", "LeadInfo"].includes(row.key)) continue
|
||||
const group = groups.find(item => item.name === row.group) || groups[groups.push({ name: row.group, rows: [] }) - 1]
|
||||
group.rows.push(row)
|
||||
}
|
||||
@@ -892,12 +898,19 @@ export const OnroadLayoutPage = {
|
||||
this.state.inspectorPanel = "edit"
|
||||
this.revealEditPanel()
|
||||
},
|
||||
openLeadEditor() {
|
||||
if (this.projection || this.state.drag || this.state.layerDrag) return
|
||||
this.deselectWidget()
|
||||
this.state.inspectorPanel = "lead"
|
||||
this.revealEditPanel()
|
||||
},
|
||||
// On narrow screens the edit controls always open with their top just under the pinned tabs.
|
||||
revealEditPanel() {
|
||||
if (typeof window === "undefined") return
|
||||
const align = () => {
|
||||
if (this.state.inspectorPanel !== "edit") return
|
||||
const tabs = this.$refs.sections, panel = this.$refs.editPanel
|
||||
const section = this.state.inspectorPanel
|
||||
if (!["edit", "lead"].includes(section)) return
|
||||
const tabs = this.$refs.sections, panel = section === "lead" ? this.$refs.leadPanel : this.$refs.editPanel
|
||||
if (!tabs || !panel || getComputedStyle(tabs).position !== "sticky") return
|
||||
const gap = panel.getBoundingClientRect().top - tabs.getBoundingClientRect().bottom - 8
|
||||
if (Math.abs(gap) >= 1) window.scrollBy(0, gap)
|
||||
@@ -1243,7 +1256,8 @@ export const OnroadLayoutPage = {
|
||||
displaySettingRow(row) {
|
||||
const blocked = row.requires && this.displayValue(row.requires) !== "On"
|
||||
return {
|
||||
label: row.label, value: this.displayValue(row.key), choices: row.choices, available: this.displayAvailable(row),
|
||||
label: row.key === "LeadInfo" ? "Lead readout" : row.label,
|
||||
value: this.displayValue(row.key), choices: row.choices, available: this.displayAvailable(row),
|
||||
reason: blocked ? "Turn on Lead Indicator first" : row.reason, action: true
|
||||
}
|
||||
},
|
||||
@@ -1643,7 +1657,7 @@ export const OnroadLayoutPage = {
|
||||
this.recordChange(before)
|
||||
},
|
||||
roadColor(id, value, group = null) {
|
||||
if (!this.editable || this.state.drag || !ROAD_COLORS.includes(id)) return
|
||||
if (!this.editable || this.state.drag || !ROAD_COLORS.includes(id) && (id !== "leadMarker" || this.projection)) return
|
||||
if (!HEX.test(value)) { this.state.colorError = "Use eight hex digits, for example #30FF9CFF."; return }
|
||||
const before = clone(this.state.draft)
|
||||
this.state.draft.roadColors[this.state.profile][id] = value.toUpperCase()
|
||||
@@ -1663,10 +1677,17 @@ export const OnroadLayoutPage = {
|
||||
resetRoad() {
|
||||
if (!this.editable || this.state.drag) return
|
||||
const before = clone(this.state.draft)
|
||||
this.state.draft.roadColors[this.state.profile] = {}
|
||||
const marker = this.roadStyle.leadMarker
|
||||
this.state.draft.roadColors[this.state.profile] = marker ? { leadMarker: marker } : {}
|
||||
this.recordChange(before)
|
||||
this.state.colorError = ''
|
||||
},
|
||||
resetLeadColor() {
|
||||
if (!this.editable || this.projection || this.state.drag || this.state.layerDrag) return
|
||||
const before = clone(this.state.draft)
|
||||
delete this.state.draft.roadColors[this.state.profile].leadMarker
|
||||
this.recordChange(before)
|
||||
},
|
||||
widgetColors(id) { return widgetPalette(this.state.draft, this.state.data.metadata, this.state.profile, id) },
|
||||
color(id, value, group = null) {
|
||||
if (!this.editable || this.state.drag || !Object.hasOwn(this.selectedWidget?.colors || {}, id)) return
|
||||
|
||||
@@ -3,9 +3,33 @@ import { GxNotice } from './notice.js'
|
||||
import { requestJson } from './startup.js'
|
||||
import { BluetoothNotice, bluetoothConnection } from './bluetooth-notice.js'
|
||||
|
||||
export const RemoteQR = {
|
||||
props: { endpoint: {type: String, required: true}, alt: {type: String, required: true} },
|
||||
data: () => ({image: '', failed: false, request: null}),
|
||||
mounted() { this.load() },
|
||||
beforeUnmount() { this.request?.abort(); if (this.image) URL.revokeObjectURL(this.image) },
|
||||
methods: {
|
||||
async load() {
|
||||
this.request?.abort()
|
||||
const request = new AbortController()
|
||||
this.request = request
|
||||
this.failed = false
|
||||
try {
|
||||
const response = await fetch(this.endpoint, {credentials: 'same-origin', cache: 'no-store', signal: request.signal})
|
||||
if (!response.ok || response.headers.get('content-type')?.split(';')[0] !== 'image/svg+xml') throw Error()
|
||||
const blob = await response.blob()
|
||||
if (request.signal.aborted) return
|
||||
if (this.image) URL.revokeObjectURL(this.image)
|
||||
this.image = URL.createObjectURL(blob)
|
||||
} catch { if (!request.signal.aborted) this.failed = true }
|
||||
},
|
||||
},
|
||||
template: '<div><button v-if="failed" class="gx-btn" @click="load">Retry QR code</button><img v-else-if="image" :src="image" :alt="alt" class="gx-tunnel__qr" @error="failed = true" /></div>',
|
||||
}
|
||||
|
||||
export const RemoteAccess = {
|
||||
name: 'RemoteAccess',
|
||||
components: { GxState, GxNotice, BluetoothNotice },
|
||||
components: { GxState, GxNotice, BluetoothNotice, RemoteQR },
|
||||
props: { title: { type: String, default: 'Remote access' }, step: { type: Number, default: 1 }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
emits: ['link'],
|
||||
data: () => ({ loading: true, paired: false, url: '', tunnelClientAvailable: false, legacyPassword: false,
|
||||
@@ -98,12 +122,12 @@ export const RemoteAccess = {
|
||||
<template v-if="paired">
|
||||
<GxNotice v-if="!tunnelClientAvailable" tone="warn">Remote access is not ready on this comma yet.</GxNotice>
|
||||
<BluetoothNotice v-if="bluetooth" feature="Galaxy QR code">Your Galaxy link remains available below.</BluetoothNotice>
|
||||
<img v-else src="./api/galaxy/qr.svg" alt="QR code for your Galaxy link" class="gx-tunnel__qr" />
|
||||
<RemoteQR v-else :key="url" endpoint="./api/galaxy/qr.svg" alt="QR code for your Galaxy link" />
|
||||
<p><a :href="url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">Open your Galaxy link</a></p>
|
||||
<section class="gx-card gx-panel gx-stack"><h3>App key</h3><p>Use this key to add remote access in the phone app. Keep it private.</p>
|
||||
<div v-if="!keyVisible" class="gx-actions"><button class="gx-btn" @click="showAppKey">Show</button></div>
|
||||
<template v-else><code class="gx-wrap">{{ appKey }}</code><div class="gx-actions"><button class="gx-btn" @click="copyAppKey">Copy</button></div>
|
||||
<img src="./api/galaxy/session/qr.svg" class="gx-tunnel__qr" alt="Add remote access to Galaxy" /></template>
|
||||
<RemoteQR endpoint="./api/galaxy/session/qr.svg" alt="Add remote access to Galaxy" /></template>
|
||||
</section>
|
||||
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--danger" @click="unpair">{{ busy ? 'Disconnecting…' : 'Turn off remote access' }}</button></div>
|
||||
</template>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DrivingHelp } from "./driving-help.js"
|
||||
import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { GxIconButton } from "./icon-button.js"
|
||||
@@ -11,7 +12,7 @@ import { LOCAL, VIDEOS, hasVideo, availableFiles, validRouteDetail, routeDate, c
|
||||
logUrl, logArchiveUrl, connectRouteUrl, formatBytes, detailMetric, segmentSummaryUrl, validSegmentSummary } from "./recording-data.js"
|
||||
|
||||
export const RouteWorkspace = {
|
||||
components: { GxState, GxNotice, GxIconButton, GxDialog, GalaxySelect, RecordingActions, CameraViewer, ReplayViewer },
|
||||
components: { GxState, GxNotice, GxIconButton, GxDialog, GalaxySelect, RecordingActions, CameraViewer, ReplayViewer, DrivingHelp },
|
||||
props: { routeId: { type: String, required: true }, summary: { type: Object, default: null },
|
||||
initialMode: { type: String, default: "footage" }, exports: { type: Object, required: true }, unauthorized: { type: Function, required: true } },
|
||||
emits: ["back", "changed"],
|
||||
@@ -198,6 +199,10 @@ export const RouteWorkspace = {
|
||||
<GxState v-if="status === 'loading'" loading>Reading saved route…</GxState>
|
||||
<GxNotice v-if="error" tone="danger">{{ error }}<template #actions v-if="status === 'unavailable'"><button class="gx-btn gx-btn--tonal" @click="load">Retry route</button></template></GxNotice>
|
||||
<template v-if="status === 'ready' && route">
|
||||
<details class="gx-card gx-panel">
|
||||
<summary>Get help with this drive</summary>
|
||||
<DrivingHelp :route-id="routeId" :segment="segment?.number ?? null" :connect="connect || ''" />
|
||||
</details>
|
||||
<GxNotice v-if="!route.inventoryComplete" tone="warn">{{ route.reason || 'Some route files could not be inspected.' }} Route downloads require a complete inventory.</GxNotice>
|
||||
<div class="gx-route-workspace__body">
|
||||
<section class="gx-card gx-route-workspace__viewer" aria-label="Route viewer">
|
||||
|
||||
@@ -6,6 +6,7 @@ const start = () => {
|
||||
const hash = location.hash.slice(1) || "/"
|
||||
let path
|
||||
try { path = decodeURIComponent(hash) } catch { path = hash }
|
||||
if (path === "/connections") return "/galaxy"
|
||||
return path === "/vehicle" ? "/settings/vehicle" : path
|
||||
}
|
||||
route.path = start()
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -2,6 +2,7 @@ import numpy as np
|
||||
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.starpilot.lateral import hkg_vehicle_shaping as shaping
|
||||
|
||||
from openpilot.starpilot.lateral.hkg_torque_policy import HKGShapedTorquePolicy, supported_torque_cp
|
||||
@@ -75,6 +76,8 @@ class HKGVehicleTorquePolicy(HKGShapedTorquePolicy):
|
||||
self.steering_pressed = False
|
||||
self.hev_center_weight = 0.0
|
||||
super().__init__(parent, cp)
|
||||
hda1_camera = self.profile == 'ioniq_5' and bool(cp.flags & HyundaiFlags.CANFD_CAMERA_SCC) and not self.ioniq_5_hda2
|
||||
self.ioniq_5_hda1_ff = FirstOrderFilter(0.0, 0.20, self.dt, initialized=False) if hda1_camera else None
|
||||
|
||||
supported_cp = staticmethod(lambda cp: policy_for(cp) is not None)
|
||||
|
||||
@@ -82,10 +85,19 @@ class HKGVehicleTorquePolicy(HKGShapedTorquePolicy):
|
||||
self.requested_curvature = curvature
|
||||
self.future_lateral_accel = curvature * cs.vEgo ** 2
|
||||
self.steering_pressed = bool(cs.steeringPressed)
|
||||
if self.ioniq_5_hda1_ff is not None:
|
||||
if not active or self.steering_pressed or self.previous_pressed or cs.vEgo <= 12.0:
|
||||
self.ioniq_5_hda1_ff.initialized = False
|
||||
if active:
|
||||
self.ioniq_5_hda1_ff.update(self.future_lateral_accel)
|
||||
return super().update(active, cs, vm, params, safety_limited, curvature, curvature_limited, delay)
|
||||
|
||||
def feedforward_context(self, value, setpoint, jerk, measurement, speed):
|
||||
if self.profile == 'ioniq_5':
|
||||
if self.ioniq_5_hda1_ff is not None and speed > 12.0:
|
||||
weight = min((speed - 12.0) / 4.0, 1.0)
|
||||
correction = float(np.clip(self.ioniq_5_hda1_ff.x - self.future_lateral_accel, -0.24, 0.24))
|
||||
value += weight * correction
|
||||
ff_scale = shaping.get_ioniq_5_ff_scale(setpoint, jerk, speed)
|
||||
if (self.ioniq_5_hda2 and 17.0 < speed < 23.0 and 1.25 < abs(setpoint) < 2.65
|
||||
and jerk != 0.0 and not (self.steering_pressed or self.previous_pressed)):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import numpy as np
|
||||
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.starpilot.lateral import palisade_shaping as shaping
|
||||
from openpilot.starpilot.lateral.hkg_torque_policy import HKGShapedTorquePolicy, supported_torque_cp
|
||||
|
||||
@@ -20,14 +21,38 @@ class PalisadeTorquePolicy(HKGShapedTorquePolicy):
|
||||
super().__init__(parent, cp)
|
||||
self.hda2 = cp.carFingerprint == CAR.HYUNDAI_PALISADE_2023 and bool(cp.flags & HyundaiFlags.CANFD_LKA_STEER_MSG)
|
||||
self.center_output_taper = 0.27 if self.hda2 else shaping.PALISADE_CENTER_OUTPUT_TAPER_MAX
|
||||
self.feedforward_demand = 0.0
|
||||
self.feedforward_filter = FirstOrderFilter(0.0, 0.27, self.dt, initialized=False) if self.hda2 else None
|
||||
|
||||
def update(self, active, cs, vm, params, safety_limited, curvature, curvature_limited, delay):
|
||||
if self.feedforward_filter is not None:
|
||||
if not active or cs.steeringPressed or self.previous_pressed or cs.vEgo <= 10.5:
|
||||
self.feedforward_filter.initialized = False
|
||||
self.feedforward_demand = curvature * cs.vEgo**2
|
||||
if active:
|
||||
self.feedforward_filter.update(self.feedforward_demand)
|
||||
return super().update(active, cs, vm, params, safety_limited, curvature, curvature_limited, delay)
|
||||
|
||||
def feedforward(self, value, setpoint, jerk, speed):
|
||||
if self.feedforward_filter is not None and speed > 10.5:
|
||||
weight = min(max((speed - 15.0) / 7.0, 0.0), 1.0)
|
||||
if speed < 22.0:
|
||||
mid_speed = min((speed - 10.5) / 5.5, 1.0)
|
||||
shallow = min(max((1.25 - abs(self.feedforward_demand)) / 0.7, 0.0), 1.0)
|
||||
transient = min(abs(jerk) / 0.35, 1.0)
|
||||
weight = max(weight, mid_speed * shallow * transient)
|
||||
correction = max(-0.28, min(self.feedforward_filter.x - self.feedforward_demand, 0.28))
|
||||
value += weight * correction
|
||||
return value * shaping.get_palisade_ff_scale(setpoint, jerk, speed) * shaping.get_palisade_center_taper_scale(setpoint, speed)
|
||||
|
||||
def friction(self, setpoint, jerk, speed):
|
||||
taper = shaping.get_palisade_center_taper_scale(setpoint, speed)
|
||||
return (shaping.get_palisade_friction_threshold(speed, setpoint, jerk),
|
||||
1.0 + (shaping.get_palisade_friction_scale(speed, setpoint, jerk) - 1.0) * taper)
|
||||
threshold = shaping.get_palisade_friction_threshold(speed, setpoint, jerk)
|
||||
if self.hda2 and speed > 24. and abs(setpoint) < 1.0 and not self.previous_pressed:
|
||||
highway = float(np.interp(speed, (24., 29.), (0., 1.)))
|
||||
shallow = float(np.interp(abs(setpoint), (.25, 1.0), (1., 0.)))
|
||||
threshold += .20 * highway * shallow
|
||||
return threshold, 1.0 + (shaping.get_palisade_friction_scale(speed, setpoint, jerk) - 1.0) * taper
|
||||
|
||||
def output(self, value, setpoint, speed):
|
||||
return value * shaping.get_palisade_center_output_scale(setpoint, speed, taper_max=self.center_output_taper)
|
||||
|
||||
@@ -182,3 +182,41 @@ def test_ioniq5_hda2_tight_curve_feedforward(op_long, direction, hda2, speed, ac
|
||||
steady = shaping.get_ioniq_5_ff_scale(setpoint, 0.0, speed)
|
||||
expected = (original + blend * (steady - original)) * shaping.get_ioniq_5_center_taper_scale(setpoint, speed)
|
||||
assert policy.feedforward_context(1.0, setpoint, jerk, setpoint, speed) == pytest.approx(expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('op_long', [False, True])
|
||||
@pytest.mark.parametrize('hda2', [False, True])
|
||||
def test_ioniq5_hda1_feedforward_damps_transients_and_reseeds_on_override(op_long, hda2):
|
||||
vehicle = CAR.HYUNDAI_IONIQ_5
|
||||
cp = interfaces[vehicle].get_non_essential_params(vehicle)
|
||||
cp.openpilotLongitudinalControl = op_long
|
||||
cp.pcmCruise = not op_long
|
||||
if hda2:
|
||||
cp.flags |= int(HyundaiFlags.CANFD_LKA_STEER_MSG)
|
||||
cp.flags &= ~int(HyundaiFlags.CANFD_CAMERA_SCC)
|
||||
else:
|
||||
cp.flags &= ~int(HyundaiFlags.CANFD_LKA_STEER_MSG)
|
||||
cp.flags |= int(HyundaiFlags.CANFD_CAMERA_SCC)
|
||||
controller = LatControlTorque(cp.as_reader(), interfaces[vehicle](cp), 0.01, controller_mode=ControllerMode.STARPILOT)
|
||||
policy = controller.starpilot_extension.policy
|
||||
vm = VehicleModel(cp)
|
||||
params = SimpleNamespace(angleOffsetDeg=0., roll=0.)
|
||||
state = SimpleNamespace(vEgo=30., steeringAngleDeg=0., steeringPressed=False)
|
||||
original = shaping.get_ioniq_5_ff_scale(.5, 0., 30.) * shaping.get_ioniq_5_center_taper_scale(.5, 30.)
|
||||
|
||||
def tick(target, active=True):
|
||||
controller.update(active, state, vm, params, False, target / state.vEgo**2, False, .37)
|
||||
return policy.feedforward_context(1.0, .5, 0., .5, state.vEgo) / original
|
||||
|
||||
assert tick(0.) == pytest.approx(1.)
|
||||
assert tick(.1) == pytest.approx(1. if hda2 else 1. - .1 * .20 / .21)
|
||||
assert tick(.5) == pytest.approx(1. if hda2 else .76)
|
||||
for _ in range(180):
|
||||
steady = tick(.5)
|
||||
assert steady == pytest.approx(1.0, abs=.0001)
|
||||
state.steeringPressed = True
|
||||
assert tick(-.5) == pytest.approx(1.)
|
||||
state.steeringPressed = False
|
||||
assert tick(.5) == pytest.approx(1.)
|
||||
tick(.5, active=False)
|
||||
assert tick(-.5) == pytest.approx(1.)
|
||||
|
||||
@@ -111,3 +111,73 @@ def test_hda2_softens_rapid_highway_corrections_across_longitudinal_modes(alpha,
|
||||
assert policy.output_context(value, demand, .2, 0., 31.) == baseline
|
||||
assert policy.output_context(value, direction, jerk, 0., 31.) == policy.output(value, direction, 31.)
|
||||
assert policy.output_context(value, demand, jerk, 0., 20.) == policy.output(value, demand, 20.)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
def test_hda2_softens_shallow_highway_friction_in_both_longitudinal_modes(alpha):
|
||||
cp = topology_params('hdaii')
|
||||
cp.openpilotLongitudinalControl, cp.pcmCruise = alpha, not alpha
|
||||
policy = LatControlTorque(cp.as_reader(), interfaces[cp.carFingerprint](cp), .01).starpilot_extension.policy
|
||||
baseline = shaping.get_palisade_friction_threshold(30., .4, 1.1)
|
||||
assert policy.friction(.4, 1.1, 30.)[0] == pytest.approx(baseline + .16)
|
||||
for speed, setpoint in ((4., .4), (30., 1.0), (24., -.4)):
|
||||
assert policy.friction(setpoint, 1.1, speed)[0] == shaping.get_palisade_friction_threshold(speed, setpoint, 1.1)
|
||||
|
||||
policy.previous_pressed = True
|
||||
assert policy.friction(.4, 1.1, 30.)[0] == baseline
|
||||
hda1_cp = topology_params('hdai')
|
||||
hda1 = LatControlTorque(hda1_cp.as_reader(), interfaces[hda1_cp.carFingerprint](hda1_cp), .01).starpilot_extension.policy
|
||||
assert hda1.friction(.4, 1.1, 30.)[0] == baseline
|
||||
|
||||
|
||||
@pytest.mark.parametrize('topology,alpha,expected', [('hdai', False, 1.0), ('hdaii', False, .72), ('hdaii', True, .72)])
|
||||
def test_exit_feedforward_damps_hda2_and_reseeds_after_driver_override(topology, alpha, expected):
|
||||
cp = topology_params(topology)
|
||||
cp.openpilotLongitudinalControl, cp.pcmCruise = alpha, not alpha
|
||||
controller = LatControlTorque(cp.as_reader(), interfaces[cp.carFingerprint](cp), .01)
|
||||
policy = controller.starpilot_extension.policy
|
||||
vm = VehicleModel(cp)
|
||||
parameters = SimpleNamespace(angleOffsetDeg=0., roll=0.)
|
||||
state = SimpleNamespace(vEgo=29., steeringAngleDeg=0., steeringPressed=False)
|
||||
|
||||
def tick(target, active=True):
|
||||
controller.update(active, state, vm, parameters, False, target / state.vEgo**2, False, .22)
|
||||
original = shaping.get_palisade_ff_scale(.5, 0., state.vEgo) * shaping.get_palisade_center_taper_scale(.5, state.vEgo)
|
||||
return policy.feedforward(1.0, .5, 0., state.vEgo) / original
|
||||
|
||||
assert tick(0.) == pytest.approx(1.)
|
||||
assert tick(.8) == pytest.approx(expected)
|
||||
for _ in range(250):
|
||||
steady = tick(.8)
|
||||
assert steady == pytest.approx(1., abs=.0001)
|
||||
state.steeringPressed = True
|
||||
assert tick(-.8) == pytest.approx(1.)
|
||||
state.steeringPressed = False
|
||||
assert tick(.8) == pytest.approx(1.)
|
||||
tick(.8, active=False)
|
||||
assert tick(-.8) == pytest.approx(1.)
|
||||
state.vEgo = 14.0
|
||||
assert tick(.8) == pytest.approx(1.)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
def test_palisade_damps_shallow_mid_speed_corrections_without_softening_deeper_turns(alpha):
|
||||
cp = topology_params('hdaii')
|
||||
cp.openpilotLongitudinalControl, cp.pcmCruise = alpha, not alpha
|
||||
controller = LatControlTorque(cp.as_reader(), interfaces[cp.carFingerprint](cp), .01)
|
||||
policy = controller.starpilot_extension.policy
|
||||
vm = VehicleModel(cp)
|
||||
parameters = SimpleNamespace(angleOffsetDeg=0., roll=0.)
|
||||
state = SimpleNamespace(vEgo=14., steeringAngleDeg=0., steeringPressed=False)
|
||||
setpoint, jerk = .4, .5
|
||||
raw = shaping.get_palisade_ff_scale(setpoint, jerk, state.vEgo) * shaping.get_palisade_center_taper_scale(setpoint, state.vEgo)
|
||||
|
||||
def tick(target):
|
||||
controller.update(True, state, vm, parameters, False, target / state.vEgo**2, False, .22)
|
||||
return policy.feedforward(1.0, setpoint, jerk, state.vEgo) / raw
|
||||
|
||||
assert tick(0.) == pytest.approx(1.0)
|
||||
assert tick(.4) == pytest.approx(1.0 - .28 * 3.5 / 5.5)
|
||||
assert tick(1.3) == pytest.approx(1.0)
|
||||
state.steeringPressed = True
|
||||
assert tick(.4) == pytest.approx(1.0)
|
||||
|
||||
@@ -67,7 +67,7 @@ def test_corolla_resume_evidence_requires_current_car_and_plan(monkeypatch):
|
||||
inputs.resume_freshness = ResumeFreshness()
|
||||
inputs.ev9_long_enabled = inputs.toyota_sienna_replay = inputs.toyota_sienna_production = False
|
||||
inputs.toyota_corolla_stop = True
|
||||
inputs._toyota_leads = lambda: (MOVING_LEAD,)
|
||||
monkeypatch.setattr(inputs, "_toyota_leads", lambda: (MOVING_LEAD,))
|
||||
publish()
|
||||
assert not inputs._vehicle_context(True).toyota_resume_fresh
|
||||
now[0] += 20_000_000
|
||||
|
||||
@@ -14,15 +14,59 @@ class TestTeslaManualSpeedStep(unittest.TestCase):
|
||||
cp.openpilotLongitudinalControl = True
|
||||
return LongitudinalPlanner(cp, init_v=V_EGO)
|
||||
|
||||
def update(self, planner, frame, cruise_kph, *, gas=False, lead=False, force=False):
|
||||
def update(self, planner, frame, cruise_kph, *, gas=False, lead=False, force=False, accel=0.0, brake=False, off=False):
|
||||
sm, _ = messages(lead=lead, force=force)
|
||||
sm['carState'].vCruise = cruise_kph
|
||||
sm['carState'].canValid = True
|
||||
sm['carState'].gasPressed = gas
|
||||
sm['carControl'].longActive = not gas
|
||||
sm['carState'].brakePressed = brake
|
||||
sm['carState'].aEgo = accel
|
||||
sm['carState'].cruiseState.enabled = True
|
||||
if gas or off:
|
||||
sm['controlsState'].longControlState = 'off'
|
||||
sm['carControl'].longActive = not (gas or off)
|
||||
idle_coast = Mock(sample=Mock(return_value=CoastPlan()))
|
||||
planner.update(sm, now_ns=1_000_000_000 + frame * 50_000_000, wheel_coast=(idle_coast, None))
|
||||
|
||||
def test_pedal_handoff_previews_only_eligible_cruise_acceleration(self):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 95, gas=True, accel=0.10)
|
||||
preview = float(planner.output_a_target)
|
||||
self.assertGreater(preview, 0.30)
|
||||
self.assertLess(preview, 0.42)
|
||||
self.update(planner, 1, 95, accel=0.10)
|
||||
self.assertGreaterEqual(planner.output_a_target, preview)
|
||||
|
||||
for context in ({'lead': True}, {'force': True}, {'brake': True}):
|
||||
with self.subTest(context=context):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 95, gas=True, accel=0.10, **context)
|
||||
self.assertLess(planner.output_a_target, 0.20)
|
||||
|
||||
def test_pedal_handoff_preserves_preview_through_near_zero_coast(self):
|
||||
for measured_accel, preview_min, preview_max in ((-0.02, 0.17, 0.26), (-0.09, 0.04, 0.12), (-0.30, -0.30, -0.20)):
|
||||
with self.subTest(measured_accel=measured_accel):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 95, gas=True, accel=measured_accel)
|
||||
preview = float(planner.output_a_target)
|
||||
self.assertGreater(preview, preview_min)
|
||||
self.assertLess(preview, preview_max)
|
||||
|
||||
def test_pedal_handoff_bridges_one_inactive_frame(self):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 95, gas=True, accel=-0.02)
|
||||
self.update(planner, 1, 95, off=True, accel=-0.02)
|
||||
self.assertGreater(planner.output_a_target, 0.17)
|
||||
self.update(planner, 2, 95, off=True, accel=-0.02)
|
||||
self.assertLess(planner.output_a_target, 0.05)
|
||||
|
||||
for frame, blocker in ((1, {'lead': True}), (1, {'brake': True}), (3, {})):
|
||||
with self.subTest(frame=frame, blocker=blocker):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 95, gas=True, accel=-0.02)
|
||||
self.update(planner, frame, 95, off=True, accel=-0.02, **blocker)
|
||||
self.assertLess(planner.output_a_target, 0.05)
|
||||
|
||||
def test_manual_up_and_down(self):
|
||||
for speed in (65, 79):
|
||||
with self.subTest(speed=speed):
|
||||
@@ -32,8 +76,16 @@ class TestTeslaManualSpeedStep(unittest.TestCase):
|
||||
previous = planner.a_cruise
|
||||
self.update(planner, 20, speed)
|
||||
self.assertGreater(abs(planner.a_cruise - previous), 0.0)
|
||||
self.assertLessEqual(abs(planner.a_cruise - previous), 0.023)
|
||||
self.assertLessEqual(abs(planner.output_a_target - previous), 0.023)
|
||||
self.assertLessEqual(abs(planner.a_cruise - previous), 0.013)
|
||||
self.assertLessEqual(abs(planner.output_a_target - previous), 0.013)
|
||||
|
||||
def test_small_positive_accel_eases_into_manual_slowdown(self):
|
||||
planner = self.setup_planner()
|
||||
self.update(planner, 0, 72)
|
||||
planner.a_cruise = planner.output_a_target = 0.08
|
||||
self.update(planner, 1, 65)
|
||||
self.assertAlmostEqual(planner.output_a_target, 0.0675)
|
||||
self.assertGreater(planner.manual_cruise_step_until_ns, 4_000_000_000)
|
||||
|
||||
def test_pedal_lead_and_forced_decel_cancel_ramp(self):
|
||||
for blocker in ('gas', 'lead', 'force'):
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Capture the camera evidence for a parked motion event."""
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import SnapshotDenied, SnapshotUnavailable
|
||||
|
||||
|
||||
def record_motion_event(store, camera, kind, stamp, permitted, *, simulated=False):
|
||||
try:
|
||||
results = camera.capture_many(("wide", "cabin"), permitted=permitted, parked=True)
|
||||
except SnapshotDenied:
|
||||
raise
|
||||
except SnapshotUnavailable:
|
||||
results = {}
|
||||
images = {name: body for name, body in results.items() if isinstance(body, bytes)}
|
||||
return store.record(kind, stamp, permitted=permitted, images=images, simulated=simulated)
|
||||
@@ -31,6 +31,8 @@ APP_IDS = ('com.starpilot.galaxy', 'link.firestar.companion', 'link.galaxy.bluet
|
||||
MAX_STATE_BYTES = 1024 * 1024
|
||||
MAX_JOBS = 512
|
||||
MAX_AGE = 86400
|
||||
TEST_PHOTO_AGE = 900
|
||||
MAX_TEST_PHOTOS = 4
|
||||
MAX_ATTEMPTS = 4
|
||||
RETRY_SECONDS = (30, 120, 600, 600)
|
||||
ID = re.compile(r'[0-9a-f]{32}\Z')
|
||||
@@ -83,6 +85,7 @@ class NotificationOwner:
|
||||
self.stop = threading.Event()
|
||||
self.thread = None
|
||||
self.state = fresh_state()
|
||||
self.test_photos: dict[str, tuple[float, bytes]] = {}
|
||||
self.available = True
|
||||
self.lock_fd = None
|
||||
self.saved_bytes = None
|
||||
@@ -430,6 +433,47 @@ class NotificationOwner:
|
||||
self._save()
|
||||
return self.snapshot()
|
||||
|
||||
def photo_test(self, target_id: str, camera: str, jpeg: bytes, *, permitted) -> None:
|
||||
if not isinstance(target_id, str) or re.fullmatch(r'[0-9a-f]{12}', target_id) is None or camera not in ('wide', 'cabin'):
|
||||
raise ValueError('Choose a phone and camera')
|
||||
if not isinstance(jpeg, bytes) or not 4 <= len(jpeg) <= 1_000_000 or not jpeg.startswith(b'\xff\xd8\xff'):
|
||||
raise NotificationUnavailable('No fresh camera image')
|
||||
with self.lock:
|
||||
if not self.available:
|
||||
raise NotificationUnavailable('Notification storage is unavailable')
|
||||
if not permitted():
|
||||
raise PermissionError('A current parked Galaxy session is required')
|
||||
if not any(sub['id'] == target_id for sub in self.state['appSubscriptions']):
|
||||
raise LookupError('Phone subscription not found')
|
||||
if not self.state['channels']['appPush']['enabled'] or len(self.state['jobs']) >= MAX_JOBS:
|
||||
raise NotificationUnavailable('Phone push is unavailable or its queue is full')
|
||||
now = self.clock()
|
||||
if sum(job['kind'] == 'test' and job['created'] > now - 60 for job in self.state['jobs'].values()) >= 4:
|
||||
raise ValueError('Wait a minute before sending more tests')
|
||||
event_id = uuid.uuid4().hex
|
||||
self._enqueue({'eventId': event_id, 'kind': 'test', 'wallTimeNs': int(now * 1e9)},
|
||||
only='appPush', target_id=target_id)
|
||||
try:
|
||||
if not permitted():
|
||||
raise PermissionError('Galaxy session or parked state changed')
|
||||
self._save()
|
||||
except (PermissionError, NotificationUnavailable, OSError):
|
||||
self.state['jobs'] = {key: job for key, job in self.state['jobs'].items() if job['eventId'] != event_id}
|
||||
raise
|
||||
self._expire_test_photos(now)
|
||||
if len(self.test_photos) >= MAX_TEST_PHOTOS:
|
||||
del self.test_photos[next(iter(self.test_photos))]
|
||||
self.test_photos[event_id] = (now + TEST_PHOTO_AGE, jpeg)
|
||||
|
||||
def _expire_test_photos(self, now):
|
||||
self.test_photos = {event: photo for event, photo in self.test_photos.items() if photo[0] > now}
|
||||
|
||||
def test_image(self, event_id: str) -> bytes | None:
|
||||
with self.lock:
|
||||
self._expire_test_photos(self.clock())
|
||||
photo = self.test_photos.get(event_id)
|
||||
return photo[1] if photo else None
|
||||
|
||||
def _enqueue(self, event: dict, *, only: str | None = None, target_id: str | None = None) -> None:
|
||||
if event['kind'] == 'selfie':
|
||||
return
|
||||
@@ -473,6 +517,9 @@ class NotificationOwner:
|
||||
return remove()
|
||||
|
||||
def tick(self) -> None:
|
||||
with self.lock:
|
||||
if self.test_photos:
|
||||
self._expire_test_photos(self.clock())
|
||||
with self.lock:
|
||||
if not self.available:
|
||||
return
|
||||
|
||||
@@ -241,17 +241,11 @@ def main() -> None:
|
||||
messages = messaging.SubMaster(["accelerometer", "deviceState", "pandaStates", "peripheralState"])
|
||||
store = EventStore()
|
||||
from openpilot.starpilot.galaxy.camera_request import request as prewarm_camera
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import CameraSnapshot, SnapshotDenied, SnapshotUnavailable
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import CameraSnapshot
|
||||
from openpilot.starpilot.sentry_mode.capture import record_motion_event
|
||||
camera = CameraSnapshot()
|
||||
def record(kind, stamp, permitted):
|
||||
try:
|
||||
results = camera.capture_many(("wide", "cabin"), permitted=permitted, parked=True)
|
||||
except SnapshotDenied:
|
||||
raise
|
||||
except SnapshotUnavailable:
|
||||
results = {}
|
||||
images = {name: body for name, body in results.items() if isinstance(body, bytes)}
|
||||
return store.record(kind, stamp, permitted=permitted, images=images)
|
||||
return record_motion_event(store, camera, kind, stamp, permitted)
|
||||
def battery(voltage, cutoff):
|
||||
if recent_battery_warning(store.snapshot()["events"], time.time_ns()):
|
||||
return
|
||||
|
||||
@@ -279,6 +279,7 @@ class EventStore:
|
||||
if not _valid(value, event_id):
|
||||
raise ValueError("Invalid event metadata")
|
||||
if value.get('simulated') and time.time_ns() - value['wallTimeNs'] > 600_000_000_000:
|
||||
remove_entry(directory, event_id, [16])
|
||||
os.unlink(entry.name, dir_fd=directory)
|
||||
continue
|
||||
result["events"].append(value)
|
||||
|
||||
@@ -148,9 +148,10 @@ def test_simulated_events_expire_without_removing_real_events(tmp_path, monkeypa
|
||||
store = EventStore(tmp_path / 'events')
|
||||
clock = [1000000000000]
|
||||
monkeypatch.setattr(time, 'time_ns', lambda: clock[0])
|
||||
fake = store.record('warning', 1, permitted=lambda: True, simulated=True)
|
||||
fake = store.record('warning', 1, permitted=lambda: True, simulated=True, images={'wide': b'\xff\xd8\xff\xd9'})
|
||||
real = store.record('warning', 2, permitted=lambda: True)
|
||||
assert len(store.snapshot()['events']) == 2
|
||||
clock[0] += 601000000000
|
||||
assert [event['eventId'] for event in store.snapshot()['events']] == [real.event_id]
|
||||
assert not (store.root / (fake.event_id + '.json')).exists()
|
||||
assert not (store.root / fake.event_id).exists()
|
||||
|
||||
@@ -24,6 +24,7 @@ detected by the sequence number and retried by the consumer.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import mmap
|
||||
import os
|
||||
import struct
|
||||
@@ -101,6 +102,42 @@ class Frame:
|
||||
pixel_format: int = FORMAT_RGBA
|
||||
|
||||
|
||||
LUMA_STEP = 16
|
||||
|
||||
|
||||
def luma_summary(frame: Frame, left: int, top: int, width: int, height: int) -> dict:
|
||||
"""Brightness of a sparse grid inside one rectangle of the frame: mean, spread and the share of near-black samples."""
|
||||
left, top = max(0, left), max(0, top)
|
||||
right, bottom = min(frame.width, left + width), min(frame.height, top + height)
|
||||
nv12 = frame.pixel_format == FORMAT_NV12
|
||||
bpp, channel, black = (1, 0, 24) if nv12 else (4, 1, 16) # NV12 black is Y=16; RGBA uses green as a luma stand-in
|
||||
samples = bytearray()
|
||||
for y in range(top, bottom, LUMA_STEP):
|
||||
row = y * frame.width * bpp
|
||||
samples += frame.data[row + left * bpp + channel:row + right * bpp:LUMA_STEP * bpp]
|
||||
if not samples:
|
||||
return {}
|
||||
count = len(samples)
|
||||
mean = sum(samples) / count
|
||||
spread = math.sqrt(max(0.0, sum(value * value for value in samples) / count - mean * mean))
|
||||
dark = sum(1 for value in samples if value <= black)
|
||||
return {"mean": round(mean, 1), "std": round(spread, 1), "dark_pct": round(100 * dark / count, 1), "samples": count}
|
||||
|
||||
|
||||
def frame_brightness(frame, mode) -> dict:
|
||||
"""Brightness of the last sent frame inside the area the car shows, and across the whole frame, for the stats log."""
|
||||
if frame is None or mode is None or not mode.width or not mode.height:
|
||||
return {}
|
||||
sx, sy = frame.width / mode.width, frame.height / mode.height
|
||||
margin_w, margin_h = mode.margin_width or 0, mode.margin_height or 0
|
||||
left = mode.content_left if mode.content_left is not None else margin_w // 2
|
||||
top = mode.content_top if mode.content_top is not None else margin_h - margin_h // 2
|
||||
visible = luma_summary(frame, round(left * sx), round(top * sy), round((mode.width - margin_w) * sx),
|
||||
round((mode.height - margin_h) * sy))
|
||||
whole = luma_summary(frame, 0, 0, frame.width, frame.height)
|
||||
return {"luma_visible": visible, "luma_frame": whole} if visible else {}
|
||||
|
||||
|
||||
def fit_content(source_w: int, source_h: int, width: int, height: int, margin_w: int, margin_h: int) -> tuple[int, int, int, int]:
|
||||
"""Largest undistorted rectangle for the source inside the receiver's visible area.
|
||||
|
||||
|
||||
@@ -184,12 +184,13 @@ def projection_appearance(appearance, document):
|
||||
def comma_display(appearance):
|
||||
"""The comma screen's display choices as AA switches, to start a car screen that has no saved layout."""
|
||||
lead_indicator = appearance.show_lead_indicator is True
|
||||
lead_mode = min(int(appearance.lead_info_mode), len(LEAD_INFO_CHOICES) - 1)
|
||||
return {'blindSpotBorder': appearance.show_blindspot_border is True,
|
||||
'signalBorder': appearance.show_signal_border is True,
|
||||
'hidePersonalityAlerts': appearance.hide_personality_alerts is True,
|
||||
'wheelPedalFeedback': appearance.wheel_pedal_feedback is True,
|
||||
'leadIndicator': lead_indicator,
|
||||
'leadInfo': LEAD_INFO_CHOICES[appearance.lead_info_mode] if lead_indicator else 'Off'}
|
||||
'leadInfo': LEAD_INFO_CHOICES[lead_mode] if lead_indicator else 'Off'}
|
||||
|
||||
|
||||
def default_layout(screen, display=None):
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
"""Classify live and logged connection failures to select retry delays."""
|
||||
|
||||
import errno
|
||||
import socket
|
||||
|
||||
ASLEEP = "asleep" # the car did not answer a page at all: off, or still waking
|
||||
NOT_READY = "not_ready" # the car answered, but its Android Auto service or Wi-Fi handshake is not up yet
|
||||
LOCAL = "local" # this comma's own Bluetooth stack refused or was busy; the car says nothing
|
||||
@@ -53,3 +56,27 @@ def retry_delay(reach: str, attempt: int, standard: float) -> float:
|
||||
def keeps_cached_channel(reach: str) -> bool:
|
||||
"""A sleeping car says nothing about which RFCOMM channel is right, so its cached channel is kept."""
|
||||
return reach in (ASLEEP, LOCAL)
|
||||
|
||||
|
||||
def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket:
|
||||
error: OSError | None = None
|
||||
for port in ports:
|
||||
try:
|
||||
sock = socket.create_connection((ip, port), timeout=5.0, source_address=(local_ip, 0) if local_ip else None)
|
||||
except OSError as failure:
|
||||
error = error or failure # the first port's failure decides how patiently to retry
|
||||
continue
|
||||
if port != advertised:
|
||||
log("tcp_port_fallback", advertised=advertised, port=port)
|
||||
return sock
|
||||
assert error is not None
|
||||
raise error
|
||||
|
||||
def _tcp_failure_kind(error: OSError) -> str:
|
||||
if isinstance(error, (TimeoutError, socket.timeout)):
|
||||
return "timeout"
|
||||
if isinstance(error, ConnectionRefusedError):
|
||||
return "refused"
|
||||
if getattr(error, "errno", None) in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN):
|
||||
return "unreachable"
|
||||
return "other"
|
||||
|
||||
@@ -244,6 +244,19 @@ def describe_video_config(config: dict, display_type: int | None = None) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def ui_config_insets(fields: dict) -> dict:
|
||||
"""The margins a head unit asks for in a UI config request: {top, bottom, left, right} in video pixels, or {}."""
|
||||
try:
|
||||
config = parse_fields(one(fields, 1, b""))
|
||||
insets = parse_fields(one(config, 1, b""))
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
if not insets:
|
||||
return {}
|
||||
return {name: int(one(insets, number, 0)) for number, name in ((1, "top"), (2, "bottom"), (3, "left"), (4, "right"))
|
||||
if isinstance(one(insets, number, 0), int)}
|
||||
|
||||
|
||||
def describe_video_configs(channels: list[dict]) -> str:
|
||||
"""What the head unit offered, for an error a person can act on."""
|
||||
offered = [describe_video_config(config, channel.get("display_type"))
|
||||
@@ -752,6 +765,8 @@ class ProjectionSession(Session):
|
||||
self.connect_handsfree: Callable[[str], str] | None = None
|
||||
self.focus_requested_at: float | None = None
|
||||
self.focus_granted_at: float | None = None
|
||||
self.focus_changed_at: float | None = None
|
||||
self.last_ui_config = b""
|
||||
self.nav = None # NavStatus, attached by the supervisor when the head unit offers turn-by-turn
|
||||
self.audio = None # MediaAudio, attached by the supervisor when Spotify plays through Android Auto
|
||||
self.input_events = 0
|
||||
@@ -1001,9 +1016,14 @@ class ProjectionSession(Session):
|
||||
if self.keyframe_test_active() and self.test_acks_logged < TEST_ACKS_LOGGED:
|
||||
self.test_acks_logged += 1
|
||||
self.event("video_ack", session=one(fields, 1), count=int(one(fields, 2, 0) or 0), pending=len(self.pending))
|
||||
elif kind == VIDEO_UI_CONFIG_REQUEST and mode.codec == CODEC_H265:
|
||||
self.send(channel, VIDEO_UI_CONFIG_REPLY, data)
|
||||
self.event("ui_config_replied", channel=channel, bytes=len(data))
|
||||
elif kind == VIDEO_UI_CONFIG_REQUEST:
|
||||
if data != self.last_ui_config:
|
||||
self.last_ui_config = data
|
||||
self.event("ui_config_request", channel=channel, insets=ui_config_insets(fields), message=describe(data),
|
||||
replied=mode.codec == CODEC_H265)
|
||||
if mode.codec == CODEC_H265:
|
||||
self.send(channel, VIDEO_UI_CONFIG_REPLY, data)
|
||||
self.event("ui_config_replied", channel=channel, bytes=len(data))
|
||||
else:
|
||||
self.ignored("video_ignored", channel, kind, data)
|
||||
elif channel == self.input_channel:
|
||||
@@ -1078,7 +1098,11 @@ class ProjectionSession(Session):
|
||||
self.focus_granted_at = time.monotonic()
|
||||
if self.focus_requested_at is not None:
|
||||
wait = {"wait_s": round(self.focus_granted_at - self.focus_requested_at, 2)}
|
||||
self.event("video_focus", focus=focus, unsolicited=unsolicited, focused=self.focused, **wait)
|
||||
now = time.monotonic()
|
||||
since = {"since_last_s": round(now - self.focus_changed_at, 1)} if self.focus_changed_at is not None else {}
|
||||
self.focus_changed_at = now
|
||||
self.event("video_focus", focus=focus, unsolicited=unsolicited, focused=self.focused, was_focused=was_focused,
|
||||
frames_sent=self.frames_sent, frames_acked=self.acked, **since, **wait)
|
||||
if was_focused and not self.focused and self.grace_frame is not None:
|
||||
self.grace_focus_lost = True # the car gave up on the stalled video: reconnect rather than wait unfocused
|
||||
if was_focused and not self.focused and self.touch is not None:
|
||||
|
||||
@@ -26,8 +26,9 @@ from openpilot.starpilot.system.starport.bootstrap import MODERN_MAJOR, NAMES, B
|
||||
from openpilot.starpilot.system.starport.bugsink_report import PairingAttempt
|
||||
from openpilot.starpilot.system.starport.event_log import EventLog
|
||||
from openpilot.starpilot.system.starport.frame_source import (DEFAULT_PATH as DEFAULT_FRAME_PATH, FLAG_ASYNC_READBACK, FLAG_NV12,
|
||||
FORMAT_NV12, FrameRequest)
|
||||
FORMAT_NV12, FrameRequest, frame_brightness)
|
||||
from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS
|
||||
from openpilot.starpilot.system.starport.reachability import _open_projection, _tcp_failure_kind
|
||||
from openpilot.starpilot.system.starport.radio_watch import (RADIO_CHANGE_WINDOW as RADIO_CHANGE_WINDOW,
|
||||
RADIO_CHECK_INTERVAL as RADIO_CHECK_INTERVAL, SharedRadioWatch)
|
||||
from openpilot.starpilot.system.starport.touch import DEFAULT_TOUCH_SOCKET, TouchEvent
|
||||
@@ -71,31 +72,6 @@ REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrat
|
||||
"unacked_video", "patient_tcp", "wired_handsfree", "head_unit_experiments", "head_unit_experiment_rules")
|
||||
|
||||
|
||||
def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket:
|
||||
error: OSError | None = None
|
||||
for port in ports:
|
||||
try:
|
||||
sock = socket.create_connection((ip, port), timeout=5.0, source_address=(local_ip, 0) if local_ip else None)
|
||||
except OSError as failure:
|
||||
error = error or failure # the first port's failure decides how patiently to retry
|
||||
continue
|
||||
if port != advertised:
|
||||
log("tcp_port_fallback", advertised=advertised, port=port)
|
||||
return sock
|
||||
assert error is not None
|
||||
raise error
|
||||
|
||||
|
||||
def _tcp_failure_kind(error: OSError) -> str:
|
||||
if isinstance(error, (TimeoutError, socket.timeout)):
|
||||
return "timeout"
|
||||
if isinstance(error, ConnectionRefusedError):
|
||||
return "refused"
|
||||
if getattr(error, "errno", None) in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN):
|
||||
return "unreachable"
|
||||
return "other"
|
||||
|
||||
|
||||
HANDSFREE_UUID = "0000111e-0000-1000-8000-00805f9b34fb"
|
||||
REFUSED_CAR_HINT_S = 120.0
|
||||
|
||||
@@ -2229,6 +2205,8 @@ class Supervisor:
|
||||
unavailable: dict[str, bytes] = {}
|
||||
recoveries: list[float] = [] # when the hardware encoder was reopened, this session
|
||||
encode_peak = 0.0
|
||||
sizes = {"bytes": 0, "frames": 0, "max": 0, "keyframe": 0} # encoded sizes over each logged 30 s window
|
||||
last_frame = None
|
||||
wait_for_frame = False
|
||||
audio = getattr(session, "audio", None)
|
||||
nav = getattr(session, "nav", None)
|
||||
@@ -2295,6 +2273,12 @@ class Supervisor:
|
||||
data, keyframe = encoded
|
||||
encode_peak = max(encode_peak, encoder.last_encode_ms)
|
||||
session.send_frame(data, frame.captured_ns // 1000, keyframe=keyframe)
|
||||
sizes["bytes"] += len(data)
|
||||
sizes["frames"] += 1
|
||||
sizes["max"] = max(sizes["max"], len(data))
|
||||
if keyframe:
|
||||
sizes["keyframe"] = len(data)
|
||||
last_frame = frame
|
||||
if source.view == "car":
|
||||
source.source.mark_sent(frame.captured_ns)
|
||||
sent_at = time.monotonic()
|
||||
@@ -2330,7 +2314,11 @@ class Supervisor:
|
||||
"uptime_s": round(now - started), "frames_from_view": source.frames, "wifi_dbm": watch.wifi_dbm}
|
||||
self._set(stats=stats)
|
||||
if int(now - started) % 30 == 0:
|
||||
self.log("stats", **{**device_health.sample(getattr(watch.lease, "interface", "wlan0")), **stats})
|
||||
picture = {"frame_bytes_avg": sizes["bytes"] // sizes["frames"] if sizes["frames"] else None,
|
||||
"frame_bytes_max": sizes["max"], "keyframe_bytes": sizes["keyframe"] or None,
|
||||
**frame_brightness(last_frame, session.mode)}
|
||||
self.log("stats", **{**device_health.sample(getattr(watch.lease, "interface", "wlan0")), **stats, **picture})
|
||||
sizes.update(bytes=0, frames=0, max=0)
|
||||
encode_peak = 0.0 # the peak covers each logged 30 s window
|
||||
if audio is not None:
|
||||
audio.reset_peaks()
|
||||
|
||||
@@ -516,3 +516,41 @@ def test_setup_state_export_uses_bounded_regular_file_reads(tmp_path, monkeypatc
|
||||
assert compat_report.shareable_setup_state(link) is None
|
||||
monkeypatch.setattr(compat_report, "MAX_LOG_BYTES", 8)
|
||||
assert compat_report.shareable_setup_state(path) is None
|
||||
|
||||
|
||||
def nv12_frame(width, height, rows):
|
||||
from openpilot.starpilot.system.starport.frame_source import FORMAT_NV12, Frame
|
||||
luma = b"".join(rows(row) for row in range(height))
|
||||
return Frame(luma + bytes([128]) * (width * height // 2), width, height, 1, 1, FORMAT_NV12)
|
||||
|
||||
|
||||
def test_luma_summary_reads_black_and_rgba_green():
|
||||
from openpilot.starpilot.system.starport.frame_source import FORMAT_RGBA, Frame, luma_summary
|
||||
black = luma_summary(nv12_frame(64, 32, lambda _: bytes([16]) * 64), 0, 0, 64, 32)
|
||||
assert black["mean"] == 16 and black["dark_pct"] == 100.0 and black["std"] == 0
|
||||
green = Frame(bytes([0, 200, 0, 255]) * (64 * 32), 64, 32, 1, 1, FORMAT_RGBA)
|
||||
assert luma_summary(green, 0, 0, 64, 32)["mean"] == 200
|
||||
assert luma_summary(green, 100, 100, 64, 32) == {}
|
||||
|
||||
|
||||
def test_frame_brightness_measures_the_area_the_car_shows():
|
||||
from openpilot.starpilot.system.starport.supervisor import frame_brightness
|
||||
frame = nv12_frame(128, 64, lambda _: bytes([200]) * 64 + bytes([16]) * 64) # bright only on the left
|
||||
mode = SimpleNamespace(width=128, height=64, margin_width=64, margin_height=0, content_left=0, content_top=0)
|
||||
result = frame_brightness(frame, mode)
|
||||
assert result["luma_visible"]["mean"] == 200 and result["luma_frame"]["mean"] < 200
|
||||
assert frame_brightness(None, mode) == {}
|
||||
|
||||
|
||||
def test_focus_change_logs_progress_and_time_since_last_change():
|
||||
events = []
|
||||
session = ProjectionSession.__new__(ProjectionSession)
|
||||
session.focused, session.allow_projection, session.media_started = False, False, True
|
||||
session.focus_requested_at = session.focus_granted_at = session.focus_changed_at = session.grace_frame = session.touch = None
|
||||
session.frames_sent, session.acked = 12, 10
|
||||
session._log = lambda name, **values: events.append((name, values))
|
||||
session._handle_focus(2, 1)
|
||||
session._handle_focus(2, 1)
|
||||
first, second = events[0][1], events[1][1]
|
||||
assert first["frames_sent"] == 12 and first["frames_acked"] == 10 and first["was_focused"] is False
|
||||
assert "since_last_s" not in first and second["since_last_s"] >= 0
|
||||
|
||||
@@ -136,6 +136,7 @@ def video_session(codec):
|
||||
session.audio = session.nav = None
|
||||
session.mode = VideoMode(1, 2, 720, 1280, 60, 0, 541, codec=codec)
|
||||
session.ignored_counts = {}
|
||||
session.last_ui_config = b""
|
||||
session._log = lambda name, **values: events.append(name)
|
||||
return session, sent, events
|
||||
|
||||
@@ -145,13 +146,29 @@ def test_h265_session_answers_the_ui_config_request_with_the_same_config():
|
||||
body = ui_config_body()
|
||||
session.handle(1, VIDEO_UI_CONFIG_REQUEST, body)
|
||||
assert sent == [(1, VIDEO_UI_CONFIG_REPLY, body)]
|
||||
assert events == ["ui_config_replied"]
|
||||
assert events == ["ui_config_request", "ui_config_replied"]
|
||||
|
||||
|
||||
def test_h264_session_still_ignores_the_ui_config_request():
|
||||
def test_h264_session_logs_but_does_not_answer_the_ui_config_request():
|
||||
session, sent, events = video_session(CODEC_H264_BP)
|
||||
session.handle(1, VIDEO_UI_CONFIG_REQUEST, ui_config_body())
|
||||
assert sent == [] and events == ["video_ignored"]
|
||||
assert sent == [] and events == ["ui_config_request"]
|
||||
|
||||
|
||||
def test_repeated_ui_config_request_is_logged_once():
|
||||
session, _, events = video_session(CODEC_H264_BP)
|
||||
session.handle(1, VIDEO_UI_CONFIG_REQUEST, ui_config_body())
|
||||
session.handle(1, VIDEO_UI_CONFIG_REQUEST, ui_config_body())
|
||||
assert events == ["ui_config_request"]
|
||||
|
||||
|
||||
def test_ui_config_insets_reads_the_margins():
|
||||
from openpilot.starpilot.system.starport.session import field, ui_config_insets
|
||||
from openpilot.starpilot.system.starport.wire import parse_fields
|
||||
insets = field(1, 66) + field(2, 66) + field(3, 0) + field(4, 390)
|
||||
assert ui_config_insets(parse_fields(field(1, field(1, insets)))) == {"top": 66, "bottom": 66, "left": 0, "right": 390}
|
||||
assert ui_config_insets({}) == {}
|
||||
assert ui_config_insets({1: [5]}) == {}
|
||||
|
||||
|
||||
def test_keyframe_summary_reads_tier_and_level_through_emulation_prevention():
|
||||
|
||||
@@ -26,25 +26,30 @@ class LeadInfoMode(IntEnum):
|
||||
OFF = 0
|
||||
DISTANCE = 1
|
||||
SPEED = 2
|
||||
RELATIVE_SPEED = 3
|
||||
|
||||
|
||||
LEAD_INFO_LABELS = ("Off", "Distance", "Speed")
|
||||
LEAD_INFO_LABELS = ("Off", "Distance", "Speed", "Relative speed")
|
||||
|
||||
|
||||
def format_lead_info(lead, mode: int, metric: bool | None) -> str:
|
||||
"""The lead's distance or speed for the text above the lead marker; empty when there is nothing to show."""
|
||||
if lead is None or not lead.present or mode not in (LeadInfoMode.DISTANCE, LeadInfoMode.SPEED) or metric is None:
|
||||
field = {LeadInfoMode.DISTANCE: "dRel", LeadInfoMode.SPEED: "vLead", LeadInfoMode.RELATIVE_SPEED: "vRel"}.get(mode)
|
||||
if lead is None or not lead.present or field is None or metric is None:
|
||||
return ""
|
||||
try:
|
||||
value = float(lead.dRel if mode == LeadInfoMode.DISTANCE else lead.vLead)
|
||||
value = float(getattr(lead, field))
|
||||
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||
return ""
|
||||
if not math.isfinite(value):
|
||||
return ""
|
||||
value = max(value, 0.0)
|
||||
if mode != LeadInfoMode.RELATIVE_SPEED:
|
||||
value = max(value, 0.0)
|
||||
if mode == LeadInfoMode.DISTANCE:
|
||||
return f"{round(value if metric else value * 3.28084)} {'m' if metric else 'ft'}"
|
||||
return f"{round(value * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))} {'km/h' if metric else 'mph'}"
|
||||
speed = round(value * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))
|
||||
prefix = "+" if mode == LeadInfoMode.RELATIVE_SPEED and speed > 0 else ""
|
||||
return f"{prefix}{speed} {'km/h' if metric else 'mph'}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -121,14 +126,14 @@ def read_lead_info(params: Any) -> SavedLeadInfo:
|
||||
raw, readable = None, False
|
||||
if not flag.readable or not readable:
|
||||
return SavedLeadInfo(flag, raw, None, False)
|
||||
if flag.value is None or raw not in (None, b"0", b"1", b"2"):
|
||||
if flag.value is None or raw not in (None, b"0", b"1", b"2", b"3"):
|
||||
return SavedLeadInfo(flag, raw, None, True)
|
||||
if not flag.value:
|
||||
mode = LeadInfoMode.OFF
|
||||
elif raw in (None, b"0", b"2"):
|
||||
mode = LeadInfoMode.SPEED
|
||||
else:
|
||||
mode = LeadInfoMode.DISTANCE
|
||||
mode = LeadInfoMode(int(raw))
|
||||
return SavedLeadInfo(flag, raw, mode, True)
|
||||
|
||||
|
||||
|
||||
@@ -640,7 +640,7 @@ def validate_document(value):
|
||||
if type(colors) is not dict or set(colors) != set(PROFILES):
|
||||
raise ValueError("Invalid road color profiles")
|
||||
for profile, overrides in colors.items():
|
||||
if type(overrides) is not dict or not overrides.keys() <= ROAD_COLORS.keys() | {"pathMode"}:
|
||||
if type(overrides) is not dict or not overrides.keys() <= ROAD_COLORS.keys() | {"pathMode", "leadMarker"}:
|
||||
raise ValueError("Invalid road color fields")
|
||||
for key, color in overrides.items():
|
||||
if key == "pathMode":
|
||||
|
||||
@@ -26,6 +26,14 @@ def _rgba(color: str) -> tuple[int, ...]:
|
||||
return tuple(int(color[index:index + 2], 16) for index in (1, 3, 5, 7))
|
||||
|
||||
|
||||
def lead_marker_color(style: dict, opacity: float) -> rl.Color | None:
|
||||
color = style.get("leadMarker")
|
||||
if color is None:
|
||||
return None
|
||||
red, green, blue, alpha = _rgba(color)
|
||||
return rl.Color(red, green, blue, int(alpha * max(0.0, min(1.0, opacity))))
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def solid_gradient(color: str = ROAD_COLORS["path"]) -> Gradient:
|
||||
red, green, blue, alpha = _rgba(color)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user