mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 02:23:40 +08:00
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dbca3b79d0 | |||
| 4e2af76cad | |||
| 1a5023ce7b | |||
| 7dc5b57dfb | |||
| 71c0456448 | |||
| 9085011936 | |||
| dfaf5ea134 | |||
| 6dcd7aada2 | |||
| 23b426a897 | |||
| 1169c9fbca | |||
| 89ce004b02 | |||
| d1619d79e2 | |||
| 5eab0f921e | |||
| f2b99c1eec | |||
| eaf7a7cba2 | |||
| 25ca42a8ce | |||
| 404d71bf38 | |||
| 1b86f08b9d | |||
| 08d94465c2 | |||
| eb3f91847b | |||
| 521e32c316 | |||
| 91e4edf3b3 | |||
| 6c4559f0c3 | |||
| 122d1825e9 | |||
| ab2641f118 | |||
| efc7ca5f3b | |||
| 3272a31fc4 | |||
| 26c2d5c5ae | |||
| 2785af8023 | |||
| 84e3ce7468 |
@@ -255,7 +255,7 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
RAYLIB_BACKEND: headless
|
RAYLIB_BACKEND: headless
|
||||||
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
|
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
|
- name: Test GM vehicle configurations and CAN behavior
|
||||||
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
||||||
timeout-minutes: 5
|
timeout-minutes: 5
|
||||||
|
|||||||
@@ -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) {
|
func TestPackedPredictedWayCannotBypassCompetingRoad(t *testing.T) {
|
||||||
local := syntheticWay{1, 8, 35.1, -97.9, 35.2, -97.9, false, 2}
|
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}
|
rival := syntheticWay{2, 30, 35.1, -97.8999, 35.2, -97.8999, false, 6}
|
||||||
|
|||||||
+23
-5
@@ -57,8 +57,8 @@ func (w *CurrentWay) EffectiveMaxSpeed() float64 {
|
|||||||
return w.MaxSpeed()
|
return w.MaxSpeed()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrAmbiguousWay means more than one distinct loaded-tile road fits the same
|
// ErrAmbiguousWay means the loaded-tile candidates do not support keeping
|
||||||
// GPS uncertainty envelope. The rank scorer must not turn that into a limit.
|
// the current road or choosing a unique match.
|
||||||
var ErrAmbiguousWay = errors.New("multiple plausible road IDs")
|
var ErrAmbiguousWay = errors.New("multiple plausible road IDs")
|
||||||
|
|
||||||
// plausibleLoadedWays considers every way in the current tile before sticky or
|
// 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 {
|
if len(candidates) == 0 {
|
||||||
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, errors.New("no plausible loaded-tile way")
|
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
|
// 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.
|
// same ID. This prevents an old tile's geometry/limit from being republished.
|
||||||
way := candidates[0]
|
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)
|
onWay, err := way.OnWay(location, 2)
|
||||||
if err != nil || !onWay.OnWay {
|
if err != nil || !onWay.OnWay {
|
||||||
return CurrentWay{SelectionType: custom.WaySelectionType_fail}, errors.New("sole way lost geographic match")
|
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
|
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 {
|
if selection == custom.WaySelectionType_fail && narrowErr == nil && narrow.OnWay {
|
||||||
for _, next := range nextWays {
|
for _, next := range nextWays {
|
||||||
if next.Way.Nodes.Len() > 1 && next.Way.Id() == way.Id() {
|
if next.Way.Nodes.Len() > 1 && next.Way.Id() == way.Id() {
|
||||||
|
|||||||
@@ -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.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.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.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.values import BRANDS
|
||||||
from opendbc.car.vin import get_vin, is_valid_vin, VIN_UNKNOWN
|
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 ****
|
# **** for use live only ****
|
||||||
def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback,
|
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,
|
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]:
|
) -> 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()):
|
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')
|
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' if honda_normal_bus_topology(normal_bus_packets) else None) or
|
||||||
('honda_nidec' if nidec_bus0_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
|
('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)
|
set_obd_multiplexing(False)
|
||||||
warmup_remaining = 0.1 - (time.monotonic() - start_time)
|
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_gm_bus0 = (explicit_candidate in interface_names['gm'] and _gm_fw_uses_normal_bus0())
|
||||||
known_ford_bus0 = ford_normal_bus0_selection(explicit_candidate)
|
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_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 (
|
if known_gm_bus0 and cached_params is not None and (
|
||||||
cached_params.brand != 'gm' or cached_params.carFingerprint != explicit_candidate):
|
cached_params.brand != 'gm' or cached_params.carFingerprint != explicit_candidate):
|
||||||
cached_params = None
|
cached_params = None
|
||||||
@@ -323,6 +327,11 @@ def get_car(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multip
|
|||||||
elif known_tesla_bus0:
|
elif known_tesla_bus0:
|
||||||
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
|
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
|
||||||
can_recv, can_send, set_obd_multiplexing, cached_params, known_tesla_bus0=True)
|
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:
|
elif forced_candidate == HONDA.HONDA_ACCORD:
|
||||||
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
|
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
|
||||||
can_recv, can_send, set_obd_multiplexing, cached_params, known_honda_accord=True)
|
can_recv, can_send, set_obd_multiplexing, cached_params, known_honda_accord=True)
|
||||||
|
|||||||
@@ -315,13 +315,14 @@ class CarState(CarStateBase):
|
|||||||
pt_cp.ts_nanos["AcceleratorPedal2"]["AcceleratorPedal2"],
|
pt_cp.ts_nanos["AcceleratorPedal2"]["AcceleratorPedal2"],
|
||||||
pt_cp.ts_nanos["ECMEngineStatus"]["CruiseMainOn"],
|
pt_cp.ts_nanos["ECMEngineStatus"]["CruiseMainOn"],
|
||||||
pt_cp.ts_nanos["EBCMRegenPaddle"]["RegenPaddle"])
|
pt_cp.ts_nanos["EBCMRegenPaddle"]["RegenPaddle"])
|
||||||
|
control_word = gm_control_word(self.CP)
|
||||||
if is_volt_longitudinal(self.CP):
|
if is_volt_longitudinal(self.CP):
|
||||||
# Observe only actual resume/driver sources, using the finalized brake owner.
|
# Observe only actual resume/driver sources, using the finalized brake owner.
|
||||||
alternate = is_volt_gateway_alternate_brake(self.CP) or (
|
alternate = is_volt_gateway_alternate_brake(self.CP) or (
|
||||||
volt_camera_removed and bool(self.CP.flags & GMFlags.NO_ACCELERATOR_POS_MSG))
|
volt_camera_removed and bool(self.CP.flags & GMFlags.NO_ACCELERATOR_POS_MSG))
|
||||||
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and not (
|
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and not (
|
||||||
gm_control_word(self.CP) & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) and
|
control_word & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) and
|
||||||
not gm_control_word(self.CP) & GMSafetyFlags.BRAKE_C9)
|
not control_word & GMSafetyFlags.BRAKE_C9)
|
||||||
brake = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
|
brake = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
|
||||||
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
|
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
|
||||||
names = (("AcceleratorPedal2", "CruiseState", 100_000_000),
|
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 is not None and self.camera_pedal_profile.volt and
|
||||||
self.camera_pedal_profile.brake_source == BrakeSource.F1)
|
self.camera_pedal_profile.brake_source == BrakeSource.F1)
|
||||||
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and (
|
c9 = self.CP.networkLocation == NetworkLocation.fwdCamera and (
|
||||||
not gm_control_word(self.CP) & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) or
|
not control_word & (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM) or
|
||||||
bool(gm_control_word(self.CP) & GMSafetyFlags.BRAKE_C9))
|
bool(control_word & GMSafetyFlags.BRAKE_C9))
|
||||||
brake_name, brake_signal = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
|
brake_name, brake_signal = (("EBCMBrakePedalPosition", "BrakePedalPosition") if alternate else
|
||||||
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
|
("ECMEngineStatus", "BrakePressed") if c9 else ("ECMAcceleratorPos", "BrakePedalPos"))
|
||||||
names = (("ECMEngineStatus", "CruiseMainOn"), ("ECMPRDNL2", "PRNDL2"), (brake_name, brake_signal),
|
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:
|
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),)
|
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.
|
# 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:
|
if alternate_force:
|
||||||
self.gm_auto_hold_brake = pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] / 208.
|
self.gm_auto_hold_brake = pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] / 208.
|
||||||
if c9:
|
if c9:
|
||||||
@@ -426,9 +427,9 @@ class CarState(CarStateBase):
|
|||||||
else:
|
else:
|
||||||
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear["PRNDL2"], None))
|
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
|
(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):
|
if is_volt_cc_f1_profile(self.CP):
|
||||||
ret.brakePressed = (pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] >= 6 or
|
ret.brakePressed = (pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] >= 6 or
|
||||||
pt_cp.vl["ECMEngineStatus"]["BrakePressed"] != 0)
|
pt_cp.vl["ECMEngineStatus"]["BrakePressed"] != 0)
|
||||||
|
|||||||
@@ -113,10 +113,11 @@ class GMPedalLongitudinalPolicy:
|
|||||||
|
|
||||||
def prepare_pid(self, pid, target: float, error: float, speed: float,
|
def prepare_pid(self, pid, target: float, error: float, speed: float,
|
||||||
last_output: float, accel_limits: tuple[float, 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):
|
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))
|
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))
|
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))))
|
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
|
EPS_STATUS_TIMEOUT_NS = 300_000_000
|
||||||
STEERING_COMMAND_TIMEOUT_NS = 100_000_000
|
STEERING_COMMAND_TIMEOUT_NS = 100_000_000
|
||||||
ButtonType = structs.CarState.ButtonEvent.Type
|
ButtonType = structs.CarState.ButtonEvent.Type
|
||||||
|
STEERING_SOURCE_LENGTHS = {0xC9: 8, 0xBE: 6, 0xBD: 7, 0x1E1: 7}
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
@cached_config
|
||||||
@@ -42,24 +43,30 @@ class SteeringAuthority:
|
|||||||
if not self.enabled:
|
if not self.enabled:
|
||||||
return
|
return
|
||||||
self.source_ns.clear()
|
self.source_ns.clear()
|
||||||
malformed = any(bus == 0 and address == 0x184 and (stamp <= 0 or len(data) != 8)
|
malformed_status = False
|
||||||
for stamp, packets in can_packets for address, data, bus in packets)
|
previous_status_ns = self.status_ns
|
||||||
lengths = {0xC9: 8, 0xBE: 6, 0xBD: 7, 0x1E1: 7}
|
invalid_sources = set()
|
||||||
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)
|
|
||||||
for stamp, packets in can_packets:
|
for stamp, packets in can_packets:
|
||||||
for address, data, bus in packets:
|
for address, data, bus in packets:
|
||||||
if bus != 0 or stamp <= 0:
|
if bus != 0:
|
||||||
continue
|
continue
|
||||||
if address in lengths and address not in invalid:
|
if address == 0x184:
|
||||||
self.source_ns[address] = max(stamp, self.source_ns.get(address, 0))
|
valid = stamp > 0 and len(data) == 8
|
||||||
if address == 0x184 and stamp > self.status_ns:
|
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:
|
if self.active_since_ns and stamp - max(self.status_ns, self.active_since_ns) > EPS_STATUS_TIMEOUT_NS:
|
||||||
self.latched = True
|
self.latched = True
|
||||||
self.status_ns = stamp
|
self.status_ns = stamp
|
||||||
self.status = -1 if malformed else (data[0] >> 3) & 7
|
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):
|
def command(self, now_ns: int, active: bool):
|
||||||
if not self.enabled:
|
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.
|
# 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))
|
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()
|
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:
|
class CANFDCameraLead:
|
||||||
def __init__(self, cp, bus):
|
def __init__(self, cp, bus):
|
||||||
self.bus = 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.observation = None
|
||||||
self.last_packet_ns = 0
|
self.last_packet_ns = 0
|
||||||
self.last_counter = None
|
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
|
# MRR35 publishes many unused/unknown fields in each object packet. Decode
|
||||||
# the four consumed track fields, retaining parser integrity fields automatically.
|
# 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)
|
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}
|
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)
|
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
|
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):
|
def test_projected_radar_matches_complete_decoder(monkeypatch, name, dbc, bus, start, count, length, lka):
|
||||||
cp = factory(name, bus, start, count, length, lka)
|
cp = factory(name, bus, start, count, length, lka)
|
||||||
projected = radar_interface.RadarInterface(cp)
|
projected = radar_interface.RadarInterface(cp)
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ DASHBOARD_CARS = frozenset(CAR)
|
|||||||
class DashboardCameraParser(CANParser):
|
class DashboardCameraParser(CANParser):
|
||||||
def __init__(self, dbc_name):
|
def __init__(self, dbc_name):
|
||||||
super().__init__(dbc_name, [], 2)
|
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):
|
def update(self, strings, sendcan=False):
|
||||||
packets = strings
|
packets = strings
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from opendbc.car import CanSignalRateCalculator
|
|||||||
SUBARU_CVT_MANUAL_GEARS = frozenset({129, 137, 145, 153, 161, 169, 177, 185, 193})
|
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.
|
# Drive range with ratio zero, with either state of the manual-mode bit.
|
||||||
PADDLE_EXIT_GEARS = (1, 129)
|
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
|
PADDLE_EXIT_PAUSE_NS = 150_000_000
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -88,9 +88,8 @@ class StopAndGo:
|
|||||||
self.departure_seen = False
|
self.departure_seen = False
|
||||||
self.remaining = 0
|
self.remaining = 0
|
||||||
duration = frame - self.last_standstill_frame
|
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
|
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:
|
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.departure_seen = True
|
||||||
self.remaining = 15
|
self.remaining = 15
|
||||||
|
|||||||
@@ -57,8 +57,12 @@ def apply(cp, *, camera_twoaa=False):
|
|||||||
cp.alphaLongitudinalAvailable = bool(cp.flags & (ToyotaFlags.NO_DSU | ToyotaFlags.RADAR_ACC))
|
cp.alphaLongitudinalAvailable = bool(cp.flags & (ToyotaFlags.NO_DSU | ToyotaFlags.RADAR_ACC))
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(cp)
|
cp = parent_cp(cp)
|
||||||
from opendbc.car.toyota import camera_2aa_filter
|
from opendbc.car.toyota import camera_2aa_filter
|
||||||
@@ -126,11 +130,15 @@ class AdvertFilterCANParser(CANParser):
|
|||||||
self.advert_distance_button = 0
|
self.advert_distance_button = 0
|
||||||
self.advert_button_ns = 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 = []
|
batches = []
|
||||||
for stamp, frames in strings:
|
for stamp, frames in strings:
|
||||||
accepted = []
|
accepted = []
|
||||||
for address, data, bus in frames:
|
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 bus == self.bus:
|
||||||
if address in (0x1D3, 0x262):
|
if address in (0x1D3, 0x262):
|
||||||
valid = len(data) == 8 and data[-1] == toyota_checksum(address, None, bytearray(data))
|
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))
|
accepted.append((address, data, bus))
|
||||||
batches.append((stamp, accepted))
|
batches.append((stamp, accepted))
|
||||||
return super().update(batches, sendcan)
|
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)
|
super().__init__(*args)
|
||||||
self.hardware_ambiguous = False
|
self.hardware_ambiguous = False
|
||||||
|
|
||||||
def update(self, strings, sendcan=False):
|
def _accept_accessory(self, address, data, bus):
|
||||||
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):
|
if address in (0x201, 0x2FF):
|
||||||
self.hardware_ambiguous = True
|
self.hardware_ambiguous = True
|
||||||
continue
|
return False
|
||||||
if address == 0x2AA:
|
if address == 0x2AA:
|
||||||
self.hardware_ambiguous |= bus not in (0, 2) or len(data) != 8
|
self.hardware_ambiguous |= bus not in (0, 2) or len(data) != 8
|
||||||
continue
|
return False
|
||||||
accepted.append((address, data, bus))
|
return True
|
||||||
batches.append((stamp, accepted))
|
|
||||||
result = super().update(batches, sendcan)
|
def update(self, strings, sendcan=False):
|
||||||
|
# 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:
|
if self.hardware_ambiguous:
|
||||||
self.main_valid = self.eps_valid = False
|
self.main_valid = self.eps_valid = False
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -110,7 +110,6 @@ class CarController(CarControllerBase):
|
|||||||
|
|
||||||
self.accel = 0
|
self.accel = 0
|
||||||
self.prev_accel = 0
|
self.prev_accel = 0
|
||||||
self.corolla_launch = CP.carFingerprint == CAR.TOYOTA_COROLLA_TSS2 and not CP.flags & (ToyotaFlags.HYBRID | ToyotaFlags.GAS_INTERCEPTOR)
|
|
||||||
# *** end long control state ***
|
# *** end long control state ***
|
||||||
|
|
||||||
self.packer = CANPacker(dbc_names[Bus.pt])
|
self.packer = CANPacker(dbc_names[Bus.pt])
|
||||||
@@ -153,7 +152,8 @@ class CarController(CarControllerBase):
|
|||||||
|
|
||||||
def update(self, CC, CS, now_nanos):
|
def update(self, CC, CS, now_nanos):
|
||||||
from opendbc.car.toyota import dsu_bypass
|
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
|
_projection = self.learning_projection_observer
|
||||||
if _projection is not None:
|
if _projection is not None:
|
||||||
_projection.begin(CC.actuators.torque, self.frame)
|
_projection.begin(CC.actuators.torque, self.frame)
|
||||||
@@ -191,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
|
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.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))
|
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)
|
composite_pedal = pedal_composite.configured(self.CP)
|
||||||
if composite_pedal:
|
if composite_pedal:
|
||||||
filter_allowed = filter_allowed and bool(
|
filter_allowed = filter_allowed and bool(
|
||||||
@@ -203,11 +199,16 @@ class CarController(CarControllerBase):
|
|||||||
(not CS.out.brakePressed or CS.out.standstill) and
|
(not CS.out.brakePressed or CS.out.standstill) and
|
||||||
CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport))
|
CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport))
|
||||||
if pedal_owner:
|
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:
|
if bypass_long:
|
||||||
preference = getattr(self, 'bypass_input', None)
|
preference = getattr(self, 'bypass_input', None)
|
||||||
filter_allowed = filter_allowed and bool(
|
bypass_ready = bool((hold_source_ready or filter_allowed) and preference is not None and preference.update(now_nanos))
|
||||||
preference is not None and preference.update(now_nanos) and CS.out.canValid and not CS.out.canTimeout and
|
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
|
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.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
|
not CS.out.seatbeltUnlatched and (not CS.out.brakePressed or CS.out.standstill) and
|
||||||
@@ -224,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:
|
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
|
pcm_cancel_cmd = True
|
||||||
lat_active = CC.latActive and abs(CS.out.steeringTorque) < MAX_USER_TORQUE
|
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 (
|
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)
|
CS.out.steerFaultTemporary or CS.out.steerFaultPermanent or CS.out.doorOpen)
|
||||||
if self.original_prius_filter:
|
if self.original_prius_filter:
|
||||||
@@ -339,6 +340,8 @@ class CarController(CarControllerBase):
|
|||||||
else:
|
else:
|
||||||
self.reset_auto_hold_state()
|
self.reset_auto_hold_state()
|
||||||
if self.CP.openpilotLongitudinalControl:
|
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,
|
# 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.
|
# 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
|
# don't use CC.cruiseControl.resume since it is gated on CS.cruiseState.standstill which goes false for 3s after resume press
|
||||||
@@ -357,12 +360,12 @@ class CarController(CarControllerBase):
|
|||||||
CS.pcm_acc_status, CC.cruiseControl.resume, long_active)
|
CS.pcm_acc_status, CC.cruiseControl.resume, long_active)
|
||||||
self.last_standstill = CS.out.standstill
|
self.last_standstill = CS.out.standstill
|
||||||
elif self.sdsu_hybrid or (advert_long and bool(self.CP.flags & ToyotaFlags.HYBRID) and
|
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
|
# Retain the existing hybrid resume behavior while active. The shared
|
||||||
# owner guard below still holds neutral when LONG or its source is lost.
|
# owner guard below still holds neutral when LONG or its source is lost.
|
||||||
self.standstill_req = not long_active and CS.out.standstill
|
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:
|
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_filter.enabled(self.CP) else actuators.accel > 0
|
should_resume = long_active and actuators.accel > 0 if rav4h_long or legacy_advert_long else actuators.accel > 0
|
||||||
if should_resume:
|
if should_resume:
|
||||||
self.standstill_req = False
|
self.standstill_req = False
|
||||||
|
|
||||||
@@ -375,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):
|
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
|
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.
|
# A radar-disable safety handoff starts with fresh native RX checks.
|
||||||
# Neutral output must not request release before LONG is admitted.
|
# Neutral output must not request release before LONG is admitted.
|
||||||
self.standstill_req = True
|
self.standstill_req = True
|
||||||
@@ -393,11 +396,6 @@ class CarController(CarControllerBase):
|
|||||||
pcm_accel_cmd = actuators.accel if filter_allowed else 0.
|
pcm_accel_cmd = actuators.accel if filter_allowed else 0.
|
||||||
if (bypass_long or self.prius_longitudinal or rav4h_long or advert_long) and not long_active:
|
if (bypass_long or self.prius_longitudinal or rav4h_long or advert_long) and not long_active:
|
||||||
pcm_accel_cmd = 0.
|
pcm_accel_cmd = 0.
|
||||||
standstill_launch = (self.corolla_launch and long_active and CS.out.standstill and not stopping and actuators.accel > 0 and
|
|
||||||
not (bypass_long or self.prius_longitudinal or rav4h_long or advert_long or pedal_owner))
|
|
||||||
if standstill_launch:
|
|
||||||
self.prev_accel = max(self.prev_accel, 0.)
|
|
||||||
self.long_pid.i = max(self.long_pid.i, 0.)
|
|
||||||
if long_active:
|
if long_active:
|
||||||
pcm_accel_cmd = rate_limit(pcm_accel_cmd, self.prev_accel, ACCEL_WINDDOWN_LIMIT, ACCEL_WINDUP_LIMIT)
|
pcm_accel_cmd = rate_limit(pcm_accel_cmd, self.prev_accel, ACCEL_WINDDOWN_LIMIT, ACCEL_WINDUP_LIMIT)
|
||||||
self.prev_accel = pcm_accel_cmd
|
self.prev_accel = pcm_accel_cmd
|
||||||
|
|||||||
@@ -87,6 +87,9 @@ class CarState(CarStateBase):
|
|||||||
|
|
||||||
ret = structs.CarState()
|
ret = structs.CarState()
|
||||||
bypass = dsu_bypass.configured(self.CP)
|
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
|
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:
|
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.steerFaultTemporary = cp.vl["EPS_STATUS"]["LKA_STATE"] in TEMP_STEER_FAULTS
|
||||||
ret.steerFaultPermanent = cp.vl["EPS_STATUS"]["LKA_STATE"] in PERM_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')
|
stamp, expiry = parser_expiry(cp, 'EPS_STATUS', 'LKA_STATE')
|
||||||
expiry = min(expiry, stamp + 400_000_000)
|
expiry = min(expiry, stamp + 400_000_000)
|
||||||
ret.steerFaultTemporary |= not (cp.eps_valid and stamp > 0 and stamp <= cp._last_update_nanos <= expiry)
|
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.accFaulted = cp.vl["PCM_CRUISE_2"]["ACC_FAULTED"] != 0
|
||||||
ret.carFaultedNonCritical = cp.vl["PCM_CRUISE_SM"]["TEMP_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
|
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"]
|
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.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
|
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}) +
|
buttonEvents.extend(create_button_events(1, 0, {1: ButtonType.lkas}) +
|
||||||
create_button_events(0, 1, {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))):
|
not (self.CP.flags & (ToyotaFlags.RADAR_ACC | ToyotaFlags.SECOC | ToyotaFlags.LONG_FILTER))):
|
||||||
# distance button is wired to the ACC module (camera or radar)
|
# distance button is wired to the ACC module (camera or radar)
|
||||||
prev_distance_button = self.distance_button
|
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})
|
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
|
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
|
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
|
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
|
self.distance_button = cp.advert_distance_button if fresh else 0
|
||||||
elif not bypass and has_optional_prius_gap_button(self.CP):
|
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
|
ret.steerFaultTemporary |= not (cp.eps_valid and eps_stamp > 0 and
|
||||||
0 <= cp._last_update_nanos - eps_stamp <= 400_000_000)
|
0 <= cp._last_update_nanos - eps_stamp <= 400_000_000)
|
||||||
|
|
||||||
if pedal.configured(self.CP):
|
if pedal_owner:
|
||||||
cp_pedal = can_parsers[Bus.alt] if pedal_composite.configured(self.CP) else cp
|
cp_pedal = can_parsers[Bus.alt] if composite_pedal else cp
|
||||||
stamp = cp_pedal.ts_nanos.get("GAS_SENSOR", {}).get("STATE", 0)
|
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)
|
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
|
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.accFaulted = ret.accFaulted or not self.pedal_ready
|
||||||
ret.buttonEvents = buttonEvents
|
ret.buttonEvents = buttonEvents
|
||||||
timestamp, expiry = parser_expiry(cp_cam, "RSA1", "TSGN1")
|
timestamp, expiry = parser_expiry(cp_cam, "RSA1", "TSGN1")
|
||||||
|
|||||||
@@ -89,8 +89,12 @@ def apply(cp):
|
|||||||
cp.dashcamOnly = False
|
cp.dashcamOnly = False
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(cp)
|
cp = parent_cp(cp)
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -47,12 +47,14 @@ def apply(cp):
|
|||||||
|
|
||||||
|
|
||||||
def configured(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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(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
|
from opendbc.car.toyota import matrix_filter
|
||||||
return matrix_filter.configured(cp, length=4)
|
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.secOcRequired or not cp.pcmCruise or len(cp.safetyConfigs) != 1 or
|
||||||
cp.steerControlType != structs.CarParams.SteerControlType.torque):
|
cp.steerControlType != structs.CarParams.SteerControlType.torque):
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ def hardware_supported(candidate, fingerprint, car_fw):
|
|||||||
|
|
||||||
|
|
||||||
def configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import hold_base_cp
|
||||||
cp = hold_base_cp(cp)
|
cp = hold_base_cp(cp)
|
||||||
from opendbc.car.toyota import pedal_composite
|
from opendbc.car.toyota import pedal_composite
|
||||||
@@ -123,6 +125,11 @@ def command(packer, value, counter):
|
|||||||
return CanData(address, bytes(data), bus)
|
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):
|
def amount(cp, cc, cs, accel):
|
||||||
if not (configured(cp) and cp.openpilotLongitudinalControl and cc.longActive and
|
if not (configured(cp) and cp.openpilotLongitudinalControl and cc.longActive and
|
||||||
cs.out.canValid and not cs.out.canTimeout and cs.pedal_ready 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)
|
return (dsu_bypass, prius_longitudinal, advert_filter, rav4h_filter, radar_filter)
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def configured(cp):
|
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())
|
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
|
cp.alphaLongitudinalAvailable = False
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(cp)
|
cp = parent_cp(cp)
|
||||||
from opendbc.car.toyota import prius_retrofit_advert
|
from opendbc.car.toyota import prius_retrofit_advert
|
||||||
@@ -79,16 +83,11 @@ class PriusAdvertCANParser(AdvertFilterCANParser):
|
|||||||
super().__init__(*args)
|
super().__init__(*args)
|
||||||
self.hardware_ambiguous = False
|
self.hardware_ambiguous = False
|
||||||
|
|
||||||
def update(self, strings, sendcan=False):
|
def _accept_accessory(self, address, data, bus):
|
||||||
batches = []
|
# Buses >= 128 carry Panda TX receipts, not physical RX.
|
||||||
for stamp, frames in strings:
|
if bus < 128 and (address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) != 4)):
|
||||||
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
|
self.hardware_ambiguous = True
|
||||||
batches.append((stamp, frames))
|
return True
|
||||||
return super().update(batches, sendcan)
|
|
||||||
|
def update(self, strings, sendcan=False):
|
||||||
|
return self._update_filtered(strings, sendcan, self._accept_accessory)
|
||||||
|
|||||||
@@ -29,8 +29,12 @@ def configured(cp):
|
|||||||
cp.openpilotLongitudinalControl == (cp.safetyConfigs[0].safetyParam == 0x8049))
|
cp.openpilotLongitudinalControl == (cp.safetyConfigs[0].safetyParam == 0x8049))
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def eps73_status_configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(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)
|
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."""
|
"""Original EPS66 Prius smartDSU ownership; the EPS73 retrofit remains distinct."""
|
||||||
|
from opendbc.can import CANParser
|
||||||
from opendbc.car import structs
|
from opendbc.car import structs
|
||||||
from opendbc.car.dashboard_speed_limit import parser_expiry
|
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.toyotacan import toyota_checksum
|
||||||
from opendbc.car.toyota.values import CAR, ToyotaFlags
|
from opendbc.car.toyota.values import CAR, ToyotaFlags
|
||||||
|
|
||||||
@@ -40,9 +40,11 @@ def apply(cp):
|
|||||||
|
|
||||||
|
|
||||||
def configured(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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(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.dashcamOnly or cp.secOcRequired or not cp.pcmCruise or len(cp.safetyConfigs) != 1 or
|
||||||
cp.steerControlType != structs.CarParams.SteerControlType.torque):
|
cp.steerControlType != structs.CarParams.SteerControlType.torque):
|
||||||
return False
|
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
|
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."""
|
"""Keep independent status, MAIN/EPS quality and receiver identity evidence."""
|
||||||
def __init__(self, *args):
|
def __init__(self, *args):
|
||||||
super().__init__(*args)
|
super().__init__(*args)
|
||||||
@@ -91,6 +93,8 @@ class PriusSDSUCANParser(Rav4hCANParser):
|
|||||||
continue
|
continue
|
||||||
if address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) == 4):
|
if address in (0x201, 0x2AA) or address == 0x2FF and (bus not in (0, 2) or len(data) == 4):
|
||||||
self.hardware_ambiguous = True
|
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):
|
if bus == self.bus and address in (0x1D3, 0x262):
|
||||||
valid = len(data) == 8 and data[-1] == toyota_checksum(address, None, bytearray(data))
|
valid = len(data) == 8 and data[-1] == toyota_checksum(address, None, bytearray(data))
|
||||||
if address == 0x1D3:
|
if address == 0x1D3:
|
||||||
|
|||||||
@@ -34,8 +34,12 @@ def hardware_supported(candidate, fingerprint, car_fw):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@cached_config
|
|
||||||
def configured(cp):
|
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
|
from opendbc.car.toyota.pedal_composite import parent_cp
|
||||||
cp = parent_cp(cp)
|
cp = parent_cp(cp)
|
||||||
from opendbc.car.toyota import eps8_sdsu, legacy_sdsu
|
from opendbc.car.toyota import eps8_sdsu, legacy_sdsu
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
from opendbc.car import structs
|
|
||||||
from opendbc.car.toyota.carcontroller import CarController
|
|
||||||
from opendbc.car.toyota.tests.test_auto_hold import setup_hold, tick_acc
|
|
||||||
from opendbc.car.toyota.values import CAR, DBC, ToyotaFlags
|
|
||||||
|
|
||||||
LONG_STATE = structs.CarControl.Actuators.LongControlState
|
|
||||||
|
|
||||||
|
|
||||||
def launch(car=CAR.TOYOTA_COROLLA_TSS2, *, standstill=True, accel=0.2, state=LONG_STATE.pid):
|
|
||||||
cp, controller, command, cs = setup_hold(car, False)
|
|
||||||
cs.out.brakePressed = False
|
|
||||||
cs.out.standstill = standstill
|
|
||||||
cs.out.vEgo = 0. if standstill else 1.
|
|
||||||
cs.out.cruiseState.enabled = True
|
|
||||||
cs.out.cruiseState.standstill = standstill
|
|
||||||
cs.pcm_acc_status = 8
|
|
||||||
cs.gvc = 0.
|
|
||||||
command.enabled = command.longActive = True
|
|
||||||
command.actuators.accel = accel
|
|
||||||
command.actuators.longControlState = state
|
|
||||||
controller.prev_accel = -2.0
|
|
||||||
controller.long_pid.i = -0.3
|
|
||||||
return cp, controller, command, cs
|
|
||||||
|
|
||||||
|
|
||||||
def test_corolla_standstill_launch_skips_brake_unwind():
|
|
||||||
cp, controller, command, cs = launch()
|
|
||||||
assert tick_acc(cp, controller, command, cs)['ACCEL_CMD'] >= 0.
|
|
||||||
assert controller.long_pid.i >= 0.
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('case', ('moving', 'stopping', 'braking', 'camry'))
|
|
||||||
def test_launch_keeps_unwind_elsewhere(case):
|
|
||||||
kwargs = {'moving': {'standstill': False}, 'stopping': {'state': LONG_STATE.stopping},
|
|
||||||
'braking': {'accel': -0.5}, 'camry': {'car': CAR.TOYOTA_CAMRY_TSS2}}[case]
|
|
||||||
cp, controller, command, cs = launch(**kwargs)
|
|
||||||
assert tick_acc(cp, controller, command, cs)['ACCEL_CMD'] < -1.
|
|
||||||
|
|
||||||
|
|
||||||
def test_hybrid_corolla_keeps_unwind():
|
|
||||||
cp, _, _, _ = launch()
|
|
||||||
cp.flags |= int(ToyotaFlags.HYBRID)
|
|
||||||
assert not CarController(DBC[cp.carFingerprint], cp).corolla_launch
|
|
||||||
@@ -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):
|
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.passive or cp.notCar or cp.dashcamOnly or cp.flags & ~KNOWN_FLAGS or
|
||||||
cp.steerControlType != structs.CarParams.SteerControlType.torque or
|
cp.steerControlType != structs.CarParams.SteerControlType.torque):
|
||||||
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))):
|
|
||||||
return False
|
return False
|
||||||
word = AOL_WORD | (MANUAL_WORD if cp.transmissionType == structs.CarParams.TransmissionType.manual else 0)
|
transmission = cp.transmissionType
|
||||||
word |= DIRECT_WORD if cp.transmissionType == structs.CarParams.TransmissionType.direct else 0
|
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)
|
word |= int(longitudinal)
|
||||||
safety = safety_config(cp)
|
safety = safety_config(cp)
|
||||||
return (safety is not None and safety.safetyModel == structs.CarParams.SafetyModel.volkswagen and
|
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."""
|
"""Physical MAIN intent for qualified angle and Impreza torque AOL; no ordinary controls grant."""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from opendbc.car import structs
|
||||||
from opendbc.safety.tests.libsafety import libsafety_py
|
from opendbc.safety.tests.libsafety import libsafety_py
|
||||||
from opendbc.safety.tests import test_subaru_stock_aol as stock_module
|
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 = stock_module.TestSubaruStockAol(methodName='runTest')
|
||||||
item.setUp()
|
item.setUp()
|
||||||
try:
|
try:
|
||||||
|
debug = item.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0
|
||||||
for param in (145, 17, 1041, 2065, 3089):
|
for param in (145, 17, 1041, 2065, 3089):
|
||||||
item.configure(param)
|
item.configure(param)
|
||||||
neutral(item)
|
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
|
assert item.feed() == 1
|
||||||
for gear in (137, 145, 153, 161, 169, 177, 185, 193):
|
for gear in (137, 145, 153, 161, 169, 177, 185, 193):
|
||||||
assert item.feed(gear=gear) == 1
|
assert item.feed(gear=gear) == 1
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -137,9 +137,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
|||||||
{"LaneCentering", {PERSISTENT, BOOL, "0"}},
|
{"LaneCentering", {PERSISTENT, BOOL, "0"}},
|
||||||
{"LaneCenteringPauseOnSignal", {PERSISTENT, BOOL, "1"}},
|
{"LaneCenteringPauseOnSignal", {PERSISTENT, BOOL, "1"}},
|
||||||
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
|
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
|
||||||
{"ParkedClearance", {PERSISTENT, BOOL, "0"}},
|
|
||||||
{"ParkedClearanceGap", {PERSISTENT, FLOAT, "1.5"}},
|
|
||||||
{"ParkedClearanceShift", {PERSISTENT, FLOAT, "0.3"}},
|
|
||||||
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
|
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
|
||||||
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
|
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
|
||||||
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
|
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
|
||||||
@@ -257,6 +254,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
|||||||
{"AlphaLongitudinalEnabled", {PERSISTENT, BOOL}},
|
{"AlphaLongitudinalEnabled", {PERSISTENT, BOOL}},
|
||||||
{"ExperimentalMode", {PERSISTENT, BOOL}},
|
{"ExperimentalMode", {PERSISTENT, BOOL}},
|
||||||
{"ExperimentalSpeedNudge", {PERSISTENT, BOOL, "0"}},
|
{"ExperimentalSpeedNudge", {PERSISTENT, BOOL, "0"}},
|
||||||
|
{"ConvergeToSetSpeed", {PERSISTENT, BOOL, "0"}},
|
||||||
{"AggressivePersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
{"AggressivePersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
||||||
{"StandardPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
{"StandardPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
||||||
{"RelaxedPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
{"RelaxedPersonalityBoost", {PERSISTENT, FLOAT, "100"}},
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from opendbc.car import DT_CTRL, structs
|
|||||||
from opendbc.car.car_helpers import interfaces
|
from opendbc.car.car_helpers import interfaces
|
||||||
from opendbc.car.interfaces import MAX_CTRL_SPEED
|
from opendbc.car.interfaces import MAX_CTRL_SPEED
|
||||||
from opendbc.car.toyota.values import ToyotaFlags
|
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.selfdrive.selfdrived.events import Events
|
||||||
from openpilot.starpilot.car.events import event_rules, unsupported_gear
|
from openpilot.starpilot.car.events import event_rules, unsupported_gear
|
||||||
@@ -19,6 +20,7 @@ class CarEvents:
|
|||||||
def __init__(self, CP: structs.CarParams):
|
def __init__(self, CP: structs.CarParams):
|
||||||
self.CP = CP
|
self.CP = CP
|
||||||
self.event_rules = event_rules(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
|
from opendbc.car.gm.values import is_volt_cc_profile
|
||||||
self.volt_cc_profile = CP.brand == "gm" and is_volt_cc_profile(CP)
|
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
|
# TODO: when we check for unexpected disengagement, check gear not S1, S2, S3
|
||||||
if self.CP.openpilotLongitudinalControl:
|
if self.CP.openpilotLongitudinalControl:
|
||||||
# Only can leave standstill when planner wants to move
|
# 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)):
|
(CC.cruiseControl.resume or self.CP.flags & ToyotaFlags.HYBRID.value)):
|
||||||
events.add(EventName.resumeRequired)
|
events.add(EventName.resumeRequired)
|
||||||
if CS.vEgo < self.CP.minEnableSpeed:
|
if CS.vEgo < self.CP.minEnableSpeed:
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePo
|
|||||||
from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate
|
from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate
|
||||||
from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns
|
from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns
|
||||||
from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported
|
from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported
|
||||||
from openpilot.starpilot.lateral.parked_runtime import ParkedClearanceHost, runtime_supported as parked_runtime_supported
|
|
||||||
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
|
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
|
||||||
from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled
|
from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled
|
||||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
from openpilot.starpilot.feature_capabilities import lateral_supported
|
||||||
@@ -115,7 +114,9 @@ class Controls:
|
|||||||
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing
|
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing
|
||||||
self.volkswagen_smoothing = ControlSmoothing(self.CP)
|
self.volkswagen_smoothing = ControlSmoothing(self.CP)
|
||||||
from openpilot.starpilot.car.hyundai.model_smoothing import seconds as kona_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
|
||||||
self.kona_smoothing = kona_smoothing(self.CP)
|
self.kona_smoothing = kona_smoothing(self.CP)
|
||||||
|
self.bolt_smoothing = bolt_smoothing(self.CP)
|
||||||
|
|
||||||
self.CI = interfaces[self.CP.carFingerprint](self.CP)
|
self.CI = interfaces[self.CP.carFingerprint](self.CP)
|
||||||
self.hyundai_lateral_fault = LateralFaultLatch(self.CP.carFingerprint)
|
self.hyundai_lateral_fault = LateralFaultLatch(self.CP.carFingerprint)
|
||||||
@@ -148,7 +149,6 @@ class Controls:
|
|||||||
optional = list(
|
optional = list(
|
||||||
dict.fromkeys(
|
dict.fromkeys(
|
||||||
self.longitudinal_inputs.optional_services + ['starpilotCarState', 'deviceState', 'autoSteeringLearning', 'starpilotSteeringTracking', 'pandaStates']
|
self.longitudinal_inputs.optional_services + ['starpilotCarState', 'deviceState', 'autoSteeringLearning', 'starpilotSteeringTracking', 'pandaStates']
|
||||||
+ (['radarTracks'] if parked_runtime_supported(self.CP) else [])
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if optional:
|
if optional:
|
||||||
@@ -200,9 +200,6 @@ class Controls:
|
|||||||
self.lane_centering_host = LaneCenteringHost(
|
self.lane_centering_host = LaneCenteringHost(
|
||||||
self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None,
|
self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None,
|
||||||
) if lane_runtime_supported(self.CP) else None
|
) if lane_runtime_supported(self.CP) else None
|
||||||
self.parked_clearance_host = ParkedClearanceHost(
|
|
||||||
self.params, settings_reader=(lambda: preferences.current.parked) if preferences is not None else None,
|
|
||||||
) if parked_runtime_supported(self.CP) else None
|
|
||||||
self.torque_host = (
|
self.torque_host = (
|
||||||
TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None))
|
TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None))
|
||||||
if torque_runtime_enabled(self.CP, self.params)
|
if torque_runtime_enabled(self.CP, self.params)
|
||||||
@@ -654,7 +651,8 @@ class Controls:
|
|||||||
kona_tau = getattr(self, "kona_smoothing", 0.)
|
kona_tau = getattr(self, "kona_smoothing", 0.)
|
||||||
from openpilot.starpilot.car.subaru.smoothing import seconds as subaru_smooth_seconds, control_maximum
|
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:
|
if getattr(self, "volkswagen_smoothing", None) is not None:
|
||||||
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
|
lat_delay += self.volkswagen_smoothing.seconds(int(self.sm.logMonoTime["modelV2"]), time.monotonic_ns())
|
||||||
|
|
||||||
@@ -684,11 +682,6 @@ class Controls:
|
|||||||
steering_limited=self.steer_limited_by_safety,
|
steering_limited=self.steer_limited_by_safety,
|
||||||
actuator_delay_s=lat_delay,
|
actuator_delay_s=lat_delay,
|
||||||
)
|
)
|
||||||
parked_clearance = getattr(self, 'parked_clearance_host', None)
|
|
||||||
if parked_clearance is not None:
|
|
||||||
new_desired_curvature += parked_clearance.update(
|
|
||||||
self.sm, now_ns=int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns(),
|
|
||||||
lateral_active=bool(CC.latActive), maneuver=bool(self.sm.valid['lateralManeuverPlan']))
|
|
||||||
lane_base_curvature = new_desired_curvature
|
lane_base_curvature = new_desired_curvature
|
||||||
self.lane_centering_applied = 0.0
|
self.lane_centering_applied = 0.0
|
||||||
self.lane_centering_inactive_reason = 'inactive'
|
self.lane_centering_inactive_reason = 'inactive'
|
||||||
@@ -725,7 +718,6 @@ class Controls:
|
|||||||
time_discontinuity=lane_centering.time_discontinuity,
|
time_discontinuity=lane_centering.time_discontinuity,
|
||||||
measured_curvature=self.curvature,
|
measured_curvature=self.curvature,
|
||||||
lateral_delay_s=lane_delay,
|
lateral_delay_s=lane_delay,
|
||||||
hold=bool(parked_clearance is not None and parked_clearance.shift > 0.0),
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.last_lane_centering_result = result
|
self.last_lane_centering_result = result
|
||||||
|
|||||||
@@ -202,7 +202,7 @@ class LongitudinalPlanner:
|
|||||||
lead_approach_key: LeadApproachKey | None = None,
|
lead_approach_key: LeadApproachKey | None = None,
|
||||||
force_stop_provider: Callable[[float], StopPlan] | None = None,
|
force_stop_provider: Callable[[float], StopPlan] | None = None,
|
||||||
faster_lead_takeoff: bool = False, takeoff_drive_id: int = 0,
|
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:
|
if curve_ceiling is not None and curve_provider is not None:
|
||||||
raise ValueError('choose explicit Curve ceiling or same-cycle provider')
|
raise ValueError('choose explicit Curve ceiling or same-cycle provider')
|
||||||
if self.plan_drive_id != drive_id:
|
if self.plan_drive_id != drive_id:
|
||||||
@@ -585,20 +585,28 @@ class LongitudinalPlanner:
|
|||||||
not all(getattr(sm, health, {}).get(service, False)
|
not all(getattr(sm, health, {}).get(service, False)
|
||||||
for health in ('alive', 'valid', 'freq_ok') for service in ('modelV2', 'carState', 'radarState'))
|
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(
|
encouraged_model = self.encouragement.update(
|
||||||
sm, self.CP, now_ns=sample_now_ns, drive_id=drive_id, dt=self.dt, target_speed=v_cruise,
|
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,
|
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)
|
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),
|
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),
|
blocked=bool(boost_blocked or convergence_blocked or
|
||||||
scale=self.personality_boost_scale)
|
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:
|
if boost_blocked or relaxed or traffic_mode is True or self.personality_boost_scale == 0.0:
|
||||||
self.personality_accel_boost.reset()
|
self.personality_accel_boost.reset()
|
||||||
else:
|
else:
|
||||||
boosted_model = self.personality_accel_boost.update(sm, output_a_target_e2e, 0.0)
|
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)
|
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)
|
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)
|
output_a_target_e2e = output_a_target_e2e + curve_offset if curve_offset < 0.0 else max(manual_model, encouraged_model)
|
||||||
|
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ def update_curve_frame(planner: LongitudinalPlanner, sm, CP, now_ns: int, *, hos
|
|||||||
event: CurveDriverEvent | None = None, lane_change_policy=None,
|
event: CurveDriverEvent | None = None, lane_change_policy=None,
|
||||||
global_braking_response: str | None = None, selected_profiles=None, conditional_handoff: ConditionalHandoff | None = 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,
|
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."""
|
"""One model cycle: MPC chooses follow time, then Curve samples and receives winner feedback."""
|
||||||
if host is None:
|
if host is None:
|
||||||
planner.update(sm, cruise_ceiling=cruise_ceiling, profile_tuning=profile_tuning, traffic_mode=traffic_mode,
|
planner.update(sm, cruise_ceiling=cruise_ceiling, profile_tuning=profile_tuning, traffic_mode=traffic_mode,
|
||||||
|
|||||||
@@ -118,13 +118,10 @@ class Track:
|
|||||||
"radarTrackId": self.identifier,
|
"radarTrackId": self.identifier,
|
||||||
}
|
}
|
||||||
|
|
||||||
def potential_low_speed_lead(self, v_ego: float, path: tuple[np.ndarray, np.ndarray] | None = None):
|
def potential_low_speed_lead(self, v_ego: float):
|
||||||
# stop for stuff in front of you and low speed, even without model confirmation
|
# stop for stuff in front of you and low speed, even without model confirmation
|
||||||
# Radar points closer than 0.75, are almost always glitches on toyota radars
|
# Radar points closer than 0.75, are almost always glitches on toyota radars
|
||||||
y_rel = self.yRel
|
return abs(self.yRel) < 1.0 and (v_ego < V_EGO_STATIONARY) and (0.75 < self.dRel < 25)
|
||||||
if path is not None and len(path[0]) and path[0][-1] >= self.dRel + RADAR_TO_CAMERA:
|
|
||||||
y_rel += float(np.interp(self.dRel + RADAR_TO_CAMERA, path[0], path[1]))
|
|
||||||
return abs(y_rel) < 1.0 and (v_ego < V_EGO_STATIONARY) and (0.75 < self.dRel < 25)
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
ret = f"x: {self.dRel:4.1f} y: {self.yRel:4.1f} v: {self.vRel:4.1f} a: {self.aLeadK:4.1f}"
|
ret = f"x: {self.dRel:4.1f} y: {self.yRel:4.1f} v: {self.vRel:4.1f} a: {self.aLeadK:4.1f}"
|
||||||
@@ -177,8 +174,7 @@ def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: floa
|
|||||||
|
|
||||||
|
|
||||||
def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader,
|
def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader,
|
||||||
model_v_ego: float, lead_prob: float, low_speed_override: bool = True,
|
model_v_ego: float, lead_prob: float, low_speed_override: bool = True) -> dict[str, Any]:
|
||||||
path: tuple[np.ndarray, np.ndarray] | None = None) -> dict[str, Any]:
|
|
||||||
# Determine leads, this is where the essential logic happens
|
# Determine leads, this is where the essential logic happens
|
||||||
if len(tracks) > 0 and ready and lead_prob > .5:
|
if len(tracks) > 0 and ready and lead_prob > .5:
|
||||||
track = match_vision_to_track(v_ego, lead_msg, tracks)
|
track = match_vision_to_track(v_ego, lead_msg, tracks)
|
||||||
@@ -192,7 +188,7 @@ def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capn
|
|||||||
lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego, lead_prob)
|
lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego, lead_prob)
|
||||||
|
|
||||||
if low_speed_override:
|
if low_speed_override:
|
||||||
low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego, path)]
|
low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego)]
|
||||||
if len(low_speed_tracks) > 0:
|
if len(low_speed_tracks) > 0:
|
||||||
closest_track = min(low_speed_tracks, key=lambda c: c.dRel)
|
closest_track = min(low_speed_tracks, key=lambda c: c.dRel)
|
||||||
|
|
||||||
@@ -203,23 +199,6 @@ def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capn
|
|||||||
return lead_dict
|
return lead_dict
|
||||||
|
|
||||||
|
|
||||||
def _has(message, field: str) -> bool:
|
|
||||||
has = getattr(message, '_has', None)
|
|
||||||
return has is None or bool(has(field))
|
|
||||||
|
|
||||||
|
|
||||||
def model_path(model) -> tuple[np.ndarray, np.ndarray] | None:
|
|
||||||
if not _has(model, 'position'):
|
|
||||||
return None
|
|
||||||
position = model.position
|
|
||||||
if not _has(position, 'x') or not _has(position, 'y'):
|
|
||||||
return None
|
|
||||||
x, y = np.asarray(position.x, dtype=float), np.asarray(position.y, dtype=float)
|
|
||||||
if len(x) < 2 or len(x) != len(y) or not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)) or np.any(np.diff(x) < 0):
|
|
||||||
return None
|
|
||||||
return x, y
|
|
||||||
|
|
||||||
|
|
||||||
class RadarD:
|
class RadarD:
|
||||||
def __init__(self, delay: float = 0.0, *, adjacent_enabled: bool = False, radar_available: bool = False,
|
def __init__(self, delay: float = 0.0, *, adjacent_enabled: bool = False, radar_available: bool = False,
|
||||||
clock_pair_fn=None, honda_bosch_a_radar: bool = False, use_voacc: bool = False):
|
clock_pair_fn=None, honda_bosch_a_radar: bool = False, use_voacc: bool = False):
|
||||||
@@ -380,8 +359,7 @@ class RadarD:
|
|||||||
elif self.honda_bosch_a is not None:
|
elif self.honda_bosch_a is not None:
|
||||||
self.radar_state.leadOne, self.radar_state.leadTwo = self.honda_bosch_a.leads(sm, self, model_v_ego)
|
self.radar_state.leadOne, self.radar_state.leadTwo = self.honda_bosch_a.leads(sm, self, model_v_ego)
|
||||||
else:
|
else:
|
||||||
self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.lead_prob_filters[0].x,
|
self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.lead_prob_filters[0].x, low_speed_override=True)
|
||||||
low_speed_override=True, path=model_path(sm['modelV2']))
|
|
||||||
self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego,
|
self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego,
|
||||||
self.lead_prob_filters[1].x, low_speed_override=False)
|
self.lead_prob_filters[1].x, low_speed_override=False)
|
||||||
if self.adjacent_enabled:
|
if self.adjacent_enabled:
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
import numpy as np
|
|
||||||
from types import SimpleNamespace as NS
|
|
||||||
|
|
||||||
from openpilot.selfdrive.controls.radard import KalmanParams, Track, get_lead, model_path
|
|
||||||
|
|
||||||
XS = np.linspace(0., 30., 33)
|
|
||||||
|
|
||||||
|
|
||||||
def stopped(d=8., y=0.):
|
|
||||||
track = Track(1, 0., KalmanParams(.05))
|
|
||||||
track.update(d, y, -2., 0.)
|
|
||||||
return track
|
|
||||||
|
|
||||||
|
|
||||||
def lead(path, track=None):
|
|
||||||
model = NS(x=[0.] * 6, y=[0.] * 6, v=[0.] * 6, a=[0.] * 6, xStd=[1.] * 6, yStd=[1.] * 6, vStd=[1.] * 6, aStd=[1.] * 6)
|
|
||||||
return get_lead(2., True, {1: track or stopped()}, model, 2., 0., low_speed_override=True, path=path)
|
|
||||||
|
|
||||||
|
|
||||||
def test_low_speed_override_follows_a_turning_path():
|
|
||||||
assert not lead((XS, -XS ** 2 / 12.))['present']
|
|
||||||
|
|
||||||
|
|
||||||
def test_low_speed_override_keeps_objects_in_path():
|
|
||||||
assert lead((XS, np.zeros_like(XS)))['present']
|
|
||||||
assert lead((XS, -XS ** 2 / 12.), stopped(8., 9.52 ** 2 / 12.))['present']
|
|
||||||
assert lead(None)['present']
|
|
||||||
|
|
||||||
|
|
||||||
def test_short_or_invalid_path_falls_back_to_straight_ahead():
|
|
||||||
assert lead((np.linspace(0., 2., 33), np.linspace(0., -5., 33)))['present']
|
|
||||||
assert model_path(NS(position=NS(x=[0., 1.], y=[0., float('nan')]))) is None
|
|
||||||
assert model_path(NS(position=NS(x=[1., 0.], y=[0., 0.]))) is None
|
|
||||||
@@ -56,6 +56,7 @@ from openpilot.starpilot.lateral.lane_change_status_wire import (
|
|||||||
from openpilot.starpilot.models.receipt import ModelReceiptOwner
|
from openpilot.starpilot.models.receipt import ModelReceiptOwner
|
||||||
from openpilot.starpilot.car.volkswagen.model_smoothing import seconds as volkswagen_smoothing
|
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.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.status import ModelVariant
|
||||||
from openpilot.starpilot.models.startup import report_load_timeout, wait_for_chestnut_power
|
from openpilot.starpilot.models.startup import report_load_timeout, wait_for_chestnut_power
|
||||||
from openpilot.starpilot.models.recovery import STARTUP_FALLBACK_EXIT
|
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
|
from openpilot.starpilot.car.subaru.smoothing import read_frozen, seconds as subaru_smooth_seconds, filter_action
|
||||||
subaru_smoothing = read_frozen(CP, params)
|
subaru_smoothing = read_frozen(CP, params)
|
||||||
kona_tau = kona_smoothing(CP)
|
kona_tau = kona_smoothing(CP)
|
||||||
|
bolt_tau = bolt_smoothing(CP)
|
||||||
|
|
||||||
st = time.monotonic()
|
st = time.monotonic()
|
||||||
cloudlog.warning("loading model")
|
cloudlog.warning("loading model")
|
||||||
@@ -581,7 +583,8 @@ def main(demo=False):
|
|||||||
v_ego = max(sm["carState"].vEgo, 0.)
|
v_ego = max(sm["carState"].vEgo, 0.)
|
||||||
subaru_tau = subaru_smooth_seconds(v_ego, subaru_smoothing)
|
subaru_tau = subaru_smooth_seconds(v_ego, subaru_smoothing)
|
||||||
volkswagen_tau = volkswagen_smoothing(CP, receipt_owner.load)
|
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']:
|
if sm.updated["extrinsicsCalibration"] and sm.seen['narrowRoadCameraState'] and sm.seen['deviceState']:
|
||||||
device_from_calib_euler = np.array(sm["extrinsicsCalibration"].rpyCalib, dtype=np.float32)
|
device_from_calib_euler = np.array(sm["extrinsicsCalibration"].rpyCalib, dtype=np.float32)
|
||||||
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['narrowRoadCameraState'].sensor))]
|
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['narrowRoadCameraState'].sensor))]
|
||||||
@@ -677,7 +680,7 @@ def main(demo=False):
|
|||||||
action = laboratory_action
|
action = laboratory_action
|
||||||
else:
|
else:
|
||||||
action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
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
|
prev_action = action
|
||||||
fill_model_msg(modelv2_send, model_output, action,
|
fill_model_msg(modelv2_send, model_output, action,
|
||||||
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
||||||
|
|||||||
@@ -6,8 +6,12 @@ import numpy as np
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from openpilot.cereal import log
|
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.controls.lib.drive_helpers import smooth_value
|
||||||
from openpilot.selfdrive.modeld.constants import LAT_SMOOTH_SECONDS
|
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():
|
def action_function():
|
||||||
@@ -46,3 +50,20 @@ def test_legacy_plan_action_is_unchanged():
|
|||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
assert action.desiredCurvature == pytest.approx(smooth_value(0.02, 0.01, LAT_SMOOTH_SECONDS))
|
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))
|
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.
@@ -107,6 +107,9 @@ class SelfdriveD:
|
|||||||
cloudlog.info("selfdrived got CarParams")
|
cloudlog.info("selfdrived got CarParams")
|
||||||
else:
|
else:
|
||||||
self.CP = CP
|
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.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
|
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_transport_pause = TransportPause(self.CP, self.aol_session_id)
|
||||||
self.aol_fault_reason = 'none'
|
self.aol_fault_reason = 'none'
|
||||||
self.steering_authority_unavailable = False
|
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))
|
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.force_stop_hold_alert = HoldAlertState()
|
||||||
self.aol_car_state_log_ns = 0
|
self.aol_car_state_log_ns = 0
|
||||||
self.aol_last_intent = None
|
self.aol_last_intent = None
|
||||||
@@ -293,7 +299,8 @@ class SelfdriveD:
|
|||||||
return update_big_model_status(self)
|
return update_big_model_status(self)
|
||||||
|
|
||||||
def _update_steering_authority(self, CS):
|
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
|
self.steering_authority_unavailable = False
|
||||||
return
|
return
|
||||||
companion = getattr(self, 'steering_companion', None)
|
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
|
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)
|
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
|
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,
|
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:
|
if not source_current:
|
||||||
pair = None
|
pair = None
|
||||||
previous_axes = self.aol_axis_decision
|
previous_axes = self.aol_axis_decision
|
||||||
expected_active = self.active or previous_axes.lateral_active or previous_axes.longitudinal_active
|
expected_active = self.active or previous_axes.lateral_active or previous_axes.longitudinal_active
|
||||||
if pair is not None:
|
if pair is not None:
|
||||||
self.steering_authority_unavailable = pair
|
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
|
self.steering_authority_unavailable = True
|
||||||
if getattr(self, 'steering_authority_unavailable', False):
|
if getattr(self, 'steering_authority_unavailable', False):
|
||||||
self.events.add(EventName.controlsMismatch)
|
self.events.add(EventName.controlsMismatch)
|
||||||
@@ -2327,15 +2336,18 @@ class SelfdriveD:
|
|||||||
not self.events.contains(ET.OVERRIDE_LONGITUDINAL)))
|
not self.events.contains(ET.OVERRIDE_LONGITUDINAL)))
|
||||||
if not hasattr(self, 'aol_transport_pause'):
|
if not hasattr(self, 'aol_transport_pause'):
|
||||||
self.aol_transport_pause = TransportPause(self.CP, self.aol_session_id)
|
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(
|
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,
|
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,
|
companion=getattr(self, 'aol_intent_companion', None), previous_intent=previous_intent, intent=intent,
|
||||||
expired_healthy_source=getattr(self, 'aol_expired_healthy_source', False),
|
expired_healthy_source=getattr(self, 'aol_expired_healthy_source', False),
|
||||||
previously_active=previous.lateral_active, hard_fault=bool(
|
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
|
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())),
|
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
|
model_ready=model_ready,
|
||||||
self.sm['extrinsicsCalibration'].calStatus == log.ExtrinsicsCalibration.Status.calibrated),
|
|
||||||
user_disable=self.events.contains(ET.USER_DISABLE))
|
user_disable=self.events.contains(ET.USER_DISABLE))
|
||||||
if source_current:
|
if source_current:
|
||||||
self.observe_ordinary_source_metadata(CS, intent, self.aol_transport_pause.observed_native, now_ns)
|
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)
|
source_expiry_events.add(EventName.commIssue)
|
||||||
availability_events += source_expiry_events.to_msg()
|
availability_events += source_expiry_events.to_msg()
|
||||||
availability = self.aol_availability_pause.observe(
|
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,
|
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,
|
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
|
model_ready=model_ready,
|
||||||
self.sm['extrinsicsCalibration'].calStatus == log.ExtrinsicsCalibration.Status.calibrated),
|
|
||||||
source_current=source_current, source_expired=publication_expiry, prior_lateral_active=previous.lateral_active,
|
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
|
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),
|
lost_companion and not publication_expiry or lost_permission or upgraded),
|
||||||
|
|||||||
@@ -316,12 +316,6 @@ class WifiUIMici(NavScroller):
|
|||||||
btn = WifiButton(network, self._wifi_manager)
|
btn = WifiButton(network, self._wifi_manager)
|
||||||
btn.set_click_callback(lambda ssid=network.ssid: self._connect_to_network(ssid))
|
btn.set_click_callback(lambda ssid=network.ssid: self._connect_to_network(ssid))
|
||||||
self._scroller.add_widget(btn)
|
self._scroller.add_widget(btn)
|
||||||
if self._wifi_manager.is_connection_saved(network.ssid):
|
|
||||||
items = self._scroller.items
|
|
||||||
first_unsaved = next((i for i, b in enumerate(items) if isinstance(b, WifiButton) and b is not btn and
|
|
||||||
not self._wifi_manager.is_connection_saved(b.network.ssid)), None)
|
|
||||||
if first_unsaved is not None:
|
|
||||||
items.insert(first_unsaved, items.pop())
|
|
||||||
|
|
||||||
if re_sort:
|
if re_sort:
|
||||||
# Remove stale buttons and sort to match scan order, preserving eager state
|
# Remove stale buttons and sort to match scan order, preserving eager state
|
||||||
|
|||||||
@@ -102,6 +102,7 @@ class TransportPauseFeedback:
|
|||||||
self.session = ''
|
self.session = ''
|
||||||
self.sequence = 0
|
self.sequence = 0
|
||||||
self.subaru_paddle_denial = None
|
self.subaru_paddle_denial = None
|
||||||
|
self.subaru_paddle_eps_ns = 0
|
||||||
self.signature = None
|
self.signature = None
|
||||||
self.paused = False
|
self.paused = False
|
||||||
self.qualified = False
|
self.qualified = False
|
||||||
@@ -737,7 +738,7 @@ class TransportPauseFeedback:
|
|||||||
if reason not in ('none', 'availabilityPause') or reason == 'none' and not availability_only(events):
|
if reason not in ('none', 'availabilityPause') or reason == 'none' and not availability_only(events):
|
||||||
return False
|
return False
|
||||||
if not (latched and current and continuity and not self.paused and not self.pending_event and
|
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
|
getattr(axis, 'intentProducerSessionId', '') == intent_producer_session == self.availability_producer and
|
||||||
int(getattr(axis, 'intentIntegrityEpoch', 0)) == self.availability_epoch and
|
int(getattr(axis, 'intentIntegrityEpoch', 0)) == self.availability_epoch and
|
||||||
self.session and
|
self.session and
|
||||||
@@ -1196,6 +1197,7 @@ class TransportPauseFeedback:
|
|||||||
self.cold_main_sparse_waiting = False
|
self.cold_main_sparse_waiting = False
|
||||||
self.subaru_braked_main = None
|
self.subaru_braked_main = None
|
||||||
self.subaru_paddle_denial = None
|
self.subaru_paddle_denial = None
|
||||||
|
self.subaru_paddle_eps_ns = 0
|
||||||
self.subaru_eps_brake_event_ns = 0
|
self.subaru_eps_brake_event_ns = 0
|
||||||
stamp = int(sm.logMonoTime['aolAxisState'])
|
stamp = int(sm.logMonoTime['aolAxisState'])
|
||||||
reason = str(axis.faultReason)
|
reason = str(axis.faultReason)
|
||||||
@@ -1230,8 +1232,8 @@ class TransportPauseFeedback:
|
|||||||
self.retention_pending = not self.retention_qualified
|
self.retention_pending = not self.retention_qualified
|
||||||
return False
|
return False
|
||||||
from openpilot.starpilot.car.gm.aol import sdgm_alpha_lateral_owner
|
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
|
if (latched and current and continuity and self.signature is not None and
|
||||||
signature[14:16] != self.signature[14:16]):
|
signature[14:16] != self.signature[14:16] and sdgm_alpha_lateral_owner(cp)):
|
||||||
self.failed = True
|
self.failed = True
|
||||||
return 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
|
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
|
cs.cruiseState.available and not cs.doorOpen and not cs.vehicleSensorsInvalid and not cs.steeringDisengage and
|
||||||
not cs.regenBraking and
|
not cs.regenBraking and
|
||||||
sm.seen['aolAxisState'] and sm.valid['aolAxisState'] and sm.alive['aolAxisState'] 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)
|
0 < stamp == axis.observedMonoTime < axis.validUntilMonoTime < now_ns)
|
||||||
brake_native = (self._honda_brake_lateral_current(sm, cp, cs, axis, 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)
|
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:
|
if cp.brand == 'subaru' and self.availability_producer:
|
||||||
self.subaru_lateral_grant_ns = max(self.subaru_lateral_grant_ns, int(native.observedMonoTime))
|
self.subaru_lateral_grant_ns = max(self.subaru_lateral_grant_ns, int(native.observedMonoTime))
|
||||||
self.subaru_braked_main = None
|
self.subaru_braked_main = None
|
||||||
|
self.subaru_paddle_eps_ns = 0
|
||||||
self.subaru_eps_brake_event_ns = 0
|
self.subaru_eps_brake_event_ns = 0
|
||||||
self.lag_withdrawal_ns = 0
|
self.lag_withdrawal_ns = 0
|
||||||
self.cold_main_wait_ns = 0
|
self.cold_main_wait_ns = 0
|
||||||
|
|||||||
@@ -18,10 +18,12 @@ class TransportPause:
|
|||||||
self.epoch = None
|
self.epoch = None
|
||||||
|
|
||||||
def observe(self, *, cp, session, sm, cs, native, now_ns, companion, previous_intent,
|
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
|
from openpilot.starpilot.aol import transport_pause as transport
|
||||||
self.observed_native = None
|
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:
|
if context_current:
|
||||||
self.observed_native = transport._healthy_transport_native(sm, cp, cs, session, now_ns, native)
|
self.observed_native = transport._healthy_transport_native(sm, cp, cs, session, now_ns, native)
|
||||||
if self.observed_native is None and cp.brand == 'ford':
|
if self.observed_native is None and cp.brand == 'ford':
|
||||||
@@ -73,11 +75,13 @@ class AvailabilityPause:
|
|||||||
self.active = False
|
self.active = False
|
||||||
|
|
||||||
def observe(self, *, cp, session, sm, cs, native, now_ns, companion, intent,
|
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
|
from openpilot.starpilot.aol import transport_pause as transport
|
||||||
try:
|
try:
|
||||||
healthy = healthy_native
|
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
|
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
|
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)
|
healthy is not None and healthy.requestedLateral and healthy.lateralAllowed and healthy.pandaInventory)
|
||||||
|
|||||||
@@ -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 fcntl
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -42,8 +42,9 @@ class _Cancelled(Exception):
|
|||||||
|
|
||||||
|
|
||||||
class SoundDownloads:
|
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.parked = parked
|
||||||
|
self.selection = selection
|
||||||
self.root = Path(root)
|
self.root = Path(root)
|
||||||
self.opener = opener or urllib.request.urlopen
|
self.opener = opener or urllib.request.urlopen
|
||||||
self._lock = threading.Lock()
|
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"):
|
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)
|
raise SoundDownloadError("download job not active", 409)
|
||||||
self._cancel.set()
|
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":
|
elif command == "download":
|
||||||
if set(data) != {"pack"}:
|
if set(data) != {"pack"}:
|
||||||
raise SoundDownloadError("invalid request")
|
raise SoundDownloadError("invalid request")
|
||||||
@@ -117,19 +136,7 @@ class SoundDownloads:
|
|||||||
self._prepare_root()
|
self._prepare_root()
|
||||||
if (self.root / slug).exists() or (self.root / slug).is_symlink():
|
if (self.root / slug).exists() or (self.root / slug).is_symlink():
|
||||||
raise SoundDownloadError("sound pack already exists", 409)
|
raise SoundDownloadError("sound pack already exists", 409)
|
||||||
try:
|
lock_file = self._acquire_storage_lock()
|
||||||
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
|
|
||||||
if (self.root / slug).exists() or (self.root / slug).is_symlink():
|
if (self.root / slug).exists() or (self.root / slug).is_symlink():
|
||||||
fcntl.flock(lock_file, fcntl.LOCK_UN)
|
fcntl.flock(lock_file, fcntl.LOCK_UN)
|
||||||
lock_file.close()
|
lock_file.close()
|
||||||
@@ -145,6 +152,22 @@ class SoundDownloads:
|
|||||||
raise SoundDownloadError("unknown action")
|
raise SoundDownloadError("unknown action")
|
||||||
return self.snapshot()
|
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:
|
def _safe_parked(self) -> bool:
|
||||||
try:
|
try:
|
||||||
return bool(self.parked())
|
return bool(self.parked())
|
||||||
|
|||||||
@@ -77,8 +77,8 @@ def migrate_removed_selection(params, root: Path = PACK_ROOT) -> bool:
|
|||||||
authorized=lambda: True, temp_prefix=".sound-pack-migration-").verified
|
authorized=lambda: True, temp_prefix=".sound-pack-migration-").verified
|
||||||
|
|
||||||
|
|
||||||
def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
|
def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked, downloaded: str | None = None) -> tuple[str, ...]:
|
||||||
"""Bounded parked migration over captured directory descriptors.
|
"""Bounded parked sound-pack cleanup over captured directory descriptors.
|
||||||
|
|
||||||
Enumerate at most 256 root entries and 64 pack entries, depth 4 / 96 MiB.
|
Enumerate at most 256 root entries and 64 pack entries, depth 4 / 96 MiB.
|
||||||
Keep captured descriptors, never follow links, and check entry identities
|
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 ()
|
return ()
|
||||||
names.append(entry.name)
|
names.append(entry.name)
|
||||||
for name in names:
|
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
|
continue
|
||||||
expected = os.stat(name, dir_fd=root_fd, follow_symlinks=False)
|
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))
|
inode(os.stat(name, dir_fd=root_fd, follow_symlinks=False)) == inode(expected))
|
||||||
|
|
||||||
if stat.S_ISLNK(expected.st_mode):
|
if stat.S_ISLNK(expected.st_mode):
|
||||||
if guard():
|
if downloaded is None and guard():
|
||||||
os.unlink(name, dir_fd=root_fd)
|
os.unlink(name, dir_fd=root_fd)
|
||||||
removed.append(name)
|
removed.append(name)
|
||||||
continue
|
continue
|
||||||
@@ -163,6 +165,12 @@ def cleanup_removed_packs(root: Path = PACK_ROOT, *, parked) -> tuple[str, ...]:
|
|||||||
return node
|
return node
|
||||||
|
|
||||||
tree = plan(pack_fd, 1)
|
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):
|
def same_entries(directory_fd, expected_names):
|
||||||
observed = set()
|
observed = set()
|
||||||
|
|||||||
@@ -54,14 +54,14 @@ class SoundDownloadTests(unittest.TestCase):
|
|||||||
self.parked = [True]
|
self.parked = [True]
|
||||||
self.managers = []
|
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": [{
|
self.catalog.write_text(json.dumps({"version": 1, "packs": [{
|
||||||
"id": slug, "name": "Duck", "path": f"theme/Themes/{slug}/sounds.zip",
|
"id": slug, "name": "Duck", "path": f"theme/Themes/{slug}/sounds.zip",
|
||||||
"size": len(payload) if size is None else size,
|
"size": len(payload) if size is None else size,
|
||||||
"sha256": hashlib.sha256(payload).hexdigest() if digest is None else digest,
|
"sha256": hashlib.sha256(payload).hexdigest() if digest is None else digest,
|
||||||
}]}))
|
}]}))
|
||||||
manager = SoundDownloads(lambda: self.parked[0], self.root, self.catalog,
|
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.managers.append(manager)
|
||||||
self.addCleanup(manager.close)
|
self.addCleanup(manager.close)
|
||||||
return manager
|
return manager
|
||||||
@@ -75,6 +75,35 @@ class SoundDownloadTests(unittest.TestCase):
|
|||||||
time.sleep(.005)
|
time.sleep(.005)
|
||||||
self.fail("download did not finish")
|
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):
|
def test_install_and_loader(self):
|
||||||
payload = archive({"sounds/": b"", "sounds/engage.wav": wav(2000),
|
payload = archive({"sounds/": b"", "sounds/engage.wav": wav(2000),
|
||||||
"sounds/warning_soft.wav": wav(3000),
|
"sounds/warning_soft.wav": wav(3000),
|
||||||
|
|||||||
@@ -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))
|
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."""
|
"""Qualified non-pedal Volt owners consume their exact raw steering receipt."""
|
||||||
from opendbc.car.gm.steering_authority import monitored_profile
|
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."""
|
"""Recognize lost Card publication; never supply a current steering receipt."""
|
||||||
from openpilot.starpilot.aol.runtime import INTENT_MAX_AGE_NS
|
from openpilot.starpilot.aol.runtime import INTENT_MAX_AGE_NS
|
||||||
service = 'starpilotCarState'
|
service = 'starpilotCarState'
|
||||||
sdgm = sdgm_alpha_lateral_owner(owner.CP)
|
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, 'steering_authority_unavailable', False) or
|
||||||
getattr(owner, 'car_state_samples', ())):
|
getattr(owner, 'car_state_samples', ())):
|
||||||
return False
|
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.controls.lib.drive_helpers import get_curvature_from_plan, smooth_value
|
||||||
from openpilot.selfdrive.modeld.constants import ModelConstants
|
from openpilot.selfdrive.modeld.constants import ModelConstants
|
||||||
from openpilot.starpilot.car.hyundai.model_smoothing import seconds
|
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
|
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)
|
cp = setup(alpha)
|
||||||
action = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=-.25, shouldStop=True)
|
action = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=-.25, shouldStop=True)
|
||||||
previous = log.ModelDataV2.Action(desiredCurvature=0.)
|
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.,
|
'subaru_smooth_seconds': lambda *args: 0., 'volkswagen_smoothing': lambda *args: 0.,
|
||||||
'kona_smoothing': seconds, 'kona_tau': seconds(cp), 'LAT_SMOOTH_SECONDS': 0.,
|
'kona_smoothing': seconds, 'kona_tau': seconds(cp), 'LAT_SMOOTH_SECONDS': 0.,
|
||||||
'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.3)}, 'action': action, 'prev_action': previous,
|
'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.3)}, 'action': action, 'prev_action': previous,
|
||||||
'filter_action': filter_action, 'frame_delay': .05, 'action_delay': .025, 'inputs': {}, 'np': np}
|
'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
|
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.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))]
|
any(isinstance(t, ast.Subscript) and ast.unparse(t) == "inputs['lateral_control_params']" for t in n.targets))]
|
||||||
|
|||||||
@@ -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):
|
if retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, latched=latched, producer=producer):
|
||||||
return True
|
return True
|
||||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
|
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
|
||||||
|
from openpilot.starpilot.car.subaru.aol import known_paddle_pause
|
||||||
previous = feedback.signature
|
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
|
if (not qualified(cp, marked_only=True) or cp.openpilotLongitudinalControl or
|
||||||
not latched or feedback.failed or feedback.paused or
|
not latched or feedback.failed or feedback.paused or
|
||||||
feedback.retention_started_ns or feedback.source_retention_started_ns or
|
feedback.retention_started_ns or feedback.source_retention_started_ns or
|
||||||
previous is None or not feedback.session or not producer 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[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
|
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
|
str(axis.mode) != ('lateralOnly' if axis.lateralActive else 'off') or
|
||||||
axis.lateralActive and not axis.desiredLateral or axis.desiredLongitudinal or axis.longitudinalActive 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 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 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.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
|
||||||
state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or
|
state.steeringDisengage or state.buttonEvents or state.gasPressed and not paddle_eps 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
|
not (cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025} and
|
||||||
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
|
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
|
||||||
not state.cruiseState.available or state.cruiseState.enabled 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
|
pending = feedback.pending_event
|
||||||
matched = axis.faultEventMonoTime == event_ns <= stamp
|
matched = axis.faultEventMonoTime == event_ns <= stamp
|
||||||
joined_event = max(axis.faultEventMonoTime, event_ns)
|
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
|
min(axis.faultEventMonoTime, event_ns) in (restriction, pending) and
|
||||||
restriction < joined_event <= now_ns and now_ns - joined_event <= AXIS_MAX_AGE_NS and
|
restriction < joined_event <= now_ns and now_ns - joined_event <= AXIS_MAX_AGE_NS and
|
||||||
(not pending or joined_event >= pending))
|
(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
|
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
|
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
|
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
|
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||||
(state.brakePressed or feedback.subaru_eps_brake_event_ns == event_ns) and
|
(state.brakePressed or feedback.subaru_eps_brake_event_ns == event_ns) and
|
||||||
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||||
return False
|
return False
|
||||||
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
|
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
|
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
|
axis.lateralActive and not native.lateralAllowed or native.requestedLongitudinal or native.longitudinalAllowed or
|
||||||
native.observedMonoTime < feedback.healthy_native_ns or
|
native.observedMonoTime < feedback.healthy_native_ns or
|
||||||
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
||||||
return False
|
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:
|
if matched:
|
||||||
feedback.pending_event = 0
|
feedback.pending_event = 0
|
||||||
feedback.temporary_eps_event_ns = event_ns
|
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):
|
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."""
|
"""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.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
|
previous = feedback.signature
|
||||||
pending, restriction = feedback.pending_event, getattr(feedback, 'temporary_eps_event_ns', 0)
|
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
|
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.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.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
|
||||||
state.steeringDisengage or state.buttonEvents or state.regenBraking 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
|
not (cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025} and
|
||||||
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
|
state.gearShifter == structs.CarState.GearShifter.manumatic)) or
|
||||||
not state.cruiseState.available or state.cruiseState.enabled):
|
not state.cruiseState.available or state.cruiseState.enabled):
|
||||||
return False
|
return False
|
||||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||||
temporary = (log.OnroadEvent.EventName.steerTempUnavailable, log.OnroadEvent.EventName.steerTempUnavailableSilent)
|
names = log.OnroadEvent.EventName
|
||||||
allowed = (*temporary, log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.gasPressedOverride,
|
temporary = (names.steerTempUnavailable, names.steerTempUnavailableSilent)
|
||||||
log.OnroadEvent.EventName.steerOverride, log.OnroadEvent.EventName.pedalPressed)
|
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
|
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
|
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
|
max(axis.faultEventMonoTime, event_ns) != pending or event_ns > stamp or
|
||||||
not any(event.name in temporary for event in sm['onroadEvents']) 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
|
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||||
(state.brakePressed or feedback.subaru_eps_brake_event_ns in (restriction, pending)) and
|
(state.brakePressed or feedback.subaru_eps_brake_event_ns in (restriction, pending)) and
|
||||||
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||||
return False
|
return False
|
||||||
native = _healthy_transport_native(sm, cp, state, feedback.session, now_ns)
|
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
|
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))):
|
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
||||||
return False
|
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 sd.aol_stopped_intent_proof is proof
|
||||||
assert (leases(feedback), feedback.signature, intent.validUntilMonoTime, sd.aol_axis_decision) == before
|
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)
|
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():
|
def common_join():
|
||||||
tree = ast.parse(Path(modeld.__file__).read_text())
|
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 = []
|
matches = []
|
||||||
for node in ast.walk(tree):
|
for node in ast.walk(tree):
|
||||||
body = getattr(node, 'body', None)
|
body = getattr(node, 'body', None)
|
||||||
@@ -28,9 +32,9 @@ def common_join():
|
|||||||
assert len(statements) == 3
|
assert len(statements) == 3
|
||||||
assert sum(isinstance(call, ast.Call) and ast.unparse(call.func) == 'model.get_action_from_model'
|
assert sum(isinstance(call, ast.Call) and ast.unparse(call.func) == 'model.get_action_from_model'
|
||||||
for call in ast.walk(statements[0])) == 1
|
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'
|
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
|
assert len(matches) == 1
|
||||||
return compile(matches[0], modeld.__file__, 'exec')
|
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))
|
SimpleNamespace(get_action_from_model=function))
|
||||||
paired_action = function(outputs, previous, .2, .2, 2.) if owner == 'laboratory' else None
|
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,
|
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)
|
exec(common_join(), scope)
|
||||||
action = scope['action']
|
action = scope['action']
|
||||||
assert isinstance(action, (_DynamicStructBuilder, _DynamicStructReader))
|
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)
|
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()
|
owner = StopAndGo()
|
||||||
cc, cs = state()
|
cc, cs = state()
|
||||||
pulses = [frame for frame in range(111) if owner.update(cc, cs, frame)[1]]
|
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
|
cs.close_distance += 0.02
|
||||||
assert owner.update(cc, cs, 111)[0]
|
assert owner.update(cc, cs, 111)[0]
|
||||||
cc.hudControl.leadVisible = False
|
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
|
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
|
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
|
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 time as time_module
|
||||||
|
|
||||||
|
import pytest
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
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.interface import CarInterface
|
||||||
from opendbc.car.subaru.sng import prepare, selected
|
from opendbc.car.subaru.sng import prepare, selected
|
||||||
from opendbc.car.subaru.values import CAR
|
from opendbc.car.subaru.values import CAR
|
||||||
|
from opendbc.safety.tests.libsafety import libsafety_py
|
||||||
from openpilot.cereal import messaging
|
from openpilot.cereal import messaging
|
||||||
from openpilot.starpilot.car.subaru.sng_caller import update as sng_caller_update
|
from openpilot.starpilot.car.subaru.sng_caller import update as sng_caller_update
|
||||||
from openpilot.starpilot.car.subaru.tests.caller_helpers import CompleteCan
|
from openpilot.starpilot.car.subaru.tests.caller_helpers import CompleteCan
|
||||||
@@ -54,7 +57,12 @@ class FakeSubMaster:
|
|||||||
self.recv_time[name] = (now_ns - 1000) / 1e9
|
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)
|
cp = CarInterface.get_params(CAR.SUBARU_IMPREZA_2020, gen_empty_fingerprint(), [], False, False, False)
|
||||||
prepare(cp, True)
|
prepare(cp, True)
|
||||||
assert selected(cp)
|
assert selected(cp)
|
||||||
@@ -90,8 +98,9 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
|
|||||||
throttle_taps = []
|
throttle_taps = []
|
||||||
ready_ticks = []
|
ready_ticks = []
|
||||||
max_duration = 0
|
max_duration = 0
|
||||||
for tick in range(200):
|
for tick in range(670):
|
||||||
now = base_ns + tick * 10_000_000
|
now = base_ns + tick * tick_ns
|
||||||
|
values['CruiseControl']['Cruise_Activated'] = int(tick >= 12)
|
||||||
_virtual['ns'] = now
|
_virtual['ns'] = now
|
||||||
frames = []
|
frames = []
|
||||||
if tick % 5 == 4:
|
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.
|
# 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.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 ()))
|
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)])
|
ci.update([(now, frames)])
|
||||||
assert ci.CS.out.standstill
|
assert ci.CS.out.standstill
|
||||||
sm.update(now)
|
sm.update(now)
|
||||||
@@ -107,9 +120,12 @@ def test_sng_hold_pulse_with_batched_throttle_delivery():
|
|||||||
if tick >= 20:
|
if tick >= 20:
|
||||||
ready_ticks.append(bool(ci.CS.sng_lead_ready))
|
ready_ticks.append(bool(ci.CS.sng_lead_ready))
|
||||||
max_duration = max(max_duration, ci.CC.frame - ci.CC.sng_owner.last_standstill_frame)
|
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:
|
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:
|
if address == 0x40 and data[4] == 5:
|
||||||
throttle_taps.append(tick)
|
throttle_taps.append(tick)
|
||||||
# The batched ticks must not flap the lead-ready health signal...
|
# 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
|
# ...the standstill clock must run past the 51 consecutive frames the
|
||||||
# hold pulse requires (it peaked at 24 in the 2026-11-24 incident)...
|
# hold pulse requires (it peaked at 24 in the 2026-11-24 incident)...
|
||||||
assert max_duration > 50, max_duration
|
assert max_duration > 50, max_duration
|
||||||
# ...and the spoofed 3 kph Brake_Pedal hold pulse must reach the wire,
|
bursts: list[list[int]] = []
|
||||||
# on roughly the designed 0.55 s cadence (two pulses in 2 s).
|
for stamp in pulses:
|
||||||
assert len(pulses) >= 2, 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.
|
# The departure tap must not fire: Close_Distance never enters 3.0-4.5 m.
|
||||||
assert not throttle_taps, throttle_taps
|
assert not throttle_taps, throttle_taps
|
||||||
finally:
|
finally:
|
||||||
|
safety.init_tests()
|
||||||
|
safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0)
|
||||||
if _ADDED_BOOTTIME:
|
if _ADDED_BOOTTIME:
|
||||||
del time_module.CLOCK_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,
|
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,
|
hard_stop_native_first=False, main_only=False, preferences=None, firmware=None,
|
||||||
manual_ratio=None, camera_hud=False, manual_phase=0,
|
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,
|
deadline_gap=False, fixed_angle_handoff=False, host_first_stop=False,
|
||||||
source_outage=False, vm_angle_handoff=0, crawl=False, eps_brake_join=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,
|
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,
|
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):
|
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
|
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
|
fw = firmware_records(candidate, FW_VERSIONS, 'subaru') if firmware is None else firmware
|
||||||
rows = []
|
rows = []
|
||||||
if candidate == CAR.SUBARU_IMPREZA_2025 and firmware is None:
|
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
|
reverse = 150 + manual_phase <= tick < 185
|
||||||
exit_transition = exit_gear and exit_tick <= tick < exit_tick + exit_duration
|
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
|
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
|
temporary = not (exit_gear or paddle_eps) and not guard_brake_release and 225 <= tick < 260
|
||||||
main = not 310 <= tick < 350 and (tick >= 30 or not main_only)
|
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)
|
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:
|
if stopped_source_gap == 2 and stopped:
|
||||||
brake = elapsed < 130
|
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)
|
temporary = bool(paused_eps in (3, 4, 6) and 95 <= tick < 111 or temporary)
|
||||||
|
|
||||||
values = {
|
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),
|
'Steering_Torque': {'Steer_Warning': int(temporary),
|
||||||
'Steer_Torque_Sensor': (250 if 70 <= tick < 76 else
|
'Steer_Torque_Sensor': (250 if 70 <= tick < 76 else
|
||||||
80 if vm_angle_handoff and 76 <= tick < 90 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
|
cs = published['carState'].carState
|
||||||
expected_gear = {3: structs.CarState.GearShifter.reverse, 121: structs.CarState.GearShifter.drive}.get(
|
expected_gear = {3: structs.CarState.GearShifter.reverse, 121: structs.CarState.GearShifter.drive}.get(
|
||||||
gear, structs.CarState.GearShifter.manumatic)
|
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):
|
if exit_transition and (not retained_exit or tick >= exit_tick + 15):
|
||||||
expected_gear = structs.CarState.GearShifter.unknown
|
expected_gear = structs.CarState.GearShifter.unknown
|
||||||
assert cs.brakePressed == brake and cs.gearShifter == expected_gear, (tick, gear, cs.gearShifter, expected_gear)
|
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 aol and main_only and cs.brakePressed and not command.enabled
|
||||||
assert request and accepted, ('CRAWL_AOL_BRAKE_WITHDREW', tick, decoded_steering)
|
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
|
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:
|
if angle_handoff and 72 <= tick < 78:
|
||||||
assert not request and accepted, (tick, decoded_steering)
|
assert not request and accepted, (tick, decoded_steering)
|
||||||
else:
|
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)
|
assert accepted, ('SUBARU_ANGLE_HANDOFF_NATIVE_REJECTED', tick, decoded_steering)
|
||||||
if output != 0:
|
if output != 0:
|
||||||
active_emissions.append(tick)
|
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:
|
if angle_handoff or angle_continuation:
|
||||||
assert not request and abs(output - cs.steeringAngleDeg) <= 0.011, (tick, decoded_steering)
|
assert not request and abs(output - cs.steeringAngleDeg) <= 0.011, (tick, decoded_steering)
|
||||||
else:
|
else:
|
||||||
@@ -497,6 +502,12 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
|||||||
if stop_creep_eps and 135 <= tick < 148:
|
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 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
|
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:
|
if exit_gear and tick == exit_tick - 1:
|
||||||
assert row['cardLatch'] and row['armed'] and row['lat'] and row['permission'] == 1, row
|
assert row['cardLatch'] and row['armed'] and row['lat'] and row['permission'] == 1, row
|
||||||
if exit_transition:
|
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
|
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):
|
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
|
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
|
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:
|
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
|
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:
|
if 165 <= tick < 180:
|
||||||
assert (not command.latActive and not bool(intent and intent.allowedLatch) and
|
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
|
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
|
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,
|
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)
|
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
|
assert not command.latActive and not bool(intent and intent.allowedLatch), row
|
||||||
if rearm_on_brake and 355 <= tick < 365:
|
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)
|
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 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 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
|
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
|
assert command.latActive and row['cardLatch'] and row['permission'] == 1 and not row['controls'], row
|
||||||
if tick >= 440:
|
if tick >= 440:
|
||||||
assert command.latActive and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol), row
|
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})
|
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):
|
def test_actual_crosstrek_paddle_exit_gear(subaru_native_pair, tmp_path, gear, duration, tick):
|
||||||
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
|
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,
|
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})
|
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)
|
CHECKS = (dsu_bypass.configured, pedal_composite.configured, aol.qualified)
|
||||||
|
CACHED_CHECKS = (dsu_bypass._configured, pedal_composite._configured, aol.qualified)
|
||||||
|
|
||||||
|
|
||||||
def params():
|
def params():
|
||||||
@@ -23,23 +24,26 @@ def params():
|
|||||||
return cp
|
return cp
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('check', CHECKS)
|
@pytest.mark.parametrize('check,cached', zip(CHECKS, CACHED_CHECKS, strict=True))
|
||||||
@pytest.mark.parametrize('field,value', [
|
@pytest.mark.parametrize('field,value', [
|
||||||
('brand', 'other'), ('carFingerprint', 'unknown'), ('flags', 0), ('passive', True),
|
('brand', 'other'), ('carFingerprint', 'unknown'), ('flags', 0), ('passive', True),
|
||||||
('dashcamOnly', True), ('notCar', True), ('pcmCruise', False), ('secOcRequired', True),
|
('dashcamOnly', True), ('notCar', True), ('pcmCruise', False), ('secOcRequired', True),
|
||||||
('openpilotLongitudinalControl', False), ('alternativeExperience', 1), ('autoResumeSng', True),
|
('openpilotLongitudinalControl', False), ('alternativeExperience', 1), ('autoResumeSng', True),
|
||||||
('alphaLongitudinalAvailable', True), ('steerControlType', 'angle'), ('carVin', 'changed'),
|
('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()
|
cp = params()
|
||||||
alias = cp.as_reader()
|
alias = cp.as_reader()
|
||||||
assert check(cp)
|
assert check(cp)
|
||||||
before = check.cache_info().misses
|
before = cached.cache_info().misses
|
||||||
assert getattr(cp, field) != value
|
assert getattr(cp, field) != value
|
||||||
setattr(cp, field, value)
|
setattr(cp, field, value)
|
||||||
expected = check.__wrapped__(cp)
|
expected = cached.__wrapped__(cp)
|
||||||
assert check(cp) == check(alias) == expected
|
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)
|
@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
|
from openpilot.starpilot.car.toyota.tests.test_pedal_parent_configurations import sources
|
||||||
|
|
||||||
ROWS = (
|
ROWS = (
|
||||||
(advert_filter.configured, advert_filter, CAR.TOYOTA_RAV4_TSS2, '2FF4', 'catalog'),
|
(advert_filter.configured, advert_filter._configured, advert_filter, CAR.TOYOTA_RAV4_TSS2, '2FF4', 'catalog'),
|
||||||
(rav4h_filter.configured, rav4h_filter, CAR.TOYOTA_RAV4H, '2FF8', 'catalog'),
|
(rav4h_filter.configured, rav4h_filter._configured, rav4h_filter, CAR.TOYOTA_RAV4H, '2FF8', 'catalog'),
|
||||||
(prius_longitudinal.configured, prius_longitudinal, CAR.TOYOTA_PRIUS_RETROFIT, '2FF8', 'EPS73_8965B47070'),
|
(prius_longitudinal.configured, 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_longitudinal.eps73_status_configured, prius_longitudinal._eps73_status_configured, prius_longitudinal,
|
||||||
(prius_advert_filter.configured, prius_advert_filter, CAR.TOYOTA_PRIUS_RETROFIT, '2FF4', 'EPS73_8965B47070'),
|
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('pedal', (False, True))
|
||||||
@pytest.mark.parametrize('stock', (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)
|
fp, fw = sources(identity, topology, rack)
|
||||||
if pedal:
|
if pedal:
|
||||||
fp[0][0x201] = 6
|
fp[0][0x201] = 6
|
||||||
cp = CarInterface.get_params(identity, fp, fw, True, False, False)
|
cp = CarInterface.get_params(identity, fp, fw, True, False, False)
|
||||||
if stock:
|
if stock:
|
||||||
assert (pedal_composite if pedal else owner).prepare_stock(cp)
|
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()
|
alias = cp.as_reader()
|
||||||
assert check(alias)
|
assert check(alias)
|
||||||
for field, value in (
|
for field, value in (
|
||||||
@@ -38,9 +40,9 @@ def test_original_parent_admission_and_mutable_aliases(check, owner, identity, t
|
|||||||
reader = mutated.as_reader()
|
reader = mutated.as_reader()
|
||||||
assert check(mutated)
|
assert check(mutated)
|
||||||
setattr(mutated, field, value)
|
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')):
|
for field, value in (('safetyParam', 0), ('safetyModel', 'noOutput')):
|
||||||
mutated = cp.as_reader().as_builder()
|
mutated = cp.as_reader().as_builder()
|
||||||
assert check(mutated)
|
assert check(mutated)
|
||||||
setattr(mutated.safetyConfigs[0], field, value)
|
setattr(mutated.safetyConfigs[0], field, value)
|
||||||
assert not check(mutated) and not check.__wrapped__(mutated)
|
assert not check(mutated) and not uncached_check(mutated)
|
||||||
|
|||||||
@@ -20,9 +20,10 @@ def lateral_output_inhibited(cp, state):
|
|||||||
|
|
||||||
|
|
||||||
def temporary_restriction(cp, state):
|
def temporary_restriction(cp, state):
|
||||||
|
from openpilot.starpilot.aol.runtime import ordinary_lateral_requested
|
||||||
gears = structs.CarState.GearShifter
|
gears = structs.CarState.GearShifter
|
||||||
return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and
|
return bool(state is not None and state.canValid and not state.canTimeout and not state.steerFaultPermanent and
|
||||||
not state.steerFaultPermanent and (state.steerFaultTemporary or lateral_output_inhibited(cp, state) or
|
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)))
|
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
|
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):
|
now_ns - self.eps_recovery_ns <= SAFETY_MAX_AGE_NS):
|
||||||
kwargs['native_rejection_ns'] = 0
|
kwargs['native_rejection_ns'] = 0
|
||||||
state = structs.CarState(**CS.to_dict())
|
state = CS
|
||||||
events = []
|
events = []
|
||||||
for event in CS.buttonEvents:
|
for event in CS.buttonEvents:
|
||||||
if event.type == ButtonType.mainCruise and self.settings.main_action != AOL_TOGGLE:
|
if event.type == ButtonType.mainCruise and self.settings.main_action != AOL_TOGGLE:
|
||||||
@@ -172,8 +173,11 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
|||||||
else:
|
else:
|
||||||
self.main_neutral = False
|
self.main_neutral = False
|
||||||
self.main_pulse = False
|
self.main_pulse = False
|
||||||
|
if CS.buttonEvents or events:
|
||||||
|
state = structs.CarState(**CS.to_dict())
|
||||||
state.buttonEvents = events
|
state.buttonEvents = events
|
||||||
super().update(state.as_reader(), **kwargs)
|
state = state.as_reader()
|
||||||
|
super().update(state, **kwargs)
|
||||||
if (self.startup_deferred and not self.startup_granted and
|
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
|
(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
|
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.cereal import log
|
||||||
from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan, smooth_value
|
from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan, smooth_value
|
||||||
from openpilot.selfdrive.modeld.constants import ModelConstants
|
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.subaru.smoothing import filter_action
|
||||||
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing, POPV2_SHA256, seconds
|
from openpilot.starpilot.car.volkswagen.model_smoothing import ControlSmoothing, POPV2_SHA256, seconds
|
||||||
from openpilot.starpilot.models.status import ModelLoad, ModelVariant
|
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()
|
cp, load = setup()
|
||||||
previous = log.ModelDataV2.Action(desiredCurvature=0.)
|
previous = log.ModelDataV2.Action(desiredCurvature=0.)
|
||||||
action = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=-.25, shouldStop=True)
|
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,
|
'subaru_smooth_seconds': lambda speed, maximum: 0., 'volkswagen_smoothing': seconds,
|
||||||
'kona_tau': 0., 'LAT_SMOOTH_SECONDS': 0., 'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.2893982231616974)},
|
'kona_tau': 0., 'LAT_SMOOTH_SECONDS': 0., 'sm': {'lateralDelay': SimpleNamespace(lateralDelay=.2893982231616974)},
|
||||||
'action': action, 'prev_action': previous, 'filter_action': filter_action}
|
'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
|
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)]
|
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
|
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/spectra.cc', '4fa26c17f0fb792a4ab6815657beccddee1d641faa2fd02e5aa7393f717a2f3a'),
|
||||||
('openpilot', 'system/camerad/cameras/camera_qcom2.cc', 'b34c24c9984a0ac086f7b961cb7ff09d0501231da50aaad0e676bb3dc3f2edd9'),
|
('openpilot', 'system/camerad/cameras/camera_qcom2.cc', 'b34c24c9984a0ac086f7b961cb7ff09d0501231da50aaad0e676bb3dc3f2edd9'),
|
||||||
('openpilot', 'system/camerad/cameras/camera_common.cc', 'bd9a416a6ee21047b4deec6df04276d8717cd92fe14de43f3e9daff86b62bb8f'),
|
('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/volkswagen/model_smoothing.py', 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540'),
|
||||||
('openpilot', 'starpilot/car/hyundai/model_smoothing.py', '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243'),
|
('openpilot', 'starpilot/car/hyundai/model_smoothing.py', '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243'),
|
||||||
('openpilot', 'selfdrive/modeld/fill_model_msg.py', 'b3916c34d1073d0c26a7a8adc51e7b148f63a1ac68b388226170fd0f8b8b56b4'),
|
('openpilot', 'selfdrive/modeld/fill_model_msg.py', 'b3916c34d1073d0c26a7a8adc51e7b148f63a1ac68b388226170fd0f8b8b56b4'),
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ from openpilot.starpilot.flm import producer_clock_equivalence as clock
|
|||||||
|
|
||||||
APPROVED = {
|
APPROVED = {
|
||||||
'starpilot/car/volkswagen/model_smoothing.py': 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540',
|
'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',
|
'starpilot/car/hyundai/model_smoothing.py': '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243',
|
||||||
'visionipc/visionipc_py.cc': '6c131c4f5eccb9f822f1aaae63733f26b1427c52340b61c9cdaf6cd4aee2f89d',
|
'visionipc/visionipc_py.cc': '6c131c4f5eccb9f822f1aaae63733f26b1427c52340b61c9cdaf6cd4aee2f89d',
|
||||||
'visionipc/visionipc_server.cc': 'a4325a5171eacb931eb271d06a992d2f27216040df113d92099f62cdfa67d81a',
|
'visionipc/visionipc_server.cc': 'a4325a5171eacb931eb271d06a992d2f27216040df113d92099f62cdfa67d81a',
|
||||||
@@ -20,7 +21,7 @@ APPROVED = {
|
|||||||
|
|
||||||
def test_exact_installed_upstream_closure_is_checked_before_contract():
|
def test_exact_installed_upstream_closure_is_checked_before_contract():
|
||||||
contract = clock.pinned_default_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 {relative: expected for _, relative, expected in clock.PRODUCER_SOURCE_HASHES if relative in APPROVED} == APPROVED
|
||||||
assert contract.producer_revision == clock.CLOSURE_SHA256
|
assert contract.producer_revision == clock.CLOSURE_SHA256
|
||||||
assert contract.proof_sha256 == clock.CLOSURE_SHA256
|
assert contract.proof_sha256 == clock.CLOSURE_SHA256
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ MAX_SPEED_MPS = 70.0
|
|||||||
# Route bytes are processed one bounded segment at a time, never concatenated.
|
# 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.
|
# Admit long recordings above the old 256 MiB cap without unbounded offroad work.
|
||||||
MAX_ROUTE_COMPRESSED_BYTES = 1024 * 1024 * 1024
|
MAX_ROUTE_COMPRESSED_BYTES = 1024 * 1024 * 1024
|
||||||
ANALYSIS_VERSION = 7
|
ANALYSIS_VERSION = 8
|
||||||
MAX_MODEL_METADATA_SECONDS = 4.0
|
MAX_MODEL_METADATA_SECONDS = 4.0
|
||||||
DISTRACTED_EVENT = 'driverDistracted2'
|
DISTRACTED_EVENT = 'driverDistracted2'
|
||||||
UNRESPONSIVE_EVENT = 'driverUnresponsive3'
|
UNRESPONSIVE_EVENT = 'driverUnresponsive3'
|
||||||
@@ -362,7 +362,9 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
|
|||||||
car_pairs = state_pairs = 0
|
car_pairs = state_pairs = 0
|
||||||
coverage_gap = False
|
coverage_gap = False
|
||||||
end_of_route = 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 = None
|
||||||
model_outputs = []
|
model_outputs = []
|
||||||
model_loads = []
|
model_loads = []
|
||||||
@@ -385,7 +387,8 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
|
|||||||
try:
|
try:
|
||||||
events = decode_segment(compressed, codec, cancelled=lambda: not allowed(),
|
events = decode_segment(compressed, codec, cancelled=lambda: not allowed(),
|
||||||
retain=frozenset(('clocks', 'initData', 'logMessage', 'modelV2', 'drivingModelData',
|
retain=frozenset(('clocks', 'initData', 'logMessage', 'modelV2', 'drivingModelData',
|
||||||
'carState', 'selfdriveState', 'carControl', 'onroadEvents', 'sentinel')))
|
'carState', 'selfdriveState', 'carControl', 'onroadEvents', 'sentinel',
|
||||||
|
'gpsLocation', 'gpsLocationExternal')))
|
||||||
except LogDecodeCancelled:
|
except LogDecodeCancelled:
|
||||||
raise
|
raise
|
||||||
except LogDecodeError:
|
except LogDecodeError:
|
||||||
@@ -406,12 +409,21 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
|
|||||||
if stamp <= 0 or not event.valid:
|
if stamp <= 0 or not event.valid:
|
||||||
continue
|
continue
|
||||||
if kind == 'clocks':
|
if kind == 'clocks':
|
||||||
wall = int(event.clocks.wallTimeNanos)
|
wall = event.clocks.wallTimeNanos / 1e9
|
||||||
if 946684800 * 1_000_000_000 <= wall <= (datetime.now(UTC).timestamp() + 86400) * 1_000_000_000:
|
if 946684800 <= wall <= latest_wall_time:
|
||||||
offset = (wall - stamp) / 1e9
|
offset = wall - stamp / 1e9
|
||||||
if clocks_offset is not None and abs(offset - clocks_offset) > 5:
|
if clocks_offset is not None and abs(offset - clocks_offset) > 5:
|
||||||
raise _Incomplete('Conflicting logged wall clocks')
|
raise _Incomplete('Conflicting logged wall clocks')
|
||||||
clocks_offset = offset if clocks_offset is None else clocks_offset
|
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:
|
elif kind == 'initData' and model is None:
|
||||||
model = _recorded_model(event.initData)
|
model = _recorded_model(event.initData)
|
||||||
elif kind == 'logMessage':
|
elif kind == 'logMessage':
|
||||||
@@ -497,10 +509,9 @@ def analyze_route(root: Path, route: dict, *, permitted: Callable[[], bool], pre
|
|||||||
if last <= first:
|
if last <= first:
|
||||||
raise _Incomplete('Route has no observed duration')
|
raise _Incomplete('Route has no observed duration')
|
||||||
duration = (last - first) / 1e9
|
duration = (last - first) / 1e9
|
||||||
if clocks_offset is not None:
|
if clocks_offset is None and not gps_conflict:
|
||||||
start_time = first / 1e9 + clocks_offset
|
clocks_offset = gps_offset
|
||||||
else:
|
start_time = first / 1e9 + clocks_offset if clocks_offset is not None else _route_wall_time(route_id)
|
||||||
start_time = _route_wall_time(route_id)
|
|
||||||
if start_time is not None:
|
if start_time is not None:
|
||||||
result['startTime'] = start_time
|
result['startTime'] = start_time
|
||||||
result['endTime'] = start_time + duration
|
result['endTime'] = start_time + duration
|
||||||
|
|||||||
@@ -367,8 +367,13 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
|||||||
with sounds_lock:
|
with sounds_lock:
|
||||||
if sound_source is None:
|
if sound_source is None:
|
||||||
from openpilot.common.params import Params
|
from openpilot.common.params import Params
|
||||||
authority = context_source(Params())
|
from openpilot.starpilot.audio.sound_pack import read_selection
|
||||||
sound_source = SoundDownloads(parked=authority.parked)
|
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_authority = authority
|
||||||
server.sound_source = sound_source
|
server.sound_source = sound_source
|
||||||
return 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/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/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
'/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/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete',
|
||||||
'/api/crash-reports/delete',
|
'/api/crash-reports/delete',
|
||||||
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
|
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
|
||||||
|
|||||||
@@ -45,9 +45,6 @@ DESCRIPTIONS = {
|
|||||||
'LaneCenteringPauseOnSignal': 'Pauses lane-centering correction while a turn signal is on.',
|
'LaneCenteringPauseOnSignal': 'Pauses lane-centering correction while a turn signal is on.',
|
||||||
'LaneCenterOffset': 'Moves the lane-centering target left or right of the detected lane center.',
|
'LaneCenterOffset': 'Moves the lane-centering target left or right of the detected lane center.',
|
||||||
'LaneCenteringE2EAuthority': 'Lets a confident driving-model path reduce lane-centering correction when the model path differs from the lane center.',
|
'LaneCenteringE2EAuthority': 'Lets a confident driving-model path reduce lane-centering correction when the model path differs from the lane center.',
|
||||||
'ParkedClearance': 'Leaves extra room beside parked cars detected by radar. Adds nothing when no parked car is detected.',
|
|
||||||
'ParkedClearanceGap': 'The room to aim for beside a parked car. The car moves left only as far as needed to reach it.',
|
|
||||||
'ParkedClearanceShift': 'The most the car will move left for a parked car, even if the target gap is not reached.',
|
|
||||||
'LaneCenteringStrength': 'Sets the strength of lane-centering correction. 100% is normal; higher values strengthen it.',
|
'LaneCenteringStrength': 'Sets the strength of lane-centering correction. 100% is normal; higher values strengthen it.',
|
||||||
'PauseLateralSpeed': 'Pauses steering assistance below this speed. Zero disables the speed-based pause.',
|
'PauseLateralSpeed': 'Pauses steering assistance below this speed. Zero disables the speed-based pause.',
|
||||||
'PauseLateralOnSignal': 'Limits the low-speed steering pause to times when a turn signal is on.',
|
'PauseLateralOnSignal': 'Limits the low-speed steering pause to times when a turn signal is on.',
|
||||||
@@ -76,10 +73,10 @@ DESCRIPTIONS = {
|
|||||||
'SET uses your current speed when you are above that floor.'),
|
'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.',
|
'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.',
|
'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.',
|
'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. ' +
|
'ConvergeToSetSpeed': ('Helps End to End ease back toward set speed when there is room. Adjust the amount with each personality’s Boost Strength. ' +
|
||||||
'Leads, stops, curve limits and driver overrides retain priority.'),
|
'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. ' +
|
'FasterLeadTakeoff': ('Improves launches from a stop and responds sooner when a lead starts moving. ' +
|
||||||
'Selected acceleration profiles, stop detection and vehicle limits still apply.'),
|
'Selected acceleration profiles, stop detection and vehicle limits still apply.'),
|
||||||
'CustomPersonalities': 'Uses your following-time and jerk settings for the selected driving personality.',
|
'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' },
|
{ 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'] },
|
] : 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'] }]
|
{ 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'] } : {}),
|
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'] } } : {}) } })
|
...(name === 'hub' ? { pageLevels: { aol: [], lane: [], torque: [], 'torque/developer': ['advanced'], lane_change: ['simple', 'advanced'], wheel: ['advanced'] } } : {}) } })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
"StandardPersonalityBoost",
|
"StandardPersonalityBoost",
|
||||||
"RelaxedPersonalityBoost",
|
"RelaxedPersonalityBoost",
|
||||||
"TrafficPersonalityBoost",
|
"TrafficPersonalityBoost",
|
||||||
"ExperimentalSpeedNudge",
|
"ConvergeToSetSpeed",
|
||||||
"FasterLeadTakeoff",
|
"FasterLeadTakeoff",
|
||||||
"ForceAutoTuneOff",
|
"ForceAutoTuneOff",
|
||||||
"ForceStopDistanceOffset",
|
"ForceStopDistanceOffset",
|
||||||
@@ -78,9 +78,6 @@
|
|||||||
"PIPPreviewInvert",
|
"PIPPreviewInvert",
|
||||||
"PIPPreviewShowOnBSM",
|
"PIPPreviewShowOnBSM",
|
||||||
"PIPPreviewShowOnBlinker",
|
"PIPPreviewShowOnBlinker",
|
||||||
"ParkedClearance",
|
|
||||||
"ParkedClearanceGap",
|
|
||||||
"ParkedClearanceShift",
|
|
||||||
"PauseLateralOnSignal",
|
"PauseLateralOnSignal",
|
||||||
"PauseLateralSpeed",
|
"PauseLateralSpeed",
|
||||||
"PromptDistractedVolume",
|
"PromptDistractedVolume",
|
||||||
|
|||||||
@@ -306,11 +306,20 @@ class AuthRuntimeTest(unittest.TestCase):
|
|||||||
finished += 1
|
finished += 1
|
||||||
condition.notify_all()
|
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 = []
|
held = []
|
||||||
with mock.patch.object(self.server.RequestHandlerClass, 'setup', observed_setup), \
|
with mock.patch.object(self.server.RequestHandlerClass, 'setup', observed_setup), \
|
||||||
mock.patch.object(self.server.RequestHandlerClass, 'finish', observed_finish), \
|
mock.patch.object(self.server.RequestHandlerClass, 'finish', observed_finish), \
|
||||||
mock.patch.object(self.server, 'loopback', return_value=False):
|
mock.patch.object(self.server, 'loopback', return_value=False):
|
||||||
try:
|
try:
|
||||||
|
with mock.patch.object(self.server, 'get_request', side_effect=hold_idle_request):
|
||||||
for _ in range(self.server.MAX_CONNECTIONS):
|
for _ in range(self.server.MAX_CONNECTIONS):
|
||||||
assert self.server is not None
|
assert self.server is not None
|
||||||
held.append(socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2))
|
held.append(socket.create_connection(('127.0.0.1', self.server.server_port), timeout=2))
|
||||||
|
|||||||
@@ -31,8 +31,8 @@ def event(kind, stamp, **fields):
|
|||||||
return message
|
return message
|
||||||
|
|
||||||
|
|
||||||
def write(root, number, events, *, lock=False, kind='rlog'):
|
def write(root, number, events, *, lock=False, kind='rlog', route=ROUTE):
|
||||||
name = f'{ROUTE}--{number}'
|
name = f'{route}--{number}'
|
||||||
segment = root / name
|
segment = root / name
|
||||||
segment.mkdir()
|
segment.mkdir()
|
||||||
(segment / f'{kind}.zst').write_bytes(zstd.compress(b''.join(item.as_reader().as_builder().to_bytes() for item in events)))
|
(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):
|
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):
|
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),
|
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')
|
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=[
|
@pytest.fixture(params=[
|
||||||
("LeadApproachBuffer", "Approaching lead buffer", "Off"),
|
("LeadApproachBuffer", "Approaching lead buffer", "Off"),
|
||||||
("FasterLeadTakeoff", "Faster Takeoffs", "Off"),
|
("FasterLeadTakeoff", "Faster Takeoffs", "Off"),
|
||||||
("ExperimentalSpeedNudge", "Speed Nudge in Relaxed", "Off"),
|
("ConvergeToSetSpeed", "Add Extra Boost", "Off"),
|
||||||
("LowSpeedCruiseOnSet", "Low-Speed Cruise Start", "Off"),
|
("LowSpeedCruiseOnSet", "Low-Speed Cruise Start", "Off"),
|
||||||
("DisengageOnAccelerator", "Disengage on Accelerator Pedal", "Off"),
|
("DisengageOnAccelerator", "Disengage on Accelerator Pedal", "Off"),
|
||||||
])
|
])
|
||||||
@@ -32,7 +32,7 @@ def setup(tmp_path, request):
|
|||||||
|
|
||||||
|
|
||||||
def page_row(gateway, label, section=None):
|
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")
|
page = gateway.page(section, "session", b"generation")
|
||||||
index = next(index for index, row in enumerate(page["rows"]) if row["label"] == label)
|
index = next(index for index, row in enumerate(page["rows"]) if row["label"] == label)
|
||||||
return page, index, page["rows"][index]
|
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))
|
intent = gateway.preview(page["view"], index, 0, "session", b"generation", value=str(chosen))
|
||||||
assert gateway.confirm(intent["intent"], "session", b"generation")
|
assert gateway.confirm(intent["intent"], "session", b"generation")
|
||||||
assert params.get(BOOST_KEYS[name]) == chosen
|
assert params.get(BOOST_KEYS[name]) == chosen
|
||||||
_, _, nudge = page_row(gateway, "Speed Nudge in Relaxed")
|
_, _, nudge = page_row(gateway, "Add Extra Boost")
|
||||||
assert nudge["level"] == "advanced" and nudge["value"] == nudge["defaultValue"] == "Off"
|
assert nudge["level"] == "simple" and nudge["value"] == nudge["defaultValue"] == "Off"
|
||||||
assert not viewer.sample(2_000_000_000)
|
assert not viewer.sample(2_000_000_000)
|
||||||
assert viewer.boost_scales == {"relaxed": .65, "standard": 1.5, "aggressive": 2., "traffic": 1.}
|
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")
|
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)
|
assert.equal(layoutModule[name], documentHelpers[name], name)
|
||||||
|
|
||||||
const data = snapshot()
|
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)
|
const restoredCompact = copy(data)
|
||||||
for (const [id, width, height, x, y] of [["max_speed", 162, 162, 0, 0], ["speed_limit", 118, 132, 330, 20]]) {
|
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} })
|
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.request('/api/ui/layout', {'revision': saved['revision'], 'document': saved['document']}, cookie)[0], 409)
|
||||||
self.assertEqual(self.params.get(PARAM_KEY), default_document())
|
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):
|
def test_mutation_requires_origin_session_and_unique_fields(self):
|
||||||
cookie = self.login()
|
cookie = self.login()
|
||||||
_, snapshot, _ = self.request('/api/ui/layout', cookie=cookie)
|
_, snapshot, _ = self.request('/api/ui/layout', cookie=cookie)
|
||||||
|
|||||||
@@ -1312,35 +1312,6 @@ class SettingsGatewayTest(SettingsGatewayFixture):
|
|||||||
self.assertTrue(_onroad_preference("lane", key))
|
self.assertTrue(_onroad_preference("lane", key))
|
||||||
self.assertFalse(_onroad_preference("torque", "reset_profiles"))
|
self.assertFalse(_onroad_preference("torque", "reset_profiles"))
|
||||||
|
|
||||||
def test_parked_clearance_needs_radar_and_master_switch(self):
|
|
||||||
def row(label):
|
|
||||||
page = self.page("lane")
|
|
||||||
index = next(i for i, item in enumerate(page["rows"]) if item["label"] == label)
|
|
||||||
return page, index, page["rows"][index]
|
|
||||||
self.assertFalse(row("Parked car clearance")[2]["available"])
|
|
||||||
cp = SimpleNamespace(**vars(self.context.value.cp), radarUnavailable=False)
|
|
||||||
self.context.value = AuthorityContext(True, cp, b"radar")
|
|
||||||
page, index, toggle = row("Parked car clearance")
|
|
||||||
self.assertTrue(toggle["available"])
|
|
||||||
self.assertEqual(toggle["value"], "Off")
|
|
||||||
self.assertFalse(row("Parked car target gap")[2]["available"])
|
|
||||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value="On")
|
|
||||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
|
||||||
self.assertEqual(Path(self.params.get_param_path("ParkedClearance")).read_bytes(), b"1")
|
|
||||||
page, index, gap = row("Parked car target gap")
|
|
||||||
self.assertTrue(gap["available"])
|
|
||||||
self.assertEqual((gap["value"], gap["minimum"], gap["maximum"], gap["unit"]), ("1.5", 1.0, 2.5, "m"))
|
|
||||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=1.8)
|
|
||||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
|
||||||
self.assertEqual(Path(self.params.get_param_path("ParkedClearanceGap")).read_bytes(), b"1.8")
|
|
||||||
from openpilot.starpilot.lateral.parked_runtime import ParkedSettings, read_settings
|
|
||||||
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8))
|
|
||||||
page, index, shift = row("Parked car max shift")
|
|
||||||
self.assertEqual((shift["value"], shift["minimum"], shift["maximum"], shift["unit"]), ("0.3", 0.1, 0.8, "m"))
|
|
||||||
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=0.45)
|
|
||||||
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
|
|
||||||
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8, 0.45))
|
|
||||||
|
|
||||||
def test_live_lane_rejects_unsupported_vehicle_and_master_dependency(self):
|
def test_live_lane_rejects_unsupported_vehicle_and_master_dependency(self):
|
||||||
self.params.put_bool("LaneCentering", False, block=True)
|
self.params.put_bool("LaneCentering", False, block=True)
|
||||||
tagged, _ = self._live_lane_context()
|
tagged, _ = self._live_lane_context()
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ assert.deepEqual(entries().map(entry => [entry.index, entry.visible]), [[0, true
|
|||||||
assert.equal(state.data.rows, rows)
|
assert.equal(state.data.rows, rows)
|
||||||
assert.equal(rows[1].value, '42')
|
assert.equal(rows[1].value, '42')
|
||||||
// Owners alone classify rows. Names, route prefixes and IDs never imply a level or create links.
|
// 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')
|
assert.equal(settingLevel({ level: 'unknown' }), 'simple')
|
||||||
state.data = { page: 'hub', rows: [{ page: 'lane_change', label: 'Lane Changes' }] }
|
state.data = { page: 'hub', rows: [{ page: 'lane_change', label: 'Lane Changes' }] }
|
||||||
assert.deepEqual(entries().map(entry => entry.row.page), ['lane_change'])
|
assert.deepEqual(entries().map(entry => entry.row.page), ['lane_change'])
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class SoundDownloadsHttpTest(unittest.TestCase):
|
|||||||
}]}))
|
}]}))
|
||||||
parked = [True]
|
parked = [True]
|
||||||
downloads = SoundDownloads(parked=lambda: parked[0], root=root / 'packs', catalog_path=catalog,
|
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 = Params(str(root / 'params'))
|
||||||
params.put('SoundPack', 'stock', block=True)
|
params.put('SoundPack', 'stock', block=True)
|
||||||
context = SimpleNamespace(sample=lambda: AuthorityContext(parked[0], None, None))
|
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'})[0], 409)
|
||||||
self.assertEqual(request('/api/sounds/download', {'pack': 'test', 'url': 'https://unrelated.example'})[0], 400)
|
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)
|
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:
|
finally:
|
||||||
server.shutdown()
|
server.shutdown()
|
||||||
thread.join(timeout=2)
|
thread.join(timeout=2)
|
||||||
|
|||||||
@@ -25,6 +25,25 @@ function fixture() {
|
|||||||
return { feed, requests, states, installed, timers, respond, fire, get unauthorized() { return unauthorized } }
|
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()
|
const normal = fixture()
|
||||||
normal.feed.start()
|
normal.feed.start()
|
||||||
assert.equal(normal.requests[0].url, "./api/sounds")
|
assert.equal(normal.requests[0].url, "./api/sounds")
|
||||||
|
|||||||
@@ -145,11 +145,13 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
|
|||||||
export function validDocument(document, metadata) {
|
export function validDocument(document, metadata) {
|
||||||
if (!object(document)) return false
|
if (!object(document)) return false
|
||||||
const profiles = metadata?.projection === true ? ["large"] : PROFILES
|
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, "speedSources") && typeof document.speedSources !== "boolean") ||
|
||||||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
|
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
|
||||||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
|
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
|
||||||
(Object.hasOwn(document, "clock24Hour") && typeof document.clock24Hour !== "boolean") ||
|
(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, "reduceMotion") && typeof document.reduceMotion !== "boolean") ||
|
||||||
(Object.hasOwn(document, "showMaxSpeed") && typeof document.showMaxSpeed !== "boolean") ||
|
(Object.hasOwn(document, "showMaxSpeed") && typeof document.showMaxSpeed !== "boolean") ||
|
||||||
(Object.hasOwn(document, "speedDisplayOffset") && (!Number.isFinite(document.speedDisplayOffset) || document.speedDisplayOffset < -5 || document.speedDisplayOffset > 5)) ||
|
(Object.hasOwn(document, "speedDisplayOffset") && (!Number.isFinite(document.speedDisplayOffset) || document.speedDisplayOffset < -5 || document.speedDisplayOffset > 5)) ||
|
||||||
|
|||||||
@@ -104,9 +104,17 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
|||||||
</g>
|
</g>
|
||||||
</template>
|
</template>
|
||||||
<rect v-if="!nativeBackdropReady" data-preview-source="scene-border"
|
<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"
|
:x="projection ? profile.bounds.x : borderInset" :y="projection ? profile.bounds.y : borderInset"
|
||||||
:width="state.profile === 'compact' ? 468 : roadBounds.width" :height="state.profile === 'compact' ? 232 : profile.bounds.height"
|
:width="state.profile === 'compact' ? 476 - borderStroke : roadBounds.width + (projection ? 0 : 60 - 2 * borderInset)"
|
||||||
:rx="state.profile === 'compact' ? 14 : 61" fill="none" :stroke="sceneBorder" :stroke-width="state.profile === 'compact' ? 8 : 30" />
|
: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" />
|
<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="!projection && state.showFavoriteZones && state.showEditingAids" aria-hidden="true" pointer-events="none">
|
||||||
<g v-if="state.profile === 'large'">
|
<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">
|
<nav ref="sections" class="gx-layout__switcher gx-layout__sections gx-settings-tabs" :class="{'is-stuck': state.stuck.sections}" aria-label="Editor sections">
|
||||||
<button class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === 'widgets'" :disabled="!!state.drag || !!state.layerDrag" @click="state.inspectorPanel = 'widgets'">Widgets</button>
|
<button class="gx-btn gx-btn--tonal" :aria-pressed="state.inspectorPanel === '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 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" 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>
|
<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>
|
</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>
|
<p v-if="!projection && !colorFields.length" class="gx-note">This widget uses its original status colors.</p>
|
||||||
</div>
|
</div>
|
||||||
</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">
|
<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>
|
<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"
|
<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) })
|
publish: update => Object.assign(state.backdrop, update) })
|
||||||
const artFeed = new LayoutPreviewFeed({ art: true, unauthorized: props.unauthorized, queue,
|
const artFeed = new LayoutPreviewFeed({ art: true, unauthorized: props.unauthorized, queue,
|
||||||
publish: update => Object.assign(state.art, update) })
|
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], () => {
|
!!state.layerDrag, state.data?.revision, state.data?.editable], () => {
|
||||||
if (props.mode !== "local" || !state.data?.editable || !state.draft) {
|
if (props.mode !== "local" || !state.data?.editable || !state.draft) {
|
||||||
artFeed.stop()
|
artFeed.stop()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!artFeed.active) artFeed.start()
|
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)
|
artFeed.update(document, props.projection ? "projection" : state.profile, state.scene, !!state.drag || !!state.layerDrag)
|
||||||
}, {flush: "sync"})
|
}, {flush: "sync"})
|
||||||
// The real screen behind the arrangement: status border, road, alerts and sidebar, without the movable widgets.
|
// 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) }))
|
["Speed limit", scene => scene.id.startsWith("slc_")]].map(([label, test]) => ({ label, scenes: this.availableScenes.filter(test) }))
|
||||||
},
|
},
|
||||||
sceneBorder() { return previewScene(this.state.scene).border },
|
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" },
|
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 },
|
roadBounds() { return this.expandedRoad ? { ...this.profile.bounds, width: this.profile.bounds.width + 300 } : this.profile.bounds },
|
||||||
favoriteZones() {
|
favoriteZones() {
|
||||||
@@ -905,13 +913,19 @@ export const OnroadLayoutPage = {
|
|||||||
this.state.inspectorPanel = "lead"
|
this.state.inspectorPanel = "lead"
|
||||||
this.revealEditPanel()
|
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.
|
// On narrow screens the edit controls always open with their top just under the pinned tabs.
|
||||||
revealEditPanel() {
|
revealEditPanel() {
|
||||||
if (typeof window === "undefined") return
|
if (typeof window === "undefined") return
|
||||||
const align = () => {
|
const align = () => {
|
||||||
const section = this.state.inspectorPanel
|
const section = this.state.inspectorPanel
|
||||||
if (!["edit", "lead"].includes(section)) return
|
if (!["edit", "lead", "border"].includes(section)) return
|
||||||
const tabs = this.$refs.sections, panel = section === "lead" ? this.$refs.leadPanel : this.$refs.editPanel
|
const tabs = this.$refs.sections, panel = this.$refs[section + "Panel"]
|
||||||
if (!tabs || !panel || getComputedStyle(tabs).position !== "sticky") return
|
if (!tabs || !panel || getComputedStyle(tabs).position !== "sticky") return
|
||||||
const gap = panel.getBoundingClientRect().top - tabs.getBoundingClientRect().bottom - 8
|
const gap = panel.getBoundingClientRect().top - tabs.getBoundingClientRect().bottom - 8
|
||||||
if (Math.abs(gap) >= 1) window.scrollBy(0, gap)
|
if (Math.abs(gap) >= 1) window.scrollBy(0, gap)
|
||||||
@@ -1243,6 +1257,16 @@ export const OnroadLayoutPage = {
|
|||||||
this.state.notice = ""
|
this.state.notice = ""
|
||||||
showDraftChange()
|
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) {
|
setReduceMotion(value) {
|
||||||
if (this.state.profile !== 'large' || !this.editable || this.projection || this.state.drag || this.state.layerDrag || typeof value !== 'boolean') return
|
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)
|
const before = clone(this.state.draft)
|
||||||
|
|||||||
@@ -594,7 +594,7 @@ export const SettingsPage = {
|
|||||||
</div></GxCollapse>
|
</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>
|
<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>
|
</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>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</Transition>
|
</Transition>
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import { reactive } from "../vendor/vue/vue.esm-browser.js"
|
|||||||
const RUNNING = new Set(["downloading", "verifying"])
|
const RUNNING = new Set(["downloading", "verifying"])
|
||||||
|
|
||||||
export class SoundPacksFeed {
|
export class SoundPacksFeed {
|
||||||
constructor({ publish, installed = () => {}, unauthorized = () => {},
|
constructor({ publish, installed = () => {}, removed = () => {}, unauthorized = () => {},
|
||||||
fetcher = (...args) => fetch(...args), later = (fn, ms) => setTimeout(fn, ms),
|
fetcher = (...args) => fetch(...args), later = (fn, ms) => setTimeout(fn, ms),
|
||||||
cancelTimer = (id) => clearTimeout(id) }) {
|
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.active = false
|
||||||
this.generation = 0
|
this.generation = 0
|
||||||
this.request = null
|
this.request = null
|
||||||
@@ -88,6 +88,7 @@ export class SoundPacksFeed {
|
|||||||
this.snapshot = payload
|
this.snapshot = payload
|
||||||
this.blocked = false
|
this.blocked = false
|
||||||
this.error = ""
|
this.error = ""
|
||||||
|
if (path === "./api/sounds/delete") this.removed(body.pack)
|
||||||
this.publish({ status: "ready", snapshot: payload, busy: false, error: "" })
|
this.publish({ status: "ready", snapshot: payload, busy: false, error: "" })
|
||||||
if (payload.job?.state === "complete" && payload.job.id != null && !this.seenComplete.has(payload.job.id)) {
|
if (payload.job?.state === "complete" && payload.job.id != null && !this.seenComplete.has(payload.job.id)) {
|
||||||
this.seenComplete.add(payload.job.id)
|
this.seenComplete.add(payload.job.id)
|
||||||
@@ -122,6 +123,13 @@ export class SoundPacksFeed {
|
|||||||
return this.run("./api/sounds/download", { pack })
|
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() {
|
cancel() {
|
||||||
const job = this.snapshot?.job
|
const job = this.snapshot?.job
|
||||||
if (!this.active || this.busy || this.blocked || !this.snapshot?.parked || !RUNNING.has(job?.state) || job.id == null) return
|
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 },
|
components: { GxState, GxIconButton, GxNotice },
|
||||||
props: { unauthorized: { type: Function, required: true }, disabled: { type: Boolean, default: false },
|
props: { unauthorized: { type: Function, required: true }, disabled: { type: Boolean, default: false },
|
||||||
busy: { type: Boolean, default: false } },
|
busy: { type: Boolean, default: false } },
|
||||||
emits: ["installed"],
|
emits: ["installed", "removed"],
|
||||||
setup(props, { emit }) {
|
setup(props, { emit }) {
|
||||||
const state = reactive({ status: "idle", snapshot: null, busy: false, error: "" })
|
const state = reactive({ status: "idle", snapshot: null, busy: false, error: "" })
|
||||||
const feed = new SoundPacksFeed({ publish: (update) => Object.assign(state, update),
|
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 }
|
return { state, feed }
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
@@ -155,13 +163,16 @@ export const SoundPacks = {
|
|||||||
canDownload(pack) { return !this.disabled && !this.state.error && this.state.status === "ready" &&
|
canDownload(pack) { return !this.disabled && !this.state.error && this.state.status === "ready" &&
|
||||||
this.state.snapshot?.parked === true && !this.running && pack.installed === false },
|
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) },
|
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() },
|
cancel() { if (!this.disabled && !this.busy && !this.state.busy) return this.feed.cancel() },
|
||||||
},
|
},
|
||||||
template: `
|
template: `
|
||||||
<section class="gx-card gx-settings__section" aria-label="Sound pack catalog" :inert="busy || state.busy" :aria-busy="busy || state.busy || undefined">
|
<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>
|
<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 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>
|
||||||
<div class="gx-settings__grid gx-panel">
|
<div class="gx-settings__grid gx-panel">
|
||||||
@@ -173,6 +184,8 @@ export const SoundPacks = {
|
|||||||
<strong>{{ pack.name }}</strong>
|
<strong>{{ pack.name }}</strong>
|
||||||
<div class="gx-settings__controls gx-actions">
|
<div class="gx-settings__controls gx-actions">
|
||||||
<span v-if="pack.installed" class="gx-chip">Installed</span>
|
<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)" />
|
<GxIconButton v-else :label="'Download ' + pack.name" icon="bi-download" :disabled="!canDownload(pack)" @click="download(pack)" />
|
||||||
</div>
|
</div>
|
||||||
</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)):
|
not cp.safetyConfigs or any(config.safetyModel in unsafe for config in cp.safetyConfigs)):
|
||||||
return None
|
return None
|
||||||
from opendbc.car.interfaces import CarInterfaceBase
|
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)
|
CarInterfaceBase.configure_torque_tune(prepared.carFingerprint, prepared.lateralTuning)
|
||||||
return prepared if generic_torque_supported(prepared) else None
|
return prepared if generic_torque_supported(prepared) else None
|
||||||
except (AttributeError, TypeError, ValueError, OverflowError, KeyError, NotImplementedError, OSError):
|
except (AttributeError, TypeError, ValueError, OverflowError, KeyError, NotImplementedError, OSError):
|
||||||
@@ -118,7 +118,7 @@ def torque_choice_cp(cp):
|
|||||||
|
|
||||||
|
|
||||||
def prepare_controller(cp, raw):
|
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)
|
selected = selection_from_bytes(cp, raw)
|
||||||
if selected.source != 'invalid' and selected.force_torque and cp.lateralTuning.which() == 'pid':
|
if selected.source != 'invalid' and selected.force_torque and cp.lateralTuning.which() == 'pid':
|
||||||
prepared = torque_choice_cp(cp)
|
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'
|
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:
|
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)
|
policy = policy_for(CP)
|
||||||
use_starpilot = policy is not None and CP.brand != 'ford'
|
use_starpilot = policy is not None and CP.brand != 'ford'
|
||||||
mode = ControllerMode.STARPILOT if use_starpilot else ControllerMode.STANDARD
|
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)
|
document = {'version': DOCUMENT_VERSION, 'vehicles': {}} if raw is None else parse_document(raw)
|
||||||
vehicles = dict(document['vehicles'])
|
vehicles = dict(document['vehicles'])
|
||||||
vehicles[str(CP.carFingerprint)] = {'brand': str(CP.brand), 'mode': mode.value}
|
vehicles[str(CP.carFingerprint)] = {'brand': str(CP.brand), 'mode': mode.value}
|
||||||
if force_torque:
|
if force_torque or (_golf_torque_default(CP) and mode == ControllerMode.STANDARD):
|
||||||
vehicles[str(CP.carFingerprint)]['forceTorque'] = True
|
vehicles[str(CP.carFingerprint)]['forceTorque'] = force_torque
|
||||||
encoded = json.dumps({'version': DOCUMENT_VERSION, 'vehicles': vehicles},
|
encoded = json.dumps({'version': DOCUMENT_VERSION, 'vehicles': vehicles},
|
||||||
sort_keys=True, separators=(',', ':'), allow_nan=False).encode()
|
sort_keys=True, separators=(',', ':'), allow_nan=False).encode()
|
||||||
if len(encoded) > MAX_DOCUMENT_BYTES:
|
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))
|
choice = parse_document(raw)['vehicles'].get(str(CP.carFingerprint))
|
||||||
if choice is None or choice['brand'] != str(CP.brand):
|
if choice is None or choice['brand'] != str(CP.brand):
|
||||||
return default
|
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)
|
force_torque = choice.get('forceTorque', False)
|
||||||
choice_cp = torque_choice_cp(CP) if force_torque else CP
|
choice_cp = torque_choice_cp(CP) if force_torque else CP
|
||||||
policy = policy_for(choice_cp) if choice_cp is not None else None
|
policy = policy_for(choice_cp) if choice_cp is not None else None
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ def supported_cp(CP):
|
|||||||
|
|
||||||
TOYOTA_COROLLA_TSS2_PHASE_SCALE = 0.12
|
TOYOTA_COROLLA_TSS2_PHASE_SCALE = 0.12
|
||||||
TOYOTA_COROLLA_TSS2_TURN_IN_FF_BOOST = 0.035
|
TOYOTA_COROLLA_TSS2_TURN_IN_FF_BOOST = 0.035
|
||||||
TOYOTA_COROLLA_TSS2_UNWIND_FF_REDUCTION = 0.12
|
TOYOTA_COROLLA_TSS2_UNWIND_FF_REDUCTION = 0.06
|
||||||
TOYOTA_COROLLA_TSS2_CURVE_LAT_ONSET = 0.24
|
TOYOTA_COROLLA_TSS2_CURVE_LAT_ONSET = 0.24
|
||||||
TOYOTA_COROLLA_TSS2_CURVE_LAT_WIDTH = 0.1
|
TOYOTA_COROLLA_TSS2_CURVE_LAT_WIDTH = 0.1
|
||||||
TOYOTA_COROLLA_TSS2_SPEED_ONSET = 4.0
|
TOYOTA_COROLLA_TSS2_SPEED_ONSET = 4.0
|
||||||
@@ -69,23 +69,6 @@ TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_LAT = 0.24
|
|||||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_LAT_WIDTH = 0.1
|
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_LAT_WIDTH = 0.1
|
||||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK = 0.25
|
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK = 0.25
|
||||||
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH = 0.1
|
TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH = 0.1
|
||||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_GAIN = 0.5
|
|
||||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT = 0.5
|
|
||||||
TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT_WIDTH = 0.15
|
|
||||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN = 12.0
|
|
||||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_BLEND_TAU = 0.15
|
|
||||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET = 1.5
|
|
||||||
TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET_WIDTH = 0.5
|
|
||||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_SECONDS = 1.5
|
|
||||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_WN = 2.0
|
|
||||||
TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT = 0.3
|
|
||||||
TOYOTA_COROLLA_TSS2_FIRM_PRESS_SECONDS = 0.3
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_RISE_SECONDS = 0.4
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS = 0.2
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_DRIVER_TORQUE_SCALE = 250.0
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RATE = 0.8
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX = 0.4
|
|
||||||
TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RELEASE_SECONDS = 1.0
|
|
||||||
|
|
||||||
|
|
||||||
def get_toyota_corolla_tss2_ff_scale(desired_lateral_accel: float, desired_lateral_jerk: float, v_ego: float) -> float:
|
def get_toyota_corolla_tss2_ff_scale(desired_lateral_accel: float, desired_lateral_jerk: float, v_ego: float) -> float:
|
||||||
@@ -104,17 +87,6 @@ def get_toyota_corolla_tss2_ff_scale(desired_lateral_accel: float, desired_later
|
|||||||
return 1.0 + curve_weight * speed_weight * (boost * turn_in_weight - unwind_reduction * unwind_weight)
|
return 1.0 + curve_weight * speed_weight * (boost * turn_in_weight - unwind_reduction * unwind_weight)
|
||||||
|
|
||||||
|
|
||||||
def get_toyota_corolla_tss2_unwind_weight(desired_lateral_accel: float, desired_lateral_jerk: float, v_ego: float) -> float:
|
|
||||||
if desired_lateral_accel == 0.0:
|
|
||||||
return 0.0
|
|
||||||
phase = math.tanh(desired_lateral_accel * desired_lateral_jerk / TOYOTA_COROLLA_TSS2_PHASE_SCALE)
|
|
||||||
curve_weight = _sigmoid((abs(desired_lateral_accel) - TOYOTA_COROLLA_TSS2_CURVE_LAT_ONSET) / TOYOTA_COROLLA_TSS2_CURVE_LAT_WIDTH)
|
|
||||||
speed_weight = _sigmoid((v_ego - TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET) / TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_SPEED_ONSET_WIDTH) * _sigmoid(
|
|
||||||
(TOYOTA_COROLLA_TSS2_SPEED_CUTOFF - v_ego) / TOYOTA_COROLLA_TSS2_SPEED_CUTOFF_WIDTH
|
|
||||||
)
|
|
||||||
return curve_weight * speed_weight * max(-phase, 0.0)
|
|
||||||
|
|
||||||
|
|
||||||
def get_toyota_corolla_tss2_friction_threshold(v_ego: float, desired_lateral_accel: float = 0.0, desired_lateral_jerk: float = 0.0) -> float:
|
def get_toyota_corolla_tss2_friction_threshold(v_ego: float, desired_lateral_accel: float = 0.0, desired_lateral_jerk: float = 0.0) -> float:
|
||||||
"""Reduce center-only friction chasing on highway-sized model corrections."""
|
"""Reduce center-only friction chasing on highway-sized model corrections."""
|
||||||
speed_weight = _sigmoid(
|
speed_weight = _sigmoid(
|
||||||
@@ -126,12 +98,8 @@ def get_toyota_corolla_tss2_friction_threshold(v_ego: float, desired_lateral_acc
|
|||||||
calm_weight = _sigmoid(
|
calm_weight = _sigmoid(
|
||||||
(TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK - abs(desired_lateral_jerk)) / TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH
|
(TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK - abs(desired_lateral_jerk)) / TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_JERK_WIDTH
|
||||||
)
|
)
|
||||||
curve_weight = _sigmoid(
|
|
||||||
(abs(desired_lateral_accel) - TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT) / TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_LAT_WIDTH
|
|
||||||
)
|
|
||||||
gain = TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_GAIN
|
gain = TOYOTA_COROLLA_TSS2_CENTER_FRICTION_THRESHOLD_GAIN
|
||||||
curve_gain = TOYOTA_COROLLA_TSS2_CURVE_FRICTION_THRESHOLD_GAIN
|
return get_standard_friction_threshold(v_ego) * (1.0 + gain * speed_weight * center_weight * calm_weight)
|
||||||
return get_standard_friction_threshold(v_ego) * (1.0 + gain * speed_weight * center_weight * calm_weight + curve_gain * curve_weight)
|
|
||||||
|
|
||||||
|
|
||||||
def get_toyota_corolla_tss2_center_output_scale(desired_lateral_accel: float, v_ego: float) -> float:
|
def get_toyota_corolla_tss2_center_output_scale(desired_lateral_accel: float, v_ego: float) -> float:
|
||||||
@@ -157,14 +125,6 @@ class CorollaTSS2TorquePolicy:
|
|||||||
self.previous_measurement = 0.0
|
self.previous_measurement = 0.0
|
||||||
self.prev_desired_lateral_accel = 0.0
|
self.prev_desired_lateral_accel = 0.0
|
||||||
self.prev_steering_pressed = False
|
self.prev_steering_pressed = False
|
||||||
self.unwind_target = 0.0
|
|
||||||
self.unwind_target_rate = 0.0
|
|
||||||
self.unwind_blend = FirstOrderFilter(0.0, TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_BLEND_TAU, self.dt)
|
|
||||||
self.release_hold = 0.0
|
|
||||||
self.carry = 0.0
|
|
||||||
self.carry_assist = 0.0
|
|
||||||
self.press_seconds = 0.0
|
|
||||||
self.prev_firm_press = False
|
|
||||||
self.low_speed_reset_threshold = max(CP.minSteerSpeed, 0.3)
|
self.low_speed_reset_threshold = max(CP.minSteerSpeed, 0.3)
|
||||||
|
|
||||||
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
|
||||||
@@ -180,22 +140,12 @@ class CorollaTSS2TorquePolicy:
|
|||||||
self.previous_measurement = measurement
|
self.previous_measurement = measurement
|
||||||
self.measurement_rate_filter.x = 0.0
|
self.measurement_rate_filter.x = 0.0
|
||||||
self.jerk_filter.x = 0.0
|
self.jerk_filter.x = 0.0
|
||||||
self.unwind_target = future_desired_lateral_accel
|
|
||||||
self.unwind_target_rate = 0.0
|
|
||||||
self.unwind_blend.x = 0.0
|
|
||||||
self.release_hold = 0.0
|
|
||||||
self.carry = 0.0
|
|
||||||
self.carry_assist = 0.0
|
|
||||||
self.press_seconds = 0.0
|
|
||||||
self.prev_firm_press = False
|
|
||||||
self.prev_desired_lateral_accel = future_desired_lateral_accel
|
self.prev_desired_lateral_accel = future_desired_lateral_accel
|
||||||
self.prev_steering_pressed = CS.steeringPressed
|
self.prev_steering_pressed = CS.steeringPressed
|
||||||
pid_log.active = False
|
pid_log.active = False
|
||||||
return 0.0, 0.0, pid_log
|
return 0.0, 0.0, pid_log
|
||||||
|
|
||||||
self.press_seconds = self.press_seconds + self.dt if CS.steeringPressed else 0.0
|
if self.prev_steering_pressed and not CS.steeringPressed:
|
||||||
firm_press = self.press_seconds >= TOYOTA_COROLLA_TSS2_FIRM_PRESS_SECONDS
|
|
||||||
if self.prev_firm_press and not firm_press:
|
|
||||||
parent.pid.i *= 0.8
|
parent.pid.i *= 0.8
|
||||||
roll_offset_fade = float(np.interp(CS.vEgo, FF_ROLL_OFFSET_FADE_BP, FF_ROLL_OFFSET_FADE_V))
|
roll_offset_fade = float(np.interp(CS.vEgo, FF_ROLL_OFFSET_FADE_BP, FF_ROLL_OFFSET_FADE_V))
|
||||||
roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY * roll_offset_fade
|
roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY * roll_offset_fade
|
||||||
@@ -211,39 +161,6 @@ class CorollaTSS2TorquePolicy:
|
|||||||
desired_lateral_jerk = float(np.clip(self.jerk_filter.update(raw_lateral_jerk), -MAX_LAT_JERK_UP, MAX_LAT_JERK_UP))
|
desired_lateral_jerk = float(np.clip(self.jerk_filter.update(raw_lateral_jerk), -MAX_LAT_JERK_UP, MAX_LAT_JERK_UP))
|
||||||
gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation
|
gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation
|
||||||
setpoint = expected_lateral_accel + desired_lateral_jerk * lat_delay
|
setpoint = expected_lateral_accel + desired_lateral_jerk * lat_delay
|
||||||
in_turn = abs(measurement) > TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT and CS.vEgo < TOYOTA_COROLLA_TSS2_SPEED_CUTOFF
|
|
||||||
if firm_press and not self.prev_firm_press:
|
|
||||||
self.carry = max(self.carry, self.release_hold)
|
|
||||||
if firm_press and in_turn:
|
|
||||||
self.carry = min(self.carry + self.dt / TOYOTA_COROLLA_TSS2_CARRY_RISE_SECONDS, 1.0)
|
|
||||||
driver = float(np.clip(-float(getattr(CS, 'steeringTorque', 0.0)) / TOYOTA_COROLLA_TSS2_CARRY_DRIVER_TORQUE_SCALE, -1.0, 1.0))
|
|
||||||
if driver * measurement > 0.0:
|
|
||||||
self.carry_assist += TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RATE * driver * self.dt
|
|
||||||
else:
|
|
||||||
self.carry_assist *= 1.0 - self.dt / TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS
|
|
||||||
self.carry_assist = float(np.clip(self.carry_assist, -TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX, TOYOTA_COROLLA_TSS2_CARRY_ASSIST_MAX))
|
|
||||||
else:
|
|
||||||
self.carry = max(self.carry - self.dt / TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS, 0.0)
|
|
||||||
fall = TOYOTA_COROLLA_TSS2_CARRY_FALL_SECONDS if firm_press else TOYOTA_COROLLA_TSS2_CARRY_ASSIST_RELEASE_SECONDS
|
|
||||||
self.carry_assist *= 1.0 - self.dt / fall
|
|
||||||
if firm_press:
|
|
||||||
self.unwind_target = measurement
|
|
||||||
self.unwind_target_rate = 0.0
|
|
||||||
self.release_hold = 0.0
|
|
||||||
elif self.prev_firm_press and abs(measurement) > TOYOTA_COROLLA_TSS2_RELEASE_HOLD_MIN_LAT and CS.vEgo < TOYOTA_COROLLA_TSS2_SPEED_CUTOFF:
|
|
||||||
self.release_hold = 1.0
|
|
||||||
else:
|
|
||||||
self.release_hold = max(self.release_hold - self.dt / TOYOTA_COROLLA_TSS2_RELEASE_HOLD_SECONDS, 0.0)
|
|
||||||
wn = TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN + (TOYOTA_COROLLA_TSS2_RELEASE_HOLD_WN - TOYOTA_COROLLA_TSS2_UNWIND_SMOOTH_WN) * self.release_hold
|
|
||||||
self.unwind_target_rate += (wn * wn * (setpoint - self.unwind_target) - 2.0 * wn * self.unwind_target_rate) * self.dt
|
|
||||||
self.unwind_target += self.unwind_target_rate * self.dt
|
|
||||||
unwind_blend = self.unwind_blend.update(get_toyota_corolla_tss2_unwind_weight(setpoint, desired_lateral_jerk, CS.vEgo))
|
|
||||||
if firm_press:
|
|
||||||
unwind_offset = self.carry * (measurement - setpoint)
|
|
||||||
else:
|
|
||||||
unwind_offset = max(unwind_blend, self.release_hold) * (self.unwind_target - setpoint)
|
|
||||||
setpoint += unwind_offset
|
|
||||||
gravity_adjusted_future_lateral_accel += unwind_offset + self.carry_assist
|
|
||||||
desired_lateral_accel_magnitude_rate = (abs(setpoint) - abs(self.prev_desired_lateral_accel)) / self.dt
|
desired_lateral_accel_magnitude_rate = (abs(setpoint) - abs(self.prev_desired_lateral_accel)) / self.dt
|
||||||
unwind_detected = desired_lateral_accel_magnitude_rate < UNWIND_D_DES_THRESHOLD and abs(setpoint) < UNWIND_LAT_ACCEL_NEAR_ZERO
|
unwind_detected = desired_lateral_accel_magnitude_rate < UNWIND_D_DES_THRESHOLD and abs(setpoint) < UNWIND_LAT_ACCEL_NEAR_ZERO
|
||||||
self.prev_desired_lateral_accel = setpoint
|
self.prev_desired_lateral_accel = setpoint
|
||||||
@@ -283,5 +200,4 @@ class CorollaTSS2TorquePolicy:
|
|||||||
pid_log.desiredLateralJerk = float(desired_lateral_jerk)
|
pid_log.desiredLateralJerk = float(desired_lateral_jerk)
|
||||||
pid_log.saturated = bool(parent._check_saturation(parent.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
|
pid_log.saturated = bool(parent._check_saturation(parent.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
|
||||||
self.prev_steering_pressed = CS.steeringPressed
|
self.prev_steering_pressed = CS.steeringPressed
|
||||||
self.prev_firm_press = firm_press
|
|
||||||
return -output_torque, 0.0, pid_log
|
return -output_torque, 0.0, pid_log
|
||||||
|
|||||||
@@ -180,7 +180,15 @@ class HKGVehicleTorquePolicy(HKGShapedTorquePolicy):
|
|||||||
transition = np.interp(abs(self.jerk_filter.x), (.8, 1.5), (1., 0.))
|
transition = np.interp(abs(self.jerk_filter.x), (.8, 1.5), (1., 0.))
|
||||||
feedback = np.interp(abs(error), (.14, .38), (0., 1.))
|
feedback = np.interp(abs(error), (.14, .38), (0., 1.))
|
||||||
damping += .35 * highway * curve * transition * feedback
|
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)
|
return error * (1.0 - shaping.KIA_CARNIVAL_HEV_CENTER_ERROR_REDUCTION * self.hev_center_weight)
|
||||||
|
|
||||||
def jerk_deadzone(self, setpoint, jerk, measurement, speed):
|
def jerk_deadzone(self, setpoint, jerk, measurement, speed):
|
||||||
|
|||||||
@@ -92,7 +92,6 @@ class LaneCenteringInput:
|
|||||||
time_discontinuity: bool = False
|
time_discontinuity: bool = False
|
||||||
measured_curvature: float | None = None
|
measured_curvature: float | None = None
|
||||||
lateral_delay_s: float | None = None
|
lateral_delay_s: float | None = None
|
||||||
hold: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -408,9 +407,6 @@ class LaneCenteringController:
|
|||||||
if settings.pause_on_signal and observation.turn_signal_active:
|
if settings.pause_on_signal and observation.turn_signal_active:
|
||||||
self._tracker.reset()
|
self._tracker.reset()
|
||||||
return self._fade(base, dt, "signal_release")
|
return self._fade(base, dt, "signal_release")
|
||||||
if observation.hold is True:
|
|
||||||
self._tracker.reset()
|
|
||||||
return self._fade(base, dt, "parked_clearance")
|
|
||||||
self._position_clock += dt
|
self._position_clock += dt
|
||||||
# Filtering runs per control tick, including repeated model samples.
|
# Filtering runs per control tick, including repeated model samples.
|
||||||
geometry = _reader_geometry_key(observation.model)
|
geometry = _reader_geometry_key(observation.model)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ from openpilot.selfdrive.controls.lib.highway_correction_gain import read_gain
|
|||||||
from openpilot.starpilot.lateral.lane_runtime import read_settings
|
from openpilot.starpilot.lateral.lane_runtime import read_settings
|
||||||
from openpilot.starpilot.lateral.lane_centering import LaneCenteringSettings
|
from openpilot.starpilot.lateral.lane_centering import LaneCenteringSettings
|
||||||
from openpilot.starpilot.lateral.lane_change_preferences import read_saved, SavedLaneChange
|
from openpilot.starpilot.lateral.lane_change_preferences import read_saved, SavedLaneChange
|
||||||
from openpilot.starpilot.lateral.parked_runtime import ParkedSettings, read_settings as read_parked
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -15,7 +14,6 @@ class SteeringPreferences:
|
|||||||
highway_gain: float
|
highway_gain: float
|
||||||
lane_centering: LaneCenteringSettings
|
lane_centering: LaneCenteringSettings
|
||||||
lane_change: SavedLaneChange
|
lane_change: SavedLaneChange
|
||||||
parked: ParkedSettings
|
|
||||||
|
|
||||||
|
|
||||||
class LiveSteeringPreferences:
|
class LiveSteeringPreferences:
|
||||||
@@ -28,7 +26,7 @@ class LiveSteeringPreferences:
|
|||||||
self._thread: threading.Thread | None = None
|
self._thread: threading.Thread | None = None
|
||||||
|
|
||||||
def _read(self):
|
def _read(self):
|
||||||
return SteeringPreferences(read_gain(self.params), read_settings(self.params), read_saved(self.params), read_parked(self.params))
|
return SteeringPreferences(read_gain(self.params), read_settings(self.params), read_saved(self.params))
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
if self._thread is None:
|
if self._thread is None:
|
||||||
|
|||||||
@@ -1,182 +0,0 @@
|
|||||||
"""Left shift request beside stationary radar tracks on the right.
|
|
||||||
|
|
||||||
The caller owns freshness, lateral authority and final curvature limiting.
|
|
||||||
This module neither reads settings nor sends commands.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from bisect import bisect_left
|
|
||||||
from dataclasses import dataclass
|
|
||||||
import math
|
|
||||||
|
|
||||||
MIN_SPEED = 4.5
|
|
||||||
MAX_SPEED = 12.5
|
|
||||||
STATIONARY_SPEED = 1.5
|
|
||||||
MIN_DISTANCE = 4.0
|
|
||||||
MAX_DISTANCE = 35.0
|
|
||||||
MIN_LATERAL = 1.5
|
|
||||||
MAX_LATERAL = 4.3
|
|
||||||
TRACK_LATERAL = 6.0
|
|
||||||
CONFIRM_SECONDS = 0.4
|
|
||||||
TRACK_GAP_SECONDS = 0.2
|
|
||||||
HOLD_SECONDS = 0.6
|
|
||||||
LATERAL_TAU = 0.15
|
|
||||||
EGO_HALF_WIDTH = 0.9
|
|
||||||
OBJECT_HALF_WIDTH = 0.9
|
|
||||||
MAX_GAP = 2.5
|
|
||||||
MAX_SHIFT = 0.3
|
|
||||||
MIN_LIMIT = 0.1
|
|
||||||
MAX_LIMIT = 0.8
|
|
||||||
RISE_RATE = 0.4
|
|
||||||
FALL_RATE = 0.15
|
|
||||||
ROOM_FALL_RATE = 1.0
|
|
||||||
ROOM_HOLD_SECONDS = 0.5
|
|
||||||
MIN_LINE_SPACING = 0.9
|
|
||||||
ONCOMING_LINE_SPACING = 1.1
|
|
||||||
MIN_EDGE_SPACING = 1.5
|
|
||||||
LINE_PROB = 0.5
|
|
||||||
LINE_STD = 0.3
|
|
||||||
NO_LINE_PROB = 0.2
|
|
||||||
UNCERTAIN_LINE_MARGIN = 0.5
|
|
||||||
MAX_EDGE_STD = 1.5
|
|
||||||
ONCOMING_SPEED = -2.0
|
|
||||||
ONCOMING_LATERAL = 4.5
|
|
||||||
ONCOMING_DISTANCE = 120.0
|
|
||||||
ROADSIDE_LATERAL = 2.0
|
|
||||||
MAX_ROADSIDE_EDGE_STD = 1.0
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RadarPoint:
|
|
||||||
identifier: int
|
|
||||||
distance: float
|
|
||||||
lateral: float
|
|
||||||
speed: float
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class _Track:
|
|
||||||
age: float
|
|
||||||
unseen: float
|
|
||||||
lateral: float
|
|
||||||
|
|
||||||
|
|
||||||
def path_lateral(path_x, path_y, distance: float, y_rel: float) -> float | None:
|
|
||||||
"""Metres right of the planned path for a radar point with left-positive yRel."""
|
|
||||||
if len(path_x) < 2 or len(path_x) != len(path_y) or not path_x[0] <= distance <= path_x[-1]:
|
|
||||||
return None
|
|
||||||
index = max(1, bisect_left(path_x, distance))
|
|
||||||
span = path_x[index] - path_x[index - 1]
|
|
||||||
if span <= 0:
|
|
||||||
return None
|
|
||||||
ratio = (distance - path_x[index - 1]) / span
|
|
||||||
value = -y_rel - (path_y[index - 1] + ratio * (path_y[index] - path_y[index - 1]))
|
|
||||||
return value if math.isfinite(value) else None
|
|
||||||
|
|
||||||
|
|
||||||
def on_road(lateral: float, edge: float | None, edge_std: float) -> bool:
|
|
||||||
"""Far targets at or beyond a confident right road edge are roadside objects."""
|
|
||||||
if lateral <= ROADSIDE_LATERAL:
|
|
||||||
return True
|
|
||||||
if edge is None or not all(math.isfinite(v) for v in (lateral, edge, edge_std)):
|
|
||||||
return False
|
|
||||||
return edge_std > MAX_ROADSIDE_EDGE_STD or lateral < edge
|
|
||||||
|
|
||||||
|
|
||||||
def oncoming_ahead(points) -> bool:
|
|
||||||
return any(math.isfinite(p.distance) and math.isfinite(p.lateral) and math.isfinite(p.speed) and p.speed < ONCOMING_SPEED and
|
|
||||||
-ONCOMING_LATERAL < p.lateral < 0 and 0 < p.distance < ONCOMING_DISTANCE for p in points)
|
|
||||||
|
|
||||||
|
|
||||||
def left_room(line_spacing: float, line_prob: float, line_std: float, edge_spacing: float, edge_std: float, *, oncoming: bool = False) -> float:
|
|
||||||
"""Metres the path may move left before the left line, or the left edge when no line is seen.
|
|
||||||
|
|
||||||
With oncoming traffic only a confident line grants room, at a wider spacing.
|
|
||||||
"""
|
|
||||||
if not all(math.isfinite(v) for v in (line_spacing, line_prob, line_std, edge_spacing, edge_std)) or line_std < 0 or edge_std < 0:
|
|
||||||
return 0.0
|
|
||||||
edge = edge_spacing - MIN_EDGE_SPACING - 2.0 * edge_std if edge_std <= MAX_EDGE_STD else 0.0
|
|
||||||
confident = line_prob >= LINE_PROB and line_std <= LINE_STD
|
|
||||||
if oncoming:
|
|
||||||
return max(0.0, line_spacing - ONCOMING_LINE_SPACING) if confident else 0.0
|
|
||||||
if line_prob < NO_LINE_PROB:
|
|
||||||
return max(0.0, edge)
|
|
||||||
line = line_spacing - MIN_LINE_SPACING
|
|
||||||
if not confident:
|
|
||||||
line -= min(line_std, UNCERTAIN_LINE_MARGIN)
|
|
||||||
return max(0.0, min(line, edge))
|
|
||||||
return max(0.0, line)
|
|
||||||
|
|
||||||
|
|
||||||
class ParkedClearance:
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self.tracks: dict[int, _Track] = {}
|
|
||||||
self.shift = 0.0
|
|
||||||
self.demand = 0.0
|
|
||||||
self.hold = 0.0
|
|
||||||
self.reason = 'inactive'
|
|
||||||
self.rooms: list[tuple[float, float]] = []
|
|
||||||
|
|
||||||
def reset(self) -> None:
|
|
||||||
self.tracks.clear()
|
|
||||||
self.shift = 0.0
|
|
||||||
self.demand = 0.0
|
|
||||||
self.hold = 0.0
|
|
||||||
self.reason = 'inactive'
|
|
||||||
self.rooms = []
|
|
||||||
|
|
||||||
def _held_room(self, room: float, dt: float) -> float:
|
|
||||||
self.rooms = [(age + dt, value) for age, value in self.rooms if age + dt <= ROOM_HOLD_SECONDS]
|
|
||||||
self.rooms.append((0.0, room))
|
|
||||||
return min(value for _, value in self.rooms)
|
|
||||||
|
|
||||||
def update(self, points, speed: float, dt: float, gap: float, room: float, active: bool, limit: float = MAX_SHIFT, watch: bool = False) -> float:
|
|
||||||
values = (speed, dt, gap, room, limit)
|
|
||||||
if not active or not all(type(v) in (int, float) and math.isfinite(v) for v in values) or dt <= 0 or gap <= 0 or limit <= 0:
|
|
||||||
self.reset()
|
|
||||||
return 0.0
|
|
||||||
gap = min(gap, MAX_GAP)
|
|
||||||
limit = min(limit, MAX_LIMIT)
|
|
||||||
seen = set()
|
|
||||||
for point in points:
|
|
||||||
if not all(math.isfinite(v) for v in (point.distance, point.lateral, point.speed)):
|
|
||||||
continue
|
|
||||||
if (abs(point.speed) > STATIONARY_SPEED or not MIN_DISTANCE <= point.distance <= MAX_DISTANCE or
|
|
||||||
not 0.0 <= point.lateral <= TRACK_LATERAL):
|
|
||||||
continue
|
|
||||||
seen.add(point.identifier)
|
|
||||||
track = self.tracks.get(point.identifier)
|
|
||||||
if track is None:
|
|
||||||
self.tracks[point.identifier] = _Track(0.0, 0.0, point.lateral)
|
|
||||||
continue
|
|
||||||
track.unseen = 0.0
|
|
||||||
track.lateral += (point.lateral - track.lateral) * (1.0 - math.exp(-dt / LATERAL_TAU))
|
|
||||||
track.age = track.age + dt if MIN_LATERAL <= track.lateral <= MAX_LATERAL else 0.0
|
|
||||||
for identifier in [i for i in self.tracks if i not in seen]:
|
|
||||||
self.tracks[identifier].unseen += dt
|
|
||||||
if self.tracks[identifier].unseen > TRACK_GAP_SECONDS:
|
|
||||||
del self.tracks[identifier]
|
|
||||||
if watch:
|
|
||||||
self.shift, self.demand, self.hold, self.reason = 0.0, 0.0, 0.0, 'inactive'
|
|
||||||
return 0.0
|
|
||||||
confirmed = [t.lateral for i, t in self.tracks.items() if i in seen and t.age >= CONFIRM_SECONDS]
|
|
||||||
if not MIN_SPEED <= speed <= MAX_SPEED:
|
|
||||||
self.demand, self.hold, self.reason = 0.0, 0.0, 'speed'
|
|
||||||
elif confirmed:
|
|
||||||
self.demand = max(0.0, gap - (min(confirmed) - EGO_HALF_WIDTH - OBJECT_HALF_WIDTH))
|
|
||||||
self.hold = HOLD_SECONDS
|
|
||||||
self.reason = 'parked'
|
|
||||||
elif self.hold > 0:
|
|
||||||
self.hold = max(0.0, self.hold - dt)
|
|
||||||
self.reason = 'hold'
|
|
||||||
else:
|
|
||||||
self.demand, self.reason = 0.0, 'clear'
|
|
||||||
room = self._held_room(room, dt)
|
|
||||||
cap = min(limit, max(0.0, room)) if self.reason != 'speed' else 0.0
|
|
||||||
target = min(self.demand, cap)
|
|
||||||
if target < self.demand and self.reason == 'parked' and room < min(self.demand, limit):
|
|
||||||
self.reason = 'left_limited'
|
|
||||||
if self.shift > cap:
|
|
||||||
self.shift = max(cap, self.shift - ROOM_FALL_RATE * dt)
|
|
||||||
step = target - self.shift
|
|
||||||
self.shift += min(step, RISE_RATE * dt) if step > 0 else max(step, -FALL_RATE * dt)
|
|
||||||
return self.shift
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
"""Saved parked-clearance preferences and fresh radar, model and car inputs, off by default."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
import math
|
|
||||||
|
|
||||||
from openpilot.cereal import log
|
|
||||||
from openpilot.cereal.services import SERVICE_LIST
|
|
||||||
from openpilot.common.scalar_clip import clip_scalar
|
|
||||||
from openpilot.starpilot.feature_capabilities import lateral_supported
|
|
||||||
from openpilot.starpilot.lateral.parked_clearance import (
|
|
||||||
MAX_GAP, MAX_LIMIT, MAX_SHIFT, MIN_LIMIT, ParkedClearance, RadarPoint, left_room, on_road, oncoming_ahead, path_lateral,
|
|
||||||
)
|
|
||||||
from openpilot.starpilot.saved_source import read_saved
|
|
||||||
|
|
||||||
GAIN = 0.45
|
|
||||||
MAX_CORRECTION = 0.009
|
|
||||||
MAX_LATERAL_ACCEL = 0.7
|
|
||||||
DEFAULT_GAP = 1.5
|
|
||||||
DEFAULT_LIMIT = MAX_SHIFT
|
|
||||||
MAX_RADAR_GAP_S = 0.25
|
|
||||||
MAX_PATH_SLOPE = 0.1
|
|
||||||
MAX_AGE_NS = {'carState': 100_000_000, 'modelV2': 200_000_000, 'radarTracks': 200_000_000}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class ParkedSettings:
|
|
||||||
enabled: bool = False
|
|
||||||
gap: float = DEFAULT_GAP
|
|
||||||
limit: float = DEFAULT_LIMIT
|
|
||||||
|
|
||||||
|
|
||||||
def read_settings(params) -> ParkedSettings:
|
|
||||||
try:
|
|
||||||
enabled, readable = read_saved(params, 'ParkedClearance', 64)
|
|
||||||
gap, gap_readable = read_saved(params, 'ParkedClearanceGap', 64)
|
|
||||||
limit, limit_readable = read_saved(params, 'ParkedClearanceShift', 64)
|
|
||||||
right_hand_drive, side_readable = read_saved(params, 'IsRhdDetected', 8)
|
|
||||||
if (not readable or not gap_readable or not limit_readable or enabled not in (None, b'0', b'1') or
|
|
||||||
not side_readable or right_hand_drive not in (None, b'0')):
|
|
||||||
return ParkedSettings()
|
|
||||||
value = DEFAULT_GAP if gap is None else float(gap)
|
|
||||||
shift = DEFAULT_LIMIT if limit is None else float(limit)
|
|
||||||
if not math.isfinite(value) or not 0 < value <= MAX_GAP or not math.isfinite(shift) or not MIN_LIMIT <= shift <= MAX_LIMIT:
|
|
||||||
return ParkedSettings()
|
|
||||||
return ParkedSettings(enabled == b'1', value, shift)
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return ParkedSettings()
|
|
||||||
|
|
||||||
|
|
||||||
def runtime_supported(CP) -> bool:
|
|
||||||
return bool(lateral_supported(CP) and getattr(CP, 'radarUnavailable', True) is False)
|
|
||||||
|
|
||||||
|
|
||||||
def _at(xs, ys, distance: float) -> float:
|
|
||||||
value = path_lateral(xs, ys, distance, 0.0)
|
|
||||||
if value is None:
|
|
||||||
raise ValueError('Path does not cover distance')
|
|
||||||
return -value
|
|
||||||
|
|
||||||
|
|
||||||
class ParkedClearanceHost:
|
|
||||||
REFRESH_NS = 1_000_000_000
|
|
||||||
REQUIRED = tuple(MAX_AGE_NS)
|
|
||||||
|
|
||||||
def __init__(self, params, *, settings_reader=None):
|
|
||||||
self.params = params
|
|
||||||
self.settings_reader = settings_reader
|
|
||||||
self.settings = ParkedSettings()
|
|
||||||
self.detector = ParkedClearance()
|
|
||||||
self.last_refresh_ns: int | None = None
|
|
||||||
self.last_radar_ns = 0
|
|
||||||
self.correction = 0.0
|
|
||||||
self.shift = 0.0
|
|
||||||
self.reason = 'inactive'
|
|
||||||
|
|
||||||
def _stop(self, reason: str) -> float:
|
|
||||||
self.detector.reset()
|
|
||||||
self.last_radar_ns = 0
|
|
||||||
self.correction = 0.0
|
|
||||||
self.shift = 0.0
|
|
||||||
self.reason = reason
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
def update(self, sm, *, now_ns: int, lateral_active: bool, maneuver: bool) -> float:
|
|
||||||
if self.settings_reader is not None:
|
|
||||||
self.settings = self.settings_reader()
|
|
||||||
elif self.last_refresh_ns is None or not 0 <= now_ns - self.last_refresh_ns < self.REFRESH_NS:
|
|
||||||
self.settings = read_settings(self.params)
|
|
||||||
self.last_refresh_ns = now_ns
|
|
||||||
if not self.settings.enabled:
|
|
||||||
return self._stop('disabled')
|
|
||||||
for name in self.REQUIRED:
|
|
||||||
stamp = int(sm.logMonoTime[name])
|
|
||||||
if not sm.valid[name] or not 0 <= now_ns - stamp <= MAX_AGE_NS[name]:
|
|
||||||
return self._stop(f'{name}_stale')
|
|
||||||
try:
|
|
||||||
car, model, radar = sm['carState'], sm['modelV2'], sm['radarTracks']
|
|
||||||
if not lateral_active or maneuver or not car.canValid or car.canTimeout or any(radar.errors.to_dict().values()):
|
|
||||||
return self._stop('inactive')
|
|
||||||
watch = bool(car.steeringPressed or car.leftBlinker or car.rightBlinker or car.leftBlindspot or
|
|
||||||
model.meta.laneChangeState != log.LaneChangeState.off)
|
|
||||||
speed = float(car.vEgo)
|
|
||||||
if not math.isfinite(speed) or speed <= 0:
|
|
||||||
return self._stop('inactive')
|
|
||||||
lookahead = clip_scalar(speed, 8.0, 35.0)
|
|
||||||
radar_ns = int(sm.logMonoTime['radarTracks'])
|
|
||||||
if radar_ns != self.last_radar_ns:
|
|
||||||
dt = (radar_ns - self.last_radar_ns) / 1e9 if self.last_radar_ns else 1.0 / SERVICE_LIST['radarTracks'].frequency
|
|
||||||
if not 0 < dt <= MAX_RADAR_GAP_S:
|
|
||||||
self.detector.reset()
|
|
||||||
dt = 1.0 / SERVICE_LIST['radarTracks'].frequency
|
|
||||||
self.last_radar_ns = radar_ns
|
|
||||||
xs, ys = list(model.position.x), list(model.position.y)
|
|
||||||
right_edge, right_edge_std = model.roadEdges[1], float(model.roadEdgeStds[1])
|
|
||||||
ex, ey = list(right_edge.x), list(right_edge.y)
|
|
||||||
points, candidates = [], []
|
|
||||||
for point in radar.points:
|
|
||||||
lateral = path_lateral(xs, ys, float(point.dRel), float(point.yRel))
|
|
||||||
if lateral is not None:
|
|
||||||
target = RadarPoint(int(point.trackId), float(point.dRel), lateral, float(point.vRel) + speed)
|
|
||||||
points.append(target)
|
|
||||||
edge = path_lateral(xs, ys, target.distance, 0.0)
|
|
||||||
edge_y = path_lateral(ex, ey, target.distance, 0.0)
|
|
||||||
if on_road(lateral, None if edge is None or edge_y is None else edge - edge_y, right_edge_std):
|
|
||||||
candidates.append(target)
|
|
||||||
center = _at(xs, ys, lookahead)
|
|
||||||
if abs(center) > MAX_PATH_SLOPE * lookahead:
|
|
||||||
return self._stop('curve')
|
|
||||||
line, edge = model.laneLines[1], model.roadEdges[0]
|
|
||||||
room = left_room(center - _at(list(line.x), list(line.y), lookahead), float(model.laneLineProbs[1]), float(model.laneLineStds[1]),
|
|
||||||
center - _at(list(edge.x), list(edge.y), lookahead), float(model.roadEdgeStds[0]), oncoming=oncoming_ahead(points))
|
|
||||||
self.detector.update(candidates, speed, dt, self.settings.gap, room, True, self.settings.limit, watch)
|
|
||||||
self.reason = self.detector.reason
|
|
||||||
elif watch:
|
|
||||||
self.detector.shift, self.detector.demand, self.detector.hold, self.reason = 0.0, 0.0, 0.0, 'inactive'
|
|
||||||
self.correction = clip_scalar(-2.0 * self.detector.shift / lookahead ** 2 * GAIN, -min(MAX_CORRECTION, MAX_LATERAL_ACCEL / speed ** 2), 0.0)
|
|
||||||
self.shift = float(self.detector.shift)
|
|
||||||
return self.correction
|
|
||||||
except (AttributeError, IndexError, TypeError, ValueError, OverflowError):
|
|
||||||
return self._stop('invalid')
|
|
||||||
@@ -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'))
|
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'),
|
@pytest.mark.parametrize('field,value', [('steerControlType', 'angle'), ('steerControlType', 'curvature'),
|
||||||
('brand', 'toyota'), ('notCar', True), ('passive', True), ('dashcamOnly', True), ('carFingerprint', 'UNKNOWN')])
|
('brand', 'toyota'), ('notCar', True), ('passive', True), ('dashcamOnly', True), ('carFingerprint', 'UNKNOWN')])
|
||||||
def test_forced_choice_refuses_unsupported_configuration(field, value):
|
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
|
assert original.to_dict() == before, identity
|
||||||
supported.append(identity)
|
supported.append(identity)
|
||||||
assert set(PID_CARS).issubset(supported)
|
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
|
policy = controller.starpilot_extension.policy
|
||||||
for direction in (-1., 1.):
|
for direction in (-1., 1.):
|
||||||
assert math.isclose(policy.pid_error_context(direction, direction * .5, 13.), direction * .55)
|
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
|
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)
|
assert math.isclose(policy.pid_error_context(1., demand, speed), base_scale)
|
||||||
policy.jerk_filter.x = -1.0
|
policy.jerk_filter.x = -1.0
|
||||||
assert math.isclose(policy.pid_error_context(1., .5, 13.), .85)
|
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)
|
_, controller = controller_for(CAR.HYUNDAI_TUCSON_4TH_GEN, ControllerMode.STARPILOT)
|
||||||
policy = controller.starpilot_extension.policy
|
policy = controller.starpilot_extension.policy
|
||||||
for side in (-1., 1.):
|
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 * .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 * 1.7, 25.) == side * .5
|
||||||
assert policy.pid_error_context(side * .5, side * .8, 31.) == 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)
|
setattr(policy, pressed, True)
|
||||||
assert scale(22., .7, .52) == scale(22., .7, .0)
|
assert scale(22., .7, .52) == scale(22., .7, .0)
|
||||||
setattr(policy, pressed, False)
|
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)
|
||||||
|
|||||||
@@ -1,193 +0,0 @@
|
|||||||
import math
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
from openpilot.starpilot.lateral import parked_clearance as pc
|
|
||||||
from openpilot.starpilot.lateral.parked_clearance import ParkedClearance, RadarPoint
|
|
||||||
|
|
||||||
DT = 0.05
|
|
||||||
|
|
||||||
|
|
||||||
def run(detector, points, seconds, *, speed=11.0, gap=1.0, room=0.6, active=True):
|
|
||||||
shift = detector.shift
|
|
||||||
for _ in range(round(seconds / DT)):
|
|
||||||
shift = detector.update(points, speed, DT, gap, room, active)
|
|
||||||
return shift
|
|
||||||
|
|
||||||
|
|
||||||
def run_limit(points, limit):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
shift = 0.0
|
|
||||||
for _ in range(round(4.0 / DT)):
|
|
||||||
shift = detector.update(points, 11.0, DT, 2.0, 1.0, True, limit)
|
|
||||||
return shift
|
|
||||||
|
|
||||||
|
|
||||||
class TestParkedClearance(unittest.TestCase):
|
|
||||||
def test_clear_road_adds_nothing(self):
|
|
||||||
self.assertEqual(run(ParkedClearance(), [], 5.0), 0.0)
|
|
||||||
|
|
||||||
def test_parked_car_shifts_left_within_cap(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
shift = run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0)
|
|
||||||
self.assertAlmostEqual(shift, pc.MAX_SHIFT)
|
|
||||||
self.assertEqual(detector.reason, 'parked')
|
|
||||||
|
|
||||||
def test_shift_matches_missing_gap(self):
|
|
||||||
shift = run(ParkedClearance(), [RadarPoint(1, 20.0, 2.7, 0.0)], 3.0)
|
|
||||||
self.assertAlmostEqual(shift, 0.1)
|
|
||||||
|
|
||||||
def test_enough_gap_adds_nothing(self):
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 3.0, 0.0)], 3.0), 0.0)
|
|
||||||
|
|
||||||
def test_brief_track_ignored(self):
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], pc.CONFIRM_SECONDS - DT), 0.0)
|
|
||||||
|
|
||||||
def test_noisy_far_object_never_confirms(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
for index in range(100):
|
|
||||||
detector.update([RadarPoint(1, 20.0, 2.8 if index % 4 == 0 else 4.4, 0.0)], 11.0, DT, 1.5, 0.6, True)
|
|
||||||
self.assertEqual(detector.shift, 0.0)
|
|
||||||
|
|
||||||
def test_close_roadside_target_and_high_speed_ignored(self):
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 1.3, 0.0)], 3.0), 0.0)
|
|
||||||
detector = ParkedClearance()
|
|
||||||
self.assertEqual(run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, speed=13.0), 0.0)
|
|
||||||
self.assertEqual(detector.reason, 'speed')
|
|
||||||
|
|
||||||
def test_turning_speeds_add_nothing(self):
|
|
||||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
|
||||||
self.assertEqual(run(ParkedClearance(), point, 3.0, speed=4.0), 0.0)
|
|
||||||
detector = ParkedClearance()
|
|
||||||
self.assertGreater(run(detector, point, 3.0, speed=5.0), 0.0)
|
|
||||||
run(detector, point, 0.35, speed=4.0)
|
|
||||||
self.assertEqual(detector.shift, 0.0)
|
|
||||||
|
|
||||||
def test_shift_follows_room_drop_quickly(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
|
||||||
self.assertAlmostEqual(run(detector, point, 3.0, room=0.6), 0.3)
|
|
||||||
run(detector, point, 0.25, room=0.05)
|
|
||||||
self.assertLessEqual(detector.shift, 0.05 + 1e-9)
|
|
||||||
|
|
||||||
def test_release_after_passing_stays_gentle(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.6)
|
|
||||||
run(detector, [], pc.HOLD_SECONDS + pc.TRACK_GAP_SECONDS + DT)
|
|
||||||
before = detector.shift
|
|
||||||
run(detector, [], 1.0)
|
|
||||||
self.assertAlmostEqual(before - detector.shift, pc.FALL_RATE * 1.0, places=6)
|
|
||||||
|
|
||||||
def test_flickering_room_keeps_the_smaller_value(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
|
||||||
for i in range(round(3.0 / DT)):
|
|
||||||
detector.update(point, 11.0, DT, 1.0, 0.6 if i % 2 else 0.1, True)
|
|
||||||
self.assertLessEqual(detector.shift, 0.1 + 1e-9)
|
|
||||||
self.assertAlmostEqual(detector.shift, 0.1)
|
|
||||||
|
|
||||||
def test_on_road(self):
|
|
||||||
self.assertTrue(pc.on_road(2.6, 3.4, 0.4))
|
|
||||||
self.assertFalse(pc.on_road(3.0, 2.5, 0.3))
|
|
||||||
self.assertTrue(pc.on_road(1.8, 1.0, 0.3))
|
|
||||||
self.assertTrue(pc.on_road(3.0, 2.5, 1.4))
|
|
||||||
self.assertFalse(pc.on_road(3.0, None, 0.3))
|
|
||||||
self.assertFalse(pc.on_road(3.0, math.nan, 0.3))
|
|
||||||
|
|
||||||
def test_far_lateral_and_moving_ignored(self):
|
|
||||||
points = [RadarPoint(1, 20.0, 4.0, 0.0), RadarPoint(2, 20.0, 2.3, 8.0), RadarPoint(3, 20.0, -2.3, 0.0), RadarPoint(4, 40.0, 2.3, 0.0)]
|
|
||||||
self.assertEqual(run(ParkedClearance(), points, 3.0), 0.0)
|
|
||||||
|
|
||||||
def test_left_room_limits_shift(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
self.assertAlmostEqual(run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.1), 0.1)
|
|
||||||
self.assertEqual(detector.reason, 'left_limited')
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, room=0.0), 0.0)
|
|
||||||
|
|
||||||
def test_oncoming_detection(self):
|
|
||||||
self.assertTrue(pc.oncoming_ahead([RadarPoint(2, 100.0, -2.5, -10.0)]))
|
|
||||||
for point in (RadarPoint(2, 130.0, -2.5, -10.0), RadarPoint(2, 50.0, 2.5, -10.0), RadarPoint(2, 50.0, -2.5, 0.0), RadarPoint(2, 50.0, -6.0, -10.0)):
|
|
||||||
self.assertFalse(pc.oncoming_ahead([point]))
|
|
||||||
|
|
||||||
def test_speed_window(self):
|
|
||||||
for speed in (pc.MIN_SPEED - 0.1, pc.MAX_SPEED + 0.1):
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0, speed=speed), 0.0)
|
|
||||||
|
|
||||||
def test_rate_limited_rise_hold_and_release(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
previous = 0.0
|
|
||||||
for _ in range(60):
|
|
||||||
shift = detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], 11.0, DT, 1.0, 0.6, True)
|
|
||||||
self.assertLessEqual(shift - previous, pc.RISE_RATE * DT + 1e-9)
|
|
||||||
previous = shift
|
|
||||||
held = run(detector, [], pc.HOLD_SECONDS - DT)
|
|
||||||
self.assertAlmostEqual(held, pc.MAX_SHIFT)
|
|
||||||
for _ in range(100):
|
|
||||||
shift = detector.update([], 11.0, DT, 1.0, 0.6, True)
|
|
||||||
self.assertLessEqual(previous - shift, pc.FALL_RATE * DT + 1e-9)
|
|
||||||
previous = shift
|
|
||||||
self.assertEqual(shift, 0.0)
|
|
||||||
|
|
||||||
def test_inactive_resets_immediately(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
run(detector, [RadarPoint(1, 20.0, 2.3, 0.0)], 3.0)
|
|
||||||
self.assertEqual(detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], 11.0, DT, 1.0, 0.6, False), 0.0)
|
|
||||||
self.assertEqual(detector.tracks, {})
|
|
||||||
|
|
||||||
def test_watch_tracks_without_shift(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
points = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
|
||||||
for _ in range(round(1.0 / DT)):
|
|
||||||
self.assertEqual(detector.update(points, 11.0, DT, 1.0, 0.6, True, pc.MAX_SHIFT, True), 0.0)
|
|
||||||
self.assertEqual(detector.reason, 'inactive')
|
|
||||||
self.assertGreater(detector.update(points, 11.0, DT, 1.0, 0.6, True), 0.0)
|
|
||||||
self.assertEqual(detector.reason, 'parked')
|
|
||||||
self.assertEqual(detector.update(points, 11.0, DT, 1.0, 0.6, True, pc.MAX_SHIFT, True), 0.0)
|
|
||||||
|
|
||||||
def test_invalid_inputs_add_nothing(self):
|
|
||||||
for speed, dt, gap, room in ((math.nan, DT, 1.0, 0.6), (11.0, 0.0, 1.0, 0.6), (11.0, DT, 0.0, 0.6), (11.0, DT, 1.0, math.inf)):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
for _ in range(60):
|
|
||||||
self.assertEqual(detector.update([RadarPoint(1, 20.0, 2.3, 0.0)], speed, dt, gap, room, True), 0.0)
|
|
||||||
self.assertEqual(run(ParkedClearance(), [RadarPoint(1, math.nan, 2.3, 0.0)], 3.0), 0.0)
|
|
||||||
|
|
||||||
def test_wide_gap_reaches_far_curb_cars(self):
|
|
||||||
point = [RadarPoint(1, 20.0, 3.5, 0.0)]
|
|
||||||
self.assertAlmostEqual(run(ParkedClearance(), point, 3.0, gap=2.0, room=0.6), 0.3)
|
|
||||||
self.assertEqual(run(ParkedClearance(), point, 3.0, gap=1.5, room=0.6), 0.0)
|
|
||||||
|
|
||||||
def test_gap_setting_capped(self):
|
|
||||||
detector = ParkedClearance()
|
|
||||||
run(detector, [RadarPoint(1, 20.0, 3.2, 0.0)], 3.0, gap=5.0)
|
|
||||||
self.assertAlmostEqual(detector.demand, pc.MAX_GAP - 1.4)
|
|
||||||
|
|
||||||
def test_limit_setting_caps_shift(self):
|
|
||||||
point = [RadarPoint(1, 20.0, 2.3, 0.0)]
|
|
||||||
self.assertAlmostEqual(run_limit(point, 0.1), 0.1)
|
|
||||||
self.assertAlmostEqual(run_limit(point, 0.5), 0.5)
|
|
||||||
self.assertAlmostEqual(run_limit(point, 0.8), 0.8)
|
|
||||||
self.assertAlmostEqual(run_limit(point, 9.0), 0.8)
|
|
||||||
for bad in (0.0, -0.2, math.nan):
|
|
||||||
self.assertEqual(run_limit(point, bad), 0.0)
|
|
||||||
|
|
||||||
def test_path_lateral(self):
|
|
||||||
self.assertAlmostEqual(pc.path_lateral([0.0, 10.0, 20.0], [0.0, 0.5, 1.0], 15.0, -3.0), 2.25)
|
|
||||||
self.assertIsNone(pc.path_lateral([0.0, 10.0], [0.0, 0.5], 15.0, -3.0))
|
|
||||||
self.assertIsNone(pc.path_lateral([0.0], [0.0], 0.0, -3.0))
|
|
||||||
|
|
||||||
def test_left_room(self):
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.1, 6.0, 0.8), 0.7)
|
|
||||||
self.assertEqual(pc.left_room(0.8, 0.9, 0.1, 6.0, 0.2), 0.0)
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 0.7), 2.5)
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 1.2), 1.5)
|
|
||||||
self.assertEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 1.6), 0.0)
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 0.5), 0.5)
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.9, 6.0, 0.5), 0.2)
|
|
||||||
self.assertEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 1.6), 0.0)
|
|
||||||
self.assertEqual(pc.left_room(math.nan, 0.9, 0.1, 6.0, 0.2), 0.0)
|
|
||||||
self.assertAlmostEqual(pc.left_room(1.6, 0.9, 0.1, 6.0, 0.8, oncoming=True), 0.5)
|
|
||||||
self.assertEqual(pc.left_room(1.6, 0.05, 1.4, 5.4, 0.7, oncoming=True), 0.0)
|
|
||||||
self.assertEqual(pc.left_room(1.6, 0.4, 0.2, 6.0, 0.5, oncoming=True), 0.0)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
import math
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from opendbc.car.structs import car
|
|
||||||
from openpilot.cereal import log
|
|
||||||
from openpilot.starpilot.lateral import parked_runtime as runtime
|
|
||||||
from openpilot.starpilot.lateral.parked_runtime import ParkedClearanceHost, ParkedSettings, read_settings
|
|
||||||
from openpilot.starpilot.lateral.lane_centering import LaneCenteringController, RELEASE_TAU
|
|
||||||
from openpilot.starpilot.lateral.tests.test_lane_centering import model as lane_model, observation as lane_observation, settled
|
|
||||||
|
|
||||||
STEP_NS = 50_000_000
|
|
||||||
|
|
||||||
|
|
||||||
class Bus:
|
|
||||||
def __init__(self):
|
|
||||||
self.data = {}
|
|
||||||
self.logMonoTime = {}
|
|
||||||
self.valid = {}
|
|
||||||
|
|
||||||
def __getitem__(self, name):
|
|
||||||
return self.data[name]
|
|
||||||
|
|
||||||
def put(self, name, message, stamp, valid=True):
|
|
||||||
self.data[name], self.logMonoTime[name], self.valid[name] = message, stamp, valid
|
|
||||||
|
|
||||||
|
|
||||||
def model_message(left_line=-1.7, line_prob=0.9, right_edge=6.0, edge_std=0.3):
|
|
||||||
model = log.ModelDataV2.new_message()
|
|
||||||
xs = [float(x) for x in range(0, 100, 3)]
|
|
||||||
model.position.x, model.position.y = xs, [0.0] * len(xs)
|
|
||||||
lines = model.init('laneLines', 4)
|
|
||||||
for line, y in zip(lines, (-5.0, left_line, 1.7, 5.0), strict=True):
|
|
||||||
line.x, line.y = xs, [y] * len(xs)
|
|
||||||
model.laneLineProbs, model.laneLineStds = [0.9, line_prob, 0.9, 0.9], [0.1] * 4
|
|
||||||
edges = model.init('roadEdges', 2)
|
|
||||||
for edge, y in zip(edges, (-6.0, right_edge), strict=True):
|
|
||||||
edge.x, edge.y = xs, [y] * len(xs)
|
|
||||||
model.roadEdgeStds = [0.3, edge_std]
|
|
||||||
return model.as_reader()
|
|
||||||
|
|
||||||
|
|
||||||
def radar_message(points):
|
|
||||||
radar = car.RadarData.new_message()
|
|
||||||
built = radar.init('points', len(points))
|
|
||||||
for target, (identifier, distance, y_rel, v_rel) in zip(built, points, strict=True):
|
|
||||||
target.trackId, target.dRel, target.yRel, target.vRel = identifier, distance, y_rel, v_rel
|
|
||||||
return radar.as_reader()
|
|
||||||
|
|
||||||
|
|
||||||
def car_message(speed=11.0, **fields):
|
|
||||||
state = car.CarState.new_message(vEgo=speed, canValid=True, **fields)
|
|
||||||
return state.as_reader()
|
|
||||||
|
|
||||||
|
|
||||||
def drive(host, seconds, points, *, speed=11.0, model=None, active=True, maneuver=False, start=1_000_000_000, **fields):
|
|
||||||
bus = Bus()
|
|
||||||
model = model_message() if model is None else model
|
|
||||||
correction = 0.0
|
|
||||||
for index in range(round(seconds / 0.05)):
|
|
||||||
now = start + index * STEP_NS
|
|
||||||
bus.put('carState', car_message(speed, **fields), now)
|
|
||||||
bus.put('modelV2', model, now)
|
|
||||||
bus.put('radarTracks', radar_message(points), now)
|
|
||||||
correction = host.update(bus, now_ns=now, lateral_active=active, maneuver=maneuver)
|
|
||||||
return correction, bus, start + round(seconds / 0.05) * STEP_NS
|
|
||||||
|
|
||||||
|
|
||||||
def host(enabled=True, gap=1.5, limit=runtime.DEFAULT_LIMIT):
|
|
||||||
return ParkedClearanceHost(None, settings_reader=lambda: ParkedSettings(enabled, gap, limit))
|
|
||||||
|
|
||||||
|
|
||||||
PARKED = [(7, 20.0, -2.6, -11.0)]
|
|
||||||
|
|
||||||
|
|
||||||
class TestParkedRuntime(unittest.TestCase):
|
|
||||||
def test_disabled_by_default_adds_nothing(self):
|
|
||||||
self.assertEqual(ParkedSettings().enabled, False)
|
|
||||||
self.assertEqual(drive(host(enabled=False), 3.0, PARKED)[0], 0.0)
|
|
||||||
|
|
||||||
def test_parked_car_steers_left_within_cap(self):
|
|
||||||
subject = host()
|
|
||||||
correction = drive(subject, 4.0, PARKED)[0]
|
|
||||||
self.assertAlmostEqual(correction, -2.0 * 0.3 / 11.0 ** 2 * runtime.GAIN, places=9)
|
|
||||||
self.assertLessEqual(-correction, min(runtime.MAX_CORRECTION, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2))
|
|
||||||
self.assertEqual(subject.reason, 'parked')
|
|
||||||
subject = host(gap=1.4)
|
|
||||||
correction = drive(subject, 4.0, [(7, 20.0, -3.1, -11.0)])[0]
|
|
||||||
self.assertAlmostEqual(subject.detector.shift, 0.1, places=5)
|
|
||||||
self.assertAlmostEqual(correction, -2.0 * 0.1 / 11.0 ** 2 * runtime.GAIN, places=7)
|
|
||||||
|
|
||||||
def test_limit_setting_scales_cap(self):
|
|
||||||
small, large = host(limit=0.1), host(gap=2.0, limit=0.5)
|
|
||||||
self.assertAlmostEqual(drive(small, 4.0, PARKED)[0], -2.0 * 0.1 / 11.0 ** 2 * runtime.GAIN, places=7)
|
|
||||||
self.assertAlmostEqual(small.shift, 0.1, places=5)
|
|
||||||
wide = model_message(line_prob=0.05)
|
|
||||||
correction = drive(large, 6.0, PARKED, model=wide)[0]
|
|
||||||
self.assertAlmostEqual(correction, -2.0 * 0.5 / 11.0 ** 2 * runtime.GAIN, places=9)
|
|
||||||
self.assertLessEqual(-correction, min(runtime.MAX_CORRECTION, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2))
|
|
||||||
self.assertLessEqual(large.shift, 0.5)
|
|
||||||
|
|
||||||
def test_city_speed_shift_is_not_clipped(self):
|
|
||||||
subject = host(gap=2.0, limit=0.5)
|
|
||||||
correction = drive(subject, 6.0, [(7, 20.0, -2.6, -9.0)], speed=9.0, model=model_message(line_prob=0.05))[0]
|
|
||||||
self.assertAlmostEqual(subject.shift, 0.5, places=5)
|
|
||||||
self.assertAlmostEqual(correction, -0.9 * 0.5 / 81.0, places=9)
|
|
||||||
|
|
||||||
def test_lateral_accel_stays_bounded_at_speed(self):
|
|
||||||
subject = host(gap=2.0, limit=0.5)
|
|
||||||
start = 1_000_000_000
|
|
||||||
for _ in range(12):
|
|
||||||
correction, _, start = drive(subject, 0.5, [(7, 20.0, -2.6, -12.5)], speed=12.5, model=model_message(line_prob=0.05), start=start)
|
|
||||||
self.assertLessEqual(-correction * 12.5 ** 2, runtime.MAX_LATERAL_ACCEL + 1e-12)
|
|
||||||
self.assertLess(correction, 0.0)
|
|
||||||
|
|
||||||
def test_oncoming_mid_shift_pulls_back(self):
|
|
||||||
subject = host()
|
|
||||||
narrow = model_message(left_line=-1.3)
|
|
||||||
_, _, now = drive(subject, 4.0, PARKED, model=narrow)
|
|
||||||
self.assertAlmostEqual(subject.shift, 0.3, places=5)
|
|
||||||
drive(subject, 0.3, PARKED + [(9, 90.0, 2.5, -22.0)], model=narrow, start=now)
|
|
||||||
self.assertLessEqual(subject.shift, 0.2 + 1e-6)
|
|
||||||
|
|
||||||
def test_wide_gap_reaches_far_curb_car(self):
|
|
||||||
wide = host(gap=2.5, limit=0.8)
|
|
||||||
self.assertLess(drive(wide, 4.0, [(7, 20.0, -4.0, -11.0)])[0], 0.0)
|
|
||||||
self.assertGreater(wide.shift, 0.25)
|
|
||||||
self.assertEqual(drive(host(gap=1.5), 4.0, [(7, 20.0, -4.0, -11.0)])[0], 0.0)
|
|
||||||
|
|
||||||
def test_large_limit_is_capped_by_lateral_accel(self):
|
|
||||||
subject = host(gap=2.5, limit=0.8)
|
|
||||||
correction = drive(subject, 6.0, [(7, 20.0, -2.6, -11.0)], model=model_message(line_prob=0.05))[0]
|
|
||||||
self.assertAlmostEqual(subject.shift, 0.8, places=5)
|
|
||||||
self.assertAlmostEqual(correction, -min(2.0 * 0.8 / 11.0 ** 2 * runtime.GAIN, runtime.MAX_LATERAL_ACCEL / 11.0 ** 2), places=9)
|
|
||||||
|
|
||||||
def test_roadside_objects_are_ignored(self):
|
|
||||||
self.assertEqual(drive(host(), 4.0, PARKED, model=model_message(right_edge=2.2))[0], 0.0)
|
|
||||||
self.assertLess(drive(host(), 4.0, PARKED, model=model_message(right_edge=2.2, edge_std=1.4))[0], 0.0)
|
|
||||||
self.assertLess(drive(host(), 4.0, [(7, 20.0, -1.8, -11.0)], model=model_message(right_edge=1.0))[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 4.0, [(7, 20.0, -1.3, -11.0)])[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 4.0, [(7, 20.0, -2.6, -13.0)], speed=13.0)[0], 0.0)
|
|
||||||
|
|
||||||
def test_clear_road_and_far_objects_add_nothing(self):
|
|
||||||
self.assertEqual(drive(host(), 3.0, [])[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 3.0, [(7, 20.0, -4.5, -11.0), (8, 20.0, 2.6, -11.0), (9, 20.0, -2.6, 0.0)])[0], 0.0)
|
|
||||||
|
|
||||||
def test_no_left_room_adds_nothing(self):
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, model=model_message(left_line=-0.9))[0], 0.0)
|
|
||||||
|
|
||||||
def test_oncoming_keeps_wider_line_spacing(self):
|
|
||||||
oncoming = PARKED + [(9, 90.0, 2.5, -22.0)]
|
|
||||||
self.assertLess(drive(host(), 4.0, oncoming)[0], 0.0)
|
|
||||||
narrow = model_message(left_line=-1.05)
|
|
||||||
self.assertLess(drive(host(), 4.0, PARKED, model=narrow)[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 4.0, oncoming, model=narrow)[0], 0.0)
|
|
||||||
unmarked = model_message(line_prob=0.05)
|
|
||||||
self.assertLess(drive(host(), 4.0, PARKED, model=unmarked)[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 4.0, oncoming, model=unmarked)[0], 0.0)
|
|
||||||
|
|
||||||
def test_driver_and_authority_gates_reset(self):
|
|
||||||
for fields in ({'steeringPressed': True}, {'leftBlinker': True}, {'rightBlinker': True}, {'canTimeout': True}, {'leftBlindspot': True}):
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, **fields)[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, active=False)[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, maneuver=True)[0], 0.0)
|
|
||||||
subject = host()
|
|
||||||
_, bus, now = drive(subject, 4.0, PARKED)
|
|
||||||
bus.put('carState', car_message(steeringPressed=True), now)
|
|
||||||
bus.put('radarTracks', radar_message(PARKED), now)
|
|
||||||
bus.put('modelV2', bus['modelV2'], now)
|
|
||||||
self.assertGreater(subject.shift, 0.0)
|
|
||||||
self.assertEqual(subject.shift, subject.detector.shift)
|
|
||||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), 0.0)
|
|
||||||
self.assertEqual(subject.detector.shift, 0.0)
|
|
||||||
self.assertEqual(subject.shift, 0.0)
|
|
||||||
|
|
||||||
def test_blinker_keeps_watching_and_resumes_without_reconfirm(self):
|
|
||||||
subject = host()
|
|
||||||
correction, _, now = drive(subject, 2.0, PARKED, leftBlinker=True)
|
|
||||||
self.assertEqual(correction, 0.0)
|
|
||||||
self.assertEqual(subject.shift, 0.0)
|
|
||||||
self.assertLess(drive(subject, 0.25, PARKED, start=now)[0], 0.0)
|
|
||||||
|
|
||||||
def test_stale_or_invalid_inputs_reset(self):
|
|
||||||
for name in ParkedClearanceHost.REQUIRED:
|
|
||||||
subject = host()
|
|
||||||
_, bus, now = drive(subject, 4.0, PARKED)
|
|
||||||
self.assertEqual(subject.update(bus, now_ns=now + 10 * STEP_NS, lateral_active=True, maneuver=False), 0.0)
|
|
||||||
subject = host()
|
|
||||||
_, bus, now = drive(subject, 4.0, PARKED)
|
|
||||||
for other in ParkedClearanceHost.REQUIRED:
|
|
||||||
bus.put(other, bus[other], now, valid=other != name)
|
|
||||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), 0.0)
|
|
||||||
self.assertEqual(subject.reason, f'{name}_stale')
|
|
||||||
|
|
||||||
def test_lane_change_and_speed_window(self):
|
|
||||||
model = model_message().as_builder()
|
|
||||||
model.meta.laneChangeState = log.LaneChangeState.laneChangeStarting
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, model=model.as_reader())[0], 0.0)
|
|
||||||
self.assertEqual(drive(host(), 3.0, [(7, 20.0, -2.6, -25.0)], speed=25.0)[0], 0.0)
|
|
||||||
|
|
||||||
def test_held_between_radar_samples(self):
|
|
||||||
subject = host()
|
|
||||||
correction, bus, now = drive(subject, 4.0, PARKED)
|
|
||||||
bus.put('carState', car_message(), now)
|
|
||||||
self.assertEqual(subject.update(bus, now_ns=now, lateral_active=True, maneuver=False), correction)
|
|
||||||
|
|
||||||
def test_curving_path_adds_nothing(self):
|
|
||||||
model = model_message().as_builder()
|
|
||||||
model.position.y = [0.15 * x for x in model.position.x]
|
|
||||||
subject = host()
|
|
||||||
self.assertEqual(drive(subject, 3.0, [(7, 20.0, -5.6, -11.0)], model=model.as_reader())[0], 0.0)
|
|
||||||
self.assertEqual(subject.reason, 'curve')
|
|
||||||
|
|
||||||
def test_malformed_model_adds_nothing(self):
|
|
||||||
self.assertEqual(drive(host(), 3.0, PARKED, model=log.ModelDataV2.new_message().as_reader())[0], 0.0)
|
|
||||||
|
|
||||||
def test_saved_settings(self):
|
|
||||||
class Saved:
|
|
||||||
def __init__(self, root):
|
|
||||||
self.root = root
|
|
||||||
|
|
||||||
def get_param_path(self, key):
|
|
||||||
return str(Path(self.root) / key)
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as root:
|
|
||||||
saved = Saved(root)
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings(False, runtime.DEFAULT_GAP))
|
|
||||||
(Path(root) / 'ParkedClearance').write_bytes(b'1')
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings(True, runtime.DEFAULT_GAP))
|
|
||||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 1.2))
|
|
||||||
for bad in (b'nan', b'0', b'2.6', b'9', b'x'):
|
|
||||||
(Path(root) / 'ParkedClearanceGap').write_bytes(bad)
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
|
||||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
|
||||||
for side, expected in ((b'0', ParkedSettings(True, 1.2)), (b'1', ParkedSettings()), (b'x', ParkedSettings())):
|
|
||||||
(Path(root) / 'IsRhdDetected').write_bytes(side)
|
|
||||||
self.assertEqual(read_settings(saved), expected)
|
|
||||||
(Path(root) / 'IsRhdDetected').unlink()
|
|
||||||
(Path(root) / 'ParkedClearanceShift').write_bytes(b'0.45')
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 1.2, 0.45))
|
|
||||||
for bad in (b'nan', b'0', b'0.85', b'x'):
|
|
||||||
(Path(root) / 'ParkedClearanceShift').write_bytes(bad)
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
|
||||||
(Path(root) / 'ParkedClearanceShift').write_bytes(b'0.8')
|
|
||||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'2.5')
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings(True, 2.5, 0.8))
|
|
||||||
(Path(root) / 'ParkedClearanceGap').write_bytes(b'1.2')
|
|
||||||
(Path(root) / 'ParkedClearanceShift').unlink()
|
|
||||||
(Path(root) / 'ParkedClearance').write_bytes(b'yes')
|
|
||||||
self.assertEqual(read_settings(saved), ParkedSettings())
|
|
||||||
|
|
||||||
|
|
||||||
class TestParkedLaneCentering(unittest.TestCase):
|
|
||||||
def test_hold_fades_lane_centering_and_resumes(self):
|
|
||||||
lanes = lane_model(left=-1.5, right=2.1)
|
|
||||||
controller = LaneCenteringController()
|
|
||||||
start = previous = settled(controller, lane_observation(lanes)).correction
|
|
||||||
self.assertGreater(start, 0.0)
|
|
||||||
for _ in range(100):
|
|
||||||
result = controller.update(lane_observation(lanes, hold=True))
|
|
||||||
self.assertEqual(result.reason, 'parked_clearance')
|
|
||||||
self.assertIsNotNone(result.candidate_curvature)
|
|
||||||
self.assertLessEqual(result.correction, previous)
|
|
||||||
self.assertGreaterEqual(result.correction, previous * math.exp(-0.01 / RELEASE_TAU) - 1e-15)
|
|
||||||
previous = result.correction
|
|
||||||
self.assertLess(previous, 0.01 * start)
|
|
||||||
resumed = settled(controller, lane_observation(lanes))
|
|
||||||
self.assertNotEqual(resumed.reason, 'parked_clearance')
|
|
||||||
self.assertAlmostEqual(resumed.correction, start, delta=0.05 * start)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
unittest.main()
|
|
||||||
@@ -5,7 +5,7 @@ import math
|
|||||||
from openpilot.starpilot.curve_speed.preferences import GENTLE_KEY
|
from openpilot.starpilot.curve_speed.preferences import GENTLE_KEY
|
||||||
from openpilot.starpilot.saved_source import read_saved
|
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")}
|
BOOST_KEYS = {name: name.title() + "PersonalityBoost" for name in ("relaxed", "standard", "aggressive", "traffic")}
|
||||||
MAX_BOOST_PERCENT = 200.0
|
MAX_BOOST_PERCENT = 200.0
|
||||||
|
|
||||||
@@ -18,6 +18,17 @@ MIN_HESITATION_GAP = 1.
|
|||||||
HESITATION_ACCEL = .3
|
HESITATION_ACCEL = .3
|
||||||
RECOVERY_ACCEL = .6
|
RECOVERY_ACCEL = .6
|
||||||
HESITATION_FILTER_SECONDS = .5
|
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:
|
class Encouragement:
|
||||||
@@ -26,10 +37,11 @@ class Encouragement:
|
|||||||
self.boost = 0.
|
self.boost = 0.
|
||||||
self.drive_id = None
|
self.drive_id = None
|
||||||
self.last_model_ns = 0
|
self.last_model_ns = 0
|
||||||
|
self.converging = False
|
||||||
self.hesitation_accel: float | None = None
|
self.hesitation_accel: float | None = None
|
||||||
|
|
||||||
def update(self, sm, cp, *, now_ns, drive_id, dt, target_speed, model_accel, mpc_accel, cruise_accel,
|
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
|
eligible = False
|
||||||
model_ns = 0
|
model_ns = 0
|
||||||
try:
|
try:
|
||||||
@@ -45,18 +57,21 @@ class Encouragement:
|
|||||||
sm['carControl'].longActive and car.canValid and not car.canTimeout and
|
sm['carControl'].longActive and car.canValid and not car.canTimeout and
|
||||||
not car.gasPressed and not car.brakePressed and not car.standstill 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['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
|
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
|
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
|
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):
|
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
|
||||||
eligible = False
|
eligible = False
|
||||||
if type(model_ns) is not int or model_ns <= 0:
|
if type(model_ns) is not int or model_ns <= 0:
|
||||||
model_ns = 0
|
model_ns = 0
|
||||||
eligible = False
|
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
|
eligible = False
|
||||||
|
self.converging = converge
|
||||||
self.drive_id = drive_id
|
self.drive_id = drive_id
|
||||||
self.last_model_ns = model_ns
|
self.last_model_ns = model_ns
|
||||||
if not eligible:
|
if not eligible:
|
||||||
@@ -75,7 +90,8 @@ class Encouragement:
|
|||||||
if self.clear_seconds > SETTLE_SECONDS and car.aEgo < RECOVERY_ACCEL:
|
if self.clear_seconds > SETTLE_SECONDS and car.aEgo < RECOVERY_ACCEL:
|
||||||
self.boost = min(MAX_BOOST, self.boost + BOOST_RATE * dt)
|
self.boost = min(MAX_BOOST, self.boost + BOOST_RATE * dt)
|
||||||
gap_scale = min(1., max(0., (target_speed - car.vEgo - .2) / 1.8))
|
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)
|
return min(model_accel + scale * bonus, mpc_accel, cruise_accel)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ import math
|
|||||||
from openpilot.common.realtime import DT_CTRL
|
from openpilot.common.realtime import DT_CTRL
|
||||||
from openpilot.starpilot.longitudinal.force_stop_braking import eligible as distance_braking_eligible
|
from openpilot.starpilot.longitudinal.force_stop_braking import eligible as distance_braking_eligible
|
||||||
from opendbc.car.structs import car
|
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.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.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 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
|
from opendbc.car.gm.bolt_mode import policy_for as bolt_mode_policy_for
|
||||||
|
|
||||||
LongCtrlState = car.CarControl.Actuators.LongControlState
|
LongCtrlState = car.CarControl.Actuators.LongControlState
|
||||||
@@ -29,6 +30,7 @@ class LongitudinalContext:
|
|||||||
force_stop_braking: bool = False
|
force_stop_braking: bool = False
|
||||||
toyota_resume_fresh: bool = False
|
toyota_resume_fresh: bool = False
|
||||||
toyota_brake_release: bool = False
|
toyota_brake_release: bool = False
|
||||||
|
bolt_cruise_settle: bool = False
|
||||||
|
|
||||||
|
|
||||||
class LongitudinalExtension:
|
class LongitudinalExtension:
|
||||||
@@ -44,6 +46,7 @@ class LongitudinalExtension:
|
|||||||
toyota_production = production_enabled(CP)
|
toyota_production = production_enabled(CP)
|
||||||
self.toyota_stopped_lead = toyota_production and str(CP.carFingerprint) == COROLLA
|
self.toyota_stopped_lead = toyota_production and str(CP.carFingerprint) == COROLLA
|
||||||
self.toyota_pcm_resume = self.toyota_stopped_lead and CP.autoResumeSng
|
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.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.ioniq6_start = Ioniq6StartPolicy() if ioniq6_start_eligible(CP) else None
|
||||||
self.force_stop_distance_braking = distance_braking_eligible(CP)
|
self.force_stop_distance_braking = distance_braking_eligible(CP)
|
||||||
@@ -99,6 +102,16 @@ class LongitudinalExtension:
|
|||||||
if self.stopping_policy is not None:
|
if self.stopping_policy is not None:
|
||||||
state = self.stopping_policy.transition(state, previous_state, active, CS, a_target, should_stop,
|
state = self.stopping_policy.transition(state, previous_state, active, CS, a_target, should_stop,
|
||||||
has_lead=context.has_lead)
|
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
|
if (self.toyota_pcm_resume and self.toyota_output is not None and active and
|
||||||
CS.standstill and CS.cruiseState.standstill):
|
CS.standstill and CS.cruiseState.standstill):
|
||||||
# The PCM clears its hold after the controller sends a positive request.
|
# 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)
|
self.bolt_mode.update(context.experimental_mode, DT_CTRL)
|
||||||
feedforward = (self.vehicle_policy.feedforward(a_target, CS.vEgo, last_output)
|
feedforward = (self.vehicle_policy.feedforward(a_target, CS.vEgo, last_output)
|
||||||
if self.vehicle_policy is not None else a_target)
|
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,
|
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)
|
should_stop=should_stop, has_lead=context.has_lead)
|
||||||
if self.vehicle_policy is not None else False)
|
|
||||||
if self.stopping_policy is not None:
|
if self.stopping_policy is not None:
|
||||||
feedforward, stop_freeze = self.stopping_policy.prepare_pid(pid, a_target, error, CS, context)
|
feedforward, stop_freeze = self.stopping_policy.prepare_pid(pid, a_target, error, CS, context)
|
||||||
freeze_integrator |= stop_freeze
|
freeze_integrator |= stop_freeze
|
||||||
@@ -182,7 +199,7 @@ def create_extension(cp, startup_preferences=None):
|
|||||||
extension = LongitudinalExtension(cp, startup_preferences)
|
extension = LongitudinalExtension(cp, startup_preferences)
|
||||||
if (extension.vehicle_policy is None and extension.toyota_output is None and extension.ioniq6_start is None and
|
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
|
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 None
|
||||||
return extension
|
return extension
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
import math
|
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.curve import frozen_raw_curve
|
||||||
from openpilot.starpilot.conditional_mode.preferences import CEMOptions, decode_preferences, PreferenceError
|
from openpilot.starpilot.conditional_mode.preferences import CEMOptions, decode_preferences, PreferenceError
|
||||||
from openpilot.starpilot.conditional_mode.projection import _horizon
|
from openpilot.starpilot.conditional_mode.projection import _horizon
|
||||||
@@ -215,7 +216,13 @@ class ForceStopRuntime:
|
|||||||
kona_handoff = distance_enabled and kona_eligible(cp)
|
kona_handoff = distance_enabled and kona_eligible(cp)
|
||||||
tune = replace(vehicle_tune(str(cp.carFingerprint)), distance_control=distance_enabled and not kona_handoff,
|
tune = replace(vehicle_tune(str(cp.carFingerprint)), distance_control=distance_enabled and not kona_handoff,
|
||||||
distance_handoff=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:
|
if takeoff_enabled:
|
||||||
self.plan = replace(self.plan, takeoff_light_observed=takeoff_observed, takeoff_light=takeoff_light)
|
self.plan = replace(self.plan, takeoff_light_observed=takeoff_observed, takeoff_light=takeoff_light)
|
||||||
return self.plan
|
return self.plan
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ import os
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
from opendbc.car.interfaces import ACCEL_MAX
|
from opendbc.car.interfaces import ACCEL_MAX
|
||||||
|
from opendbc.car.toyota.pedal import supports_standstill_resume
|
||||||
|
|
||||||
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
|
from openpilot.starpilot.longitudinal.extension import LongitudinalContext
|
||||||
from opendbc.car.hyundai.blended_stopping import eligible as blended_longitudinal_eligible
|
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.feature_runtime import enabled as feature_enabled
|
||||||
from openpilot.starpilot.conditional_mode.traffic_launch import TrafficLaunchState
|
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,
|
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,
|
development_enabled as toyota_development_enabled,
|
||||||
production_enabled as toyota_production_enabled, leads_from_radar)
|
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.lead_takeoff_preferences import TakeoffPreferences
|
||||||
from openpilot.starpilot.longitudinal.takeoffs import eligible as takeoff_eligible
|
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.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.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.hybrid_cc import policy_for as hybrid_policy_for
|
||||||
from opendbc.car.gm.suburban import SuburbanStopEvidence
|
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
|
self.toyota_sienna_replay = toyota_development_enabled(self.CP) and str(self.CP.carFingerprint) == SIENNA_4G
|
||||||
toyota_production = toyota_production_enabled(self.CP)
|
toyota_production = toyota_production_enabled(self.CP)
|
||||||
self.toyota_corolla_stop = toyota_production and str(self.CP.carFingerprint) == COROLLA
|
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.toyota_sienna_production = toyota_production and str(self.CP.carFingerprint) == SIENNA_4G
|
||||||
self.ioniq6_start_enabled = ioniq6_start_eligible(self.CP)
|
self.ioniq6_start_enabled = ioniq6_start_eligible(self.CP)
|
||||||
self.force_stop_distance_braking = distance_braking_eligible(self.CP)
|
self.force_stop_distance_braking = distance_braking_eligible(self.CP)
|
||||||
gm_policy = gm_pedal_policy_for(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.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)
|
installed_policy = installed_policy_for(self.CP)
|
||||||
stop_policy = installed_policy.stop_policy() if hasattr(installed_policy, 'stop_policy') else None
|
stop_policy = installed_policy.stop_policy() if hasattr(installed_policy, 'stop_policy') else None
|
||||||
evidence_type = getattr(stop_policy, 'evidence_type', 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 [])
|
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
|
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.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 [])
|
return ['radarState', 'deviceState'] + (['slcState'] if self.gm_start_enabled or self.ev9_long_enabled else [])
|
||||||
if self.ev9_long_enabled:
|
if self.ev9_long_enabled:
|
||||||
return ['radarState', 'deviceState', 'slcState']
|
return ['radarState', 'deviceState', 'slcState']
|
||||||
@@ -179,6 +184,11 @@ class LongitudinalInputs:
|
|||||||
can_release_brake = (resume_fresh and self.sm['longitudinalPlan'].allowThrottle and
|
can_release_brake = (resume_fresh and self.sm['longitudinalPlan'].allowThrottle and
|
||||||
not self.sm['longitudinalPlan'].fcw)
|
not self.sm['longitudinalPlan'].fcw)
|
||||||
return LongitudinalContext(leads=leads, toyota_resume_fresh=resume_fresh, toyota_brake_release=can_release_brake)
|
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()
|
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)
|
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
|
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,
|
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,
|
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,
|
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)
|
has_lead=(bool(self.sm['longitudinalPlan'].hasLead)
|
||||||
if self.blended_longitudinal_enabled and self.sm.all_checks(['longitudinalPlan'])
|
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]
|
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):
|
def resume_sources_current(self):
|
||||||
return self.resume_freshness.current(self.sm)
|
return self.resume_freshness.current(self.sm)
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ def attach_inputs(controls):
|
|||||||
inputs.faster_takeoffs = False
|
inputs.faster_takeoffs = False
|
||||||
inputs.force_stop_distance_braking = 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',
|
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'):
|
'gm_cc_enabled', 'gm_cc_stop_enabled', 'gm_ascm_enabled', 'gm_suburban_enabled'):
|
||||||
setattr(inputs, name, False)
|
setattr(inputs, name, False)
|
||||||
inputs.gm_cc_evidence = None
|
inputs.gm_cc_evidence = None
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user