mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-30 00:33:41 +08:00
StarPort: Default AA Fallback, Fallback IP, and Skip Step 1 for Unofficial Dongles
This commit is contained in:
@@ -259,10 +259,7 @@ class StarPortLogSender:
|
||||
def status(self) -> dict:
|
||||
with self._lock:
|
||||
if self._fork is None:
|
||||
try:
|
||||
self._fork = not self._official()
|
||||
except Exception:
|
||||
self._fork = False
|
||||
self._fork = not self._official()
|
||||
return {**self._state, "available": bool(self._url()), "fork": self._fork, "messageLimit": MESSAGE_LIMIT}
|
||||
|
||||
def start(self, message, discord="") -> dict:
|
||||
|
||||
@@ -256,6 +256,13 @@ class DiscordFollowUpTest(unittest.TestCase):
|
||||
job.start("hi", "not a handle")
|
||||
self.assertIsNone(job._thread)
|
||||
|
||||
def test_a_failed_fork_check_is_raised_and_retried(self):
|
||||
official = mock.Mock(side_effect=[OSError("no metadata"), True])
|
||||
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=mock.Mock(), summary=lambda: SUMMARY, url=lambda: URL, official=official)
|
||||
with self.assertRaises(OSError):
|
||||
job.status()
|
||||
self.assertFalse(job.status()["fork"])
|
||||
|
||||
def test_custom_forks_are_flagged_but_can_still_send(self):
|
||||
from openpilot.starpilot.system.starport.bugsink_transport import is_official_repo, repo_name
|
||||
for origin, repo in (("https://github.com/StarPilotHQ/StarPilot.git", "StarPilotHQ/StarPilot"),
|
||||
|
||||
@@ -11,7 +11,7 @@ RULES: list[dict] = [
|
||||
{"id": "aawireless", "label": "AAWireless", "match": {},
|
||||
"tuning": {"max_window": 30, "phone_services": True, "phone_frames": True, "stay_while_projecting": True,
|
||||
"dhcp_patience_s": 6.0, "own_handsfree": True, "static_ip": True}},
|
||||
{"id": "unofficial", "label": "Unofficial dongle", "match": {}, "tuning": {"bootstrap_experiments": True}},
|
||||
{"id": "unofficial", "label": "Unofficial dongle", "match": {}, "tuning": {"bootstrap_experiments": True, "dhcp_patience_s": 6.0}},
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -305,12 +305,15 @@ class Session:
|
||||
DISCOVERY_TIMEOUT = 60.0
|
||||
|
||||
def __init__(self, peer, cert: str, key: str, log: Callable[..., None] | None = None, ca: str | None = None, *,
|
||||
receive_timeout: float = 3.0, send_timeout: float = 3.0, handshake_timeout: float = 15.0):
|
||||
receive_timeout: float = 3.0, send_timeout: float = 3.0, handshake_timeout: float = 15.0,
|
||||
version_wait: float | None = None):
|
||||
self.peer = peer
|
||||
self._log = log
|
||||
self.receive_timeout = self._timeout(receive_timeout)
|
||||
self.send_timeout = self._timeout(send_timeout)
|
||||
self.handshake_timeout = self._timeout(handshake_timeout)
|
||||
# Relaying adapters ping until the car starts its own session
|
||||
self.version_wait = max(self.handshake_timeout, self._timeout(version_wait)) if version_wait is not None else self.handshake_timeout
|
||||
self.authenticated = False
|
||||
self.head_unit_subject: str = ""
|
||||
self.incoming = ssl.MemoryBIO()
|
||||
@@ -473,14 +476,15 @@ class Session:
|
||||
def authenticate(self) -> None:
|
||||
# Some wireless adapters send a control keepalive before their version request.
|
||||
# A pong keeps the transport alive; version, TLS and certificate checks remain mandatory.
|
||||
deadline = time.monotonic() + self.handshake_timeout
|
||||
started = time.monotonic()
|
||||
deadline = started + self.version_wait
|
||||
pings = 0
|
||||
while True:
|
||||
channel, kind, data = self.receive(deadline=deadline)
|
||||
if channel != 0 or kind != MSG_PING_REQUEST:
|
||||
break
|
||||
pings += 1
|
||||
if pings > 8 or len(data) > 64:
|
||||
if pings > 8 + 3 * (time.monotonic() - started) or len(data) > 64:
|
||||
raise ValueError('Excessive pre-version Android Auto keepalive')
|
||||
fields = parse_fields(data)
|
||||
timestamps = fields.get(1, [])
|
||||
|
||||
@@ -41,6 +41,7 @@ DESCRIPTIONS = {
|
||||
"patient": "Waits up to twice as long for the receiver to send its Wi-Fi details.",
|
||||
"experiments": "Tries the extra message variations some adapters need.",
|
||||
}
|
||||
UNOFFICIAL_FIRST = "other_reply" # the reply known unofficial dongles answer
|
||||
MODERN_RUNGS = ("other_reply", "modern_dual", "modern_24ghz", "phone_identity") # only mean something to a car that speaks protocol 4 or newer
|
||||
|
||||
|
||||
@@ -219,7 +220,7 @@ class SetupLadder:
|
||||
entry = self.cars.get(address.upper())
|
||||
return bool(entry) and entry["boot"] == self.boot_id() and entry["passes"] >= MAX_PASSES and not entry["working"]
|
||||
|
||||
def strategy(self, address: str, base_modern: bool) -> Strategy:
|
||||
def strategy(self, address: str, base_modern: bool, unofficial: bool = False) -> Strategy:
|
||||
"""What to try now: the strategy that worked, else the current rung (standard once the passes are used up)."""
|
||||
entry = self._entry(address)
|
||||
working = _valid_strategy(entry["working"])
|
||||
@@ -227,6 +228,8 @@ class SetupLadder:
|
||||
return working
|
||||
if entry["passes"] >= MAX_PASSES:
|
||||
return resolve("standard", base_modern)
|
||||
if unofficial and entry["rung"] == "standard" and not entry["results"] and not entry["passes"]:
|
||||
entry["rung"] = UNOFFICIAL_FIRST
|
||||
return resolve(entry["rung"], base_modern)
|
||||
|
||||
def failed(self, address: str, strategy: Strategy, *, ladder_failure: bool, video_seen: bool, version_major: int,
|
||||
|
||||
@@ -60,6 +60,8 @@ UNAVAILABLE_AFTER = 1.0 # focused but no fresh UI frame for this long -> "u
|
||||
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
|
||||
STANDARD_AA_PORT = 5288
|
||||
VERSION_WAIT_SECONDS = 90.0
|
||||
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
|
||||
@@ -85,6 +87,21 @@ REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrat
|
||||
"unacked_video", "patient_tcp", "head_unit_experiments", "head_unit_experiment_rules")
|
||||
|
||||
|
||||
def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket:
|
||||
error: OSError | None = None
|
||||
for port in ports:
|
||||
try:
|
||||
sock = socket.create_connection((ip, port), timeout=5.0, source_address=(local_ip, 0) if local_ip else None)
|
||||
except OSError as failure:
|
||||
error = error or failure # the first port's failure decides how patiently to retry
|
||||
continue
|
||||
if port != advertised:
|
||||
log("tcp_port_fallback", advertised=advertised, port=port)
|
||||
return sock
|
||||
assert error is not None
|
||||
raise error
|
||||
|
||||
|
||||
def _tcp_failure_kind(error: OSError) -> str:
|
||||
if isinstance(error, (TimeoutError, socket.timeout)):
|
||||
return "timeout"
|
||||
@@ -1629,7 +1646,7 @@ class Supervisor:
|
||||
# only when a car that answered the handshake keeps refusing it before any video.
|
||||
with self._lock:
|
||||
base_modern = self._modern_reply.get(address, config.get("modern_reply_cache", {}).get(address, False))
|
||||
strategy = self._strategy = self._ladder.strategy(address, base_modern)
|
||||
strategy = self._strategy = self._ladder.strategy(address, base_modern, unofficial)
|
||||
learned = self._ladder.snapshot(address, adapter, unofficial)["learned"]
|
||||
tries = self._ladder.tried(address, strategy.rung)
|
||||
self.log("ladder_strategy", rung=strategy.rung, label=strategy.label, learned=learned, modern_reply=strategy.modern_reply,
|
||||
@@ -1669,7 +1686,7 @@ class Supervisor:
|
||||
video_seen=self._video_seen, version_major=boot.version_major if boot is not None else 0,
|
||||
adapter=adapter, unofficial=unofficial)
|
||||
if outcome:
|
||||
self.log("ladder_failed", outcome=outcome, rung=strategy.rung, next=self._ladder.strategy(address, base_modern).rung,
|
||||
self.log("ladder_failed", outcome=outcome, rung=strategy.rung, next=self._ladder.strategy(address, base_modern, unofficial).rung,
|
||||
version_major=boot.version_major, reason="rejected_reply" if rejected else "timeout", why=reason)
|
||||
elif boot is not None and isinstance(error, BootstrapTimeout) and error.stage == "wifi_start" and boot.only_not_ready():
|
||||
self.log("ladder_not_ready", rung=strategy.rung, refusals=len(boot.refusals))
|
||||
@@ -1963,11 +1980,13 @@ class Supervisor:
|
||||
last_error: Exception | None = None
|
||||
patient_until = time.monotonic() + PATIENT_TCP_SECONDS if self.config["patient_tcp"] else 0.0
|
||||
attempt = 0
|
||||
advertised = result.endpoint.port
|
||||
# Some dongles advertise one port but listen on the standard one
|
||||
ports = list(dict.fromkeys((advertised, STANDARD_AA_PORT)))
|
||||
while True:
|
||||
self._check_cancel()
|
||||
try:
|
||||
sock = socket.create_connection((result.endpoint.ip, result.endpoint.port), timeout=5.0,
|
||||
source_address=(lease.local_ip, 0) if lease.local_ip else None)
|
||||
sock = _open_projection(result.endpoint.ip, ports, advertised, lease.local_ip, self.log)
|
||||
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
return self._track(sock)
|
||||
except OSError as error:
|
||||
@@ -2010,7 +2029,8 @@ class Supervisor:
|
||||
config = self.config
|
||||
sock = connect() if connect is not None else self._connect_tcp(result, lease)
|
||||
ca = ident.root if config.get("verify_head_unit", False) else None
|
||||
session = ProjectionSession(sock, ident.cert, ident.key, self.log, ca)
|
||||
version_wait = VERSION_WAIT_SECONDS if self.car_type() == "adapter" else None
|
||||
session = ProjectionSession(sock, ident.cert, ident.key, self.log, ca, version_wait=version_wait)
|
||||
session.fragment_acks = fragment_acks
|
||||
tuning = car_profiles.tuning(config)
|
||||
session.max_window = tuning["max_window"]
|
||||
|
||||
@@ -322,7 +322,7 @@ def test_projection_verifies_head_unit_only_when_chosen(identity, tmp_path, monk
|
||||
pass
|
||||
|
||||
class RecordingSession:
|
||||
def __init__(self, sock, cert, key, log, ca):
|
||||
def __init__(self, sock, cert, key, log, ca, **kwargs):
|
||||
seen.append(ca)
|
||||
|
||||
def authenticate(self):
|
||||
@@ -334,6 +334,29 @@ def test_projection_verifies_head_unit_only_when_chosen(identity, tmp_path, monk
|
||||
assert seen == [ident.root if verified else None]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("car_type, wait", [("adapter", 90.0), ("built_in", None)])
|
||||
def test_only_adapters_wait_long_for_the_version_request(identity, tmp_path, monkeypatch, car_type, wait):
|
||||
from openpilot.starpilot.system.starport import identity as identity_store, supervisor
|
||||
sup, _ = make_supervisor(identity, tmp_path, monkeypatch, lambda *a, **k: socket.socketpair()[0])
|
||||
monkeypatch.setattr(sup, "car_type", lambda: car_type)
|
||||
seen = []
|
||||
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
class RecordingSession:
|
||||
def __init__(self, sock, cert, key, log, ca, **kwargs):
|
||||
seen.append(kwargs.get("version_wait"))
|
||||
|
||||
def authenticate(self):
|
||||
raise Stop
|
||||
|
||||
monkeypatch.setattr(supervisor, "ProjectionSession", RecordingSession)
|
||||
with pytest.raises(Stop):
|
||||
sup._project(None, None, identity_store.load_identity(), connect=lambda: socket.socketpair()[0])
|
||||
assert seen == [wait]
|
||||
|
||||
|
||||
def _wireless_backoff_harness(sup, monkeypatch, failure):
|
||||
from openpilot.starpilot.system.starport import supervisor
|
||||
now = [100.0]
|
||||
|
||||
@@ -157,3 +157,25 @@ def test_repeated_pings_do_not_reset_version_deadline(identity):
|
||||
worker.join(1)
|
||||
session.peer.close()
|
||||
hu.close()
|
||||
|
||||
|
||||
def test_relaying_adapter_may_ping_past_the_handshake_timeout(identity):
|
||||
events = []
|
||||
session, hu = raw_session(identity, handshake_timeout=.5, version_wait=5.0, log=lambda name, **v: events.append(name))
|
||||
def relay():
|
||||
for i in range(12):
|
||||
hu.sendall(frame(0, 0x0b, field(1, i)))
|
||||
time.sleep(.2)
|
||||
time.sleep(.2)
|
||||
hu.sendall(frame(0, 0x01, b'\x00\x01\x00\x07'))
|
||||
worker = threading.Thread(target=relay, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
with pytest.raises((TimeoutError, OSError)):
|
||||
session.authenticate()
|
||||
assert events.count('pre_version_ping') == 12 and 'version' in events
|
||||
assert not session.authenticated
|
||||
finally:
|
||||
worker.join(2)
|
||||
session.peer.close()
|
||||
hu.close()
|
||||
|
||||
@@ -17,14 +17,18 @@ def fake_supervisor(clock, patient):
|
||||
_track=lambda sock: sock, log=lambda name, **v: logs.append((name, v))), waits, logs
|
||||
|
||||
|
||||
def run(monkeypatch, patient, error, succeed_after=None):
|
||||
def run(monkeypatch, patient, error, succeed_after=None, open_port=None):
|
||||
clock = Clock()
|
||||
monkeypatch.setattr(sup.time, "monotonic", lambda: clock.now)
|
||||
calls = []
|
||||
class Sock:
|
||||
def setsockopt(self, *a):
|
||||
pass
|
||||
def connect(*a, **k):
|
||||
def connect(address, *a, **k):
|
||||
if address[1] == open_port:
|
||||
return Sock()
|
||||
if address[1] != 1234:
|
||||
raise REFUSED
|
||||
calls.append(clock.now)
|
||||
if succeed_after is not None and len(calls) > succeed_after:
|
||||
return Sock()
|
||||
@@ -34,27 +38,39 @@ def run(monkeypatch, patient, error, succeed_after=None):
|
||||
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
|
||||
return sup.Supervisor._connect_tcp(self, result, lease), calls, logs
|
||||
except RuntimeError:
|
||||
return None, calls
|
||||
return None, calls, logs
|
||||
|
||||
|
||||
REFUSED = ConnectionRefusedError(111, "Connection refused")
|
||||
|
||||
|
||||
def test_default_gives_up_after_the_usual_attempts(monkeypatch):
|
||||
sock, calls = run(monkeypatch, False, REFUSED)
|
||||
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)
|
||||
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)
|
||||
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"))
|
||||
sock, calls, _ = run(monkeypatch, True, TimeoutError("timed out"))
|
||||
assert sock is None and len(calls) == sup.TCP_ATTEMPTS
|
||||
|
||||
|
||||
def test_refused_advertised_port_falls_back_to_the_standard_port(monkeypatch):
|
||||
sock, calls, logs = run(monkeypatch, False, REFUSED, open_port=sup.STANDARD_AA_PORT)
|
||||
assert sock is not None and len(calls) == 1
|
||||
assert ("tcp_port_fallback", {"advertised": 1234, "port": sup.STANDARD_AA_PORT}) in logs
|
||||
|
||||
|
||||
def test_a_timed_out_advertised_port_also_falls_back(monkeypatch):
|
||||
sock, calls, logs = run(monkeypatch, False, TimeoutError("timed out"), open_port=sup.STANDARD_AA_PORT)
|
||||
assert sock is not None and len(calls) == 1
|
||||
assert ("tcp_port_fallback", {"advertised": 1234, "port": sup.STANDARD_AA_PORT}) in logs
|
||||
|
||||
@@ -512,3 +512,28 @@ def test_a_reset_during_a_session_is_written_at_once(sup, monkeypatch):
|
||||
def test_only_galaxy_can_reset_the_handshake():
|
||||
from openpilot.starpilot.system.starport import daemon
|
||||
assert "reset_handshake" in daemon.AUTHENTICATED_COMMANDS
|
||||
|
||||
|
||||
def test_unofficial_dongle_starts_at_the_other_reply(ladder):
|
||||
assert ladder.strategy(CAR, False, unofficial=True).rung == "other_reply"
|
||||
assert ladder.strategy(CAR, False, unofficial=True).modern_reply is True
|
||||
|
||||
|
||||
def test_unofficial_dongle_still_reaches_standard_after_a_full_pass(ladder):
|
||||
seen = []
|
||||
for _ in range(len(sl.RUNGS)):
|
||||
strategy = ladder.strategy(CAR, False, unofficial=True)
|
||||
seen.append(strategy.rung)
|
||||
if refuse(ladder, strategy, adapter=True, unofficial=True) in ("wrapped", "exhausted"):
|
||||
break
|
||||
assert seen[0] == "other_reply" and "standard" not in seen
|
||||
assert ladder.strategy(CAR, False, unofficial=True).rung == "standard"
|
||||
|
||||
|
||||
def test_unofficial_dongle_keeps_what_worked(ladder):
|
||||
ladder.worked(CAR, sl.resolve("standard", False))
|
||||
assert ladder.strategy(CAR, False, unofficial=True).rung == "standard"
|
||||
|
||||
|
||||
def test_other_receivers_still_start_at_standard(ladder):
|
||||
assert ladder.strategy(CAR, False).rung == "standard"
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "05c49bd791d78b58a070246b534f788e779de8dda55c8b4a6ea248256b6b4602", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "f7b554f3afffab7bb90aa74b865f5081b69aa98f1a02094966978c62e2cf87b5", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user