StarPort: Add unacknowledged video fix for the Polestar 2 and a patient adapter connect option

Co-authored-by: Jericho Adler <60821753+jericho-adler@users.noreply.github.com>
This commit is contained in:
Danny
2026-11-16 18:06:39 -08:00
parent 9b127466d5
commit ce34ddefef
14 changed files with 461 additions and 17 deletions
@@ -27,6 +27,14 @@ STARPORT_TALL_HEVC_KEY = "StarPortTallHevc"
STARPORT_TALL_HEVC_DESCRIPTION = ("Experimental test for a car that only takes H.265. Uses the car's 1080x1920 screen mode instead of " +
"720x1280 when it offers one. Needs Allow H.265 video on. H.264 cars are not affected. " +
"Applies from the next StarPort connection.")
STARPORT_UNACKED_VIDEO_KEY = "StarPortUnackedVideo"
STARPORT_UNACKED_VIDEO_DESCRIPTION = ("Experimental. For a car that shows video but never acknowledges it, so the picture freezes " +
"and reconnects every few seconds. Sends video without waiting for acknowledgments, on " +
"H.264 or H.265. Applies from the next StarPort connection.")
STARPORT_PATIENT_TCP_KEY = "StarPortPatientConnect"
STARPORT_PATIENT_TCP_DESCRIPTION = ("Experimental. For a wireless adapter that hands over its Wi-Fi but then refuses the connection, " +
"as if it is still starting up. Keeps trying for up to a minute instead of about 15 seconds. " +
"Applies from the next StarPort connection.")
STARPORT_EXPERIMENTS_KEY = "StarPortHeadUnitExperiments"
STARPORT_EXPERIMENTS_DESCRIPTION = ("Shows experimental fixes for specific cars and dongles, each with its own switch. Turn off to use the " +
"standard connection for every car. Applies from the next StarPort connection.")
@@ -74,6 +82,16 @@ class DeveloperSettingsOwner:
rows.append(FeatureRow(STARPORT_TALL_HEVC_KEY, "H.265 at 1080x1920", "On" if tall_hevc else "Off", b"1" if tall_hevc else b"0",
("Off", "On"), available=parked, reason=STARPORT_TALL_HEVC_DESCRIPTION if parked else held,
default_value="Off"))
unacked_video = bool(status.get("unacked_video"))
rows.append(FeatureRow(STARPORT_UNACKED_VIDEO_KEY, "Unacknowledged video", "On" if unacked_video else "Off",
b"1" if unacked_video else b"0",
("Off", "On"), available=parked, reason=STARPORT_UNACKED_VIDEO_DESCRIPTION if parked else held,
default_value="Off"))
patient_tcp = bool(status.get("patient_tcp"))
rows.append(FeatureRow(STARPORT_PATIENT_TCP_KEY, "Wait longer for the adapter", "On" if patient_tcp else "Off",
b"1" if patient_tcp else b"0",
("Off", "On"), available=parked, reason=STARPORT_PATIENT_TCP_DESCRIPTION if parked else held,
default_value="Off"))
experiments = bool(status.get("head_unit_experiments"))
chosen = set(status.get("head_unit_experiment_rules") or ())
rows.append(FeatureRow(STARPORT_EXPERIMENTS_KEY, "Try experimental fixes", "On" if experiments else "Off",
@@ -146,6 +164,10 @@ class DeveloperSettingsOwner:
return self._apply_starport(request, "keyframe_test", "set_keyframe_test")
if request.key == STARPORT_TALL_HEVC_KEY:
return self._apply_starport(request, "tall_hevc", "set_tall_hevc")
if request.key == STARPORT_UNACKED_VIDEO_KEY:
return self._apply_starport(request, "unacked_video", "set_unacked_video")
if request.key == STARPORT_PATIENT_TCP_KEY:
return self._apply_starport(request, "patient_tcp", "set_patient_tcp")
if request.key == STARPORT_EXPERIMENTS_KEY:
return self._apply_starport(request, "head_unit_experiments", "set_head_unit_experiments")
if request.key.startswith(STARPORT_EXPERIMENT_PREFIX):
@@ -117,6 +117,8 @@ DESCRIPTIONS = {
'StarPortAllowHevc': 'Lets a car that offers only H.265 video receive H.265; a car with an H.264 mode keeps H.264.',
'StarPortKeyframeTest': 'Sends every H.265 frame as a keyframe and logs the car\'s acknowledgments, to diagnose H.265-only cars.',
'StarPortTallHevc': 'Uses the car\'s 1080x1920 H.265 screen mode instead of 720x1280, to diagnose H.265-only cars. Needs Allow H.265 video on.',
'StarPortUnackedVideo': 'Sends video without waiting for the car\'s acknowledgments, on H.264 or H.265, for cars that show video but never acknowledge it.',
'StarPortPatientConnect': 'Keeps trying for up to a minute when a wireless adapter hands over its Wi-Fi but refuses the connection.',
'StarPortHeadUnitExperiments': 'Shows experimental fixes for specific cars and dongles, each with its own switch. Off is the standard connection.',
'StarPortDedicatedWifi': "Joins the car's Wi-Fi on a second interface so the comma stays on its home Wi-Fi or phone hotspot.",
'TeslaWakeOnCAN': 'Wakes comma when the Tesla wakes up, before you press the brake.',
@@ -191,6 +193,8 @@ INITIALIZATION = {
'StarPortAllowHevc': 'Applies from the next StarPort connection.',
'StarPortKeyframeTest': 'Applies from the next StarPort connection.',
'StarPortTallHevc': 'Applies from the next StarPort connection.',
'StarPortUnackedVideo': 'Applies from the next StarPort connection.',
'StarPortPatientConnect': 'Applies from the next StarPort connection.',
'StarPortHeadUnitExperiments': 'Applies from the next StarPort connection.',
'StarPortDedicatedWifi': 'Applies from the next StarPort connection.',
'LateralControllerSelection': ('Applies when driving processes next start: the controller class, vehicle policy and ' +
@@ -117,7 +117,9 @@
"StarPortHeadUnitExperiments",
"StarPortKeyframeTest",
"StarPortNewSetup",
"StarPortPatientConnect",
"StarPortTallHevc",
"StarPortUnackedVideo",
"SteerFriction",
"SteerLatAccel",
"StockConfidenceBallWidget",
@@ -12,7 +12,7 @@ from unittest.mock import patch
from openpilot.starpilot.galaxy.developer_settings import (CALIBRATION_RESET, DRIVER_MONITORING_RESET, STARPORT_EXPERIMENT_PREFIX,
STARPORT_EXPERIMENTS_KEY,
STARPORT_HEADING_KEY, STARPORT_HEVC_KEY, STARPORT_KEYFRAME_TEST_KEY,
STARPORT_TALL_HEVC_KEY,
STARPORT_TALL_HEVC_KEY, STARPORT_UNACKED_VIDEO_KEY, STARPORT_PATIENT_TCP_KEY,
STARPORT_NEW_SETUP_KEY, STARPORT_WIFI_KEY, DeveloperSettingsOwner)
from openpilot.starpilot.galaxy.settings import AuthorityContext, ContextSource, SettingsChanged, SettingsGateway
from openpilot.starpilot.longitudinal.voacc import KEY, selected
@@ -47,7 +47,7 @@ class FileParams:
class FakeStarPort:
def __init__(self, enabled=False, running=True):
self.enabled, self.running, self.hevc = enabled, running, False
self.keyframe_test = self.tall_hevc = False
self.keyframe_test = self.tall_hevc = self.unacked_video = self.patient_tcp = False
self.experiments, self.rules = False, []
def call(self, command, **payload):
@@ -65,6 +65,12 @@ class FakeStarPort:
if command == "set_tall_hevc":
self.tall_hevc = payload["enabled"]
return {"ok": True}
if command == "set_patient_tcp":
self.patient_tcp = payload["enabled"]
return {"ok": True}
if command == "set_unacked_video":
self.unacked_video = payload["enabled"]
return {"ok": True}
if command == "set_head_unit_experiments":
self.experiments = payload["enabled"]
return {"ok": True}
@@ -72,7 +78,8 @@ class FakeStarPort:
self.rules = sorted(set(self.rules) | {payload["rule"]} if payload["enabled"] else set(self.rules) - {payload["rule"]})
return {"ok": True, "changed": True}
return {"ok": True, "status": {"dedicated_wifi_interface": self.enabled, "allow_hevc": self.hevc, "keyframe_test": self.keyframe_test,
"tall_hevc": self.tall_hevc, "head_unit_experiments": self.experiments, "head_unit_experiment_rules": self.rules}}
"tall_hevc": self.tall_hevc, "unacked_video": self.unacked_video, "patient_tcp": self.patient_tcp,
"head_unit_experiments": self.experiments, "head_unit_experiment_rules": self.rules}}
class DeveloperSettingsTest(unittest.TestCase):
@@ -278,6 +285,28 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertFalse(service.keyframe_test or service.hevc)
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_TALL_HEVC_KEY, row.source, "Off"))) # stale view
def test_unacked_video_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
keys = [row.key for row in rows]
row = rows[keys.index(STARPORT_UNACKED_VIDEO_KEY)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_UNACKED_VIDEO_KEY, row.source, "On")))
self.assertTrue(service.unacked_video)
self.assertFalse(service.hevc or service.tall_hevc or service.experiments)
def test_patient_connect_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
keys = [row.key for row in rows]
row = rows[keys.index(STARPORT_PATIENT_TCP_KEY)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_PATIENT_TCP_KEY, row.source, "On")))
self.assertTrue(service.patient_tcp)
self.assertFalse(service.unacked_video)
def test_try_experimental_fixes_defaults_off_and_is_the_only_master_switch(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
@@ -301,7 +330,8 @@ class DeveloperSettingsTest(unittest.TestCase):
rows = owner.snapshot().rows
keys = [row.key for row in rows]
self.assertEqual(keys[keys.index(STARPORT_EXPERIMENTS_KEY) + 1:],
[STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e", STARPORT_EXPERIMENT_PREFIX + "phone_ping"])
[STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e", STARPORT_EXPERIMENT_PREFIX + "polestar_ps2_aar_301433653",
STARPORT_EXPERIMENT_PREFIX + "phone_ping"])
rule_key = STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e"
row = rows[keys.index(rule_key)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
@@ -124,6 +124,10 @@ def handle(supervisor: Supervisor, request: dict[str, Any], verifier: StarPortSo
supervisor.set_keyframe_test(request.get("enabled") is True)
elif command == "set_tall_hevc":
supervisor.set_tall_hevc(request.get("enabled") is True)
elif command == "set_unacked_video":
supervisor.set_unacked_video(request.get("enabled") is True)
elif command == "set_patient_tcp":
supervisor.set_patient_tcp(request.get("enabled") is True)
elif command == "set_head_unit_experiments":
supervisor.set_head_unit_experiments(request.get("enabled") is True)
elif command == "set_head_unit_experiment_rule":
@@ -11,6 +11,7 @@ from openpilot.starpilot.system.starport.projection_geometry import projection_g
SCREEN_PATH = DATA_DIR / 'screen.json'
MAX_BYTES = 2048
FIELDS = {'width', 'height', 'margin_width', 'margin_height', 'fps', 'config_index'}
SUPPORTED_SIZES = ((800, 480), (1280, 720), (1920, 1080), (720, 1280), (1080, 1920))
def validate_screen(value):
@@ -18,7 +19,7 @@ def validate_screen(value):
raise ValueError('Invalid projection screen')
if any(type(value[key]) is not int for key in FIELDS):
raise ValueError('Invalid projection dimensions')
if ((value['width'], value['height']) not in ((800, 480), (1280, 720), (1920, 1080), (720, 1280)) or
if ((value['width'], value['height']) not in SUPPORTED_SIZES or
value['fps'] not in (30, 60) or not 0 <= value['config_index'] <= 255):
raise ValueError('Unsupported projection screen')
projection_geometry(value['width'], value['height'], value['margin_width'], value['margin_height'])
@@ -9,13 +9,14 @@ from openpilot.starpilot.system.starport.quirk_state import MATCH_FIELDS, QuirkS
EXPERIMENTAL, VALIDATED = "experimental", "validated"
# Actions a rule's ladder may use. Each opens or sends one thing, and nothing else.
# Actions a rule's ladder may use. Each opens or sends one thing, or changes one thing about how video is sent, and nothing else.
OPEN_BLUETOOTH = "open_bluetooth" # open the car's Bluetooth channel, without a pairing request
OPEN_PHONE_STATUS = "open_phone_status" # open the car's phone-status channel
OPEN_SENSORS = "open_sensors" # open the car-data channel (driving status and night only)
OPEN_VENDOR = "open_vendor" # open the car's vendor channel; nothing is sent on it
REQUEST_BT_PAIRING = "request_bt_pairing" # send the Bluetooth pairing request with this comma's own address
ACTIONS = (OPEN_BLUETOOTH, OPEN_PHONE_STATUS, OPEN_SENSORS, OPEN_VENDOR, REQUEST_BT_PAIRING)
UNACKED_VIDEO = "unacked_video" # send video without waiting for acknowledgments; the car's pings show it is there
ACTIONS = (OPEN_BLUETOOTH, OPEN_PHONE_STATUS, OPEN_SENSORS, OPEN_VENDOR, REQUEST_BT_PAIRING, UNACKED_VIDEO)
# ServiceDiscoveryResponse field numbers (JSON turns them into strings).
SDR_LABELS = {"2": "car_make", "3": "car_model", "4": "car_year", "7": "head_unit_make", "8": "head_unit_model",
@@ -53,6 +54,15 @@ RULES: tuple[Rule, ...] = (
("2026-10-12 sessions 5-8", "2026-11-08 sessions 1, 2, 4")),
ladder=(OPEN_BLUETOOTH, OPEN_PHONE_STATUS, OPEN_SENSORS, OPEN_VENDOR, REQUEST_BT_PAIRING),
summary="This car's screen keeps ending after about 25 seconds."),
Rule(id="polestar_ps2_aar_301433653", label="2022 Polestar 2 (AAR.301433653 build)",
match={"car_make": "Polestar", "car_model": "PS2", "car_year": "2022", "head_unit_make": "VolvoCars",
"head_unit_model": "Polestar [AAR]",
"head_unit_software_version": "AAR.301433653 (6.1 (aareceiver_20260609.02_RC11 RELEASE PROD 1004961323)) 1"},
transports=(WIRELESS, WIRED), status=EXPERIMENTAL,
evidence=Evidence("The car shows every frame but never acknowledges one, so the comma gives up after 2.5 s; unacked it ran 100 s.",
("2026-11-16 sessions 1-15",)),
ladder=(UNACKED_VIDEO,),
summary="This car shows a still picture for a few seconds, then reconnects, over and over."),
)
@@ -106,7 +116,8 @@ def validate_rules(rules: tuple[Rule, ...] = RULES) -> list[str]:
if set(rule.match) != set(MATCH_FIELDS):
problems.append(f"{rule.id}: match must name exactly {MATCH_FIELDS}")
for key, value in rule.match.items():
if not value.strip() or any(char in value for char in "*?[]|^$\\"):
# Brackets are allowed: the Polestar 2 reports its model as "Polestar [AAR]".
if not value.strip() or any(char in value for char in "*?|^$\\"):
problems.append(f"{rule.id}: {key} must be a plain, non-empty string")
if not rule.evidence.failure or not rule.evidence.sessions:
problems.append(f"{rule.id}: evidence is required")
@@ -151,6 +151,8 @@ DEFAULT_CONFIG = {
"dedicated_wifi_interface": True, # join the car on its own aa0 station so wlan0 stays on home Wi-Fi
"allow_hevc": False, # offer H.265 when the car offers no usable H.264 mode (Galaxy Developer > StarPort)
"tall_hevc": False, # H.265 only: use the car's 1080x1920 mode when offered (Galaxy Developer > StarPort)
"unacked_video": False, # any codec: send video without waiting for the car's acknowledgments (Galaxy Developer > StarPort)
"patient_tcp": False, # wireless: keep retrying a refused projection connection for a minute (Galaxy Developer > StarPort)
"keyframe_test": False, # H.265 sessions only: every frame a keyframe, plus ack and frame logging (Galaxy Developer > StarPort)
"device_name": "StarPilot",
"version_status": 0, # WifiVersionResponse status (0 = success) for receivers that negotiate a version
@@ -205,6 +207,8 @@ def load_config(path: Path | None = None) -> dict:
config["allow_hevc"] = config["allow_hevc"] is True
config["keyframe_test"] = config["keyframe_test"] is True
config["tall_hevc"] = config["tall_hevc"] is True
config["unacked_video"] = config["unacked_video"] is True
config["patient_tcp"] = config["patient_tcp"] is True
config["head_unit_experiments"] = config["head_unit_experiments"] is True
config["head_unit_experiment_rules"] = sorted({str(rule)[:64] for rule in config["head_unit_experiment_rules"]
if isinstance(rule, str)})[:16]
+52 -5
View File
@@ -694,6 +694,12 @@ class ProjectionSession(Session):
# HeadunitPad acknowledges every fragment (codec config included) rather than every frame.
fragment_acks = False
# Owner toggle or head-unit fix, any codec: for cars that show video but never acknowledge it.
unacked_video = False
UNACKED_SILENCE_TIMEOUT = 5.0
unacked_started_at: float | None = None # when the first frame of an unacknowledged stream was sent
unacked_ack_seen = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.frame_fragments: deque[int] = deque()
@@ -876,6 +882,8 @@ class ProjectionSession(Session):
if self.vendor_channel is None:
self.vendor_channel = self._open_service(VENDOR_SERVICE, "vendor")
done = self.vendor_channel is not None
elif action == "unacked_video":
self.unacked_video = done = True
elif action == "request_bt_pairing":
if self.bluetooth_channel is not None and self.phone_address:
bluetooth = next((ch for ch in self.channels if ch.get("id") == self.bluetooth_channel), {})
@@ -1034,6 +1042,12 @@ class ProjectionSession(Session):
def _handle_ack(self, sid, count: int) -> None:
if sid in self.retired_sessions:
return
if self.unacked_video:
self.acked += count
if not self.unacked_ack_seen:
self.unacked_ack_seen = True
self.event("unexpected_video_ack", session=sid, count=count, frames_sent=self.frames_sent)
return
if self.fragment_acks:
if sid != self.session_id:
raise ValueError(f"Invalid video acknowledgement session={sid} count={count} pending={self.unacked}")
@@ -1086,6 +1100,8 @@ class ProjectionSession(Session):
# Altering this can degrade video smoothness or introduce lag on Android Auto.
# Do not change it autonomously; require an explicit user request specifically for this video optimization.
def can_send(self) -> bool:
if self.unacked_video:
return self.focused
return self.focused and self.unacked < self.window
def _ack_overdue(self, now: float) -> bool:
@@ -1106,16 +1122,43 @@ class ProjectionSession(Session):
now = time.monotonic()
if self._ack_overdue(now):
self._wait_out_radio_change(now)
if self.unacked_video:
now = self._check_unacked_video(now, measured)
# Only a receiver known to answer pings can be declared dead by silence; for
# others a lost link surfaces as a socket error or a dropped Wi-Fi lease.
if self.ping_responses and now - self.last_rx > 15.0:
raise TimeoutError("Head unit stopped answering for 15 s")
def _unacked_silent(self, now: float) -> bool:
started = self.unacked_started_at
return bool(self.focused and started is not None and now - max(self.last_rx, started) > self.UNACKED_SILENCE_TIMEOUT)
def _check_unacked_video(self, now: float, measured: bool) -> float:
"""Without ACKs a car that still talks is still there: give up on silence, and count video as shown once it has stayed."""
if self._unacked_silent(now):
deadline = time.monotonic() + self.ACK_DRAIN_SECONDS
while time.monotonic() < deadline and self.pump(0.0):
pass
if measured:
now = time.monotonic()
if self._unacked_silent(now):
raise TimeoutError(f"Head unit stopped answering for {self.UNACKED_SILENCE_TIMEOUT:.1f} s while projecting without video acknowledgments")
started = self.unacked_started_at
if (not self.video_confirmed and self.focused and started is not None and now - started > self.ACK_TIMEOUT and
self.last_rx > started):
self.video_confirmed = True
self.video_confirmed_at = started
self.event("video_acknowledged", session=self.session_id, ack_ms=None, unacked=True, frames_sent=self.frames_sent)
return now
def _wait_out_radio_change(self, now: float) -> None:
"""The oldest frame is past ACK_TIMEOUT: give up, unless the comma's other Wi-Fi just changed networks."""
oldest = self.pending[0]
if self.grace_frame != oldest:
if not self.radio_change():
if not self.acked and not self.video_confirmed:
self.event("video_never_acknowledged", frames_sent=self.frames_sent,
last_rx_ms=round((time.monotonic() - self.last_rx) * 1000))
raise TimeoutError(f"Video acknowledgement older than {self.ACK_TIMEOUT:.1f} s")
self.grace_frame = oldest
self.event("ack_grace", after_ms=round((now - oldest) * 1000))
@@ -1143,11 +1186,15 @@ class ProjectionSession(Session):
if self.phone_frames:
data = (wire_frame_hevc if self.mode.codec == CODEC_H265 else wire_frame)(data, drop_config=bool(config))
fragments += self.send(self.mode.channel, AV_MEDIA_WITH_TIMESTAMP, struct.pack(">Q", timestamp_us) + data)
if self.fragment_acks:
self.frame_fragments.append(fragments)
self.needs_keyframe = False
self.pending.append(time.monotonic())
self.unacked += 1
if self.unacked_video:
if self.unacked_started_at is None:
self.unacked_started_at = time.monotonic()
else:
if self.fragment_acks:
self.frame_fragments.append(fragments)
self.pending.append(time.monotonic())
self.unacked += 1
self.frames_sent += 1
if self.keyframe_test_active() and self.test_frames_logged < TEST_FRAMES_LOGGED:
self.test_frames_logged += 1
@@ -1180,4 +1227,4 @@ class ProjectionSession(Session):
return {"frames_sent": self.frames_sent, "frames_acked": self.acked, "pending": self.unacked,
"focus_epoch": self.focus_epoch, "focused": self.focused, "max_ack_ms": round(self.max_ack_seconds * 1000),
"input_events": self.input_events, "touch": self.touch is not None,
"sensor_events": sum(self.sensor_events.values())}
"sensor_events": sum(self.sensor_events.values()), **({"unacked_video": True} if self.unacked_video else {})}
@@ -57,6 +57,7 @@ SOFTWARE_FPS = 15 # libx264 cadence; the hardware encoder runs at 30
UNAVAILABLE_AFTER = 1.0 # focused but no fresh UI frame for this long -> "unavailable" card; the Honda gives the screen back after 3 s without video
SDP_SETTLE = (1.5, 2.2, 3.0)
TCP_ATTEMPTS = 6
PATIENT_TCP_SECONDS = 60.0 # owner toggle: keep retrying a refused projection connection this long
MAX_LOG_FILES = 20
LOG_QUEUE_MAX = 1000 # session log records waiting for the writer; past this they are dropped and counted
ENCODER_RECOVERIES = 3 # hardware encoder reopens allowed per window before the session is torn down
@@ -81,7 +82,7 @@ STALL_CAPTURE_S = 20.0 # device logs kept from before a shared-radio stall
REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrate_kbps", "rate_control", "gpu_nv12",
"async_readback", "wifi_interface", "dedicated_wifi_interface", "verify_head_unit", "version_status",
"rfcomm_channel", "phone_class", "auto_connect", "allow_hevc", "keyframe_test", "tall_hevc",
"head_unit_experiments", "head_unit_experiment_rules")
"unacked_video", "patient_tcp", "head_unit_experiments", "head_unit_experiment_rules")
def _tcp_failure_kind(error: OSError) -> str:
@@ -532,6 +533,8 @@ class Supervisor:
status["allow_hevc"] = bool(self.config["allow_hevc"])
status["keyframe_test"] = bool(self.config["keyframe_test"])
status["tall_hevc"] = bool(self.config["tall_hevc"])
status["unacked_video"] = bool(self.config["unacked_video"])
status["patient_tcp"] = bool(self.config["patient_tcp"])
status["head_unit_experiments"] = bool(self.config["head_unit_experiments"])
status["head_unit_experiment_rules"] = list(self.config["head_unit_experiment_rules"])
status["experimental_fixes"] = head_unit_fixes.experimental_entries()
@@ -588,6 +591,20 @@ class Supervisor:
identity_store.save_config(self.config)
self.log("tall_hevc_selected", enabled=bool(enabled))
def set_unacked_video(self, enabled: bool) -> None:
"""Sessions send video without waiting for the car's acknowledgments, on any codec; used from the next session."""
with self._lock:
self.config["unacked_video"] = bool(enabled)
identity_store.save_config(self.config)
self.log("unacked_video_selected", enabled=bool(enabled))
def set_patient_tcp(self, enabled: bool) -> None:
"""Keep retrying a refused projection connection for up to a minute; used from the next connection."""
with self._lock:
self.config["patient_tcp"] = bool(enabled)
identity_store.save_config(self.config)
self.log("patient_tcp_selected", enabled=bool(enabled))
def set_head_unit_experiments(self, enabled: bool) -> None:
"""The master switch for car and dongle fixes; off gives the standard connection to every car from the next session."""
with self._lock:
@@ -1994,7 +2011,9 @@ class Supervisor:
def _connect_tcp(self, result, lease) -> socket.socket:
self._stage("connecting_tcp", f"{result.endpoint.ip}:{result.endpoint.port}")
last_error: Exception | None = None
for attempt in range(TCP_ATTEMPTS):
patient_until = time.monotonic() + PATIENT_TCP_SECONDS if self.config["patient_tcp"] else 0.0
attempt = 0
while True:
self._check_cancel()
try:
sock = socket.create_connection((result.endpoint.ip, result.endpoint.port), timeout=5.0,
@@ -2003,8 +2022,12 @@ class Supervisor:
return self._track(sock)
except OSError as error:
last_error = error
self.log("tcp_retry", attempt=attempt + 1, error=str(error), kind=_tcp_failure_kind(error))
self._wait(1.0 + attempt * 0.5)
kind = _tcp_failure_kind(error)
self.log("tcp_retry", attempt=attempt + 1, error=str(error), kind=kind)
self._wait(min(1.0 + attempt * 0.5, 3.5))
attempt += 1
if attempt >= TCP_ATTEMPTS and not (kind == "refused" and time.monotonic() < patient_until):
break
raise RuntimeError(f"Car did not accept the projection connection: {last_error}")
def _unofficial_dongle(self) -> bool:
@@ -2045,6 +2068,7 @@ class Supervisor:
session.allow_hevc = bool(config["allow_hevc"])
session.keyframe_test = bool(config["keyframe_test"])
session.tall_hevc = bool(config["tall_hevc"])
session.unacked_video = bool(config["unacked_video"])
if tuning["phone_services"]:
session.phone_services = True
session.phone_address = self._adapter_address()
@@ -31,6 +31,25 @@ def test_validate_rejects_missing_evidence():
assert hf.validate_rules((bad,))
POLESTAR = {"car_make": "Polestar", "car_model": "PS2", "car_year": "2022", "head_unit_make": "VolvoCars",
"head_unit_model": "Polestar [AAR]",
"head_unit_software_version": "AAR.301433653 (6.1 (aareceiver_20260609.02_RC11 RELEASE PROD 1004961323)) 1"}
def test_a_bracketed_head_unit_model_is_allowed():
"""Brackets are literal in an exact match, so they cannot widen a rule."""
rule = next(r for r in hf.RULES if r.match["head_unit_model"] == "Polestar [AAR]")
assert hf.validate_rules((rule,)) == []
assert hf.matches(rule, POLESTAR)
assert not hf.matches(rule, {**POLESTAR, "head_unit_model": "Polestar [AAX]"})
@pytest.mark.parametrize("wildcard", ["AAR.*", "AAR.?01433653", "a|b", "^AAR", "AAR$"])
def test_wildcards_are_still_rejected(wildcard):
bad = replace(RULE, match={**RULE.match, "head_unit_software_version": wildcard})
assert hf.validate_rules((bad,))
@pytest.mark.parametrize("build", ["W46E-V164.3.1-MIHS21A-127", "W48E-V167.3.1-MIHS21A-131", "W59E-V176.5.2-MIHS21A-193", "<ip>", ""])
def test_other_builds_do_not_match(build):
labels = {**BOLT, "head_unit_software_version": build}
@@ -45,6 +45,15 @@ def test_portrait_frames_pass_every_size_check(tmp_path):
consumer.close()
def test_the_tall_hevc_mode_is_accepted_by_the_screen_profile():
"""Whatever mode choose_video_mode selects must pass validate_screen."""
mode = choose_video_mode(POLESTAR, True, True)
assert (mode.width, mode.height, mode.codec) == (1080, 1920, CODEC_H265)
validate_screen({"version": 1, "width": mode.width, "height": mode.height,
"margin_width": mode.margin_width, "margin_height": mode.margin_height,
"fps": mode.fps, "config_index": mode.config_index})
@pytest.mark.parametrize("encoder", [HardwareH264Encoder, HardwareHevcEncoder])
def test_hardware_encoders_accept_portrait_and_reject_oversized(encoder, tmp_path):
with pytest.raises(ValueError, match="Hardware encoder supports"):
@@ -0,0 +1,60 @@
from types import SimpleNamespace
from openpilot.starpilot.system.starport import supervisor as sup
class Clock:
def __init__(self):
self.now = 1000.0
def fake_supervisor(clock, patient):
waits, logs = [], []
def wait(seconds):
waits.append(seconds)
clock.now += seconds
return SimpleNamespace(config={"patient_tcp": patient}, _stage=lambda *a: None, _check_cancel=lambda: None, _wait=wait,
_track=lambda sock: sock, log=lambda name, **v: logs.append((name, v))), waits, logs
def run(monkeypatch, patient, error, succeed_after=None):
clock = Clock()
monkeypatch.setattr(sup.time, "monotonic", lambda: clock.now)
calls = []
class Sock:
def setsockopt(self, *a):
pass
def connect(*a, **k):
calls.append(clock.now)
if succeed_after is not None and len(calls) > succeed_after:
return Sock()
raise error
monkeypatch.setattr(sup.socket, "create_connection", connect)
self, waits, logs = fake_supervisor(clock, patient)
result = SimpleNamespace(endpoint=SimpleNamespace(ip="192.168.1.101", port=1234))
lease = SimpleNamespace(local_ip="")
try:
return sup.Supervisor._connect_tcp(self, result, lease), calls
except RuntimeError:
return None, calls
REFUSED = ConnectionRefusedError(111, "Connection refused")
def test_default_gives_up_after_the_usual_attempts(monkeypatch):
sock, calls = run(monkeypatch, False, REFUSED)
assert sock is None and len(calls) == sup.TCP_ATTEMPTS
def test_patient_keeps_trying_a_refused_connection_for_a_minute(monkeypatch):
sock, calls = run(monkeypatch, True, REFUSED)
assert sock is None and len(calls) > sup.TCP_ATTEMPTS
assert sup.PATIENT_TCP_SECONDS <= calls[-1] - calls[0] + 3.0 <= sup.PATIENT_TCP_SECONDS + 6.0
sock, calls = run(monkeypatch, True, REFUSED, succeed_after=15)
assert sock is not None and len(calls) == 16
def test_patient_does_not_stretch_other_errors(monkeypatch):
sock, calls = run(monkeypatch, True, TimeoutError("timed out"))
assert sock is None and len(calls) == sup.TCP_ATTEMPTS
@@ -0,0 +1,207 @@
"""A head unit that shows video but never acknowledges it."""
import time
from pathlib import Path
import pytest
from openpilot.starpilot.system.starport import head_unit_fixes as hf
from openpilot.starpilot.system.starport.quirk_state import QuirkState
from openpilot.starpilot.system.starport.session import CODEC_H265, MSG_PING_REQUEST, ProjectionSession
from openpilot.starpilot.system.starport.tests.fake_head_unit import FakeHeadUnit, make_identity
from openpilot.starpilot.system.starport.tests.test_starport import connect, delta_au, keyframe_au, pump_until
from openpilot.starpilot.system.starport.wire import field
POLESTAR_RULE = next(rule for rule in hf.RULES if rule.id == "polestar_ps2_aar_301433653")
POLESTAR = dict(POLESTAR_RULE.match)
ON = {"head_unit_experiments": True, "head_unit_experiment_rules": [POLESTAR_RULE.id]}
@pytest.fixture(scope="module")
def identity(tmp_path_factory):
return make_identity(tmp_path_factory.mktemp("unacked-identity"))
def pick(config, transport="wired", key="usb:polestar"):
return hf.select(config, POLESTAR, transport, QuirkState(Path("/nonexistent/q.json")), key, car_type="usb", profile="default")
def silent_car_session(identity, *, fix: bool):
"""A session with a car that takes video and never acknowledges it, config or frames."""
hu = FakeHeadUnit(identity, ack_codec_config=False)
hu.hold_acks.set()
session = connect(hu, identity)
events: list[tuple[str, dict]] = []
session._log = lambda name, **values: events.append((name, values))
if fix:
session.on_discovered = lambda info: (hf.UNACKED_VIDEO,)
session.authenticate()
session.start("StarPilot", "comma.ai")
pump_until(session, lambda: session.focused)
return hu, session, events
def send_frames(hu, session, count):
sent = 0
for tag in range(count):
if not session.can_send():
break
session.send_frame(keyframe_au(tag) if tag == 0 else delta_au(tag), tag + 1, keyframe=tag == 0)
sent += 1
deadline = time.monotonic() + 5
while len(hu.frames) < sent:
assert time.monotonic() < deadline, "the car never received the frames"
time.sleep(0.01)
return sent
def end(session, hu):
hu.close()
session.peer.close()
def names(events):
return [name for name, _ in events]
# ------------------------------------------------------------------ the rule
def test_the_polestar_rule_is_the_one_action_and_nothing_a_phone_opens():
assert POLESTAR_RULE.ladder == (hf.UNACKED_VIDEO,)
assert hf.validate_rules() == []
def test_the_fix_needs_the_owners_opt_in_and_works_wired_or_wireless():
assert pick({}) is None
assert pick({**ON, "head_unit_experiments": False}) is None
for transport, key in (("wired", "usb:polestar"), ("wireless", "bt:AA")):
selection = pick(ON, transport=transport, key=key)
assert selection is not None and selection.actions == (hf.UNACKED_VIDEO,)
def test_another_build_of_the_same_car_does_not_get_it():
other = {**POLESTAR, "head_unit_software_version": "AAR.301433654 (6.1) 1"}
quirks = QuirkState(Path("/nonexistent/q.json"))
assert hf.select(ON, other, "wired", quirks, "usb:other", car_type="usb", profile="default") is None
assert hf.near_miss(POLESTAR_RULE, other)
# --------------------------------------------------------------- the session
def test_without_the_fix_the_car_stalls_at_the_window_and_times_out(identity):
hu, session, events = silent_car_session(identity, fix=False)
assert not session.unacked_video
assert send_frames(hu, session, 10) == session.window # the window never reopens
assert not session.can_send()
session.last_rx = time.monotonic() # the car is still talking: it pings throughout
with pytest.raises(TimeoutError, match="Video acknowledgement older than 2.5 s"):
session.check_progress(now=session.pending[0] + ProjectionSession.ACK_TIMEOUT + 0.05)
never = [values for name, values in events if name == "video_never_acknowledged"]
assert len(never) == 1 and never[0]["frames_sent"] == session.window and never[0]["last_rx_ms"] < 1000
end(session, hu)
def test_a_car_that_acknowledged_before_is_not_reported_as_never_acknowledging(identity):
hu = FakeHeadUnit(identity)
session = connect(hu, identity)
events: list[tuple[str, dict]] = []
session._log = lambda name, **values: events.append((name, values))
session.authenticate()
session.start("StarPilot", "comma.ai")
pump_until(session, lambda: session.focused)
session.send_frame(keyframe_au(1), 1, keyframe=True)
pump_until(session, lambda: not session.pending and not session.config_ack_slack) # frame and codec config ACKs both in
hu.hold_acks.set()
session.send_frame(delta_au(2), 2, keyframe=False)
with pytest.raises(TimeoutError, match="Video acknowledgement older"):
session.check_progress(now=session.pending[0] + ProjectionSession.ACK_TIMEOUT + 0.05)
assert "video_never_acknowledged" not in names(events)
end(session, hu)
def test_with_the_fix_video_keeps_going_past_the_window(identity):
hu, session, events = silent_car_session(identity, fix=True)
assert session.unacked_video
assert ("fix_action", {"action": hf.UNACKED_VIDEO, "done": True}) in events
count = session.window * 4
assert send_frames(hu, session, count) == count
assert len(hu.frames) == count and session.frames_sent == count
assert session.can_send() and not session.pending and session.unacked == 0 # nothing is waited for or accumulated
assert session.stats()["unacked_video"] is True
session.last_rx = time.monotonic()
session.check_progress(now=session.unacked_started_at + ProjectionSession.ACK_TIMEOUT - 0.5)
assert not session.video_confirmed # too soon: an acknowledging car would not have been given up on yet
session.check_progress(now=session.unacked_started_at + ProjectionSession.ACK_TIMEOUT + 0.05)
assert session.video_confirmed and session.video_confirmed_at == session.unacked_started_at
confirmed = [values for name, values in events if name == "video_acknowledged"]
assert confirmed == [{"session": session.session_id, "ack_ms": None, "unacked": True, "frames_sent": count}]
session.last_rx = time.monotonic()
session.check_progress() # and it stays up while the car talks
end(session, hu)
def test_with_the_fix_a_silent_car_still_ends_the_session(identity):
hu, session, _ = silent_car_session(identity, fix=True)
send_frames(hu, session, 3)
started = session.unacked_started_at
session.last_rx = started - 1.0 # nothing from the car since before the first frame
session.check_progress(now=started + ProjectionSession.UNACKED_SILENCE_TIMEOUT - 0.5)
with pytest.raises(TimeoutError, match="Head unit stopped answering for 5.0 s while projecting without video acknowledgments"):
session.check_progress(now=started + ProjectionSession.UNACKED_SILENCE_TIMEOUT + 1.0)
assert not session.video_confirmed # a car that went quiet straight away never counted as showing video
end(session, hu)
def test_with_the_fix_a_message_already_in_the_socket_is_read_before_calling_the_car_silent(identity):
hu, session, _ = silent_car_session(identity, fix=True)
send_frames(hu, session, 1)
while session.pump(0.2):
pass
session.unacked_started_at -= 30.0 # well into the stream
session.last_rx = time.monotonic() - ProjectionSession.UNACKED_SILENCE_TIMEOUT - 1.0 # this loop stalled; the car did not
session.send(0, MSG_PING_REQUEST, field(1, 1)) # our ping: the car's answer is now waiting unread
deadline = time.monotonic() + 5
while hu.messages_seen.get((0, MSG_PING_REQUEST), 0) == 0:
assert time.monotonic() < deadline
time.sleep(0.01)
time.sleep(0.1)
session.check_progress() # reads the answer instead of raising
assert time.monotonic() - session.last_rx < 1.0
end(session, hu)
def test_with_the_fix_an_acknowledgment_is_counted_and_never_fatal(identity):
hu, session, events = silent_car_session(identity, fix=True)
send_frames(hu, session, 2)
session._handle_ack(session.session_id, 5) # more than was ever sent: fatal for a car that is waited on
session._handle_ack(session.session_id, 1)
assert session.acked == 6 and session.unacked == 0
assert names(events).count("unexpected_video_ack") == 1
end(session, hu)
def test_the_fix_does_not_touch_a_car_that_acknowledges(identity):
hu = FakeHeadUnit(identity)
session = connect(hu, identity)
session.authenticate()
session.start("StarPilot", "comma.ai")
pump_until(session, lambda: session.focused)
assert not session.unacked_video and "unacked_video" not in session.stats()
session.send_frame(keyframe_au(1), 1, keyframe=True)
assert session.unacked == 1 and len(session.pending) == 1 and session.unacked_started_at is None
pump_until(session, lambda: session.acked == 1 and not session.pending)
end(session, hu)
def test_the_owner_toggle_works_on_h264_without_any_fix(identity):
hu = FakeHeadUnit(identity, ack_codec_config=False)
hu.hold_acks.set()
session = connect(hu, identity)
session.unacked_video = True
session.authenticate()
session.start("StarPilot", "comma.ai")
pump_until(session, lambda: session.focused)
assert session.mode.codec != CODEC_H265
count = session.window * 3
assert send_frames(hu, session, count) == count
assert session.can_send() and not session.pending
end(session, hu)