"""Private, expiring ownership of CAN channels by the onboard controller service.""" import binascii import copy import math import struct import uuid from collections import deque from .contracts import ARBITRATION, DEFAULT, channel, integer from . import confirmed_tx def acknowledged_read(frames, receive_id): """Recognize six exact, argument-free VESC reads for confirmed transmission. Waveshare API 2.5: single-shot drops a frame on lost arbitration/error; normal sending retries in the controller. This classifier never admits arbitrary packets, forwarding or writes; exact setters use a separate path. COMM_PING_CAN (62) is the read-only neighbour scan required before control; it needs the same normal arbitration as identity/configuration reads. Closing the claim resets the channel after a failed request; the application never replays a command. """ if len(frames) != 1: return False frame = frames[0] data = bytes.fromhex(frame["data"]) return (frame["id"] >> 8 == 8 and frame["id"] & 255 not in (255, receive_id) and len(data) == 3 and data[:2] == bytes((receive_id, 0)) and data[2] in (0, 4, 14, 17, 31, 62)) def acknowledged_limits(frames, receive_id): """Recognize only the pinned Tool's non-storing, non-forwarding limits packet. A complete 37-byte COMM_SET_MCCONF_TEMP request is six ordered fragments plus its length/CRC commit. Native Tool validates the configuration before emitting this packet. It requests an ACK and never emits a motor setpoint. Reject classification on any ambiguity; arbitrary writes stay single-shot. """ if len(frames) != 7: return False target = frames[0]["id"] & 255 if target in (255, receive_id): return False payload = bytearray() for index, frame in enumerate(frames[:-1]): data = bytes.fromhex(frame["data"]) size = 7 if index < 5 else 2 if (frame["id"] != (5 << 8) | target or len(data) != size + 1 or data[0] != len(payload)): return False payload.extend(data[1:]) final = frames[-1] commit = (bytes((receive_id, 0, 0, 37)) + binascii.crc_hqx(payload, 0).to_bytes(2, "big")) if final["id"] != (7 << 8) | target or bytes.fromhex(final["data"]) != commit: return False if payload[:5] != bytes((48, 0, 0, 1, 0)): return False values = struct.unpack(">8f", payload[5:]) return (all(math.isfinite(v) for v in values) and all(0 < scale <= 1 for scale in values[:2])) def acknowledged_configuration(frames, receive_id): """Recognize one complete native configuration write and its exact ACK code. Motor/application configurations use the ordinary VESC fragmented transport, including the two-byte offset after byte 255. The native Tool owns schema validation and write admission; this boundary checks destination, contiguous framing, length and CRC before permitting CAN-controller arbitration retry. It never retries the application command or admits forwarded/broadcast writes. """ if len(frames) < 2: return None target = frames[0]["id"] & 255 if target in (255, receive_id): return None payload = bytearray() for index, frame in enumerate(frames[:-1]): width, size, code = (1, 7, 5) if len(payload) <= 255 else (2, 6, 6) data = bytes.fromhex(frame["data"]) if (frame["id"] != (code << 8) | target or not width < len(data) <= width + size or int.from_bytes(data[:width], "big") != len(payload) or (index < len(frames) - 2 and len(data) != width + size)): return None payload.extend(data[width:]) if len(payload) > 10000: return None if len(payload) < 7 or payload[0] not in (13, 16): return None commit = (bytes((receive_id, 0)) + len(payload).to_bytes(2, "big") + binascii.crc_hqx(payload, 0).to_bytes(2, "big")) if frames[-1]["id"] != (7 << 8) | target or bytes.fromhex(frames[-1]["data"]) != commit: return None return payload[0] class Bridges: def __init__(self, engine): self.e = engine self.claims = {} self.previous = {} def occupied(self, ch): return any(c["channel"] == ch for c in self.claims.values()) def close(self, token): claim = self.claims.pop(token, None) if claim and (claim["write_pending"] is not None or claim["tx_pending"]): # A write without its exact ACK may still be queued in the adapter. # Retire every shared claim before resetting the channel; another # reader must not keep a timed-out mutation alive in hardware. for other, value in list(self.claims.items()): if value["channel"] == claim["channel"]: self.claims.pop(other) if claim and not self.occupied(claim["channel"]): ch = claim["channel"] self.e.running[ch] = False self.e.configs[ch] = self.previous.pop(ch, copy.deepcopy(DEFAULT)) self.e.sdk.stop(ch) def expire(self): for token, claim in list(self.claims.items()): if self.e.clock() >= claim["until"]: self.close(token) def receive(self, frame): for claim in self.claims.values(): if ( frame["channel"] == claim["channel"] and frame.get("extended") and frame["id"] & 255 == claim["receive_id"] ): pending = claim["write_pending"] if (pending is not None and frame["id"] >> 8 == 8 and not any(frame.get(k) for k in ("fd", "rtr", "error")) and frame.get("data", "").lower() == bytes((pending["target"], 1, pending["command"])).hex()): claim["write_pending"] = None if len(claim["frames"]) == 512: claim["error"] = "Переполнение CAN. Сеанс требует повторного подключения." claim["frames"].append(frame) def dispatch(self, action, p): self.expire() e = self.e if action == "open": if set(p) != {"channel", "bitrate", "receive_id"}: raise ValueError("Invalid bridge configuration") ch, bitrate = channel(p["channel"]), p["bitrate"] receive_id = integer(p["receive_id"], 0, 254) if type(bitrate) is not int or bitrate not in ARBITRATION: raise ValueError("Unsupported CAN bitrate") if len(self.claims) >= 8 or any( c["channel"] == ch and c["receive_id"] == receive_id for c in self.claims.values() ): raise ValueError("Адрес ответа CAN уже занят.") if self.occupied(ch): if e.configs[ch]["bitrate"] != bitrate: raise ValueError("На одном канале нужна одна скорость CAN.") else: if e.running[ch] or e.jobs[ch]: raise ValueError( "Остановите ручную работу CAN-канала перед подключением привода." ) config = {**copy.deepcopy(DEFAULT), "mode": "normal", "bitrate": bitrate} e.sdk.start(ch, config) self.previous[ch] = e.configs[ch] e.configs[ch], e.running[ch] = config, True token = uuid.uuid4().hex self.claims[token] = { "channel": ch, "receive_id": receive_id, "until": e.clock() + 0.75, "frames": deque(maxlen=512), "error": None, "write_pending": None, "tx_pending": False, "tx_confirmation": {"kind": "adapter_echo", "confirmed": 0, "elapsed_ms": None}, } return {"token": token} token = p.get("token") claim = self.claims.get(token) if not claim: raise ValueError("Сеанс CAN завершён. Автоматическая передача не возобновляется.") if action == "close": self.close(token) return {} if claim["error"] or not e.running[claim["channel"]]: self.close(token) raise ValueError(claim["error"] or "CAN-канал остановлен.") claim["until"] = e.clock() + 0.75 if action == "send": frames, deadline = p.get("frames"), p.get("deadline") if ( type(deadline) not in (int, float) or not math.isfinite(deadline) or not e.clock() < deadline <= e.clock() + 0.3 or not isinstance(frames, list) or not 1 <= len(frames) <= 2048 ): raise ValueError("Передача CAN устарела или превышает предел.") for frame in frames: if ( set(frame) != {"id", "data"} or type(frame["id"]) is not int or not 0 <= frame["id"] <= 0x1FFFFFFF or not isinstance(frame["data"], str) or not 1 <= len(bytes.fromhex(frame["data"])) <= 8 ): raise ValueError("Invalid classic CAN frame") if claim["write_pending"] is not None: self.close(token) raise ValueError( "Подтверждение записи не получено; CAN-сеанс закрыт." ) ack_command = (48 if acknowledged_limits(frames, claim["receive_id"]) else acknowledged_configuration(frames, claim["receive_id"])) confirm = (acknowledged_read(frames, claim["receive_id"]) or confirmed_tx.output_frame(frames, claim["receive_id"])) send_type = 0 if ack_command is not None else 1 if ack_command is not None: claim["write_pending"] = {"target": frames[0]["id"] & 255, "command": ack_command} try: for frame in frames: if e.clock() >= deadline: raise ValueError("Срок передачи CAN истёк; повтор запрещён.") value = { **frame, "extended": True, "fd": False, "rtr": False, "brs": False, "dlc": len(frame["data"]) // 2, "send_type": send_type, } if confirm: claim["tx_pending"] = True confirmed_tx.send(e, claim, value, deadline) claim["tx_pending"] = False else: e.sdk.transmit(claim["channel"], value) e.counts[claim["channel"]]["tx_accepted"] += 1 except (OSError, ValueError): self.close(token) raise elif action != "poll": raise ValueError("Unknown bridge action") frames = list(claim["frames"]) claim["frames"].clear() result = {"frames": frames} if action == "send" and confirm: result["tx_confirmation"] = dict(claim["tx_confirmation"]) return result