Compare commits

...

4 Commits

Author SHA1 Message Date
firestar5683 5a9deaca5f Cinquev3 2026-09-18 13:43:23 -05:00
firestarsdog 673ca37396 Small UI UX 2026-09-18 03:42:24 -04:00
firestar5683 44beb5b778 EV6 2026-09-17 08:33:35 -05:00
firestar5683 00ac287223 EV6 2026-09-17 08:33:10 -05:00
8 changed files with 304 additions and 22 deletions
@@ -1033,7 +1033,9 @@ class CarController(CarControllerBase):
left_sound_active=left_warning.sound_active, right_sound_active=right_warning.sound_active,
)
else:
adrv_messages = hyundaicanfd.create_adrv_messages(self.packer, self.CAN, self.frame)
adrv_messages = hyundaicanfd.create_adrv_messages(self.packer, self.CAN, self.frame,
car_fingerprint=self.CP.carFingerprint,
drive_gear=drive_gear)
can_sends.extend(adrv_messages)
# The front radar treats ADAS_DRV's 0x100 broadcast as its host heartbeat
# and stops publishing object tracks when it disappears.
@@ -8,6 +8,34 @@ from opendbc.car.crc import CRC16_XMODEM
from opendbc.car.hyundai.values import HyundaiFlags, CAR, CANFD_ALT_BUTTONS_RESUME_CAR
_adrv_0x51_templates: dict[CAR, bytes] = {}
def cache_adrv_0x51_template(car_fingerprint: CAR, dat: bytes | None) -> None:
if car_fingerprint != CAR.KIA_EV6:
return
if dat is None:
_adrv_0x51_templates.pop(car_fingerprint, None)
elif len(dat) == 32 and any(dat[3:]):
_adrv_0x51_templates[car_fingerprint] = bytes(dat)
def create_adrv_0x51(packer, CAN, frame: int, car_fingerprint: CAR | None = None, drive_gear: bool = False):
template = _adrv_0x51_templates.get(car_fingerprint)
if template is None:
return packer.make_can_msg("ADRV_0x51", CAN.ACAN, {})
# EV6 MRR30 tracks stop when the ADAS takeover replaces this platform payload with zeros.
dat = bytearray(template)
dat[2] = (template[2] + frame + 1) & 0xFF
dat[3] = (dat[3] & ~0x1) | int(drive_gear)
crc = hkg_can_fd_checksum(0x51, None, dat)
dat[0] = crc & 0xFF
dat[1] = (crc >> 8) & 0xFF
return CanData(0x51, bytes(dat), CAN.ACAN)
def _set_value(msg: bytearray, sig, ival: int) -> None:
i = sig.lsb // 8
bits = sig.size
@@ -788,15 +816,13 @@ def create_fca_warning_light(packer, CAN, frame):
return ret
def create_adrv_messages(packer, CAN, frame, blended_hda2=False):
def create_adrv_messages(packer, CAN, frame, blended_hda2=False, car_fingerprint=None, drive_gear=False):
# messages needed to car happy after disabling
# the ADAS Driving ECU to do longitudinal control
ret = []
values = {
}
ret.append(packer.make_can_msg("ADRV_0x51", CAN.ACAN, values))
ret.append(create_adrv_0x51(packer, CAN, frame, car_fingerprint, drive_gear))
if blended_hda2:
return ret
+16 -1
View File
@@ -2,6 +2,7 @@ import time
# Provenance: portions of HKG angle integration are adapted from sunnypilot/opendbc's
# hkg-angle-steering-2025 branch at cc4b08625. See CREDITS.md and THIRD_PARTY_NOTICES.md.
from opendbc.car import get_safety_config, structs, uds
from opendbc.car.hyundai import hyundaicanfd
from opendbc.car.hyundai.hyundaicanfd import CanBus
from opendbc.car.hyundai.values import HyundaiFlags, CAR, CarControllerParams, \
CANFD_UNSUPPORTED_LONGITUDINAL_CAR, \
@@ -391,11 +392,25 @@ class CarInterface(CarInterfaceBase):
skip_disable_ecu = True
if not skip_disable_ecu:
disable_can_recv = can_recv
if CP.carFingerprint == CAR.KIA_EV6 and can_recv is not None:
hyundaicanfd.cache_adrv_0x51_template(CP.carFingerprint, None)
base_can_recv = can_recv
adrv_bus = CanBus(CP).ACAN
def disable_can_recv(*args, **kwargs):
packets = base_can_recv(*args, **kwargs)
for packet in packets or []:
for msg in packet:
if msg.src == adrv_bus and msg.address == 0x51:
hyundaicanfd.cache_adrv_0x51_template(CP.carFingerprint, msg.dat)
return packets
# Try ECU disable. If it succeeds (IGN-ON mode), enable longitudinal.
# If it fails (READY mode returns NRC 0x22, or timeout), strip LONG safety flag
# so panda forwards stock SCC messages normally (lateral-only mode).
ecu_log(f"=== ECU DISABLE attempt: addr=0x{addr:x}, bus={bus} ===")
ecu_disabled = disable_ecu(can_recv, can_send, bus=bus, addr=addr, com_cont_req=communication_control,
ecu_disabled = disable_ecu(disable_can_recv, can_send, bus=bus, addr=addr, com_cont_req=communication_control,
reset=bool(CP.flags & HyundaiFlags.CAN_CANFD_BLENDED))
if CP.carFingerprint in (CAR.HYUNDAI_IONIQ_6, CAR.HYUNDAI_IONIQ_5_PE):
@@ -149,6 +149,60 @@ class TestHyundaiFingerprint:
assert get_communication_control_request(CAR.HYUNDAI_IONIQ_6) == radar_keepalive_request
def test_ev6_adrv_0x51_replays_factory_payload(self):
CP = CarParams.new_message()
CP.carFingerprint = CAR.KIA_EV6
CP.flags = int(HyundaiFlags.CANFD | HyundaiFlags.CANFD_LKA_STEERING | HyundaiFlags.EV)
packer = CANPacker(DBC[CP.carFingerprint][Bus.pt])
can_bus = CanBus(CP)
factory = bytes.fromhex("88ed2e091700ffff5e0d0000012006ff021c2200000000000800000010000000")
hyundaicanfd.cache_adrv_0x51_template(CAR.KIA_EV6, factory)
try:
address, dat, bus = hyundaicanfd.create_adrv_0x51(packer, can_bus, 7, CAR.KIA_EV6, drive_gear=True)
_, parked_dat, _ = hyundaicanfd.create_adrv_0x51(packer, can_bus, 8, CAR.KIA_EV6, drive_gear=False)
_, other_dat, _ = hyundaicanfd.create_adrv_0x51(packer, can_bus, 7, CAR.HYUNDAI_IONIQ_6)
finally:
hyundaicanfd.cache_adrv_0x51_template(CAR.KIA_EV6, None)
assert address == 0x51
assert bus == can_bus.ACAN
assert dat[2] == (factory[2] + 8) & 0xFF
assert dat[3:] == factory[3:]
assert int.from_bytes(dat[:2], "little") == hkg_can_fd_checksum(address, None, bytearray(dat))
assert parked_dat[3] == factory[3] & ~0x1
assert parked_dat[4:] == factory[4:]
assert int.from_bytes(parked_dat[:2], "little") == hkg_can_fd_checksum(address, None, bytearray(parked_dat))
assert other_dat[3:] == bytes(29)
def test_ev6_init_captures_factory_adrv_0x51(self, monkeypatch):
fingerprint = gen_empty_fingerprint()
fingerprint[CanBus(None, fingerprint).CAM][0x50] = 16
radar_config = get_radar_track_config(CAR.KIA_EV6)
fingerprint[radar_config.bus][radar_config.start_addr] = radar_config.expected_length
car_fw = [CarParams.CarFw(ecu=Ecu.adas, fwVersion=b"", address=0x730, brand="hyundai")]
CP = CarInterface.get_params(CAR.KIA_EV6, fingerprint, car_fw, True, False, False, get_test_toggles())
factory = bytes.fromhex("6b657d090900e1ff000000000020ffff00000000000000000800000010000000")
def can_recv(*, wait_for_one=True):
msg = SimpleNamespace(address=0x51, src=CanBus(CP).ACAN, dat=factory)
return [[msg]]
def fake_disable_ecu(capturing_can_recv, *_args, **_kwargs):
capturing_can_recv(wait_for_one=True)
return True
monkeypatch.setattr("opendbc.car.hyundai.interface.disable_ecu", fake_disable_ecu)
CarInterface.init(CP, can_recv, None)
packer = CANPacker(DBC[CP.carFingerprint][Bus.pt])
try:
_, dat, _ = hyundaicanfd.create_adrv_0x51(packer, CanBus(CP), 0, CAR.KIA_EV6, drive_gear=True)
finally:
hyundaicanfd.cache_adrv_0x51_template(CAR.KIA_EV6, None)
assert dat[3:] == factory[3:]
def test_carnival_hev_low_speed_torque_rate_limits(self):
CP = CarInterface.get_params(CAR.KIA_CARNIVAL_HEV_4TH_GEN, gen_empty_fingerprint(), [],
False, False, False, None)
+79 -12
View File
@@ -467,7 +467,54 @@ def make_run_supercombo(model_runner, metadata, frame_skip, image_history_pipeli
return run_policy
def compile_jit(jit, make_random_inputs, input_keys, make_queues):
def stateful_image_shapes(metadata):
shape = tuple(metadata['input_shapes']['new_img'])
if len(shape) != 4 or shape[:2] != (2, 6):
raise ValueError(f"Unsupported stateful image shape: {shape}")
return dict.fromkeys(('img', 'big_img'), (1, *shape[1:]))
def stateful_host_shapes(metadata):
return {name: shape for name, shape in metadata['input_shapes'].items()
if name != 'new_img' and name not in metadata['state_pairs']}
def make_stateful_input_queues(metadata, device):
queues, npy = make_warp_input_queues(stateful_image_shapes(metadata), 1, device)
shapes = stateful_host_shapes(metadata)
sizes = [math.prod(shape) for shape in shapes.values()]
packed = np.zeros(sum(sizes), dtype=np.float32)
npy.update({name: value.reshape(shape) for (name, shape), value in
zip(shapes.items(), np.split(packed, np.cumsum(sizes[:-1])), strict=True)})
queues['packed_npy_inputs'] = Tensor(packed, device='NPY').realize()
for name in metadata['state_pairs']:
queues[name] = Tensor(np.zeros(metadata['input_shapes'][name], dtype=metadata['input_dtypes'][name]),
device=device).contiguous().realize()
return queues, npy
def make_run_stateful_supercombo(model_runner, metadata):
shapes = stateful_host_shapes(metadata)
sizes = [math.prod(shape) for shape in shapes.values()]
def run_policy(warped, packed_npy_inputs, **state):
packed = packed_npy_inputs.to(Device.DEFAULT).realize()
inputs = {name: value.reshape(shape).cast(model_runner.graph_inputs[name].dtype)
for (name, shape), value in zip(shapes.items(), packed.split(sizes), strict=True)}
inputs['new_img'] = warped.to(Device.DEFAULT).cast(model_runner.graph_inputs['new_img'].dtype)
outputs = {name: value.contiguous() for name, value in model_runner(inputs | state).items()}
for name, next_name in metadata['state_pairs'].items():
if outputs[next_name].dtype != state[name].dtype:
raise ValueError(f'State dtype mismatch: {name} -> {next_name}')
# All reads of the previous state must finish before updating any history buffer.
Tensor.realize(*outputs.values())
Tensor.realize(*(state[name].assign(outputs[next_name]) for name, next_name in metadata['state_pairs'].items()))
return outputs['outputs'].cast('float32'),
return run_policy
def compile_jit(jit, make_random_inputs, input_keys, make_queues, validation_runs=1):
seed = 42
def random_inputs_run(fn, current_seed, test_values=None, test_buffers=None, expect_match=True):
@@ -475,7 +522,8 @@ def compile_jit(jit, make_random_inputs, input_keys, make_queues):
np.random.seed(current_seed)
Tensor.manual_seed(current_seed)
testing = test_values is not None or test_buffers is not None
run_count = 1 if testing else 3
run_count = validation_runs if testing else max(3, validation_runs)
values, buffers = [], []
for index in range(run_count):
for value in npy.values():
@@ -489,9 +537,9 @@ def compile_jit(jit, make_random_inputs, input_keys, make_queues):
end = time.perf_counter()
print(f" [{index + 1}/{run_count}] enqueue {(mid - start) * 1e3:6.2f} ms -- total {(end - start) * 1e3:6.2f} ms")
if index == 0:
values = [np.copy(value.numpy()) for value in outputs]
buffers = [np.copy(value.numpy()) for value in input_queues.values()]
if index < validation_runs:
values.extend(np.copy(value.numpy()) for value in outputs)
buffers.extend(np.copy(value.numpy()) for value in input_queues.values())
if not all(np.isfinite(value).all() for value in values):
raise ValueError("Compiled JIT produced non-finite outputs")
@@ -602,13 +650,31 @@ def main():
output["metadata"]["model"] = make_metadata_dict(model_path)
validate_metadata(output["metadata"]["model"])
policy_shapes = output["metadata"]["model"]["input_shapes"]
frame_skip = args.frame_skip or derive_frame_skip(policy_shapes)
make_policy_queues = partial(make_supercombo_input_queues, policy_shapes, frame_skip)
run_policy = make_run_supercombo(
model_runner, output["metadata"], frame_skip, args.image_history_pipeline,
)
image_shapes = policy_shapes
policy_input_keys = FAST_POLICY_INPUTS if args.image_history_pipeline == IMAGE_HISTORY_IN_POLICY else SUPERCOMBO_POLICY_INPUTS
if 'new_img' in policy_shapes:
if args.image_history_pipeline != IMAGE_HISTORY_IN_POLICY:
parser.error('ONNX-managed history requires --image-history-pipeline policy')
metadata = output['metadata']['model']
metadata['state_pairs'] = {name: f'next_{name}' for name in policy_shapes
if f'next_{name}' in metadata['output_shapes']}
if not metadata['state_pairs']:
raise ValueError('Stateful supercombo is missing next-state outputs')
metadata['input_dtypes'] = {name: np.dtype(spec.dtype.fmt).name for name, spec in model_runner.graph_inputs.items()}
for name, next_name in metadata['state_pairs'].items():
if policy_shapes[name] != metadata['output_shapes'][next_name]:
raise ValueError(f'State shape mismatch: {name} -> {next_name}')
frame_skip = 1
make_policy_queues = partial(make_stateful_input_queues, metadata)
run_policy = make_run_stateful_supercombo(model_runner, metadata)
image_shapes = stateful_image_shapes(metadata)
policy_input_keys = ('packed_npy_inputs', *metadata['state_pairs'])
else:
frame_skip = args.frame_skip or derive_frame_skip(policy_shapes)
make_policy_queues = partial(make_supercombo_input_queues, policy_shapes, frame_skip)
run_policy = make_run_supercombo(
model_runner, output["metadata"], frame_skip, args.image_history_pipeline,
)
image_shapes = policy_shapes
policy_input_keys = FAST_POLICY_INPUTS if args.image_history_pipeline == IMAGE_HISTORY_IN_POLICY else SUPERCOMBO_POLICY_INPUTS
else:
if not args.vision_onnx:
parser.error("--vision-onnx is required for split models")
@@ -675,6 +741,7 @@ def main():
)
output["run_policy"] = compile_jit(
run_policy_jit, make_random_model_inputs, policy_input_keys, make_policy_queues,
validation_runs=5 if output['metadata'].get('model', {}).get('state_pairs') else 1,
)
model_w, model_h = args.model_size
+14 -2
View File
@@ -48,6 +48,9 @@ from openpilot.selfdrive.modeld.compile_modeld import (
derive_frame_skip,
make_split_input_queues,
make_supercombo_input_queues,
make_stateful_input_queues,
stateful_host_shapes,
stateful_image_shapes,
)
from openpilot.selfdrive.modeld.helpers import get_tg_input_devices, load_oob, tinygrad_dev_config, usbgpu_present
from openpilot.selfdrive.modeld.usbgpu_link import wait_usbgpu_link
@@ -587,8 +590,15 @@ class ModelState:
self.run_policy = artifact["run_policy"]
self.warp_enqueue = artifact[(cam_w, cam_h)]
self.can_prepare_only = self.image_history_pipeline == IMAGE_HISTORY_IN_WARP
self.onnx_history = self.model_type == 'supercombo' and bool(self.metadata['model'].get('state_pairs'))
if self.model_type == "supercombo":
if self.onnx_history:
metadata = self.metadata['model']
input_shapes = stateful_image_shapes(metadata)
self.output_slices = metadata['output_slices']
self.input_queues, self.npy = make_stateful_input_queues(metadata, self.QUEUE_DEV)
self.policy_input_shapes = stateful_host_shapes(metadata)
elif self.model_type == "supercombo":
input_shapes = self.metadata["model"]["input_shapes"]
self.output_slices = self.metadata["model"]["output_slices"]
self.input_queues, self.npy = make_supercombo_input_queues(input_shapes, self.frame_skip, self.QUEUE_DEV)
@@ -698,7 +708,9 @@ class ModelState:
return parsed
def _reset_state(self) -> None:
if self.model_type == "supercombo":
if self.onnx_history:
self.input_queues, self.npy = make_stateful_input_queues(self.metadata['model'], self.QUEUE_DEV)
elif self.model_type == "supercombo":
self.input_queues, self.npy = make_supercombo_input_queues(
self.policy_input_shapes, self.frame_skip, self.QUEUE_DEV,
)
@@ -0,0 +1,106 @@
import pyray as rl
import pytest
from openpilot.system.ui import widgets
from openpilot.system.ui.lib import scroll_panel2
from openpilot.system.ui.lib.application import MouseEvent, MousePos, gui_app
from openpilot.system.ui.widgets.scroller import _Scroller
class Item(widgets.Widget):
def __init__(self):
super().__init__()
self.set_rect(rl.Rectangle(0, 0, 402, 180))
self.clicks = 0
self.set_click_callback(self._clicked)
def _clicked(self):
self.clicks += 1
def _render(self, _):
pass
@pytest.fixture
def make_scroller(monkeypatch):
monkeypatch.setattr(rl, "begin_scissor_mode", lambda *args: None)
monkeypatch.setattr(rl, "end_scissor_mode", lambda: None)
monkeypatch.setattr(rl, "get_frame_time", lambda: 1 / 60)
monkeypatch.setattr(rl, "get_time", lambda: 1.0)
monkeypatch.setattr(rl, "get_mouse_wheel_move", lambda: 0)
monkeypatch.setattr(gui_app, "texture", lambda *args: rl.Texture())
monkeypatch.setattr(gui_app, "_show_touches", False)
monkeypatch.setattr(gui_app, "_mouse_events", [])
monkeypatch.setattr(widgets, "PC", False)
monkeypatch.setattr(widgets.device, "awake", True)
monkeypatch.setattr(scroll_panel2, "TICI", True)
def make(**kwargs):
scroller = _Scroller([Item() for _ in range(8)], scroll_indicator=False, edge_shadows=False, **kwargs)
scroller.set_rect(rl.Rectangle(0, 0, 536, 240))
scroller.scroll_panel.set_offset(-500)
scroller.render()
return scroller
return make
def frame(scroller, *, pressed=False, released=False, pos=(200, 100), t=1.0):
gui_app._mouse_events = [MouseEvent(MousePos(*pos), 0, pressed, released, not released, t)]
scroller.render()
def test_tap_interrupts_programmatic_scroll_tail(make_scroller):
scroller = make_scroller()
scroller.scroll_to(3, smooth=True)
frame(scroller, pressed=True)
frame(scroller, released=True, t=1.05)
assert not scroller.is_auto_scrolling
assert sum(item.clicks for item in scroller.items) == 1
def test_blocking_programmatic_scroll_still_rejects_taps(make_scroller):
scroller = make_scroller()
scroller.scroll_to(30, smooth=True, block_interaction=True)
frame(scroller, pressed=True)
frame(scroller, released=True, t=1.05)
assert scroller.is_auto_scrolling
assert sum(item.clicks for item in scroller.items) == 0
@pytest.mark.parametrize("horizontal", [True, False])
def test_touch_down_immediately_stops_snapping(make_scroller, horizontal):
scroller = make_scroller(snap_items=True, horizontal=horizontal)
offset = scroller.scroll_panel.get_offset()
frame(scroller, pressed=True)
assert scroller.scroll_panel.state == scroll_panel2.ScrollState.PRESSED
assert scroller.scroll_panel.get_offset() == offset
def test_drag_outside_viewport_does_not_resume_snapping(make_scroller):
scroller = make_scroller(snap_items=True)
frame(scroller, pressed=True)
frame(scroller, pos=(180, 100), t=1.02)
frame(scroller, pos=(160, 250), t=1.04)
offset = scroller.scroll_panel.get_offset()
frame(scroller, pos=(140, 250), t=1.06)
assert scroller.scroll_panel.state == scroll_panel2.ScrollState.MANUAL_SCROLL
assert scroller.scroll_panel.get_offset() == pytest.approx(offset - 20)
@pytest.mark.parametrize("speed, expected_clicks", [(25, 1), (119, 1), (121, 0)])
def test_inertial_scroll_click_threshold_is_unchanged(make_scroller, speed, expected_clicks):
scroller = make_scroller()
scroller.scroll_panel._state = scroll_panel2.ScrollState.AUTO_SCROLL
scroller.scroll_panel._velocity = -speed
frame(scroller, pressed=True)
frame(scroller, released=True, t=1.05)
assert sum(item.clicks for item in scroller.items) == expected_clicks
+2 -2
View File
@@ -148,7 +148,7 @@ class _Scroller(Widget):
# preserve original touch valid callback
original_touch_valid_callback = item._touch_valid_callback
item.set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid() and self.enabled and self._scrolling_to[0] is None
item.set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid() and self.enabled and not self._scrolling_to[1]
and not self.moving_items and (original_touch_valid_callback() if
original_touch_valid_callback else True))
@@ -207,7 +207,7 @@ class _Scroller(Widget):
if scroll_snap_idx is not None:
snap_item = visible_items[scroll_snap_idx]
if self.is_pressed:
if self.scroll_panel.state in (ScrollState.PRESSED, ScrollState.MANUAL_SCROLL):
# no snapping until released
self._scroll_snap_filter.x = 0
else: