"""Stop-and-wait CAN transmission; an adapter echo is not a VESC command ACK.""" # Bound the adapter's normal arbitration retries inside the caller's deadline. # One frame may be outstanding. Timeout retires the whole shared channel. ECHO_TIMEOUT = 0.040 def output_frame(frames, receive_id): """Exact non-forwarded native setters and the existing 250 ms PPM lease.""" if len(frames) != 1: return False frame = frames[0] data = bytes.fromhex(frame["data"]) if (frame["id"] >> 8 != 8 or frame["id"] & 255 in (receive_id, 255) or data[:2] != bytes((receive_id, 0))): return False payload = data[2:] return ((len(payload) == 5 and payload[0] in (5, 6, 8)) or payload == bytes((63, 0, 0, 0, 0, 250))) def matches(frame, sent, channel): return (frame.get("channel") == channel and frame.get("id") == sent["id"] and frame.get("extended") is True and not any(frame.get(k) for k in ("fd", "rtr", "error")) and frame.get("dlc") == sent["dlc"] and frame.get("data", "").lower() == sent["data"].lower()) def send(engine, claim, frame, deadline): """Submit once; normal+self-reception retries are owned by the CAN controller. The caller must reset the entire shared channel on ANY failure, including exceptions after SDK acceptance. Never replay or fall back to single-shot. Drain before submission so buffered echoes cannot acknowledge a new request. Every previous confirmed request consumed exactly one echo (no app retries). Unrelated RX is routed normally, including traffic for other shared claims. """ channel = claim["channel"] until = min(deadline, engine.clock() + ECHO_TIMEOUT) while True: if engine.clock() >= until: raise OSError("Истёк срок подтверждения передачи CAN.") received = engine.sdk.receive(channel) for rx in received: engine.receive(rx) if rx.get("error"): raise OSError("Ошибка CAN перед отправкой команды.") if not received: break started = engine.clock() engine.sdk.transmit(channel, {**frame, "send_type": 2}) engine.counts[channel]["tx_accepted"] += 1 while engine.clock() < until: received = engine.sdk.receive(channel) confirmed = False for rx in received: engine.receive(rx) if rx.get("error"): raise OSError("Ошибка CAN при подтверждении передачи.") confirmed = confirmed or matches(rx, frame, channel) if confirmed and engine.clock() < until: elapsed = (engine.clock() - started) * 1000 claim["tx_confirmation"] = { "kind": "adapter_echo", "confirmed": claim["tx_confirmation"]["confirmed"] + 1, "elapsed_ms": elapsed, } return # Injectable sleep keeps the deadline tests deterministic. engine.sleep(min(0.001, max(0, until - engine.clock()))) raise OSError("Адаптер не подтвердил передачу CAN в срок; канал остановлен.")