Files
StarPilot/openpilot/starpilot/controllers/tesla_input_worker.py
T
Claude f67edb6529 Tesla Model 3/Y: controls work with nothing saved, and three recovery fixes
- The input worker never parsed its settings on an install where CarControlAssignments had never been saved, so no
  scroll, stalk press or nudge reached the comma until a Wheel Controls row was changed. It now starts from the
  defaults.
- Saved assignments are used on either model: a Model 3 and a Model Y have the same controls. Before, a document
  saved on the other model gave no controls and locked every Wheel Controls row.
- Speed sync no longer waits for the Tesla's own speed to change after unanswered requests once the comma's speed is
  on the other side of the Tesla's (the Tesla had been at its own lowest or highest set speed).
- The UI restarts a stopped input worker after a wait that grows from 2 s to 30 s, instead of at most three times a
  drive. A first start that fails is retried on the same wait, not every frame.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 20:12:29 +00:00

194 lines
8.1 KiB
Python

"""Tesla input worker. Receive-only CAN; never invokes vehicle/UI actions."""
import os
import select
import secrets
import socket
import sys
import time
def configure_worker():
# A subprocess can inherit UI FIFO policy/affinity at startup. This is solely
# the new custom worker's policy, not a change to any stock process.
os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0))
os.setpriority(os.PRIO_PROCESS, 0, 10)
os.sched_setaffinity(0, {0, 1, 2, 3})
if __name__ == '__main__':
configure_worker()
from openpilot.starpilot.common.car_control_config import (PARAM, MAX_ASSIGNMENT_BYTES, STALK_HOLD, STALK_TAP, STALK_TAP_FULL,
WHEEL_HOLDS, effective_bindings, parse_assignments,
vehicle_supported, screen_reserved)
from openpilot.starpilot.car.tesla.set_speed import Polled
from opendbc.car.tesla.speed_sync import selected as speed_sync_selected
from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.controllers.tesla_controls import TeslaInputDecoder
from openpilot.starpilot.controllers.tesla_input_protocol import MAX_AGE, READY, document_hash, drive_id, encode_event
from openpilot.starpilot.controllers.wheel_actions import cp_fingerprint
# Nothing read yet. The first read is always parsed, also when it finds no saved file (read_saved gives None for that).
UNREAD = object()
class InputPump:
def __init__(self, params, send, *, socket_factory, receive, clock=time.monotonic, boot_clock_ns=None):
self.params, self.send, self.clock = params, send, clock
self.boot_clock_ns = boot_clock_ns or (lambda: time.clock_gettime_ns(time.CLOCK_BOOTTIME))
self.worker_session = secrets.token_hex(16)
# Speed sync is admitted on this car: each scroll carries where it was seen on the bus.
self.sync_provenance = False
self.comma_speed = Polled(params, clock)
self.socket_factory, self.receive = socket_factory, receive
self.socket = None
self.decoder: TeslaInputDecoder | None = None
self.identity = None
self.sequence = 0
self.raw = UNREAD
self.document = None
self.cp = None
self.cp_hash = None
def reset(self):
self.socket = None
self.decoder = None
self.identity = None
def set_vehicle(self, cp):
fingerprint = cp_fingerprint(cp) if vehicle_supported(cp) else None
provenance = bool(fingerprint) and speed_sync_selected(cp)
if fingerprint != self.cp_hash or provenance != self.sync_provenance:
self.reset()
self.cp = cp
self.sync_provenance = provenance
self.cp_hash = fingerprint
def poll(self, sm):
cp = self.cp
now = self.clock()
drive = drive_id(sm, now)
if (not self.cp_hash or drive is None or
read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True))):
self.reset()
return
raw, readable = read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES)
if raw != self.raw:
self.raw = raw
self.document = parse_assignments(raw) if readable else None
doc = self.document if readable else None
# Nothing saved yet still has the fixed and default bindings (the right stalk hold and half press). A saved document
# is a Model 3's or a Model Y's (parse_assignments); the two have the same controls, so either car uses it.
bindings = effective_bindings(doc, comma_speed=self.comma_speed(cp)) if doc else {}
if not bindings:
self.reset()
return
identity = (raw, self.cp_hash, drive, 'right_wheel_up' in bindings)
if identity != self.identity:
self.reset()
self.identity = identity
from opendbc.car.tesla.values import CANBUS
self.decoder = TeslaInputDecoder(CANBUS.vehicle, stalk_hold=STALK_HOLD in bindings,
stalk_tap=STALK_TAP in bindings, stalk_tap_full=STALK_TAP_FULL in bindings,
wheel_holds=frozenset(name for name in WHEEL_HOLDS.values() if name in bindings))
self.socket = self.socket_factory()
decoder = self.decoder
if decoder is None:
return
try:
decoder.cruise_engaged = bool(sm['carState'].cruiseState.enabled)
except (AttributeError, KeyError, TypeError):
decoder.cruise_engaged = False
count = 0
# A fixed per-tick bound prevents an unending drain. If still overloaded on
# following ticks, original producer timestamps expire and reset the decoder.
for _ in range(256):
event = self.receive(self.socket)
if event is None:
break
# CAN is stamped on the boot clock. Keep that raw integer stamp for speed sync, and translate only the private
# freshness stamp to this process's monotonic clock: the two clocks are never compared directly.
source_boot_ns = int(event.logMonoTime)
before = self.clock()
boot = self.boot_clock_ns()
after = self.clock()
if not (0 <= after - before <= .005 and 0 < source_boot_ns <= boot and
boot - source_boot_ns <= int(MAX_AGE * 1e9)):
decoder.reset()
continue
stamp = after - (boot - source_boot_ns) / 1e9
if not event.valid or not 0 <= self.clock() - stamp <= MAX_AGE:
decoder.reset()
continue
for frame_index, frame in enumerate(event.can):
# These checks precede payload conversion and decoder access.
if frame.src != decoder.bus or frame.address not in decoder.groups:
continue
for name, fast in decoder.feed(frame.address, bytes(frame.dat), frame.src, stamp, details=True):
if name == 'screen_three_finger_tap' and screen_reserved(cp):
continue
if name not in bindings or count >= 4:
continue
if (read_saved(self.params, PARAM, MAX_ASSIGNMENT_BYTES) != (raw, True)
or read_saved(self.params, 'SafeMode', 8) not in ((None, True), (b'0', True))
or drive_id(sm, self.clock()) != drive or self.clock() - stamp > MAX_AGE):
self.reset()
return
self.sequence += 1
provenance = None
if self.sync_provenance and name in ("right_wheel_up", "right_wheel_down"):
from openpilot.starpilot.controllers.tesla_gesture_context import GestureSource
provenance = GestureSource(self.worker_session, self.sequence, source_boot_ns, frame_index,
name, fast, document_hash(raw or b''), self.cp_hash, drive).to_wire()
packet = encode_event(self.sequence, name, fast, stamp, drive, document_hash(raw or b''), self.cp_hash,
provenance=provenance)
try:
self.send(packet)
except (BlockingIOError, OSError):
# No retry of an input action; fail the worker on a full/disconnected IPC channel.
self.reset()
raise
count += 1
def main(fd, parent):
from openpilot.cereal import messaging
from openpilot.common.params import Params
channel = socket.socket(fileno=fd)
channel.setblocking(False)
sm = messaging.SubMaster(['deviceState', 'carState', 'carParams'])
pump = InputPump(Params(), channel.send,
socket_factory=lambda: messaging.sub_sock('can'),
receive=lambda sock: messaging.recv_one_or_none(sock))
channel.send(READY)
# Card publishes the car's parameters only every 50 s; a worker started mid-drive reads this drive's saved copy.
try:
saved = pump.params.get("CarParams")
if saved:
from opendbc.car.structs import car
pump.set_vehicle(messaging.log_from_bytes(saved, car.CarParams))
except Exception:
pass
try:
while os.getppid() == parent:
# Closure is observed even when no gestures occur. No UI heartbeat writes.
if select.select([channel], [], [], 0)[0]:
break
sm.update(0)
if sm.updated['carParams']:
pump.set_vehicle(sm['carParams'].as_builder().as_reader())
pump.poll(sm)
time.sleep(.01)
finally:
pump.reset()
channel.close()
if __name__ == '__main__':
from openpilot.common.swaglog import cloudlog
try:
main(int(sys.argv[1]), int(sys.argv[2]))
except Exception:
cloudlog.exception('Tesla input worker failed')
raise