"""Explicit, bounded native Sample Data; never starts a motor or a background logger.""" import re import time from .motor_test import Rejected PREFIX = "vesc.samples." ACTIONS = frozenset(PREFIX + n for n in ("start", "status", "fetch", "stop", "read")) def validate(action, p): name = action.removeprefix(PREFIX) shapes = { "start": {"mode", "count", "decimation", "timeout_s", "raw"}, "status": set(), "fetch": {"capture_id"}, "stop": {"capture_id"}, "read": {"capture_id", "offset"}, } if name not in shapes or set(p) != shapes[name]: raise ValueError("Invalid Sample Data parameters") if "capture_id" in p and ( not isinstance(p["capture_id"], str) or not re.fullmatch(r"sample_[0-9a-f]{32}", p["capture_id"]) ): raise ValueError("Invalid capture identity") for key, lo, hi in ( ("mode", 1, 7), ("count", 1, 2000), ("decimation", 1, 255), ("timeout_s", 2, 120), ("offset", 0, 2000), ): if key in p and (type(p[key]) is not int or not lo <= p[key] <= hi): raise ValueError("Sample Data argument outside bounds") if "raw" in p and p["raw"] is not False: raise ValueError("FW5.02 does not support raw ADC samples") class SampleData: def __init__(self, service): self.service = service self.pending = {} def active(self, device): state = self.pending.get(device.id) return bool(state and state[0] == device.session and time.monotonic() < state[1]) def maintain(self, devices): current = {d.id: d for d in devices} for key in list(self.pending): if key not in current or not self.active(current[key]): del self.pending[key] def execute(self, device, action, p): if not device.readable or device.identity["version"] != "5.02": raise Rejected("Для этой прошивки формат Sample Data ещё не подтверждён.") name = action.removeprefix(PREFIX) if name == "start": s = self.service if ( s.firmware_update.pending(device) or s.bms_configuration.pending(device) or s.code_tools.blocked(device) or s.config_editor.pending_path(device.id).exists() ): raise Rejected("Сначала завершите изменение прошивки, конфигурации или кода.") # Sampling must also work during an ordinary drive. It neither # claims an output lease nor changes app/current/motor settings. if any( (s.root / n).exists() for n in ("hall-pending.json", "calibration-pending.json") ): raise Rejected("Дождитесь завершения измерения мотора.") result = device.link.rpc("sample_" + name, **p) if result.get("accepted") is False: raise Rejected(result.get("reason", "Sample Data занят.")) if name == "start" and result.get("state") in ("armed", "stored_wait", "receiving"): self.pending[device.id] = (device.session, time.monotonic() + p["timeout_s"] + 2) elif name == "fetch" and result.get("state") == "armed": self.pending[device.id] = (device.session, time.monotonic() + 32) elif result.get("state") in ( "complete", "incomplete", "timeout", "cancelled", "unverified", "expired", "idle", ): self.pending.pop(device.id, None) return result