Compare commits

...

30 Commits

Author SHA1 Message Date
firestar5683 dbca3b79d0 Exercise combined ModelD delay in the vehicle and Jetlink tests 2026-11-30 00:11:46 -06:00
firestar5683 4e2af76cad Test the combined ModelD steering smoothing join 2026-11-30 00:10:23 -06:00
firestar5683 1a5023ce7b Restore the hosted unit test worker budget 2026-11-29 23:31:13 -06:00
firestar5683 7dc5b57dfb Decode only consumed camera signals 2026-11-29 23:06:12 -06:00
firestar5683 71c0456448 Keep Subaru standstill hold bursts on one clock 2026-11-29 23:01:49 -06:00
firestar5683 9085011936 Preserve Crosstrek AOL through paddle EPS and delayed gear transitions 2026-11-29 22:50:06 -06:00
firestar5683 dfaf5ea134 Reuse accessory checks and CAN validation 2026-11-29 22:43:13 -06:00
firestar5683 6dcd7aada2 Qualify Bolt model smoothing in the FLM source contract 2026-11-29 22:41:25 -06:00
firestar5683 23b426a897 Share cruise throttle settling across non-ACC pedal Bolts 2026-11-29 22:37:09 -06:00
firestar5683 1169c9fbca Smooth early Bolt pedal cruise and steering 2026-11-29 22:26:00 -06:00
firestar5683 89ce004b02 Skip unused Toyota legacy filter checks 2026-11-29 22:13:58 -06:00
firestar5683 d1619d79e2 Wrap Toyota cache test parameters 2026-11-29 22:04:45 -06:00
firestar5683 5eab0f921e Repair Galaxy socket and Toyota cache test fixtures 2026-11-29 22:02:09 -06:00
firestar5683 f2b99c1eec Default gateway Mk7 Golf steering to the Torque Controller 2026-11-29 21:43:57 -06:00
firestar5683 eaf7a7cba2 Keep fixed Mk7 Golf discovery on normal CAN wiring 2026-11-29 21:32:19 -06:00
firestar5683 25ca42a8ce Recover Galaxy recording dates from late GPS fixes 2026-11-29 21:30:56 -06:00
firestar5683 404d71bf38 Bring Bolt ACC model stops closer by default 2026-11-29 21:28:51 -06:00
firestar5683 1b86f08b9d Reduce Volkswagen AOL work in Card 2026-11-29 21:26:07 -06:00
firestar5683 08d94465c2 Resume RAV4 SmartDSU pedal acceleration from standstill 2026-11-29 21:24:36 -06:00
firestar5683 eb3f91847b Reduce Tucson steering oscillation during steady demand 2026-11-29 21:23:32 -06:00
fantasist 521e32c316 Fix Steering Controller missing in UI for PID cars when CarParams is a reader 2026-11-29 21:17:11 -06:00
firestar5683 91e4edf3b3 Decode only tracked fields in Hyundai dual-object radar 2026-11-29 21:16:05 -06:00
firestar5683 6c4559f0c3 Build the ARM64 Mapd provider 2026-11-29 21:15:36 -06:00
firestar5683 122d1825e9 Keep the current map road through crossings 2026-11-29 21:12:42 -06:00
firestar5683 ab2641f118 Skip irrelevant Toyota accessory configuration checks 2026-11-29 21:11:51 -06:00
firestar5683 efc7ca5f3b Add adjustable onroad border width 2026-11-29 20:24:58 -06:00
firestar5683 3272a31fc4 Remove downloaded sound packs in Galaxy 2026-11-29 18:17:01 -06:00
firestar5683 26c2d5c5ae Rename the toggle to Add Extra Boost 2026-11-29 17:40:42 -06:00
firestar5683 2785af8023 Align Traffic Mode follow floor fixture 2026-11-29 17:15:52 -06:00
firestar5683 84e3ce7468 Add opt-in End to End convergence to set speed 2026-11-29 16:55:31 -06:00
110 changed files with 1442 additions and 356 deletions
+1 -1
View File
@@ -255,7 +255,7 @@ jobs:
env:
RAYLIB_BACKEND: headless
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
run: tools/op.sh test --json-output unit-test-results.json
run: tools/op.sh test --jobs 2 --json-output unit-test-results.json
- name: Test GM vehicle configurations and CAN behavior
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 5
+63
View File
@@ -165,6 +165,69 @@ func TestPackedStickyRoadAmbiguityAndEmptyNewTileClearState(t *testing.T) {
}
}
func TestPackedStickyRoadAtCrossings(t *testing.T) {
local := syntheticWay{1, 8, 35.1, -97.9, 35.2, -97.9, false, 2}
updated := local
updated.speed = 12
crossing := syntheticWay{2, 30, 35.15, -97.95, 35.15, -97.85, false, 6}
parallel := syntheticWay{3, 27, 35.1, -97.8999, 35.2, -97.8999, false, 2}
shallow := syntheticWay{2, 30, 35.14, -97.9085, 35.16, -97.8915, false, 6}
secondCrossing := syntheticWay{3, 27, 35.15005, -97.95, 35.15005, -97.85, false, 2}
endpoint := updated
endpoint.lat1 = 35.15
broadOnly := updated
broadOnly.lon1, broadOnly.lon2 = -97.89985, -97.89985
for _, tc := range []struct {
name string
ways []syntheticWay
bearing float32
sticky bool
}{
{"crossing after current", []syntheticWay{updated, crossing}, 0, true},
{"crossing before current", []syntheticWay{crossing, updated}, 0, true},
{"multiple crossing rivals", []syntheticWay{crossing, updated, secondCrossing}, 0, true},
{"crossing and parallel rival", []syntheticWay{crossing, updated, parallel}, 0, false},
{"crossing rival too aligned", []syntheticWay{updated, shallow}, 0, false},
{"current heading mismatch", []syntheticWay{updated, crossing}, 35, false},
{"current at endpoint", []syntheticWay{endpoint, crossing}, 0, false},
{"current only fits broad envelope", []syntheticWay{broadOnly, crossing}, 0, false},
{"current absent from loaded tile", []syntheticWay{crossing, secondCrossing}, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
s := State{}
s.Init()
boot := uint64(10_100_000_000)
s.bootNow = func() uint64 { return boot }
now := time.Unix(0, 0)
first := packedRoadTile(t, []syntheticWay{local})
s.ProcessGps(ambiguitySample(t, 10_000_000_000, true), true, func(m.Position) (maps.Offline, error) { return first, nil }, now)
if !s.RoadMatched() {
t.Fatal("initial road did not match")
}
previous := s.CurrentWay
s.Data = packedRoadTile(t, tc.ways)
boot += 100_000_000
sample := ambiguitySample(t, 10_100_000_000, false)
sample.Location.SetBearingDeg(tc.bearing)
sample.Location.SetHorizontalAccuracy(9)
if candidates := plausibleLoadedWays(&s.Data, sample.Location); len(candidates) != len(tc.ways) {
t.Fatalf("expected %d broad-envelope candidates, got %d", len(tc.ways), len(candidates))
}
s.ProcessGps(sample, true, nil, now.Add(100*time.Millisecond))
event, out := decodedOutput(t, &s)
if tc.sticky {
if !event.Valid() || out.RoadStatus() != custom.MapdOut_SampleStatus_matchedLimit || out.WayId() != updated.id || out.SpeedLimit() != float32(updated.speed) ||
s.CurrentWay.SelectionType != custom.WaySelectionType_current || s.CurrentWay.ConfidenceCounter != previous.ConfidenceCounter+1 ||
s.CurrentWay.LastChangeTime != previous.LastChangeTime {
t.Fatalf("crossing lost current road: status=%v way=%d limit=%f selection=%v", out.RoadStatus(), out.WayId(), out.SpeedLimit(), s.CurrentWay.SelectionType)
}
} else if event.Valid() || out.RoadStatus() != custom.MapdOut_SampleStatus_unknown || out.WayId() != 0 || out.SpeedLimit() != 0 {
t.Fatalf("competing roads leaked match: status=%v way=%d limit=%f", out.RoadStatus(), out.WayId(), out.SpeedLimit())
}
})
}
}
func TestPackedPredictedWayCannotBypassCompetingRoad(t *testing.T) {
local := syntheticWay{1, 8, 35.1, -97.9, 35.2, -97.9, false, 2}
rival := syntheticWay{2, 30, 35.1, -97.8999, 35.2, -97.8999, false, 6}
+23 -5
View File
@@ -57,8 +57,8 @@ func (w *CurrentWay) EffectiveMaxSpeed() float64 {
return w.MaxSpeed()
}
// ErrAmbiguousWay means more than one distinct loaded-tile road fits the same
// GPS uncertainty envelope. The rank scorer must not turn that into a limit.
// ErrAmbiguousWay means the loaded-tile candidates do not support keeping
// the current road or choosing a unique match.
var ErrAmbiguousWay = errors.New("multiple plausible road IDs")
// plausibleLoadedWays considers every way in the current tile before sticky or
@@ -107,12 +107,24 @@ func GetCurrentWay(currentWay CurrentWay, nextWays []maps.NextWayResult, offline
if len(candidates) == 0 {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, errors.New("no plausible loaded-tile way")
}
if len(candidates) > 1 {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, ErrAmbiguousWay
}
// Use the loaded tile's representation, even when a prior sticky way has the
// same ID. This prevents an old tile's geometry/limit from being republished.
way := candidates[0]
if len(candidates) > 1 {
if currentWay.Way.Nodes.Len() < 2 {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, ErrAmbiguousWay
}
for _, candidate := range candidates {
if candidate.Id() == currentWay.Way.Id() {
way = candidate
continue
}
alignment, err := candidate.BearingAlignment(location)
if err != nil || !(alignment >= 0.7) {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, ErrAmbiguousWay
}
}
}
onWay, err := way.OnWay(location, 2)
if err != nil || !onWay.OnWay {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, errors.New("sole way lost geographic match")
@@ -131,6 +143,12 @@ func GetCurrentWay(currentWay CurrentWay, nextWays []maps.NextWayResult, offline
onWay = narrow
}
}
if len(candidates) > 1 {
alignment, err := way.BearingAlignment(location)
if selection != custom.WaySelectionType_current || err != nil || !(alignment <= 0.5) {
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, ErrAmbiguousWay
}
}
if selection == custom.WaySelectionType_fail && narrowErr == nil && narrow.OnWay {
for _, next := range nextWays {
if next.Way.Nodes.Len() > 1 && next.Way.Id() == way.Id() {
+11 -2
View File
@@ -24,6 +24,8 @@ from opendbc.car.honda.values import CAR as HONDA, HondaFlags
from opendbc.car.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
from opendbc.car.tesla.discovery import normal_bus0_topology as tesla_normal_bus0_topology
from opendbc.car.volkswagen.discovery import golf_normal_bus_topology
from opendbc.car.volkswagen.values import CAR as VOLKSWAGEN
from opendbc.car.values import BRANDS
from opendbc.car.vin import get_vin, is_valid_vin, VIN_UNKNOWN
@@ -120,7 +122,7 @@ def _tesla_fw_uses_normal_bus0() -> bool:
# **** for use live only ****
def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback,
cached_params: CarParamsT | None, *, known_gm_bus0: bool = False, known_ford_bus0: bool = False,
known_tesla_bus0: bool = False, known_honda_accord: bool = False
known_tesla_bus0: bool = False, known_honda_accord: bool = False, known_vw_golf: bool = False
) -> tuple[str | None, dict, str, list[CarParams.CarFw], CarParams.FingerprintSource, bool]:
if known_ford_bus0 and (known_gm_bus0 or not ford_normal_bus0_queries()):
raise ValueError('Ford discovery topology no longer uses normal bus 0')
@@ -199,7 +201,8 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
('honda' if honda_normal_bus_topology(normal_bus_packets) else None) or
('honda_nidec' if nidec_bus0_topology(normal_bus_packets) else None) or
('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None) or
('mazda' if mazda_normal_bus0_topology(normal_bus_packets) else None)) is not None:
('mazda' if mazda_normal_bus0_topology(normal_bus_packets) else None) or
('volkswagen' if known_vw_golf and golf_normal_bus_topology(normal_bus_packets) else None)) is not None:
set_obd_multiplexing(False)
warmup_remaining = 0.1 - (time.monotonic() - start_time)
@@ -305,6 +308,7 @@ def get_car(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multip
known_gm_bus0 = (explicit_candidate in interface_names['gm'] and _gm_fw_uses_normal_bus0())
known_ford_bus0 = ford_normal_bus0_selection(explicit_candidate)
known_tesla_bus0 = explicit_candidate in interface_names['tesla'] and _tesla_fw_uses_normal_bus0()
known_vw_golf = explicit_candidate == VOLKSWAGEN.VOLKSWAGEN_GOLF_MK7
if known_gm_bus0 and cached_params is not None and (
cached_params.brand != 'gm' or cached_params.carFingerprint != explicit_candidate):
cached_params = None
@@ -323,6 +327,11 @@ def get_car(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multip
elif known_tesla_bus0:
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
can_recv, can_send, set_obd_multiplexing, cached_params, known_tesla_bus0=True)
elif known_vw_golf:
if cached_params is not None and (cached_params.brand != 'volkswagen' or cached_params.carFingerprint != explicit_candidate):
cached_params = None
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
can_recv, can_send, set_obd_multiplexing, cached_params, known_vw_golf=True)
elif forced_candidate == HONDA.HONDA_ACCORD:
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
can_recv, can_send, set_obd_multiplexing, cached_params, known_honda_accord=True)
+8 -7
View File
@@ -315,13 +315,14 @@ class CarState(CarStateBase):
pt_cp.ts_nanos["AcceleratorPedal2"]["AcceleratorPedal2"],
pt_cp.ts_nanos["ECMEngineStatus"]["CruiseMainOn"],
pt_cp.ts_nanos["EBCMRegenPaddle"]["RegenPaddle"])
control_word = gm_control_word(self.CP)
if is_volt_longitudinal(self.CP):
# Observe only actual resume/driver sources, using the finalized brake owner.
alternate = is_volt_gateway_alternate_brake(self.CP) or (
volt_camera_removed and bool(self.CP.flags & GMFlags.NO_ACCELERATOR_POS_MSG))
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and not (
gm_control_word(self.CP) & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) and
not gm_control_word(self.CP) & GMSafetyFlags.BRAKE_C9)
control_word & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) and
not control_word & GMSafetyFlags.BRAKE_C9)
brake = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
names = (("AcceleratorPedal2", "CruiseState", 100_000_000),
@@ -342,8 +343,8 @@ class CarState(CarStateBase):
self.camera_pedal_profile is not None and self.camera_pedal_profile.volt and
self.camera_pedal_profile.brake_source == BrakeSource.F1)
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and (
not gm_control_word(self.CP) & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) or
bool(gm_control_word(self.CP) & GMSafetyFlags.BRAKE_C9))
not control_word & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) or
bool(control_word & GMSafetyFlags.BRAKE_C9))
brake_name, brake_signal = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
names = (("ECMEngineStatus", "CruiseMainOn"), ("ECMPRDNL2", "PRNDL2"), (brake_name, brake_signal),
@@ -357,7 +358,7 @@ class CarState(CarStateBase):
if self.camera_pedal_profile is not None and self.camera_pedal_profile.volt:
self.gm_auto_hold_sources += ((pt_cp.ts_nanos["GAS_SENSOR"]["COUNTER_PEDAL"], 100_000_000),)
# C9 is pressed authority, never analog force; missing-BE profiles retain minimum hold.
absent_be = c9 and bool(gm_control_word(self.CP) & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM))
absent_be = c9 and bool(control_word & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM))
if alternate_force:
self.gm_auto_hold_brake = pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] / 208.
if c9:
@@ -426,9 +427,9 @@ class CarState(CarStateBase):
else:
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear["PRNDL2"], None))
source_be_brake = (gm_control_word(self.CP) &
source_be_brake = (control_word &
(GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM).value and
not gm_control_word(self.CP) & GMSafetyFlags.BRAKE_C9.value)
not control_word & GMSafetyFlags.BRAKE_C9.value)
if is_volt_cc_f1_profile(self.CP):
ret.brakePressed = (pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] >= 6 or
pt_cp.vl["ECMEngineStatus"]["BrakePressed"] != 0)
+3 -2
View File
@@ -113,10 +113,11 @@ class GMPedalLongitudinalPolicy:
def prepare_pid(self, pid, target: float, error: float, speed: float,
last_output: float, accel_limits: tuple[float, float], *,
should_stop: bool = False, has_lead: bool | None = None) -> bool:
should_stop: bool = False, has_lead: bool | None = None, gentle_cruise_settle: bool = False) -> bool:
if pid.i > 0.0 and target < -0.05 and error < -0.25 and not (speed <= 0.35 and target > -0.40):
bleed = _interp(abs(error), (0.25, 0.75, 1.5), (0.55, 0.25, 0.0))
pid.i *= bleed
# Retain the steady uphill demand through a minor no-lead cruise correction.
pid.i *= .985 if gentle_cruise_settle and not should_stop and -.10 < target else bleed
handoff_threshold = _interp(speed, (0.0, 4.0, 12.0, 25.0), (0.35, 0.45, 0.55, 0.70))
hold_frames = int(round(_interp(speed, (0.0, 4.0, 12.0, 25.0), (25.0, 20.0, 14.0, 10.0))))
@@ -7,6 +7,7 @@ from opendbc.car.gm.values import (GMFlags, camera_acc_pedal_profile, is_volt_as
EPS_STATUS_TIMEOUT_NS = 300_000_000
STEERING_COMMAND_TIMEOUT_NS = 100_000_000
ButtonType = structs.CarState.ButtonEvent.Type
STEERING_SOURCE_LENGTHS = {0xC9: 8, 0xBE: 6, 0xBD: 7, 0x1E1: 7}
@cached_config
@@ -42,24 +43,30 @@ class SteeringAuthority:
if not self.enabled:
return
self.source_ns.clear()
malformed = any(bus == 0 and address == 0x184 and (stamp <= 0 or len(data) != 8)
for stamp, packets in can_packets for address, data, bus in packets)
lengths = {0xC9: 8, 0xBE: 6, 0xBD: 7, 0x1E1: 7}
invalid = {address for stamp, packets in can_packets for address, data, bus in packets
if bus == 0 and address in lengths and (stamp <= 0 or len(data) != lengths[address])}
for address in invalid:
self.source_ns.pop(address, None)
malformed_status = False
previous_status_ns = self.status_ns
invalid_sources = set()
for stamp, packets in can_packets:
for address, data, bus in packets:
if bus != 0 or stamp <= 0:
if bus != 0:
continue
if address in lengths and address not in invalid:
self.source_ns[address] = max(stamp, self.source_ns.get(address, 0))
if address == 0x184 and stamp > self.status_ns:
if self.active_since_ns and stamp - max(self.status_ns, self.active_since_ns) > EPS_STATUS_TIMEOUT_NS:
self.latched = True
self.status_ns = stamp
self.status = -1 if malformed else (data[0] >> 3) & 7
if address == 0x184:
valid = stamp > 0 and len(data) == 8
malformed_status |= not valid
if stamp > self.status_ns and stamp > 0:
if self.active_since_ns and stamp - max(self.status_ns, self.active_since_ns) > EPS_STATUS_TIMEOUT_NS:
self.latched = True
self.status_ns = stamp
self.status = (data[0] >> 3) & 7 if valid else -1
elif (length := STEERING_SOURCE_LENGTHS.get(address)) is not None:
if stamp > 0 and len(data) == length:
self.source_ns[address] = max(stamp, self.source_ns.get(address, 0))
else:
invalid_sources.add(address)
for address in invalid_sources:
self.source_ns.pop(address, None)
if malformed_status and self.status_ns > previous_status_ns:
self.status = -1
def command(self, now_ns: int, active: bool):
if not self.enabled:
@@ -42,3 +42,19 @@ def test_sdgm_refusal_requires_physical_disable_neutral_and_fresh_rearm(monkeypa
# Reuse the full original parser/controller physical sequence for this exact factory CP.
monkeypatch.setattr(ascm_fixture, "params", lambda *args, **kwargs: sdgm_params(brake_c9=c9, radar=True))
ascm_fixture.TestAscmIntercept(methodName="runTest").test_volt_steering_loss_requires_driver_rearm()
@pytest.mark.parametrize('bad_first', [True, False])
def test_sdgm_mixed_valid_and_malformed_batch_withdraws_source_credit(bad_first):
authority = CarInterface(sdgm_params(alpha=True)).CS.steering_authority
first_ns, second_ns = 1_000_000_000, 1_010_000_000
valid = [(0x184, bytes((8,)) + bytes(7), 0), (0xC9, bytes(8), 0), (0xBE, bytes(6), 0)]
malformed = [(0x184, b'', 0), (0xC9, bytes(7), 0), (0xBE, b'', 128)]
first, second = (malformed, valid) if bad_first else (valid, malformed)
authority.observe([(first_ns, first), (second_ns, second)])
assert authority.status_ns == second_ns
assert authority.status == -1
assert authority.source_ns == {0xBE: second_ns if bad_first else first_ns}
authority.observe([(second_ns + 1, valid)])
assert authority.status == 1
assert authority.source_ns == {0xC9: second_ns + 1, 0xBE: second_ns + 1}
@@ -23,7 +23,10 @@ class CameraLeadObservation:
class CANFDCameraLead:
def __init__(self, cp, bus):
self.bus = bus
self.parser = CANParser(DBC[cp.carFingerprint][Bus.pt], [('FR_CMR_03_50ms', math.nan)], self.bus)
camera = 'FR_CMR_03_50ms'
self.parser = CANParser(DBC[cp.carFingerprint][Bus.pt], [(camera, math.nan)], self.bus, signals={
camera: ('FR_CMR_Crc3Val', 'FR_CMR_AlvCnt3Val', 'Longitudinal_Distance', 'Relative_Velocity'),
})
self.observation = None
self.last_packet_ns = 0
self.last_counter = None
@@ -161,7 +161,10 @@ def get_radar_can_parser(CP):
# MRR35 publishes many unused/unknown fields in each object packet. Decode
# the four consumed track fields, retaining parser integrity fields automatically.
selected = ({name: ('STATE', 'LONG_DIST', 'LAT_DIST', 'REL_SPEED') for name, _ in messages} if mrr35 else None)
if radar_dbc(CP) == "hyundai_kia_mando_front_radar_generated":
if mrr30 or gv70:
track_fields = tuple(f'{slot}_{field}' for slot in (1, 2) for field in ('STATE', 'LONG_DIST', 'LAT_DIST', 'REL_SPEED'))
selected = {name: track_fields for name, _ in messages}
elif radar_dbc(CP) == "hyundai_kia_mando_front_radar_generated":
selected = {name: ('STATE', 'AZIMUTH', 'LONG_DIST', 'REL_SPEED') for name, _ in messages}
return CANParser(radar_dbc(CP), messages, radar_bus(CP) if mrr35 or mrr30 or gv70 else 1, signals=selected)
@@ -4,7 +4,9 @@ from opendbc.car.hyundai import radar_interface
from opendbc.car.hyundai.tests.test_dom_radar_complete_paths import CASES, bank, factory
@pytest.mark.parametrize('name,dbc,bus,start,count,length,lka', [case for case in CASES if any(layout in case[1] for layout in ('mrr35', 'mando_front'))])
@pytest.mark.parametrize('name,dbc,bus,start,count,length,lka', [
case for case in CASES if any(layout in case[1] for layout in ('mrr35', 'mando_front', 'mrr30', '210_21f'))
])
def test_projected_radar_matches_complete_decoder(monkeypatch, name, dbc, bus, start, count, length, lka):
cp = factory(name, bus, start, count, length, lka)
projected = radar_interface.RadarInterface(cp)
+2 -1
View File
@@ -13,7 +13,8 @@ DASHBOARD_CARS = frozenset(CAR)
class DashboardCameraParser(CANParser):
def __init__(self, dbc_name):
super().__init__(dbc_name, [], 2)
self.dashboard_parser = CANParser(dbc_name, [("CAM_TRAFFIC_SIGNS", float('nan'))], 2)
signs = "CAM_TRAFFIC_SIGNS"
self.dashboard_parser = CANParser(dbc_name, [(signs, float('nan'))], 2, signals={signs: ("STOP_SIGN",)})
def update(self, strings, sendcan=False):
packets = strings
+1 -1
View File
@@ -12,7 +12,7 @@ from opendbc.car import CanSignalRateCalculator
SUBARU_CVT_MANUAL_GEARS = frozenset({129, 137, 145, 153, 161, 169, 177, 185, 193})
# Drive range with ratio zero, with either state of the manual-mode bit.
PADDLE_EXIT_GEARS = (1, 129)
PADDLE_EXIT_WINDOW_NS = 750_000_000
PADDLE_EXIT_WINDOW_NS = 2_000_000_000
PADDLE_EXIT_PAUSE_NS = 150_000_000
+1 -2
View File
@@ -88,9 +88,8 @@ class StopAndGo:
self.departure_seen = False
self.remaining = 0
duration = frame - self.last_standstill_frame
# The sender starts each burst on its first fresh brake frame and owns the repeat interval.
speed = state.standstill and duration > 50
if duration >= 55:
self.last_standstill_frame = frame
if state.standstill and self.previous_distance is not None and 3.0 < distance < 4.5 and distance > self.previous_distance and not self.departure_seen:
self.departure_seen = True
self.remaining = 15
@@ -57,8 +57,12 @@ def apply(cp, *, camera_twoaa=False):
cp.alphaLongitudinalAvailable = bool(cp.flags & (ToyotaFlags.NO_DSU | ToyotaFlags.RADAR_ACC))
@cached_config
def configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.RADAR_CAN_FILTER) and _configured(cp))
@cached_config
def _configured(cp):
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
from opendbc.car.toyota import camera_2aa_filter
@@ -126,11 +130,15 @@ class AdvertFilterCANParser(CANParser):
self.advert_distance_button = 0
self.advert_button_ns = 0
def update(self, strings, sendcan=False):
def _update_filtered(self, strings, sendcan, accept_accessory=None, *, physical_only=False):
batches = []
for stamp, frames in strings:
accepted = []
for address, data, bus in frames:
if physical_only and bus >= 128:
continue
if accept_accessory is not None and address in (0x201, 0x2AA, 0x2FF) and not accept_accessory(address, data, bus):
continue
if bus == self.bus:
if address in (0x1D3, 0x262):
valid = len(data) == 8 and data[-1] == toyota_checksum(address, None, bytearray(data))
@@ -148,3 +156,6 @@ class AdvertFilterCANParser(CANParser):
accepted.append((address, data, bus))
batches.append((stamp, accepted))
return super().update(batches, sendcan)
def update(self, strings, sendcan=False):
return self._update_filtered(strings, sendcan)
@@ -93,24 +93,18 @@ class CameraTwoAACANParser(AdvertFilterCANParser):
super().__init__(*args)
self.hardware_ambiguous = False
def _accept_accessory(self, address, data, bus):
if address in (0x201, 0x2FF):
self.hardware_ambiguous = True
return False
if address == 0x2AA:
self.hardware_ambiguous |= bus not in (0, 2) or len(data) != 8
return False
return True
def update(self, strings, sendcan=False):
batches = []
for stamp, frames in strings:
accepted = []
for address, data, bus in frames:
# pandad marks TX confirmations/rejections with bus >= 128; they
# are not received hardware (see panda.h CAN_*_BUS_OFFSET).
if bus >= 128:
continue
if address in (0x201, 0x2FF):
self.hardware_ambiguous = True
continue
if address == 0x2AA:
self.hardware_ambiguous |= bus not in (0, 2) or len(data) != 8
continue
accepted.append((address, data, bus))
batches.append((stamp, accepted))
result = super().update(batches, sendcan)
# Buses >= 128 carry Panda TX receipts, not physical RX.
result = self._update_filtered(strings, sendcan, self._accept_accessory, physical_only=True)
if self.hardware_ambiguous:
self.main_valid = self.eps_valid = False
return result
@@ -152,7 +152,8 @@ class CarController(CarControllerBase):
def update(self, CC, CS, now_nanos):
from opendbc.car.toyota import dsu_bypass
bypass_long = dsu_bypass.enabled(self.CP)
bypass_owner = dsu_bypass.configured(self.CP)
bypass_long = bypass_owner and self.CP.openpilotLongitudinalControl
_projection = self.learning_projection_observer
if _projection is not None:
_projection.begin(CC.actuators.torque, self.frame)
@@ -190,10 +191,6 @@ class CarController(CarControllerBase):
CS.out.canValid and not CS.out.canTimeout and CS.out.cruiseState.available and not CS.out.accFaulted and
not CS.out.stockAeb and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent and not CS.out.doorOpen and
not CS.out.seatbeltUnlatched and CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport))
if pedal_owner:
hold_source_ready = hold_source_ready and bool(self.pedal_input is not None and self.pedal_input.update(now_nanos) and CS.pedal_ready)
if bypass_long:
hold_source_ready = hold_source_ready and bool(self.bypass_input is not None and self.bypass_input.update(now_nanos))
composite_pedal = pedal_composite.configured(self.CP)
if composite_pedal:
filter_allowed = filter_allowed and bool(
@@ -202,11 +199,16 @@ class CarController(CarControllerBase):
(not CS.out.brakePressed or CS.out.standstill) and
CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport))
if pedal_owner:
filter_allowed = filter_allowed and bool(self.pedal_input is not None and self.pedal_input.update(now_nanos) and CS.pedal_ready)
pedal_ready = bool((hold_source_ready or filter_allowed) and self.pedal_input is not None and
self.pedal_input.update(now_nanos) and CS.pedal_ready)
hold_source_ready = hold_source_ready and pedal_ready
filter_allowed = filter_allowed and pedal_ready
if bypass_long:
preference = getattr(self, 'bypass_input', None)
filter_allowed = filter_allowed and bool(
preference is not None and preference.update(now_nanos) and CS.out.canValid and not CS.out.canTimeout and
bypass_ready = bool((hold_source_ready or filter_allowed) and preference is not None and preference.update(now_nanos))
hold_source_ready = hold_source_ready and bypass_ready
filter_allowed = filter_allowed and bypass_ready and bool(
CS.out.canValid and not CS.out.canTimeout and
CS.out.cruiseState.available and not CS.out.accFaulted and not CS.out.stockAeb and
not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent and not CS.out.doorOpen and
not CS.out.seatbeltUnlatched and (not CS.out.brakePressed or CS.out.standstill) and
@@ -223,7 +225,7 @@ class CarController(CarControllerBase):
if (bypass_long or rav4h_long or pedal_owner or advert_long or original_prius_long) and not filter_allowed and CS.out.cruiseState.enabled:
pcm_cancel_cmd = True
lat_active = CC.latActive and abs(CS.out.steeringTorque) < MAX_USER_TORQUE
if dsu_bypass.configured(self.CP):
if bypass_owner:
lat_active = lat_active and CS.out.canValid and not CS.out.canTimeout and CS.out.cruiseState.available and not (
CS.out.steerFaultTemporary or CS.out.steerFaultPermanent or CS.out.doorOpen)
if self.original_prius_filter:
@@ -338,6 +340,8 @@ class CarController(CarControllerBase):
else:
self.reset_auto_hold_state()
if self.CP.openpilotLongitudinalControl:
legacy_advert_long = legacy_advert_filter.configured(self.CP)
legacy_rav4h_long = legacy_advert_long and self.CP.carFingerprint == CAR.TOYOTA_RAV4H
# if user engages at a stop with foot on brake, PCM starts in a special cruise standstill mode. on resume press,
# brakes can take a while to ramp up causing a lurch forward. prevent resume press until planner wants to move.
# don't use CC.cruiseControl.resume since it is gated on CS.cruiseState.standstill which goes false for 3s after resume press
@@ -356,12 +360,12 @@ class CarController(CarControllerBase):
CS.pcm_acc_status, CC.cruiseControl.resume, long_active)
self.last_standstill = CS.out.standstill
elif self.sdsu_hybrid or (advert_long and bool(self.CP.flags & ToyotaFlags.HYBRID) and
not (legacy_advert_filter.enabled(self.CP) and self.CP.carFingerprint == CAR.TOYOTA_RAV4H)):
not legacy_rav4h_long):
# Retain the existing hybrid resume behavior while active. The shared
# owner guard below still holds neutral when LONG or its source is lost.
self.standstill_req = not long_active and CS.out.standstill
elif rav4h_long or (legacy_advert_filter.enabled(self.CP) and self.CP.carFingerprint == CAR.TOYOTA_RAV4H) or not self.CP.flags & ToyotaFlags.HYBRID.value:
should_resume = long_active and actuators.accel > 0 if rav4h_long or legacy_advert_filter.enabled(self.CP) else actuators.accel > 0
elif rav4h_long or legacy_rav4h_long or not self.CP.flags & ToyotaFlags.HYBRID.value:
should_resume = long_active and actuators.accel > 0 if rav4h_long or legacy_advert_long else actuators.accel > 0
if should_resume:
self.standstill_req = False
@@ -374,7 +378,7 @@ class CarController(CarControllerBase):
if (bypass_long or rav4h_long or pedal_owner or advert_long or original_prius_long) and (not filter_allowed or not long_active and CS.out.standstill):
self.standstill_req = True
if pedal_owner and (self.CP.carFingerprint in pedal.RADAR_PEDAL_CARS or pedal_composite.configured(self.CP)) and not long_active:
if pedal_owner and (self.CP.carFingerprint in pedal.RADAR_PEDAL_CARS or composite_pedal) and not long_active:
# A radar-disable safety handoff starts with fresh native RX checks.
# Neutral output must not request release before LONG is admitted.
self.standstill_req = True
+11 -8
View File
@@ -87,6 +87,9 @@ class CarState(CarStateBase):
ret = structs.CarState()
bypass = dsu_bypass.configured(self.CP)
advert_owner = advert_filter.configured(self.CP)
pedal_owner = pedal.configured(self.CP)
composite_pedal = pedal_owner and pedal_composite.configured(self.CP)
cp_acc = cp_cam if bypass or (self.CP.flags & ToyotaFlags.TSS2) and not (self.CP.flags & ToyotaFlags.RADAR_ACC) else cp
if not self.CP.flags & ToyotaFlags.SECOC.value:
@@ -153,7 +156,7 @@ class CarState(CarStateBase):
ret.steerFaultTemporary = cp.vl["EPS_STATUS"]["LKA_STATE"] in TEMP_STEER_FAULTS
ret.steerFaultPermanent = cp.vl["EPS_STATUS"]["LKA_STATE"] in PERM_STEER_FAULTS
if advert_filter.configured(self.CP):
if advert_owner:
stamp, expiry = parser_expiry(cp, 'EPS_STATUS', 'LKA_STATE')
expiry = min(expiry, stamp + 400_000_000)
ret.steerFaultTemporary |= not (cp.eps_valid and stamp > 0 and stamp <= cp._last_update_nanos <= expiry)
@@ -180,7 +183,7 @@ class CarState(CarStateBase):
ret.accFaulted = cp.vl["PCM_CRUISE_2"]["ACC_FAULTED"] != 0
ret.carFaultedNonCritical = cp.vl["PCM_CRUISE_SM"]["TEMP_ACC_FAULTED"] != 0
ret.cruiseState.available = cp.vl["PCM_CRUISE_2"]["MAIN_ON"] != 0
if (pedal.configured(self.CP) and not pedal_composite.configured(self.CP)) or advert_filter.configured(self.CP):
if (pedal_owner and not composite_pedal) or advert_owner:
stamp = cp.ts_nanos["PCM_CRUISE_2"]["MAIN_ON"]
ret.cruiseState.available &= bool(cp.main_valid and stamp > 0 and 0 <= cp._last_update_nanos - stamp <= 303_031_000)
ret.cruiseState.speed = cp.vl["PCM_CRUISE_2"]["SET_SPEED"] * CV.KPH_TO_MS
@@ -266,7 +269,7 @@ class CarState(CarStateBase):
buttonEvents.extend(create_button_events(1, 0, {1: ButtonType.lkas}) +
create_button_events(0, 1, {1: ButtonType.lkas}))
if (self.CP.flags & ToyotaFlags.TSS2 and not advert_filter.configured(self.CP) and
if (self.CP.flags & ToyotaFlags.TSS2 and not advert_owner and
not (self.CP.flags & (ToyotaFlags.RADAR_ACC | ToyotaFlags.SECOC | ToyotaFlags.LONG_FILTER))):
# distance button is wired to the ACC module (camera or radar)
prev_distance_button = self.distance_button
@@ -275,9 +278,9 @@ class CarState(CarStateBase):
buttonEvents += create_button_events(self.distance_button, prev_distance_button, {1: ButtonType.gapAdjustCruise})
if (self.CP.carFingerprint in (CAR.TOYOTA_PRIUS, CAR.TOYOTA_PRIUS_RETROFIT) or
self.CP.flags & (ToyotaFlags.LONG_FILTER | ToyotaFlags.FILTER_BUTTONS) or advert_filter.configured(self.CP)):
self.CP.flags & (ToyotaFlags.LONG_FILTER | ToyotaFlags.FILTER_BUTTONS) or advert_owner):
prev_distance_button = self.distance_button
if self.CP.flags & ToyotaFlags.FILTER_BUTTONS or advert_filter.configured(self.CP) or prius_advert_filter.configured(self.CP):
if self.CP.flags & ToyotaFlags.FILTER_BUTTONS or advert_owner or prius_advert_filter.configured(self.CP):
fresh = cp.advert_button_ns > 0 and 0 <= cp._last_update_nanos - cp.advert_button_ns <= 200_000_000
self.distance_button = cp.advert_distance_button if fresh else 0
elif not bypass and has_optional_prius_gap_button(self.CP):
@@ -338,12 +341,12 @@ class CarState(CarStateBase):
ret.steerFaultTemporary |= not (cp.eps_valid and eps_stamp > 0 and
0 <= cp._last_update_nanos - eps_stamp <= 400_000_000)
if pedal.configured(self.CP):
cp_pedal = can_parsers[Bus.alt] if pedal_composite.configured(self.CP) else cp
if pedal_owner:
cp_pedal = can_parsers[Bus.alt] if composite_pedal else cp
stamp = cp_pedal.ts_nanos.get("GAS_SENSOR", {}).get("STATE", 0)
self.pedal_ready = bool(cp_pedal.pedal_valid and stamp > 0 and 0 <= cp_pedal._last_update_nanos - stamp <= 200_000_000)
pedal_gas = (cp_pedal.vl['GAS_SENSOR']['INTERCEPTOR_GAS'] + cp_pedal.vl['GAS_SENSOR']['INTERCEPTOR_GAS2']) / 2 > 805
ret.gasPressed = (ret.gasPressed or pedal_gas) if pedal_composite.configured(self.CP) else pedal_gas
ret.gasPressed = (ret.gasPressed or pedal_gas) if composite_pedal else pedal_gas
ret.accFaulted = ret.accFaulted or not self.pedal_ready
ret.buttonEvents = buttonEvents
timestamp, expiry = parser_expiry(cp_cam, "RSA1", "TSGN1")
@@ -89,8 +89,12 @@ def apply(cp):
cp.dashcamOnly = False
@cached_config
def configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.DSU_BYPASS) and _configured(cp))
@cached_config
def _configured(cp):
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
if (
@@ -47,12 +47,14 @@ def apply(cp):
def configured(cp):
if cp is None or not cp.flags & int(ToyotaFlags.RADAR_CAN_FILTER):
return False
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
if cp is not None and cp.carFingerprint == CAR.TOYOTA_MATRIX_RETROFIT:
if cp.carFingerprint == CAR.TOYOTA_MATRIX_RETROFIT:
from opendbc.car.toyota import matrix_filter
return matrix_filter.configured(cp, length=4)
if (cp is None or cp.brand != 'toyota' or cp.carFingerprint not in PROFILES or cp.notCar or cp.passive or cp.dashcamOnly or
if (cp.brand != 'toyota' or cp.carFingerprint not in PROFILES or cp.notCar or cp.passive or cp.dashcamOnly or
cp.secOcRequired or not cp.pcmCruise or len(cp.safetyConfigs) != 1 or
cp.steerControlType != structs.CarParams.SteerControlType.torque):
return False
+7
View File
@@ -64,6 +64,8 @@ def hardware_supported(candidate, fingerprint, car_fw):
def configured(cp):
if cp is None or not cp.flags & int(ToyotaFlags.GAS_INTERCEPTOR):
return False
from opendbc.car.toyota.pedal_composite import hold_base_cp
cp = hold_base_cp(cp)
from opendbc.car.toyota import pedal_composite
@@ -123,6 +125,11 @@ def command(packer, value, counter):
return CanData(address, bytes(data), bus)
def supports_standstill_resume(cp):
return (cp is not None and cp.brand == 'toyota' and cp.carFingerprint == CAR.TOYOTA_RAV4 and cp.openpilotLongitudinalControl and
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyParam == 0xB549 and configured(cp))
def amount(cp, cc, cs, accel):
if not (configured(cp) and cp.openpilotLongitudinalControl and cc.longActive and
cs.out.canValid and not cs.out.canTimeout and cs.pedal_ready and
@@ -114,8 +114,12 @@ def parent_modules():
return (dsu_bypass, prius_longitudinal, advert_filter, rav4h_filter, radar_filter)
@cached_config
def configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.GAS_INTERCEPTOR) and _configured(cp))
@cached_config
def _configured(cp):
return marked(cp) and not cp.secOcRequired and any(module.configured(parent_cp(cp)) for module in parent_modules())
@@ -42,8 +42,12 @@ def apply(cp):
cp.alphaLongitudinalAvailable = False
@cached_config
def configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.LONG_FILTER) and _configured(cp))
@cached_config
def _configured(cp):
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
from opendbc.car.toyota import prius_retrofit_advert
@@ -79,16 +83,11 @@ class PriusAdvertCANParser(AdvertFilterCANParser):
super().__init__(*args)
self.hardware_ambiguous = False
def _accept_accessory(self, address, data, bus):
# Buses >= 128 carry Panda TX receipts, not physical RX.
if bus < 128 and (address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) != 4)):
self.hardware_ambiguous = True
return True
def update(self, strings, sendcan=False):
batches = []
for stamp, frames in strings:
frames = list(frames)
for address, data, bus in frames:
# pandad marks TX confirmations/rejections with bus >= 128; they
# are not received hardware (see panda.h CAN_*_BUS_OFFSET).
if bus >= 128:
continue
if address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) != 4):
self.hardware_ambiguous = True
batches.append((stamp, frames))
return super().update(batches, sendcan)
return self._update_filtered(strings, sendcan, self._accept_accessory)
@@ -29,8 +29,12 @@ def configured(cp):
cp.openpilotLongitudinalControl == (cp.safetyConfigs[0].safetyParam == 0x8049))
@cached_config
def eps73_status_configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.LONG_FILTER) and _eps73_status_configured(cp))
@cached_config
def _eps73_status_configured(cp):
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
return configured(cp) and cp.carFingerprint in (CAR.TOYOTA_PRIUS, CAR.TOYOTA_PRIUS_RETROFIT) and cp.safetyConfigs[0].safetyParam in (0x8049, 0x8249)
@@ -1,7 +1,7 @@
"""Original EPS66 Prius smartDSU ownership; the EPS73 retrofit remains distinct."""
from opendbc.can import CANParser
from opendbc.car import structs
from opendbc.car.dashboard_speed_limit import parser_expiry
from opendbc.car.toyota.rav4h_filter import Rav4hCANParser
from opendbc.car.toyota.toyotacan import toyota_checksum
from opendbc.car.toyota.values import CAR, ToyotaFlags
@@ -40,9 +40,11 @@ def apply(cp):
def configured(cp):
if cp is None or not cp.flags & int(ToyotaFlags.LONG_FILTER):
return False
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
if (cp is None or cp.brand != 'toyota' or cp.carFingerprint != CAR.TOYOTA_PRIUS or cp.notCar or cp.passive or
if (cp.brand != 'toyota' or cp.carFingerprint != CAR.TOYOTA_PRIUS or cp.notCar or cp.passive or
cp.dashcamOnly or cp.secOcRequired or not cp.pcmCruise or len(cp.safetyConfigs) != 1 or
cp.steerControlType != structs.CarParams.SteerControlType.torque):
return False
@@ -73,7 +75,7 @@ def source_current(parser, message, signal):
return bound > 0 and stamp > 0 and stamp <= parser._last_update_nanos <= expiry
class PriusSDSUCANParser(Rav4hCANParser):
class PriusSDSUCANParser(CANParser):
"""Keep independent status, MAIN/EPS quality and receiver identity evidence."""
def __init__(self, *args):
super().__init__(*args)
@@ -91,6 +93,8 @@ class PriusSDSUCANParser(Rav4hCANParser):
continue
if address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) == 4):
self.hardware_ambiguous = True
if bus == self.bus and address == 0x2FF and len(data) != 8:
continue
if bus == self.bus and address in (0x1D3, 0x262):
valid = len(data) == 8 and data[-1] == toyota_checksum(address, None, bytearray(data))
if address == 0x1D3:
@@ -34,8 +34,12 @@ def hardware_supported(candidate, fingerprint, car_fw):
return True
@cached_config
def configured(cp):
return bool(cp is not None and cp.flags & int(ToyotaFlags.LONG_FILTER) and _configured(cp))
@cached_config
def _configured(cp):
from opendbc.car.toyota.pedal_composite import parent_cp
cp = parent_cp(cp)
from opendbc.car.toyota import eps8_sdsu, legacy_sdsu
@@ -0,0 +1,19 @@
"""Normal diagnostic wiring evidence for the fixed-selection Mk7 Golf."""
from opendbc.car.volkswagen.mqbcan import volkswagen_mqb_meb_checksum
NORMAL_MQB_LAYOUT = frozenset(((0, 0x9F), (0, 0x12B), (1, 0x86), (1, 0xFD), (1, 0x120)))
def golf_normal_bus_topology(packets):
counters = {key: set() for key in NORMAL_MQB_LAYOUT}
for packet in packets:
for frame in packet:
key = frame.src, frame.address
if key not in counters:
continue
data = frame.dat
if len(data) != 8 or volkswagen_mqb_meb_checksum(frame.address, None, data) != data[0]:
return False
counters[key].add(data[1] & 0xF)
return all(len(seen) >= 2 for seen in counters.values())
@@ -26,17 +26,20 @@ def safety_config(cp):
def _qualified(cp, *, marked_only=False, longitudinal=False):
if (cp is None or cp.brand != "volkswagen" or cp.carFingerprint not in MQB_CARS or
if (cp is None or cp.brand != "volkswagen" or bool(cp.openpilotLongitudinalControl) != longitudinal or
bool(cp.pcmCruise) == longitudinal or cp.carFingerprint not in MQB_CARS or
cp.passive or cp.notCar or cp.dashcamOnly or cp.flags & ~KNOWN_FLAGS or
cp.steerControlType != structs.CarParams.SteerControlType.torque or
cp.transmissionType not in (structs.CarParams.TransmissionType.automatic, structs.CarParams.TransmissionType.manual,
structs.CarParams.TransmissionType.direct) or
cp.networkLocation not in (structs.CarParams.NetworkLocation.gateway, structs.CarParams.NetworkLocation.fwdCamera) or
bool(cp.openpilotLongitudinalControl) != longitudinal or bool(cp.pcmCruise) == longitudinal or
(longitudinal and (cp.networkLocation != structs.CarParams.NetworkLocation.gateway or not cp.alphaLongitudinalAvailable))):
cp.steerControlType != structs.CarParams.SteerControlType.torque):
return False
word = AOL_WORD | (MANUAL_WORD if cp.transmissionType == structs.CarParams.TransmissionType.manual else 0)
word |= DIRECT_WORD if cp.transmissionType == structs.CarParams.TransmissionType.direct else 0
transmission = cp.transmissionType
location = cp.networkLocation
if (transmission not in (structs.CarParams.TransmissionType.automatic, structs.CarParams.TransmissionType.manual,
structs.CarParams.TransmissionType.direct) or
location not in (structs.CarParams.NetworkLocation.gateway, structs.CarParams.NetworkLocation.fwdCamera) or
(longitudinal and (location != structs.CarParams.NetworkLocation.gateway or not cp.alphaLongitudinalAvailable))):
return False
word = AOL_WORD | (MANUAL_WORD if transmission == structs.CarParams.TransmissionType.manual else 0)
word |= DIRECT_WORD if transmission == structs.CarParams.TransmissionType.direct else 0
word |= int(longitudinal)
safety = safety_config(cp)
return (safety is not None and safety.safetyModel == structs.CarParams.SafetyModel.volkswagen and
@@ -0,0 +1,60 @@
from unittest.mock import patch
import pytest
from opendbc.car.can_definitions import CanData
from opendbc.car.car_helpers import get_car
from opendbc.car.volkswagen.discovery import NORMAL_MQB_LAYOUT
from opendbc.car.volkswagen.mqbcan import volkswagen_mqb_meb_checksum
from opendbc.car.volkswagen.values import CAR
from opendbc.car.vin import VIN_UNKNOWN
@pytest.mark.parametrize('selection', ('fixed', 'environment', 'automatic', 'other'))
@pytest.mark.parametrize('layout', ('normal', 'missing', 'echo', 'wrong_dlc', 'bad_crc', 'no_counter_change'))
def test_fixed_golf_queries_normal_buses_with_live_mqb_layout(monkeypatch, selection, layout):
monkeypatch.delenv('SKIP_FW_QUERY', raising=False)
monkeypatch.delenv('FINGERPRINT', raising=False)
identity = CAR.VOLKSWAGEN_GOLF_MK7
forced = identity if selection == 'fixed' else None
if selection == 'environment':
monkeypatch.setenv('FINGERPRINT', identity)
elif selection == 'other':
forced = CAR.SEAT_ATECA_MK1
wires = []
for counter in (7, 8):
frames = []
for bus, address in sorted(NORMAL_MQB_LAYOUT):
target = (bus, address) == (1, 0xFD)
if target and layout == 'missing':
continue
data = bytearray((0, 7 if target and layout == 'no_counter_change' else counter, 0, 0, 0, 0, 0, 0))
data[0] = volkswagen_mqb_meb_checksum(address, None, data)
if target and layout == 'bad_crc':
data[0] ^= 1
if target and layout == 'wrong_dlc':
data.pop()
frames.append(CanData(address, bytes(data), bus + 128 if target and layout == 'echo' else bus))
wires.append(frames)
mux = []
with (patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin,
patch('opendbc.car.car_helpers.get_fw_versions', return_value=[]) as fw,
patch('opendbc.car.car_helpers.get_present_ecus', return_value=set()),
patch('opendbc.car.car_helpers.get_fw_versions_ordered', return_value=[]),
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {0: {0xAD: 8}, 1: {0xFD: 8}, 2: {}})),
patch('opendbc.car.car_helpers.time.sleep')):
car = get_car(lambda **_: wires, lambda _: None, mux.append, True, False, forced_candidate=forced)
if layout == 'normal' and selection in ('fixed', 'environment'):
assert mux and not any(mux)
fw.assert_called_once()
assert fw.call_args.kwargs == {'query_brand': 'volkswagen', 'normal_bus_only': True}
assert vin.call_args.args[2] == (0, 1)
assert car.CP.carFingerprint == identity
assert car.CP.fingerprintSource == 'fixed'
assert car.CP.networkLocation == 'gateway' and car.CP.transmissionType == 'automatic'
assert car.CP.openpilotLongitudinalControl and car.CP.safetyConfigs[0].safetyParam == 1
else:
assert any(mux)
fw.assert_not_called()
@@ -1,6 +1,7 @@
"""Physical MAIN intent for qualified angle and Impreza torque AOL; no ordinary controls grant."""
import pytest
from opendbc.car import structs
from opendbc.safety.tests.libsafety import libsafety_py
from opendbc.safety.tests import test_subaru_stock_aol as stock_module
@@ -122,9 +123,15 @@ def test_legacy_2025_cvt_manual_gears():
item = stock_module.TestSubaruStockAol(methodName='runTest')
item.setUp()
try:
debug = item.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0
for param in (145, 17, 1041, 2065, 3089):
item.configure(param)
neutral(item)
if not debug and param in (1041, 3089):
assert item.feed() == 0
assert item.feed(gear=137) == 0
assert not item.safety.safety_tx_hook(item.frame('ES_LKAS_ANGLE', {}, 0))
continue
assert item.feed() == 1
for gear in (137, 145, 153, 161, 169, 177, 185, 193):
assert item.feed(gear=gear) == 1
Binary file not shown.
Binary file not shown.
+1
View File
@@ -254,6 +254,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"AlphaLongitudinalEnabled", {PERSISTENT, BOOL}},
{"ExperimentalMode", {PERSISTENT, BOOL}},
{"ExperimentalSpeedNudge", {PERSISTENT, BOOL, "0"}},
{"ConvergeToSetSpeed", {PERSISTENT, BOOL, "0"}},
{"AggressivePersonalityBoost", {PERSISTENT, FLOAT, "100"}},
{"StandardPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
{"RelaxedPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
+5 -1
View File
@@ -4,6 +4,7 @@ from opendbc.car import DT_CTRL, structs
from opendbc.car.car_helpers import interfaces
from opendbc.car.interfaces import MAX_CTRL_SPEED
from opendbc.car.toyota.values import ToyotaFlags
from opendbc.car.toyota.pedal import supports_standstill_resume
from openpilot.selfdrive.selfdrived.events import Events
from openpilot.starpilot.car.events import event_rules, unsupported_gear
@@ -19,6 +20,7 @@ class CarEvents:
def __init__(self, CP: structs.CarParams):
self.CP = CP
self.event_rules = event_rules(CP)
self.toyota_pedal_resume = supports_standstill_resume(CP)
from opendbc.car.gm.values import is_volt_cc_profile
self.volt_cc_profile = CP.brand == "gm" and is_volt_cc_profile(CP)
@@ -69,7 +71,9 @@ class CarEvents:
# TODO: when we check for unexpected disengagement, check gear not S1, S2, S3
if self.CP.openpilotLongitudinalControl:
# Only can leave standstill when planner wants to move
if (not self.CP.autoResumeSng and CS.standstill and CS.cruiseState.standstill and not CS.brakePressed and
pedal_resuming = (self.toyota_pedal_resume and CC.longActive and CC.cruiseControl.resume and CC.actuators.accel > 0 and
CS.canValid and not CS.canTimeout and not CS.accFaulted and not CS.stockAeb and not CS.gasPressed)
if (not self.CP.autoResumeSng and not pedal_resuming and CS.standstill and CS.cruiseState.standstill and not CS.brakePressed and
(CC.cruiseControl.resume or self.CP.flags & ToyotaFlags.HYBRID.value)):
events.add(EventName.resumeRequired)
if CS.vEgo < self.CP.minEnableSpeed:
+4 -1
View File
@@ -114,7 +114,9 @@ class Controls:
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing
self.volkswagen_smoothing = ControlSmoothing(self.CP)
from openpilot.starpilot.car.hyundai.model_smoothing import seconds as kona_smoothing
from openpilot.starpilot.car.gm.model_smoothing import seconds as bolt_smoothing
self.kona_smoothing = kona_smoothing(self.CP)
self.bolt_smoothing = bolt_smoothing(self.CP)
self.CI = interfaces[self.CP.carFingerprint](self.CP)
self.hyundai_lateral_fault = LateralFaultLatch(self.CP.carFingerprint)
@@ -649,7 +651,8 @@ class Controls:
kona_tau = getattr(self, "kona_smoothing", 0.)
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
lat_delay = self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) + kona_tau
lat_delay = (self.sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_smooth_seconds(CS.vEgo, control_maximum(self)) +
kona_tau + getattr(self, "bolt_smoothing", 0.))
if getattr(self, "volkswagen_smoothing", None) is not None:
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
@@ -202,7 +202,7 @@ class LongitudinalPlanner:
lead_approach_key: LeadApproachKey | None = None,
force_stop_provider: Callable[[float], StopPlan] | None = None,
faster_lead_takeoff: bool = False, takeoff_drive_id: int = 0,
now_ns: int | None = None, drive_id: int = 0, wheel_coast=None, experimental_speed_nudge: bool = True):
now_ns: int | None = None, drive_id: int = 0, wheel_coast=None, experimental_speed_nudge: bool = False):
if curve_ceiling is not None and curve_provider is not None:
raise ValueError('choose explicit Curve ceiling or same-cycle provider')
if self.plan_drive_id != drive_id:
@@ -585,20 +585,28 @@ class LongitudinalPlanner:
not all(getattr(sm, health, {}).get(service, False)
for health in ('alive', 'valid', 'freq_ok') for service in ('modelV2', 'carState', 'radarState'))
)
use_nudge = traffic_mode is True or relaxed and experimental_speed_nudge is True
converge = experimental_speed_nudge is True
convergence_blocked = converge and (self.force_stop_plan.should_stop or
self.force_stop_plan.approach_distance_m > 0.0 or
downhill_error is not None or
(coast_plan is not None and (coast_plan.force_decel or coast_plan.pulse_coasting or
coast_plan.brake_floor is not None)))
encouraged_model = self.encouragement.update(
sm, self.CP, now_ns=sample_now_ns, drive_id=drive_id, dt=self.dt, target_speed=v_cruise,
model_accel=output_a_target_e2e, mpc_accel=output_a_target_mpc, cruise_accel=self.a_cruise,
lateral_accel=(v_ego ** 2 * steer_angle_without_offset * CV.DEG_TO_RAD / (self.CP.steerRatio * self.CP.wheelbase)
if self.CP.steerRatio > 0 and self.CP.wheelbase > 0 else math.inf),
blocked=bool(boost_blocked or not use_nudge or self.personality_boost_scale == 0.0),
scale=self.personality_boost_scale)
blocked=bool(boost_blocked or convergence_blocked or
not (converge or traffic_mode is True) or self.personality_boost_scale == 0.0),
scale=self.personality_boost_scale, converge=converge,
follow_seconds=float(self.mpc.params[0, 4]) if converge else None)
if boost_blocked or relaxed or traffic_mode is True or self.personality_boost_scale == 0.0:
self.personality_accel_boost.reset()
else:
boosted_model = self.personality_accel_boost.update(sm, output_a_target_e2e, 0.0)
scale = self.personality_boost_scale if output_a_target_e2e > 0.0 else min(self.personality_boost_scale, 1.0)
encouraged_model = output_a_target_e2e + scale * (boosted_model - output_a_target_e2e)
personality_model = output_a_target_e2e + scale * (boosted_model - output_a_target_e2e)
encouraged_model = max(personality_model, encouraged_model)
manual_model = self.accel_boost.update(sm, output_a_target_e2e, output_a_target_mpc, self.a_cruise)
output_a_target_e2e = output_a_target_e2e + curve_offset if curve_offset < 0.0 else max(manual_model, encouraged_model)
+1 -1
View File
@@ -232,7 +232,7 @@ def update_curve_frame(planner: LongitudinalPlanner, sm, CP, now_ns: int, *, hos
event: CurveDriverEvent | None = None, lane_change_policy=None,
global_braking_response: str | None = None, selected_profiles=None, conditional_handoff: ConditionalHandoff | None = None,
lead_approach_key: LeadApproachKey | None = None, force_stop_provider=None,
faster_lead_takeoff: bool = False, wheel_coast=None, experimental_speed_nudge: bool = True):
faster_lead_takeoff: bool = False, wheel_coast=None, experimental_speed_nudge: bool = False):
"""One model cycle: MPC chooses follow time, then Curve samples and receives winner feedback."""
if host is None:
planner.update(sm, cruise_ceiling=cruise_ceiling, profile_tuning=profile_tuning, traffic_mode=traffic_mode,
+5 -2
View File
@@ -56,6 +56,7 @@ from openpilot.starpilot.lateral.lane_change_status_wire import (
from openpilot.starpilot.models.receipt import ModelReceiptOwner
from openpilot.starpilot.car.volkswagen.model_smoothing import seconds as volkswagen_smoothing
from openpilot.starpilot.car.hyundai.model_smoothing import seconds as kona_smoothing
from openpilot.starpilot.car.gm.model_smoothing import seconds as bolt_smoothing
from openpilot.starpilot.models.status import ModelVariant
from openpilot.starpilot.models.startup import report_load_timeout, wait_for_chestnut_power
from openpilot.starpilot.models.recovery import STARTUP_FALLBACK_EXIT
@@ -390,6 +391,7 @@ def main(demo=False):
from openpilot.starpilot.car.subaru.smoothing import read_frozen, seconds as subaru_smooth_seconds, filter_action
subaru_smoothing = read_frozen(CP, params)
kona_tau = kona_smoothing(CP)
bolt_tau = bolt_smoothing(CP)
st = time.monotonic()
cloudlog.warning("loading model")
@@ -581,7 +583,8 @@ def main(demo=False):
v_ego = max(sm["carState"].vEgo, 0.)
subaru_tau = subaru_smooth_seconds(v_ego, subaru_smoothing)
volkswagen_tau = volkswagen_smoothing(CP, receipt_owner.load)
lat_delay = sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + subaru_tau + volkswagen_tau + kona_tau
steering_smoothing = subaru_tau + volkswagen_tau + kona_tau + bolt_tau
lat_delay = sm["lateralDelay"].lateralDelay + LAT_SMOOTH_SECONDS + steering_smoothing
if sm.updated["extrinsicsCalibration"] and sm.seen['narrowRoadCameraState'] and sm.seen['deviceState']:
device_from_calib_euler = np.array(sm["extrinsicsCalibration"].rpyCalib, dtype=np.float32)
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['narrowRoadCameraState'].sensor))]
@@ -677,7 +680,7 @@ def main(demo=False):
action = laboratory_action
else:
action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
filter_action(action, prev_action, v_ego, subaru_tau + volkswagen_tau + kona_tau)
filter_action(action, prev_action, v_ego, steering_smoothing)
prev_action = action
fill_model_msg(modelv2_send, model_output, action,
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
@@ -6,8 +6,12 @@ import numpy as np
import pytest
from openpilot.cereal import log
from opendbc.car.gm.values import CAR
from openpilot.selfdrive.controls.lib.drive_helpers import smooth_value
from openpilot.selfdrive.modeld.constants import LAT_SMOOTH_SECONDS
from openpilot.starpilot.car.gm.model_smoothing import seconds as bolt_smoothing
from openpilot.starpilot.car.subaru.smoothing import filter_action
from openpilot.starpilot.longitudinal.tests.test_bolt_cc_integrator import params as bolt_params
def action_function():
@@ -46,3 +50,20 @@ def test_legacy_plan_action_is_unchanged():
assert len(calls) == 1
assert action.desiredCurvature == pytest.approx(smooth_value(0.02, 0.01, LAT_SMOOTH_SECONDS))
assert action.desiredAcceleration == pytest.approx(smooth_value(0.4, 0.1, 0.3))
def test_bolt_interceptor_restores_legacy_smoothing_without_touching_longitudinal_action():
previous = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=.1)
for candidate, pedal, seconds in (
(CAR.CHEVROLET_BOLT_CC_2017, True, 0.),
(CAR.CHEVROLET_BOLT_CC_2018_2021, False, 0.),
(CAR.CHEVROLET_BOLT_CC_2018_2021, True, .1),
(CAR.CHEVROLET_BOLT_CC_2022_2023, True, 0.),
):
tau = bolt_smoothing(bolt_params(candidate, pedal=pedal))
assert tau == seconds
action = log.ModelDataV2.Action(desiredCurvature=.0016, desiredAcceleration=-.1, shouldStop=True)
filter_action(action, previous, 34., tau)
assert action.desiredCurvature == pytest.approx(smooth_value(.0016, .001, seconds))
assert action.desiredAcceleration == pytest.approx(-.1)
assert action.shouldStop
Binary file not shown.
+20 -8
View File
@@ -107,6 +107,9 @@ class SelfdriveD:
cloudlog.info("selfdrived got CarParams")
else:
self.CP = CP
# The Params reader owns its immutable bytes. Injected CarParams can change.
self._startup_cp = self.CP if CP is None else None
self._startup_cp_identity = cp_identity(self.CP) if self._startup_cp is not None else None
self.aol_replay = feature_enabled(self.params, self.CP, 'aol', os.environ)
self.ordinary_axis_ack_required = axis_policy_for(self.CP).ordinary_axis_ack_required
@@ -124,8 +127,11 @@ class SelfdriveD:
self.aol_transport_pause = TransportPause(self.CP, self.aol_session_id)
self.aol_fault_reason = 'none'
self.steering_authority_unavailable = False
from openpilot.starpilot.car.gm.aol import steering_raw_projection_owner
self._startup_steering_monitored = self.CP.brand == 'gm' and monitored_profile(self.CP)
self._startup_raw_projection = steering_raw_projection_owner(self.CP, monitored=self._startup_steering_monitored)
self.steering_companion = (SteeringCompanion(messaging.sub_sock('starpilotCarState', conflate=False))
if monitored_profile(self.CP) else None)
if self._startup_steering_monitored else None)
self.force_stop_hold_alert = HoldAlertState()
self.aol_car_state_log_ns = 0
self.aol_last_intent = None
@@ -293,7 +299,8 @@ class SelfdriveD:
return update_big_model_status(self)
def _update_steering_authority(self, CS):
if self.CP.brand != 'gm' or not monitored_profile(self.CP):
fixed_cp = self.CP is getattr(self, '_startup_cp', None)
if self.CP.brand != 'gm' or not (self._startup_steering_monitored if fixed_cp else monitored_profile(self.CP)):
self.steering_authority_unavailable = False
return
companion = getattr(self, 'steering_companion', None)
@@ -307,15 +314,17 @@ class SelfdriveD:
source_current = bool(getattr(self, 'conditional_car_state_valid', False) and CS.canValid and not CS.canTimeout and
0 < source_ns <= now_ns and now_ns - source_ns <= INTENT_MAX_AGE_NS)
from openpilot.starpilot.car.gm.aol import steering_raw_projection_owner, steering_source_gap_intent_only
raw_projection = drained and (self._startup_raw_projection if fixed_cp else
steering_raw_projection_owner(self.CP, monitored=True))
pair = companion.current(self.sm, source_ns=source_ns, now_ns=now_ns, drain=False,
allow_raw_projection=steering_raw_projection_owner(self.CP)) if drained else None
allow_raw_projection=raw_projection) if drained else None
if not source_current:
pair = None
previous_axes = self.aol_axis_decision
expected_active = self.active or previous_axes.lateral_active or previous_axes.longitudinal_active
if pair is not None:
self.steering_authority_unavailable = pair
elif expected_active and not (drained and steering_source_gap_intent_only(self, CS, companion, now_ns)):
elif expected_active and not (drained and steering_source_gap_intent_only(self, CS, companion, now_ns, raw_projection=raw_projection)):
self.steering_authority_unavailable = True
if getattr(self, 'steering_authority_unavailable', False):
self.events.add(EventName.controlsMismatch)
@@ -2327,15 +2336,18 @@ class SelfdriveD:
not self.events.contains(ET.OVERRIDE_LONGITUDINAL)))
if not hasattr(self, 'aol_transport_pause'):
self.aol_transport_pause = TransportPause(self.CP, self.aol_session_id)
current_cp_identity = (self._startup_cp_identity if self.CP is getattr(self, '_startup_cp', None) else cp_identity(self.CP))
model_ready = bool(self.sm.all_checks(['modelV2', 'extrinsicsCalibration']) and
self.sm['extrinsicsCalibration'].calStatus == log.ExtrinsicsCalibration.Status.calibrated)
pause, upgraded = self.aol_transport_pause.observe(
current_cp_identity=current_cp_identity,
cp=self.CP, session=self.aol_session_id, sm=self.sm, cs=CS, native=native, now_ns=now_ns,
companion=getattr(self, 'aol_intent_companion', None), previous_intent=previous_intent, intent=intent,
expired_healthy_source=getattr(self, 'aol_expired_healthy_source', False),
previously_active=previous.lateral_active, hard_fault=bool(
self.aol_selected_pair_future or self.aol_authority_lost or lost_active_aol or lost_permission or aol_immediate_disable or
any(event.softDisable and event.name not in LONGITUDINAL_ONLY_EVENTS for event in self.events.to_msg())),
model_ready=bool(self.sm.all_checks(['modelV2', 'extrinsicsCalibration']) and
self.sm['extrinsicsCalibration'].calStatus == log.ExtrinsicsCalibration.Status.calibrated),
model_ready=model_ready,
user_disable=self.events.contains(ET.USER_DISABLE))
if source_current:
self.observe_ordinary_source_metadata(CS, intent, self.aol_transport_pause.observed_native, now_ns)
@@ -2355,10 +2367,10 @@ class SelfdriveD:
source_expiry_events.add(EventName.commIssue)
availability_events += source_expiry_events.to_msg()
availability = self.aol_availability_pause.observe(
current_cp_identity=current_cp_identity,
cp=self.CP, session=self.aol_session_id, sm=self.sm, cs=CS, native=native, now_ns=now_ns,
companion=intent_companion, intent=intent if intent is not None else retained_intent, events=availability_events,
model_ready=bool(self.sm.all_checks(['modelV2', 'extrinsicsCalibration']) and
self.sm['extrinsicsCalibration'].calStatus == log.ExtrinsicsCalibration.Status.calibrated),
model_ready=model_ready,
source_current=source_current, source_expired=publication_expiry, prior_lateral_active=previous.lateral_active,
hard_fault=bool(self.aol_selected_pair_future or self.aol_authority_lost or lost_active_aol or
lost_companion and not publication_expiry or lost_permission or upgraded),
+7 -4
View File
@@ -102,6 +102,7 @@ class TransportPauseFeedback:
self.session = ''
self.sequence = 0
self.subaru_paddle_denial = None
self.subaru_paddle_eps_ns = 0
self.signature = None
self.paused = False
self.qualified = False
@@ -737,7 +738,7 @@ class TransportPauseFeedback:
if reason not in ('none', 'availabilityPause') or reason == 'none' and not availability_only(events):
return False
if not (latched and current and continuity and not self.paused and not self.pending_event and
cp_identity(cp) == self.cp and intent_producer_session and
intent_producer_session and
getattr(axis, 'intentProducerSessionId', '') == intent_producer_session == self.availability_producer and
int(getattr(axis, 'intentIntegrityEpoch', 0)) == self.availability_epoch and
self.session and
@@ -1196,6 +1197,7 @@ class TransportPauseFeedback:
self.cold_main_sparse_waiting = False
self.subaru_braked_main = None
self.subaru_paddle_denial = None
self.subaru_paddle_eps_ns = 0
self.subaru_eps_brake_event_ns = 0
stamp = int(sm.logMonoTime['aolAxisState'])
reason = str(axis.faultReason)
@@ -1230,8 +1232,8 @@ class TransportPauseFeedback:
self.retention_pending = not self.retention_qualified
return False
from openpilot.starpilot.car.gm.aol import sdgm_alpha_lateral_owner
if (sdgm_alpha_lateral_owner(cp) and latched and current and continuity and self.signature is not None and
signature[14:16] != self.signature[14:16]):
if (latched and current and continuity and self.signature is not None and
signature[14:16] != self.signature[14:16] and sdgm_alpha_lateral_owner(cp)):
self.failed = True
return True
if ((self.cold_main_wait_ns or self.cold_park_waiting) and current and continuity and self.signature is not None and
@@ -1479,7 +1481,7 @@ class TransportPauseFeedback:
cs.cruiseState.available and not cs.doorOpen and not cs.vehicleSensorsInvalid and not cs.steeringDisengage and
not cs.regenBraking and
sm.seen['aolAxisState'] and sm.valid['aolAxisState'] and sm.alive['aolAxisState'] and
axis.qualified and str(axis.faultSessionId) == self.session and cp_identity(cp) == self.cp and
axis.qualified and str(axis.faultSessionId) == self.session and same_cp and
0 < stamp == axis.observedMonoTime < axis.validUntilMonoTime < now_ns)
brake_native = (self._honda_brake_lateral_current(sm, cp, cs, axis, now_ns,
latched=latched, brake_source_ns=brake_source_ns) if (current or honda_driver_pending) and continuity else None)
@@ -1692,6 +1694,7 @@ class TransportPauseFeedback:
if cp.brand == 'subaru' and self.availability_producer:
self.subaru_lateral_grant_ns = max(self.subaru_lateral_grant_ns, int(native.observedMonoTime))
self.subaru_braked_main = None
self.subaru_paddle_eps_ns = 0
self.subaru_eps_brake_event_ns = 0
self.lag_withdrawal_ns = 0
self.cold_main_wait_ns = 0
@@ -18,10 +18,12 @@ class TransportPause:
self.epoch = None
def observe(self, *, cp, session, sm, cs, native, now_ns, companion, previous_intent,
intent, expired_healthy_source, previously_active, hard_fault, model_ready, user_disable):
intent, expired_healthy_source, previously_active, hard_fault, model_ready, user_disable,
current_cp_identity=None):
from openpilot.starpilot.aol import transport_pause as transport
self.observed_native = None
context_current = bool(transport.cp_identity(cp) == self.cp and session == self.session and model_ready and companion is not None)
identity = transport.cp_identity(cp) if current_cp_identity is None else current_cp_identity
context_current = bool(identity == self.cp and session == self.session and model_ready and companion is not None)
if context_current:
self.observed_native = transport._healthy_transport_native(sm, cp, cs, session, now_ns, native)
if self.observed_native is None and cp.brand == 'ford':
@@ -73,11 +75,13 @@ class AvailabilityPause:
self.active = False
def observe(self, *, cp, session, sm, cs, native, now_ns, companion, intent,
events, model_ready, source_current, prior_lateral_active, hard_fault, healthy_native, source_expired=False):
events, model_ready, source_current, prior_lateral_active, hard_fault, healthy_native, source_expired=False,
current_cp_identity=None):
from openpilot.starpilot.aol import transport_pause as transport
try:
healthy = healthy_native
eligible = bool(transport.cp_identity(cp) == self.cp and
identity = transport.cp_identity(cp) if current_cp_identity is None else current_cp_identity
eligible = bool(identity == self.cp and
session == self.session and not hard_fault and model_ready and (source_current or source_expired) and companion is not None and
companion.last_drain_ok and intent is not None and intent.allowedLatch and intent.lateralArmed and
healthy is not None and healthy.requestedLateral and healthy.lateralAllowed and healthy.pandaInventory)
+38 -15
View File
@@ -1,4 +1,4 @@
"""Bounded installation of published sound packs while the car is parked."""
"""Bounded management of published sound packs while the car is parked."""
import fcntl
import hashlib
@@ -42,8 +42,9 @@ class _Cancelled(Exception):
class SoundDownloads:
def __init__(self, parked, root: Path = PACK_ROOT, catalog_path: Path = CATALOG_PATH, opener=None):
def __init__(self, parked, root: Path = PACK_ROOT, catalog_path: Path = CATALOG_PATH, opener=None, selection=lambda: None):
self.parked = parked
self.selection = selection
self.root = Path(root)
self.opener = opener or urllib.request.urlopen
self._lock = threading.Lock()
@@ -104,6 +105,24 @@ class SoundDownloads:
if not self._job or data.get("job") != self._job["id"] or self._job["state"] not in ("downloading", "verifying"):
raise SoundDownloadError("download job not active", 409)
self._cancel.set()
elif command == "delete":
slug = data.get("pack")
if set(data) != {"pack"} or not isinstance(slug, str) or slug not in self._packs:
raise SoundDownloadError("unknown sound pack")
if not self._safe_parked():
raise SoundDownloadError("park the car before removing a sound pack", 409)
if self._thread and self._thread.is_alive():
raise SoundDownloadError("a download is already running", 409)
selected = self.selection()
if selected is None or slug == selected:
raise SoundDownloadError("select a different sound pack before removing this one", 409)
self._prepare_root()
with self._acquire_storage_lock():
if not cleanup_removed_packs(self.root, parked=lambda: self._safe_parked() and self.selection() == selected,
downloaded=slug):
raise SoundDownloadError("sound pack could not be removed", 409)
if self._job and self._job["pack"] == slug:
self._job = None
elif command == "download":
if set(data) != {"pack"}:
raise SoundDownloadError("invalid request")
@@ -117,19 +136,7 @@ class SoundDownloads:
self._prepare_root()
if (self.root / slug).exists() or (self.root / slug).is_symlink():
raise SoundDownloadError("sound pack already exists", 409)
try:
descriptor = os.open(self.root / ".sound-download.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
os.close(descriptor)
raise OSError("unsafe lock file")
lock_file = os.fdopen(descriptor, "r+b")
except OSError as exc:
raise SoundDownloadError("sound storage unavailable", 503) from exc
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
lock_file.close()
raise SoundDownloadError("a download is already running", 409) from exc
lock_file = self._acquire_storage_lock()
if (self.root / slug).exists() or (self.root / slug).is_symlink():
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
@@ -145,6 +152,22 @@ class SoundDownloads:
raise SoundDownloadError("unknown action")
return self.snapshot()
def _acquire_storage_lock(self):
try:
descriptor = os.open(self.root / ".sound-download.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
os.close(descriptor)
raise OSError("unsafe lock file")
lock_file = os.fdopen(descriptor, "r+b")
except OSError as exc:
raise SoundDownloadError("sound storage unavailable", 503) from exc
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
lock_file.close()
raise SoundDownloadError("a download is already running", 409) from exc
return lock_file
def _safe_parked(self) -> bool:
try:
return bool(self.parked())
+12 -4
View File
@@ -77,8 +77,8 @@ def migrate_removed_selection(params, root: Path = PACK_ROOT) -> bool:
authorized=lambda: True, temp_prefix=".sound-pack-migration-").verified
def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
"""Bounded parked migration over captured directory descriptors.
def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked, downloaded: str | None = None) -> tuple[str, ...]:
"""Bounded parked sound-pack cleanup over captured directory descriptors.
Enumerate at most 256 root entries and 64 pack entries, depth 4 / 96 MiB.
Keep captured descriptors, never follow links, and check entry identities
@@ -112,7 +112,9 @@ def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
return ()
names.append(entry.name)
for name in names:
if name.casefold() not in REMOVED_PACKS or not safe():
if (name != downloaded if downloaded is not None else name.casefold() not in REMOVED_PACKS) or not safe():
continue
if downloaded is not None and pack_directory(name, root) is None:
continue
expected = os.stat(name, dir_fd=root_fd, follow_symlinks=False)
@@ -121,7 +123,7 @@ def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
inode(os.stat(name, dir_fd=root_fd, follow_symlinks=False)) == inode(expected))
if stat.S_ISLNK(expected.st_mode):
if guard():
if downloaded is None and guard():
os.unlink(name, dir_fd=root_fd)
removed.append(name)
continue
@@ -163,6 +165,12 @@ def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
return node
tree = plan(pack_fd, 1)
if downloaded is not None:
children = tree[2]
if (len(children) != 1 or children[0][0] != 'sounds' or children[0][2] is None or
not children[0][2][2] or any(not filename.endswith('.wav') or not stat.S_ISREG(saved.st_mode)
for filename, saved, _ in children[0][2][2])):
continue
def same_entries(directory_fd, expected_names):
observed = set()
@@ -54,14 +54,14 @@ class SoundDownloadTests(unittest.TestCase):
self.parked = [True]
self.managers = []
def manager(self, payload, opener=None, slug="duck", digest=None, size=None):
def manager(self, payload, opener=None, slug="duck", digest=None, size=None, selection=lambda: None):
self.catalog.write_text(json.dumps({"version": 1, "packs": [{
"id": slug, "name": "Duck", "path": f"theme/Themes/{slug}/sounds.zip",
"size": len(payload) if size is None else size,
"sha256": hashlib.sha256(payload).hexdigest() if digest is None else digest,
}]}))
manager = SoundDownloads(lambda: self.parked[0], self.root, self.catalog,
opener=opener or (lambda url, timeout: io.BytesIO(payload)))
opener=opener or (lambda url, timeout: io.BytesIO(payload)), selection=selection)
self.managers.append(manager)
self.addCleanup(manager.close)
return manager
@@ -75,6 +75,35 @@ class SoundDownloadTests(unittest.TestCase):
time.sleep(.005)
self.fail("download did not finish")
def test_remove_only_parked_inactive_download(self):
selected = ["duck"]
manager = self.manager(archive({"engage.wav": wav()}), selection=lambda: selected[0])
manager.action("download", {"pack": "duck"})
self.assertTrue(self.finish(manager)["packs"][0]["installed"])
manager._thread.join(timeout=2)
for pack in ("stock", "starpilot", "../duck"):
with self.assertRaises(SoundDownloadError):
manager.action("delete", {"pack": pack})
with self.assertRaisesRegex(SoundDownloadError, "select a different"):
manager.action("delete", {"pack": "duck"})
selected[0] = "stock"
self.parked[0] = False
with self.assertRaisesRegex(SoundDownloadError, "park the car"):
manager.action("delete", {"pack": "duck"})
self.parked[0] = True
keep = self.root / "duck" / "unrelated.txt"
keep.write_text("keep")
with self.assertRaisesRegex(SoundDownloadError, "could not be removed"):
manager.action("delete", {"pack": "duck"})
self.assertEqual(keep.read_text(), "keep")
keep.unlink()
result = manager.action("delete", {"pack": "duck"})
self.assertFalse(result["packs"][0]["installed"])
self.assertIsNone(result["job"])
self.assertFalse((self.root / "duck").exists())
manager.action("download", {"pack": "duck"})
self.assertTrue(self.finish(manager)["packs"][0]["installed"])
def test_install_and_loader(self):
payload = archive({"sounds/": b"", "sounds/engage.wav": wav(2000),
"sounds/warning_soft.wav": wav(3000),
+5 -4
View File
@@ -48,19 +48,20 @@ def sdgm_alpha_lateral_owner(cp) -> bool:
return bool(qualified_gm(cp) and aol_enabled(cp) and is_volt_sdgm_accepted_envelope(cp))
def steering_raw_projection_owner(cp) -> bool:
def steering_raw_projection_owner(cp, *, monitored=None) -> bool:
"""Qualified non-pedal Volt owners consume their exact raw steering receipt."""
from opendbc.car.gm.steering_authority import monitored_profile
return bool(qualified_gm(cp) and monitored_profile(cp))
return bool((monitored_profile(cp) if monitored is None else monitored) and qualified_gm(cp))
def steering_source_gap_intent_only(owner, cs, companion, now_ns: int) -> bool:
def steering_source_gap_intent_only(owner, cs, companion, now_ns: int, *, raw_projection=None) -> bool:
"""Recognize lost Card publication; never supply a current steering receipt."""
from openpilot.starpilot.aol.runtime import INTENT_MAX_AGE_NS
service = 'starpilotCarState'
sdgm = sdgm_alpha_lateral_owner(owner.CP)
if (not (is_volt_ascm_longitudinal(owner.CP) or sdgm) or not steering_raw_projection_owner(owner.CP) or
if (not (is_volt_ascm_longitudinal(owner.CP) or sdgm) or
not (steering_raw_projection_owner(owner.CP) if raw_projection is None else raw_projection) or
getattr(owner, 'steering_authority_unavailable', False) or
getattr(owner, 'car_state_samples', ())):
return False
@@ -0,0 +1,7 @@
from opendbc.car.gm.values import CAR, is_bolt_pedal_profile
def seconds(cp):
if cp.carFingerprint == CAR.CHEVROLET_BOLT_CC_2018_2021 and is_bolt_pedal_profile(cp):
return .1
return 0.
@@ -13,6 +13,7 @@ from openpilot.cereal import log
from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan, smooth_value
from openpilot.selfdrive.modeld.constants import ModelConstants
from openpilot.starpilot.car.hyundai.model_smoothing import seconds
from openpilot.starpilot.car.gm.model_smoothing import seconds as bolt_smoothing
from openpilot.starpilot.car.subaru.smoothing import filter_action
@@ -101,12 +102,12 @@ def test_common_model_join_keeps_filter_and_lookahead_matched(alpha):
cp = setup(alpha)
action = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=-.25, shouldStop=True)
previous = log.ModelDataV2.Action(desiredCurvature=0.)
env = {'CP': cp, 'receipt_owner': SimpleNamespace(load=object()), 'v_ego': 18., 'subaru_smoothing': 0.,
env = {'CP': cp, 'bolt_smoothing': bolt_smoothing, 'receipt_owner': SimpleNamespace(load=object()), 'v_ego': 18., 'subaru_smoothing': 0.,
'subaru_smooth_seconds': lambda *args: 0., 'volkswagen_smoothing': lambda *args: 0.,
'kona_smoothing': seconds, 'kona_tau': seconds(cp), 'LAT_SMOOTH_SECONDS': 0.,
'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.3)}, 'action': action, 'prev_action': previous,
'filter_action': filter_action, 'frame_delay': .05, 'action_delay': .025, 'inputs': {}, 'np': np}
wanted = {'kona_tau', 'subaru_tau', 'volkswagen_tau', 'lat_delay', 'lat_action_t'}
wanted = {'kona_tau', 'subaru_tau', 'volkswagen_tau', 'bolt_tau', 'steering_smoothing', 'lat_delay', 'lat_action_t'}
nodes = [n for n in ast.walk(tree) if isinstance(n, ast.Assign) and
(any(isinstance(t, ast.Name) and t.id in wanted for t in n.targets) or
any(isinstance(t, ast.Subscript) and ast.unparse(t) == "inputs['lateral_control_params']" for t in n.targets))]
+35 -13
View File
@@ -195,23 +195,33 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
if retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, latched=latched, producer=producer):
return True
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
from openpilot.starpilot.car.subaru.aol import known_paddle_pause
previous = feedback.signature
paddle = known_paddle_pause(cp, state)
# Keep the OFF proof through the same warning if the driver returns to Drive before it clears.
last_paddle_eps = getattr(feedback, 'subaru_paddle_eps_ns', 0)
held_off = (0 < last_paddle_eps <= now_ns <= last_paddle_eps + AXIS_MAX_AGE_NS and
(paddle or state.gearShifter == structs.CarState.GearShifter.drive))
paddle_eps = (paddle and state.steerFaultTemporary) or held_off
if paddle_eps and (previous is None or any(previous[9:13]) or axis.desiredLateral or axis.lateralActive):
return False
if (not qualified(cp, marked_only=True) or cp.openpilotLongitudinalControl or
not latched or feedback.failed or feedback.paused or
feedback.retention_started_ns or feedback.source_retention_started_ns or
previous is None or not feedback.session or not producer or
previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or
previous[10] or previous[12] or previous[9] and not previous[11] or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
previous[10] or previous[12] or previous[9] and not previous[11] or not (previous[13] or held_off) or
previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or
str(axis.faultReason) != 'none' or not axis.nativeAcknowledged or
str(axis.faultReason) != 'none' or not (axis.nativeAcknowledged or paddle_eps) or
str(axis.mode) != ('lateralOnly' if axis.lateralActive else 'off') or
axis.lateralActive and not axis.desiredLateral or axis.desiredLongitudinal or axis.longitudinalActive or
not 0 < previous[8] <= previous[2] <= now_ns <= previous[4] or now_ns - previous[8] > AXIS_MAX_AGE_NS or
not previous[8] <= axis.sourceCarStateMonoTime <= stamp <= now_ns or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
not state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
not (state.steerFaultTemporary or held_off) or state.steerFaultPermanent or not state.canValid or state.canTimeout or
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or
(state.gearShifter != structs.CarState.GearShifter.drive and
state.steeringDisengage or state.buttonEvents or state.gasPressed and not paddle_eps or state.regenBraking or
(not paddle and state.gearShifter != structs.CarState.GearShifter.drive and
not (cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025} and
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
not state.cruiseState.available or state.cruiseState.enabled or
@@ -222,7 +232,10 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
pending = feedback.pending_event
matched = axis.faultEventMonoTime == event_ns <= stamp
joined_event = max(axis.faultEventMonoTime, event_ns)
joining = bool(0 < restriction and previous[6] in (restriction, pending) and
paddle_onset = bool(paddle and not restriction and not pending and
0 < min(axis.faultEventMonoTime, event_ns) == previous[6] < joined_event <= now_ns and
now_ns - joined_event <= AXIS_MAX_AGE_NS)
joining = paddle_onset or bool(0 < restriction and previous[6] in (restriction, pending) and
min(axis.faultEventMonoTime, event_ns) in (restriction, pending) and
restriction < joined_event <= now_ns and now_ns - joined_event <= AXIS_MAX_AGE_NS and
(not pending or joined_event >= pending))
@@ -232,17 +245,23 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or not (matched or joining) or
any(event.immediateDisable or
event.softDisable and event.name != log.OnroadEvent.EventName.steerTempUnavailable or
event.softDisable and event.name != log.OnroadEvent.EventName.steerTempUnavailable and
not (paddle_eps and event.name == log.OnroadEvent.EventName.wrongGear) or
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
(state.brakePressed or feedback.subaru_eps_brake_event_ns == event_ns) and
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
return False
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or
paddle_eps and not native_off(native) or
axis.lateralActive and not native.lateralAllowed or native.requestedLongitudinal or native.longitudinalAllowed or
native.observedMonoTime < feedback.healthy_native_ns or
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
return False
if paddle_eps and state.steerFaultTemporary:
feedback.subaru_paddle_eps_ns = now_ns
if paddle_onset:
feedback.temporary_eps_event_ns = min(axis.faultEventMonoTime, event_ns)
if matched:
feedback.pending_event = 0
feedback.temporary_eps_event_ns = event_ns
@@ -257,6 +276,8 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
"""Complete an existing EPS event join after recovery; never renew authority."""
from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity
from openpilot.starpilot.car.subaru.aol import known_paddle_pause
paddle = known_paddle_pause(cp, state)
previous = feedback.signature
pending, restriction = feedback.pending_event, getattr(feedback, 'temporary_eps_event_ns', 0)
if (not qualified(cp, marked_only=True) or not cp.pcmCruise or cp.openpilotLongitudinalControl or
@@ -279,26 +300,27 @@ def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, no
state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
state.steeringDisengage or state.buttonEvents or state.regenBraking or
(state.gearShifter != structs.CarState.GearShifter.drive and
(not paddle and state.gearShifter != structs.CarState.GearShifter.drive and
not (cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025} and
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
not state.cruiseState.available or state.cruiseState.enabled):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
temporary = (log.OnroadEvent.EventName.steerTempUnavailable, log.OnroadEvent.EventName.steerTempUnavailableSilent)
allowed = (*temporary, log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.gasPressedOverride,
log.OnroadEvent.EventName.steerOverride, log.OnroadEvent.EventName.pedalPressed)
names = log.OnroadEvent.EventName
temporary = (names.steerTempUnavailable, names.steerTempUnavailableSilent)
soft_allowed = (temporary[0], names.wrongGear) if paddle else (temporary[0],)
allowed = (temporary[1], *soft_allowed, names.pcmDisable, names.gasPressedOverride, names.steerOverride, names.pedalPressed)
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
axis.faultEventMonoTime not in (restriction, pending) or event_ns not in (restriction, pending) or
max(axis.faultEventMonoTime, event_ns) != pending or event_ns > stamp or
not any(event.name in temporary for event in sm['onroadEvents']) or
any(event.name not in allowed or event.immediateDisable or event.softDisable and event.name != temporary[0] or
any(event.name not in allowed or event.immediateDisable or event.softDisable and event.name not in soft_allowed or
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
(state.brakePressed or feedback.subaru_eps_brake_event_ns in (restriction, pending)) and
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
return False
native = _healthy_transport_native(sm, cp, state, feedback.session, now_ns)
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or paddle and not native_off(native) or
native.requestedLongitudinal or native.longitudinalAllowed or native.observedMonoTime < feedback.healthy_native_ns or
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
return False
@@ -394,3 +394,28 @@ def test_stopped_source_proof_depends_on_zero_wheel_speed_not_brake(brake_presse
assert sd.aol_stopped_intent_proof is proof
assert (leases(feedback), feedback.signature, intent.validUntilMonoTime, sd.aol_axis_decision) == before
assert not retain_stopped_source(sd, state, intent, stamp, stamp + 200_000_001)
@pytest.mark.parametrize('axis_first', (False, True), ids=('event-first', 'axis-first'))
@pytest.mark.parametrize('hard_fault', (False, True), ids=('temporary', 'controls-mismatch'))
def test_subaru_paddle_eps_onset_preserves_only_the_off_intent(axis_first, hard_fault):
cp, state, feedback, _, _, stamp = paused_case()
state.gearShifter = 'manumatic'
state.gasPressed = True
now = stamp + 20_000_000
earlier, later = int(feedback.signature[6]), stamp + 10_000_000
sm, _ = sample(cp, now, now, 3, active=False, requested=False, allowed=False,
event_stamp=earlier if axis_first else later)
change(sm, 'aolAxisState', lambda a: (setattr(a, 'faultEventMonoTime', later if axis_first else earlier),
setattr(a, 'intentIntegrityEpoch', 0)))
event = sm.messages['onroadEvents'].as_builder()
event.onroadEvents = [{'name': 'pcmDisable', 'userDisable': True}, {'name': 'wrongGear', 'softDisable': True},
{'name': 'gasPressedOverride'}, {'name': 'steerOverride'}]
if hard_fault:
event.onroadEvents = [*event.onroadEvents, {'name': 'controlsMismatch', 'immediateDisable': True}]
sm.messages['onroadEvents'] = event.as_reader()
before = leases(feedback), feedback.healthy_feedback_ns, feedback.healthy_native_ns
assert feedback.observe(sm, cp, state, now, latched=True, intent_producer_session=PRODUCER) == hard_fault
if not hard_fault:
assert feedback.pending_event == later
assert (leases(feedback), feedback.healthy_feedback_ns, feedback.healthy_native_ns) == before
@@ -15,6 +15,10 @@ from openpilot.starpilot.models.laboratory_runner import LaboratoryPair
def common_join():
tree = ast.parse(Path(modeld.__file__).read_text())
smoothing = [statement for statement in ast.walk(tree) if isinstance(statement, ast.Assign)
and any(isinstance(target, ast.Name) and target.id == 'steering_smoothing' for target in statement.targets)]
assert len(smoothing) == 1
assert ast.unparse(smoothing[0]) == 'steering_smoothing = subaru_tau + volkswagen_tau + kona_tau + bolt_tau'
matches = []
for node in ast.walk(tree):
body = getattr(node, 'body', None)
@@ -28,9 +32,9 @@ def common_join():
assert len(statements) == 3
assert sum(isinstance(call, ast.Call) and ast.unparse(call.func) == 'model.get_action_from_model'
for call in ast.walk(statements[0])) == 1
assert ast.unparse(statements[1]) == 'filter_action(action, prev_action, v_ego, subaru_tau + volkswagen_tau + kona_tau)'
assert ast.unparse(statements[1]) == 'filter_action(action, prev_action, v_ego, steering_smoothing)'
assert ast.unparse(statements[2]) == 'prev_action = action'
matches.append(ast.Module(body=statements, type_ignores=[]))
matches.append(ast.Module(body=smoothing + statements, type_ignores=[]))
assert len(matches) == 1
return compile(matches[0], modeld.__file__, 'exec')
@@ -56,7 +60,8 @@ def test_actual_common_join_once_and_acceleration_unchanged(owner, tau, kona_tau
SimpleNamespace(get_action_from_model=function))
paired_action = function(outputs, previous, .2, .2, 2.) if owner == 'laboratory' else None
scope = {'model': model, 'LaboratoryPair': LaboratoryPair, 'laboratory_action': paired_action, 'model_output': outputs, 'prev_action': previous,
'lat_action_t': .2, 'long_action_t': .2, 'v_ego': 2., 'subaru_tau': tau, 'volkswagen_tau': 0., 'kona_tau': kona_tau, 'filter_action': filter_action}
'lat_action_t': .2, 'long_action_t': .2, 'v_ego': 2., 'subaru_tau': tau,
'volkswagen_tau': 0., 'kona_tau': kona_tau, 'bolt_tau': 0., 'filter_action': filter_action}
exec(common_join(), scope)
action = scope['action']
assert isinstance(action, (_DynamicStructBuilder, _DynamicStructReader))
@@ -46,11 +46,11 @@ def test_one_bounded_departure_burst_and_no_old_request_after_disable():
assert owner.update(cc, cs, 101) == (False, False)
def test_dom_global_hold_timing_and_clear_on_lead_loss():
def test_hold_readiness_after_settling_and_clear_on_lead_loss():
owner = StopAndGo()
cc, cs = state()
pulses = [frame for frame in range(111) if owner.update(cc, cs, frame)[1]]
assert pulses == [51, 52, 53, 54, 55, 106, 107, 108, 109, 110]
assert pulses == list(range(51, 111))
cs.close_distance += 0.02
assert owner.update(cc, cs, 111)[0]
cc.hudControl.leadVisible = False
@@ -6,17 +6,20 @@ and the 2026-11-24 standstill failure is unrepresentable in it. Here the
100 Hz Throttle source is delivered pandad-style: every fifth tick the packet
carries two Throttle frames, the CANParser accepts both, and capture() can only
store the newest -- the stored counter jumps by 2. The StopAndGo ready clock
must still reach 51 consecutive frames and emit the 3 kph hold pulse.
must still reach 51 consecutive frames and send complete source-backed bursts.
"""
import time as time_module
import pytest
from types import SimpleNamespace
from unittest.mock import patch
from opendbc.car import Bus, gen_empty_fingerprint
from opendbc.car import Bus, gen_empty_fingerprint, structs
from opendbc.car.subaru.interface import CarInterface
from opendbc.car.subaru.sng import prepare, selected
from opendbc.car.subaru.values import CAR
from opendbc.safety.tests.libsafety import libsafety_py
from openpilot.cereal import messaging
from openpilot.starpilot.car.subaru.sng_caller import update as sng_caller_update
from openpilot.starpilot.car.subaru.tests.caller_helpers import CompleteCan
@@ -54,7 +57,12 @@ class FakeSubMaster:
self.recv_time[name] = (now_ns - 1000) / 1e9
def test_sng_hold_pulse_with_batched_throttle_delivery():
@pytest.mark.parametrize('tick_ns', (10_000_000, 9_600_000))
def test_sng_hold_pulse_with_batched_throttle_delivery(tick_ns):
safety = libsafety_py.libsafety
safety.init_tests()
safety.set_alternative_experience(0)
assert safety.set_safety_hooks(structs.CarParams.SafetyModel.subaru, 8) == 0
cp = CarInterface.get_params(CAR.SUBARU_IMPREZA_2020, gen_empty_fingerprint(), [], False, False, False)
prepare(cp, True)
assert selected(cp)
@@ -90,8 +98,9 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
throttle_taps = []
ready_ticks = []
max_duration = 0
for tick in range(200):
now = base_ns + tick * 10_000_000
for tick in range(670):
now = base_ns + tick * tick_ns
values['CruiseControl']['Cruise_Activated'] = int(tick >= 12)
_virtual['ns'] = now
frames = []
if tick % 5 == 4:
@@ -99,6 +108,10 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
# parser accepts from this tick's packet; frames() packs the newer.
frames.append(stream.packers[Bus.pt].make_can_msg('Throttle', pt_bus, values["Throttle"]))
frames.extend(stream.frames(values, tick=tick, omit=((Bus.pt, 'Brake_Pedal'),) if tick % 2 else ()))
safety.set_timer((now // 1000) & 0xffffffff)
for address, data, bus in frames:
safety.safety_rx_hook(libsafety_py.make_CANPacket(address, bus, data))
safety.safety_tick()
ci.update([(now, frames)])
assert ci.CS.out.standstill
sm.update(now)
@@ -107,9 +120,12 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
if tick >= 20:
ready_ticks.append(bool(ci.CS.sng_lead_ready))
max_duration = max(max_duration, ci.CC.frame - ci.CC.sng_owner.last_standstill_frame)
for address, data, _bus in sends:
for address, data, bus in sends:
if address == 0x139 and data[2] == 53 and (data[3] & 15) == 0:
pulses.append(tick)
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, data)), tick
pulses.append(now)
elif address in (0x139, 0x40):
safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, data))
if address == 0x40 and data[4] == 5:
throttle_taps.append(tick)
# The batched ticks must not flap the lead-ready health signal...
@@ -117,11 +133,18 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
# ...the standstill clock must run past the 51 consecutive frames the
# hold pulse requires (it peaked at 24 in the 2026-11-24 incident)...
assert max_duration > 50, max_duration
# ...and the spoofed 3 kph Brake_Pedal hold pulse must reach the wire,
# on roughly the designed 0.55 s cadence (two pulses in 2 s).
assert len(pulses) >= 2, pulses
bursts: list[list[int]] = []
for stamp in pulses:
if not bursts or stamp - bursts[-1][0] > 50_000_000:
bursts.append([])
bursts[-1].append(stamp)
assert len(bursts) >= 10, pulses
assert all(len(burst) == 3 for burst in bursts[:-1]), [len(burst) for burst in bursts]
assert all(b[0] - a[0] <= 570_000_000 for a, b in zip(bursts, bursts[1:], strict=False))
# The departure tap must not fire: Close_Distance never enters 3.0-4.5 m.
assert not throttle_taps, throttle_taps
finally:
safety.init_tests()
safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0)
if _ADDED_BOOTTIME:
del time_module.CLOCK_BOOTTIME
@@ -26,7 +26,7 @@ from openpilot.starpilot.car.subaru.tests.native_fixture import subaru_native_pa
def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, subaru_native_pair, tmp_path, aol=True, manual=False, stop_resume=False,
hard_stop_native_first=False, main_only=False, preferences=None, firmware=None,
manual_ratio=None, camera_hud=False, manual_phase=0,
paddle_gear_delay=0, exit_gear=0, exit_duration=7, exit_tick=220,
paddle_gear_delay=0, paddle_eps=0, exit_gear=0, exit_duration=7, exit_tick=220,
deadline_gap=False, fixed_angle_handoff=False, host_first_stop=False,
source_outage=False, vm_angle_handoff=0, crawl=False, eps_brake_join=False,
high_angle_guard=False, main_on_brake=False, guard_brake_release=False,
@@ -34,6 +34,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
angle_continuation=0, stopped_source_gap=False, paused_eps=0,
eps_clear_join=0, eps_clear_axis_first=False, stop_creep_eps=0, cold_stop=False):
angle_handoff = fixed_angle_handoff or vm_angle_handoff
paddle_eps_end = {1: 233, 2: 317, 3: 176}.get(paddle_eps, 0)
fw = firmware_records(candidate, FW_VERSIONS, 'subaru') if firmware is None else firmware
rows = []
if candidate == CAR.SUBARU_IMPREZA_2025 and firmware is None:
@@ -108,8 +109,11 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
reverse = 150 + manual_phase <= tick < 185
exit_transition = exit_gear and exit_tick <= tick < exit_tick + exit_duration
gear = exit_gear if exit_transition else manual_ratio if reverse and manual_ratio is not None else 3 if reverse else 121
temporary = not exit_gear and not guard_brake_release and 225 <= tick < 260
main = not 310 <= tick < 350 and (tick >= 30 or not main_only)
temporary = not (exit_gear or paddle_eps) and not guard_brake_release and 225 <= tick < 260
main = (paddle_eps or exit_tick >= 310 and exit_gear or not 310 <= tick < 350) and (tick >= 30 or not main_only)
if paddle_eps:
temporary |= 165 + paddle_eps <= tick < paddle_eps_end
brake |= paddle_eps == 2 and 155 <= tick < paddle_eps_end + 5
stopped = stop_resume and (125 <= tick < 135 if hard_stop_native_first or host_first_stop or stop_creep_eps else 185 <= tick < 195)
if stopped_source_gap == 2 and stopped:
brake = elapsed < 130
@@ -127,7 +131,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
temporary = bool(paused_eps in (3, 4, 6) and 95 <= tick < 111 or temporary)
values = {
'Throttle': {'Throttle_Pedal': 100 if source_outage and 60 <= tick < 90 else 0},
'Throttle': {'Throttle_Pedal': 100 if source_outage and 60 <= tick < 90 or paddle_eps == 1 and 155 <= tick < paddle_eps_end + 3 else 0},
'Steering_Torque': {'Steer_Warning': int(temporary),
'Steer_Torque_Sensor': (250 if 70 <= tick < 76 else
80 if vm_angle_handoff and 76 <= tick < 90 else
@@ -300,7 +304,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
cs = published['carState'].carState
expected_gear = {3: structs.CarState.GearShifter.reverse, 121: structs.CarState.GearShifter.drive}.get(
gear, structs.CarState.GearShifter.manumatic)
retained_exit = bool(manual_ratio and exit_tick - 184 <= 75 and exit_gear in (1, 129))
retained_exit = bool(manual_ratio and exit_tick - 184 <= 200 and exit_gear in (1, 129))
if exit_transition and (not retained_exit or tick >= exit_tick + 15):
expected_gear = structs.CarState.GearShifter.unknown
assert cs.brakePressed == brake and cs.gearShifter == expected_gear, (tick, gear, cs.gearShifter, expected_gear)
@@ -405,7 +409,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
assert aol and main_only and cs.brakePressed and not command.enabled
assert request and accepted, ('CRAWL_AOL_BRAKE_WITHDREW', tick, decoded_steering)
if not stopped and (65 <= tick < 90 and not (main_during_eps and tick < 75) and not (source_outage and 75 <= tick < 84) or
aol and (first_resume or 205 <= tick < 220 or 280 <= tick < 300)):
aol and not temporary and (first_resume or 205 <= tick < 220 or 280 <= tick < 300)):
if angle_handoff and 72 <= tick < 78:
assert not request and accepted, (tick, decoded_steering)
else:
@@ -413,7 +417,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
assert accepted, ('SUBARU_ANGLE_HANDOFF_NATIVE_REJECTED', tick, decoded_steering)
if output != 0:
active_emissions.append(tick)
if 165 <= tick < 180 or not exit_gear and 240 <= tick < 255 or not aol and (125 <= tick < 145 or 205 <= tick < 220 or 280 <= tick < 300):
if (165 <= tick < 180 or not (exit_gear or paddle_eps) and 240 <= tick < 255 or
not aol and (125 <= tick < 145 or 205 <= tick < 220 or 280 <= tick < 300)):
if angle_handoff or angle_continuation:
assert not request and abs(output - cs.steeringAngleDeg) <= 0.011, (tick, decoded_steering)
else:
@@ -497,6 +502,12 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if stop_creep_eps and 135 <= tick < 148:
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_STOP_CREEP_EPS_LOST_INTENT', row)
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
if paddle_eps and 165 + paddle_eps <= tick < paddle_eps_end:
assert row['cardLatch'] and row['armed'] and not row['lat'] and row['permission'] == 0, row
assert all(not frame['request'] and frame['output'] == 0 for frame in row['steering']), row
if paddle_eps and tick == paddle_eps_end + 25:
assert row['cardLatch'] and row['armed'] and row['lat'] and row['permission'] == 1, row
return
if exit_gear and tick == exit_tick - 1:
assert row['cardLatch'] and row['armed'] and row['lat'] and row['permission'] == 1, row
if exit_transition:
@@ -515,7 +526,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
assert not command.latActive and not bool(intent and intent.allowedLatch) and row['permission'] == 0, row
if 65 <= tick < 90 and not (stop_creep_eps and cold_stop) and not (main_during_eps and tick < 75) and not (source_outage and 75 <= tick < 84):
assert command.latActive and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol), row
if not stopped and (first_resume or 205 <= tick < 220 or 280 <= tick < 300):
if not stopped and not temporary and (first_resume or 205 <= tick < 220 or 280 <= tick < 300):
assert command.latActive == aol and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol) and not row['controls'], row
if manual_ratio is not None and 150 + manual_phase <= tick < 185:
assert not command.latActive and row['permission'] == 0 and row['cardLatch'] and row['armed'], row
@@ -524,11 +535,11 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
if 165 <= tick < 180:
assert (not command.latActive and not bool(intent and intent.allowedLatch) and
bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0), row
if not exit_gear and 240 <= tick < 255:
if not (exit_gear or paddle_eps) and 240 <= tick < 255:
assert not command.latActive and bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0, row
main_rearm = aol and candidate in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_IMPREZA_2020,
CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023, CAR.SUBARU_CROSSTREK_2018, CAR.SUBARU_IMPREZA)
if 330 <= tick < (350 if main_rearm else 400):
if not (paddle_eps or exit_gear and exit_tick >= 310) and 330 <= tick < (350 if main_rearm else 400):
assert not command.latActive and not bool(intent and intent.allowedLatch), row
if rearm_on_brake and 355 <= tick < 365:
assert row['cardLatch'] and row['armed'] and not row['lat'] and row['permission'] == 0, ('SUBARU_REPEAT_BRAKED_MAIN_LOST', row)
@@ -536,7 +547,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
assert cs.leftBlinker or cs.rightBlinker, row
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_SIGNAL_PAUSE_LOST_INTENT', row)
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
if main_rearm and 375 <= tick < 400 and rearm_on_brake not in (1, 2):
if main_rearm and not exit_transition and 375 <= tick < 400 and rearm_on_brake not in (1, 2):
assert command.latActive and row['cardLatch'] and row['permission'] == 1 and not row['controls'], row
if tick >= 440:
assert command.latActive and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol), row
@@ -872,8 +883,16 @@ def test_actual_crosstrek_panda_denial_before_card_gear(subaru_native_pair, tmp_
paddle_gear_delay=delay, preferences={'SubaruSNG': True})
@pytest.mark.parametrize(("gear", "duration", "tick"), [(1, 7, 236), (129, 7, 220), (129, 30, 220), (200, 7, 220), (1, 7, 265)])
@pytest.mark.parametrize(("gear", "duration", "tick"), [(1, 7, 236), (129, 7, 220), (129, 30, 220), (200, 7, 220),
(1, 6, 339), (129, 6, 339), (1, 7, 390)])
def test_actual_crosstrek_paddle_exit_gear(subaru_native_pair, tmp_path, gear, duration, tick):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, manual_ratio=145, exit_gear=gear,
exit_duration=duration, exit_tick=tick, crawl=True, preferences={'SubaruSNG': True})
@pytest.mark.parametrize("pedal", (1, 2, 3), ids=("gas", "brake", "clears-in-manual"))
def test_actual_crosstrek_paddle_eps_pause(subaru_native_pair, tmp_path, pedal):
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, manual_ratio=145, paddle_eps=pedal,
preferences={'SubaruSNG': True})
@@ -13,6 +13,7 @@ from openpilot.starpilot.car.toyota.tests.test_pedal_parent_configurations impor
CHECKS = (dsu_bypass.configured, pedal_composite.configured, aol.qualified)
CACHED_CHECKS = (dsu_bypass._configured, pedal_composite._configured, aol.qualified)
def params():
@@ -23,23 +24,26 @@ def params():
return cp
@pytest.mark.parametrize('check', CHECKS)
@pytest.mark.parametrize('check,cached', zip(CHECKS, CACHED_CHECKS, strict=True))
@pytest.mark.parametrize('field,value', [
('brand', 'other'), ('carFingerprint', 'unknown'), ('flags', 0), ('passive', True),
('dashcamOnly', True), ('notCar', True), ('pcmCruise', False), ('secOcRequired', True),
('openpilotLongitudinalControl', False), ('alternativeExperience', 1), ('autoResumeSng', True),
('alphaLongitudinalAvailable', True), ('steerControlType', 'angle'), ('carVin', 'changed'),
])
def test_mutable_builder_and_reader_alias(check, field, value):
def test_mutable_builder_and_reader_alias(check, cached, field, value):
cp = params()
alias = cp.as_reader()
assert check(cp)
before = check.cache_info().misses
before = cached.cache_info().misses
assert getattr(cp, field) != value
setattr(cp, field, value)
expected = check.__wrapped__(cp)
expected = cached.__wrapped__(cp)
assert check(cp) == check(alias) == expected
assert check.cache_info().misses > before
if field == 'flags' and check is not cached:
assert not expected and cached.cache_info().misses == before
else:
assert cached.cache_info().misses > before
@pytest.mark.parametrize('check', CHECKS)
@@ -6,25 +6,27 @@ from opendbc.car.toyota.values import CAR
from openpilot.starpilot.car.toyota.tests.test_pedal_parent_configurations import sources
ROWS = (
(advert_filter.configured, advert_filter, CAR.TOYOTA_RAV4_TSS2, '2FF4', 'catalog'),
(rav4h_filter.configured, rav4h_filter, CAR.TOYOTA_RAV4H, '2FF8', 'catalog'),
(prius_longitudinal.configured, prius_longitudinal, CAR.TOYOTA_PRIUS_RETROFIT, '2FF8', 'EPS73_8965B47070'),
(prius_longitudinal.eps73_status_configured, prius_longitudinal, CAR.TOYOTA_PRIUS_RETROFIT, '2FF8', 'EPS73_8965B47070'),
(prius_advert_filter.configured, prius_advert_filter, CAR.TOYOTA_PRIUS_RETROFIT, '2FF4', 'EPS73_8965B47070'),
(advert_filter.configured, advert_filter._configured, advert_filter, CAR.TOYOTA_RAV4_TSS2, '2FF4', 'catalog'),
(rav4h_filter.configured, rav4h_filter._configured, rav4h_filter, CAR.TOYOTA_RAV4H, '2FF8', 'catalog'),
(prius_longitudinal.configured, prius_longitudinal.configured, prius_longitudinal, CAR.TOYOTA_PRIUS_RETROFIT, '2FF8', 'EPS73_8965B47070'),
(prius_longitudinal.eps73_status_configured, prius_longitudinal._eps73_status_configured, prius_longitudinal,
CAR.TOYOTA_PRIUS_RETROFIT, '2FF8', 'EPS73_8965B47070'),
(prius_advert_filter.configured, prius_advert_filter._configured, prius_advert_filter, CAR.TOYOTA_PRIUS_RETROFIT, '2FF4', 'EPS73_8965B47070'),
)
@pytest.mark.parametrize('check,owner,identity,topology,rack', ROWS)
@pytest.mark.parametrize('check,cached_check,owner,identity,topology,rack', ROWS)
@pytest.mark.parametrize('pedal', (False, True))
@pytest.mark.parametrize('stock', (False, True))
def test_original_parent_admission_and_mutable_aliases(check, owner, identity, topology, rack, pedal, stock):
def test_original_parent_admission_and_mutable_aliases(check, cached_check, owner, identity, topology, rack, pedal, stock):
fp, fw = sources(identity, topology, rack)
if pedal:
fp[0][0x201] = 6
cp = CarInterface.get_params(identity, fp, fw, True, False, False)
if stock:
assert (pedal_composite if pedal else owner).prepare_stock(cp)
assert check(cp) and check.__wrapped__(cp)
uncached_check = cached_check.__wrapped__
assert check(cp) and uncached_check(cp)
alias = cp.as_reader()
assert check(alias)
for field, value in (
@@ -38,9 +40,9 @@ def test_original_parent_admission_and_mutable_aliases(check, owner, identity, t
reader = mutated.as_reader()
assert check(mutated)
setattr(mutated, field, value)
assert check(mutated) == check(reader) == check.__wrapped__(mutated)
assert check(mutated) == check(reader) == uncached_check(mutated)
for field, value in (('safetyParam', 0), ('safetyModel', 'noOutput')):
mutated = cp.as_reader().as_builder()
assert check(mutated)
setattr(mutated.safetyConfigs[0], field, value)
assert not check(mutated) and not check.__wrapped__(mutated)
assert not check(mutated) and not uncached_check(mutated)
+9 -5
View File
@@ -20,9 +20,10 @@ def lateral_output_inhibited(cp, state):
def temporary_restriction(cp, state):
from openpilot.starpilot.aol.runtime import ordinary_lateral_requested
gears = structs.CarState.GearShifter
return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and
not state.steerFaultPermanent and (state.steerFaultTemporary or lateral_output_inhibited(cp, state) or
return bool(state is not None and state.canValid and not state.canTimeout and not state.steerFaultPermanent and
qualified(cp, marked_only=True) and (state.steerFaultTemporary or not ordinary_lateral_requested(True, state, cp) or
state.gearShifter not in (gears.drive, gears.sport, gears.eco, gears.manumatic)))
@@ -124,7 +125,7 @@ class VolkswagenStockCardIntent(AolCardIntent):
if (kwargs.get('fault_active') is False and 0 < rejection_ns <= self.eps_recovery_ns <= now_ns and
now_ns - self.eps_recovery_ns <= SAFETY_MAX_AGE_NS):
kwargs['native_rejection_ns'] = 0
state = structs.CarState(**CS.to_dict())
state = CS
events = []
for event in CS.buttonEvents:
if event.type == ButtonType.mainCruise and self.settings.main_action != AOL_TOGGLE:
@@ -172,8 +173,11 @@ class VolkswagenStockCardIntent(AolCardIntent):
else:
self.main_neutral = False
self.main_pulse = False
state.buttonEvents = events
super().update(state.as_reader(), **kwargs)
if CS.buttonEvents or events:
state = structs.CarState(**CS.to_dict())
state.buttonEvents = events
state = state.as_reader()
super().update(state, **kwargs)
if (self.startup_deferred and not self.startup_granted and
(now_ns > self.startup_arm_ns + SAFETY_MAX_AGE_NS or kwargs.get('fault_active') or
kwargs.get('native_rejection_ns') or not state.canValid or state.canTimeout or not available or
@@ -10,6 +10,7 @@ from opendbc.car.volkswagen.values import CAR
from openpilot.cereal import log
from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan, smooth_value
from openpilot.selfdrive.modeld.constants import ModelConstants
from openpilot.starpilot.car.gm.model_smoothing import seconds as bolt_smoothing
from openpilot.starpilot.car.subaru.smoothing import filter_action
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing, POPV2_SHA256, seconds
from openpilot.starpilot.models.status import ModelLoad, ModelVariant
@@ -109,11 +110,11 @@ def test_model_join_applies_matching_input_delay_and_exactly_one_filter():
cp, load = setup()
previous = log.ModelDataV2.Action(desiredCurvature=0.)
action = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=-.25, shouldStop=True)
env = {'CP': cp, 'receipt_owner': SimpleNamespace(load=load), 'v_ego': 18., 'subaru_smoothing': 0.,
env = {'CP': cp, 'bolt_smoothing': bolt_smoothing, 'receipt_owner': SimpleNamespace(load=load), 'v_ego': 18., 'subaru_smoothing': 0.,
'subaru_smooth_seconds': lambda speed, maximum: 0., 'volkswagen_smoothing': seconds,
'kona_tau': 0., 'LAT_SMOOTH_SECONDS': 0., 'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.2893982231616974)},
'action': action, 'prev_action': previous, 'filter_action': filter_action}
wanted = {'subaru_tau', 'volkswagen_tau', 'lat_delay'}
wanted = {'subaru_tau', 'volkswagen_tau', 'bolt_tau', 'steering_smoothing', 'lat_delay'}
nodes = [n for n in ast.walk(tree) if isinstance(n, ast.Assign) and
any(isinstance(t, ast.Name) and t.id in wanted for t in n.targets)]
filters = [n for n in ast.walk(tree) if isinstance(n, ast.Expr) and isinstance(n.value, ast.Call) and
@@ -18,7 +18,8 @@ PRODUCER_SOURCE_HASHES = (
('openpilot', 'system/camerad/cameras/spectra.cc', '4fa26c17f0fb792a4ab6815657beccddee1d641faa2fd02e5aa7393f717a2f3a'),
('openpilot', 'system/camerad/cameras/camera_qcom2.cc', 'b34c24c9984a0ac086f7b961cb7ff09d0501231da50aaad0e676bb3dc3f2edd9'),
('openpilot', 'system/camerad/cameras/camera_common.cc', 'bd9a416a6ee21047b4deec6df04276d8717cd92fe14de43f3e9daff86b62bb8f'),
('openpilot', 'selfdrive/modeld/modeld.py', 'd1dbf1e8b862ecac9fa2005d13cc2725c70a6e566a2a574807ad6d1a5a4977f4'),
('openpilot', 'selfdrive/modeld/modeld.py', 'f3e9a96c1f70196b2efcba2efb8c5f356b57b2906ae2a1d29816eec41ecf7c8d'),
('openpilot', 'starpilot/car/gm/model_smoothing.py', '04855d064b5a01c489370d856eb6f1eb6616f187a85074e93d0b1d7f1d4ee1f2'),
('openpilot', 'starpilot/car/volkswagen/model_smoothing.py', 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540'),
('openpilot', 'starpilot/car/hyundai/model_smoothing.py', '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243'),
('openpilot', 'selfdrive/modeld/fill_model_msg.py', 'b3916c34d1073d0c26a7a8adc51e7b148f63a1ac68b388226170fd0f8b8b56b4'),
@@ -10,7 +10,8 @@ from openpilot.starpilot.flm import producer_clock_equivalence as clock
APPROVED = {
'starpilot/car/volkswagen/model_smoothing.py': 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540',
'selfdrive/modeld/modeld.py': 'd1dbf1e8b862ecac9fa2005d13cc2725c70a6e566a2a574807ad6d1a5a4977f4',
'selfdrive/modeld/modeld.py': 'f3e9a96c1f70196b2efcba2efb8c5f356b57b2906ae2a1d29816eec41ecf7c8d',
'starpilot/car/gm/model_smoothing.py': '04855d064b5a01c489370d856eb6f1eb6616f187a85074e93d0b1d7f1d4ee1f2',
'starpilot/car/hyundai/model_smoothing.py': '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243',
'visionipc/visionipc_py.cc': '6c131c4f5eccb9f822f1aaae63733f26b1427c52340b61c9cdaf6cd4aee2f89d',
'visionipc/visionipc_server.cc': 'a4325a5171eacb931eb271d06a992d2f27216040df113d92099f62cdfa67d81a',
@@ -20,7 +21,7 @@ APPROVED = {
def test_exact_installed_upstream_closure_is_checked_before_contract():
contract = clock.pinned_default_contract()
assert len(clock.PRODUCER_SOURCE_HASHES) == 21
assert len(clock.PRODUCER_SOURCE_HASHES) == 22
assert {relative: expected for _, relative, expected in clock.PRODUCER_SOURCE_HASHES if relative in APPROVED} == APPROVED
assert contract.producer_revision == clock.CLOSURE_SHA256
assert contract.proof_sha256 == clock.CLOSURE_SHA256
+21 -10
View File
@@ -27,7 +27,7 @@ MAX_SPEED_MPS = 70.0
# Route bytes are processed one bounded segment at a time, never concatenated.
# Admit long recordings above the old 256 MiB cap without unbounded offroad work.
MAX_ROUTE_COMPRESSED_BYTES = 1024 * 1024 * 1024
ANALYSIS_VERSION = 7
ANALYSIS_VERSION = 8
MAX_MODEL_METADATA_SECONDS = 4.0
DISTRACTED_EVENT = 'driverDistracted2'
UNRESPONSIVE_EVENT = 'driverUnresponsive3'
@@ -362,7 +362,9 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
car_pairs = state_pairs = 0
coverage_gap = False
end_of_route = False
clocks_offset = None
clocks_offset = gps_offset = None
gps_conflict = False
latest_wall_time = datetime.now(UTC).timestamp() + 86400
model = None
model_outputs = []
model_loads = []
@@ -385,7 +387,8 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
try:
events = decode_segment(compressed, codec, cancelled=lambda: not allowed(),
retain=frozenset(('clocks', 'initData', 'logMessage', 'modelV2', 'drivingModelData',
'carState', 'selfdriveState', 'carControl', 'onroadEvents', 'sentinel')))
'carState', 'selfdriveState', 'carControl', 'onroadEvents', 'sentinel',
'gpsLocation', 'gpsLocationExternal')))
except LogDecodeCancelled:
raise
except LogDecodeError:
@@ -406,12 +409,21 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
if stamp <= 0 or not event.valid:
continue
if kind == 'clocks':
wall = int(event.clocks.wallTimeNanos)
if 946684800 * 1_000_000_000 <= wall <= (datetime.now(UTC).timestamp() + 86400) * 1_000_000_000:
offset = (wall - stamp) / 1e9
wall = event.clocks.wallTimeNanos / 1e9
if 946684800 <= wall <= latest_wall_time:
offset = wall - stamp / 1e9
if clocks_offset is not None and abs(offset - clocks_offset) > 5:
raise _Incomplete('Conflicting logged wall clocks')
clocks_offset = offset if clocks_offset is None else clocks_offset
elif kind in ('gpsLocation', 'gpsLocationExternal'):
gps = getattr(event, kind)
wall = gps.unixTimestampMillis / 1e3
if gps.hasFix and 946684800 <= wall <= latest_wall_time:
offset = wall - stamp / 1e9
if gps_offset is None:
gps_offset = offset
elif abs(offset - gps_offset) > 5:
gps_conflict = True
elif kind == 'initData' and model is None:
model = _recorded_model(event.initData)
elif kind == 'logMessage':
@@ -497,10 +509,9 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
if last <= first:
raise _Incomplete('Route has no observed duration')
duration = (last - first) / 1e9
if clocks_offset is not None:
start_time = first / 1e9 + clocks_offset
else:
start_time = _route_wall_time(route_id)
if clocks_offset is None and not gps_conflict:
clocks_offset = gps_offset
start_time = first / 1e9 + clocks_offset if clocks_offset is not None else _route_wall_time(route_id)
if start_time is not None:
result['startTime'] = start_time
result['endTime'] = start_time + duration
+8 -3
View File
@@ -367,8 +367,13 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
with sounds_lock:
if sound_source is None:
from openpilot.common.params import Params
authority = context_source(Params())
sound_source = SoundDownloads(parked=authority.parked)
from openpilot.starpilot.audio.sound_pack import read_selection
params = Params()
authority = context_source(params)
def selection():
_, selected, readable = read_selection(params)
return selected if readable else None
sound_source = SoundDownloads(parked=authority.parked, selection=selection)
server.sound_authority = authority
server.sound_source = sound_source
return sound_source
@@ -1805,7 +1810,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
'/api/models/active', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
'/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/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/sounds/delete', '/api/software/action', '/api/drives/ignore',
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete',
'/api/crash-reports/delete',
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
@@ -73,10 +73,10 @@ DESCRIPTIONS = {
'SET uses your current speed when you are above that floor.'),
'StandardPersonalityBoost': 'Scales the Standard End to End acceleration boost. 100% is stock and 0% is off.',
'AggressivePersonalityBoost': 'Scales the Aggressive End to End acceleration boost. 100% is stock and 0% is off.',
'RelaxedPersonalityBoost': 'Scales clear-road assistance when Speed Nudge in Relaxed is on. 100% is the regular nudge.',
'RelaxedPersonalityBoost': 'Scales Relaxed assistance when Add Extra Boost is on. 0% turns it off.',
'TrafficPersonalityBoost': 'Scales clear-road End to End assistance in Traffic Mode. 200% is the default and 0% is off.',
'ExperimentalSpeedNudge': ('Helps End to End return to set speed on clear roads in the Relaxed personality. ' +
'Leads, stops, curve limits and driver overrides retain priority.'),
'ConvergeToSetSpeed': ('Helps End to End ease back toward set speed when there is room. Adjust the amount with each personality’s Boost Strength. ' +
'Lead spacing, stops, speed limits, curves and driver overrides still take priority.'),
'FasterLeadTakeoff': ('Improves launches from a stop and responds sooner when a lead starts moving. ' +
'Selected acceleration profiles, stop detection and vehicle limits still apply.'),
'CustomPersonalities': 'Uses your following-time and jerk settings for the selected driving personality.',
@@ -26,7 +26,7 @@ const web = path.resolve(__dirname, '../../web')
{ id: 'experiment', label: 'Turn experiment', value: 'Off', choices: ['Off', 'On'], available: true, action: true, level: 'advanced' },
] : name === 'hub' ? [{ label: 'Lane Changes', page: 'lane_change', available: true, value: 'Configure lane changes', levels: ['simple', 'advanced'] },
{ label: 'Developer', page: 'torque/developer', available: true, levels: ['advanced'] }]
: [{ id: 'ExperimentalSpeedNudge', label: 'Default control', value: 'Off', choices: ['Off', 'On'], available: true, action: true, ...(name === 'torque/developer' ? { level: 'advanced' } : {}) }]
: [{ id: 'ConvergeToSetSpeed', label: 'Default control', value: 'Off', choices: ['Off', 'On'], available: true, action: true, ...(name === 'torque/developer' ? { level: 'advanced' } : {}) }]
return route.fulfill({ json: { page: name, title: name, view: 'test-view', parked: true, rows, settingsMode: deviceMode, ...(name === 'torque/developer' ? { levels: ['advanced'] } : {}),
...(name === 'hub' ? { pageLevels: { aol: [], lane: [], torque: [], 'torque/developer': ['advanced'], lane_change: ['simple', 'advanced'], wheel: ['advanced'] } } : {}) } })
}
@@ -33,7 +33,7 @@
"StandardPersonalityBoost",
"RelaxedPersonalityBoost",
"TrafficPersonalityBoost",
"ExperimentalSpeedNudge",
"ConvergeToSetSpeed",
"FasterLeadTakeoff",
"ForceAutoTuneOff",
"ForceStopDistanceOffset",
@@ -306,16 +306,25 @@ class AuthRuntimeTest(unittest.TestCase):
finished += 1
condition.notify_all()
get_request = self.server.get_request
def hold_idle_request():
request, address = get_request()
# Saturation ends when the test closes a client, even if CI pauses the test thread.
request.settimeout(None)
return request, address
held = []
with mock.patch.object(self.server.RequestHandlerClass, 'setup', observed_setup), \
mock.patch.object(self.server.RequestHandlerClass, 'finish', observed_finish), \
mock.patch.object(self.server, 'loopback', return_value=False):
try:
for _ in range(self.server.MAX_CONNECTIONS):
assert self.server is not None
held.append(socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2))
with condition:
self.assertTrue(condition.wait_for(lambda: accepted == require_value(self.server).MAX_CONNECTIONS, timeout=2))
with mock.patch.object(self.server, 'get_request', side_effect=hold_idle_request):
for _ in range(self.server.MAX_CONNECTIONS):
assert self.server is not None
held.append(socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2))
with condition:
self.assertTrue(condition.wait_for(lambda: accepted == require_value(self.server).MAX_CONNECTIONS, timeout=2))
admission_started = threading.Event()
assert self.server is not None
process_request = self.server.process_request
@@ -31,8 +31,8 @@ def event(kind, stamp, **fields):
return message
def write(root, number, events, *, lock=False, kind='rlog'):
name = f'{ROUTE}--{number}'
def write(root, number, events, *, lock=False, kind='rlog', route=ROUTE):
name = f'{route}--{number}'
segment = root / name
segment.mkdir()
(segment / f'{kind}.zst').write_bytes(zstd.compress(b''.join(item.as_reader().as_builder().to_bytes() for item in events)))
@@ -46,6 +46,24 @@ def selection(*segments):
class DriveAnalysisTest(unittest.TestCase):
def test_recovers_route_date_from_late_gps_fix_after_invalid_boot_clock(self):
corrected = 1_790_334_400
final = BASE + 500_000_000
for has_fix in (True, False):
with self.subTest(has_fix=has_fix):
root = self.root / str(has_fix)
root.mkdir()
boot_clock = event('clocks', BASE, wallTimeNanos=1_760_534_400_000_000_000)
boot_clock.valid = False
events = [boot_clock, *self.sample(BASE, 10, True), *self.sample(final, 10, True),
event('gpsLocationExternal', final, unixTimestampMillis=corrected * 1000 + 500, hasFix=has_fix),
event('sentinel', final, type='endOfRoute')]
route = '00000009--f93c55a690'
segment = write(root, 0, events, route=route)
result = analyze_route(root, dict(selection(segment), routeId=route), permitted=lambda: True)
self.assertEqual(result['complete'], has_fix, result)
self.assertEqual(result['startTime'], corrected if has_fix else None)
def test_dashboard_recovers_prefix_before_locked_and_empty_tail_without_changing_logs(self):
first = write(self.root, 0, [*self.sample(BASE, 10, True), *self.sample(BASE + 500_000_000, 10, True),
event('sentinel', BASE + 500_000_000, type='endOfSegment')], kind='qlog')
@@ -17,7 +17,7 @@ from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
@pytest.fixture(params=[
("LeadApproachBuffer", "Approaching lead buffer", "Off"),
("FasterLeadTakeoff", "Faster Takeoffs", "Off"),
("ExperimentalSpeedNudge", "Speed Nudge in Relaxed", "Off"),
("ConvergeToSetSpeed", "Add Extra Boost", "Off"),
("LowSpeedCruiseOnSet", "Low-Speed Cruise Start", "Off"),
("DisengageOnAccelerator", "Disengage on Accelerator Pedal", "Off"),
])
@@ -32,7 +32,7 @@ def setup(tmp_path, request):
def page_row(gateway, label, section=None):
section = section or ("relaxed" if label == "Speed Nudge in Relaxed" else "profiles")
section = section or "profiles"
page = gateway.page(section, "session", b"generation")
index = next(index for index, row in enumerate(page["rows"]) if row["label"] == label)
return page, index, page["rows"][index]
@@ -163,8 +163,8 @@ def test_galaxy_boost_slider_round_trip_and_planner_preference(tmp_path):
intent = gateway.preview(page["view"], index, 0, "session", b"generation", value=str(chosen))
assert gateway.confirm(intent["intent"], "session", b"generation")
assert params.get(BOOST_KEYS[name]) == chosen
_, _, nudge = page_row(gateway, "Speed Nudge in Relaxed")
assert nudge["level"] == "advanced" and nudge["value"] == nudge["defaultValue"] == "Off"
_, _, nudge = page_row(gateway, "Add Extra Boost")
assert nudge["level"] == "simple" and nudge["value"] == nudge["defaultValue"] == "Off"
assert not viewer.sample(2_000_000_000)
assert viewer.boost_scales == {"relaxed": .65, "standard": 1.5, "aggressive": 2., "traffic": 1.}
Path(params.get_param_path(BOOST_KEYS["relaxed"])).write_bytes(b"201")
@@ -67,6 +67,17 @@ for (const name of ["layoutDocument", "previewDocument", "withDisplay", "ordered
assert.equal(layoutModule[name], documentHelpers[name], name)
const data = snapshot()
for (const width of [50, 65, 100])
assert.equal(validDocument({ ...data.document, borderWidth: width }, data.metadata), true)
for (const width of [0, 49, 51, 102, null, "60"])
assert.equal(validDocument({ ...data.document, borderWidth: width }, data.metadata), false)
const borderEditor = { state: { draft: copy(data.document), notice: "" }, editable: true, projection: false,
recordChange: (before, group) => assert.equal(group, "borderWidth") }
OnroadLayoutPage.methods.setBorderWidth.call(borderEditor, 55)
assert.equal(previewDocument(borderEditor.state.draft).borderWidth, 55)
OnroadLayoutPage.methods.setBorderWidth.call(borderEditor, 100)
assert.deepEqual(borderEditor.state.draft, data.document)
assert.ok(ONROAD_LAYOUT_TEMPLATE.includes('aria-label="Edit Screen Border"'))
const restoredCompact = copy(data)
for (const [id, width, height, x, y] of [["max_speed", 162, 162, 0, 0], ["speed_limit", 118, 132, 330, 20]]) {
Object.assign(restoredCompact.metadata.profiles.compact.widgets[id], { width, height, default: {x, y, enabled:true} })
@@ -308,6 +308,24 @@ class TestOnroadLayoutHttp(unittest.TestCase):
self.assertEqual(self.request('/api/ui/layout', {'revision': saved['revision'], 'document': saved['document']}, cookie)[0], 409)
self.assertEqual(self.params.get(PARAM_KEY), default_document())
def test_border_width_persists_without_moving_widgets(self):
cookie = self.login()
_, snapshot, _ = self.request('/api/ui/layout', cookie=cookie)
request = {key: snapshot[key] for key in ('revision', 'document')}
initial = copy.deepcopy(request["document"])
request["document"]["borderWidth"] = 0
self.assertEqual(self.request('/api/ui/layout', request, cookie)[0], 400)
request["document"]["borderWidth"] = 60
code, saved, _ = self.request('/api/ui/layout', request, cookie)
self.assertEqual(saved["document"]["borderWidth"], 60)
self.assertEqual(saved["document"]["layouts"], initial["layouts"])
_, reread, _ = self.request('/api/ui/layout', cookie=cookie)
self.assertEqual(reread["document"]["borderWidth"], 60)
reset = {'revision': reread['revision'], 'document': {**reread['document'], 'borderWidth': 100}}
reset_code, reset_saved, _ = self.request('/api/ui/layout', reset, cookie)
self.assertEqual(reset_code, 200)
self.assertEqual(reset_saved['document'], initial)
def test_mutation_requires_origin_session_and_unique_fields(self):
cookie = self.login()
_, snapshot, _ = self.request('/api/ui/layout', cookie=cookie)
@@ -32,7 +32,7 @@ assert.deepEqual(entries().map(entry => [entry.index, entry.visible]), [[0, true
assert.equal(state.data.rows, rows)
assert.equal(rows[1].value, '42')
// Owners alone classify rows. Names, route prefixes and IDs never imply a level or create links.
for (const id of ['lane_change:speed', 'AlphaLongitudinalEnabled', 'ExperimentalSpeedNudge']) assert.equal(settingLevel({ id }), 'simple')
for (const id of ['lane_change:speed', 'AlphaLongitudinalEnabled', 'ConvergeToSetSpeed']) assert.equal(settingLevel({ id }), 'simple')
assert.equal(settingLevel({ level: 'unknown' }), 'simple')
state.data = { page: 'hub', rows: [{ page: 'lane_change', label: 'Lane Changes' }] }
assert.deepEqual(entries().map(entry => entry.row.page), ['lane_change'])
@@ -41,7 +41,7 @@ class SoundDownloadsHttpTest(unittest.TestCase):
}]}))
parked = [True]
downloads = SoundDownloads(parked=lambda: parked[0], root=root / 'packs', catalog_path=catalog,
opener=lambda *args, **kwargs: io.BytesIO(data))
opener=lambda *args, **kwargs: io.BytesIO(data), selection=lambda: params.get("SoundPack"))
params = Params(str(root / 'params'))
params.put('SoundPack', 'stock', block=True)
context = SimpleNamespace(sample=lambda: AuthorityContext(parked[0], None, None))
@@ -99,6 +99,19 @@ class SoundDownloadsHttpTest(unittest.TestCase):
self.assertEqual(request('/api/sounds/download', {'pack': 'test'})[0], 409)
self.assertEqual(request('/api/sounds/download', {'pack': 'test', 'url': 'https://unrelated.example'})[0], 400)
self.assertEqual(request('/api/sounds/cancel', {'job': 'not-current'})[0], 409)
require_value(downloads._thread).join(timeout=2)
self.assertEqual(request('/api/sounds/delete', {'pack': 'test'}, origin='https://unrelated.example')[0], 403)
parked[0] = False
self.assertEqual(request('/api/sounds/delete', {'pack': 'test'})[0], 409)
parked[0] = True
params.put('SoundPack', 'test', block=True)
self.assertEqual(request('/api/sounds/delete', {'pack': 'test'})[0], 409)
params.put('SoundPack', 'stock', block=True)
status, removed = request('/api/sounds/delete', {'pack': 'test'})
self.assertEqual(status, 200)
self.assertFalse(removed['packs'][0]['installed'])
self.assertFalse((root / 'packs/test').exists())
self.assertEqual(params.get('SoundPack'), 'stock')
finally:
server.shutdown()
thread.join(timeout=2)
@@ -25,6 +25,25 @@ function fixture() {
return { feed, requests, states, installed, timers, respond, fire, get unauthorized() { return unauthorized } }
}
const removing = fixture()
removing.feed.start()
await removing.respond(0, snapshot(null, false, [{ ...packs[0], installed: true }, packs[1]]))
removing.feed.remove("one")
assert.equal(removing.requests.length, 1)
removing.feed.refresh()
await removing.respond(1, snapshot(null, true, [{ ...packs[0], installed: true }, packs[1]]))
removing.feed.remove("missing")
assert.equal(removing.requests.length, 2)
const deleted = []
removing.feed.removed = (pack) => deleted.push(pack)
removing.feed.remove("one")
assert.equal(removing.requests[2].url, "./api/sounds/delete")
assert.deepEqual(JSON.parse(removing.requests[2].options.body), { pack: "one" })
await removing.respond(2, snapshot())
assert.deepEqual(deleted, ["one"])
assert.equal(removing.feed.snapshot.packs[0].installed, false)
removing.feed.stop()
const normal = fixture()
normal.feed.start()
assert.equal(normal.requests[0].url, "./api/sounds")
@@ -145,11 +145,13 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
export function validDocument(document, metadata) {
if (!object(document)) return false
const profiles = metadata?.projection === true ? ["large"] : PROFILES
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 17) ||
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "borderWidth") ? ["borderWidth"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 17) ||
(Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") ||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
(Object.hasOwn(document, "clock24Hour") && typeof document.clock24Hour !== "boolean") ||
(Object.hasOwn(document, "borderWidth") && (!Number.isInteger(document.borderWidth) || document.borderWidth < 50 ||
document.borderWidth > 100 || document.borderWidth % 5 !== 0)) ||
(Object.hasOwn(document, "reduceMotion") && typeof document.reduceMotion !== "boolean") ||
(Object.hasOwn(document, "showMaxSpeed") && typeof document.showMaxSpeed !== "boolean") ||
(Object.hasOwn(document, "speedDisplayOffset") && (!Number.isFinite(document.speedDisplayOffset) || document.speedDisplayOffset < -5 || document.speedDisplayOffset > 5)) ||
@@ -104,9 +104,17 @@ export const ONROAD_LAYOUT_TEMPLATE = `
</g>
</template>
<rect v-if="!nativeBackdropReady" data-preview-source="scene-border"
:x="state.profile === 'compact' ? 4 : profile.bounds.x" :y="state.profile === 'compact' ? 4 : profile.bounds.y"
:width="state.profile === 'compact' ? 468 : roadBounds.width" :height="state.profile === 'compact' ? 232 : profile.bounds.height"
:rx="state.profile === 'compact' ? 14 : 61" fill="none" :stroke="sceneBorder" :stroke-width="state.profile === 'compact' ? 8 : 30" />
:x="projection ? profile.bounds.x : borderInset" :y="projection ? profile.bounds.y : borderInset"
:width="state.profile === 'compact' ? 476 - borderStroke : roadBounds.width + (projection ? 0 : 60 - 2 * borderInset)"
:height="projection ? profile.bounds.height : profile.height - 2 * borderInset"
:rx="state.profile === 'compact' ? 14 : 61" fill="none" :stroke="sceneBorder" :stroke-width="borderStroke" />
<rect v-if="!projection" class="gx-layout__widget" role="button" tabindex="0" style="cursor: pointer"
:class="{'is-editing': state.inspectorPanel === 'border'}" aria-label="Edit Screen Border"
:aria-pressed="state.inspectorPanel === 'border'" :x="borderInset" :y="borderInset"
:width="state.profile === 'compact' ? 476 - borderStroke : roadBounds.width + 60 - 2 * borderInset"
:height="profile.height - 2 * borderInset" :rx="state.profile === 'compact' ? 14 : 61"
fill="none" stroke="transparent" :stroke-width="state.profile === 'compact' ? 16 : 48"
@pointerdown.stop @click="openBorderEditor" @keydown.enter.prevent="openBorderEditor" @keydown.space.prevent="openBorderEditor" />
<rect v-if="state.showEditingAids" :x="roadBounds.x" :y="roadBounds.y" :width="roadBounds.width" :height="roadBounds.height" fill="none" stroke="#8495a855" stroke-width="2" stroke-dasharray="8 8" />
<g v-if="!projection && state.showFavoriteZones && state.showEditingAids" aria-hidden="true" pointer-events="none">
<g v-if="state.profile === 'large'">
@@ -198,6 +206,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<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="['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 === 'border'" :disabled="!!state.drag || !!state.layerDrag" @click="openBorderEditor">Border</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>
@@ -384,6 +393,14 @@ 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 === 'border'" ref="borderPanel" class="gx-layout__panel gx-layout__edit" aria-label="Edit Screen Border">
<div class="gx-layout__subhead"><h4>Screen Border</h4></div>
<label for="layout-border-width">Width · {{ borderWidth }}%</label>
<input id="layout-border-width" class="gx-slider" type="range" min="50" max="100" step="5" :value="borderWidth"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag"
@input="setBorderWidth($event.target.valueAsNumber)" @change="finishColorEdit" @blur="finishColorEdit">
<p class="gx-note">Applies to both comma layouts. The border stays in place and keeps its status colors.</p>
</section>
<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"
@@ -539,14 +539,19 @@ export const OnroadLayoutPage = {
publish: update => Object.assign(state.backdrop, update) })
const artFeed = new LayoutPreviewFeed({ art: true, unauthorized: props.unauthorized, queue,
publish: update => Object.assign(state.art, update) })
watch(() => [state.draft && JSON.stringify(state.draft), state.profile, state.scene, !!state.drag,
const widgetArtDraft = () => {
if (!state.draft || props.projection) return state.draft
const { borderWidth, ...document } = state.draft
return document
}
watch(() => [state.draft && JSON.stringify(widgetArtDraft()), state.profile, state.scene, !!state.drag,
!!state.layerDrag, state.data?.revision, state.data?.editable], () => {
if (props.mode !== "local" || !state.data?.editable || !state.draft) {
artFeed.stop()
return
}
if (!artFeed.active) artFeed.start()
const document = props.projection ? projectionPayload({document: state.draft}, state.data.metadata).document : layoutDocument(state.draft)
const document = props.projection ? projectionPayload({document: state.draft}, state.data.metadata).document : layoutDocument(widgetArtDraft())
artFeed.update(document, props.projection ? "projection" : state.profile, state.scene, !!state.drag || !!state.layerDrag)
}, {flush: "sync"})
// The real screen behind the arrangement: status border, road, alerts and sidebar, without the movable widgets.
@@ -605,6 +610,9 @@ export const OnroadLayoutPage = {
["Speed limit", scene => scene.id.startsWith("slc_")]].map(([label, test]) => ({ label, scenes: this.availableScenes.filter(test) }))
},
sceneBorder() { return previewScene(this.state.scene).border },
borderWidth() { return this.projection ? 100 : this.state.draft?.borderWidth ?? 100 },
borderStroke() { return Math.round((this.state.profile === "compact" ? 8 : 30) * this.borderWidth / 100) },
borderInset() { return this.state.profile === "compact" ? this.borderStroke / 2 : this.borderStroke },
expandedRoad() { return !this.projection && this.state.profile === "large" && this.displayValue("DeveloperSidebar") !== "On" },
roadBounds() { return this.expandedRoad ? { ...this.profile.bounds, width: this.profile.bounds.width + 300 } : this.profile.bounds },
favoriteZones() {
@@ -905,13 +913,19 @@ export const OnroadLayoutPage = {
this.state.inspectorPanel = "lead"
this.revealEditPanel()
},
openBorderEditor() {
if (this.projection || this.state.drag || this.state.layerDrag) return
this.deselectWidget()
this.state.inspectorPanel = "border"
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 = () => {
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 (!["edit", "lead", "border"].includes(section)) return
const tabs = this.$refs.sections, panel = this.$refs[section + "Panel"]
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,6 +1257,16 @@ export const OnroadLayoutPage = {
this.state.notice = ""
showDraftChange()
},
setBorderWidth(value) {
if (!this.editable || this.projection || this.state.drag || this.state.layerDrag ||
!Number.isInteger(value) || value < 50 || value > 100 || value % 5) return
const before = clone(this.state.draft)
if (value === 100) delete this.state.draft.borderWidth
else this.state.draft.borderWidth = value
this.recordChange(before, "borderWidth")
this.state.notice = ""
showDraftChange()
},
setReduceMotion(value) {
if (this.state.profile !== 'large' || !this.editable || this.projection || this.state.drag || this.state.layerDrag || typeof value !== 'boolean') return
const before = clone(this.state.draft)
@@ -594,7 +594,7 @@ export const SettingsPage = {
</div></GxCollapse>
<div v-if="!cardIndex && !visibleRows.length" class="gx-empty"><template v-if="state.data.page === 'starport_options'">Turn on StarPort to manage connection options. <a class="gx-link" href="#/starport">Open StarPort setup</a></template><template v-else>No matching settings.</template></div>
</section></GxCollapse>
<GxCollapse><div v-if="state.data.page === 'sounds'" v-show="categoryVisible" :inert="!categoryVisible"><SoundPacks :unauthorized="unauthorized" :busy="busy" @installed="refreshSoundChoices" /></div></GxCollapse>
<GxCollapse><div v-if="state.data.page === 'sounds'" v-show="categoryVisible" :inert="!categoryVisible"><SoundPacks :unauthorized="unauthorized" :busy="busy" @installed="refreshSoundChoices" @removed="refreshSoundChoices" /></div></GxCollapse>
</template>
</div>
</Transition>
@@ -7,10 +7,10 @@ import { reactive } from "../vendor/vue/vue.esm-browser.js"
const RUNNING = new Set(["downloading", "verifying"])
export class SoundPacksFeed {
constructor({ publish, installed = () => {}, unauthorized = () => {},
constructor({ publish, installed = () => {}, removed = () => {}, unauthorized = () => {},
fetcher = (...args) => fetch(...args), later = (fn, ms) => setTimeout(fn, ms),
cancelTimer = (id) => clearTimeout(id) }) {
Object.assign(this, { publish, installed, unauthorized, fetcher, later, cancelTimer })
Object.assign(this, { publish, installed, removed, unauthorized, fetcher, later, cancelTimer })
this.active = false
this.generation = 0
this.request = null
@@ -88,6 +88,7 @@ export class SoundPacksFeed {
this.snapshot = payload
this.blocked = false
this.error = ""
if (path === "./api/sounds/delete") this.removed(body.pack)
this.publish({ status: "ready", snapshot: payload, busy: false, error: "" })
if (payload.job?.state === "complete" && payload.job.id != null && !this.seenComplete.has(payload.job.id)) {
this.seenComplete.add(payload.job.id)
@@ -122,6 +123,13 @@ export class SoundPacksFeed {
return this.run("./api/sounds/download", { pack })
}
remove(pack) {
if (!this.active || this.busy || this.blocked || !this.snapshot?.parked ||
!this.snapshot.packs.some((item) => item.id === pack && item.installed === true) ||
RUNNING.has(this.snapshot.job?.state)) return
return this.run("./api/sounds/delete", { pack })
}
cancel() {
const job = this.snapshot?.job
if (!this.active || this.busy || this.blocked || !this.snapshot?.parked || !RUNNING.has(job?.state) || job.id == null) return
@@ -133,11 +141,11 @@ export const SoundPacks = {
components: { GxState, GxIconButton, GxNotice },
props: { unauthorized: { type: Function, required: true }, disabled: { type: Boolean, default: false },
busy: { type: Boolean, default: false } },
emits: ["installed"],
emits: ["installed", "removed"],
setup(props, { emit }) {
const state = reactive({ status: "idle", snapshot: null, busy: false, error: "" })
const feed = new SoundPacksFeed({ publish: (update) => Object.assign(state, update),
installed: (pack) => emit("installed", pack), unauthorized: props.unauthorized })
installed: (pack) => emit("installed", pack), removed: (pack) => emit("removed", pack), unauthorized: props.unauthorized })
return { state, feed }
},
computed: {
@@ -155,13 +163,16 @@ export const SoundPacks = {
canDownload(pack) { return !this.disabled && !this.state.error && this.state.status === "ready" &&
this.state.snapshot?.parked === true && !this.running && pack.installed === false },
download(pack) { if (!this.busy && !this.state.busy && this.canDownload(pack)) return this.feed.download(pack.id) },
canRemove(pack) { return !this.disabled && !this.state.error && this.state.status === "ready" &&
this.state.snapshot?.parked === true && !this.running && pack.installed === true },
remove(pack) { if (!this.busy && !this.state.busy && this.canRemove(pack)) return this.feed.remove(pack.id) },
cancel() { if (!this.disabled && !this.busy && !this.state.busy) return this.feed.cancel() },
},
template: `
<section class="gx-card gx-settings__section" aria-label="Sound pack catalog" :inert="busy || state.busy" :aria-busy="busy || state.busy || undefined">
<div class="gx-section__header"><i class="bi bi-music-note-list" aria-hidden="true"></i>
<span class="gx-section__title">Sound pack catalog</span>
<span v-if="state.snapshot && !state.snapshot.parked" class="gx-note gx-settings__hint">Park the vehicle to download sound packs.</span>
<span v-if="state.snapshot && !state.snapshot.parked" class="gx-note gx-settings__hint">Park the vehicle to manage sound packs.</span>
</div>
<div class="gx-settings__grid gx-panel">
@@ -173,6 +184,8 @@ export const SoundPacks = {
<strong>{{ pack.name }}</strong>
<div class="gx-settings__controls gx-actions">
<span v-if="pack.installed" class="gx-chip">Installed</span>
<GxIconButton v-if="pack.installed" :label="'Remove ' + pack.name" icon="bi-trash"
:disabled="!canRemove(pack)" @click="remove(pack)" />
<GxIconButton v-else :label="'Download ' + pack.name" icon="bi-download" :disabled="!canDownload(pack)" @click="download(pack)" />
</div>
</div>
@@ -110,7 +110,7 @@ def torque_choice_cp(cp):
not cp.safetyConfigs or any(config.safetyModel in unsafe for config in cp.safetyConfigs)):
return None
from opendbc.car.interfaces import CarInterfaceBase
prepared = cp.as_reader().as_builder()
prepared = cp.as_builder() if hasattr(cp, 'as_builder') else cp.as_reader().as_builder()
CarInterfaceBase.configure_torque_tune(prepared.carFingerprint, prepared.lateralTuning)
return prepared if generic_torque_supported(prepared) else None
except (AttributeError, TypeError, ValueError, OverflowError, KeyError, NotImplementedError, OSError):
@@ -118,7 +118,7 @@ def torque_choice_cp(cp):
def prepare_controller(cp, raw):
"""Apply an explicit saved type before the interface and published CP exist."""
"""Apply the selected type before the interface and published CP exist."""
selected = selection_from_bytes(cp, raw)
if selected.source != 'invalid' and selected.force_torque and cp.lateralTuning.which() == 'pid':
prepared = torque_choice_cp(cp)
@@ -204,7 +204,16 @@ def model_turn_assist_supported(CP) -> bool:
return turn_assist_supported(CP) and policy_for(CP) == 'ioniq6'
def _golf_torque_default(cp) -> bool:
return (cp.brand == 'volkswagen' and cp.carFingerprint == 'VOLKSWAGEN_GOLF_MK7' and
cp.networkLocation == structs.CarParams.NetworkLocation.gateway and
cp.transmissionType in (structs.CarParams.TransmissionType.manual, structs.CarParams.TransmissionType.automatic) and
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.volkswagen)
def default_selection(CP) -> ControllerSelection:
if _golf_torque_default(CP) and torque_choice_cp(CP) is not None:
return ControllerSelection(ControllerMode.STANDARD, 'generic', 'default', force_torque=True)
policy = policy_for(CP)
use_starpilot = policy is not None and CP.brand != 'ford'
mode = ControllerMode.STARPILOT if use_starpilot else ControllerMode.STANDARD
@@ -251,8 +260,8 @@ def replace_mode(raw: bytes | None, CP, mode: ControllerMode, *, force_torque: b
document = {'version': DOCUMENT_VERSION, 'vehicles': {}} if raw is None else parse_document(raw)
vehicles = dict(document['vehicles'])
vehicles[str(CP.carFingerprint)] = {'brand': str(CP.brand), 'mode': mode.value}
if force_torque:
vehicles[str(CP.carFingerprint)]['forceTorque'] = True
if force_torque or (_golf_torque_default(CP) and mode == ControllerMode.STANDARD):
vehicles[str(CP.carFingerprint)]['forceTorque'] = force_torque
encoded = json.dumps({'version': DOCUMENT_VERSION, 'vehicles': vehicles},
sort_keys=True, separators=(',', ':'), allow_nan=False).encode()
if len(encoded) > MAX_DOCUMENT_BYTES:
@@ -268,6 +277,10 @@ def selection_from_bytes(CP, raw: bytes | None) -> ControllerSelection:
choice = parse_document(raw)['vehicles'].get(str(CP.carFingerprint))
if choice is None or choice['brand'] != str(CP.brand):
return default
# Previous Stock Controller entries omitted forceTorque. Apply the new Golf
# default to those entries and honor explicit PID choices saved afterward.
if default.force_torque and choice['mode'] == ControllerMode.STANDARD and 'forceTorque' not in choice:
return default
force_torque = choice.get('forceTorque', False)
choice_cp = torque_choice_cp(CP) if force_torque else CP
policy = policy_for(choice_cp) if choice_cp is not None else None
@@ -180,7 +180,15 @@ class HKGVehicleTorquePolicy(HKGShapedTorquePolicy):
transition = np.interp(abs(self.jerk_filter.x), (.8, 1.5), (1., 0.))
feedback = np.interp(abs(error), (.14, .38), (0., 1.))
damping += .35 * highway * curve * transition * feedback
return error * (1.0 - damping)
feedback = error * (1.0 - damping)
if abs(error) > .12 and abs(setpoint) < 1.55 and (1. < speed < 5. or 15. < speed < 31.):
road_weight = np.interp(speed, (15., 18., 27., 31.), (0., 1., 1., 0.))
crawl_weight = np.interp(speed, (1., 2., 3.5, 5.), (0., 1., 1., 0.))
turn_weight = np.interp(abs(setpoint), (.62, 1.55), (1., 0.))
steady_weight = np.interp(abs(self.jerk_filter.x), (.65, 1.5), (1., 0.))
error_weight = np.interp(abs(error), (.12, .38), (0., 1.))
feedback *= 1.0 - (.42 * road_weight + .22 * crawl_weight) * turn_weight * steady_weight * error_weight
return feedback
return error * (1.0 - shaping.KIA_CARNIVAL_HEV_CENTER_ERROR_REDUCTION * self.hev_center_weight)
def jerk_deadzone(self, setpoint, jerk, measurement, speed):
@@ -78,6 +78,19 @@ def test_developer_choice_saved_and_startup_snapshot_is_frozen(tmp_path, identit
assert not owner.apply(replace(request, value='Invented Controller'))
@pytest.mark.parametrize('identity', PID_CARS)
def test_reader_car_params_exposes_steering_controller_in_settings(tmp_path, identity):
cp = factory(identity).as_reader()
assert torque_choice_cp(cp) is not None
params = Params(str(tmp_path))
owner = FeatureSettingsOwner(params, lambda _: True, vehicle_fingerprint=lambda: identity, vehicle_params=lambda: cp)
for page in ('torque', 'torque/developer'):
state = owner.snapshot(page, parked=True, system_long=False, lateral_context=True, metric=False)
current = next(r for r in state.rows if r.key == DOCUMENT_KEY)
assert current.available and current.value == 'Stock Controller'
assert current.choices == ('Stock Controller', 'Torque Controller', 'StarPilot Controller')
@pytest.mark.parametrize('field,value', [('steerControlType', 'angle'), ('steerControlType', 'curvature'),
('brand', 'toyota'), ('notCar', True), ('passive', True), ('dashcamOnly', True), ('carFingerprint', 'UNKNOWN')])
def test_forced_choice_refuses_unsupported_configuration(field, value):
@@ -150,3 +163,67 @@ def test_every_eligible_factory_pid_can_select_and_restore():
assert original.to_dict() == before, identity
supported.append(identity)
assert set(PID_CARS).issubset(supported)
@pytest.mark.parametrize('automatic', (False, True))
@pytest.mark.parametrize('alpha', (False, True))
def test_gateway_golf_upgrades_once_and_can_keep_stock_pid(tmp_path, automatic, alpha):
from opendbc.car import gen_empty_fingerprint
identity = 'VOLKSWAGEN_GOLF_MK7'
interface = interfaces[identity]
fingerprints = gen_empty_fingerprint()
fingerprints[1][0xFD] = 8
if automatic:
fingerprints[0][0xAD] = 8
def golf():
return interface.get_params(identity, fingerprints, [], alpha, False, False)
params = Params(str(tmp_path))
cp = golf()
factory_config = cp.to_dict()
legacy = {'version': 1, 'vehicles': {identity: {'brand': 'volkswagen', 'mode': 'standard'}}}
for saved in (None, json.dumps(legacy).encode()):
torque = prepare_controller(golf(), saved)
assert torque.lateralTuning.which() == 'torque'
before = torque.to_dict()
before['lateralTuning'] = factory_config['lateralTuning']
assert before == factory_config
choice = selection_from_bytes(torque, saved)
assert choice.force_torque and choice.mode == ControllerMode.STANDARD
ci = interface(torque)
control = create_lateral_controller(torque.as_reader(), ci, DT_CTRL, mode=choice.mode)
assert type(control).__name__ == 'LatControlTorque' and control.starpilot_extension is None
params.put(DOCUMENT_KEY, legacy, block=True)
owner = FeatureSettingsOwner(params, lambda _: True, vehicle_fingerprint=lambda: identity, vehicle_params=lambda: torque.as_reader())
def row():
state = owner.snapshot('torque/developer', parked=True, system_long=alpha, lateral_context=True, metric=False)
return next(r for r in state.rows if r.key == DOCUMENT_KEY)
current = row()
assert current.value == current.default_value == 'Torque Controller'
assert owner.apply(FeatureSettingsRequest(current.key, current.source, 'Stock Controller', vehicle_fingerprint=identity,
capability=current.capability, dependencies=current.dependencies))
current = row()
assert current.value == 'Stock Controller' and 'Torque Controller' in current.choices
assert parse_document(current.source)['vehicles'][identity]['forceTorque'] is False
for _ in range(2):
assert VehicleStartupPreferences.read(params, enabled=True).prepare(golf()).to_dict() == factory_config
assert owner.apply(FeatureSettingsRequest(current.key, current.source, 'StarPilot Controller', vehicle_fingerprint=identity,
capability=current.capability, dependencies=current.dependencies))
other_raw = row().source
assert parse_document(other_raw)['vehicles'][identity]['forceTorque'] is True
assert selection_from_bytes(golf(), other_raw).mode == ControllerMode.STARPILOT
assert VehicleStartupPreferences.read(params, enabled=False).prepare(golf()).to_dict() == factory_config
assert prepare_controller(golf(), b'{}').to_dict() == factory_config
fingerprints[1].clear()
assert prepare_controller(golf(), None).lateralTuning.which() == 'pid'
fingerprints[1][0xFD] = 8
fingerprints[0].pop(0xAD, None)
fingerprints[0][0x187] = 8
assert prepare_controller(golf(), None).lateralTuning.which() == 'pid'
@@ -174,9 +174,9 @@ def test_tucson_softens_shallow_curve_feedback_in_both_cruise_modes():
policy = controller.starpilot_extension.policy
for direction in (-1., 1.):
assert math.isclose(policy.pid_error_context(direction, direction * .5, 13.), direction * .55)
for speed, demand in ((4., .5), (31., .5), (13., 1.15)):
for speed, demand in ((1., .5), (31., .5), (13., 1.15)):
assert policy.pid_error_context(direction, direction * demand, speed) == direction
for demand, speed, base_scale in ((.5, 19., .8875), (.9, 13., .925)):
for demand, speed, base_scale in ((.5, 19., .8875 * .58), (.9, 13., .925)):
assert math.isclose(policy.pid_error_context(1., demand, speed), base_scale)
policy.jerk_filter.x = -1.0
assert math.isclose(policy.pid_error_context(1., .5, 13.), .85)
@@ -196,7 +196,7 @@ def test_tucson_highway_feedback_damps_large_errors_without_touching_steady_trac
_, controller = controller_for(CAR.HYUNDAI_TUCSON_4TH_GEN, ControllerMode.STARPILOT)
policy = controller.starpilot_extension.policy
for side in (-1., 1.):
assert math.isclose(policy.pid_error_context(side * .5, side * .8, 25.), side * .325)
assert math.isclose(policy.pid_error_context(side * .5, side * .8, 25.), side * .325 * (1. - .42 * (1.55 - .8) / (1.55 - .62)))
assert policy.pid_error_context(side * .1, side * .8, 25.) == side * .1
assert policy.pid_error_context(side * .5, side * 1.7, 25.) == side * .5
assert policy.pid_error_context(side * .5, side * .8, 31.) == side * .5
@@ -247,3 +247,24 @@ def test_tucson_damps_large_road_speed_corrections_in_both_cruise_modes():
setattr(policy, pressed, True)
assert scale(22., .7, .52) == scale(22., .7, .0)
setattr(policy, pressed, False)
def test_tucson_reduces_wobble_feedback_without_dulling_small_corrections():
for alpha_long in (False, True):
_, controller = controller_for(CAR.HYUNDAI_TUCSON_4TH_GEN, ControllerMode.STARPILOT,
openpilotLongitudinalControl=alpha_long, pcmCruise=not alpha_long)
policy = controller.starpilot_extension.policy
for side in (-1., 1.):
assert math.isclose(policy.pid_error_context(side * .5, side * .5, 2.5), side * .39)
assert math.isclose(policy.pid_error_context(side * .5, side * .5, 20.), side * .5 * .925 * .58)
assert policy.pid_error_context(side * .1, side * .5, 2.5) == side * .1
assert policy.pid_error_context(side * .5, side * 1.55, 20.) == side * .5
assert policy.pid_error_context(side * .5, side * .5, 1.) == side * .5
policy.jerk_filter.x = 1.5
assert math.isclose(policy.pid_error_context(side * .5, side * .5, 20.), side * .5 * .925)
policy.jerk_filter.x = 0.
for field in ('steering_pressed', 'previous_pressed'):
setattr(policy, field, True)
assert policy.pid_error_context(side * .5, side * .5, 20.) == side * .5
setattr(policy, field, False)
@@ -5,7 +5,7 @@ import math
from openpilot.starpilot.curve_speed.preferences import GENTLE_KEY
from openpilot.starpilot.saved_source import read_saved
KEY = "ExperimentalSpeedNudge"
KEY = "ConvergeToSetSpeed"
BOOST_KEYS = {name: name.title() + "PersonalityBoost" for name in ("relaxed", "standard", "aggressive", "traffic")}
MAX_BOOST_PERCENT = 200.0
@@ -18,6 +18,17 @@ MIN_HESITATION_GAP = 1.
HESITATION_ACCEL = .3
RECOVERY_ACCEL = .6
HESITATION_FILTER_SECONDS = .5
CONVERGENCE_MAX_LATERAL_ACCEL = 2.0
def opening_lead(lead, target_speed, follow_seconds):
if not lead.present:
return True
if follow_seconds is None or not math.isfinite(follow_seconds) or follow_seconds <= 0.0:
return False
return (all(math.isfinite(x) for x in (lead.dRel, lead.vRel, lead.vLead, lead.vLeadK, lead.aLeadK)) and
lead.dRel > max(20., 11. + target_speed * follow_seconds) and lead.vRel > .5 and
min(lead.vLead, lead.vLeadK) >= target_speed - .25 and lead.aLeadK > -.25)
class Encouragement:
@@ -26,10 +37,11 @@ class Encouragement:
self.boost = 0.
self.drive_id = None
self.last_model_ns = 0
self.converging = False
self.hesitation_accel: float | None = None
def update(self, sm, cp, *, now_ns, drive_id, dt, target_speed, model_accel, mpc_accel, cruise_accel,
lateral_accel, blocked, scale=1.0):
lateral_accel, blocked, scale=1.0, converge=False, follow_seconds=None):
eligible = False
model_ns = 0
try:
@@ -45,18 +57,21 @@ class Encouragement:
sm['carControl'].longActive and car.canValid and not car.canTimeout and
not car.gasPressed and not car.brakePressed and not car.standstill and
not sm['controlsState'].forceDecel and not sm['modelV2'].action.shouldStop and
not sm['radarState'].leadOne.present and not sm['radarState'].leadTwo.present and
all(opening_lead(lead, target_speed, follow_seconds) if converge else not lead.present
for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
not any(sm['radarState'].radarErrors.to_dict().values()) and
all(math.isfinite(x) for x in (dt, target_speed, model_accel, mpc_accel, cruise_accel, lateral_accel, car.vEgo, car.aEgo)) and
0 < dt <= .1 and car.vEgo >= 4.5 and target_speed - car.vEgo > .2 and
model_accel >= 0 and abs(lateral_accel) < .5 and min(mpc_accel, cruise_accel) > model_accel)
model_accel >= 0 and abs(lateral_accel) < (CONVERGENCE_MAX_LATERAL_ACCEL if converge else .5) and
min(mpc_accel, cruise_accel) > model_accel)
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
eligible = False
if type(model_ns) is not int or model_ns <= 0:
model_ns = 0
eligible = False
if drive_id != self.drive_id or model_ns <= self.last_model_ns:
if drive_id != self.drive_id or model_ns <= self.last_model_ns or converge != self.converging:
eligible = False
self.converging = converge
self.drive_id = drive_id
self.last_model_ns = model_ns
if not eligible:
@@ -75,7 +90,8 @@ class Encouragement:
if self.clear_seconds > SETTLE_SECONDS and car.aEgo < RECOVERY_ACCEL:
self.boost = min(MAX_BOOST, self.boost + BOOST_RATE * dt)
gap_scale = min(1., max(0., (target_speed - car.vEgo - .2) / 1.8))
bonus = max(0.0, self.boost * gap_scale - model_accel)
turn_scale = min(1., (CONVERGENCE_MAX_LATERAL_ACCEL - abs(lateral_accel)) / .25) if converge else 1.
bonus = max(0.0, self.boost * gap_scale * turn_scale - model_accel)
return min(model_accel + scale * bonus, mpc_accel, cruise_accel)
+22 -5
View File
@@ -5,10 +5,11 @@ import math
from openpilot.common.realtime import DT_CTRL
from openpilot.starpilot.longitudinal.force_stop_braking import eligible as distance_braking_eligible
from opendbc.car.structs import car
from opendbc.car.toyota.pedal import supports_standstill_resume
from openpilot.starpilot.longitudinal.toyota_output_policy import COROLLA, ToyotaOutputPolicy, development_enabled, production_enabled
from openpilot.starpilot.longitudinal.ioniq6_start import Ioniq6StartPolicy, StartEvidence, eligible as ioniq6_start_eligible
from openpilot.starpilot.longitudinal.vehicle_policy import policy_for as vehicle_policy_for, stopping_decel_rate, stopping_policy_for
from opendbc.car.gm.longitudinal import GMPedalStartPolicy, volt_sng_resume_policy_for
from opendbc.car.gm.longitudinal import GMPedalLongitudinalPolicy, GMPedalStartPolicy, volt_sng_resume_policy_for
from opendbc.car.gm.bolt_mode import policy_for as bolt_mode_policy_for
LongCtrlState = car.CarControl.Actuators.LongControlState
@@ -29,6 +30,7 @@ class LongitudinalContext:
force_stop_braking: bool = False
toyota_resume_fresh: bool = False
toyota_brake_release: bool = False
bolt_cruise_settle: bool = False
class LongitudinalExtension:
@@ -44,6 +46,7 @@ class LongitudinalExtension:
toyota_production = production_enabled(CP)
self.toyota_stopped_lead = toyota_production and str(CP.carFingerprint) == COROLLA
self.toyota_pcm_resume = self.toyota_stopped_lead and CP.autoResumeSng
self.toyota_pedal_resume = supports_standstill_resume(CP)
self.toyota_output = ToyotaOutputPolicy(CP) if toyota_production or development_enabled(CP) else None
self.ioniq6_start = Ioniq6StartPolicy() if ioniq6_start_eligible(CP) else None
self.force_stop_distance_braking = distance_braking_eligible(CP)
@@ -99,6 +102,16 @@ class LongitudinalExtension:
if self.stopping_policy is not None:
state = self.stopping_policy.transition(state, previous_state, active, CS, a_target, should_stop,
has_lead=context.has_lead)
if self.toyota_pedal_resume and active and CS.standstill and CS.cruiseState.standstill:
# This PCM stays latched until it receives a positive request. Only a
# current departure plan may release it through the existing pedal path.
can_resume = (context.toyota_brake_release and not should_stop and not context.force_stop_braking and
math.isfinite(a_target) and a_target >= 0.1 and CS.canValid and not CS.canTimeout and
CS.cruiseState.available and CS.cruiseState.enabled and not CS.stockAeb and not CS.accFaulted and
not CS.brakePressed and not CS.gasPressed and not CS.doorOpen and not CS.seatbeltUnlatched and
not CS.steerFaultTemporary and not CS.steerFaultPermanent and
CS.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport))
return LongCtrlState.pid if can_resume else LongCtrlState.stopping
if (self.toyota_pcm_resume and self.toyota_output is not None and active and
CS.standstill and CS.cruiseState.standstill):
# The PCM clears its hold after the controller sends a positive request.
@@ -156,9 +169,13 @@ class LongitudinalExtension:
self.bolt_mode.update(context.experimental_mode, DT_CTRL)
feedforward = (self.vehicle_policy.feedforward(a_target, CS.vEgo, last_output)
if self.vehicle_policy is not None else a_target)
freeze_integrator = (self.vehicle_policy.prepare_pid(pid, a_target, error, CS.vEgo, last_output, accel_limits,
should_stop=should_stop, has_lead=context.has_lead)
if self.vehicle_policy is not None else False)
freeze_integrator = False
if context.bolt_cruise_settle and isinstance(self.vehicle_policy, GMPedalLongitudinalPolicy):
freeze_integrator = self.vehicle_policy.prepare_pid(pid, a_target, error, CS.vEgo, last_output, accel_limits,
should_stop=should_stop, gentle_cruise_settle=True)
elif self.vehicle_policy is not None:
freeze_integrator = self.vehicle_policy.prepare_pid(pid, a_target, error, CS.vEgo, last_output, accel_limits,
should_stop=should_stop, has_lead=context.has_lead)
if self.stopping_policy is not None:
feedforward, stop_freeze = self.stopping_policy.prepare_pid(pid, a_target, error, CS, context)
freeze_integrator |= stop_freeze
@@ -182,7 +199,7 @@ def create_extension(cp, startup_preferences=None):
extension = LongitudinalExtension(cp, startup_preferences)
if (extension.vehicle_policy is None and extension.toyota_output is None and extension.ioniq6_start is None and
extension.bolt_mode is None and extension.stopping_policy is None and extension.stopping_decel_rate == 1.0 and
not extension.ignore_cruise_standstill and not extension.force_stop_distance_braking):
not extension.ignore_cruise_standstill and not extension.force_stop_distance_braking and not extension.toyota_pedal_resume):
return None
return extension
@@ -3,6 +3,7 @@
from dataclasses import replace
import math
from opendbc.car.gm.values import CAR as GM, is_bolt_euv_longitudinal
from openpilot.starpilot.conditional_mode.curve import frozen_raw_curve
from openpilot.starpilot.conditional_mode.preferences import CEMOptions, decode_preferences, PreferenceError
from openpilot.starpilot.conditional_mode.projection import _horizon
@@ -215,7 +216,13 @@ class ForceStopRuntime:
kona_handoff = distance_enabled and kona_eligible(cp)
tune = replace(vehicle_tune(str(cp.carFingerprint)), distance_control=distance_enabled and not kona_handoff,
distance_handoff=kona_handoff)
self.plan = self.policy.step(frame, tune, self.offset)
offset_ft = self.offset
model_stop = frame.light or (self.policy.forcing and self.policy.from_light)
if (offset_ft == 0 and cp.carFingerprint == GM.CHEVROLET_BOLT_ACC_2022_2023 and is_bolt_euv_longitudinal(cp) and
model_stop and not (frame.sign or frame.lead_present or frame.tracking_lead or self.policy.sign_confirmed or
self.policy.queue_line is not None)):
offset_ft = 4
self.plan = self.policy.step(frame, tune, offset_ft)
if takeoff_enabled:
self.plan = replace(self.plan, takeoff_light_observed=takeoff_observed, takeoff_light=takeoff_light)
return self.plan
+27 -1
View File
@@ -5,12 +5,14 @@ import os
import time
from opendbc.car.interfaces import ACCEL_MAX
from opendbc.car.toyota.pedal import supports_standstill_resume
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
from opendbc.car.hyundai.blended_stopping import eligible as blended_longitudinal_eligible
from openpilot.starpilot.feature_runtime import enabled as feature_enabled
from openpilot.starpilot.conditional_mode.traffic_launch import TrafficLaunchState
from openpilot.starpilot.conditional_mode.ui_action import fresh_service
from openpilot.starpilot.longitudinal.toyota_output_policy import (CLOCK_PAIR_MAX_SKEW_NS, COROLLA, SIENNA_4G, clock_pair_ns,
development_enabled as toyota_development_enabled,
production_enabled as toyota_production_enabled, leads_from_radar)
@@ -19,6 +21,7 @@ from openpilot.starpilot.longitudinal.force_stop_braking import eligible as dist
from openpilot.starpilot.longitudinal.lead_takeoff_preferences import TakeoffPreferences
from openpilot.starpilot.longitudinal.takeoffs import eligible as takeoff_eligible
from opendbc.car.gm.conventional_pedal import policy_for as conventional_pedal_policy_for
from opendbc.car.gm.values import NO_ACC_BOLT_CAR
from opendbc.car.gm.ordinary_cc import policy_for as ordinary_cc_policy_for
from opendbc.car.gm.hybrid_cc import policy_for as hybrid_policy_for
from opendbc.car.gm.suburban import SuburbanStopEvidence
@@ -85,11 +88,13 @@ class LongitudinalInputs:
self.toyota_sienna_replay = toyota_development_enabled(self.CP) and str(self.CP.carFingerprint) == SIENNA_4G
toyota_production = toyota_production_enabled(self.CP)
self.toyota_corolla_stop = toyota_production and str(self.CP.carFingerprint) == COROLLA
self.toyota_pedal_resume = supports_standstill_resume(self.CP)
self.toyota_sienna_production = toyota_production and str(self.CP.carFingerprint) == SIENNA_4G
self.ioniq6_start_enabled = ioniq6_start_eligible(self.CP)
self.force_stop_distance_braking = distance_braking_eligible(self.CP)
gm_policy = gm_pedal_policy_for(self.CP)
self.gm_start_enabled = gm_policy is not None and gm_policy.friction_variant
self.bolt_cruise_settle = gm_policy is not None and cp.carFingerprint in NO_ACC_BOLT_CAR
installed_policy = installed_policy_for(self.CP)
stop_policy = installed_policy.stop_policy() if hasattr(installed_policy, 'stop_policy') else None
evidence_type = getattr(stop_policy, 'evidence_type', None)
@@ -139,7 +144,7 @@ class LongitudinalInputs:
return ['radarState', 'deviceState', 'starpilotLongitudinalPlan'] + (['slcState'] if self.ev9_long_enabled else [])
if (self.toyota_sienna_replay or self.toyota_sienna_production or self.toyota_corolla_stop or
self.ioniq6_start_enabled or self.gm_start_enabled or self.gm_volt_enabled or self.gm_euv_enabled or
self.gm_cc_enabled or self.gm_cc_stop_enabled or self.gm_ascm_enabled or self.gm_suburban_enabled):
self.gm_cc_enabled or self.gm_cc_stop_enabled or self.gm_ascm_enabled or self.gm_suburban_enabled or self.bolt_cruise_settle):
return ['radarState', 'deviceState'] + (['slcState'] if self.gm_start_enabled or self.ev9_long_enabled else [])
if self.ev9_long_enabled:
return ['radarState', 'deviceState', 'slcState']
@@ -179,6 +184,11 @@ class LongitudinalInputs:
can_release_brake = (resume_fresh and self.sm['longitudinalPlan'].allowThrottle and
not self.sm['longitudinalPlan'].fcw)
return LongitudinalContext(leads=leads, toyota_resume_fresh=resume_fresh, toyota_brake_release=can_release_brake)
if self.toyota_pedal_resume and active:
cs = self.sm['carState']
plan = self.sm['longitudinalPlan']
if cs.standstill and cs.cruiseState.standstill:
return LongitudinalContext(toyota_brake_release=self.resume_sources_current() and plan.allowThrottle and not plan.fcw)
cc_evidence = (self.gm_cc_evidence if self.gm_cc_enabled else self._gm_cc_evidence()
if self.gm_cc_stop_enabled and active else None)
volt_observation = self._gm_volt_observation() if self.gm_volt_enabled and active else None
@@ -186,6 +196,7 @@ class LongitudinalInputs:
experimental_mode=bool(self.sm['selfdriveState'].experimentalMode) if self.sm.all_checks(['selfdriveState']) else None,
start_evidence=self._ioniq6_start_evidence() if self.ioniq6_start_enabled else None,
gm_start_evidence=self._gm_start_evidence() if self.gm_start_enabled and active else None,
bolt_cruise_settle=active and self.bolt_cruise_settle and self._bolt_cruise_settle(),
has_lead=(bool(self.sm['longitudinalPlan'].hasLead)
if self.blended_longitudinal_enabled and self.sm.all_checks(['longitudinalPlan'])
else cc_evidence.has_lead if cc_evidence is not None else volt_observation[0]
@@ -197,6 +208,21 @@ class LongitudinalInputs:
)
def _bolt_cruise_settle(self):
sm = self.sm
cs, plan, state, device = (sm[name] for name in ('carState', 'longitudinalPlan', 'selfdriveState', 'deviceState'))
if (not device.started or not state.enabled or state.experimentalMode or
not cs.canValid or cs.canTimeout or cs.gasPressed or cs.brakePressed or cs.regenBraking or
cs.vEgo < 20. or not 0. < cs.vEgo - cs.vCruise / 3.6 < .224 or
not -.10 < plan.aTarget < -.05 or plan.longitudinalPlanSource != 'cruise' or
plan.hasLead or plan.shouldStop or plan.fcw or not plan.allowThrottle):
return False
radar = sm['radarState']
now, drive = time.monotonic_ns(), device.startedMonoTime
return (not (radar.leadOne.present or radar.leadTwo.present) and 0 < drive < now and
fresh_service(sm, 'deviceState', drive, now, 2_000_000_000) and
all(fresh_service(sm, name, drive, now) for name in ('carState', 'longitudinalPlan', 'selfdriveState', 'radarState')))
def resume_sources_current(self):
return self.resume_freshness.current(self.sm)
@@ -16,7 +16,7 @@ def attach_inputs(controls):
inputs.faster_takeoffs = False
inputs.force_stop_distance_braking = False
for name in ('ev9_long_enabled', 'blended_longitudinal_enabled', 'toyota_sienna_replay', 'toyota_sienna_production', 'toyota_corolla_stop',
'ioniq6_start_enabled', 'gm_start_enabled', 'gm_volt_enabled', 'gm_euv_enabled',
'toyota_pedal_resume', 'ioniq6_start_enabled', 'gm_start_enabled', 'gm_volt_enabled', 'gm_euv_enabled', 'bolt_cruise_settle',
'gm_cc_enabled', 'gm_cc_stop_enabled', 'gm_ascm_enabled', 'gm_suburban_enabled'):
setattr(inputs, name, False)
inputs.gm_cc_evidence = None
@@ -1,14 +1,19 @@
from openpilot.starpilot.longitudinal.tests.extension_helpers import extension_state
from openpilot.starpilot.longitudinal.tests.extension_helpers import empty_params, extension_state
from types import SimpleNamespace
import unittest
from unittest.mock import patch
from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.gm.interface import CarInterface
from opendbc.car.gm.values import CAR
from opendbc.car.gm.bolt_cc import BoltCcLongitudinalPolicy
from opendbc.car.gm.longitudinal import GMPedalLongitudinalPolicy
from openpilot.cereal import log, messaging
from openpilot.common.realtime import DT_CTRL
from openpilot.selfdrive.controls.lib.longcontrol import LongControl
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
from openpilot.starpilot.longitudinal.inputs import LongitudinalInputs
from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import messages
def params(identity, pedal=False):
@@ -21,6 +26,61 @@ def params(identity, pedal=False):
class TestBoltCcIntegrator(unittest.TestCase):
def test_non_acc_pedal_bolts_share_the_same_cruise_correction(self):
settings = empty_params(self)
state = structs.CarState.new_message(vEgo=34.483, aEgo=.292)
expected = None
for identity in (CAR.CHEVROLET_BOLT_CC_2017, CAR.CHEVROLET_BOLT_CC_2018_2021, CAR.CHEVROLET_BOLT_CC_2022_2023):
cp = params(identity, pedal=True)
inputs = LongitudinalInputs(cp, settings, dict)
self.assertTrue(inputs.bolt_cruise_settle)
self.assertIn('radarState', inputs.optional_services)
control = LongControl(cp)
control.pid.i = .34
result = control.update(True, state, -.06, False, (-3., 2.),
context=LongitudinalContext(bolt_cruise_settle=inputs.bolt_cruise_settle))
if expected is None:
expected = result
self.assertEqual(result, expected)
for cp in (params(CAR.CHEVROLET_BOLT_ACC_2022_2023_PEDAL, pedal=True), params(CAR.CHEVROLET_BOLT_CC_2022_2023)):
self.assertFalse(LongitudinalInputs(cp, settings, dict).bolt_cruise_settle)
def test_mild_cruise_correction_retains_pedal_integrator_only_with_current_evidence(self):
cp = params(CAR.CHEVROLET_BOLT_CC_2018_2021, pedal=True)
sm, _ = messages()
plan = log.LongitudinalPlan.new_message(aTarget=-.06, allowThrottle=True, longitudinalPlanSource='cruise')
device = messaging.new_message('deviceState').deviceState
device.started, device.startedMonoTime = True, 1_000_000_000
state = sm['carState']
state.canValid, state.vCruise, state.vEgo, state.aEgo = True, 123.9, 34.483, .292
sm.update(longitudinalPlan=plan, deviceState=device)
inputs = LongitudinalInputs.__new__(LongitudinalInputs)
inputs.messages = lambda: sm
for checks, lead, target, source, stop, permitted in (
(True, False, -.06, 'cruise', False, True),
(False, False, -.06, 'cruise', False, False),
(True, True, -.06, 'cruise', False, False),
(True, False, -.20, 'cruise', False, False),
(True, False, -.06, 'e2e', False, False),
(True, False, -.06, 'cruise', True, False),
):
plan.hasLead, plan.aTarget, plan.longitudinalPlanSource, plan.shouldStop = lead, target, source, stop
with patch('openpilot.starpilot.longitudinal.inputs.time.monotonic_ns', return_value=2_000_000_000), \
patch('openpilot.starpilot.longitudinal.inputs.fresh_service', return_value=checks):
settle = inputs._bolt_cruise_settle()
self.assertEqual(settle, permitted)
controller = LongControl(cp)
controller.pid.i = .34
controller.update(True, state, target, stop, (-3., 2.), context=LongitudinalContext(bolt_cruise_settle=settle))
if permitted:
self.assertGreater(controller.pid.i, .32)
else:
self.assertLess(controller.pid.i, .19)
plan.shouldStop = False
sm['radarState'].leadTwo.present = True
with patch('openpilot.starpilot.longitudinal.inputs.fresh_service', return_value=True):
self.assertFalse(inputs._bolt_cruise_settle())
def test_actual_longcontrol_reduces_stale_positive_integrator_during_deceleration(self):
for identity in (CAR.CHEVROLET_BOLT_CC_2017, CAR.CHEVROLET_BOLT_CC_2018_2021, CAR.CHEVROLET_BOLT_CC_2022_2023):
controller = LongControl(params(identity))
@@ -92,7 +92,7 @@ def test_native_planner_helps_weak_clear_road_recovery_toward_set_speed(factory,
sm['carState'].aEgo = .2
sm['carState'].vCruise = 22.24 * 3.6
sm['modelV2'].action.desiredAcceleration = .2
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.mpc.solution_status == 0
assert planner.output_a_target <= planner.a_cruise + 1e-6
assert not planner.output_should_stop
@@ -103,7 +103,7 @@ def test_native_planner_helps_weak_clear_road_recovery_toward_set_speed(factory,
sm['carState'].aEgo = .2
sm['carState'].vCruise = 22.24 * 3.6
sm['modelV2'].action.desiredAcceleration = .2
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.encouragement.boost == pytest.approx(MAX_BOOST)
@@ -149,8 +149,8 @@ def test_native_planner_normal_acceleration_is_unchanged(factory, car):
sm['carState'].aEgo = .4
sm['modelV2'].action.desiredAcceleration = .4
with patch.object(original.encouragement, 'update', side_effect=lambda *a, **kw: kw['model_accel']):
original.update(sm, now_ns=now)
current.update(sm, now_ns=now)
original.update(sm, now_ns=now, experimental_speed_nudge=True)
current.update(sm, now_ns=now, experimental_speed_nudge=True)
assert current.output_a_target == original.output_a_target
assert current.output_should_stop == original.output_should_stop
assert current.encouragement.boost == 0.
@@ -249,8 +249,8 @@ def test_real_native_planner_clear_road_across_families(factory, car):
for tick in range(120):
sm, now = frame(tick)
with patch.object(original.encouragement, 'update', side_effect=lambda *a, **kw: kw['model_accel']):
original.update(sm, now_ns=now)
current.update(sm, now_ns=now)
original.update(sm, now_ns=now, experimental_speed_nudge=True)
current.update(sm, now_ns=now, experimental_speed_nudge=True)
assert current.mpc.solution_status == original.mpc.solution_status == 0
assert current.output_a_target >= original.output_a_target
assert current.output_a_target <= current.a_cruise + 1e-6
@@ -281,7 +281,7 @@ def test_native_planner_limits_and_immediate_withdrawal(case):
if case == 'slc':
options['cruise_ceiling'] = CruiseCeiling(19., ACTIVE)
if case == 'turn':
sm['carState'].steeringAngleDeg = 5.
sm['carState'].steeringAngleDeg = 20.
if case == 'force':
sm['controlsState'].forceDecel = True
if case == 'throttle':
@@ -297,8 +297,8 @@ def test_native_planner_limits_and_immediate_withdrawal(case):
if case == 'traffic':
options['traffic_mode'] = None
with patch.object(original.encouragement, 'update', side_effect=lambda *a, **kw: kw['model_accel']):
original.update(sm, now_ns=now, **options)
current.update(sm, now_ns=now, **options)
original.update(sm, now_ns=now, experimental_speed_nudge=True, **options)
current.update(sm, now_ns=now, experimental_speed_nudge=True, **options)
assert current.mpc.solution_status == original.mpc.solution_status == 0
if tick >= 90:
assert current.output_a_target <= original.output_a_target + 1e-6
@@ -315,17 +315,17 @@ def test_native_planner_override_release_uses_higher_request_without_stacking(fa
planner = LongitudinalPlanner(params, init_v=20.)
for tick in range(220):
sm, now = frame(tick)
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.encouragement.boost == pytest.approx(MAX_BOOST)
for tick in range(220, 260):
sm, now = frame(tick)
sm['carState'].gasPressed = True
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.encouragement.boost == 0.
assert planner.accel_boost.total_boost == pytest.approx(.05)
for tick in range(260, 480):
sm, now = frame(tick)
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.mpc.solution_status == 0
assert planner.accel_boost.total_boost == pytest.approx(.05)
assert planner.output_a_target <= max(.05, planner.encouragement.boost) + 1e-6
@@ -334,7 +334,7 @@ def test_native_planner_override_release_uses_higher_request_without_stacking(fa
assert planner.output_a_target == pytest.approx(MAX_BOOST, abs=.01)
sm, now = frame(480)
sm['selfdriveState'].enabled = False
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.accel_boost.total_boost == planner.encouragement.boost == 0.
@@ -359,14 +359,14 @@ def test_native_planner_preserves_manual_override_input_and_boost():
for tick in range(120):
sm, now = frame(tick)
with patch.object(planner.accel_boost, 'update', wraps=planner.accel_boost.update) as manual:
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert manual.call_args.args[1] == 0.
assert planner.encouragement.boost > 0.
assert planner.accel_boost.boost_eligible
for tick in range(120, 160):
sm, now = frame(tick)
sm['carState'].gasPressed = True
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.encouragement.boost == 0.
assert planner.accel_boost.total_boost == pytest.approx(.05)
@@ -380,7 +380,7 @@ def test_native_planner_reaches_clear_road_boost_plateau(factory, car):
planner = LongitudinalPlanner(params, init_v=20.)
for tick in range(220):
sm, now = frame(tick)
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.mpc.solution_status == 0
assert planner.output_a_target <= planner.a_cruise + 1e-6
assert planner.encouragement.boost == pytest.approx(MAX_BOOST)
@@ -408,7 +408,7 @@ def test_native_planner_recovers_despite_recorded_acceleration_noise(factory, ca
sm['carState'].vEgo, sm['carState'].aEgo, sm['carState'].vCruise = speed, accel, set_kph
sm['selfdriveState'].experimentalMode = experimental
sm['modelV2'].action.desiredAcceleration = model_accel
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.mpc.solution_status == 0
assert planner.output_a_target <= planner.a_cruise + 1e-6
assert not planner.output_should_stop
@@ -446,7 +446,7 @@ def test_native_planner_speed_nudge_off_removes_entire_automatic_floor(factory,
planner = LongitudinalPlanner(params, init_v=20.)
for tick in range(220):
sm, now = frame(tick)
planner.update(sm, now_ns=now)
planner.update(sm, now_ns=now, experimental_speed_nudge=True)
assert planner.encouragement.boost > 0.
for tick in range(220, 300):
sm, now = frame(tick)
@@ -467,3 +467,42 @@ def test_plannerd_forwards_speed_nudge_choice_through_both_curve_paths(host):
with patch('openpilot.selfdrive.controls.plannerd.confirm_curve_frame'):
update_curve_frame(planner, sm, cp(), now, host=host, experimental_speed_nudge=False)
assert planner.update.call_args.kwargs['experimental_speed_nudge'] is False
@pytest.mark.parametrize('personality,traffic', [('relaxed', False), ('standard', False), ('aggressive', False), ('relaxed', True)])
@pytest.mark.parametrize('scale', [0.0, .5, 1.0])
def test_opt_in_convergence_uses_each_profile_strength(personality, traffic, scale):
current, off = (LongitudinalPlanner(cp(), init_v=20.) for _ in range(2))
current.personality_boost_scale = off.personality_boost_scale = scale
for tick in range(120):
sm, now = frame(tick)
sm['selfdriveState'].personality = personality
sm['carState'].steeringAngleDeg = 6.0
lead = sm['radarState'].leadOne
lead.present, lead.dRel, lead.vLead, lead.vLeadK, lead.vRel = True, 85., 28., 28., 8.
current.update(sm, now_ns=now, traffic_mode=traffic, experimental_speed_nudge=True)
off.update(sm, now_ns=now, traffic_mode=traffic, experimental_speed_nudge=False)
assert current.mpc.solution_status == off.mpc.solution_status == 0
assert current.output_a_target <= current.a_cruise + 1e-6
if scale:
assert current.output_a_target > off.output_a_target + .05
assert current.output_a_target <= MAX_BOOST * scale + 1e-6
else:
assert current.output_a_target == off.output_a_target
assert current.encouragement.boost == 0.
@pytest.mark.parametrize('field,value', [('vRel', -.01), ('vLead', 26.0), ('aLeadK', -.4), ('dRel', 20.)])
def test_convergence_withdraws_immediately_when_either_lead_binds(field, value):
owner = Encouragement()
for tick in range(100):
step(owner, tick, converge=True, follow_seconds=1.5, lateral_accel=1.6)
assert owner.boost > 0.
sm, now = frame(100)
lead = sm['radarState'].leadTwo
lead.present, lead.dRel, lead.vLead, lead.vLeadK, lead.vRel = True, 80., 29., 29., 9.
setattr(lead, field, value)
assert owner.update(sm, cp(), now_ns=now, drive_id=1, dt=.05, target_speed=27., model_accel=0.,
mpc_accel=.8, cruise_accel=.8, lateral_accel=1.6, blocked=False,
converge=True, follow_seconds=1.5) == 0.
assert owner.boost == 0.
@@ -18,7 +18,7 @@ def test_registered_half_second_follow_reaches_mpc_and_resets_to_stock_owner(tmp
params = Params(str(tmp_path))
params.put_bool('CustomPersonalities', True, block=True)
params.put('TrafficFollow', .5, block=True)
params.put('RelaxedFollow', .5, block=True)
params.put('AggressiveFollow', .5, block=True)
settings = read_traffic_settings(params)
assert settings.valid
cp = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC)
@@ -64,6 +64,31 @@ class ForceStopRuntimeFixture(unittest.TestCase):
class ForceStopRuntimeTests(ForceStopRuntimeFixture):
def test_bolt_acc_default_offset_only_applies_to_no_lead_model_stops(self):
from unittest.mock import patch
from opendbc.car import gen_empty_fingerprint
from opendbc.car.gm.interface import CarInterface as GMInterface
from opendbc.car.gm.values import CAR as GM, is_bolt_euv_longitudinal
self.cp = GMInterface.get_params(GM.CHEVROLET_BOLT_ACC_2022_2023, gen_empty_fingerprint(), [], True, False, False)
self.assertTrue(is_bolt_euv_longitudinal(self.cp))
with patch.object(self.owner.policy, 'step', wraps=self.owner.policy.step) as step:
self.prime()
self.assertEqual(step.call_args.args[2], 4)
model_dropout = Frame(40)
model_dropout['modelV2'].position.x = []
self.sample(model_dropout)
self.assertFalse(step.call_args.args[0].perception_available)
self.assertEqual(step.call_args.args[2], 4)
with_lead = Frame(41)
lead = with_lead['radarState'].leadOne
lead.present, lead.dRel, lead.radar = True, 12., True
self.sample(with_lead)
self.assertEqual(step.call_args.args[2], 0)
self.params.put('ForceStopDistanceOffset', 4, block=True)
self.sample(Frame(70))
self.assertEqual(step.call_args.args[2], 4)
def test_always_hold_selection_is_next_drive_and_preserves_hold(self):
from openpilot.starpilot.longitudinal.enhanced_stop_hold import KEY
self.params.put_bool(KEY, True, block=True)
@@ -0,0 +1,102 @@
from dataclasses import replace
from types import SimpleNamespace
import pytest
from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.toyota import pedal
from opendbc.car.toyota.interface import CarInterface, apply_toyota_auto_hold
from opendbc.car.toyota.values import CAR
from openpilot.cereal import log
from openpilot.common.params import Params
from openpilot.selfdrive.car.car_events import CarEvents
from openpilot.selfdrive.controls.lib.longcontrol import LongControl
from openpilot.starpilot.car.toyota.tests.test_rav4h_caller_native import decode, firmware
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
from openpilot.starpilot.longitudinal.inputs import LongitudinalInputs
from openpilot.starpilot.longitudinal.toyota_output_policy import Lead
@pytest.fixture
def cp():
fp = gen_empty_fingerprint()
fp[0].update({0x2FF: 4, 0x201: 6})
cp = CarInterface.get_params(CAR.TOYOTA_RAV4, fp, firmware(CAR.TOYOTA_RAV4), False, False, False)
cp.alternativeExperience = 32
assert apply_toyota_auto_hold(cp, True)
assert cp.flags == 0x61000 and cp.alternativeExperience == 160
assert cp.safetyConfigs[0].safetyParam == 0xB549 and not cp.autoResumeSng
return cp
def stop():
cs = structs.CarState(standstill=True, canValid=True, gearShifter='drive')
cs.cruiseState.enabled = cs.cruiseState.available = cs.cruiseState.standstill = True
return cs
@pytest.mark.parametrize('lead', (None, Lead(True, 8.3, 1.0, 1.2, 0.0)))
def test_plan_release_while_pcm_is_latched_drives_existing_pedal(cp, lead):
ci = CarInterface(cp)
cs = stop()
ci.CS.out = cs.as_reader()
ci.CS.pedal_ready = True
ci.CC.advert_filter_input = ci.CC.pedal_input = SimpleNamespace(update=lambda now: True)
owner = LongControl(cp)
cc = structs.CarControl(enabled=True, longActive=True)
context = LongitudinalContext(leads=() if lead is None else (lead,), toyota_brake_release=True)
for frame in range(250):
cc.actuators.accel = float(owner.update(True, cs, -.2, True, (-3.5, 2.0), context=context))
_, frames = ci.apply(cc.as_reader(), 1_000_000_000 + frame * 10_000_000)
assert not any(data[4] & 0x80 for address, data, _ in frames if address == 0x200)
cc.cruiseControl.resume = True
assert log.OnroadEvent.EventName.resumeRequired in CarEvents(cp).update(cs, cs, cc).names
released = pedal_sent = False
for frame in range(250, 335):
cc.actuators.accel = float(owner.update(True, cs, .54, False, (-3.5, 2.0), context=context))
cc.actuators.longControlState = owner.long_control_state
_, frames = ci.apply(cc.as_reader(), 1_000_000_000 + frame * 10_000_000)
for message in frames:
address, data, bus = message
if address == 0x343:
acc = decode(cp, (address, data, bus), 'ACC_CONTROL')
released |= acc['ACCEL_CMD'] > 0 and bool(acc['RELEASE_STANDSTILL'])
if address == 0x200 and data[4] & 0x80:
assert data[-1] == pedal.checksum(data)
pedal_sent = True
assert released and pedal_sent
assert log.OnroadEvent.EventName.resumeRequired not in CarEvents(cp).update(cs, cs, cc).names
@pytest.mark.parametrize('blocker', ('stale', 'stop', 'force', 'brakePressed', 'gasPressed', 'canTimeout', 'stockAeb',
'accFaulted', 'doorOpen', 'seatbeltUnlatched', 'steerFaultTemporary', 'inactive', 'stock', 'cruise_off'))
def test_standstill_resume_stays_neutral_when_blocked(cp, blocker):
cs = stop()
if blocker == 'stock':
pedal.prepare_stock(cp)
if blocker == 'cruise_off':
cs.cruiseState.enabled = False
elif blocker in ('brakePressed', 'gasPressed', 'canTimeout', 'stockAeb', 'accFaulted',
'doorOpen', 'seatbeltUnlatched', 'steerFaultTemporary'):
setattr(cs, blocker, True)
owner = LongControl(cp)
context = LongitudinalContext(toyota_brake_release=blocker != 'stale', force_stop_braking=blocker == 'force')
assert owner.update(blocker != 'inactive', cs, .54, blocker == 'stop', (-3.5, 2.0), context=context) <= 0
def test_resume_context_requires_fresh_plan_and_throttle_permission(cp, monkeypatch, tmp_path):
plan = SimpleNamespace(allowThrottle=True, fcw=False)
state = stop()
sm = {'carState': state, 'longitudinalPlan': plan}
inputs = LongitudinalInputs(cp, Params(str(tmp_path)), lambda: sm)
monkeypatch.setattr(inputs, 'resume_sources_current', lambda: True)
context = inputs.context(True)
assert context == replace(LongitudinalContext(), toyota_brake_release=True)
plan.fcw = True
assert not inputs.context(True).toyota_brake_release
plan.fcw = False
plan.allowThrottle = False
assert not inputs.context(True).toyota_brake_release
plan.allowThrottle = True
monkeypatch.setattr(inputs, 'resume_sources_current', lambda: False)
assert not inputs.context(True).toyota_brake_release
@@ -1 +1 @@
{"binarySha256":"72e46f007b4dd5a813148aa3ea3fc7170db2d01004db5884b0895fafd00508e0","goVersion":"go1.25.1","schemaVersion":1,"sourceDigest":"736914d0326a3785673227d36b8e189e1ee7d0cbb87a9d8b725607810d8cde9f","sourceRevision":"291fc1d62f84fae5875fd4fb66185657e1f1f113","target":"linux-arm64-static","upstreamRevision":"7201c6b4b4ec1b0b9ea21daa8c05b80fdd7e01ee"}
{"binarySha256":"0696b2608cb09b2beac441b799736d438919fa9b67a06ff4b6d26ff3bb073805","goVersion":"go1.25.1","schemaVersion":1,"sourceDigest":"a1e0ee1f1ae5f3f1ed1a28dd9c2807bf713cb98deb04a58f77d2d76471f5b47e","sourceRevision":"122d1825e9f04b13555aa9553c17a6f708900735","target":"linux-arm64-static","upstreamRevision":"7201c6b4b4ec1b0b9ea21daa8c05b80fdd7e01ee"}
Binary file not shown.
@@ -40,18 +40,21 @@ def test_jetlink_gets_the_frames_delay_before_every_run():
any(isinstance(child, ast.Call) and ast.unparse(child.func) == "model.run" for child in ast.walk(node)))
assert (line("subaru_tau = subaru_smooth_seconds(v_ego, subaru_smoothing)") <
line("volkswagen_tau = volkswagen_smoothing(CP, receipt_owner.load)") <
line("lat_delay = sm['lateralDelay'].lateralDelay + LAT_SMOOTH_SECONDS + subaru_tau + volkswagen_tau + kona_tau") <
line("steering_smoothing = subaru_tau + volkswagen_tau + kona_tau + bolt_tau") <
line("lat_delay = sm['lateralDelay'].lateralDelay + LAT_SMOOTH_SECONDS + steering_smoothing") <
line("model.lat_delay = lat_delay") < run)
assignments = {ast.unparse(node.targets[0]): node for node in statements if isinstance(node, ast.Assign)}
# Reuse the same joined runner across frames: each write must include the current delay and smoothing.
model = SimpleNamespace(lat_delay=-1.)
for delay, subaru_tau, volkswagen_tau, kona_tau in ((.1, 0., 0., 0.), (.25, .4, 0., 0.), (.05, 2., 0., 0.),
(.2, 0., .3, 0.), (.15, .4, .3, 0.), (.3, 0., 0., .1), (.1, 0., 0., 0.)):
for delay, subaru_tau, volkswagen_tau, kona_tau, bolt_tau in (
(.1, 0., 0., 0., 0.), (.25, .4, 0., 0., 0.), (.05, 2., 0., 0., 0.),
(.2, 0., .3, 0., 0.), (.15, .4, .3, 0., 0.), (.3, 0., 0., .1, 0.), (.2, 0., 0., 0., .1), (.1, 0., 0., 0., 0.),
):
env = {"sm": {"lateralDelay": SimpleNamespace(lateralDelay=delay)}, "LAT_SMOOTH_SECONDS": .03,
"subaru_tau": subaru_tau, "volkswagen_tau": volkswagen_tau, "kona_tau": kona_tau, "model": model}
code = ast.Module(body=[assignments["lat_delay"], assignments["model.lat_delay"]], type_ignores=[])
"subaru_tau": subaru_tau, "volkswagen_tau": volkswagen_tau, "kona_tau": kona_tau, "bolt_tau": bolt_tau, "model": model}
code = ast.Module(body=[assignments[name] for name in ("steering_smoothing", "lat_delay", "model.lat_delay")], type_ignores=[])
exec(compile(ast.fix_missing_locations(code), str(MODEL_SOURCE), "exec"), env)
assert model.lat_delay == pytest.approx(delay + .03 + subaru_tau + volkswagen_tau + kona_tau)
assert model.lat_delay == pytest.approx(delay + .03 + subaru_tau + volkswagen_tau + kona_tau + bolt_tau)
@pytest.mark.parametrize("runner_chestnut,stored_active", [(True, False), (True, True), (False, True), (False, False)])
+8 -4
View File
@@ -123,7 +123,8 @@ class ControllerFeature:
return {**SETUP_DEFAULTS, **learning, LANE_CHANGE_KEY: json.dumps(to_value(lane), sort_keys=True, separators=(',', ':')).encode(),
DOCUMENT_KEY: replace_mode(sources[DOCUMENT_KEY], CP, ControllerMode.STARPILOT,
force_torque=steering_controller(CP) == 'pid' or
selection_from_bytes(CP, sources[DOCUMENT_KEY]).force_torque)}
selection_from_bytes(CP, sources[DOCUMENT_KEY]).force_torque or
selection_from_bytes(CP, None).force_torque)}
def setup_row(self) -> FeatureRow | None:
CP = self.vehicle_params()
@@ -184,7 +185,9 @@ class ControllerFeature:
valid = readable and selected is not None and selected.source != 'invalid'
value = (TORQUE_CHOICE if selected.force_torque and selected.mode == ControllerMode.STANDARD else
CHOICES[0] if selected.mode == ControllerMode.STANDARD else CHOICES[1]) if valid else 'Invalid saved controller choice'
choices = (CHOICES[0], TORQUE_CHOICE, CHOICES[1]) if steering_controller(CP) == 'pid' or valid and selected.force_torque else CHOICES
default = selection_from_bytes(CP, None)
has_pid_choice = steering_controller(CP) == 'pid' or default.force_torque or valid and selected.force_torque
choices = (CHOICES[0], TORQUE_CHOICE, CHOICES[1]) if has_pid_choice else CHOICES
learning, learning_readable = read_saved(self.params, LEARNING_OFF_KEY, 1)
preference = read_preference(self.params, CP, legacy_snapshot=(learning, learning_readable))
learning_valid = learning_readable and preference.valid
@@ -194,7 +197,8 @@ class ControllerFeature:
return FeatureRow(DOCUMENT_KEY, 'Steering Controller', value, raw, choices if valid else (),
available=allowed, reason=reason, capability=capability,
dependencies=((LEARNING_OFF_KEY, learning), (LEARNING_PREFERENCES_KEY, preference.raw)),
default_value=CHOICES[0] if selection_from_bytes(CP, None).mode == ControllerMode.STANDARD else CHOICES[1], level=SettingLevel.ADVANCED)
default_value=TORQUE_CHOICE if default.force_torque else CHOICES[0] if default.mode == ControllerMode.STANDARD else CHOICES[1],
level=SettingLevel.ADVANCED)
def learning_row(self, CP=None) -> FeatureRow | None:
CP = self.vehicle_params() if CP is None else CP
@@ -260,7 +264,7 @@ class ControllerFeature:
if selected.source == 'invalid':
return False
force_torque = request.value == TORQUE_CHOICE or request.value == CHOICES[1] and (
steering_controller(CP) == 'pid' or selected.force_torque)
steering_controller(CP) == 'pid' or selected.force_torque or selection_from_bytes(CP, None).force_torque)
encoded = replace_mode(raw, CP, MODES[request.value], force_torque=force_torque)
except (UnicodeError, ValueError, TypeError, OverflowError):
return False
@@ -1244,6 +1244,7 @@ class FeatureSettingsOwner:
rows.append(self._bool_row(LEAD_TAKEOFF_KEY, "Faster Takeoffs", self.authority("preferences"),
reason="Improves launches from a stop and responds sooner when a lead starts moving. " +
"Selected acceleration profiles, stop detection and vehicle limits still apply."))
rows.append(self._bool_row(NUDGE_KEY, "Add Extra Boost", self.authority("preferences")))
downhill_allowed = allowed and self.authority("long") and self._value(PLANNER_SELECTION_KEY)[0] == "1"
downhill = self._bool_row(DOWNHILL_KEY, "Coast Downhills", downhill_allowed,
"Lets gravity carry the car above set speed without targeting a higher speed. Changes apply while driving.")
@@ -1314,10 +1315,7 @@ class FeatureSettingsOwner:
level = SettingLevel.ADVANCED
allowed = configurable and system_long
name = page.title()
if page == "relaxed":
rows.append(self._bool_row(NUDGE_KEY, "Speed Nudge in Relaxed", self.authority("preferences"),
reason="Helps End to End return to set speed on clear roads in the Relaxed personality.",
level=SettingLevel.ADVANCED))
rows.append(self._number_row(BOOST_KEYS[page], "End to End Boost Strength",
allowed and self._value(PLANNER_SELECTION_KEY)[0] == "1",
level=SettingLevel.ADVANCED))
+13 -10
View File
@@ -23,7 +23,7 @@ from openpilot.starpilot.ui.onroad_customization import (CLOCK_WIDGET, MODE_WIDG
from openpilot.starpilot.ui.appearance_preferences import CameraViewChoice
from openpilot.starpilot.ui.onroad_alerts import AlertRenderer
from openpilot.starpilot.ui.onroad_border import render_compact_half_borders, render_large_half_borders
from openpilot.starpilot.ui.onroad_border import compact_border, render_compact_half_borders, render_large_half_borders
from openpilot.starpilot.ui.onroad_compact_widgets import CompactHudRenderer, MiciSidebarWidgets, compact_wheel_warning
from openpilot.starpilot.ui.onroad_personality import PersonalityWidget
from openpilot.starpilot.ui.onroad_curve import GlowPhase, controlling as curve_controlling, glow_color, intensity, render_glow, status_label
@@ -388,16 +388,18 @@ class OnroadView:
right_shift = width - 1860
frame = rl.Rectangle(0, 0, width, height)
content = rl.Rectangle(30, 30, width - 60, height - 60)
stroke = 30 if self.projection_viewport else (30 * state.customization.get("borderWidth", 100) + 50) // 100
road = content if stroke == 30 else rl.Rectangle(stroke, stroke, width - 2 * stroke, height - 2 * stroke)
# Current CameraView's no-frame placeholder stays at the disengaged blue.
color = rl.Color(18, 40, 57, 255)
edge = axis_status_color(state)
rl.draw_rectangle_rec(content, color)
clip.begin_scissor_mode(30, 30, int(content.width), int(content.height))
rl.draw_rectangle_rec(road, color)
clip.begin_scissor_mode(stroke, stroke, int(road.width), int(road.height))
try:
if self.camera_layer is not None and state.camera_available:
self.camera_layer(content, state)
self.camera_layer(road, state)
elif self.background_layer is not None:
self.background_layer(content, state)
self.background_layer(road, state)
draw_top_scrim(content)
ordered = bool(state.customization.get("widgetOrder", {}).get("large"))
if ordered:
@@ -479,11 +481,11 @@ class OnroadView:
self.fonts.draw(label, FontRole.SEMI_BOLD, 29, 1390 + right_shift, 56,
curve_color)
self._traffic_badge(state, 56 + 45 * int(label is not None))
render_glow(content, state, border_width=30, time_s=state.observed_ns / 1e9 if state.observed_ns else rl.get_time(),
render_glow(road, state, border_width=stroke, time_s=state.observed_ns / 1e9 if state.observed_ns else rl.get_time(),
phase=getattr(self, "_curve_glow_phase", None))
rl.draw_rectangle_lines_ex(frame, 30, rl.BLACK)
rl.draw_rectangle_rounded_lines_ex(content, 0.12, 10, 30, edge)
render_large_half_borders(state, state.observed_ns / 1e9 if state.observed_ns else rl.get_time(), content, int(height))
rl.draw_rectangle_lines_ex(frame, stroke, rl.BLACK)
rl.draw_rectangle_rounded_lines_ex(road, 0.12, 10, stroke, edge)
render_large_half_borders(state, state.observed_ns / 1e9 if state.observed_ns else rl.get_time(), road, int(height), stroke)
self._preview_badge(state)
def _compact(self, state: OnroadState) -> None:
@@ -569,7 +571,8 @@ class OnroadView:
self.compact_sidebar.render(rail, state)
clip.begin_scissor_mode(0, 0, 476, 240)
try:
rl.draw_rectangle_rounded_lines_ex(rl.Rectangle(4, 4, 468, 232), 0.12, 16, 8, color)
border, stroke = compact_border(state.customization)
rl.draw_rectangle_rounded_lines_ex(border, 0.12, 16, stroke, color)
finally:
clip.end_scissor_mode()
render_compact_half_borders(state, state.observed_ns / 1e9 if state.observed_ns else rl.get_time())
+10 -4
View File
@@ -35,20 +35,26 @@ def half_colors(state: OnroadState, time_s: float) -> tuple[rl.Color | None, rl.
return color(signals.left_blindspot, signals.left_blinker), color(signals.right_blindspot, signals.right_blinker)
def compact_border(document) -> tuple[rl.Rectangle, int]:
width = round(8 * document.get("borderWidth", 100) / 100)
inset = width / 2
return rl.Rectangle(inset, inset, 476 - width, 240 - width), width
def render_compact_half_borders(state: OnroadState, time_s: float) -> None:
left, right = half_colors(state, time_s)
border = rl.Rectangle(4, 4, 468, 232)
border, stroke = compact_border(state.customization)
for x, width, color in ((0, 238, left), (238, 238, right)):
if color is None:
continue
clip.begin_scissor_mode(x, 0, width, 240)
try:
rl.draw_rectangle_rounded_lines_ex(border, 0.12, 16, 8, color)
rl.draw_rectangle_rounded_lines_ex(border, 0.12, 16, stroke, color)
finally:
clip.end_scissor_mode()
def render_large_half_borders(state: OnroadState, time_s: float, content: rl.Rectangle, frame_height: int) -> None:
def render_large_half_borders(state: OnroadState, time_s: float, content: rl.Rectangle, frame_height: int, stroke: int = 30) -> None:
"""Android Auto: tint each half of the large status edge, matching the C4 half borders."""
left, right = half_colors(state, time_s)
middle = int(content.x + content.width / 2)
@@ -57,7 +63,7 @@ def render_large_half_borders(state: OnroadState, time_s: float, content: rl.Rec
continue
clip.begin_scissor_mode(x, 0, width, frame_height)
try:
rl.draw_rectangle_rounded_lines_ex(content, 0.12, 10, 30, color)
rl.draw_rectangle_rounded_lines_ex(content, 0.12, 10, stroke, color)
finally:
clip.end_scissor_mode()

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