feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
"""Onboard VESC discovery, archive and bounded motor identification service."""
|
||||
|
||||
VERSION = "0.7.4"
|
||||
VERSION = "0.20.11"
|
||||
MODEL = "vesc.controller"
|
||||
SCHEMA = "missioncore.nodedc/plugin-sdk/v0alpha2"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Explicit CAN BMS operations; never use the VESC's implicitly selected proxy.
|
||||
|
||||
Upstream BMS control has no ACK. Durable intent and consumed previews prevent
|
||||
replay; a sent command is not represented as an applied setting.
|
||||
"""
|
||||
from collections import OrderedDict
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from .motor_test import Rejected
|
||||
|
||||
PREFIX='vesc.bms.'
|
||||
ACTIONS=frozenset(PREFIX+n for n in ('read','prepare','apply'))
|
||||
COMMANDS=frozenset(('charge_enable','charge_disable','balance_enable','balance_disable','reset_ah','reset_wh','zero_current'))
|
||||
|
||||
|
||||
def validate(action,p):
|
||||
name=action.removeprefix(PREFIX)
|
||||
if name in ('read','prepare'):
|
||||
if set(p)!=({'can_id','command'} if name=='prepare' else {'can_id'}) or type(p.get('can_id')) is not int or not 0<=p['can_id']<=253:
|
||||
raise ValueError('Exact unicast CAN address required')
|
||||
if name=='prepare' and p['command'] not in COMMANDS:raise ValueError('Unknown BMS command')
|
||||
elif name=='apply':
|
||||
if set(p)!={'preview_id','confirmed','inputs_isolated'} or p['confirmed'] is not True or p['inputs_isolated'] is not True or not isinstance(p['preview_id'],str) or not re.fullmatch(r'bms_[0-9a-f]{32}',p['preview_id']):
|
||||
raise ValueError('Fresh BMS preview and explicit confirmation required')
|
||||
else:raise ValueError('Unknown BMS operation')
|
||||
|
||||
|
||||
class BmsControl:
|
||||
def __init__(self,service,atomic,utc,clock=time.monotonic):
|
||||
self.service,self.atomic,self.utc,self.clock=service,atomic,utc,clock
|
||||
self.plans=OrderedDict()
|
||||
|
||||
def read(self,device,can_id):
|
||||
result=device.link.bms_read(can_id)
|
||||
if result.get('state')=='received':
|
||||
target=result.get('target',{});values=result.get('values',{})
|
||||
if target.get('can_id')!=can_id or not re.fullmatch(r'[0-9a-f]{24}',target.get('uuid','')):
|
||||
raise ValueError('Invalid BMS target')
|
||||
if target.get('hardware_type')==1 and (not isinstance(values.get('v_cells'),list) or not 1<=len(values['v_cells'])<=96):
|
||||
raise Rejected('BMS ответила без напряжений ячеек. Управление недоступно.')
|
||||
return {**result,'observed_at':self.utc()}
|
||||
|
||||
def prepare(self,device,p):
|
||||
value=self.read(device,p['can_id'])
|
||||
if value.get('state')!='received' or value.get('commands_supported') is not True:
|
||||
raise Rejected('Адресная BMS с поддерживаемой прошивкой не подтверждена.')
|
||||
self.plans=OrderedDict((k,v) for k,v in self.plans.items() if self.clock()-v['at']<60)
|
||||
while len(self.plans)>=4:self.plans.popitem(last=False)
|
||||
identifier='bms_'+uuid.uuid4().hex
|
||||
plan={'at':self.clock(),'device_id':device.id,'session':device.session,'identity':dict(device.identity),
|
||||
'target':value['target'],'command':p['command']}
|
||||
self.plans[identifier]=plan
|
||||
return {'preview_id':identifier,'expires_in_s':60,'target':plan['target'],'command':p['command']}
|
||||
|
||||
def apply(self,device,p,operation):
|
||||
plan=self.plans.get(p['preview_id'])
|
||||
if not plan or self.clock()-plan['at']>=60 or plan['device_id']!=device.id or plan['session']!=device.session or plan['identity']!=device.identity:
|
||||
raise Rejected('Подтверждение BMS истекло или сеанс изменился. Подготовьте команду заново.')
|
||||
if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device):
|
||||
raise Rejected('Сначала подтвердите результат предыдущего изменения VESC.')
|
||||
self.service.config_editor.idle(device,self.service.config_editor.read(device))
|
||||
fresh=self.read(device,plan['target']['can_id'])
|
||||
if fresh.get('state')!='received' or fresh.get('target')!=plan['target'] or fresh.get('commands_supported') is not True:
|
||||
raise Rejected('BMS изменилась после подтверждения. Команда отменена.')
|
||||
if plan['command']=='zero_current':
|
||||
readings=[fresh.get('values',{}).get(k) for k in ('i_in','i_in_ic')]
|
||||
if any(type(v) not in (int,float) or not math.isfinite(v) or abs(v)>0.1 for v in readings):
|
||||
raise Rejected('Для калибровки нуля отключите зарядку и нагрузку: оба тока должны быть меньше 0,1 А.')
|
||||
record={'schema':'missioncore.vesc.bms-command/v1','operation_id':operation,'target':plan['target'],
|
||||
'command':plan['command'],'state':'unknown','acknowledged':False,'started_at':self.utc()}
|
||||
path=self.service.root/('bms-command-'+operation+'.json')
|
||||
self.atomic(path,record)
|
||||
self.plans.pop(p['preview_id'])
|
||||
try:
|
||||
result=device.link.bms_command(plan['target'],plan['command'])
|
||||
if result.get('sent') is not True:raise OSError('BMS command was not emitted')
|
||||
record['state']='sent_unconfirmed'
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
record['error']=str(error)[:512]
|
||||
record['finished_at']=self.utc()
|
||||
self.atomic(path,record)
|
||||
return record
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Schema-driven BMS configuration, UUID-bound preview and durable readback barrier."""
|
||||
from collections import OrderedDict
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from .motor_test import Rejected
|
||||
|
||||
PREFIX = 'vesc.bms.configuration.'
|
||||
ACTIONS = frozenset(PREFIX+n for n in ('read', 'preview', 'apply', 'reconcile', 'restore'))
|
||||
READS = ACTIONS - {PREFIX+'apply'}
|
||||
HASH = re.compile(r'[0-9a-f]{64}')
|
||||
|
||||
|
||||
def validate(action, p):
|
||||
name = action.removeprefix(PREFIX)
|
||||
if name == 'apply':
|
||||
if (set(p) != {'preview_id', 'confirmed', 'inputs_isolated'} or p['confirmed'] is not True
|
||||
or p['inputs_isolated'] is not True or not isinstance(p['preview_id'], str)
|
||||
or not re.fullmatch(r'bcfg_[0-9a-f]{32}', p['preview_id'])):
|
||||
raise ValueError('Explicit BMS configuration preview confirmation required')
|
||||
return
|
||||
if type(p.get('can_id')) is not int or not 0 <= p['can_id'] <= 253 or type(p.get('index')) is not int or not 0 <= p['index'] < 8:
|
||||
raise ValueError('Unicast CAN address and configuration index required')
|
||||
base = {'can_id', 'index'}
|
||||
if name in ('read', 'reconcile', 'restore'):
|
||||
if set(p) != base: raise ValueError('Unsupported BMS configuration request')
|
||||
elif name == 'preview':
|
||||
choices = set(p) - base - {'baseline', 'schema_sha256'}
|
||||
if len(choices) != 1 or not choices <= {'changes', 'xml', 'defaults'}:
|
||||
raise ValueError('One configuration source required')
|
||||
if any(not isinstance(p.get(k), str) or not HASH.fullmatch(p[k]) for k in ('baseline', 'schema_sha256')):
|
||||
raise ValueError('Exact baseline and schema required')
|
||||
if 'changes' in p and (not isinstance(p['changes'], dict) or not 1 <= len(p['changes']) <= 512): raise ValueError('Invalid edit')
|
||||
if 'xml' in p and (not isinstance(p['xml'], str) or not 0 < len(p['xml'].encode()) <= 32768): raise ValueError('Invalid XML size')
|
||||
if 'defaults' in p and p['defaults'] is not True: raise ValueError('Invalid default request')
|
||||
else: raise ValueError('Unknown BMS configuration operation')
|
||||
|
||||
|
||||
def same_target(a, b):
|
||||
return {k:v for k,v in a.items() if k != 'can_id'} == {k:v for k,v in b.items() if k != 'can_id'}
|
||||
|
||||
|
||||
class BmsConfiguration:
|
||||
def __init__(self, service, atomic, utc, clock=time.monotonic):
|
||||
self.service, self.atomic, self.utc, self.clock = service, atomic, utc, clock
|
||||
self.plans = OrderedDict()
|
||||
|
||||
def path(self, device):
|
||||
return self.service.root / ('bms-configuration-pending-' + (device if isinstance(device, str) else device.id) + '.json')
|
||||
|
||||
def pending(self, device):
|
||||
path = self.path(device)
|
||||
return json.loads(path.read_text()) if path.exists() else None
|
||||
|
||||
def read(self, device, p):
|
||||
value = device.link.rpc('custom_read', timeout=28, **p)
|
||||
raw = base64.b64decode(value['payload'], validate=True)
|
||||
if (value['index'] != p['index'] or value['target']['can_id'] != p['can_id']
|
||||
or hashlib.sha256(raw).hexdigest() != value['configuration']['packet_sha256']):
|
||||
raise ValueError('BMS snapshot identity or content mismatch')
|
||||
return value
|
||||
|
||||
def preview(self, device, p, recovery=False):
|
||||
pending = self.pending(device)
|
||||
if pending and not recovery:
|
||||
raise Rejected('Сначала проверьте предыдущую запись BMS или восстановите исходную копию.')
|
||||
args = dict(p)
|
||||
if recovery:
|
||||
if not pending: raise Rejected('Нет незавершённой записи BMS.')
|
||||
current = self.read(device, p)
|
||||
if (pending['identity'] != device.identity or not same_target(pending['before']['target'], current['target'])
|
||||
or pending['before']['index'] != p['index'] or pending['before']['schema_sha256'] != current['schema_sha256']):
|
||||
raise Rejected('Исходная копия относится к другой BMS, прошивке или схеме.')
|
||||
args.update(baseline=current['configuration']['packet_sha256'], schema_sha256=current['schema_sha256'], source={'payload':pending['before']['payload']})
|
||||
else:
|
||||
args['source'] = {k:args.pop(k) for k in ('changes', 'xml') if k in args}
|
||||
value = device.link.rpc('custom_preview', timeout=30, **args)
|
||||
now = self.clock()
|
||||
self.plans = OrderedDict((k,v) for k,v in self.plans.items() if now-v['at'] < 300)
|
||||
while len(self.plans) >= 4: self.plans.popitem(last=False)
|
||||
key = 'bcfg_' + uuid.uuid4().hex
|
||||
self.plans[key] = {'at':now, 'identity':dict(device.identity), 'session':device.session, 'device_id':device.id,
|
||||
'value':value, 'recovery':recovery}
|
||||
return {'preview_id':key, 'expires_in_s':300, 'target':value['target'], 'changes':value['candidate']['changes']}
|
||||
|
||||
def apply(self, device, p, operation, deadline):
|
||||
from datetime import datetime, timezone
|
||||
plan = self.plans.get(p['preview_id'])
|
||||
if (not plan or self.clock()-plan['at'] >= 300 or plan['identity'] != device.identity
|
||||
or plan['session'] != device.session or plan['device_id'] != device.id):
|
||||
raise Rejected('Сравнение BMS истекло или изменился сеанс.')
|
||||
if self.pending(device) and not plan['recovery']: raise Rejected('Предыдущая запись BMS не подтверждена.')
|
||||
if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device): raise Rejected('Сначала подтвердите предыдущее изменение VESC.')
|
||||
self.service.config_editor.idle(device, self.service.config_editor.read(device))
|
||||
# Confirm battery load independently of the USB gateway's idle motor.
|
||||
battery = self.service.bms.read(device, plan['value']['target']['can_id'])
|
||||
if battery.get('target') != plan['value']['target'] or battery.get('state') != 'received': raise Rejected('BMS изменилась после сравнения.')
|
||||
import math
|
||||
currents = [battery.get('values', {}).get(k) for k in ('i_in','i_in_ic')]
|
||||
if any(type(v) not in (int,float) or not math.isfinite(v) or abs(v) > .1 for v in currents): raise Rejected('Отключите зарядку и нагрузку BMS перед записью параметров.')
|
||||
if (deadline-datetime.now(timezone.utc)).total_seconds() < 45: raise Rejected('Недостаточно времени для записи и проверки BMS.')
|
||||
value = plan['value']; candidate = value['candidate']
|
||||
before = self.read(device, {'can_id':value['target']['can_id'], 'index':value['index']})
|
||||
if (before['target'] != value['target'] or before['schema_sha256'] != value['schema_sha256']
|
||||
or before['configuration']['packet_sha256'] != candidate['before_sha256']): raise Rejected('Параметры или схема BMS изменились после сравнения.')
|
||||
record = {'schema':'missioncore.vesc.bms-configuration/v1','operation_id':operation, 'identity':device.identity,
|
||||
'before':before, 'expected':candidate['after_sha256'], 'started_at':self.utc(), 'state':'unknown'}
|
||||
self.atomic(self.service.root / ('bms-configuration-backup-'+operation+'.json'), record)
|
||||
self.atomic(self.path(device), record)
|
||||
self.plans.pop(p['preview_id'])
|
||||
self.service.motor.state('rc')
|
||||
try:
|
||||
result = device.link.rpc('custom_apply', timeout=42, can_id=value['target']['can_id'], index=value['index'], target=value['target'],
|
||||
baseline=candidate['before_sha256'], schema_sha256=value['schema_sha256'], after_sha256=candidate['after_sha256'], source={'payload':candidate['payload']})
|
||||
if result.get('verified') is not True: raise ValueError('Missing readback')
|
||||
self.finish(device, record, 'applied')
|
||||
return {'verified':True, 'outcome':'applied'}
|
||||
except (ValueError, OSError, TimeoutError) as error:
|
||||
record['failure_type'] = type(error).__name__; self.atomic(self.path(device),record)
|
||||
return {'verified':False, 'outcome':'unknown', 'message':'Итог записи неизвестен. Автоповтора нет. Если менялся CAN-адрес, выберите новый адрес и проверьте запись.'}
|
||||
|
||||
def finish(self, device, record, outcome):
|
||||
self.atomic(self.service.root / ('bms-configuration-result-'+record['operation_id']+'.json'),
|
||||
{**record,'state':'verified','outcome':outcome,'finished_at':self.utc()})
|
||||
self.path(device).unlink()
|
||||
import os
|
||||
fd = os.open(self.service.root,os.O_RDONLY)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
|
||||
def reconcile(self, device, p):
|
||||
record = self.pending(device)
|
||||
if not record: return {'verified':True,'outcome':'no_pending_write'}
|
||||
current = self.read(device,p);before = record['before']
|
||||
if (record['identity'] != device.identity or not same_target(before['target'],current['target'])
|
||||
or before['index'] != current['index'] or before['schema_sha256'] != current['schema_sha256']): raise Rejected('UUID, прошивка или схема BMS изменились.')
|
||||
actual = current['configuration']['packet_sha256']
|
||||
outcome = 'applied' if actual == record['expected'] else 'unchanged' if actual == before['configuration']['packet_sha256'] else 'different'
|
||||
if outcome != 'different': self.finish(device,record,outcome)
|
||||
return {'verified':outcome != 'different', 'outcome':outcome, 'configuration':current['configuration']}
|
||||
|
||||
def execute(self, device, action, p, operation, deadline):
|
||||
name = action.removeprefix(PREFIX)
|
||||
if not device.readable: raise Rejected('Бортовой VESC не поддерживает адресную настройку BMS.')
|
||||
if name == 'read':
|
||||
value = self.read(device,p)
|
||||
return {**value,'pending':bool(self.pending(device))}
|
||||
if name in ('preview','restore'): return self.preview(device,p,name=='restore')
|
||||
if name == 'apply': return self.apply(device,p,operation,deadline)
|
||||
return self.reconcile(device,p)
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Private loopback transport for upstream VESC Tool; never generates motor commands."""
|
||||
|
||||
import contextlib
|
||||
import http.client
|
||||
import json
|
||||
import select
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .can_protocol import Reassembly, fragment, serial_frame
|
||||
from .protocol import Decoder
|
||||
from .serial import device_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Attachment:
|
||||
adapter: str
|
||||
adapter_session: str
|
||||
channel: int
|
||||
target: int
|
||||
bitrate: int
|
||||
sender: int
|
||||
expected_uuid: str
|
||||
|
||||
@property
|
||||
def binding(self):
|
||||
return (
|
||||
f"can:{self.adapter}:{self.adapter_session}:{self.channel}:"
|
||||
f"{self.target}:{self.bitrate}:{self.sender}"
|
||||
)
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return device_id("uuid:" + self.expected_uuid)
|
||||
|
||||
@property
|
||||
def usb(self):
|
||||
return f"CAN{self.channel + 1} · ID {self.target}"
|
||||
|
||||
@property
|
||||
def address(self):
|
||||
return self.adapter_session
|
||||
|
||||
@property
|
||||
def tty(self):
|
||||
return self.binding
|
||||
|
||||
@property
|
||||
def speed(self):
|
||||
return f"{self.bitrate // 1000} кбит/с"
|
||||
|
||||
@property
|
||||
def route(self):
|
||||
return {
|
||||
"kind": "can",
|
||||
"uuid": self.expected_uuid,
|
||||
"adapter_id": self.adapter,
|
||||
"channel": self.channel,
|
||||
"can_id": self.target,
|
||||
"bitrate": self.bitrate,
|
||||
}
|
||||
|
||||
|
||||
class LocalHTTP(http.client.HTTPConnection):
|
||||
def connect(self):
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.settimeout(self.timeout)
|
||||
self.sock.connect("/run/mission-core-usb-can/driver.sock")
|
||||
|
||||
|
||||
def inventory():
|
||||
c = LocalHTTP("local", timeout=0.5)
|
||||
try:
|
||||
c.request("GET", "/bridge-inventory")
|
||||
r = c.getresponse()
|
||||
data = json.loads(r.read(196608))
|
||||
if r.status != 200:
|
||||
raise OSError(data.get("error", "CAN inventory unavailable"))
|
||||
return data["items"]
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
class Bridge:
|
||||
def __init__(self, attachment):
|
||||
self.attachment, self.error, self.client = attachment, None, None
|
||||
self.metrics = {"requests": 0, "responses": 0, "rx_frames": 0,
|
||||
"last_request": None, "last_response": None,
|
||||
"send_ms": None, "response_ms": None,
|
||||
"tx_confirmation": None}
|
||||
self.sent_at = None
|
||||
self.stop = threading.Event()
|
||||
self.token = self.call(
|
||||
"open",
|
||||
{
|
||||
"channel": attachment.channel,
|
||||
"bitrate": attachment.bitrate,
|
||||
"receive_id": attachment.sender,
|
||||
},
|
||||
)["token"]
|
||||
self.listener = socket.socket()
|
||||
try:
|
||||
self.listener.bind(("127.0.0.1", 0))
|
||||
self.listener.listen(1)
|
||||
self.port = self.listener.getsockname()[1]
|
||||
self.thread = threading.Thread(target=self.run, daemon=True, name="vesc-can-bridge")
|
||||
self.thread.start()
|
||||
except BaseException:
|
||||
self.listener.close()
|
||||
self.call("close", {"token": self.token})
|
||||
raise
|
||||
|
||||
def call(self, action, parameters):
|
||||
c = LocalHTTP("local", timeout=0.6)
|
||||
try:
|
||||
body = json.dumps(
|
||||
{
|
||||
"adapter": self.attachment.adapter,
|
||||
"session": self.attachment.adapter_session,
|
||||
"action": action,
|
||||
"parameters": parameters,
|
||||
}
|
||||
)
|
||||
c.request("POST", "/bridge", body, {"Content-Type": "application/json"})
|
||||
r = c.getresponse()
|
||||
data = json.loads(r.read(196608))
|
||||
if r.status != 200:
|
||||
raise OSError(action + ": " + data.get("error", "CAN transport failed"))
|
||||
return data
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
def diagnostics(self):
|
||||
# Bounded counters and timing only; never retain CAN payloads or samples.
|
||||
return dict(self.metrics, error=self.error)
|
||||
|
||||
def received(self, frame, rx):
|
||||
self.metrics["rx_frames"] += 1
|
||||
packet = rx.feed(frame)
|
||||
if packet:
|
||||
self.metrics["responses"] += 1
|
||||
self.metrics["last_response"] = packet[0]
|
||||
self.metrics["response_ms"] = (
|
||||
(time.monotonic() - self.sent_at) * 1000 if self.sent_at else None
|
||||
)
|
||||
if self.client:
|
||||
self.client.sendall(serial_frame(packet))
|
||||
|
||||
def run(self):
|
||||
decoder = Decoder()
|
||||
rx = Reassembly(self.attachment.target, self.attachment.sender)
|
||||
try:
|
||||
while not self.stop.is_set():
|
||||
if self.client is None:
|
||||
if select.select([self.listener], [], [], 0.01)[0]:
|
||||
self.client, _ = self.listener.accept()
|
||||
self.client.settimeout(0.2)
|
||||
self.client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
elif select.select([self.client], [], [], 0.005)[0]:
|
||||
data = self.client.recv(16384)
|
||||
if not data:
|
||||
return
|
||||
for payload in decoder.feed(data):
|
||||
if payload == b"\xffMCBR":
|
||||
# FIFO barrier follows bridge.send completion. Exact
|
||||
# native setters now wait for their adapter TX echo.
|
||||
# This is still not a VESC application-level ACK.
|
||||
self.client.sendall(serial_frame(payload))
|
||||
continue
|
||||
self.sent_at = time.monotonic()
|
||||
self.metrics["requests"] += 1
|
||||
self.metrics["last_request"] = payload[0]
|
||||
result = self.call(
|
||||
"send",
|
||||
{
|
||||
"token": self.token,
|
||||
"frames": fragment(
|
||||
payload, self.attachment.target, self.attachment.sender
|
||||
),
|
||||
"deadline": time.monotonic() + 0.2,
|
||||
},
|
||||
)
|
||||
self.metrics["send_ms"] = (time.monotonic() - self.sent_at) * 1000
|
||||
self.metrics["tx_confirmation"] = result.get("tx_confirmation")
|
||||
for frame in result["frames"]:
|
||||
self.received(frame, rx)
|
||||
result = self.call("poll", {"token": self.token})
|
||||
for frame in result["frames"]:
|
||||
self.received(frame, rx)
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
self.error = str(error)
|
||||
finally:
|
||||
self.stop.set()
|
||||
if self.client:
|
||||
self.client.close()
|
||||
with contextlib.suppress(OSError, ValueError):
|
||||
self.call("close", {"token": self.token})
|
||||
self.listener.close()
|
||||
|
||||
def check(self):
|
||||
if self.stop.is_set() or not self.thread.is_alive():
|
||||
raise OSError(self.error or "CAN connection closed")
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
self.thread.join(1)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""VESC CAN fragmentation: upstream comm_can.c, packet IDs 5..8.
|
||||
Commands themselves remain generated by the pinned upstream VESC Tool.
|
||||
"""
|
||||
|
||||
import binascii
|
||||
import time
|
||||
|
||||
MAX_PAYLOAD = 10000
|
||||
|
||||
|
||||
def fragment(payload, target, sender):
|
||||
if (
|
||||
not 1 <= len(payload) <= MAX_PAYLOAD
|
||||
or not 0 <= target < 255
|
||||
or not 0 <= sender < 255
|
||||
or target == sender
|
||||
):
|
||||
raise ValueError("Invalid VESC CAN endpoint/payload")
|
||||
|
||||
def f(code, data):
|
||||
return {"id": (code << 8) | target, "data": data.hex()}
|
||||
|
||||
if len(payload) <= 6:
|
||||
return [f(8, bytes((sender, 0)) + payload)]
|
||||
result, offset = [], 0
|
||||
while offset < len(payload):
|
||||
width, size, code = (1, 7, 5) if offset <= 255 else (2, 6, 6)
|
||||
chunk = payload[offset : offset + size]
|
||||
result.append(f(code, offset.to_bytes(width, "big") + chunk))
|
||||
offset += len(chunk)
|
||||
result.append(
|
||||
f(
|
||||
7,
|
||||
bytes((sender, 0))
|
||||
+ len(payload).to_bytes(2, "big")
|
||||
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big"),
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def serial_frame(payload):
|
||||
width = 1 if len(payload) < 256 else 2
|
||||
return (
|
||||
bytes((width + 1,))
|
||||
+ len(payload).to_bytes(width, "big")
|
||||
+ payload
|
||||
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big")
|
||||
+ b"\x03"
|
||||
)
|
||||
|
||||
|
||||
class Reassembly:
|
||||
def __init__(self, target, sender, clock=time.monotonic):
|
||||
self.target, self.sender, self.clock = target, sender, clock
|
||||
self.buffer, self.until = bytearray(), 0
|
||||
|
||||
def feed(self, frame):
|
||||
if (
|
||||
not frame.get("extended")
|
||||
or frame.get("fd")
|
||||
or frame.get("rtr")
|
||||
or frame.get("error")
|
||||
or frame["id"] & 255 != self.sender
|
||||
):
|
||||
return None
|
||||
data, code = bytes.fromhex(frame["data"]), frame["id"] >> 8
|
||||
if len(data) > 8:
|
||||
raise ValueError("Invalid classic CAN frame")
|
||||
if self.clock() >= self.until:
|
||||
self.buffer.clear()
|
||||
if code in (5, 6):
|
||||
width = 1 if code == 5 else 2
|
||||
if len(data) <= width:
|
||||
raise ValueError("Empty CAN fragment")
|
||||
offset = int.from_bytes(data[:width], "big")
|
||||
if offset == 0:
|
||||
self.buffer.clear()
|
||||
if offset != len(self.buffer) or offset + len(data) - width > MAX_PAYLOAD:
|
||||
self.buffer.clear()
|
||||
raise ValueError("CAN fragment sequence lost")
|
||||
self.buffer.extend(data[width:])
|
||||
self.until = self.clock() + 1
|
||||
elif code in (7, 8):
|
||||
if len(data) < (6 if code == 7 else 3) or data[0] != self.target or data[1] != 1:
|
||||
return None
|
||||
payload = bytes(self.buffer) if code == 7 else data[2:]
|
||||
self.buffer.clear()
|
||||
if code == 7 and (
|
||||
len(payload) != int.from_bytes(data[2:4], "big")
|
||||
or binascii.crc_hqx(payload, 0) != int.from_bytes(data[4:6], "big")
|
||||
):
|
||||
raise ValueError("CAN response length/CRC mismatch")
|
||||
return payload
|
||||
return None
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Bounded code projects and explicit programming transactions. No automatic run."""
|
||||
from collections import OrderedDict
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from .motor_test import Rejected
|
||||
|
||||
PREFIX='vesc.code.'
|
||||
NAMES=('read','begin','chunk','prepare','erase_prepare','apply','reconcile','control_prepare','control_apply','stats','restore')
|
||||
ACTIONS=frozenset(PREFIX+n for n in NAMES)
|
||||
READS=ACTIONS-{PREFIX+'apply',PREFIX+'control_apply'}
|
||||
KINDS={'lisp','qml','qml_hw'}
|
||||
ID=re.compile(r'code_[0-9a-f]{32}')
|
||||
HASH=re.compile(r'[0-9a-f]{64}')
|
||||
|
||||
|
||||
def validate(action,p):
|
||||
n=action.removeprefix(PREFIX)
|
||||
shapes={'read':{'kind'},'begin':{'kind','size','sha256'},'chunk':{'upload_id','offset','data'},'prepare':{'upload_id'},
|
||||
'erase_prepare':{'kind'},'apply':{'preview_id','confirmed','inputs_isolated'},'reconcile':{'kind'},
|
||||
'control_prepare':{'command','text'},'control_apply':{'preview_id','confirmed','inputs_isolated'},'stats':set(),'restore':{'kind'}}
|
||||
if n not in shapes or set(p)!=shapes[n]:raise ValueError('Invalid code operation parameters')
|
||||
if 'kind' in p and (p['kind'] not in KINDS or (n not in ('read',) and p['kind']=='qml_hw')):raise ValueError('Invalid writable code kind')
|
||||
for key in ('upload_id','preview_id'):
|
||||
if key in p and (not isinstance(p[key],str) or not ID.fullmatch(p[key])):raise ValueError('Invalid code project identity')
|
||||
if n=='begin' and (type(p['size']) is not int or not 1<=p['size']<=256*1024 or not isinstance(p['sha256'],str) or not HASH.fullmatch(p['sha256'])):raise ValueError('Invalid project size/hash')
|
||||
if n=='chunk':
|
||||
if type(p['offset']) is not int or p['offset']<0 or not isinstance(p['data'],str) or not 0<len(p['data'])<=22000:raise ValueError('Invalid code fragment')
|
||||
raw=base64.b64decode(p['data'],validate=True)
|
||||
if not raw or len(raw)>16384 or base64.b64encode(raw).decode()!=p['data']:raise ValueError('Invalid code fragment encoding')
|
||||
if n in ('apply','control_apply') and (p['confirmed'] is not True or p['inputs_isolated'] is not True):raise ValueError('Explicit isolated-input confirmation required')
|
||||
if n=='control_prepare' and (p['command'] not in ('start','stop','repl') or not isinstance(p['text'],str) or len(p['text'].encode())>1024 or '\0' in p['text'] or (p['command']=='repl')!=bool(p['text'])):raise ValueError('Invalid Lisp control')
|
||||
|
||||
|
||||
class CodeTools:
|
||||
def __init__(self,service,atomic,utc,clock=time.monotonic):
|
||||
self.service,self.atomic,self.utc,self.clock=service,atomic,utc,clock
|
||||
self.uploads=OrderedDict();self.plans=OrderedDict()
|
||||
|
||||
@staticmethod
|
||||
def supported(device):
|
||||
i=device.identity or {}
|
||||
return i.get('major')==6 and i.get('minor')==0 and i.get('hardware_type')==0 and i.get('test_firmware')==0
|
||||
|
||||
def path(self,device,kind='pending'):
|
||||
return self.service.root/('code-'+kind+'-'+(device if isinstance(device,str) else device.id)+'.json')
|
||||
|
||||
def pending(self,device):
|
||||
path=self.path(device)
|
||||
return json.loads(path.read_text()) if path.exists() else None
|
||||
|
||||
def blocked(self,device):return self.path(device).exists() or self.path(device,'execution').exists() or (self.service.root/('package-pending-'+device.id+'.json')).exists()
|
||||
|
||||
def identity(self,device):return {'identity':dict(device.identity),'device_id':device.id,'session':device.session}
|
||||
|
||||
def match(self,device,record):return all(record.get(k)==v for k,v in self.identity(device).items()) and self.clock()-record['at']<300
|
||||
|
||||
def remember(self,store,value):
|
||||
now=self.clock()
|
||||
for k,v in list(store.items()):
|
||||
if now-v['at']>=300:del store[k]
|
||||
while len(store)>=2:store.popitem(last=False)
|
||||
key='code_'+uuid.uuid4().hex;store[key]={'at':now,**value};return key
|
||||
|
||||
def clear(self,path):
|
||||
if not path.exists():return
|
||||
path.unlink()
|
||||
import os
|
||||
fd=os.open(self.service.root,os.O_RDONLY)
|
||||
try:os.fsync(fd)
|
||||
finally:os.close(fd)
|
||||
|
||||
def idle(self,device,allow_package=False):
|
||||
if not allow_package and (self.service.root/("package-pending-"+device.id+".json")).exists():raise Rejected("Сначала проверьте установку расширения.")
|
||||
if self.service.motor.active or self.service.motor.limits.pending(device):raise Rejected('Завершите управление приводом.')
|
||||
if self.service.config_editor.pending(device) or self.service.firmware_update.pending(device) or self.service.bms_configuration.pending(device):raise Rejected('Сначала проверьте предыдущее изменение устройства.')
|
||||
if any((self.service.root/n).exists() for n in ('hall-pending.json','calibration-pending.json')):raise Rejected('Процедура мотора не завершена.')
|
||||
|
||||
def read(self,device,kind):return device.link.rpc('code_read',timeout=30,kind=kind)
|
||||
|
||||
def preview(self,device,kind,image,erase=False,recovery=False):
|
||||
if self.pending(device) and not recovery:raise Rejected('Сначала проверьте предыдущую запись кода или восстановите копию.')
|
||||
before=self.read(device,kind)
|
||||
key=self.remember(self.plans,{**self.identity(device),'kind':kind,'image':image,'erase':erase,'before':before,'recovery':recovery})
|
||||
data=base64.b64decode(image) if image else b''
|
||||
return {'preview_id':key,'kind':kind,'bytes':len(data),'sha256':hashlib.sha256(data[8:]).hexdigest(),
|
||||
'before_sha256':before['sha256'],'erase':erase,'expires_in_s':300,'running_requested':False}
|
||||
|
||||
def execute(self,device,action,p,operation,deadline):
|
||||
name=action.removeprefix(PREFIX)
|
||||
if not self.supported(device):raise Rejected('Lisp/QML требуют поддерживаемой прошивки 6.00. Установка ядра Tool не меняет прошивку VESC.')
|
||||
if name=='read':return {**self.read(device,p['kind']),'pending':bool(self.pending(device)),'execution_pending':self.path(device,'execution').exists()}
|
||||
if name=='stats':return device.link.rpc('code_stats',timeout=4)
|
||||
if name=='begin':
|
||||
key=self.remember(self.uploads,{**self.identity(device),**p,'data':bytearray()})
|
||||
return {'upload_id':key,'chunk_bytes':16384}
|
||||
if name in ('chunk','prepare'):
|
||||
upload=self.uploads.get(p['upload_id'])
|
||||
if not upload or not self.match(device,upload):raise Rejected('Передача проекта истекла или изменился контроллер.')
|
||||
if name=='chunk':
|
||||
data=base64.b64decode(p['data'],validate=True);offset=p['offset']
|
||||
if offset<len(upload['data']) and upload['data'][offset:offset+len(data)]==data:return {'offset':len(upload['data'])}
|
||||
if offset!=len(upload['data']) or offset+len(data)>upload['size']:raise ValueError('Code chunk offset/size mismatch')
|
||||
upload['data'].extend(data);return {'offset':len(upload['data'])}
|
||||
raw=bytes(upload['data'])
|
||||
if len(raw)!=upload['size'] or hashlib.sha256(raw).hexdigest()!=upload['sha256']:raise ValueError('Code project checksum mismatch')
|
||||
project=json.loads(raw)
|
||||
if not isinstance(project,dict) or set(project)!={'kind','source','imports','fullscreen'} or project['kind']!=upload['kind'] or not isinstance(project['source'],str) or not isinstance(project['imports'],dict) or type(project['fullscreen']) is not bool:raise ValueError('Invalid code project')
|
||||
project=self.service.packages.resolve_imports(device,project)
|
||||
packed=device.link.rpc('code_pack',timeout=8,project=project)
|
||||
result=self.preview(device,project['kind'],packed['image']);self.uploads.pop(p['upload_id']);return result
|
||||
if name=='erase_prepare':return self.preview(device,p['kind'],'',True)
|
||||
if name=='restore':
|
||||
record=self.pending(device)
|
||||
if not record or record['identity']!=device.identity or record['kind']!=p['kind']:raise Rejected('Нет исходной копии для этой прошивки и вида кода.')
|
||||
# Repack the captured project through the upstream codec. Original
|
||||
# application flags are retained in the saved project.
|
||||
project=record['before']['project'];packed=device.link.rpc('code_pack',timeout=8,project=project) if project['source'] else {'image':''}
|
||||
return self.preview(device,p['kind'],packed['image'],not bool(packed['image']),True)
|
||||
if name=='reconcile':return self.reconcile(device,p['kind'])
|
||||
if name=='control_prepare':
|
||||
if p['command']!='stop': self.idle(device)
|
||||
if self.pending(device) and p['command']!='stop':raise Rejected('Сначала проверьте запись кода.')
|
||||
before=self.read(device,'lisp') if p['command']!='stop' else {'sha256':None}
|
||||
key=self.remember(self.plans,{**self.identity(device),**p,'baseline':before['sha256'],'control':True})
|
||||
return {'preview_id':key,'command':p['command'],'text':p['text'],'expires_in_s':300}
|
||||
plan=self.plans.get(p['preview_id'])
|
||||
if not plan or not self.match(device,plan) or bool(plan.get('control'))!=(name=='control_apply'):raise Rejected('Подтверждение кода истекло или сеанс изменился.')
|
||||
if name=='control_apply':return self.control(device,p['preview_id'],plan,operation)
|
||||
return self.apply(device,p['preview_id'],plan,operation,deadline)
|
||||
|
||||
def control(self,device,key,plan,operation):
|
||||
if plan['command']!='stop': self.idle(device)
|
||||
if self.pending(device) and plan['command']!='stop':raise Rejected('Сначала проверьте запись кода.')
|
||||
if plan['command']!='stop' and self.read(device,'lisp')['sha256']!=plan['baseline']:raise Rejected('Lisp изменился после подтверждения.')
|
||||
record={'schema':'missioncore.vesc.code-execution/v1','identity':device.identity,'operation_id':operation,'command':plan['command'],'state':'unknown','started_at':self.utc()}
|
||||
self.atomic(self.path(device,'execution'),record);self.plans.pop(key);self.service.motor.state('rc')
|
||||
try:
|
||||
result=device.link.rpc('code_control',timeout=8,command=plan['command'],text=plan['text'])
|
||||
record.update(result,state='acknowledged' if result.get('acknowledged') else 'sent_unconfirmed')
|
||||
self.atomic(self.service.root/('code-control-result-'+operation+'.json'),record)
|
||||
if plan['command']=='stop' and result.get('acknowledged'):self.clear(self.path(device,'execution'))
|
||||
else:self.atomic(self.path(device,'execution'),record)
|
||||
return record
|
||||
except (OSError,ValueError,TimeoutError):return {**record,'message':'Итог выполнения неизвестен. Автоповтора нет; остановите Lisp отдельной командой.'}
|
||||
|
||||
def apply(self,device,key,plan,operation,deadline):
|
||||
self.idle(device)
|
||||
if self.path(device,"execution").exists():raise Rejected("Остановите Lisp перед записью кода.")
|
||||
if self.pending(device) and not plan['recovery']:raise Rejected('Предыдущая запись кода не подтверждена.')
|
||||
if (deadline-datetime.now(timezone.utc)).total_seconds()<100:raise Rejected('Недостаточно времени для записи кода и проверки.')
|
||||
current=self.read(device,plan['kind'])
|
||||
if current['sha256']!=plan['before']['sha256'] or current['project']['fullscreen']!=plan['before']['project']['fullscreen']:raise Rejected('Код изменился после сравнения.')
|
||||
data=base64.b64decode(plan['image']) if plan['image'] else b''
|
||||
record={'schema':'missioncore.vesc.code-write/v1','operation_id':operation,'identity':device.identity,'kind':plan['kind'],
|
||||
'before':current,'expected_fullscreen':len(data)>7 and data[7]==2,'expected':hashlib.sha256(data[8:]).hexdigest(),'state':'unknown','started_at':self.utc()}
|
||||
self.atomic(self.service.root/('code-backup-'+operation+'.json'),record);self.atomic(self.path(device),record)
|
||||
self.plans.pop(key);self.service.motor.state('rc')
|
||||
try:
|
||||
result=device.link.rpc('code_write',timeout=100,kind=plan['kind'],image=plan['image'],erase=plan['erase'],baseline=current['sha256'],baseline_fullscreen=current['project']['fullscreen'])
|
||||
if result.get('verified') is not True:raise ValueError('Missing code readback')
|
||||
self.finish(device,record,'applied')
|
||||
if plan['kind']=='lisp':self.clear(self.path(device,'execution'))
|
||||
return {'verified':True,'outcome':'applied','running_requested':False}
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
record['failure_type']=type(error).__name__;self.atomic(self.path(device),record)
|
||||
return {'verified':False,'outcome':'unknown','message':'Запись могла выполниться частично. Автоповтора нет. Прочитайте результат или восстановите исходную копию.'}
|
||||
|
||||
def finish(self,device,record,outcome):
|
||||
self.atomic(self.service.root/('code-result-'+record['operation_id']+'.json'),{**record,'state':'verified','outcome':outcome,'finished_at':self.utc()});self.clear(self.path(device))
|
||||
|
||||
def reconcile(self,device,kind):
|
||||
record=self.pending(device)
|
||||
if not record:return {'verified':True,'outcome':'no_pending_write'}
|
||||
if record['identity']!=device.identity or record['kind']!=kind:raise Rejected('Незавершённая запись относится к другой прошивке или виду кода.')
|
||||
current=self.read(device,kind)
|
||||
outcome='applied' if current['sha256']==record['expected'] and current['project']['fullscreen']==record['expected_fullscreen'] else 'unchanged' if current['sha256']==record['before']['sha256'] and current['project']['fullscreen']==record['before']['project']['fullscreen'] else 'different'
|
||||
if outcome!='different':self.finish(device,record,outcome)
|
||||
return {'verified':outcome!='different','outcome':outcome}
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Session-bound preview -> explicit write -> exact readback, using native codecs.
|
||||
|
||||
No automatic retry or rollback of flash writes. Incomplete transactions leave
|
||||
an identity-bound interlock that survives a process restart. Reconciliation is
|
||||
read-only; recovery requires a new preview of the retained pre-write backup.
|
||||
"""
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .configuration import decode
|
||||
from .motor_test import Rejected
|
||||
from .protocol import firmware, values, ppm
|
||||
from .receiver import active, neutral_band
|
||||
from .release_observation import IDLE_BOUNDS
|
||||
|
||||
ACTIONS = frozenset({'vesc.configuration.preview', 'vesc.configuration.apply', 'vesc.configuration.reconcile'})
|
||||
KINDS = {'motor': 14, 'application': 17}
|
||||
HASH = re.compile(r'[0-9a-f]{64}')
|
||||
OP = re.compile(r'op_[0-9a-f]{32}')
|
||||
|
||||
|
||||
def validate(action, p):
|
||||
if action == 'vesc.configuration.preview':
|
||||
if set(p) == {'backup_id'}:
|
||||
if not isinstance(p['backup_id'], str) or not OP.fullmatch(p['backup_id']):
|
||||
raise ValueError('Invalid backup ID')
|
||||
elif set(p) in ({'kind', 'baseline', 'changes'}, {'kind', 'baseline', 'xml'}):
|
||||
if p['kind'] not in KINDS or not isinstance(p['baseline'], dict) or set(p['baseline']) != set(KINDS):
|
||||
raise ValueError('Full baseline and configuration kind required')
|
||||
if any(not isinstance(v, str) or not HASH.fullmatch(v) for v in p['baseline'].values()):
|
||||
raise ValueError('Invalid baseline hash')
|
||||
if 'changes' in p and (not isinstance(p['changes'], dict) or not 1 <= len(p['changes']) <= 512):
|
||||
raise ValueError('Empty or oversized edit')
|
||||
if 'xml' in p and (not isinstance(p['xml'], str) or not 0 < len(p['xml'].encode()) <= 32768):
|
||||
raise ValueError('XML import exceeds its bound')
|
||||
else:
|
||||
raise ValueError('Unsupported configuration preview')
|
||||
elif action == 'vesc.configuration.apply':
|
||||
if (set(p) != {'preview_id', 'rig_clear', 'inputs_isolated'}
|
||||
or not isinstance(p['preview_id'], str) or not re.fullmatch(r'cfg_[0-9a-f]{32}', p['preview_id'])
|
||||
or p['rig_clear'] is not True or p['inputs_isolated'] is not True):
|
||||
raise ValueError('Preview and explicit isolated-input/raised-rig confirmation required')
|
||||
elif p:
|
||||
raise ValueError('Reconciliation takes no parameters')
|
||||
|
||||
|
||||
def packet_hashes(raw):
|
||||
return {k: hashlib.sha256(v).hexdigest() for k, v in raw.items()}
|
||||
|
||||
|
||||
class ConfigEditor:
|
||||
def __init__(self, service, atomic, utc, clock=time.monotonic):
|
||||
self.service, self.atomic, self.utc, self.clock = service, atomic, utc, clock
|
||||
self.plans = OrderedDict()
|
||||
|
||||
def pending_path(self, device):
|
||||
return self.service.root / ('configuration-pending-' + (device if isinstance(device, str) else device.id) + '.json')
|
||||
|
||||
def pending(self, device):
|
||||
path = self.pending_path(device)
|
||||
return json.loads(path.read_text()) if path.exists() else None
|
||||
|
||||
def read(self, device):
|
||||
if device.link is None or firmware(device.link.query(0)) != device.identity:
|
||||
raise Rejected('Контроллер изменился или отключён. Обновите устройства.')
|
||||
raw = {k: device.link.query(code) for k, code in KINDS.items()}
|
||||
if firmware(device.link.query(0)) != device.identity:
|
||||
raise Rejected('Личность контроллера изменилась во время чтения.')
|
||||
return raw
|
||||
|
||||
def backup(self, device, raw):
|
||||
op = 'op_' + uuid.uuid4().hex
|
||||
value = {'schema': 'missioncore.vesc.config-backup/v1', 'identity': device.identity,
|
||||
'device_id': device.id, 'observed_at': self.utc(), 'operation_id': op,
|
||||
'decoded': False, 'configs': {k: {'encoding': 'base64', 'payload': base64.b64encode(v).decode(),
|
||||
'bytes': len(v), 'sha256': hashlib.sha256(v).hexdigest(), 'signature_hex': v[1:5].hex()}
|
||||
for k, v in raw.items()}}
|
||||
self.service.archive.add('local', value)
|
||||
device.backup = {'observed_at': value['observed_at'], 'operation_id': op,
|
||||
'configs': {k: {'bytes': v['bytes'], 'sha256': v['sha256']} for k, v in value['configs'].items()}}
|
||||
return op
|
||||
|
||||
def preview(self, device, p):
|
||||
pending = self.pending(device)
|
||||
if pending and p.get('backup_id') != pending['before_backup_id']:
|
||||
raise Rejected('Итог предыдущей записи не подтверждён. Проверьте его или выберите исходную резервную копию для восстановления.')
|
||||
if 'backup_id' in p:
|
||||
backup = self.service.archive.read('local', device.id, p['backup_id'])
|
||||
if backup['identity'] != device.identity:
|
||||
raise Rejected('Резервная копия относится к другому контроллеру или прошивке.')
|
||||
sources = {k: {'payload': v['payload']} for k, v in backup['configs'].items()}
|
||||
else:
|
||||
sources = {p['kind']: {k: p[k] for k in ('xml', 'changes') if k in p}}
|
||||
native = device.link.configuration_preview(sources)
|
||||
if 'baseline' in p and native['baseline'] != p['baseline']:
|
||||
raise Rejected('Конфигурация изменилась после чтения. Прочитайте параметры заново.')
|
||||
if firmware(device.link.query(0)) != device.identity:
|
||||
raise Rejected('Контроллер изменился во время сравнения.')
|
||||
now = self.clock()
|
||||
self.plans = OrderedDict((k, v) for k, v in self.plans.items() if now - v['at'] < 300)
|
||||
while len(self.plans) >= 4:
|
||||
self.plans.popitem(last=False)
|
||||
if len(json.dumps(native).encode()) > 256 * 1024:
|
||||
raise ValueError('Native preview exceeds bound')
|
||||
identifier = 'cfg_' + uuid.uuid4().hex
|
||||
self.plans[identifier] = {'at': now, 'identity': dict(device.identity), 'device_id': device.id,
|
||||
'session': device.session, 'native': native, 'recovery': p.get('backup_id')}
|
||||
return {'preview_id': identifier, 'expires_in_s': 300, 'identity': device.identity,
|
||||
'baseline': native['baseline'], 'changes': [{**change, 'kind': k}
|
||||
for k, v in native['configs'].items() for change in v['changes']]}
|
||||
|
||||
def idle(self, device, raw):
|
||||
if self.service.motor.active or self.service.motor.limits.pending(device):
|
||||
raise Rejected('Завершите управление и восстановление временных пределов перед настройкой.')
|
||||
for name in ('hall-pending.json', 'calibration-pending.json'):
|
||||
if (self.service.root / name).exists():
|
||||
raise Rejected('Предыдущая процедура мотора ещё не завершена.')
|
||||
app = decode(raw['application'], 'application')
|
||||
tachometer = None
|
||||
# Query fresh native values on every round; never admit a cached UI
|
||||
# sample. Two waits prove a half-second neutral window before any write.
|
||||
for sample in range(3):
|
||||
if sample:
|
||||
time.sleep(.25)
|
||||
state = values(device.link.query(4))
|
||||
if any(not math.isfinite(state[key]) or abs(state[key]) > bound
|
||||
for key, bound in IDLE_BOUNDS):
|
||||
raise Rejected('Перед записью требуется остановленный привод без выходной мощности и ошибок.')
|
||||
count = state['tachometer']
|
||||
if not math.isfinite(count) or (tachometer is not None and count != tachometer):
|
||||
raise Rejected('Привод движется. Дождитесь полной остановки перед записью.')
|
||||
tachometer = count
|
||||
if app['app_to_use'] in (1, 4) and active(ppm(device.link.query(31))['level'], neutral_band(app)):
|
||||
raise Rejected('Приёмник передаёт команду. Отключите входы управления перед записью.')
|
||||
|
||||
def apply(self, device, p, operation, deadline):
|
||||
if self.service.firmware_update.pending(device):
|
||||
raise Rejected('Сначала подтвердите результат загрузки прошивки.')
|
||||
plan = self.plans.get(p['preview_id'])
|
||||
if (not plan or self.clock() - plan['at'] >= 300 or plan['identity'] != device.identity
|
||||
or plan['device_id'] != device.id or plan['session'] != device.session):
|
||||
raise Rejected('Сравнение истекло или сеанс изменился. Подготовьте изменения заново.')
|
||||
pending = self.pending(device)
|
||||
if pending and plan['recovery'] != pending['before_backup_id']:
|
||||
raise Rejected('Требуется проверить предыдущую запись или восстановить её исходную копию.')
|
||||
before = self.read(device)
|
||||
if packet_hashes(before) != plan['native']['baseline']:
|
||||
raise Rejected('Настройки изменились после сравнения. Запись отменена.')
|
||||
self.idle(device, before)
|
||||
if (deadline - datetime.now(timezone.utc)).total_seconds() < 25:
|
||||
raise Rejected('Недостаточно времени для записи и проверки. Повторите предварительное сравнение.')
|
||||
expected = dict(plan['native']['baseline'])
|
||||
expected.update({k: v['after_sha256'] for k, v in plan['native']['configs'].items()})
|
||||
if expected == packet_hashes(before):
|
||||
self.plans.pop(p['preview_id'])
|
||||
return {'outcome': 'unchanged', 'verified': True}
|
||||
backup_id = self.backup(device, before)
|
||||
record = {'operation_id': operation, 'identity': device.identity,
|
||||
'before_backup_id': backup_id, 'before': packet_hashes(before), 'expected': expected,
|
||||
'started_at': self.utc(), 'state': 'unknown'}
|
||||
self.atomic(self.pending_path(device), record)
|
||||
self.plans.pop(p['preview_id']) # A consumed plan never grants another write.
|
||||
self.service.motor.state('rc') # A new explicit control admission is required.
|
||||
try:
|
||||
for kind, target in plan['native']['configs'].items():
|
||||
if target['before_sha256'] == target['after_sha256']:
|
||||
continue
|
||||
device.link.configuration_apply(kind, target)
|
||||
after = self.read(device)
|
||||
if packet_hashes(after) != expected:
|
||||
raise ValueError('Final readback differs from the preview')
|
||||
after_id = self.backup(device, after)
|
||||
record.update(state='verified', after_backup_id=after_id, finished_at=self.utc())
|
||||
self.atomic(self.service.root / ('configuration-result-' + operation + '.json'), record)
|
||||
self.clear(device)
|
||||
device.sample = device.telemetry = None
|
||||
return {'outcome': 'applied', 'verified': True, 'before_backup_id': backup_id, 'after_backup_id': after_id}
|
||||
except (OSError, ValueError, TimeoutError) as error:
|
||||
record['failure_type'] = type(error).__name__
|
||||
self.atomic(self.pending_path(device), record)
|
||||
return {'outcome': 'unknown', 'verified': False, 'before_backup_id': backup_id,
|
||||
'message': 'Запись могла выполниться частично. Автоповтора нет. Проверьте итог перед дальнейшим управлением.'}
|
||||
|
||||
def clear(self, device):
|
||||
import os
|
||||
self.pending_path(device).unlink()
|
||||
fd = os.open(self.service.root, os.O_RDONLY)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
|
||||
def reconcile(self, device):
|
||||
pending = self.pending(device)
|
||||
if not pending:
|
||||
return {'outcome': 'no_pending_write', 'verified': True}
|
||||
if pending['identity'] != device.identity:
|
||||
raise Rejected('Прошивка или личность контроллера отличается от незавершённой записи.')
|
||||
raw = self.read(device)
|
||||
actual = packet_hashes(raw)
|
||||
self.idle(device, raw)
|
||||
outcome = 'applied' if actual == pending['expected'] else 'unchanged' if actual == pending['before'] else 'different'
|
||||
if outcome != 'different':
|
||||
archive = self.backup(device, raw)
|
||||
self.atomic(self.service.root / ('configuration-result-' + pending['operation_id'] + '.json'),
|
||||
{**pending, 'state': 'verified', 'outcome': outcome, 'after_backup_id': archive, 'finished_at': self.utc()})
|
||||
self.clear(device)
|
||||
return {'outcome': outcome, 'verified': outcome != 'different', 'before_backup_id': pending['before_backup_id'],
|
||||
'message': 'Параметры отличаются и от исходных, и от ожидаемых. Доступно восстановление исходной копии.' if outcome == 'different' else 'Итог подтверждён повторным чтением. Управление включается отдельно.'}
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Exact, read-only firmware configuration decoder. Never serializes a write."""
|
||||
import math
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import xml.etree.ElementTree as ET
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def crc32c(data):
|
||||
@@ -14,14 +15,25 @@ def crc32c(data):
|
||||
return value ^ 0xffffffff
|
||||
|
||||
|
||||
def decode(data, kind):
|
||||
@lru_cache(maxsize=2)
|
||||
def _schema(kind):
|
||||
"""Installed schemas are immutable for the lifetime of this process.
|
||||
|
||||
Parse/sign the definition once, not while accepting a 25 ms input RPC.
|
||||
Controller bytes and decoded results are never cached.
|
||||
"""
|
||||
code, name = {"motor": (14, "mcconf"), "application": (17, "appconf")}[kind]
|
||||
xml = ET.parse(Path(__file__).parent / "schemas/5.02" / ("parameters_" + name + ".xml")).getroot()
|
||||
params = {p.tag: p for p in xml.find("Params")}
|
||||
order = [p.text for p in xml.find("SerOrder")]
|
||||
signature = "".join(n + params[n].findtext("type", "0") + params[n].findtext("vTx", "0")
|
||||
+ "".join(x.text or "" for x in params[n].findall("enumNames")) for n in order)
|
||||
if len(data) < 5 or data[0] != code or int.from_bytes(data[1:5], "big") != crc32c(signature.encode()):
|
||||
return code, params, tuple(order), crc32c(signature.encode())
|
||||
|
||||
|
||||
def decode(data, kind):
|
||||
code, params, order, signature = _schema(kind)
|
||||
if len(data) < 5 or data[0] != code or int.from_bytes(data[1:5], "big") != signature:
|
||||
raise ValueError("Configuration signature differs from firmware 5.02 schema")
|
||||
offset, result = 5, {}
|
||||
for name in order:
|
||||
@@ -44,3 +56,9 @@ def decode(data, kind):
|
||||
result[name] = value
|
||||
if offset != len(data): raise ValueError("Unexpected configuration tail")
|
||||
return result
|
||||
|
||||
|
||||
# Load before the service starts its input/observation threads. Lazy warming
|
||||
# in the first arm would leave one avoidable XML/CRC pause in that session.
|
||||
for _kind in ("motor", "application"):
|
||||
_schema(_kind)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Persisted operator transport choices. Pure metadata: no device I/O.
|
||||
|
||||
A route never falls back to another bus. A control session must pin revision,
|
||||
controller UUID and attachment session before it obtains output authority.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
|
||||
SCHEMA = "missioncore.vesc.control-transport/v1"
|
||||
BITRATES = (125000, 250000, 500000, 1000000)
|
||||
|
||||
|
||||
def validate_routes(routes, drive):
|
||||
bindings = {b["device_id"]: b["uuid"] for b in drive["bindings"].values()}
|
||||
if not isinstance(routes, dict) or set(routes) != set(bindings) or not bindings:
|
||||
raise ValueError("Выберите шину для каждого назначенного мотора.")
|
||||
channels, addresses = {}, set()
|
||||
for device, route in routes.items():
|
||||
if not isinstance(route, dict) or route.get("kind") not in ("usb", "can"):
|
||||
raise ValueError("Неизвестная шина управления.")
|
||||
keys = {"kind", "uuid"}
|
||||
if route["kind"] == "can":
|
||||
keys |= {"adapter_id", "channel", "can_id", "bitrate"}
|
||||
if set(route) != keys or route["uuid"] != bindings[device]:
|
||||
raise ValueError("Назначение мотора изменилось. Обновите настройки.")
|
||||
if not re.fullmatch(r"[0-9a-f]{24}", str(route["uuid"])):
|
||||
raise ValueError("Не подтверждён UUID контроллера.")
|
||||
if route["kind"] == "can":
|
||||
if (
|
||||
not re.fullmatch(r"usbcan_[0-9a-f]{32}", str(route["adapter_id"]))
|
||||
or type(route["channel"]) is not int
|
||||
or route["channel"] not in (0, 1)
|
||||
or type(route["can_id"]) is not int
|
||||
or not 0 <= route["can_id"] < 255
|
||||
or type(route["bitrate"]) is not int
|
||||
or route["bitrate"] not in BITRATES
|
||||
):
|
||||
raise ValueError("Проверьте адаптер, канал, CAN ID и скорость.")
|
||||
channel = (route["adapter_id"], route["channel"])
|
||||
address = (*channel, route["can_id"])
|
||||
if address in addresses:
|
||||
raise ValueError("Один CAN-адрес назначен нескольким моторам.")
|
||||
if channel in channels and channels[channel] != route["bitrate"]:
|
||||
raise ValueError("На одном CAN-канале нужна одинаковая скорость.")
|
||||
addresses.add(address)
|
||||
channels[channel] = route["bitrate"]
|
||||
return copy.deepcopy(routes)
|
||||
|
||||
|
||||
class ControlTransport:
|
||||
def __init__(self, root, atomic):
|
||||
self.path, self.atomic = root / "control-transport.json", atomic
|
||||
self.value = (
|
||||
json.loads(self.path.read_text())
|
||||
if self.path.exists()
|
||||
else {"schema": SCHEMA, "revision": 0, "routes": {}}
|
||||
)
|
||||
if (
|
||||
self.value.get("schema") != SCHEMA
|
||||
or type(self.value.get("revision")) is not int
|
||||
or self.value["revision"] < 0
|
||||
or not isinstance(self.value.get("routes"), dict)
|
||||
):
|
||||
raise ValueError("Профиль шины управления повреждён.")
|
||||
|
||||
def snapshot(self, drive, available=None):
|
||||
# Preserve legacy USB only for a controller never explicitly configured.
|
||||
# An explicit CAN choice cannot revert to USB after hotplug or restart.
|
||||
routes = {}
|
||||
for binding in drive["bindings"].values():
|
||||
identifier, uid = binding["device_id"], binding["uuid"]
|
||||
route = self.value["routes"].get(identifier)
|
||||
if route is None:
|
||||
if available is None:
|
||||
route = {"kind": "usb", "uuid": uid}
|
||||
else:
|
||||
candidates = [a["route"] for a in available if a.get("device_id") == identifier
|
||||
and a.get("uuid") == uid and a.get("verified") is True]
|
||||
usb = [r for r in candidates if r["kind"] == "usb"]
|
||||
if len(usb) == 1: route = usb[0]
|
||||
elif len(candidates) == 1: route = candidates[0]
|
||||
if route is not None: routes[identifier] = copy.deepcopy(route)
|
||||
return {**copy.deepcopy(self.value), "routes": routes}
|
||||
|
||||
def update(self, parameters, drive, *, active=False):
|
||||
if active:
|
||||
raise ValueError("Остановите удалённое управление перед сменой шины.")
|
||||
if (
|
||||
not isinstance(parameters, dict)
|
||||
or set(parameters) != {"revision", "drive_revision", "routes"}
|
||||
or type(parameters["revision"]) is not int
|
||||
or type(parameters["drive_revision"]) is not int
|
||||
or parameters["revision"] != self.value["revision"]
|
||||
or parameters["drive_revision"] != drive["revision"]
|
||||
):
|
||||
raise ValueError("Профиль изменился. Обновите настройки.")
|
||||
routes = validate_routes(parameters["routes"], drive)
|
||||
value = {"schema": SCHEMA, "revision": self.value["revision"] + 1, "routes": routes}
|
||||
self.atomic(self.path, value)
|
||||
self.value = value
|
||||
return copy.deepcopy(value)
|
||||
|
||||
def pin(self, drive, available):
|
||||
"""Select exact verified attachments. Caller owns output admission/lease."""
|
||||
profile = self.snapshot(drive, available)
|
||||
routes = validate_routes(profile["routes"], drive)
|
||||
pinned = {}
|
||||
for device, route in routes.items():
|
||||
matches = [
|
||||
a
|
||||
for a in available
|
||||
if a.get("device_id") == device
|
||||
and a.get("uuid") == route["uuid"]
|
||||
and a.get("verified") is True
|
||||
and a.get("route") == route
|
||||
and a.get("session_id")
|
||||
]
|
||||
if len(matches) != 1:
|
||||
raise ValueError("Выбранная шина мотора недоступна или его UUID не подтверждён.")
|
||||
pinned[device] = copy.deepcopy(matches[0])
|
||||
return {
|
||||
"revision": profile["revision"],
|
||||
"drive_revision": drive["revision"],
|
||||
"devices": pinned,
|
||||
}
|
||||
|
||||
def assert_pinned(self, pinned, drive, available):
|
||||
if self.pin(drive, available) != pinned:
|
||||
raise ValueError("Подключение или профиль изменился. Начните новый сеанс управления.")
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Bounded, read-only firmware diagnostics and exact-attachment USB descriptors."""
|
||||
from pathlib import Path
|
||||
from .serial import check_attachment
|
||||
|
||||
|
||||
def read_diagnostics(device):
|
||||
attachment = device.attachment
|
||||
check_attachment(attachment)
|
||||
path = Path('/sys/bus/usb/devices') / attachment.usb
|
||||
usb = {"port": attachment.usb, "tty": attachment.tty, "speed": attachment.speed}
|
||||
for field in ('idVendor', 'idProduct', 'bcdDevice', 'manufacturer', 'product', 'serial'):
|
||||
try:
|
||||
usb[field] = (path / field).read_text()[:256].strip()
|
||||
except OSError:
|
||||
usb[field] = None
|
||||
reports = {name: device.link.diagnostic(name) for name in ('hw_status', 'faults')}
|
||||
check_attachment(attachment)
|
||||
return {"usb": usb, "reports": reports}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Bounded failure evidence in the service journal, never in the drive loop."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
LOGGER = logging.getLogger("missioncore.vesc.failure")
|
||||
|
||||
|
||||
def failure(error, phase, *, device=None, session_id=None, release_confirmed=None):
|
||||
# NativeLink attaches the original RPC and recent calls to the exception.
|
||||
# Cleanup uses the same link and replaces last_rpc; reading it afterwards
|
||||
# would record 'process not running' instead of the initiating timeout.
|
||||
try:
|
||||
record = {
|
||||
"event": "vesc_failure",
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"phase": phase,
|
||||
"error": str(error)[:512],
|
||||
"type": type(error).__name__,
|
||||
"violation": getattr(error,"violation",None),
|
||||
"device_id": getattr(error,"device_id",None),
|
||||
"session_id": session_id,
|
||||
"release_confirmed": release_confirmed,
|
||||
"native_rpc": getattr(error, "native_rpc", None),
|
||||
"native_startup": getattr(error, "native_startup", None),
|
||||
"can_bridge": getattr(error, "can_bridge", None),
|
||||
"native_history": list(getattr(error, "native_history", []))[-8:],
|
||||
}
|
||||
if device is not None:
|
||||
record["device_id"] = device.id
|
||||
record["attachment"] = {
|
||||
key: getattr(device.attachment, key) for key in ("usb", "address", "tty")
|
||||
}
|
||||
raw = json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
if len(raw.encode()) > 16000:
|
||||
record["native_history"] = []
|
||||
record["history_omitted"] = True
|
||||
raw = json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
if len(raw.encode()) > 16000:
|
||||
record["native_rpc"] = None
|
||||
record["rpc_omitted"] = True
|
||||
raw = json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
if len(raw.encode()) > 16000:
|
||||
record["native_startup"] = None
|
||||
record["startup_omitted"] = True
|
||||
raw = json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
LOGGER.warning("%s", raw)
|
||||
except Exception:
|
||||
# Journal failure must never bypass release/fault/ownership cleanup.
|
||||
pass
|
||||
|
||||
|
||||
def connection(event, device, error=None):
|
||||
"""One event per lifecycle transition, before its session/sample is cleared."""
|
||||
try:
|
||||
sample = device.sample
|
||||
record = {
|
||||
"event": "vesc_connection",
|
||||
"transition": event,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
"monotonic": time.monotonic(),
|
||||
"device_id": device.id,
|
||||
"session_id": device.session,
|
||||
"identity": device.identity,
|
||||
"attachment": {
|
||||
key: getattr(device.attachment, key) for key in ("usb", "address", "tty")
|
||||
},
|
||||
"last_sample_at": sample.get("observed_at") if sample else None,
|
||||
"last_sample_age_s": max(0.0, time.monotonic() - sample["sampled_at"])
|
||||
if sample
|
||||
else None,
|
||||
"error": str(error)[:512] if error else None,
|
||||
"error_type": type(error).__name__ if error else None,
|
||||
}
|
||||
if sample:
|
||||
record["last_values"] = {
|
||||
k: sample["values"].get(k)
|
||||
for k in ("erpm", "motor_current_a", "input_voltage_v", "duty", "fault_code")
|
||||
}
|
||||
raw = json.dumps(record, ensure_ascii=False, allow_nan=False)
|
||||
if len(raw.encode()) <= 4096:
|
||||
LOGGER.info("%s", raw)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,85 @@
|
||||
"""No-I/O recorder for existing reads/commands; opt-in never changes ownership."""
|
||||
try:
|
||||
from .bounded_diagnostics import BoundedDiagnostics
|
||||
except ModuleNotFoundError:
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
BoundedDiagnostics=runpy.run_path(str(Path(__file__).resolve().parents[3]/
|
||||
"packages/plugin-sdk/python/missioncore_plugin_sdk/bounded_diagnostics.py"))["BoundedDiagnostics"]
|
||||
|
||||
try:
|
||||
from .diagnostic_options import LEGACY_OPTIONS, diagnostic_options
|
||||
except ModuleNotFoundError:
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
_options=runpy.run_path(str(Path(__file__).resolve().parents[3]/
|
||||
"packages/plugin-sdk/python/missioncore_plugin_sdk/diagnostic_options.py"))
|
||||
LEGACY_OPTIONS,diagnostic_options=_options["LEGACY_OPTIONS"],_options["diagnostic_options"]
|
||||
|
||||
class DriveDiagnostics(BoundedDiagnostics):
|
||||
def __init__(self,root):
|
||||
super().__init__('vesc')
|
||||
from .session_log import SessionLog
|
||||
self.log=SessionLog(root)
|
||||
self.stop_after=None
|
||||
self.options=dict(LEGACY_OPTIONS)
|
||||
|
||||
def add(self,event,**data):
|
||||
if not self.active():return
|
||||
row=super().add(event,**data)
|
||||
if row is not None:
|
||||
try:self.log.append(row)
|
||||
except Exception:self.rejected+=1
|
||||
|
||||
def exchange(self,body):
|
||||
if not isinstance(body,dict) or set(body)-{'id','enabled','after','vehicle','core_events','relay_events','export','stop_after','options'}:
|
||||
raise ValueError('Invalid diagnostic request')
|
||||
if type(body.get('enabled')) is not bool or type(body.get('after')) is not int or body['after']<0:
|
||||
raise ValueError('Invalid diagnostic state')
|
||||
stop_after=body.get('stop_after')
|
||||
if 'stop_after' in body and (type(stop_after) is not int or not 0<=stop_after<=2**53-1 or body['enabled']):
|
||||
raise ValueError('Invalid diagnostic stop cursor')
|
||||
options=diagnostic_options(body.get('options'))
|
||||
if body['id']==self.id and options!=self.options:
|
||||
raise ValueError('Diagnostic capture options changed')
|
||||
previous=self.id
|
||||
self.options=options
|
||||
if body['enabled'] or body['id']!=self.id:
|
||||
try:self.log.start(body['id'],body.get('vehicle','Rover'),create=body['enabled'],options=options)
|
||||
except OSError as error:
|
||||
self.log.id=body['id'];self.log.error=type(error).__name__;self.log.closed=True
|
||||
self.configure(body['id'],False)
|
||||
return {**self.snapshot(body['after'],24),'id':body['id'],'storage':self.log.status()}
|
||||
if previous!=body['id']:self.stop_after=None
|
||||
if stop_after is not None:
|
||||
if self.stop_after is not None and self.stop_after!=stop_after:
|
||||
raise ValueError('Diagnostic stop cursor changed')
|
||||
self.stop_after=stop_after
|
||||
stop_after=self.stop_after
|
||||
if options['core_trace']:self.log.external('core',body.get('core_events',[]))
|
||||
self.log.external('node',body.get('relay_events',[]))
|
||||
if not body['enabled'] and self.active():self.add('capture_stopped')
|
||||
self.configure(body['id'],body['enabled'] and stop_after is None and not self.log.closed and not self.log.closing and not self.log.error)
|
||||
# Stop acquisition now; preserve only the already-created Core/browser
|
||||
# tail until its final sequence has been accepted by the disk writer.
|
||||
draining=stop_after is not None and self.log.external_ack.get('core',0)<stop_after
|
||||
if (not body['enabled'] or stop_after is not None) and not draining:self.log.finish()
|
||||
if previous!=self.id:
|
||||
from . import VERSION
|
||||
self.add('capture_started',runtime_version=VERSION,options=options)
|
||||
result={**self.snapshot(body['after'],0 if stop_after is not None or not options['live'] else 24),
|
||||
'storage':self.log.status(),'stop_tail_v1':True,'options':dict(options)}
|
||||
if stop_after is not None:result['stop_after']=stop_after
|
||||
if body.get('export'):
|
||||
spec=body['export']
|
||||
result['export']={**self.log.chunk(body['id'],spec['offset'],spec.get('total_bytes'),
|
||||
limit=spec.get('chunk_bytes',4096),snapshot=spec.get('snapshot')),'token':spec.get('token')}
|
||||
return result
|
||||
|
||||
def sample(self,device,value,receiver,owner):
|
||||
if not self.active() or not self.options['motor_samples']:return
|
||||
self.add('sample',device_id=device.id,device_session=device.session,
|
||||
owner=owner,receiver=receiver,control=getattr(getattr(device,"link",None),"last_rpc",{}).get("control"),
|
||||
can_bridge=getattr(getattr(device,"link",None),"last_rpc",{}).get("can_bridge"),values={k:value.get(k) for k in (
|
||||
'motor_current_a','input_current_a','input_voltage_v','erpm','duty','fault_code',
|
||||
'tachometer','tachometer_abs','id_current_a','iq_current_a','vd_v','vq_v','mos_temperature_c')})
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Installer-owned, pinned official images. No runtime downloads or mutable cache."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
ROOT = Path('/usr/lib/mission-core-vesc/firmware-catalog')
|
||||
|
||||
|
||||
def catalogue(root=ROOT):
|
||||
value = json.loads((root / 'catalog.json').read_bytes())
|
||||
if (value.get('schema') != 'missioncore.vesc.firmware-catalog/v1'
|
||||
or value.get('repository') != 'https://github.com/vedderb/vesc_fw_archive'
|
||||
or not re.fullmatch(r'[0-9a-f]{40}', value.get('commit', ''))
|
||||
or not isinstance(value.get('items'), list) or not 1 <= len(value['items']) <= 512):
|
||||
raise ValueError('Invalid firmware catalogue')
|
||||
ids=set()
|
||||
for item in value['items']:
|
||||
if (not re.fullmatch(r'fwimg_[0-9a-f]{32}',item.get('id','')) or item['id'] in ids
|
||||
or not re.fullmatch(r'[0-9a-f]{64}',item.get('sha256',''))
|
||||
or type(item.get('bytes')) is not int or not 256<=item['bytes']<=2*1024**2
|
||||
or not isinstance(item.get('hardware'),list) or not 1<=len(item['hardware'])<=32
|
||||
or any(not isinstance(hw,str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,64}',hw) for hw in item['hardware'])
|
||||
or item.get('version') not in value.get('admitted_versions',[])
|
||||
or item.get('kind')!='firmware' or type(item.get('hardware_limits')) is not bool):
|
||||
raise ValueError('Invalid firmware catalogue entry')
|
||||
ids.add(item['id'])
|
||||
return value
|
||||
|
||||
|
||||
def compatible(device, root=ROOT):
|
||||
value = catalogue(root)
|
||||
profiles = getattr(device.link,'engine',{}).get('contract',{}).get('firmware_profiles',[])
|
||||
versions = {f"{p['major']}.{p['minor']:02}" for p in profiles} or {device.identity['version']}
|
||||
return {k:value[k] for k in ('repository','commit')} | {'items':[i for i in value['items']
|
||||
if device.identity['hardware'] in i['hardware'] and i['version'] in versions]}
|
||||
|
||||
|
||||
def image(device, identifier, root=ROOT):
|
||||
matches = [i for i in compatible(device,root)['items'] if i['id']==identifier]
|
||||
if len(matches)!=1:
|
||||
raise ValueError('Образ отсутствует в каталоге для этого контроллера и версии.')
|
||||
item=matches[0]; path=root/(item['sha256']+'.bin')
|
||||
if path.is_symlink() or path.stat().st_size != item['bytes']:
|
||||
raise ValueError('Installed firmware image changed')
|
||||
data=path.read_bytes()
|
||||
if hashlib.sha256(data).hexdigest()!=item['sha256']:
|
||||
raise ValueError('Installed firmware image digest changed')
|
||||
return item,data
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Exact unicast firmware targets. No route or background process survives a read."""
|
||||
import base64
|
||||
import hashlib
|
||||
from types import SimpleNamespace
|
||||
from .motor_test import Rejected
|
||||
|
||||
|
||||
def target(device, can_id):
|
||||
result=device.link.firmware_rpc('target',can_id=can_id)
|
||||
if result.get('admitted') is not True:
|
||||
raise Rejected('CAN-контроллер не поддерживается установленным ядром.')
|
||||
value=result['target']
|
||||
if value.get('can_id')!=can_id or value.get('hardware_type')!=0 or len(value.get('uuid',''))!=24:
|
||||
raise Rejected('Идентификация CAN-контроллера неполна.')
|
||||
return value
|
||||
|
||||
|
||||
def identity(value):
|
||||
return {'major':value['major'],'minor':value['minor'],'version':f"{value['major']}.{value['minor']:02}",
|
||||
'hardware':value['hardware'],'uuid':value['uuid'],'hardware_type':value['hardware_type'],
|
||||
'test_firmware':value['test_firmware'],'custom_configs':value.get('custom_configs',0)}
|
||||
|
||||
|
||||
def snapshot(device, expected):
|
||||
result=device.link.firmware_rpc('snapshot',can_id=expected['can_id'],target=expected)
|
||||
if result.get('target')!=expected:raise Rejected('CAN-контроллер изменился.')
|
||||
packets={int(k):base64.b64decode(v,validate=True) for k,v in result['packets'].items()}
|
||||
# Only the already captured, identity-checked packets are exposed to the
|
||||
# existing standstill guard. No temporary Python serial owner is created.
|
||||
view=SimpleNamespace(id="vesc_"+hashlib.sha256(("uuid:"+expected["uuid"]).encode()).hexdigest()[:32],session=device.session,identity=identity(expected),
|
||||
link=SimpleNamespace(query=lambda code:packets[code]),backup=None)
|
||||
return view,{'motor':packets[14],'application':packets[17]}
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Bounded firmware staging and single-shot upstream upload.
|
||||
|
||||
Raw image compatibility is an operator declaration, never inferred from a file
|
||||
name. Persistent uncertainty blocks control; reconnect never replays a write.
|
||||
"""
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from .motor_test import Rejected
|
||||
from .protocol import firmware
|
||||
from .config_editor import packet_hashes
|
||||
from . import firmware_catalog, firmware_target, swd
|
||||
|
||||
PREFIX = 'vesc.firmware.'
|
||||
ACTIONS = frozenset(PREFIX + name for name in ('begin', 'chunk', 'seal', 'discard', 'apply', 'status', 'cancel', 'reconcile', 'catalog', 'catalog_prepare', 'target', 'backup'))
|
||||
SNAPSHOTS = frozenset({PREFIX + 'status', PREFIX + 'catalog', PREFIX + 'target', PREFIX + 'backup'})
|
||||
MAX_IMAGE = 2 * 1024 * 1024
|
||||
MAX_SOURCE = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def validate(action, p):
|
||||
name = action.removeprefix(PREFIX)
|
||||
keys = {'begin': {'name','bytes','sha256','kind','hardware','target_version'},
|
||||
'chunk': {'transfer_id','offset','data'}, 'seal': {'transfer_id'},
|
||||
'discard': {'transfer_id'}, 'apply': {'transfer_id','rig_clear','inputs_isolated','compatible_image_confirmed'},
|
||||
'status': set(), 'cancel': {'operation_id'}, 'reconcile': set(),
|
||||
'catalog':set(), 'catalog_prepare':{'image_id'}, 'target':{'can_id'},'backup':{'operation_id'}}
|
||||
extra = {'hardware_limits_removed_confirmed','swd_target_confirmed'} if name == 'apply' else ({'can_id','target','swd'} if name=='begin' else {'can_id'} if name in ('catalog','catalog_prepare') else set())
|
||||
if 'can_id' in p and (type(p['can_id']) is not int or not 0<=p['can_id']<=253):raise ValueError('Exact unicast CAN address required')
|
||||
if name=='begin' and (('can_id' in p)!=('target' in p) or ('target' in p and not isinstance(p['target'],dict))):raise ValueError('CAN identity required')
|
||||
if name not in keys or not keys[name].issubset(p) or set(p)-keys[name]-extra:
|
||||
raise ValueError('Invalid firmware operation')
|
||||
if 'swd' in p:
|
||||
swd.validate(p['swd'])
|
||||
if name!='begin' or 'can_id' in p or p.get('kind')!='firmware':raise ValueError('SWD requires a dedicated firmware image')
|
||||
if name == 'catalog_prepare' and (not isinstance(p['image_id'],str) or not re.fullmatch(r'fwimg_[0-9a-f]{32}',p['image_id'])):
|
||||
raise ValueError('Invalid catalogue image')
|
||||
if name == 'begin':
|
||||
if (not isinstance(p['name'],str) or not re.fullmatch(r'[^/\\\x00-\x1f]{1,128}\.(bin|hex)',p['name'],re.I)
|
||||
or type(p['bytes']) is not int or not (32 if str(p['name']).lower().endswith('.hex') else 256) <= p['bytes'] <= (MAX_SOURCE if str(p['name']).lower().endswith('.hex') else MAX_IMAGE)
|
||||
or p['kind'] not in ('firmware','bootloader')
|
||||
or not isinstance(p['sha256'],str) or not re.fullmatch(r'[0-9a-f]{64}',p['sha256'])
|
||||
or not isinstance(p['hardware'],str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,64}',p['hardware'])
|
||||
or not isinstance(p['target_version'],str) or not re.fullmatch(r'[0-9]{1,2}\.[0-9]{2}',p['target_version'])):
|
||||
raise ValueError('BIN/HEX size, digest, hardware and target version required')
|
||||
if p['kind'] == 'bootloader' and p['name'].lower().endswith('.bin') and p['bytes'] > 65536:
|
||||
raise ValueError('Bootloader exceeds bound')
|
||||
if 'transfer_id' in p and (not isinstance(p['transfer_id'],str) or not re.fullmatch(r'fw_[0-9a-f]{32}',p['transfer_id'])):
|
||||
raise ValueError('Invalid firmware transfer')
|
||||
if name == 'chunk':
|
||||
if type(p['offset']) is not int or not 0 <= p['offset'] < MAX_SOURCE or not isinstance(p['data'],str) or len(p['data']) > 43700:
|
||||
raise ValueError('Invalid firmware chunk')
|
||||
data = base64.b64decode(p['data'],validate=True)
|
||||
if not 1 <= len(data) <= 32768:
|
||||
raise ValueError('Invalid firmware chunk size')
|
||||
if name == 'apply' and any(p[key] is not True for key in ('rig_clear','inputs_isolated','compatible_image_confirmed')):
|
||||
raise ValueError('Image compatibility and stopped, isolated drive confirmation required')
|
||||
if name in ('cancel','backup') and (not isinstance(p['operation_id'],str) or not re.fullmatch(r'op_[0-9a-f]{32}',p['operation_id'])):
|
||||
raise ValueError('Exact upload operation required')
|
||||
|
||||
|
||||
class FirmwareUpdate:
|
||||
def __init__(self, service, atomic, utc, clock=time.monotonic, sleep=time.sleep):
|
||||
self.service, self.atomic, self.utc, self.clock, self.sleep = service, atomic, utc, clock, sleep
|
||||
self.transfers = OrderedDict()
|
||||
self.lock = threading.RLock()
|
||||
self.active = None
|
||||
self.cancel_event = threading.Event()
|
||||
|
||||
def path(self, device):
|
||||
return self.service.root / ('firmware-pending-' + (device if isinstance(device,str) else device.id) + '.json')
|
||||
|
||||
def pending(self, device):
|
||||
path = self.path(device)
|
||||
if path.exists():return json.loads(path.read_text())
|
||||
identifier=device if isinstance(device,str) else device.id
|
||||
# An uncertain CAN write follows the target UUID if it later appears
|
||||
# directly on USB. Changing transports must never remove its interlock.
|
||||
for candidate in self.service.root.glob('firmware-pending-vesc_*.json'):
|
||||
record=json.loads(candidate.read_text())
|
||||
if record.get('image',{}).get('target') and record.get('before_backup_device_id')==identifier:return record
|
||||
return None
|
||||
|
||||
def owns(self, device):
|
||||
with self.lock:
|
||||
active=self.active
|
||||
if not active:return False
|
||||
return active['device_id']==device.id or (active.get('image',{}).get('target',{}).get('uuid') is not None
|
||||
and active['image']['target']['uuid']==(device.identity or {}).get('uuid'))
|
||||
|
||||
def require_can_owner(self, device, target):
|
||||
with self.service.lock:
|
||||
peers=list(self.service.devices.values())
|
||||
if any(d.identity and d.identity.get('uuid')==target['uuid'] for d in peers):
|
||||
raise Rejected('Этот CAN-контроллер уже подключён по USB. Откройте его собственные настройки и выберите USB.')
|
||||
|
||||
def status(self, device_id):
|
||||
with self.lock:
|
||||
if self.active and self.active['device_id'] == device_id:
|
||||
return dict(self.active)
|
||||
record = self.pending(device_id)
|
||||
if record and record['state'] == 'uploading':
|
||||
return {**record,'state':'unknown','message':'Загрузка прервана. Итог записи не подтверждён.'}
|
||||
return record or {'state':'idle'}
|
||||
|
||||
def cancel(self, device_id, operation):
|
||||
with self.lock:
|
||||
if not self.active or self.active['device_id'] != device_id or self.active['operation_id'] != operation:
|
||||
raise Rejected('Эта загрузка уже не выполняется. Обновите её состояние.')
|
||||
self.cancel_event.set()
|
||||
return {'cancel_requested':True,'operation_id':operation}
|
||||
|
||||
def get(self, device, identifier):
|
||||
now = self.clock()
|
||||
self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if now-v['at'] < 600)
|
||||
value = self.transfers.get(identifier)
|
||||
if not value or value['identity'] != device.identity or value['device_id'] != device.id or value['session'] != device.session:
|
||||
raise Rejected('Файл истёк или контроллер переподключён. Загрузите файл заново.')
|
||||
return value
|
||||
|
||||
def stage(self, device, action, p):
|
||||
name = action.removeprefix(PREFIX)
|
||||
if name=='backup':
|
||||
record=self.pending(device)
|
||||
if not record or record.get('operation_id')!=p['operation_id']:
|
||||
path=self.service.root/('firmware-result-'+p['operation_id']+'.json')
|
||||
record=json.loads(path.read_text()) if path.exists() else None
|
||||
if not record or record.get('device_id')!=device.id or record.get('identity',{}).get('uuid')!=device.identity['uuid']:
|
||||
raise Rejected('Копия не относится к этому сеансу прошивания.')
|
||||
return {'backup':self.service.archive.read('local',record.get('before_backup_device_id',device.id),record['before_backup_id'])}
|
||||
if name=='target':return {'target':firmware_target.target(device,p['can_id'])}
|
||||
selected=firmware_target.target(device,p['can_id']) if name in ('begin','catalog','catalog_prepare') and 'can_id' in p else None
|
||||
from types import SimpleNamespace
|
||||
view=SimpleNamespace(identity=firmware_target.identity(selected),link=device.link) if selected else device
|
||||
if name == 'catalog':
|
||||
return firmware_catalog.compatible(view)
|
||||
if name == 'catalog_prepare':
|
||||
item,data=firmware_catalog.image(view,p['image_id'])
|
||||
manifest={'name':item['name'],'bytes':item['bytes'],'sha256':item['sha256'],'kind':'firmware',
|
||||
'hardware':view.identity['hardware'],'target_version':item['version'],**({'can_id':p['can_id'],'target':selected} if selected else {})}
|
||||
identifier=self.stage(device,PREFIX+'begin',manifest)['transfer_id']
|
||||
self.transfers[identifier]['data'].extend(data)
|
||||
self.transfers[identifier]['manifest'].update(catalog_image_id=item['id'],hardware_limits=item['hardware_limits'])
|
||||
return self.stage(device,PREFIX+'seal',{'transfer_id':identifier})
|
||||
if name == 'begin':
|
||||
if selected:self.require_can_owner(device,selected)
|
||||
if p['name'].lower().endswith('.hex') and 'hex' not in getattr(device.link,'engine',{}).get('contract',{}).get('firmware_formats',[]):
|
||||
raise Rejected('Для HEX требуется обновление ядра VESC Tool на борту.')
|
||||
if selected and p['target']!=selected:raise Rejected('CAN-контроллер изменился после выбора.')
|
||||
if p['hardware'] != view.identity['hardware'] or view.identity['hardware_type'] != 0:
|
||||
raise Rejected('Выбранная аппаратная конфигурация не совпадает с контроллером.')
|
||||
profiles = getattr(device.link,'engine',{}).get('contract',{}).get('firmware_profiles',[])
|
||||
versions = {f"{v['major']}.{v['minor']:02}" for v in profiles} or {device.identity['version']}
|
||||
if 'swd' in p and 'swd' not in getattr(device.link,'engine',{}).get('contract',{}).get('firmware_targets',[]):raise Rejected('Обновите ядро для SWD.')
|
||||
if 'swd' not in p and (p['target_version'] not in versions or (p['kind'] == 'bootloader' and p['target_version'] != view.identity['version'])):
|
||||
raise Rejected('Целевая версия не поддерживается этим выпуском бортового приложения.')
|
||||
self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if self.clock()-v['at'] < 600)
|
||||
# One candidate per UUID; a replaced candidate can no longer apply.
|
||||
self.transfers = OrderedDict((k,v) for k,v in self.transfers.items() if v['device_id'] != device.id)
|
||||
if len(self.transfers) >= 2:
|
||||
raise Rejected('Уже подготовлены два образа. Удалите один из них.')
|
||||
identifier = 'fw_' + uuid.uuid4().hex
|
||||
self.transfers[identifier] = {'at':self.clock(),'identity':dict(device.identity),
|
||||
'device_id':device.id,'session':device.session,'manifest':dict(p),'data':bytearray(),'sealed':False}
|
||||
return {'transfer_id':identifier,'offset':0,'expires_in_s':600}
|
||||
value = self.get(device,p['transfer_id'])
|
||||
if name == 'discard':
|
||||
del self.transfers[p['transfer_id']]
|
||||
return {'discarded':True}
|
||||
if name == 'chunk':
|
||||
data = base64.b64decode(p['data'],validate=True)
|
||||
if value['sealed'] or p['offset'] != len(value['data']) or len(value['data'])+len(data) > value['manifest']['bytes']:
|
||||
raise Rejected('Порядок или размер частей файла изменился. Начните загрузку заново.')
|
||||
value['data'].extend(data)
|
||||
return {'transfer_id':p['transfer_id'],'offset':len(value['data'])}
|
||||
if name != 'seal':
|
||||
raise ValueError('Unknown staging operation')
|
||||
raw, manifest = bytes(value['data']),value['manifest']
|
||||
if len(raw) != manifest['bytes'] or hashlib.sha256(raw).hexdigest() != manifest['sha256']:
|
||||
raise Rejected('Размер или контрольная сумма файла не совпадают.')
|
||||
# Native upstream file validation; staging never issues USB writes.
|
||||
device.link.firmware_rpc('begin',**{k:manifest[k] for k in ('kind','bytes','sha256','hardware')},uuid=manifest.get('target',device.identity)['uuid'],**({'can_id':manifest['can_id']} if 'can_id' in manifest else {}),**({'swd':manifest['swd']} if 'swd' in manifest else {}),format='hex' if manifest['name'].lower().endswith('.hex') else 'bin')
|
||||
for offset in range(0,len(raw),32768):
|
||||
device.link.firmware_rpc('chunk',offset=offset,data=base64.b64encode(raw[offset:offset+32768]).decode())
|
||||
info = device.link.firmware_rpc('seal')
|
||||
if (info.get('source_sha256',info.get('sha256')) != manifest['sha256']
|
||||
or info.get('source_bytes',info.get('bytes')) != len(raw)
|
||||
or not isinstance(info.get('sha256'),str) or not re.fullmatch(r'[0-9a-f]{64}',info['sha256'])
|
||||
or type(info.get('bytes')) is not int or not 256<=info['bytes']<=(65536 if manifest['kind']=='bootloader' else MAX_IMAGE)):
|
||||
raise ValueError('Native image inspection mismatch')
|
||||
manifest.update(source_sha256=manifest['sha256'],source_bytes=manifest['bytes'],
|
||||
sha256=info['sha256'],bytes=info['bytes'],format=info.get('source_format','bin'),base_address=info.get('base_address'))
|
||||
value['sealed'] = True
|
||||
# The native owner retains the sealed bytes. Python needs only metadata.
|
||||
value['data'].clear()
|
||||
return {'transfer_id':p['transfer_id'],'image':manifest,'inspection':info,'identity':firmware_target.identity(manifest['target']) if 'target' in manifest else device.identity,
|
||||
'expires_in_s':max(0,600-int(self.clock()-value['at']))}
|
||||
|
||||
def apply(self, device, p, operation, deadline):
|
||||
plan = self.get(device,p['transfer_id'])
|
||||
if plan['manifest'].get('hardware_limits') is False and p.get('hardware_limits_removed_confirmed') is not True:
|
||||
raise Rejected('Этот образ отключает аппаратные пределы. Требуется отдельное подтверждение.')
|
||||
if 'swd' in plan['manifest'] and p.get('swd_target_confirmed') is not True:raise Rejected('Подтвердите физическую цель SWD, распиновку и размер её flash.')
|
||||
if not plan['sealed']:
|
||||
raise Rejected('Сначала проверьте полный образ.')
|
||||
if self.service.config_editor.pending(device):
|
||||
raise Rejected('Сначала завершите проверку предыдущей записи конфигурации.')
|
||||
previous = self.pending(device)
|
||||
if previous and previous['device_id']!=device.id:
|
||||
raise Rejected('Завершите прежнее прошивание в карточке USB-контроллера, через который оно начато.')
|
||||
if previous and previous['state'] == 'uploading':
|
||||
# On service restart the in-memory active operation is absent. An
|
||||
# uncertain write can only be replaced by another explicit upload.
|
||||
if self.active:
|
||||
raise Rejected('Прошивка уже загружается.')
|
||||
before = self.service.config_editor.read(device)
|
||||
self.service.config_editor.idle(device,before)
|
||||
if (deadline-datetime.now(timezone.utc)).total_seconds() < 270:
|
||||
raise Rejected('Для загрузки требуется полный срок операции. Подготовьте команду заново.')
|
||||
view=device
|
||||
if 'target' in plan['manifest']:
|
||||
self.require_can_owner(device,plan['manifest']['target'])
|
||||
view,before=firmware_target.snapshot(device,plan['manifest']['target'])
|
||||
self.service.config_editor.idle(view,before)
|
||||
backup = self.service.config_editor.backup(view,before)
|
||||
record = {'schema':'missioncore.vesc.firmware-update/v1','device_id':device.id,
|
||||
'session_id':device.session,'identity':dict(device.identity),'image':plan['manifest'],
|
||||
'operation_id':operation,'before_backup_id':backup,'before_backup_device_id':view.id,'started_at':self.utc(),
|
||||
'state':'uploading','progress':0,'write_started':False,'before':packet_hashes(before),'upload_confirmed':False,'binary_readback_verified':False}
|
||||
if previous:
|
||||
self.atomic(self.service.root/('firmware-result-'+previous['operation_id']+'.json'),previous)
|
||||
self.atomic(self.path(device),record) # durable interlock before any erase
|
||||
self.transfers.pop(p['transfer_id']) # consume once, including uncertain start
|
||||
self.service.motor.state('rc')
|
||||
self.cancel_event.clear()
|
||||
with self.lock: self.active = dict(record)
|
||||
try:
|
||||
record['write_started'] = True
|
||||
self.atomic(self.path(device),record)
|
||||
device.link.firmware_rpc('start',sha256=plan['manifest']['sha256'])
|
||||
limit = self.clock()+250
|
||||
while self.clock() < limit:
|
||||
if self.cancel_event.is_set():
|
||||
device.link.firmware_rpc('cancel')
|
||||
self.cancel_event.clear()
|
||||
value = device.link.firmware_rpc('status')
|
||||
with self.lock:
|
||||
self.active.update(progress=value.get('progress',0),message=value.get('message',''))
|
||||
if value.get('state') in ('uploaded','unknown'):
|
||||
record.update(state='awaiting_identity' if value.get('upload_confirmed') else 'unknown',
|
||||
upload_confirmed=value.get('upload_confirmed') is True,
|
||||
progress=value.get('progress',0),message=value.get('message',''),
|
||||
binary_readback_verified=value.get('binary_readback_verified') is True,
|
||||
reboot_confirmed=value.get('reboot_confirmed') is True,boot_verified=False)
|
||||
break
|
||||
self.sleep(.5)
|
||||
else:
|
||||
try: device.link.firmware_rpc('cancel')
|
||||
except (OSError,ValueError,TimeoutError): pass
|
||||
record.update(state='unknown',message='Срок загрузки истёк. Итог не подтверждён.')
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
record.update(state='unknown',message='Связь во время загрузки потеряна. Итог записи не подтверждён.',error=str(error)[:512])
|
||||
finally:
|
||||
record['finished_at'] = self.utc()
|
||||
try:
|
||||
self.atomic(self.path(device),record)
|
||||
finally:
|
||||
with self.lock: self.active = None
|
||||
# Force fresh identification even if the result journal cannot
|
||||
# be updated. The earlier durable pending record stays unsafe.
|
||||
link,device.link = device.link,None
|
||||
device.sample = device.telemetry = None
|
||||
device.session = 'vesc_'+uuid.uuid4().hex
|
||||
device.retry_at = time.monotonic()+2
|
||||
if link: link.close()
|
||||
return record
|
||||
|
||||
def reconcile(self, device):
|
||||
record = self.pending(device)
|
||||
if not record:
|
||||
return {'state':'idle'}
|
||||
gateway = firmware(device.link.query(0))
|
||||
if gateway['uuid']!=record['identity']['uuid'] or gateway['hardware']!=record['identity']['hardware']:
|
||||
raise Rejected('USB-контроллер изменился.')
|
||||
expected=record['image'].get('target')
|
||||
identity=firmware_target.identity(firmware_target.target(device,expected['can_id'])) if expected else gateway
|
||||
expected_identity=expected or record['identity']
|
||||
if identity['uuid'] != expected_identity['uuid'] or identity['hardware'] != expected_identity['hardware']:
|
||||
raise Rejected('Ответил другой контроллер. Привязка прошивки не подтверждена.')
|
||||
# Successful native ACKs plus a fresh identity can settle the upload
|
||||
# workflow, including bootloader transfer. Neither proves binary readback.
|
||||
# Identity alone cannot settle an interrupted/uncertain upload.
|
||||
record['observed_identity'] = identity
|
||||
not_started=False
|
||||
if record.get('write_started') is False:
|
||||
before=firmware_target.snapshot(device,expected)[1] if expected else self.service.config_editor.read(device)
|
||||
not_started=packet_hashes(before)==record.get('before')
|
||||
swd_done='swd' in record['image'] and record.get('binary_readback_verified') is True and record.get('reboot_confirmed') is True
|
||||
if not_started or (record['upload_confirmed'] and (swd_done or ('swd' not in record['image'] and identity['version'] == record['image']['target_version']))):
|
||||
record.update(state='not_started' if not_started else 'identified',finished_at=self.utc())
|
||||
self.atomic(self.service.root/('firmware-result-'+record['operation_id']+'.json'),record)
|
||||
self.path(device).unlink()
|
||||
import os
|
||||
fd = os.open(self.service.root,os.O_RDONLY)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
else:
|
||||
record['state'] = 'unknown'
|
||||
self.atomic(self.path(device),record)
|
||||
return record
|
||||
@@ -51,9 +51,14 @@ def measure(owner, devices, target, original, backups, unchanged, preflight):
|
||||
if "rc_during_native_cycle" not in issues: issues.append("rc_during_native_cycle")
|
||||
sample = values(target.link.query(4, timeout=0.06))
|
||||
samples.append({"at": owner.monotonic() - started, "values": sample})
|
||||
for device in devices: device.link.test_command("claim")
|
||||
# The native Hall procedure exclusively owns the target.
|
||||
# Renewing its output lease is rejected by the native guard
|
||||
# and retires its transport before the result can arrive.
|
||||
# Only keep non-target controllers inhibited and released.
|
||||
for device in devices:
|
||||
if device is not target: device.link.test_command("release")
|
||||
if device is not target:
|
||||
device.link.test_command("claim")
|
||||
device.link.test_command("release")
|
||||
except (OSError, ValueError, TimeoutError):
|
||||
if "communication_unconfirmed" not in issues: issues.append("communication_unconfirmed")
|
||||
if owner.stop.is_set() and "stop_requested_during_native_cycle" not in issues:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Quiescence proof excludes every powered/pending owner; closes transport only."""
|
||||
|
||||
|
||||
def idle(service):
|
||||
remote = service.remote
|
||||
trace=getattr(remote,"trace",None)
|
||||
if trace and (trace.active() or not trace.log.closed):
|
||||
return "diagnostic-capture-active"
|
||||
with remote.lock:
|
||||
if remote.lease.live() or (remote.thread and remote.thread.is_alive()):
|
||||
return "control-active"
|
||||
if remote.release_confirmed is False:
|
||||
return "release-unconfirmed"
|
||||
if service.motor.active:
|
||||
return "motor-procedure-active"
|
||||
with service.firmware_update.lock:
|
||||
if service.firmware_update.active:
|
||||
return "firmware-active"
|
||||
patterns = ("limits_*.json", "*pending*.json", "code-execution-*.json")
|
||||
if any(any(service.root.glob(pattern)) for pattern in patterns):
|
||||
return "device-change-unresolved"
|
||||
with service.lock:
|
||||
devices = list(service.devices.values())
|
||||
if any(service.samples.active(d) for d in devices):
|
||||
return "sample-capture-active"
|
||||
return None
|
||||
|
||||
|
||||
def quiesce(service):
|
||||
# Admission is closed and both discovery/observer callbacks have drained.
|
||||
# No stop/current/lease/release/configuration RPC is issued here.
|
||||
with service.lock:
|
||||
devices = list(service.devices.values())
|
||||
service.devices.clear()
|
||||
for device in devices:
|
||||
device.close()
|
||||
with service.remote.lock:
|
||||
service.remote.primed = False
|
||||
service.remote.state = "observing"
|
||||
@@ -33,7 +33,7 @@ class LimitExceeded(Rejected):
|
||||
super().__init__(f"Тест остановлен: {label} {number(value)} {unit}; диапазон проверки {number(low)}…{number(high)} {unit}.")
|
||||
|
||||
|
||||
def check_configuration(identity, motor, app):
|
||||
def check_configuration(identity, motor, app, *, remote=False):
|
||||
if (identity["version"], identity["hardware"], identity["test_firmware"], identity["hardware_type"]) != ("5.02", "75_300_R2", 0, 0):
|
||||
raise Rejected("Тест поддерживает только проверенный профиль VESC 75_300_R2 / 5.02.")
|
||||
if (motor["motor_type"] != 2 or app["app_to_use"] not in (1, 4)
|
||||
@@ -41,18 +41,39 @@ def check_configuration(identity, motor, app):
|
||||
or app["timeout_brake_current"] != 0 or app["app_ppm_conf.ctrl_type"] != 4
|
||||
or not 0.01 <= app["app_ppm_conf.hyst"] <= 0.3):
|
||||
raise Rejected("Настройки FOC, PPM или тайм-аута не подходят для короткой проверки.")
|
||||
if not 2 <= motor["l_current_max"] <= 100 or not 2 <= motor["l_in_current_max"] <= 100:
|
||||
if any(not math.isfinite(motor[k]) or motor[k] < 2 for k in ("l_current_max", "l_in_current_max")) or (not remote and
|
||||
(motor["l_current_max"] > 100 or motor["l_in_current_max"] > 100)):
|
||||
raise Rejected("Нужна проверка токовых ограничений.")
|
||||
|
||||
|
||||
def check_values(value, moving=False, current_a=2, motor=None, *, standstill_confirmed=False):
|
||||
def check_values(value, moving=False, current_a=2, motor=None, *, standstill_confirmed=False,
|
||||
configured_drive=False, settling=False):
|
||||
current_limit = max(5, current_a * 1.2 + 2) if moving else 1
|
||||
speed_limit = TEST_LIMITS["max_erpm"] if moving else 30
|
||||
duty_limit = TEST_LIMITS["max_duty"] if moving else 0.01
|
||||
if configured_drive and moving:
|
||||
# Remote throttle uses the installed controller's operating envelope;
|
||||
# the separate raised-rig tests retain their 6000 ERPM / 25% bounds.
|
||||
if motor is None:
|
||||
raise Rejected("Пределы контроллера не прочитаны.")
|
||||
speed_limit = min(motor["l_max_erpm"], -motor["l_min_erpm"])
|
||||
duty_limit = motor["l_max_duty"]
|
||||
if not math.isfinite(speed_limit) or speed_limit <= 0 or not 0 < duty_limit <= 1:
|
||||
raise Rejected("Некорректные пределы движения контроллера.")
|
||||
if moving and motor is not None:
|
||||
current_limit = min(current_limit, motor["l_current_max"])
|
||||
# The operating current is regulated inside VESC, not a sampled trip
|
||||
# threshold. Short overshoot/measurement quantization must not kill a
|
||||
# remote session. Firmware fault remains authoritative; retain its
|
||||
# independent absolute-current envelope as a telemetry sanity bound.
|
||||
current_limit = motor["l_abs_current_max"] if configured_drive else min(current_limit, motor["l_current_max"])
|
||||
if not math.isfinite(current_limit) or current_limit <= 0:
|
||||
raise Rejected("Некорректный абсолютный предел тока VESC.")
|
||||
speed_limit = min(speed_limit, motor["l_max_erpm"], -motor["l_min_erpm"])
|
||||
duty_limit = min(duty_limit, motor["l_max_duty"])
|
||||
if configured_drive:
|
||||
# GET_VALUES quantizes duty to 1/1000, whereas MCCONF uses float32
|
||||
# (e.g. 0.949999988). Do not fault at the same configured endpoint.
|
||||
duty_limit = math.ceil(duty_limit * 1000) / 1000
|
||||
# FW 5.02 continues its observer/PLL while undriven. Sensorless ERPM and
|
||||
# tachometer share that estimate, so neither proves physical standstill.
|
||||
# Only explicitly attended Hall/speed/release operations may substitute
|
||||
@@ -66,7 +87,10 @@ def check_values(value, moving=False, current_a=2, motor=None, *, standstill_con
|
||||
# one idle quantum is not proof that PWM is enabled. Permit at most
|
||||
# that quantum only with fresh operator-confirmed physical standstill.
|
||||
# Current/voltage/temperature/fault and neutral-window guards remain.
|
||||
duty_limit = 0.001
|
||||
# Remote preparation may wait through a small idle-estimator transient,
|
||||
# within the ordinary 1% idle bound. This does NOT admit output: the
|
||||
# subsequent whole-profile window still requires <=0.1% continuously.
|
||||
duty_limit = 0.01 if settling else 0.001
|
||||
bounds = (
|
||||
("fault_code", 0, 0, "код ошибки VESC", "", 1),
|
||||
("input_voltage_v", 20, 60, "напряжение питания", "В", 1),
|
||||
@@ -115,11 +139,14 @@ class MotorTest:
|
||||
self.stop.set()
|
||||
|
||||
def neutral(self, devices):
|
||||
receivers = {}
|
||||
for device in devices:
|
||||
value = ppm(device.link.query(31, timeout=0.06))
|
||||
receivers[device.id] = value
|
||||
if self.receiver_active(device.id, value["level"]):
|
||||
self.state("rc")
|
||||
raise Rejected("Приёмник передаёт команду. Управление удерживается за пультом.")
|
||||
return receivers
|
||||
|
||||
def receiver_active(self, identifier, level):
|
||||
if identifier not in self.receiver_bands:
|
||||
@@ -132,7 +159,8 @@ class MotorTest:
|
||||
duration = command["parameters"]["duration_s"]
|
||||
current_a = command["parameters"]["current_a"]
|
||||
group_mode = command["action_id"] == "vesc.drive.run"
|
||||
speed_mode = command["action_id"] in ("vesc.motor.run", "vesc.drive.run")
|
||||
remote_duty = remote is not None and "max_duty_percent" in command["parameters"]
|
||||
speed_mode = command["action_id"] in ("vesc.motor.run", "vesc.drive.run") and not remote_duty
|
||||
moving = [target]
|
||||
if group_mode:
|
||||
from .group_test import targets
|
||||
@@ -153,8 +181,13 @@ class MotorTest:
|
||||
if (deadline - datetime.now(timezone.utc)).total_seconds() < budget + 5:
|
||||
raise Rejected("Не хватило времени для проверки всех контроллеров. Ток не подавался.")
|
||||
attachments = {d.attachment for d in devices}
|
||||
hub = getattr(self.service, "transports", None)
|
||||
pinned = self.service.transport.pin(self.service.drive.value, hub.endpoints()) if hub and remote is not None else None
|
||||
def unchanged():
|
||||
if set(self.service.discover_fn()) != attachments:
|
||||
if hub:
|
||||
try: hub.assert_devices(devices, pinned)
|
||||
except (OSError, ValueError) as error: raise Rejected(str(error)) from error
|
||||
elif set(self.service.discover_fn()) != attachments:
|
||||
raise Rejected("Подключение VESC изменилось. Обновите устройства.")
|
||||
with self.stop_lock:
|
||||
if self.cancelled_at is not None and requested <= self.cancelled_at:
|
||||
@@ -174,11 +207,17 @@ class MotorTest:
|
||||
raise Rejected("Возврат управления пока невозможен: итог калибровки, конфигурация или нулевой ток не подтверждены.") from error
|
||||
identities, applications, backups, originals = {}, {}, [], {}
|
||||
motors, idle_samples = {}, []
|
||||
observed_standstill = (hall_mode or speed_mode or release) and command["parameters"].get("standstill_confirmed") is True
|
||||
observed_standstill = (hall_mode or speed_mode or remote_duty or release) and command["parameters"].get("standstill_confirmed") is True
|
||||
target_motor, target_raw = None, None
|
||||
for device in devices:
|
||||
preflight()
|
||||
if device.link is None: raise Rejected("Один из контроллеров отключён.")
|
||||
if self.service.bms_configuration.pending(device) or self.service.code_tools.blocked(device):
|
||||
raise Rejected("Сначала проверьте запись BMS/кода и остановите Lisp.")
|
||||
if self.service.firmware_update.pending(device):
|
||||
raise Rejected("Итог загрузки прошивки не подтверждён. Управление заблокировано.")
|
||||
if self.service.config_editor.pending(device):
|
||||
raise Rejected("Итог записи конфигурации ещё не подтверждён. Проверьте его в настройках VESC.")
|
||||
if self.limits.pending(device):
|
||||
raise Rejected("Восстановление временных токовых пределов ещё не подтверждено.")
|
||||
if (self.service.root / "hall-pending.json").exists():
|
||||
@@ -191,10 +230,13 @@ class MotorTest:
|
||||
originals[device.id] = configs
|
||||
motor, app = decode(configs["motor"], "motor"), decode(configs["application"], "application")
|
||||
motors[device.id] = motor
|
||||
check_configuration(identity, motor, app)
|
||||
if remote is not None:
|
||||
from .remote_limits import publish
|
||||
publish(device, motor)
|
||||
check_configuration(identity, motor, app, remote=remote is not None)
|
||||
self.receiver_bands[device.id] = neutral_band(app)
|
||||
if device in moving:
|
||||
if not foc_mode and current_a > min(motor["l_current_max"], motor["l_in_current_max"]):
|
||||
if remote is None and not foc_mode and current_a > min(motor["l_current_max"], motor["l_in_current_max"]):
|
||||
raise Rejected("Ток проверки превышает настроенный предел выбранного контроллера.")
|
||||
if not (motor["l_max_erpm"] > 0 and motor["l_min_erpm"] < 0 and 0 < motor["l_max_duty"] <= 1):
|
||||
raise Rejected("Нужна проверка настроенных пределов оборотов и PWM.")
|
||||
@@ -208,7 +250,7 @@ class MotorTest:
|
||||
if speed_mode and abs(command["parameters"]["erpm"]) < motor["s_pid_min_erpm"]:
|
||||
raise Rejected(f"Минимальная скорость регулятора этого VESC: {motor['s_pid_min_erpm']:g} ERPM.")
|
||||
check_values(values(device.link.query(4)), motor=motor,
|
||||
standstill_confirmed=observed_standstill)
|
||||
standstill_confirmed=observed_standstill, settling=remote_duty)
|
||||
identities[device.id], applications[device.id] = identity, app
|
||||
identifier = "op_" + uuid.uuid4().hex
|
||||
backup = {"schema": "missioncore.vesc.config-backup/v1", "device_id": device.id,
|
||||
@@ -236,17 +278,30 @@ class MotorTest:
|
||||
raise Rejected("На CAN обнаружено другое устройство. Нужна проверка схемы.")
|
||||
if foc_mode and len(peers) != 1:
|
||||
raise Rejected("Этот профиль калибрует VESC по отдельным USB без CAN-соседей. Требуется профиль связанного CAN-борта.")
|
||||
for _ in range(10):
|
||||
stable, attempts = 0, 0
|
||||
settle_until = self.monotonic() + 3
|
||||
while stable < 10:
|
||||
preflight()
|
||||
unchanged()
|
||||
self.neutral(devices)
|
||||
receivers = self.neutral(devices)
|
||||
quiet = True
|
||||
attempts += 1
|
||||
if observed_standstill:
|
||||
for device in devices:
|
||||
sample = values(device.link.query(4, timeout=0.06))
|
||||
check_values(sample, motor=motors[device.id],
|
||||
standstill_confirmed=observed_standstill)
|
||||
standstill_confirmed=observed_standstill, settling=remote_duty)
|
||||
if remote_duty and motors[device.id]["foc_sensor_mode"] == 0:
|
||||
quiet = quiet and abs(sample["duty"]) <= 0.001
|
||||
if remote is not None:
|
||||
# Reuse the exclusive owner's actual reads. No extra
|
||||
# CAN traffic and no renewal of an old sample clock.
|
||||
remote._publish(device, sample, receivers[device.id])
|
||||
idle_samples.append({"device_id": device.id, "at": self.monotonic(),
|
||||
"sensor_mode": motors[device.id]["foc_sensor_mode"], "values": sample})
|
||||
stable = stable + 1 if quiet else 0
|
||||
if remote_duty and stable < 10 and (attempts >= 30 or self.monotonic() >= settle_until):
|
||||
raise Rejected("Подготовка остановлена: показатель PWM не стабилизировался за 3 секунды. Проверьте остановку ровера и нейтраль пульта.")
|
||||
self.sleep(0.1)
|
||||
preflight_record = {"standstill_confirmed": observed_standstill, "samples": idle_samples}
|
||||
if release:
|
||||
|
||||
@@ -12,62 +12,127 @@ from pathlib import Path
|
||||
import select
|
||||
import subprocess
|
||||
import time
|
||||
import threading
|
||||
|
||||
from .serial import check_attachment
|
||||
|
||||
|
||||
# A process stuck in kernel USB I/O may outlive SIGKILL. Keep its ownership
|
||||
# until poll confirms exit; do not accumulate replacement owners or waiter threads.
|
||||
_retiring = {}
|
||||
_retiring_lock = threading.Lock()
|
||||
|
||||
|
||||
def reap_retired(tty=None):
|
||||
with _retiring_lock:
|
||||
for key, process in list(_retiring.items()):
|
||||
if process.poll() is not None:
|
||||
del _retiring[key]
|
||||
if tty in _retiring:
|
||||
raise OSError("Previous native USB owner has not exited")
|
||||
|
||||
|
||||
class NativeLink:
|
||||
def __init__(self, attachment):
|
||||
self.attachment = attachment
|
||||
self.process = None
|
||||
self.bridge = None
|
||||
self.buffer = b""
|
||||
self.sequence = 0
|
||||
self.hall_pending = False
|
||||
self.history = deque(maxlen=32)
|
||||
reap_retired(attachment.tty)
|
||||
from .can_bridge import Attachment, Bridge
|
||||
if isinstance(attachment, Attachment):
|
||||
self.bridge = Bridge(attachment)
|
||||
self.check()
|
||||
root = Path("/usr/lib/mission-core-vesc/native")
|
||||
config = Path("/run/mission-core-vesc/native") / hashlib.sha256(attachment.binding.encode()).hexdigest()[:24]
|
||||
config.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(config),
|
||||
XDG_CACHE_HOME=str(config / "cache"), LD_LIBRARY_PATH=str(root / "lib"),
|
||||
QT_PLUGIN_PATH=str(root / "plugins"))
|
||||
QT_PLUGIN_PATH=str(root / "plugins"), TMPDIR=str(config))
|
||||
target = "--can-bridge=" + str(self.bridge.port) if self.bridge else "/dev/" + attachment.tty
|
||||
# Preserve native startup diagnostics in the private runtime directory.
|
||||
with (config / "engine.log").open("wb") as diagnostic:
|
||||
self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), "/dev/" + attachment.tty],
|
||||
try:
|
||||
with (config / "engine.log").open("wb") as diagnostic:
|
||||
self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), target],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=diagnostic,
|
||||
env=env, bufsize=0, close_fds=True)
|
||||
except BaseException:
|
||||
if self.bridge: self.bridge.close()
|
||||
raise
|
||||
try:
|
||||
hello = self._receive(time.monotonic() + 6)
|
||||
if hello.get("ready") is not True or not hello.get("engine", {}).get("connected"):
|
||||
raise OSError("Native VESC Tool did not connect")
|
||||
self.engine = hello["engine"]
|
||||
manifest = json.loads((root / "manifest.json").read_bytes())
|
||||
if (self.engine.get("contract", {}).get("rpc_version") != 1
|
||||
or self.engine.get("contract") != manifest.get("engine_contract")
|
||||
or self.engine.get("version") != manifest.get("upstream_version")
|
||||
or self.engine.get("commit") != manifest.get("upstream_commit")):
|
||||
raise OSError("Native engine contract does not match the installed release")
|
||||
self.check()
|
||||
except BaseException:
|
||||
except BaseException as error:
|
||||
# Preserve this attempt's evidence before close/retry replaces it.
|
||||
try:
|
||||
with (config / "engine.log").open("rb") as diagnostic:
|
||||
diagnostic.seek(0, os.SEEK_END)
|
||||
size = diagnostic.tell()
|
||||
diagnostic.seek(max(0, size - 4096))
|
||||
tail = diagnostic.read(4096).decode("utf-8", errors="replace")
|
||||
error.native_startup = {"pid": self.process.pid,
|
||||
"exit_code": self.process.poll(), "stderr_tail": tail,
|
||||
"stderr_truncated": size > 4096}
|
||||
except Exception:
|
||||
pass
|
||||
if self.bridge:
|
||||
error.can_bridge = self.bridge.diagnostics()
|
||||
self.close()
|
||||
raise
|
||||
|
||||
@property
|
||||
def alive(self):
|
||||
return self.process is not None and self.process.poll() is None
|
||||
return (self.process is not None and self.process.poll() is None
|
||||
and not (getattr(self, "bridge", None) and self.bridge.stop.is_set()))
|
||||
|
||||
def check(self):
|
||||
check_attachment(self.attachment)
|
||||
if getattr(self, "bridge", None):
|
||||
self.bridge.check()
|
||||
else:
|
||||
check_attachment(self.attachment)
|
||||
|
||||
def failure_error(self):
|
||||
bridge = getattr(self, "bridge", None)
|
||||
if bridge and bridge.error:
|
||||
return OSError("CAN bridge: " + str(bridge.error)[:512])
|
||||
code = self.process.poll() if self.process is not None else None
|
||||
return OSError(f"Native transport exited (code={code})")
|
||||
|
||||
def _receive(self, deadline):
|
||||
while b"\n" not in self.buffer:
|
||||
if not self.alive or not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]:
|
||||
if not self.alive:
|
||||
raise self.failure_error()
|
||||
if not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]:
|
||||
if not self.alive:
|
||||
raise self.failure_error()
|
||||
raise TimeoutError("Native VESC Tool response timed out")
|
||||
data = os.read(self.process.stdout.fileno(), 65536)
|
||||
if not data: raise OSError("Native VESC Tool exited")
|
||||
if not data: raise self.failure_error()
|
||||
self.buffer += data
|
||||
if len(self.buffer) > 2 * 1024 * 1024: raise ValueError("Native response exceeds bound")
|
||||
line, self.buffer = self.buffer.split(b"\n", 1)
|
||||
return json.loads(line)
|
||||
|
||||
def rpc(self, method, timeout=2, **parameters):
|
||||
# These two methods only inspect/cancel the already-owned native job.
|
||||
# They must survive the expected USB detach caused by fwUpload itself;
|
||||
# no other method may bypass exact-attachment validation.
|
||||
detached_status = method in ('firmware_status','firmware_cancel')
|
||||
self.sequence += 1
|
||||
request = json.dumps({"id": self.sequence, "method": method, **parameters}, allow_nan=False).encode()+b"\n"
|
||||
if len(request) > 65536: raise ValueError("Native request exceeds bound")
|
||||
if len(request) > (2*1024*1024 if method == "package_unpack" else 512*1024 if method in ("code_pack", "code_write") else 65536): raise ValueError("Native request exceeds bound")
|
||||
started = time.monotonic()
|
||||
deadline = started + timeout
|
||||
trace = {"method": method, "command": parameters.get("command"),
|
||||
@@ -76,14 +141,19 @@ class NativeLink:
|
||||
"tty": self.attachment.tty}}
|
||||
try:
|
||||
trace["stage"] = "attachment_before"
|
||||
self.check()
|
||||
if not detached_status: self.check()
|
||||
trace["attachment_before_ms"] = (time.monotonic()-started)*1000
|
||||
trace["stage"] = "request_write"
|
||||
if not self.alive: raise OSError("Native VESC Tool is not running")
|
||||
if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]:
|
||||
raise TimeoutError("Native VESC Tool request timed out")
|
||||
if os.write(self.process.stdin.fileno(), request) != len(request):
|
||||
raise OSError("Native request write incomplete")
|
||||
offset = 0
|
||||
while offset < len(request):
|
||||
if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]:
|
||||
raise TimeoutError("Native request write timed out")
|
||||
written = os.write(self.process.stdin.fileno(), request[offset:offset+4096])
|
||||
if written <= 0: raise OSError("Native request write incomplete")
|
||||
offset += written
|
||||
sent_at = time.monotonic()
|
||||
trace["request_write_ms"] = (sent_at-started)*1000-trace["attachment_before_ms"]
|
||||
trace["stage"] = "native_response"
|
||||
@@ -92,12 +162,14 @@ class NativeLink:
|
||||
trace["native_response_ms"] = (received_at-sent_at)*1000
|
||||
if not isinstance(response, dict): raise ValueError("Invalid native response")
|
||||
if response.get("id") != self.sequence: raise ValueError("Native response identity mismatch")
|
||||
if isinstance(response.get("control"), dict): trace["control"] = response["control"]
|
||||
if getattr(self, "bridge", None): trace["can_bridge"] = self.bridge.diagnostics()
|
||||
if response.get("ok") is not True:
|
||||
if isinstance(response.get("diagnostics"), dict):
|
||||
trace["transport"] = response["diagnostics"]
|
||||
raise OSError(response.get("error", "Native operation failed"))
|
||||
trace["stage"] = "attachment_after"
|
||||
self.check()
|
||||
if not detached_status: self.check()
|
||||
trace["attachment_after_ms"] = (time.monotonic()-received_at)*1000
|
||||
trace["stage"] = "complete"
|
||||
result = response.get("result")
|
||||
@@ -112,11 +184,13 @@ class NativeLink:
|
||||
process_alive=self.alive, error=str(error))
|
||||
try: self.check(); trace["attachment_present"] = True
|
||||
except OSError: trace["attachment_present"] = False
|
||||
if getattr(self, "bridge", None):
|
||||
trace["can_bridge"] = self.bridge.diagnostics()
|
||||
self.last_rpc = trace
|
||||
if hasattr(self, "history"): self.history.append(trace)
|
||||
error.native_rpc = trace
|
||||
error.native_history = list(getattr(self, "history", []))
|
||||
self.close()
|
||||
trace["cleanup"] = self.close()
|
||||
raise
|
||||
|
||||
def query(self, command, timeout=2):
|
||||
@@ -133,13 +207,40 @@ class NativeLink:
|
||||
def test_speed(self, erpm):
|
||||
self.rpc("rpm", timeout=0.1, erpm=erpm)
|
||||
|
||||
def drive_duty(self, duty, current_a):
|
||||
self.rpc("duty_limited", timeout=0.1, duty=duty, current_a=current_a)
|
||||
|
||||
def set_temporary_limits(self, config):
|
||||
from .temporary_limits import FIELDS
|
||||
self.rpc("limits", timeout=2.2, parameters={k: config[k] for k in FIELDS})
|
||||
|
||||
def diagnostic(self, command):
|
||||
return self.rpc("diagnostic", timeout=3.5, command=command)
|
||||
|
||||
def device_tool(self, tool):
|
||||
return self.rpc("device_tool",timeout=3,tool=tool)
|
||||
|
||||
def bms_read(self, can_id):
|
||||
return self.rpc("bms_read", timeout=6, can_id=can_id)
|
||||
|
||||
def bms_command(self, target, command):
|
||||
return self.rpc("bms_command", timeout=3, can_id=target['can_id'], target=target, command=command)
|
||||
|
||||
def configuration(self):
|
||||
return self.rpc("configuration", timeout=5)
|
||||
|
||||
def configuration_preview(self, sources):
|
||||
return self.rpc("configuration_preview", timeout=6, sources=sources)
|
||||
|
||||
def configuration_apply(self, kind, target):
|
||||
return self.rpc("configuration_apply", timeout=9, kind=kind,
|
||||
**{k: target[k] for k in ("payload", "before_sha256", "after_sha256")})
|
||||
|
||||
def firmware_rpc(self, action, **parameters):
|
||||
if action not in ('begin','chunk','seal','start','status','cancel','target','snapshot'):
|
||||
raise ValueError('Unknown firmware operation')
|
||||
return self.rpc('firmware_' + action, timeout=11 if action=='snapshot' else 4, **parameters)
|
||||
|
||||
def detect_hall(self):
|
||||
if self.hall_pending: raise ValueError("Hall measurement already pending")
|
||||
self.hall_pending = True
|
||||
@@ -160,12 +261,35 @@ class NativeLink:
|
||||
return base64.b64decode(result["payload"], validate=True)
|
||||
|
||||
def close(self):
|
||||
if getattr(self, "bridge", None):
|
||||
self.bridge.close()
|
||||
process, self.process = self.process, None
|
||||
if process is None: return
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try: process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=1)
|
||||
for stream in (process.stdin, process.stdout):
|
||||
if stream: stream.close()
|
||||
result = {"exit_confirmed": False}
|
||||
try:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
try:
|
||||
process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
# SIGKILL cannot finish uninterruptible kernel I/O.
|
||||
# Retire the owner below without masking the original RPC.
|
||||
pass
|
||||
except OSError as error:
|
||||
result["error"] = str(error)[:256]
|
||||
finally:
|
||||
result["exit_confirmed"] = process.poll() is not None
|
||||
if not result["exit_confirmed"]:
|
||||
with _retiring_lock:
|
||||
_retiring[self.attachment.tty] = process
|
||||
for stream in (process.stdin, process.stdout):
|
||||
if stream:
|
||||
try:
|
||||
stream.close()
|
||||
except OSError as error:
|
||||
result["pipe_error"] = str(error)[:256]
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Bounded Qt RCC and VESC package containers. Never evaluates QML or Lisp."""
|
||||
import hashlib
|
||||
import re
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
MAX_ARCHIVE=8*1024*1024
|
||||
MAX_PACKAGE=1024*1024
|
||||
MAX_EXPANDED=4*1024*1024
|
||||
|
||||
def digest(data):return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def uncompress(data,limit=MAX_EXPANDED):
|
||||
if len(data)<5:raise ValueError('Truncated Qt compressed data')
|
||||
size=int.from_bytes(data[:4],'big')
|
||||
if not 0<size<=limit:raise ValueError('Expanded package exceeds bound')
|
||||
decoder=zlib.decompressobj()
|
||||
try:out=decoder.decompress(data[4:],size+1)
|
||||
except zlib.error as error:raise ValueError('Invalid compressed package stream') from error
|
||||
if len(out)!=size or not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:raise ValueError('Invalid compressed package size or stream')
|
||||
return out
|
||||
|
||||
def fields(data):
|
||||
if not 5<=len(data)<=MAX_PACKAGE:raise ValueError('Package exceeds bound')
|
||||
raw=uncompress(data)
|
||||
if not raw.startswith(b'VESC Packet\0'):raise ValueError('Not a VESC package')
|
||||
at=12;out={}
|
||||
while at<len(raw):
|
||||
end=raw.find(b'\0',at,at+65)
|
||||
if end<at+1 or end+5>len(raw):raise ValueError('Invalid package field')
|
||||
name=raw[at:end].decode('ascii');size=struct.unpack_from('>i',raw,end+1)[0];at=end+5
|
||||
if name in out or size<0 or size>len(raw)-at or len(out)>=32:raise ValueError('Duplicate, truncated or excessive package field')
|
||||
out[name]=raw[at:at+size];at+=size
|
||||
if not out.get('name') or len(out['name'])>256:raise ValueError('Package name required')
|
||||
for k in ('name','description','description_md','qmlFile','pkgDescQml'):
|
||||
if k in out and b'\0' in out[k]:raise ValueError('Invalid text field')
|
||||
if k in out:out[k].decode('utf-8')
|
||||
if out.get('qmlIsFullscreen',b'\0') not in (b'\0',b'\1'):raise ValueError('Invalid fullscreen flag')
|
||||
return out
|
||||
|
||||
def metadata(data,path='import.vescpkg'):
|
||||
f=fields(data)
|
||||
return {'id':digest(data),'path':path,'name':f['name'].decode(),'library':path.split('/')[0].startswith('lib_'),
|
||||
'bytes':len(data),'lisp_bytes':len(f.get('lispData',b'')),'qml_bytes':len(f.get('qmlFile',b'')),
|
||||
'description':f.get('description_md',b'').decode()[:65536], 'has_compatibility':bool(f.get('pkgDescQml'))}
|
||||
|
||||
def archive(data):
|
||||
if not 24<=len(data)<=MAX_ARCHIVE or data[:4]!=b'qres':raise ValueError('Invalid Qt package archive')
|
||||
version,tree,blobs,names,features=struct.unpack_from('>5I',data,4)
|
||||
if version not in (2,3) or features!=0 or not 24<=blobs<names<tree<len(data) or (len(data)-tree)%22:raise ValueError('Unsupported RCC layout')
|
||||
count=(len(data)-tree)//22
|
||||
if not 2<=count<=2048:raise ValueError('RCC node bound exceeded')
|
||||
seen=set();out={};total=0
|
||||
def visit(index,parent,depth):
|
||||
nonlocal total
|
||||
if index in seen or not 0<=index<count or depth>5:raise ValueError('Invalid RCC tree')
|
||||
seen.add(index);at=tree+index*22;name_offset,flags=struct.unpack_from('>IH',data,at)
|
||||
if flags&~3:raise ValueError('Unsupported RCC compression')
|
||||
if index==0:path=''
|
||||
else:
|
||||
n=names+name_offset
|
||||
if not names<=n<tree-6:raise ValueError('Invalid RCC name')
|
||||
size=int.from_bytes(data[n:n+2],'big')
|
||||
if not 0<size<=128 or n+6+size*2>tree:raise ValueError('RCC name exceeds bound')
|
||||
name=data[n+6:n+6+size*2].decode('utf-16-be')
|
||||
if not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',name) or name in ('.','..'):raise ValueError('Invalid RCC path')
|
||||
path=parent+'/'+name if parent else name
|
||||
if flags&2:
|
||||
children,first=struct.unpack_from('>II',data,at+6)
|
||||
if children<1 or first+children>count:raise ValueError('Invalid RCC children')
|
||||
for i in range(first,first+children):visit(i,path,depth+1)
|
||||
else:
|
||||
offset=int.from_bytes(data[at+10:at+14],'big');pos=blobs+offset
|
||||
if not blobs<=pos<names-4:raise ValueError('Invalid RCC data pointer')
|
||||
size=int.from_bytes(data[pos:pos+4],'big')
|
||||
if not 0<size<=MAX_PACKAGE or pos+4+size>names:raise ValueError('Invalid RCC file size')
|
||||
blob=data[pos+4:pos+4+size]
|
||||
if flags&1:blob=uncompress(blob,MAX_PACKAGE)
|
||||
if not path.startswith('vesc_packages/') or not path.endswith('.vescpkg') or path in out:raise ValueError('Unexpected RCC member')
|
||||
total+=len(blob)
|
||||
if total>MAX_ARCHIVE or len(out)>=128:raise ValueError('Catalog exceeds bound')
|
||||
fields(blob);out[path.removeprefix('vesc_packages/')]=blob
|
||||
visit(0,'',0)
|
||||
if len(seen)!=count or not out:raise ValueError('Incomplete RCC tree')
|
||||
return out
|
||||
@@ -0,0 +1,65 @@
|
||||
"""One pinned catalogue plus one bounded, operator-imported replacement."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
from .package_archive import archive,metadata,digest,MAX_ARCHIVE,MAX_PACKAGE
|
||||
|
||||
ROOT=Path('/usr/lib/mission-core-vesc/package-catalog')
|
||||
|
||||
class PackageCatalog:
|
||||
def __init__(self,root,atomic,builtin=ROOT):self.root,self.atomic,self.builtin=root,atomic,builtin;self.cached=None;self.cache_key=None
|
||||
def load(self):
|
||||
path=self.root/'package-catalog.json'
|
||||
key=(path.stat().st_mtime_ns,path.stat().st_size) if path.exists() else None
|
||||
if self.cached is not None and key==self.cache_key:return self.cached
|
||||
if path.exists():
|
||||
if path.stat().st_size>12*1024*1024:raise ValueError('Package catalogue exceeds storage bound')
|
||||
value=json.loads(path.read_text());data=base64.b64decode(value['data'],validate=True)
|
||||
if digest(data)!=value['sha256']:raise ValueError('Stored package catalogue changed')
|
||||
else:
|
||||
value=json.loads((self.builtin/'catalog.json').read_text());data=(self.builtin/'vesc_pkg_all.rcc').read_bytes()
|
||||
if len(data)!=value['bytes'] or digest(data)!=value['sha256']:raise ValueError('Bundled package catalogue changed')
|
||||
entries=archive(data);self.cached=(value,entries);self.cache_key=key;return self.cached
|
||||
def imports(self):
|
||||
path=self.root/'package-imports.json'
|
||||
if not path.exists():return {}
|
||||
if path.stat().st_size>12*1024*1024:raise ValueError('Imported packages exceed storage bound')
|
||||
values=json.loads(path.read_text())
|
||||
if len(values)>16:raise ValueError('Too many imported packages')
|
||||
return values
|
||||
def listing(self):
|
||||
version,entries=self.load();items=[metadata(v,k) for k,v in entries.items()]
|
||||
items+=[{**metadata(base64.b64decode(v['data'],validate=True),v['name']),'library':v['library'],'imported':True} for v in self.imports().values()]
|
||||
items=[{**i,'description':i['description'][:160]} for i in items]
|
||||
return {'sha256':version['sha256'],'source':version.get('source','import'),'items':sorted(items,key=lambda i:(i['library'],i['name'].lower()))}
|
||||
def get(self,key):
|
||||
_,entries=self.load()
|
||||
for path,data in entries.items():
|
||||
if digest(data)==key:return metadata(data,path),data
|
||||
item=self.imports().get(key)
|
||||
if item:
|
||||
data=base64.b64decode(item['data'],validate=True)
|
||||
if digest(data)!=key:raise ValueError('Imported package changed')
|
||||
return {**metadata(data,item['name']),'library':item['library'],'imported':True},data
|
||||
raise ValueError('Пакет отсутствует в текущем каталоге. Обновите список.')
|
||||
def save(self,path,value):
|
||||
size=len(json.dumps(value,ensure_ascii=False).encode())
|
||||
occupied=sum(p.stat().st_size for p in self.root.glob('*.json') if p!=path)
|
||||
if occupied+size>24*1024*1024:raise ValueError('Хранилище каталога заполнено; сохранён резерв для журнала и восстановления.')
|
||||
self.atomic(path,value)
|
||||
def publish(self,data,kind,name,library,source):
|
||||
if kind=='catalog':
|
||||
items=archive(data);value={'schema':'missioncore.vesc.package-catalog/v1','sha256':digest(data),'bytes':len(data),'source':source,'data':base64.b64encode(data).decode()}
|
||||
self.save(self.root/'package-catalog.json',value);self.cached=None
|
||||
return {'count':len(items),'sha256':digest(data)}
|
||||
if len(data)>MAX_PACKAGE:raise ValueError('Package exceeds bound')
|
||||
item=metadata(data,name)
|
||||
_,entries=self.load()
|
||||
if any(digest(v)==item['id'] for v in entries.values()):return {'id':item['id'],'existing':True}
|
||||
values=self.imports();values[item['id']]={'name':name,'library':library,'data':base64.b64encode(data).decode()}
|
||||
if len(values)>16 or sum(len(base64.b64decode(v['data'])) for v in values.values())>MAX_ARCHIVE:raise ValueError('Хранилище импортов заполнено. Удалите ненужный импорт из списка.')
|
||||
self.save(self.root/'package-imports.json',values);return {'id':item['id']}
|
||||
def forget(self,key):
|
||||
values=self.imports()
|
||||
if key not in values:raise ValueError('Удалять из списка можно только отдельные импорты.')
|
||||
values.pop(key);self.save(self.root/'package-imports.json',values);return {'removed':True}
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Catalogue and whole-extension transactions; no automatic program execution."""
|
||||
from collections import OrderedDict
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime,timezone
|
||||
from .code_tools import ID,HASH
|
||||
from .motor_test import Rejected
|
||||
from .package_archive import digest,MAX_ARCHIVE,MAX_PACKAGE
|
||||
from .package_catalog import PackageCatalog
|
||||
|
||||
PREFIX='vesc.packages.'
|
||||
NAMES=('catalog','inspect','download','begin','chunk','load','forget','status','prepare','remove_prepare','restore','apply','reconcile')
|
||||
ACTIONS=frozenset(PREFIX+n for n in NAMES)
|
||||
READS=ACTIONS-{PREFIX+'apply'}
|
||||
|
||||
def validate(action,p):
|
||||
n=action.removeprefix(PREFIX)
|
||||
shapes={'catalog':set(),'inspect':{'id'},'download':{'id','offset'},'begin':{'kind','name','size','sha256','library','source'},'chunk':{'upload_id','offset','data'},'load':{'upload_id'},'forget':{'id'},'status':set(),'prepare':{'id','compatibility_confirmed'},'remove_prepare':set(),'restore':set(),'apply':{'preview_id','confirmed','inputs_isolated'},'reconcile':set()}
|
||||
if n not in shapes or set(p)!=shapes[n]:raise ValueError('Invalid package operation parameters')
|
||||
if 'id' in p and (not isinstance(p['id'],str) or not HASH.fullmatch(p['id'])):raise ValueError('Invalid package digest')
|
||||
for k in ('upload_id','preview_id'):
|
||||
if k in p and (not isinstance(p[k],str) or not ID.fullmatch(p[k])):raise ValueError('Invalid package transaction')
|
||||
if n=='begin':
|
||||
if p['kind'] not in ('catalog','package') or not isinstance(p['name'],str) or not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',p['name']) or p['name'] in ('.','..') or type(p['library']) is not bool or p['source'] not in ('import','upstream'):raise ValueError('Invalid package import metadata')
|
||||
if type(p['size']) is not int or not 5<=p['size']<=(MAX_ARCHIVE if p['kind']=='catalog' else MAX_PACKAGE) or not isinstance(p['sha256'],str) or not HASH.fullmatch(p['sha256']):raise ValueError('Invalid package size/hash')
|
||||
if 'offset' in p and (type(p['offset']) is not int or p['offset']<0):raise ValueError('Invalid package offset')
|
||||
if n=='chunk':
|
||||
if not isinstance(p['data'],str) or not 0<len(p['data'])<=22000:raise ValueError('Invalid package chunk')
|
||||
raw=base64.b64decode(p['data'],validate=True)
|
||||
if not 0<len(raw)<=16384 or base64.b64encode(raw).decode()!=p['data']:raise ValueError('Invalid package chunk encoding')
|
||||
if n=='prepare' and type(p['compatibility_confirmed']) is not bool:raise ValueError('Compatibility confirmation required')
|
||||
if n=='apply' and (p['confirmed'] is not True or p['inputs_isolated'] is not True):raise ValueError('Explicit isolated-input confirmation required')
|
||||
|
||||
def image(snapshot,kind):
|
||||
data=base64.b64decode(snapshot['payload'],validate=True)
|
||||
if digest(data)!=snapshot['sha256']:raise ValueError('Backup digest changed')
|
||||
if not data:return ''
|
||||
flags=2 if snapshot.get('fullscreen') else 1 if kind=='qml' else 0
|
||||
content=flags.to_bytes(2,'big')+data
|
||||
raw=len(data).to_bytes(4,'big')+binascii.crc_hqx(content,0).to_bytes(2,'big')+content
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
def expected(images):
|
||||
return {k:{'sha256':digest(base64.b64decode(v)[8:]),'fullscreen':bool(v and base64.b64decode(v)[7]==2)} for k,v in images.items()}
|
||||
|
||||
def same(a,b):return all(a[k]['sha256']==b[k]['sha256'] and a[k]['fullscreen']==b[k]['fullscreen'] for k in ('lisp','qml'))
|
||||
|
||||
class PackageTools:
|
||||
def __init__(self,service,atomic,utc):
|
||||
self.service,self.atomic,self.utc=service,atomic,utc;self.code=service.code_tools
|
||||
self.catalog=PackageCatalog(service.root,atomic);self.uploads=OrderedDict();self.plans=OrderedDict()
|
||||
def path(self,device,kind='pending'):return self.service.root/('package-'+kind+'-'+(device if isinstance(device,str) else device.id)+'.json')
|
||||
def record(self,device,kind='pending'):
|
||||
path=self.path(device,kind);return json.loads(path.read_text()) if path.exists() else None
|
||||
def read(self,device):return {k:device.link.rpc('code_snapshot',timeout=30,kind=k) for k in ('lisp','qml')}
|
||||
def inspect(self,device,key):
|
||||
meta,data=self.catalog.get(key)
|
||||
value=device.link.rpc('package_unpack',timeout=4,data=base64.b64encode(data).decode(),identity=device.identity)
|
||||
return {**meta,**value}
|
||||
def resolve_imports(self,device,project):
|
||||
if project['kind']!='lisp' or 'pkg' not in project['source']:return project
|
||||
pattern=re.compile(r'(?im)^([ \t]*\(import +)"(pkg(?:::[A-Za-z_][A-Za-z0-9_-]{0,63})?@://vesc_packages/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.vescpkg))"( +\'?([A-Za-z_][A-Za-z0-9_-]{0,63})\) *\r?(?:;[^\n]*)?)$')
|
||||
matches=list(pattern.finditer(project['source']))
|
||||
if not matches:return project
|
||||
if len(matches)>32:raise ValueError('Too many package imports')
|
||||
_,entries=self.catalog.load();files=dict(project['imports']);cached={}
|
||||
def replace(match):
|
||||
path=match[3]
|
||||
if path not in entries:raise Rejected('Библиотека не найдена в сохранённом каталоге: '+path)
|
||||
if path not in cached:
|
||||
data=entries[path];cached[path]=device.link.rpc('package_unpack',timeout=4,data=base64.b64encode(data).decode(),identity=device.identity,export_library=True)
|
||||
value=cached[path]
|
||||
if value['compatible'] is False:raise Rejected('Библиотека несовместима с контроллером: '+path)
|
||||
tag=match[2].split('@',1)[0].removeprefix('pkg::') if match[2].startswith('pkg::') else None
|
||||
if tag:
|
||||
payload=value['library']['imports'].get(tag)
|
||||
if payload is None:raise Rejected('В библиотеке нет вложения '+tag)
|
||||
else:payload=base64.b64encode(value['library']['source'].encode()).decode()
|
||||
name='pkg_'+digest(entries[path])[:16]+'_'+match[5]+'.bin'
|
||||
if name in files and files[name]!=payload:raise ValueError('Package attachment name collision')
|
||||
files[name]=payload
|
||||
return match[1]+'"'+name+'"'+match[4]
|
||||
source=pattern.sub(replace,project['source'])
|
||||
return {**project,'source':source,'imports':files}
|
||||
def supported(self,device):
|
||||
if not self.code.supported(device):raise Rejected('Установка расширений требует поддерживаемого профиля VESC 6.00. Каталог и импорт доступны без смены прошивки.')
|
||||
def preview(self,device,images,meta,recovery=False):
|
||||
self.supported(device);self.code.idle(device,allow_package=True)
|
||||
if self.code.blocked(device) and not (recovery and self.record(device)):raise Rejected('Сначала проверьте предыдущую запись и остановите Lisp.')
|
||||
before=self.read(device);key=self.code.remember(self.plans,{**self.code.identity(device),'before':before,'images':images,'meta':meta,'recovery':recovery})
|
||||
return {'preview_id':key,'package':meta,'before':{k:{x:v[x] for x in ('sha256','bytes','fullscreen')} for k,v in before.items()},'after':expected(images),'expires_in_s':300,'running_requested':False}
|
||||
def execute(self,device,action,p,operation,deadline):
|
||||
n=action.removeprefix(PREFIX)
|
||||
if n=='catalog':return self.catalog.listing()
|
||||
if n=='inspect':
|
||||
value=self.inspect(device,p['id']);value.pop('images');return value
|
||||
if n=='download':
|
||||
meta,data=self.catalog.get(p['id']);at=p['offset']
|
||||
if at>len(data):raise ValueError('Download offset exceeds package')
|
||||
return {'id':p['id'],'name':meta['path'].split('/')[-1],'bytes':len(data),'offset':at,'data':base64.b64encode(data[at:at+16384]).decode()}
|
||||
if n=='forget':return self.catalog.forget(p['id'])
|
||||
if n=='begin':return {'upload_id':self.code.remember(self.uploads,{**self.code.identity(device),**p,'data':bytearray()}),'chunk_bytes':16384}
|
||||
if n in ('chunk','load'):
|
||||
upload=self.uploads.get(p['upload_id'])
|
||||
if not upload or not self.code.match(device,upload):raise Rejected('Передача истекла или изменился сеанс контроллера.')
|
||||
if n=='chunk':
|
||||
raw=base64.b64decode(p['data'],validate=True);at=p['offset']
|
||||
if at<len(upload['data']) and upload['data'][at:at+len(raw)]==raw:return {'offset':len(upload['data'])}
|
||||
if at!=len(upload['data']) or at+len(raw)>upload['size']:raise ValueError('Package fragment offset/size mismatch')
|
||||
upload['data'].extend(raw);upload['at']=self.code.clock();return {'offset':len(upload['data'])}
|
||||
data=bytes(upload['data'])
|
||||
if len(data)!=upload['size'] or digest(data)!=upload['sha256']:raise ValueError('Package import checksum mismatch')
|
||||
value=self.catalog.publish(data,upload['kind'],upload['name'],upload['library'],upload['source']);self.uploads.pop(p['upload_id']);return value
|
||||
self.supported(device)
|
||||
if n=='status':
|
||||
current=self.read(device);installed=self.record(device,'installed');known=bool(installed and installed['identity']==device.identity and same(current,installed['expected']))
|
||||
return {'pending':bool(self.record(device)),'installed':installed['meta'] if known else None,'recognized':known,'empty':all(v['bytes']==0 for v in current.values()),'current':{k:{x:v[x] for x in ('sha256','bytes','fullscreen')} for k,v in current.items()}}
|
||||
if n=='prepare':
|
||||
value=self.inspect(device,p['id'])
|
||||
if value['library']:raise Rejected('Библиотека используется как import в Lisp; отдельно на контроллер не устанавливается.')
|
||||
if value['compatible'] is False:raise Rejected('Автор пакета исключил этот тип контроллера или прошивку.')
|
||||
if value['compatible'] is None and not p['compatibility_confirmed']:raise Rejected('В пакете нет проверяемых условий совместимости. Подтвердите совместимость по документации автора.')
|
||||
if not value['fits']:raise Rejected('Размер кода превышает предел flash этого профиля.')
|
||||
return self.preview(device,value['images'],{k:value[k] for k in ('id','path','name')})
|
||||
if n=='remove_prepare':return self.preview(device,{'lisp':'','qml':''},None)
|
||||
if n=='restore':
|
||||
record=self.record(device,'backup')
|
||||
if not record or record['identity']!=device.identity:raise Rejected('Нет исходной копии для этого контроллера и прошивки.')
|
||||
return self.preview(device,{k:image(v,k) for k,v in record['before'].items()},record.get('previous_meta'),True)
|
||||
if n=='reconcile':return self.reconcile(device)
|
||||
plan=self.plans.get(p['preview_id'])
|
||||
if not plan or not self.code.match(device,plan):raise Rejected('Подтверждение истекло или изменился контроллер.')
|
||||
return self.apply(device,p['preview_id'],plan,operation,deadline)
|
||||
def apply(self,device,key,plan,operation,deadline):
|
||||
self.code.idle(device,allow_package=True)
|
||||
if self.code.path(device).exists() or self.code.path(device,'execution').exists():raise Rejected('Сначала проверьте запись кода и остановите Lisp.')
|
||||
if self.record(device) and not plan['recovery']:raise Rejected('Предыдущее изменение расширения не подтверждено.')
|
||||
if (deadline-datetime.now(timezone.utc)).total_seconds()<330:raise Rejected('Недостаточно времени для записи расширения и проверки.')
|
||||
before=self.read(device)
|
||||
if not same(before,plan['before']):raise Rejected('Код изменился после предварительного просмотра.')
|
||||
installed=self.record(device,'installed');previous=installed['meta'] if installed and installed['identity']==device.identity and same(before,installed['expected']) else None
|
||||
record={'schema':'missioncore.vesc.package-write/v1','identity':device.identity,'operation_id':operation,'before':before,'expected':expected(plan['images']),'meta':plan['meta'],'previous_meta':previous,'recovery':plan['recovery'],'state':'unknown','started_at':self.utc()}
|
||||
# One durable recovery copy per controller, retained across restart.
|
||||
# A recovery attempt must never replace the original backup with a partial result.
|
||||
if not plan['recovery']:self.atomic(self.path(device,'backup'),record)
|
||||
self.atomic(self.path(device),record);self.plans.pop(key);self.service.motor.state('rc')
|
||||
try:
|
||||
stopped=device.link.rpc('code_control',timeout=8,command='stop',text='')
|
||||
if stopped.get('acknowledged') is not True:raise ValueError('Lisp stop not acknowledged')
|
||||
for kind in ('qml','lisp'):
|
||||
raw=plan['images'][kind]
|
||||
r=device.link.rpc('code_write',timeout=100,kind=kind,image=raw,erase=not bool(raw),baseline=before[kind]['sha256'],baseline_fullscreen=before[kind]['fullscreen'])
|
||||
if r.get('verified') is not True:raise ValueError('Missing package readback')
|
||||
if not same(self.read(device),record['expected']):raise ValueError('Whole package readback mismatch')
|
||||
self.finish(device,record,'applied');return {'verified':True,'outcome':'applied','running_requested':False}
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
record['failure_type']=type(error).__name__;self.atomic(self.path(device),record)
|
||||
return {'verified':False,'outcome':'unknown','message':'Запись могла выполниться частично. Автоповтора нет. Проверьте содержимое или восстановите исходную копию.'}
|
||||
def finish(self,device,record,outcome):
|
||||
if outcome=='applied':self.atomic(self.path(device,'installed'),{'identity':device.identity,'meta':record['meta'],'expected':record['expected']})
|
||||
self.atomic(self.path(device,'result'),{'operation_id':record['operation_id'],'outcome':outcome,'finished_at':self.utc()});self.code.clear(self.path(device))
|
||||
def reconcile(self,device):
|
||||
record=self.record(device)
|
||||
if not record:return {'verified':True,'outcome':'no_pending_write'}
|
||||
if record['identity']!=device.identity:raise Rejected('Незавершённая запись относится к другой прошивке или контроллеру.')
|
||||
current=self.read(device);outcome='applied' if same(current,record['expected']) else 'unchanged' if not record.get('recovery') and same(current,record['before']) else 'different'
|
||||
if outcome!='different':self.finish(device,record,outcome)
|
||||
return {'verified':outcome!='different','outcome':outcome}
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Read-only recovery of missing bound devices before motor ownership began."""
|
||||
import copy
|
||||
import re
|
||||
|
||||
from .release_observation import ReleaseObservation
|
||||
|
||||
|
||||
class PreflightRecovery:
|
||||
def __init__(self, profile):
|
||||
self.profile = copy.deepcopy(profile)
|
||||
self.proof = None
|
||||
|
||||
def reset(self):
|
||||
self.proof = None
|
||||
|
||||
def check(self, profile, devices, now, receiver_active, limits_pending):
|
||||
if profile != self.profile:
|
||||
self.reset()
|
||||
return False
|
||||
selected = []
|
||||
for binding in self.profile["bindings"].values():
|
||||
matches = [d for d in devices if d.id == binding["device_id"]]
|
||||
if len(matches) != 1:
|
||||
self.reset()
|
||||
return False
|
||||
d = matches[0]
|
||||
expected = binding.get("uuid", "")
|
||||
if (not re.fullmatch(r"[0-9a-f]{24}", expected)
|
||||
or d.identity.get("uuid") != expected
|
||||
or getattr(d, "identified_session", None) != d.session
|
||||
or not d.link or not getattr(d.link, "alive", True)
|
||||
or limits_pending(d)):
|
||||
self.reset()
|
||||
return False
|
||||
selected.append(d)
|
||||
if not selected:
|
||||
return False
|
||||
if self.proof is None:
|
||||
self.proof = ReleaseObservation(selected, now)
|
||||
return self.proof.check(selected, now, receiver_active)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Typed, rate-limited reads between isolated QML and the sole USB owner.
|
||||
|
||||
No raw packet forwarding, writes, terminal, CAN routing, captures or code execution.
|
||||
No background acquisition: a bounded batch is serviced on an operator frame request.
|
||||
"""
|
||||
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
|
||||
from .motor_test import Rejected
|
||||
|
||||
READ_CODES = frozenset((0, 4, 14, 17, 31, 32, 33, 65, 96))
|
||||
|
||||
|
||||
def read_intent(value):
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid QML read intent")
|
||||
command = value.get("command")
|
||||
if type(command) is not int or command not in READ_CODES:
|
||||
raise ValueError("QML command is not a permitted read")
|
||||
if set(value) != ({"command", "mask"} if command == 65 else {"command"}):
|
||||
raise ValueError("Invalid QML read shape")
|
||||
if command == 65 and (type(value["mask"]) is not int or not 0 <= value["mask"] <= 65535):
|
||||
raise ValueError("Invalid IMU mask")
|
||||
return dict(value)
|
||||
|
||||
|
||||
class QmlBroker:
|
||||
def __init__(self, clock):
|
||||
self.clock = clock
|
||||
self.pending = OrderedDict()
|
||||
self.last = {}
|
||||
self.batch_at = float("-inf")
|
||||
self.reads = 0
|
||||
self.observed_at = None
|
||||
|
||||
def enqueue(self, frame):
|
||||
requests = frame.get("read_requests", [])
|
||||
if not isinstance(requests, list) or len(requests) > 9:
|
||||
raise ValueError("QML read queue exceeded")
|
||||
# Validate the entire untrusted batch before any USB operation.
|
||||
intents = [read_intent(v) for v in requests]
|
||||
for intent in intents:
|
||||
self.pending[intent["command"]] = intent
|
||||
|
||||
def exchange(self, device, service, worker, frame):
|
||||
self.enqueue(frame)
|
||||
now = self.clock()
|
||||
packets = []
|
||||
if self.pending and now - self.batch_at >= 0.5:
|
||||
service.code_tools.idle(device)
|
||||
if not device.readable or not device.link:
|
||||
raise Rejected("Контроллер недоступен для чтения QML.")
|
||||
if (
|
||||
service.code_tools.pending(device)
|
||||
or service.code_tools.path(device, "execution").exists()
|
||||
):
|
||||
raise Rejected("Сначала проверьте предыдущее действие программы VESC.")
|
||||
self.batch_at = now
|
||||
for code, intent in list(self.pending.items()):
|
||||
cooldown = 10 if code in (0, 14, 17) else 1
|
||||
if now - self.last.get(code, float("-inf")) < cooldown:
|
||||
continue
|
||||
# Existing owner builds a typed upstream request; never raw bytes from QML.
|
||||
result = device.link.rpc("qml_read", timeout=1.2, intent=intent)
|
||||
packet = base64.b64decode(result["payload"], validate=True)
|
||||
if not 1 <= len(packet) <= 32768 or packet[0] != code:
|
||||
raise ValueError("QML read response does not match request")
|
||||
packets.append(base64.b64encode(packet).decode())
|
||||
del self.pending[code]
|
||||
self.last[code] = self.clock()
|
||||
self.reads += 1
|
||||
self.observed_at = service.qml_utc()
|
||||
if len(packets) == 2:
|
||||
break
|
||||
if packets:
|
||||
frame = worker.exchange({"op": "frame", "events": [], "packets": packets})
|
||||
self.enqueue(frame)
|
||||
return {
|
||||
**frame,
|
||||
"hardware_access": True,
|
||||
"direct_hardware_access": False,
|
||||
"broker_status": {
|
||||
"mode": "read_only",
|
||||
"reads": self.reads,
|
||||
"pending": len(self.pending),
|
||||
"observed_at": self.observed_at,
|
||||
"max_reads_per_frame": 2,
|
||||
"background_reads": False,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
"""Bounded Qt Quick sessions with an optional typed read-only hardware broker."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
|
||||
from .motor_test import Rejected
|
||||
from .qml_broker import QmlBroker
|
||||
from .qml_session import QmlSession
|
||||
|
||||
PREFIX = "vesc.qml."
|
||||
ACTIONS = frozenset(PREFIX + n for n in ("begin", "chunk", "render", "open", "frame", "close"))
|
||||
|
||||
|
||||
def validate(action, p):
|
||||
name = action.removeprefix(PREFIX)
|
||||
shapes = {
|
||||
"begin": {"size", "sha256"},
|
||||
"chunk": {"upload_id", "offset", "data"},
|
||||
"render": {"upload_id"},
|
||||
"open": {"upload_id", "snapshot"},
|
||||
"frame": {"qml_id", "events"},
|
||||
"close": {"qml_id"},
|
||||
}
|
||||
if name not in shapes or set(p) not in (
|
||||
[shapes[name], shapes[name] | {"broker"}] if name == "open" else [shapes[name]]
|
||||
):
|
||||
raise ValueError("Invalid QML preview parameters")
|
||||
|
||||
def identifier(value, prefix, size):
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and value.startswith(prefix)
|
||||
and len(value) == len(prefix) + size
|
||||
and all(c in "0123456789abcdef" for c in value[len(prefix) :])
|
||||
)
|
||||
|
||||
if name == "begin" and (
|
||||
type(p["size"]) is not int
|
||||
or not 1 <= p["size"] <= 120 * 1024
|
||||
or not identifier(p["sha256"], "", 64)
|
||||
):
|
||||
raise ValueError("Invalid QML preview size/hash")
|
||||
if "upload_id" in p and not identifier(p["upload_id"], "qml_", 32):
|
||||
raise ValueError("Invalid QML upload identity")
|
||||
if name == "open" and type(p["snapshot"]) is not bool:
|
||||
raise ValueError("Invalid snapshot selection")
|
||||
if "broker" in p and (type(p["broker"]) is not bool or (p["broker"] and not p["snapshot"])):
|
||||
raise ValueError("QML broker requires controller context")
|
||||
if "qml_id" in p and not identifier(p["qml_id"], "view_", 32):
|
||||
raise ValueError("Invalid QML session identity")
|
||||
if name == "frame":
|
||||
events = p["events"]
|
||||
if not isinstance(events, list) or len(events) > 32:
|
||||
raise ValueError("Too many QML input events")
|
||||
keys = {
|
||||
"Enter",
|
||||
"Tab",
|
||||
"Backspace",
|
||||
"Delete",
|
||||
"ArrowLeft",
|
||||
"ArrowRight",
|
||||
"ArrowUp",
|
||||
"ArrowDown",
|
||||
"Home",
|
||||
"End",
|
||||
"Escape",
|
||||
"SelectAll",
|
||||
}
|
||||
for event in events:
|
||||
if not isinstance(event, dict):
|
||||
raise ValueError("Invalid QML input")
|
||||
kind = event.get("kind")
|
||||
fields = {
|
||||
"down": {"x", "y"},
|
||||
"up": {"x", "y"},
|
||||
"move": {"x", "y"},
|
||||
"wheel": {"x", "y", "delta"},
|
||||
"text": {"text"},
|
||||
"key": {"key"},
|
||||
}
|
||||
if kind not in fields or set(event) != fields[kind] | {"kind"}:
|
||||
raise ValueError("Invalid QML input shape")
|
||||
for axis, limit in (("x", 640), ("y", 480)):
|
||||
if axis in event and (
|
||||
type(event[axis]) not in (int, float) or not 0 <= event[axis] < limit
|
||||
):
|
||||
raise ValueError("QML input outside frame")
|
||||
if kind == "wheel" and (type(event["delta"]) is not int or abs(event["delta"]) > 1200):
|
||||
raise ValueError("Invalid wheel delta")
|
||||
if kind == "text" and (
|
||||
not isinstance(event["text"], str)
|
||||
or len(event["text"]) > 1024
|
||||
or "\0" in event["text"]
|
||||
):
|
||||
raise ValueError("Invalid QML text")
|
||||
if kind == "key" and event["key"] not in keys:
|
||||
raise ValueError("Invalid QML key")
|
||||
if name == "chunk":
|
||||
if (
|
||||
type(p["offset"]) is not int
|
||||
or p["offset"] < 0
|
||||
or not isinstance(p["data"], str)
|
||||
or not 0 < len(p["data"]) <= 22000
|
||||
):
|
||||
raise ValueError("Invalid QML fragment")
|
||||
data = base64.b64decode(p["data"], validate=True)
|
||||
if not 0 < len(data) <= 16384 or base64.b64encode(data).decode() != p["data"]:
|
||||
raise ValueError("Invalid QML fragment encoding")
|
||||
|
||||
|
||||
def render_native(request):
|
||||
group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[
|
||||
1
|
||||
].lstrip("/")
|
||||
maximum = (group / "memory.max").read_text().strip()
|
||||
current = int((group / "memory.current").read_text())
|
||||
if maximum == "max" or int(maximum) < 1024**3 or current > 384 * 1024**2:
|
||||
raise Rejected("Недостаточно свободной памяти в службе для предпросмотра QML.")
|
||||
root = Path("/usr/lib/mission-core-vesc/native")
|
||||
env = {
|
||||
"PATH": "/usr/bin:/bin",
|
||||
"LANG": "C",
|
||||
"LC_ALL": "C",
|
||||
"HOME": "/nonexistent",
|
||||
"LD_LIBRARY_PATH": str(root / "lib"),
|
||||
"QT_PLUGIN_PATH": str(root / "plugins"),
|
||||
"QT_QPA_PLATFORM": "offscreen",
|
||||
"QT_QUICK_BACKEND": "software",
|
||||
"QML_DISABLE_DISK_CACHE": "1",
|
||||
"QV4_FORCE_INTERPRETER": "1",
|
||||
}
|
||||
try:
|
||||
# One child, synchronous bounded lifetime; communicate kills and reaps on timeout.
|
||||
with tempfile.TemporaryDirectory(prefix="qml-", dir="/run/mission-core-vesc") as runtime:
|
||||
env["XDG_RUNTIME_DIR"] = runtime
|
||||
p = subprocess.run(
|
||||
[str(root / "bin/mission-core-vesc-qml-preview")],
|
||||
input=json.dumps(request).encode(),
|
||||
capture_output=True,
|
||||
env=env,
|
||||
timeout=6,
|
||||
close_fds=True,
|
||||
)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise Rejected(
|
||||
"Предпросмотр QML остановлен: код не завершился за отведённое время."
|
||||
) from error
|
||||
if len(p.stdout) > 800 * 1024 or len(p.stderr) > 8192:
|
||||
raise Rejected("Предпросмотр QML превысил размер ответа.")
|
||||
try:
|
||||
result = json.loads(p.stdout)
|
||||
except (ValueError, UnicodeError) as error:
|
||||
raise Rejected("Qt Quick не смог построить предпросмотр.") from error
|
||||
if result.get("hardware_access") is not False or result.get("snapshot_only") is not True:
|
||||
raise ValueError("QML preview contract mismatch")
|
||||
if not result.get("ok") or p.returncode:
|
||||
return {
|
||||
"rendered": False,
|
||||
"warnings": result.get("warnings", [])[:16],
|
||||
"error": result.get("error", "Qt Quick не построил кадр."),
|
||||
}
|
||||
raw = base64.b64decode(result["png"], validate=True)
|
||||
if (
|
||||
len(raw) > 512 * 1024
|
||||
or not raw.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
or (result["width"], result["height"]) != (640, 480)
|
||||
):
|
||||
raise ValueError("Invalid QML frame")
|
||||
return {**result, "rendered": True}
|
||||
|
||||
|
||||
class QmlPreview:
|
||||
def __init__(self, service, renderer=render_native, clock=time.monotonic):
|
||||
self.service, self.renderer, self.clock = service, renderer, clock
|
||||
self.uploads = OrderedDict()
|
||||
self.session = None
|
||||
self.session_factory = QmlSession
|
||||
|
||||
def close_session(self):
|
||||
if self.session:
|
||||
self.session["worker"].close()
|
||||
self.session = None
|
||||
|
||||
def maintain(self, devices):
|
||||
if self.session and (
|
||||
self.session["worker"].expired()
|
||||
or not any(
|
||||
d.id == self.session["device"]
|
||||
and d.session == self.session["session"]
|
||||
and d.link is not None
|
||||
for d in devices
|
||||
)
|
||||
):
|
||||
self.close_session()
|
||||
|
||||
def execute(self, device, action, p):
|
||||
now = self.clock()
|
||||
for key, value in list(self.uploads.items()):
|
||||
if now - value["at"] >= 300:
|
||||
del self.uploads[key]
|
||||
name = action.removeprefix(PREFIX)
|
||||
identity = {"device": device.id, "session": device.session}
|
||||
if name in ("frame", "close"):
|
||||
session = self.session
|
||||
if (
|
||||
not session
|
||||
or session["id"] != p["qml_id"]
|
||||
or any(session[k] != v for k, v in identity.items())
|
||||
):
|
||||
raise Rejected("Сеанс QML истёк или контроллер переподключён.")
|
||||
if name == "close":
|
||||
self.close_session()
|
||||
return {"closed": True}
|
||||
if session["worker"].expired():
|
||||
self.close_session()
|
||||
raise Rejected("Сеанс QML завершён. Откройте интерфейс заново.")
|
||||
try:
|
||||
frame = session["worker"].exchange({"op": "frame", "events": p["events"]})
|
||||
if session.get("broker"):
|
||||
frame = session["broker"].exchange(
|
||||
device, self.service, session["worker"], frame
|
||||
)
|
||||
return {**frame, "qml_id": session["id"], "observed_at": session["observed_at"]}
|
||||
except BaseException:
|
||||
self.close_session()
|
||||
raise
|
||||
if name == "begin":
|
||||
while len(self.uploads) >= 2:
|
||||
self.uploads.popitem(last=False)
|
||||
key = "qml_" + uuid.uuid4().hex
|
||||
self.uploads[key] = {**identity, **p, "at": now, "data": bytearray()}
|
||||
return {"upload_id": key, "chunk_bytes": 16384}
|
||||
upload = self.uploads.get(p["upload_id"])
|
||||
if not upload or any(upload[k] != v for k, v in identity.items()):
|
||||
raise Rejected("Передача QML истекла или сеанс контроллера изменился.")
|
||||
if name == "chunk":
|
||||
raw = base64.b64decode(p["data"], validate=True)
|
||||
offset = p["offset"]
|
||||
if offset < len(upload["data"]) and upload["data"][offset : offset + len(raw)] == raw:
|
||||
return {"offset": len(upload["data"])}
|
||||
if offset != len(upload["data"]) or offset + len(raw) > upload["size"]:
|
||||
raise ValueError("QML fragment offset/size mismatch")
|
||||
upload["data"].extend(raw)
|
||||
return {"offset": len(upload["data"])}
|
||||
raw = bytes(upload["data"])
|
||||
if len(raw) != upload["size"] or hashlib.sha256(raw).hexdigest() != upload["sha256"]:
|
||||
raise ValueError("QML source checksum mismatch")
|
||||
source = raw.decode("utf-8")
|
||||
if not source.strip() or "\0" in source:
|
||||
raise ValueError("Empty or invalid QML source")
|
||||
if name == "open":
|
||||
self.close_session()
|
||||
broker = p.get("broker", False)
|
||||
if broker and "qml_read" not in (getattr(device.link, "engine", None) or {}).get(
|
||||
"contract", {}
|
||||
).get("methods", []):
|
||||
raise Rejected("Обновите бортовое ядро для аппаратного QML-брокера.")
|
||||
snapshot = name == "render" or p.get("snapshot", False)
|
||||
if snapshot:
|
||||
self.service.code_tools.idle(device)
|
||||
if snapshot and not device.readable:
|
||||
raise Rejected("Для предпросмотра нужна поддерживаемая схема контроллера.")
|
||||
configs = {}
|
||||
for kind, command in (("motor", 14), ("application", 17)) if snapshot else ():
|
||||
packet = device.link.query(command)
|
||||
configs[kind] = {
|
||||
"encoding": "base64",
|
||||
"payload": base64.b64encode(packet).decode(),
|
||||
"bytes": len(packet),
|
||||
"sha256": hashlib.sha256(packet).hexdigest(),
|
||||
}
|
||||
value = device.link.query(4) if snapshot else b""
|
||||
observed_at = self.service.qml_utc()
|
||||
del self.uploads[p["upload_id"]]
|
||||
request = {
|
||||
"identity": dict(device.identity),
|
||||
"configs": configs,
|
||||
"values": base64.b64encode(value).decode(),
|
||||
"source": source,
|
||||
"width": 640,
|
||||
"height": 480,
|
||||
"standalone": not snapshot,
|
||||
"broker": broker,
|
||||
}
|
||||
if name == "open":
|
||||
worker = self.session_factory(request)
|
||||
key = "view_" + uuid.uuid4().hex
|
||||
self.session = {
|
||||
**identity,
|
||||
"id": key,
|
||||
"worker": worker,
|
||||
"observed_at": observed_at,
|
||||
"broker": QmlBroker(self.clock) if broker else None,
|
||||
}
|
||||
try:
|
||||
frame = worker.initial
|
||||
if broker:
|
||||
frame = self.session["broker"].exchange(device, self.service, worker, frame)
|
||||
return {**frame, "qml_id": key, "observed_at": observed_at}
|
||||
except BaseException:
|
||||
self.close_session()
|
||||
raise
|
||||
result = self.renderer(request)
|
||||
return {
|
||||
**result,
|
||||
"observed_at": observed_at,
|
||||
"source_sha256": upload["sha256"],
|
||||
"snapshot_only": True,
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""One bounded Qt Quick child with no device FD; broker intents are parent-validated."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .motor_test import Rejected
|
||||
|
||||
|
||||
def environment():
|
||||
group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[
|
||||
1
|
||||
].lstrip("/")
|
||||
maximum = (group / "memory.max").read_text().strip()
|
||||
if (
|
||||
maximum == "max"
|
||||
or int(maximum) < 1024**3
|
||||
or int((group / "memory.current").read_text()) > 384 * 1024**2
|
||||
):
|
||||
raise Rejected("Недостаточно свободной памяти в службе для QML.")
|
||||
root = Path("/usr/lib/mission-core-vesc/native")
|
||||
return root, {
|
||||
"PATH": "/usr/bin:/bin",
|
||||
"LANG": "C",
|
||||
"LC_ALL": "C",
|
||||
"HOME": "/nonexistent",
|
||||
"LD_LIBRARY_PATH": str(root / "lib"),
|
||||
"QT_PLUGIN_PATH": str(root / "plugins"),
|
||||
"QT_QPA_PLATFORM": "offscreen",
|
||||
"QT_QUICK_BACKEND": "software",
|
||||
"QML_DISABLE_DISK_CACHE": "1",
|
||||
"QV4_FORCE_INTERPRETER": "1",
|
||||
}
|
||||
|
||||
|
||||
def checked_frame(result):
|
||||
if (
|
||||
not isinstance(result, dict)
|
||||
or result.get("hardware_access") is not False
|
||||
or type(result.get("snapshot_only")) is not bool
|
||||
or result["snapshot_only"] == (result.get("broker") is True)
|
||||
or result.get("sandbox_verified") is not True
|
||||
):
|
||||
raise Rejected("Не подтверждена изоляция QML.")
|
||||
if not result.get("ok"):
|
||||
raise Rejected(str(result.get("error", "Qt Quick не построил кадр."))[:320])
|
||||
raw = base64.b64decode(result["png"], validate=True)
|
||||
if (
|
||||
len(raw) > 512 * 1024
|
||||
or not raw.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
or (result["width"], result["height"]) != (640, 480)
|
||||
):
|
||||
raise Rejected("Некорректный кадр QML.")
|
||||
return {**result, "rendered": True}
|
||||
|
||||
|
||||
class QmlSession:
|
||||
def __init__(self, request):
|
||||
self.process = None
|
||||
self.directory = None
|
||||
self.buffer = b""
|
||||
self.at = self.used = time.monotonic()
|
||||
self.count = 0
|
||||
self.broker = request.get("broker", False)
|
||||
root, env = environment()
|
||||
try:
|
||||
self.directory = tempfile.TemporaryDirectory(
|
||||
prefix="qml-", dir="/run/mission-core-vesc"
|
||||
)
|
||||
env["XDG_RUNTIME_DIR"] = self.directory.name
|
||||
self.process = subprocess.Popen(
|
||||
[str(root / "bin/mission-core-vesc-qml-preview")],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
env=env,
|
||||
close_fds=True,
|
||||
bufsize=0,
|
||||
)
|
||||
os.set_blocking(self.process.stdin.fileno(), False)
|
||||
os.set_blocking(self.process.stdout.fileno(), False)
|
||||
self.initial = self.exchange({**request, "interactive": True})
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def alive(self):
|
||||
return self.process is not None and self.process.poll() is None
|
||||
|
||||
def expired(self):
|
||||
return (
|
||||
not self.alive()
|
||||
or time.monotonic() - self.at >= 300
|
||||
or time.monotonic() - self.used >= 60
|
||||
or self.count >= 240
|
||||
)
|
||||
|
||||
def exchange(self, request):
|
||||
deadline = time.monotonic() + 6
|
||||
try:
|
||||
raw = json.dumps(request, allow_nan=False).encode() + b"\n"
|
||||
if len(raw) > 512 * 1024:
|
||||
raise ValueError("QML request exceeds bound")
|
||||
while raw:
|
||||
if (
|
||||
not self.alive()
|
||||
or not select.select(
|
||||
[], [self.process.stdin], [], max(0, deadline - time.monotonic())
|
||||
)[1]
|
||||
):
|
||||
raise TimeoutError("QML input timed out")
|
||||
size = os.write(self.process.stdin.fileno(), raw[:4096])
|
||||
if size <= 0:
|
||||
raise OSError("QML input closed")
|
||||
raw = raw[size:]
|
||||
while b"\n" not in self.buffer:
|
||||
if (
|
||||
not self.alive()
|
||||
or not select.select(
|
||||
[self.process.stdout], [], [], max(0, deadline - time.monotonic())
|
||||
)[0]
|
||||
):
|
||||
raise TimeoutError("QML frame timed out")
|
||||
chunk = os.read(self.process.stdout.fileno(), 65536)
|
||||
if not chunk:
|
||||
raise OSError("QML process exited")
|
||||
self.buffer += chunk
|
||||
if len(self.buffer) > 800 * 1024:
|
||||
raise ValueError("QML response exceeds bound")
|
||||
line, self.buffer = self.buffer.split(b"\n", 1)
|
||||
result = checked_frame(json.loads(line))
|
||||
if (
|
||||
result.get("interactive") is not True
|
||||
or (result.get("broker") is True) != self.broker
|
||||
):
|
||||
raise ValueError("Interactive QML protocol missing")
|
||||
self.used = time.monotonic()
|
||||
self.count += 1
|
||||
return result
|
||||
except (ValueError, KeyError, OSError, TimeoutError, Rejected) as error:
|
||||
self.close()
|
||||
raise Rejected("Сеанс QML завершён: " + str(error)[:240]) from error
|
||||
|
||||
def close(self):
|
||||
if self.process:
|
||||
if self.alive():
|
||||
self.process.kill()
|
||||
try:
|
||||
self.process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise Rejected("Прежний процесс QML ещё завершается.") from error
|
||||
for stream in (self.process.stdin, self.process.stdout):
|
||||
if stream:
|
||||
stream.close()
|
||||
if self.directory:
|
||||
self.directory.cleanup()
|
||||
self.directory = None
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Bounded snapshots, separate from durable configuration backups and write receipts."""
|
||||
from collections import OrderedDict
|
||||
import json
|
||||
import time
|
||||
|
||||
SNAPSHOT_ACTIONS = frozenset({"vesc.tools.read", "vesc.terminal.read", "vesc.firmware.status", "vesc.configuration.read", "vesc.configuration.preview", "vesc.diagnostics.read"})
|
||||
EXPIRED = {"state": "error", "error": "Снимок больше не хранится. Прочитайте данные заново."}
|
||||
|
||||
|
||||
class ReadCache:
|
||||
def __init__(self, *, count=8, bytes_limit=8 * 1024**2, ttl=600, clock=time.monotonic):
|
||||
self.items = OrderedDict()
|
||||
self.count, self.bytes_limit, self.ttl, self.clock = count, bytes_limit, ttl, clock
|
||||
self.bytes = 0
|
||||
|
||||
def prune(self):
|
||||
for key, (at, size, _) in list(self.items.items()):
|
||||
if self.clock() - at >= self.ttl:
|
||||
del self.items[key]
|
||||
self.bytes -= size
|
||||
|
||||
def put(self, key, receipt):
|
||||
raw = json.dumps(receipt, ensure_ascii=False, allow_nan=False).encode()
|
||||
if len(raw) > self.bytes_limit:
|
||||
raise ValueError("Read snapshot exceeds cache bound")
|
||||
self.prune()
|
||||
if key in self.items:
|
||||
self.bytes -= self.items.pop(key)[1]
|
||||
while self.items and (len(self.items) >= self.count or self.bytes + len(raw) > self.bytes_limit):
|
||||
self.bytes -= self.items.popitem(last=False)[1][1]
|
||||
self.items[key] = (self.clock(), len(raw), raw)
|
||||
self.bytes += len(raw)
|
||||
|
||||
def get(self, key):
|
||||
self.prune()
|
||||
entry = self.items.get(key)
|
||||
return json.loads(entry[2]) if entry else dict(EXPIRED)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Read-only evidence of settled release, tied to the stopped attachments.
|
||||
|
||||
GET_VALUES current averages span reads. A failed immediate cleanup read is not
|
||||
a permanent description of the controller. Require a new whole-profile neutral
|
||||
window; never extend a command lease or transfer motor authority here.
|
||||
"""
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
# The same electrical standstill envelope is used by release observation and
|
||||
# configuration writes. GET_VALUES may report sub-amp idle sensor offset.
|
||||
IDLE_BOUNDS = (
|
||||
("motor_current_a", 1),
|
||||
("input_current_a", 1),
|
||||
("duty", 0.001),
|
||||
("erpm", 1),
|
||||
("fault_code", 0),
|
||||
)
|
||||
|
||||
NOTICE = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов."
|
||||
|
||||
|
||||
def settlement_pending(evidence):
|
||||
"""A successful release with finite readback may still be settling.
|
||||
|
||||
This classifies a normal input-ended cleanup only. It does not confirm
|
||||
release, grant authority, or excuse transport/configuration/device faults.
|
||||
"""
|
||||
devices = (evidence or {}).get("devices", {})
|
||||
return bool(devices) and all(
|
||||
item.get("send", {}).get("sent") is True
|
||||
and item.get("reason") in ("neutral_readback", "non_neutral_readback")
|
||||
and all(type(item.get("values", {}).get(k)) in (int, float)
|
||||
and math.isfinite(item["values"][k])
|
||||
for k in ("motor_current_a", "input_current_a", "duty", "erpm", "fault_code"))
|
||||
and item["values"]["fault_code"] == 0
|
||||
for item in devices.values()
|
||||
)
|
||||
|
||||
|
||||
class ReleaseObservation:
|
||||
def __init__(self, devices, started_at):
|
||||
self.attachments = {d.id: getattr(d, "session", None) for d in devices}
|
||||
self.identities = {d.id: (getattr(d, "identity", None) or {}).get("uuid") for d in devices}
|
||||
self.started_at = started_at
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.since = None
|
||||
self.previous = {}
|
||||
self.count = 0
|
||||
|
||||
def faulted(self, devices, now):
|
||||
"""Retain a real firmware fault seen while waiting for settlement."""
|
||||
for d in devices:
|
||||
try:
|
||||
s = d.sample
|
||||
code = s["values"]["fault_code"]
|
||||
if (d.session == self.attachments.get(d.id) == s["session_id"]
|
||||
and d.link and getattr(d.link, "alive", True)
|
||||
and self.started_at <= s["sampled_at"] <= now
|
||||
and now - s["sampled_at"] <= .5
|
||||
and math.isfinite(code) and code != 0):
|
||||
return True
|
||||
except (KeyError, TypeError, ValueError, AttributeError):
|
||||
continue
|
||||
return False
|
||||
|
||||
def check(self, devices, now, receiver_active):
|
||||
stamps = {}
|
||||
try:
|
||||
if (
|
||||
not self.attachments
|
||||
or len(devices) != len(self.attachments)
|
||||
or {d.id for d in devices} != set(self.attachments)
|
||||
):
|
||||
raise ValueError("Incomplete release observation")
|
||||
# A new attachment can prove CURRENT neutral state only after its
|
||||
# physical UUID was identified again. It never confirms old output.
|
||||
for d in devices:
|
||||
expected = self.identities[d.id]
|
||||
if expected and (getattr(d, "identity", None) or {}).get("uuid") != expected:
|
||||
raise ValueError("Controller identity changed")
|
||||
if any(d.session != self.attachments[d.id] for d in devices):
|
||||
if not all(re.fullmatch(r"[0-9a-f]{24}", self.identities[d.id] or "")
|
||||
and getattr(d, "identified_session", None) == d.session
|
||||
and d.link and getattr(d.link, "alive", True) for d in devices):
|
||||
raise ValueError("New attachment identity is not verified")
|
||||
self.attachments = {d.id: d.session for d in devices}
|
||||
self.started_at = now
|
||||
self.reset()
|
||||
return False
|
||||
for d in devices:
|
||||
sample = d.sample
|
||||
if (
|
||||
not self.attachments[d.id]
|
||||
or d.session != self.attachments[d.id]
|
||||
or not d.link
|
||||
or not getattr(d.link, "alive", True)
|
||||
or not sample
|
||||
or sample["session_id"] != d.session
|
||||
):
|
||||
raise ValueError("Attachment changed")
|
||||
at = sample["sampled_at"]
|
||||
if (
|
||||
not math.isfinite(at)
|
||||
or at < self.started_at
|
||||
or not 0 <= now - at <= 0.5
|
||||
or at <= self.previous.get(d.id, -math.inf)
|
||||
):
|
||||
raise ValueError("No new release sample")
|
||||
value = sample["values"]
|
||||
if any(
|
||||
not math.isfinite(value[k]) or abs(value[k]) > bound
|
||||
for k, bound in IDLE_BOUNDS
|
||||
):
|
||||
raise ValueError("Controller is not idle")
|
||||
if receiver_active(d.id, sample["receiver"]["level"]):
|
||||
raise ValueError("Receiver requests output")
|
||||
stamps[d.id] = at
|
||||
# Gaps restart the proof; old samples cannot bridge missing data.
|
||||
if self.previous and any(stamps[k] - self.previous[k] > 0.5 for k in stamps):
|
||||
self.reset()
|
||||
except (KeyError, TypeError, ValueError, AttributeError):
|
||||
self.reset()
|
||||
return False
|
||||
if self.since is None:
|
||||
self.since = max(stamps.values())
|
||||
self.previous = stamps
|
||||
self.count += 1
|
||||
return self.count >= 3 and min(stamps.values()) - self.since >= 0.5
|
||||
@@ -15,6 +15,13 @@ from datetime import datetime, timedelta, timezone
|
||||
from .group_test import batch
|
||||
from .protocol import ppm, values
|
||||
from .drive_profile import LAYOUTS, slot_label
|
||||
from .remote_duty import DutyOutput
|
||||
from .configuration import decode
|
||||
from .diagnostics import failure
|
||||
from .drive_diagnostics import DriveDiagnostics
|
||||
from . import remote_limits
|
||||
from .release_observation import NOTICE as RELEASE_NOTICE, ReleaseObservation, settlement_pending
|
||||
from .preflight_recovery import PreflightRecovery
|
||||
|
||||
|
||||
class ControlEnded(ValueError):
|
||||
@@ -28,6 +35,7 @@ class InputLease:
|
||||
self.sequence = -1
|
||||
self.until = 0
|
||||
self.demand = (0., 0.)
|
||||
self.settings = None
|
||||
self.retired = set()
|
||||
|
||||
def accept(self, command):
|
||||
@@ -40,10 +48,12 @@ class InputLease:
|
||||
or not 0 < command["ttl_ms"] <= 400):
|
||||
raise ValueError("Invalid control bounds")
|
||||
s = command["settings"]
|
||||
if (not isinstance(s, dict) or set(s) != {"standstill_confirmed","current_a","max_erpm"}
|
||||
duty = isinstance(s, dict) and "max_duty_percent" in s
|
||||
speed_key, low, high = ("max_duty_percent", 1, 100) if duty else ("max_erpm", 300, 3000)
|
||||
if (not isinstance(s, dict) or set(s) != {"standstill_confirmed","current_a",speed_key}
|
||||
or s["standstill_confirmed"] is not True
|
||||
or type(s["current_a"]) not in (int,float) or not .5 <= s["current_a"] <= 30
|
||||
or type(s["max_erpm"]) not in (int,float) or not 300 <= s["max_erpm"] <= 3000):
|
||||
or type(s["current_a"]) not in (int,float) or not math.isfinite(s["current_a"]) or s["current_a"] < .5
|
||||
or type(s[speed_key]) not in (int,float) or not low <= s[speed_key] <= high):
|
||||
raise ValueError("Invalid control settings")
|
||||
if command["id"] in self.retired:
|
||||
return False
|
||||
@@ -52,7 +62,11 @@ class InputLease:
|
||||
return False
|
||||
if self.id == command["id"] and command["sequence"] <= self.sequence:
|
||||
return False # Repeated frames cannot extend a lease.
|
||||
if self.id == command["id"] and s != self.settings:
|
||||
self.stop()
|
||||
raise ValueError("Control settings changed during the session")
|
||||
self.id, self.sequence = command["id"], command["sequence"]
|
||||
self.settings = copy.deepcopy(s)
|
||||
self.until = self.clock()+command["ttl_ms"]/1000
|
||||
self.demand = (command["left"], command["right"])
|
||||
return True
|
||||
@@ -73,6 +87,7 @@ class InputLease:
|
||||
class RemoteControl:
|
||||
def __init__(self, service):
|
||||
self.service = service
|
||||
self.trace = DriveDiagnostics(getattr(service,"root","/tmp/mission-core-vesc-test"))
|
||||
self.lock = threading.RLock()
|
||||
self.lease = InputLease()
|
||||
self.instance = uuid.uuid4().hex
|
||||
@@ -82,8 +97,11 @@ class RemoteControl:
|
||||
self.watch_until = 0
|
||||
self.state = "observing"
|
||||
self.message = None
|
||||
self.readings = {}
|
||||
self.release_confirmed = None
|
||||
self.release_evidence = None
|
||||
self.pending_release = None
|
||||
self.pending_availability = None
|
||||
self.last_stop = None
|
||||
|
||||
def feed(self, body):
|
||||
if (set(body) != {"watch","command","relay_id"} or type(body["watch"]) is not bool
|
||||
@@ -91,6 +109,7 @@ class RemoteControl:
|
||||
raise ValueError("Invalid relay")
|
||||
with self.lock:
|
||||
if self.relay != body["relay_id"]:
|
||||
self.trace.add("relay_changed", session_id=self.lease.id)
|
||||
self.lease.stop()
|
||||
self.relay = body["relay_id"]
|
||||
self.primed = False
|
||||
@@ -98,6 +117,7 @@ class RemoteControl:
|
||||
self.watch_until = time.monotonic()+2
|
||||
command = body["command"]
|
||||
if command is None:
|
||||
if self.lease.live():self.trace.add("intent_retired",session_id=self.lease.id,sequence=self.lease.sequence)
|
||||
self.primed = True
|
||||
self.lease.stop()
|
||||
elif not self.primed:
|
||||
@@ -108,20 +128,68 @@ class RemoteControl:
|
||||
self.lease.id = None
|
||||
self.lease.sequence = -1
|
||||
accepted = self.lease.accept(command)
|
||||
self.trace.add("input",session_id=command["id"],sequence=command["sequence"],
|
||||
ttl_ms=command["ttl_ms"],left=command["left"],right=command["right"],accepted=accepted,
|
||||
state=self.state,lease_remaining_ms=max(0,(self.lease.until-time.monotonic())*1000))
|
||||
if accepted and not running:
|
||||
self.state, self.message = "preparing", None
|
||||
# This new lease has not applied output or checked release
|
||||
# yet. Never inherit the previous session's failed release,
|
||||
# nor claim success: normal neutral/pending-limit preflight
|
||||
# must still complete before drive() can take ownership.
|
||||
self.release_confirmed = None
|
||||
self.release_evidence = None
|
||||
self.pending_release = None
|
||||
self.pending_availability = None
|
||||
self.thread = threading.Thread(target=self._prepare, args=(copy.deepcopy(command),), daemon=True,
|
||||
name="vesc-remote-control")
|
||||
self.thread.start()
|
||||
return self.snapshot()
|
||||
|
||||
def observe_snapshot(self):
|
||||
"""Renew read interest only. Never change relay, input lease or outputs."""
|
||||
with self.lock:
|
||||
self.watch_until = time.monotonic() + 2
|
||||
return self.snapshot()
|
||||
|
||||
def snapshot(self):
|
||||
with self.lock:
|
||||
readings = [{**copy.deepcopy(v), "age_ms": int((time.monotonic()-v["sampled_at"])*1000)} for v in self.readings.values()]
|
||||
for v in readings: v.pop("sampled_at", None)
|
||||
return {"supported": True, "instance": self.instance, "state": self.state,
|
||||
# Samples belong to a live attachment generation, never a UUID cache.
|
||||
# Discovery removes old generations before closing them; no serial lock
|
||||
# or I/O is taken while projecting a snapshot.
|
||||
with self.service.lock:
|
||||
devices = [{**d.__dict__, "readable": getattr(d, "readable", False)}
|
||||
for d in self.service.devices.values()]
|
||||
ids = [d["id"] for d in devices]
|
||||
profile = self.service.drive.value
|
||||
readings = []
|
||||
initializing = []
|
||||
for d in devices:
|
||||
sample = d.get("sample")
|
||||
# Identity and the initial sample are distinct milestones of
|
||||
# this live attachment. Cached inventory/old generations cannot
|
||||
# claim initialization, nor can a failed/disconnected reader.
|
||||
if (d.get("session") and ids.count(d["id"]) == 1
|
||||
and d.get("identified_session") == d["session"]
|
||||
and d["link"] and getattr(d["link"], "alive", True)
|
||||
and d["readable"] and not d.get("error")
|
||||
and (not sample or sample["session_id"] != d["session"])):
|
||||
initializing.append(d["id"])
|
||||
if (not sample or sample["session_id"] != d["session"] or ids.count(d["id"]) != 1
|
||||
or not d["link"] or not getattr(d["link"], "alive", True)):
|
||||
continue
|
||||
slot = next((k for k, v in profile["bindings"].items() if v["device_id"] == d["id"]), None)
|
||||
readings.append({"id": d["id"], "uuid": d["identity"]["uuid"], "slot": slot,
|
||||
"label": slot_label(profile["layout"], slot) if slot else "VESC " + d["identity"]["uuid"][:6].upper(),
|
||||
"session_id": sample["session_id"], "sample_time_ms": sample["sampled_at"] * 1000,
|
||||
"observed_at": sample.get("observed_at"), "values": copy.deepcopy(sample["values"]),
|
||||
"receiver": copy.deepcopy(sample["receiver"]), "current_limits": remote_limits.projection(d),
|
||||
"age_ms": max(0, int((time.monotonic() - sample["sampled_at"]) * 1000))})
|
||||
return {"supported": True, "control_modes": ["rpm", "duty"], "instance": self.instance, "state": self.state,
|
||||
"control_active": self.lease.live() or bool(self.thread and self.thread.is_alive()),
|
||||
"session_id": self.lease.id, "message": self.message, "devices": readings,
|
||||
"release_confirmed": self.release_confirmed,
|
||||
"observation": {"initializing_devices": initializing},
|
||||
"release_confirmed": self.release_confirmed, "last_stop": copy.deepcopy(self.last_stop),
|
||||
"profile": copy.deepcopy(self.service.drive.value)}
|
||||
|
||||
def observe(self):
|
||||
@@ -130,31 +198,121 @@ class RemoteControl:
|
||||
# the control worker is waiting to become the exclusive owner.
|
||||
if self.thread is not None and self.thread.is_alive():
|
||||
return
|
||||
if time.monotonic() >= self.watch_until or not self.service.operation_lock.acquire(False):
|
||||
firmware_owner = None
|
||||
with self.service.firmware_update.lock:
|
||||
if self.service.firmware_update.active:
|
||||
firmware_owner = self.service.firmware_update.active['device_id']
|
||||
operation_owned = self.service.operation_lock.acquire(False)
|
||||
if not operation_owned and firmware_owner is None:
|
||||
return
|
||||
try:
|
||||
with self.service.lock: devices = [d for d in self.service.devices.values() if d.link and d.readable]
|
||||
# Reading is explicit window interest, never discovery-port reset.
|
||||
with self.service.lock: devices = [d for d in self.service.devices.values() if not self.service.firmware_update.owns(d) and d.link and d.readable]
|
||||
ids = [d.id for d in devices]
|
||||
# One initial read per connection even without an open viewer. Further
|
||||
# reads require live window interest; discovery never resets USB ports.
|
||||
for d in devices:
|
||||
if ids.count(d.id) != 1 or (d.sample is not None and time.monotonic() >= self.watch_until
|
||||
and not self.trace.active() and self.pending_release is None
|
||||
and self.pending_availability is None): continue
|
||||
if not d.lock.acquire(False): continue
|
||||
try:
|
||||
self._publish(d, values(d.link.query(4, timeout=.06)), ppm(d.link.query(31, timeout=.06)))
|
||||
except (OSError, ValueError, TimeoutError):
|
||||
pass # Old values retain age; a read failure is never zero.
|
||||
# Passive observation has no output lease. A CAN send may take
|
||||
# up to 200 ms across the bounded SDK owner; the USB motor
|
||||
# loop's 60 ms budget is not a valid observer deadline here.
|
||||
from .can_bridge import Attachment as CanAttachment
|
||||
timeout = .3 if isinstance(d.attachment, CanAttachment) else .06
|
||||
self._publish(d, values(d.link.query(4, timeout=timeout)), ppm(d.link.query(31, timeout=timeout)))
|
||||
known = getattr(d, "drive_limits", None)
|
||||
if (d.identity.get("version") == "5.02" and (not known or known["session_id"] != d.session
|
||||
or time.monotonic() - known["sampled_at"] > 30)):
|
||||
remote_limits.publish(d, decode(d.link.query(14), "motor"))
|
||||
except Exception as error:
|
||||
d.failed(error, "observation")
|
||||
finally: d.lock.release()
|
||||
finally: self.service.operation_lock.release()
|
||||
if operation_owned:
|
||||
self._reconcile_release(devices)
|
||||
self._reconcile_preflight(devices)
|
||||
finally:
|
||||
if operation_owned: self.service.operation_lock.release()
|
||||
|
||||
def _await_release(self, devices):
|
||||
with self.lock:
|
||||
self.pending_release = ReleaseObservation(devices, time.monotonic())
|
||||
|
||||
def _reconcile_preflight(self, devices):
|
||||
# Only the missing-device preflight path creates this observer. No
|
||||
# motor output/configuration was attempted, so it cannot invent a
|
||||
# historical release ACK or clear an unrelated execution fault.
|
||||
with self.lock:
|
||||
pending = self.pending_availability
|
||||
if pending is None:
|
||||
return
|
||||
with self.service.firmware_update.lock:
|
||||
firmware_active = self.service.firmware_update.active is not None
|
||||
if (self.lease.live() or (self.thread and self.thread.is_alive())
|
||||
or self.service.motor.active or firmware_active):
|
||||
pending.reset()
|
||||
return
|
||||
if not pending.check(self.service.drive.value, devices, time.monotonic(),
|
||||
self.service.motor.receiver_active, self.service.motor.limits.pending):
|
||||
return
|
||||
self.pending_availability = None
|
||||
self.state, self.message = "stopped", None
|
||||
if self.last_stop is not None:
|
||||
self.last_stop["recovered_at"] = datetime.now(timezone.utc).isoformat()
|
||||
self.trace.add("preflight_availability_recovered", session_id=self.lease.id)
|
||||
|
||||
def _reconcile_release(self, devices):
|
||||
# Called under the existing observer's operation lock, after passive
|
||||
# reads. A newly starting control worker may still hold a live lease;
|
||||
# it must win over this status-only reconciliation.
|
||||
with self.lock:
|
||||
pending = self.pending_release
|
||||
if pending is None:
|
||||
return
|
||||
with self.service.firmware_update.lock:
|
||||
firmware_active = self.service.firmware_update.active is not None
|
||||
if (self.lease.live() or (self.thread and self.thread.is_alive())
|
||||
or self.service.motor.active or firmware_active):
|
||||
pending.reset()
|
||||
return
|
||||
if self.state == "stopping" and pending.faulted(devices, time.monotonic()):
|
||||
self.state = "fault"
|
||||
self.message = "VESC сообщил об ошибке. Проверьте состояние перед включением."
|
||||
if self.last_stop is not None:
|
||||
self.last_stop.update(state="fault", message=self.message)
|
||||
self.trace.add("release_settlement_fault", session_id=self.lease.id)
|
||||
if not pending.check(devices, time.monotonic(), self.service.motor.receiver_active):
|
||||
return
|
||||
newly_observed = self.release_confirmed is not True
|
||||
self.release_confirmed = True
|
||||
self.message = (self.message or "").replace(RELEASE_NOTICE, "", 1).strip() or None
|
||||
if newly_observed:
|
||||
self.trace.add("release_observed", session_id=self.lease.id,
|
||||
attachments=pending.attachments, samples=pending.count,
|
||||
window_ms=(min(pending.previous.values()) - pending.since) * 1000)
|
||||
# Configuration ACK/read-back belongs to the existing restoration
|
||||
# owner. Observation cannot assert success or write configuration.
|
||||
if any(self.service.motor.limits.pending(d) for d in devices):
|
||||
return
|
||||
if self.last_stop is not None:
|
||||
self.last_stop["recovered_at"] = datetime.now(timezone.utc).isoformat()
|
||||
self.pending_release = None
|
||||
if self.last_stop is not None:
|
||||
self.message = None
|
||||
if self.state in ("fault", "stopping") and self.message is None:
|
||||
self.state = "stopped"
|
||||
# Keep the motor latch and retired lease. Only explicit new arm may
|
||||
# take authority after a hardware fault; observation never rearms.
|
||||
|
||||
def _publish(self, device, value, receiver):
|
||||
profile = self.service.drive.value
|
||||
slot = next((k for k,b in profile["bindings"].items() if b["device_id"]==device.id), None)
|
||||
with self.lock:
|
||||
self.readings[device.id] = {"id": device.id,"uuid":device.identity["uuid"],
|
||||
"slot":slot,"label":slot_label(profile["layout"],slot) if slot else "VESC "+device.identity["uuid"][:6].upper(),
|
||||
"values":value,"receiver":receiver,"sampled_at":time.monotonic()}
|
||||
device.publish_sample(value, receiver)
|
||||
self.trace.sample(device,value,receiver,getattr(self.service.motor,"mode",None) or "receiver_or_idle")
|
||||
|
||||
def _prepare(self, envelope):
|
||||
owner = self.service.motor
|
||||
acquired = False
|
||||
devices = []
|
||||
try:
|
||||
# Observation also owns this lock. A nonblocking attempt made
|
||||
# arming depend on which thread happened to read first. Wait only
|
||||
@@ -172,43 +330,73 @@ class RemoteControl:
|
||||
slots = LAYOUTS.get(profile["layout"], ())
|
||||
if not slots or set(profile["bindings"]) != set(slots):
|
||||
raise ValueError("Назначьте все моторы в настройках борта.")
|
||||
if not devices or any(not d.link for d in devices):
|
||||
required = {binding["device_id"] for binding in profile["bindings"].values()}
|
||||
if (not devices or any(not d.link for d in devices)
|
||||
or not required.issubset({d.id for d in devices})):
|
||||
with self.lock:
|
||||
self.pending_availability = PreflightRecovery(profile)
|
||||
raise ValueError("Один из VESC недоступен.")
|
||||
now = datetime.now(timezone.utc)
|
||||
settings = envelope["settings"]
|
||||
output = ({"max_duty_percent": settings["max_duty_percent"]} if "max_duty_percent" in settings
|
||||
else {"erpm": settings["max_erpm"]})
|
||||
command = {"action_id":"vesc.drive.run","operation_id":"op_"+uuid.uuid4().hex,
|
||||
"requested_at":now.isoformat(),"deadline_at":(now+timedelta(seconds=300)).isoformat(),
|
||||
"parameters":{"current_a":settings["current_a"],"duration_s":30,"erpm":settings["max_erpm"],
|
||||
"parameters":{"current_a":settings["current_a"],"duration_s":30,**output,
|
||||
"standstill_confirmed":True,"profile_revision":profile["revision"],
|
||||
"device_ids":[profile["bindings"][s]["device_id"] for s in slots]}}
|
||||
owner.run(command, devices, devices[0], remote=self)
|
||||
except ControlEnded:
|
||||
except ControlEnded as error:
|
||||
self.trace.add("control_ended",reason=str(error),session_id=envelope["id"],release_confirmed=self.release_confirmed)
|
||||
with self.lock:
|
||||
self.state = "fault" if self.message or self.release_confirmed is False else "stopped"
|
||||
# drive() classifies only successful, finite release readback
|
||||
# as pending. Keep that state while the passive observer proves
|
||||
# standstill; an expired input is never granted more lifetime.
|
||||
if self.state != "stopping" or not settlement_pending(self.release_evidence):
|
||||
self.state = "fault" if self.message or self.release_confirmed is False else "stopped"
|
||||
except (OSError, ValueError, TimeoutError, KeyError) as error:
|
||||
with self.lock:
|
||||
self.state = "fault"
|
||||
self.message = str(error) if self.message is None else self.message + " " + str(error)
|
||||
self.trace.add("failure",error_type=type(error).__name__,reason=str(error)[:512],
|
||||
violation=getattr(error,"violation",None),device_id=getattr(error,"device_id",None),session_id=envelope["id"])
|
||||
failure(error, "remote_control", session_id=envelope["id"],
|
||||
release_confirmed=self.release_confirmed)
|
||||
finally:
|
||||
with self.lock: self.lease.stop()
|
||||
with self.lock:
|
||||
self.lease.stop()
|
||||
self.last_stop = {"session_id": envelope["id"], "state": self.state,
|
||||
"message": self.message, "release_confirmed": self.release_confirmed,
|
||||
"release_evidence": copy.deepcopy(self.release_evidence),
|
||||
"at": datetime.now(timezone.utc).isoformat()}
|
||||
if ((self.state == "fault" or self.message) and devices and self.pending_release is None
|
||||
and self.pending_availability is None):
|
||||
self._await_release(devices)
|
||||
if acquired: self.service.operation_lock.release()
|
||||
|
||||
def ensure_live(self):
|
||||
with self.lock:
|
||||
if not self.lease.live(): raise ControlEnded("Управление остановлено: команда больше не подтверждается.")
|
||||
if not self.lease.live():
|
||||
self.trace.add("lease_expired",session_id=self.lease.id,sequence=self.lease.sequence,
|
||||
remaining_ms=(self.lease.until-time.monotonic())*1000)
|
||||
raise ControlEnded("Управление остановлено: команда больше не подтверждается.")
|
||||
|
||||
def drive(self, owner, command, devices, moving, originals, unchanged):
|
||||
from .motor_test import check_values
|
||||
limit = command["parameters"]["current_a"]
|
||||
maximum = command["parameters"]["erpm"]
|
||||
maximum = command["parameters"].get("erpm", 0)
|
||||
duty_percent = command["parameters"].get("max_duty_percent")
|
||||
duty = None
|
||||
profile = copy.deepcopy(self.service.drive.value)
|
||||
sides = {b["device_id"]:0 if slot.startswith("left.") else 1 for slot,b in profile["bindings"].items()}
|
||||
configs, minimum_speeds, claimed, neutral_since = {}, {}, False, None
|
||||
previous, speeds = time.monotonic(), {d.id:0. for d in moving}
|
||||
last_sign, undriven_since = {}, None
|
||||
self.release_confirmed = None
|
||||
self.release_evidence = None
|
||||
owner.active, owner.mode = True, "remote"
|
||||
receiver = False
|
||||
input_ended = False
|
||||
zero_seen = False
|
||||
stalls = {}
|
||||
with ThreadPoolExecutor(max_workers=min(16,len(devices)),thread_name_prefix="vesc-remote") as pool:
|
||||
@@ -216,6 +404,14 @@ class RemoteControl:
|
||||
for d in moving:
|
||||
self.ensure_live()
|
||||
configs[d.id] = owner.limits.apply(d, originals[d.id]["motor"], limit)
|
||||
if self.trace.active():self.trace.add("limits_applied",device_id=d.id,requested_current_a=limit,
|
||||
motor={k:configs[d.id].get(k) for k in ("l_current_min","l_current_max",
|
||||
"l_current_min_scale","l_current_max_scale","l_max_duty","foc_sensor_mode","s_pid_min_erpm")},
|
||||
application={k:decode(originals[d.id]["application"],"application").get(k) for k in
|
||||
("app_to_use","app_ppm_conf.ctrl_type","app_ppm_conf.hyst","app_ppm_conf.ramp_time_pos","app_ppm_conf.ramp_time_neg")})
|
||||
if duty_percent is not None:
|
||||
minimum_speeds[d.id] = 0
|
||||
continue
|
||||
minimum = configs[d.id]["s_pid_min_erpm"]
|
||||
if not math.isfinite(minimum) or minimum < 0:
|
||||
raise ValueError("Некорректный минимальный порог регулятора VESC.")
|
||||
@@ -224,6 +420,9 @@ class RemoteControl:
|
||||
minimum_speeds[d.id] = max(1, math.ceil(minimum))
|
||||
if maximum < minimum_speeds[d.id]:
|
||||
raise ValueError(f"Минимальная скорость регулятора этого VESC: {minimum_speeds[d.id]} ERPM.")
|
||||
if duty_percent is not None:
|
||||
duty = DutyOutput(configs, {d.id: decode(originals[d.id]["application"], "application")
|
||||
for d in moving}, duty_percent)
|
||||
self.state = "ready"
|
||||
while True:
|
||||
cycle = time.monotonic()
|
||||
@@ -256,8 +455,12 @@ class RemoteControl:
|
||||
targets = {}
|
||||
for d in moving:
|
||||
value=readouts[d.id][0]
|
||||
check_values(value,moving=True,current_a=limit,motor=configs[d.id])
|
||||
target=demand[sides[d.id]]*maximum
|
||||
try:check_values(value,moving=True,current_a=limit,motor=configs[d.id],configured_drive=duty is not None)
|
||||
except ValueError as error:
|
||||
error.device_id=d.id
|
||||
self.trace.add("guard_failed",device_id=d.id,violation=getattr(error,"violation",None),reason=str(error),values=value)
|
||||
raise
|
||||
target=duty.target(d.id,demand[sides[d.id]]) if duty else demand[sides[d.id]]*maximum
|
||||
minimum = minimum_speeds[d.id]
|
||||
# A small analogue request must never be rounded UP to
|
||||
# a faster requested speed. Release below the operable
|
||||
@@ -274,7 +477,8 @@ class RemoteControl:
|
||||
if undriven_since is None: undriven_since = now
|
||||
else: undriven_since = None
|
||||
reversing = any(sign and last_sign.get(key,sign)!=sign for key,sign in signs.items())
|
||||
if reversing and (undriven_since is None or now-undriven_since<.5):
|
||||
reversal_wait = reversing and (undriven_since is None or now-undriven_since<.5)
|
||||
if reversal_wait:
|
||||
# One shared barrier: after a turn, the side keeping its
|
||||
# direction must not drive while the other waits to reverse.
|
||||
targets = dict.fromkeys(targets, 0.)
|
||||
@@ -284,9 +488,12 @@ class RemoteControl:
|
||||
value=readouts[d.id][0]
|
||||
target=targets[d.id]
|
||||
minimum=minimum_speeds[d.id]
|
||||
# Zero is immediate release, never an RPM hold/brake.
|
||||
# Zero removes demand immediately; send() distinguishes an idle
|
||||
# side during a duty turn from releasing the whole drive.
|
||||
if target==0:
|
||||
speeds[d.id]=0
|
||||
elif duty:
|
||||
speeds[d.id]=duty.advance(d.id,speeds[d.id],target,dt)
|
||||
else:
|
||||
step=600*dt
|
||||
speeds[d.id]+=max(-step,min(step,target-speeds[d.id]))
|
||||
@@ -296,7 +503,9 @@ class RemoteControl:
|
||||
# immediately, then keep the existing ramp above it.
|
||||
if abs(speeds[d.id]) < minimum:
|
||||
speeds[d.id] = math.copysign(minimum, target)
|
||||
if abs(value["motor_current_a"])>5:
|
||||
# A zero-duty side can brake while the other side turns;
|
||||
# stationary braking is not a failed motion command.
|
||||
if abs(value["motor_current_a"])>5 and (not duty or target != 0):
|
||||
at,tacho=stalls.setdefault(d.id,(now,value["tachometer"]))
|
||||
if abs(value["erpm"])>=60 and abs(value["tachometer"]-tacho)>=3: stalls[d.id]=(now,value["tachometer"])
|
||||
elif now-at>=2: raise ValueError("Мотор не движется при токе выше 5 А.")
|
||||
@@ -309,35 +518,74 @@ class RemoteControl:
|
||||
if not receiver: self.ensure_live()
|
||||
def send(d):
|
||||
if not receiver: self.ensure_live()
|
||||
if owner.stop.is_set() or receiver or abs(speeds.get(d.id,0))<1: d.link.test_command("release")
|
||||
if owner.stop.is_set() or receiver or d not in moving or (not any(speeds.values()) if duty else abs(speeds.get(d.id,0))<1): d.link.test_command("release")
|
||||
elif duty: d.link.drive_duty(speeds[d.id], limit)
|
||||
else: d.link.test_speed(speeds[d.id])
|
||||
self.trace.add("output_attempt",session_id=self.lease.id,sequence=self.lease.sequence,
|
||||
demand=list(demand),targets=targets,outputs=speeds.copy(),mode="duty" if duty else "rpm",
|
||||
zero_seen=zero_seen,receiver=receiver,quiet=quiet,reversal_wait=reversal_wait,
|
||||
quiet_ms=None if undriven_since is None else (now-undriven_since)*1000,
|
||||
read_elapsed_ms=(now-cycle)*1000,cycle_elapsed_ms=(time.monotonic()-cycle)*1000)
|
||||
batch(pool,devices,send)
|
||||
self.trace.add("output_sent",session_id=self.lease.id,sequence=self.lease.sequence,
|
||||
elapsed_ms=(time.monotonic()-cycle)*1000,
|
||||
rpc={d.id:{k:getattr(d.link,"last_rpc",{}).get(k) for k in ("method","elapsed_ms","ok","control","can_bridge")} for d in devices})
|
||||
if not receiver: self.state="driving" if any(speeds.values()) else "ready"
|
||||
owner.sleep(max(0,.1-(time.monotonic()-cycle)))
|
||||
except ControlEnded:
|
||||
input_ended = True
|
||||
raise
|
||||
finally:
|
||||
self.state="stopping"
|
||||
def release(d):
|
||||
try: d.link.test_command("release")
|
||||
except (OSError,ValueError,TimeoutError): pass
|
||||
if claimed: batch(pool,devices,release)
|
||||
try:
|
||||
d.link.test_command("release")
|
||||
self.trace.add("release_sent",device_id=d.id)
|
||||
return {"sent": True}
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
self.trace.add("release_send_failed",device_id=d.id,error_type=type(error).__name__)
|
||||
return {"sent": False, "error_type": type(error).__name__}
|
||||
if claimed: sent = batch(pool,devices,release)
|
||||
if claimed:
|
||||
owner.sleep(.3)
|
||||
def released(d):
|
||||
try:
|
||||
value = values(d.link.query(4, timeout=.1))
|
||||
return all(math.isfinite(value[k]) and abs(value[k]) <= 1
|
||||
for k in ("motor_current_a", "input_current_a")) and abs(value["duty"]) < .01
|
||||
except (OSError, ValueError, TimeoutError): return False
|
||||
self.release_confirmed = all(batch(pool, devices, released).values())
|
||||
self.trace.add("release_readback",device_id=d.id,values=value)
|
||||
confirmed = all(math.isfinite(value[k]) and abs(value[k]) <= 1
|
||||
for k in ("motor_current_a", "input_current_a")) and abs(value["duty"]) < .01
|
||||
keys = ("motor_current_a", "input_current_a", "duty", "erpm", "fault_code")
|
||||
finite = all(math.isfinite(value[k]) for k in keys)
|
||||
return {"confirmed": confirmed,
|
||||
"reason": "neutral_readback" if confirmed else "non_neutral_readback" if finite else "invalid_readback",
|
||||
"values": {k: value[k] if math.isfinite(value[k]) else None for k in keys}}
|
||||
except (OSError, ValueError, TimeoutError) as error:
|
||||
self.trace.add("release_read_failed",device_id=d.id,error_type=type(error).__name__)
|
||||
return {"confirmed": False, "reason": "read_failed", "error_type": type(error).__name__}
|
||||
readback = batch(pool, devices, released)
|
||||
# Publish only after every read completes. This diagnostic record
|
||||
# does not change release thresholds, waits, outputs or authority.
|
||||
self.release_evidence = {"schema": "missioncore.release-evidence/v1",
|
||||
"sample_mono_ms": time.monotonic() * 1000,
|
||||
"devices": {key: {"send": sent[key], **value} for key, value in readback.items()}}
|
||||
self.release_confirmed = all(value["confirmed"] for value in readback.values())
|
||||
if not self.release_confirmed:
|
||||
self.message = "Снятие тока не подтверждено. Проверьте фактическое состояние моторов."
|
||||
self.message = RELEASE_NOTICE
|
||||
owner.state("rc")
|
||||
for d in moving:
|
||||
try: owner.limits.restore(d)
|
||||
except (OSError,ValueError,TimeoutError):
|
||||
notice="Восстановление пределов ожидает нейтрали."
|
||||
try:
|
||||
owner.limits.restore(d)
|
||||
self.trace.add("limits_restored",device_id=d.id)
|
||||
except (OSError,ValueError,TimeoutError) as error:
|
||||
self.trace.add("limits_restore_failed",device_id=d.id,error_type=type(error).__name__,reason=str(error)[:512])
|
||||
notice="Восстановление токовых пределов не подтверждено."
|
||||
self.message=(self.message+" " if self.message else "")+notice
|
||||
owner.state("rc")
|
||||
owner.active,owner.mode=False,None
|
||||
self.state="fault" if self.release_confirmed is False else "receiver" if receiver else "stopped"
|
||||
if self.release_confirmed is False:
|
||||
self._await_release(devices)
|
||||
pending = (input_ended and not receiver and self.release_confirmed is False
|
||||
and self.message == RELEASE_NOTICE and settlement_pending(self.release_evidence))
|
||||
self.state=("stopping" if pending else "fault") if self.release_confirmed is False else "receiver" if receiver else "stopped"
|
||||
self.trace.add("cleanup_complete",session_id=self.lease.id,release_confirmed=self.release_confirmed,state=self.state,message=self.message)
|
||||
if not receiver and not owner.latched: owner.state("ready")
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Remote throttle matching the admitted FW 5.02 PPM Duty Cycle profile.
|
||||
|
||||
Percent is an output request, not ground speed or a manufacturer rating.
|
||||
Zero always releases; the caller retains lease, neutral and reversal ownership.
|
||||
"""
|
||||
import math
|
||||
|
||||
|
||||
class DutyOutput:
|
||||
def __init__(self, motors, applications, percent):
|
||||
if type(percent) not in (int, float) or not 1 <= percent <= 100:
|
||||
raise ValueError("Газ должен быть в диапазоне 1–100%.")
|
||||
self.fraction = percent / 100
|
||||
self.maxima = {}
|
||||
positive, negative = [], []
|
||||
for identifier, motor in motors.items():
|
||||
app = applications[identifier]
|
||||
maximum = motor["l_max_duty"]
|
||||
if (app["app_ppm_conf.ctrl_type"] != 4 or not math.isfinite(maximum)
|
||||
or not 0 < maximum <= 1):
|
||||
raise ValueError("Для управления газом требуется профиль PPM Duty Cycle.")
|
||||
self.maxima[identifier] = maximum
|
||||
for field, target in (("ramp_time_pos", positive), ("ramp_time_neg", negative)):
|
||||
value = app["app_ppm_conf." + field]
|
||||
if not math.isfinite(value) or not 0 <= value <= 60:
|
||||
raise ValueError("Некорректная плавность газа в настройках пульта.")
|
||||
target.append(value)
|
||||
# One normalised ramp for both tracks, no side outruns the other due
|
||||
# to unequal receiver settings. Never faster than either configured ramp.
|
||||
self.positive = max(positive)
|
||||
self.negative = max(negative)
|
||||
|
||||
def target(self, identifier, demand):
|
||||
return demand * self.fraction * self.maxima[identifier]
|
||||
|
||||
def advance(self, identifier, previous, target, dt):
|
||||
if target == 0:
|
||||
return 0.0
|
||||
ramp = self.positive if abs(target) > abs(previous) else self.negative
|
||||
if ramp <= .01:
|
||||
return target
|
||||
step = self.maxima[identifier] * max(0, min(.15, dt)) / ramp
|
||||
return previous + max(-step, min(step, target - previous))
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Read-only operating-current projection; never a configuration writer."""
|
||||
import math
|
||||
import time
|
||||
|
||||
def publish(device, motor):
|
||||
fields = ("l_current_max", "l_current_min", "l_current_max_scale", "l_current_min_scale")
|
||||
if any(type(motor.get(k)) not in (int, float) or not math.isfinite(motor[k]) for k in fields):
|
||||
raise ValueError("Invalid motor current configuration")
|
||||
if not (motor["l_current_min"] < 0 < motor["l_current_max"] and
|
||||
0 < motor["l_current_max_scale"] <= 1 and 0 < motor["l_current_min_scale"] <= 1):
|
||||
raise ValueError("Invalid motor current scales")
|
||||
device.drive_limits = {"session_id": device.session, "sampled_at": time.monotonic(),
|
||||
"motor_a": motor["l_current_max"] * motor["l_current_max_scale"],
|
||||
"brake_a": -motor["l_current_min"] * motor["l_current_min_scale"]}
|
||||
|
||||
def projection(device):
|
||||
limits = device.get("drive_limits")
|
||||
if not limits or limits["session_id"] != device["session"]: return None
|
||||
return {k: limits[k] for k in ("motor_a", "brake_a")}
|
||||
@@ -0,0 +1,92 @@
|
||||
"""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
|
||||
@@ -1,19 +1,46 @@
|
||||
"""Private Unix socket endpoint; peer UID must be the installed Node service."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pwd
|
||||
import re
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from urllib.parse import urlsplit, parse_qs
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from .service import Service
|
||||
from .diagnostics import failure
|
||||
from .remote_control import RemoteControl
|
||||
from .maintenance_state import idle, quiesce
|
||||
from .service import Service
|
||||
try:
|
||||
from .maintenance import Maintenance # Same SDK file copied by payload.py.
|
||||
except ModuleNotFoundError: # Source checkout, never needed on installed Node.
|
||||
import runpy
|
||||
Maintenance = runpy.run_path(str(Path(__file__).resolve().parents[3] /
|
||||
"packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py"))["Maintenance"]
|
||||
|
||||
|
||||
def poll_readonly(callback, stop, interval, phase, maintenance=None):
|
||||
"""Keep discovery/observation alive; never retry a powered operation here."""
|
||||
next_report = 0.0
|
||||
while not stop.is_set():
|
||||
try:
|
||||
if maintenance is None:
|
||||
callback()
|
||||
else:
|
||||
with maintenance.work(background=True) as admitted:
|
||||
if admitted: callback()
|
||||
except Exception as error:
|
||||
if time.monotonic() >= next_report:
|
||||
next_report = time.monotonic() + 30
|
||||
failure(error, phase)
|
||||
stop.wait(interval)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
@@ -27,14 +54,46 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.dispatch()
|
||||
|
||||
def dispatch(self):
|
||||
_, uid, _ = struct.unpack("3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
|
||||
if uid == 0:
|
||||
result = None
|
||||
if self.command == "POST" and self.path == "/maintenance/enter":
|
||||
result = self.server.maintenance.enter(self.server.idle, self.server.quiesce)
|
||||
elif self.command == "POST" and self.path == "/maintenance/leave":
|
||||
try: result = self.server.maintenance.leave()
|
||||
except ValueError: result = {"resumed": False}
|
||||
elif self.command == "GET" and self.path == "/prepare-safe":
|
||||
result = {"safe": self.server.maintenance.closed and self.server.idle() is None}
|
||||
if result is not None:
|
||||
data = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
self.send_error(403)
|
||||
return
|
||||
with self.server.maintenance.work() as admitted:
|
||||
if not admitted:
|
||||
self.send_error(503, "Device service is under maintenance")
|
||||
return
|
||||
self.dispatch_admitted()
|
||||
|
||||
def dispatch_admitted(self):
|
||||
self.connection.settimeout(10)
|
||||
status = 200
|
||||
try:
|
||||
node = self.headers.get("X-Node-Id", "")
|
||||
if not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) or self.headers.get("Transfer-Encoding"):
|
||||
if not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) or self.headers.get(
|
||||
"Transfer-Encoding"
|
||||
):
|
||||
raise ValueError("Invalid request")
|
||||
if self.command == "GET" and self.path == "/inventory":
|
||||
result = self.server.service.inventory(node)
|
||||
elif self.command == "GET" and self.path == "/observe":
|
||||
result = self.server.service.remote.observe_snapshot()
|
||||
elif self.command == "GET" and self.path.startswith("/archives/"):
|
||||
url = urlsplit(self.path)
|
||||
parts = url.path.split("/")
|
||||
@@ -49,19 +108,26 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif self.command == "GET" and self.path.startswith("/archive-export?"):
|
||||
after = int(parse_qs(urlsplit(self.path).query).get("after", ["0"])[0])
|
||||
result = self.server.service.archive.export("local", after)
|
||||
elif self.command == "POST" and self.path in ("/operation", "/remote"):
|
||||
elif self.command == "POST" and self.path in ("/operation", "/remote", "/drive-trace"):
|
||||
size = int(self.headers.get("Content-Length", "0"))
|
||||
if not 0 < size <= 65536 or self.headers.get("Content-Type") != "application/json":
|
||||
raise ValueError("Invalid command")
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise ValueError("Truncated command")
|
||||
result = (self.server.service.execute(json.loads(raw)) if self.path == "/operation"
|
||||
else self.server.service.remote.feed(json.loads(raw)))
|
||||
result = (
|
||||
self.server.service.execute(json.loads(raw))
|
||||
if self.path == "/operation"
|
||||
else self.server.service.remote.trace.exchange(json.loads(raw)) if self.path == "/drive-trace"
|
||||
else self.server.service.remote.feed(json.loads(raw))
|
||||
)
|
||||
else:
|
||||
raise ValueError("Unknown route")
|
||||
except (ValueError, KeyError, TypeError, OSError):
|
||||
status, result = 400, {"error": "Запрос VESC отклонён. Обновите сведения об устройстве."}
|
||||
status, result = (
|
||||
400,
|
||||
{"error": "Запрос VESC отклонён. Обновите сведения об устройстве."},
|
||||
)
|
||||
data = json.dumps(result, ensure_ascii=False, allow_nan=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
@@ -95,40 +161,42 @@ class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
self.slots.release()
|
||||
|
||||
def verify_request(self, request, address):
|
||||
_, uid, _ = struct.unpack("3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
|
||||
return uid == self.node_uid
|
||||
_, uid, _ = struct.unpack(
|
||||
"3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||
)
|
||||
return uid in (0, self.node_uid)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
if os.geteuid() == 0:
|
||||
raise RuntimeError("VESC must run as its own unprivileged user")
|
||||
os.umask(0o007)
|
||||
service = Service("/var/lib/mission-core-vesc")
|
||||
service.remote = RemoteControl(service)
|
||||
stop = threading.Event()
|
||||
|
||||
def scan():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
service.scan()
|
||||
except OSError:
|
||||
# A transient sysfs race must not silently kill discovery.
|
||||
pass
|
||||
stop.wait(2)
|
||||
|
||||
def observe():
|
||||
while not stop.is_set():
|
||||
service.remote.observe()
|
||||
stop.wait(.2)
|
||||
maintenance = Maintenance()
|
||||
|
||||
path = Path("/run/mission-core-vesc/driver.sock")
|
||||
path.unlink(missing_ok=True)
|
||||
with Server(str(path), Handler) as server:
|
||||
server.node_uid = pwd.getpwnam("mission-core-node").pw_uid
|
||||
server.service = service
|
||||
thread = threading.Thread(target=scan, daemon=True)
|
||||
thread.start()
|
||||
threading.Thread(target=observe, daemon=True, name="vesc-observer").start()
|
||||
server.maintenance = maintenance
|
||||
server.idle = lambda: idle(service)
|
||||
server.quiesce = lambda: quiesce(service)
|
||||
threading.Thread(
|
||||
target=poll_readonly,
|
||||
args=(service.scan, stop, 2, "discovery-loop", maintenance),
|
||||
daemon=True,
|
||||
name="vesc-discovery",
|
||||
).start()
|
||||
threading.Thread(
|
||||
target=poll_readonly,
|
||||
args=(service.remote.observe, stop, 0.2, "observation-loop", maintenance),
|
||||
daemon=True,
|
||||
name="vesc-observer",
|
||||
).start()
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
|
||||
+266
-58
@@ -16,16 +16,39 @@ from . import MODEL, SCHEMA, VERSION
|
||||
from .protocol import firmware, values, ppm, TEST_LIMITS, SPEED_LIMITS
|
||||
from .motor_test import MotorTest, Rejected
|
||||
from .drive_profile import DriveProfile, slot_label, validate as validate_drive
|
||||
from .control_transport import ControlTransport, validate_routes
|
||||
from .transport_hub import TransportHub, Missing
|
||||
from .can_bridge import Attachment as CanAttachment
|
||||
from .serial import device_id, discover
|
||||
from .native_link import NativeLink
|
||||
from .native_link import NativeLink, reap_retired
|
||||
from .diagnostics import failure, connection
|
||||
from .read_cache import ReadCache, SNAPSHOT_ACTIONS, EXPIRED
|
||||
from .bms_configuration import BmsConfiguration, ACTIONS as BMS_CONFIG_ACTIONS, READS as BMS_CONFIG_READS, validate as validate_bms_config
|
||||
from .package_tools import PackageTools, ACTIONS as PACKAGE_ACTIONS, READS as PACKAGE_READS, validate as validate_packages
|
||||
from .sample_data import SampleData, ACTIONS as SAMPLE_ACTIONS, validate as validate_samples
|
||||
from .qml_preview import QmlPreview, ACTIONS as QML_ACTIONS, validate as validate_qml
|
||||
from .code_tools import CodeTools, ACTIONS as CODE_ACTIONS, READS as CODE_READS, validate as validate_code
|
||||
from .bms import BmsControl, ACTIONS as BMS_ACTIONS, validate as validate_bms
|
||||
from .firmware_update import FirmwareUpdate, ACTIONS as FIRMWARE_ACTIONS, SNAPSHOTS as FIRMWARE_SNAPSHOTS, validate as validate_firmware
|
||||
try:
|
||||
from .archive import Archive
|
||||
except ImportError: # Source checkout; packaging copies this exact shared file.
|
||||
from k1link.device_plugins.vesc.archive import Archive
|
||||
|
||||
ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"})
|
||||
ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.configuration.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"})
|
||||
|
||||
|
||||
ACTIONS = ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_ACTIONS | BMS_CONFIG_ACTIONS | CODE_ACTIONS | BMS_ACTIONS | FIRMWARE_ACTIONS | {"vesc.tools.read", "vesc.terminal.read"}
|
||||
|
||||
READ_ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read",
|
||||
"vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read",
|
||||
"vesc.config.backup", "vesc.configuration.preview", "vesc.configuration.reconcile", "vesc.input.read", "vesc.can.read"})
|
||||
|
||||
SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | FIRMWARE_SNAPSHOTS
|
||||
READ_ACTIONS = READ_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"}
|
||||
SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"}
|
||||
READ_ACTIONS = READ_ACTIONS | (FIRMWARE_ACTIONS - {'vesc.firmware.apply','vesc.firmware.cancel','vesc.firmware.status'})
|
||||
|
||||
def utc():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
@@ -62,11 +85,15 @@ class Device:
|
||||
self.backup = None
|
||||
self.lock = threading.Lock()
|
||||
self.retry_at = 0
|
||||
self.failure_at = 0
|
||||
self.failures = 0
|
||||
self.sample = None
|
||||
self.identified_session = None
|
||||
|
||||
@property
|
||||
def readable(self):
|
||||
identity = self.identity
|
||||
return self.readable_identity(identity)
|
||||
return self.readable_identity(identity) and getattr(self.link,"engine",{}).get("firmware_admitted",True)
|
||||
|
||||
@staticmethod
|
||||
def readable_identity(identity):
|
||||
@@ -77,23 +104,64 @@ class Device:
|
||||
with self.lock:
|
||||
try:
|
||||
self.session = "vesc_" + uuid.uuid4().hex
|
||||
self.opened = utc()
|
||||
self.identified_session = None
|
||||
self.sample = self.telemetry = None
|
||||
self.link = factory(self.attachment)
|
||||
identity = firmware(self.link.query(0))
|
||||
if isinstance(self.attachment, CanAttachment) and identity["uuid"] != self.attachment.expected_uuid:
|
||||
raise ValueError("На этом CAN-адресе другой UUID VESC.")
|
||||
self.identity = identity
|
||||
self.id = device_id("uuid:" + identity["uuid"])
|
||||
self.identified_session = self.session
|
||||
self.error = None
|
||||
except (OSError, ValueError, TimeoutError):
|
||||
if self.link:
|
||||
self.link.close()
|
||||
self.link = None
|
||||
self.error = "Контроллер не ответил. Проверьте питание, USB и доступность порта."
|
||||
self.retry_at = time.monotonic() + 15
|
||||
connection("identified", self)
|
||||
# A firmware reply alone does not reset repeated read failures.
|
||||
except Exception as error:
|
||||
self.failed(error, "connection")
|
||||
|
||||
def failed(self, error, phase):
|
||||
"""Called with device.lock held. One retry deadline, no retry worker."""
|
||||
previous_session = self.session
|
||||
if self.link is not None or self.sample is not None:
|
||||
connection("read_failed", self, error)
|
||||
link, self.link = self.link, None
|
||||
self.sample = self.telemetry = None
|
||||
self.session = "vesc_" + uuid.uuid4().hex
|
||||
self.failures = min(self.failures + 1, 5)
|
||||
self.retry_at = time.monotonic() + min(2 ** self.failures, 30)
|
||||
self.error = "Нет ответа VESC. Повторное подключение выполняется автоматически."
|
||||
try:
|
||||
if link: link.close()
|
||||
except Exception as cleanup_error:
|
||||
if time.monotonic() >= self.failure_at:
|
||||
failure(cleanup_error, "connection-cleanup", device=self)
|
||||
if time.monotonic() >= self.failure_at:
|
||||
self.failure_at = time.monotonic() + 30
|
||||
failure(error, phase, device=self, session_id=previous_session)
|
||||
|
||||
def publish_sample(self, value, receiver):
|
||||
restored = self.sample is None
|
||||
self.sample = {"session_id": self.session, "values": value,
|
||||
"receiver": receiver, "sampled_at": time.monotonic(), "observed_at": utc()}
|
||||
self.failures = 0
|
||||
self.retry_at = 0
|
||||
self.error = None
|
||||
if restored:
|
||||
connection("sample_restored", self)
|
||||
|
||||
def close(self):
|
||||
with self.lock:
|
||||
if self.link:
|
||||
self.link.close()
|
||||
self.link = None
|
||||
connection("usb_detached", self)
|
||||
link, self.link = self.link, None
|
||||
self.sample = self.telemetry = None
|
||||
self.session = "vesc_" + uuid.uuid4().hex
|
||||
try:
|
||||
if link: link.close()
|
||||
except Exception as error:
|
||||
if time.monotonic() >= self.failure_at:
|
||||
self.failure_at = time.monotonic() + 30
|
||||
failure(error, "connection-close", device=self)
|
||||
|
||||
|
||||
class Service:
|
||||
@@ -108,31 +176,35 @@ class Service:
|
||||
self.lock = threading.RLock()
|
||||
self.operation_lock = threading.Lock()
|
||||
self.journal_lock = threading.Lock()
|
||||
self.read_cache = ReadCache()
|
||||
self.motor = MotorTest(self, atomic, utc)
|
||||
from .config_editor import ConfigEditor
|
||||
self.config_editor = ConfigEditor(self, atomic, utc)
|
||||
self.firmware_update = FirmwareUpdate(self, atomic, utc)
|
||||
self.bms = BmsControl(self, atomic, utc)
|
||||
self.bms_configuration = BmsConfiguration(self, atomic, utc)
|
||||
self.code_tools = CodeTools(self, atomic, utc)
|
||||
self.samples = SampleData(self)
|
||||
self.qml = QmlPreview(self)
|
||||
self.qml_utc = utc
|
||||
self.packages = PackageTools(self, atomic, utc)
|
||||
self.drive = DriveProfile(self.root, atomic)
|
||||
self.instance = "vesc_" + uuid.uuid4().hex
|
||||
self.revision = 0
|
||||
self.device_type = Device
|
||||
self.transport = ControlTransport(self.root, atomic)
|
||||
self.transports = TransportHub(self, atomic)
|
||||
|
||||
def scan(self):
|
||||
attachments = {item.binding: item for item in self.discover_fn()}
|
||||
with self.lock:
|
||||
removed = [self.devices.pop(k) for k, d in list(self.devices.items())
|
||||
if attachments.get(k) != d.attachment]
|
||||
for key, item in attachments.items():
|
||||
if key not in self.devices:
|
||||
self.devices[key] = Device(item)
|
||||
devices = list(self.devices.values())
|
||||
for device in removed:
|
||||
device.close()
|
||||
for device in devices:
|
||||
if device.link is not None and not getattr(device.link, "alive", True):
|
||||
device.close()
|
||||
if device.link is None and time.monotonic() >= device.retry_at:
|
||||
device.connect(self.link_factory)
|
||||
reap_retired()
|
||||
self.transports.scan()
|
||||
with self.lock: devices = list(self.devices.values())
|
||||
if self.operation_lock.acquire(blocking=False):
|
||||
try:
|
||||
self.qml.maintain(devices)
|
||||
self.samples.maintain(devices)
|
||||
for device in devices:
|
||||
if device.link is not None and self.motor.limits.pending(device):
|
||||
if device.link is not None and not self.firmware_update.pending(device) and not self.bms_configuration.pending(device) and not self.code_tools.blocked(device) and self.motor.limits.pending(device):
|
||||
with device.lock:
|
||||
try:
|
||||
self.motor.limits.restore(device)
|
||||
@@ -149,32 +221,36 @@ class Service:
|
||||
# Copy each generation before counting identities. Serial I/O never
|
||||
# holds the inventory lock; it can complete during this projection.
|
||||
devices = [d.__dict__.copy() for d in self.devices.values()]
|
||||
keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] and d["link"] else d["attachment"].id for d in devices]
|
||||
items = []
|
||||
for d, key in zip(devices, keys):
|
||||
identity, attachment = d["identity"], d["attachment"]
|
||||
unique = keys.count(key) == 1 and identity is not None and d["link"] is not None
|
||||
identifier = key if unique else attachment.id
|
||||
message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна."
|
||||
items.append({"id": identifier, "attachment_id": attachment.id,
|
||||
"name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb),
|
||||
"model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL,
|
||||
"firmware": identity["version"] if unique else None,
|
||||
"initializable": True, "prepared": True, "configured": unique, "verified": unique,
|
||||
"preparation_safe": True, "online": True, "usb": attachment.speed,
|
||||
"connection_label": "USB " + attachment.usb + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [],
|
||||
"vesc_status": {"identity": identity if unique else None, "readable": unique and Device.readable_identity(identity),
|
||||
"engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"], "backup": d["backup"], "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": unique and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched},
|
||||
"snapshot": {"context": {"session_id": d["session"],
|
||||
"device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc",
|
||||
"plugin_version": VERSION, "model_id": MODEL},
|
||||
"stability": "stable" if unique else "provisional",
|
||||
"basis": "hardware-identifier" if unique else "transport-local"},
|
||||
"execution": {"node_id": node_id, "agent_instance_id": self.instance, "platform": "linux"},
|
||||
"opened_at": d["opened"]}, "revision": self.revision, "observed_at": utc(),
|
||||
"enrollment": "enrolled" if unique else "empty", "acquisition": "idle",
|
||||
"connectivity": "connected" if unique else "degraded", "message": message}})
|
||||
return {"items": items}
|
||||
keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] else d["attachment"].id for d in devices]
|
||||
items = []
|
||||
for d, key in zip(devices, keys):
|
||||
identity, attachment = d["identity"], d["attachment"]
|
||||
unique = keys.count(key) == 1 and identity is not None
|
||||
available = (unique and d["identified_session"] == d["session"]
|
||||
and d["link"] is not None and getattr(d["link"], "alive", True))
|
||||
sample = d["sample"] if available and d["sample"] and d["sample"]["session_id"] == d["session"] else None
|
||||
identifier = key if unique else attachment.id
|
||||
message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна."
|
||||
items.append({"id": identifier, "attachment_id": attachment.id,
|
||||
"name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb),
|
||||
"model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL,
|
||||
"firmware": identity["version"] if unique else None,
|
||||
"initializable": True, "prepared": True, "configured": unique, "verified": bool(available),
|
||||
"preparation_safe": True, "online": bool(available) if isinstance(attachment, CanAttachment) else not isinstance(attachment, Missing), "usb": attachment.speed,
|
||||
"connection_label": (attachment.usb if isinstance(attachment, CanAttachment) else "Недоступно" if isinstance(attachment, Missing) else "USB " + attachment.usb) + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [],
|
||||
"vesc_status": {"identity": identity if unique else None, "readable": bool(available) and Device.readable_identity(identity) and getattr(d["link"],"engine",{}).get("firmware_admitted",True),
|
||||
"connected": bool(available), "telemetry_ready": sample is not None,
|
||||
"engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"] if available else None, "backup": d["backup"], "configuration_read_supported": True, "configuration_edit_supported": True, "firmware_update_supported": True, "tools_read_supported": True, "terminal_read_supported": True, "firmware_update": self.firmware_update.status(identifier), "configuration_pending": self.config_editor.pending_path(identifier).exists(), "bms_configuration_pending": self.bms_configuration.path(identifier).exists(), "package_pending": self.packages.path(identifier).exists(), "code_pending": self.code_tools.path(identifier).exists(), "code_execution_pending": self.code_tools.path(identifier,"execution").exists(), "diagnostics_read_supported": True, "qml_preview_supported": True, "qml_interactive_supported": True, "qml_broker_supported": "qml_read" in (getattr(d["link"], "engine", None) or {}).get("contract", {}).get("methods", []), "sample_data_supported": bool(identity and identity["version"] == "5.02"), "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": bool(available) and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "control_transport": self.transports.profile(), "control_endpoints": self.transports.endpoints(), "control_adapters": [{**a, "label": a["name"]} for a in self.transports.adapters], "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched},
|
||||
"snapshot": {"context": {"session_id": d["session"],
|
||||
"device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc",
|
||||
"plugin_version": VERSION, "model_id": MODEL},
|
||||
"stability": "stable" if unique else "provisional",
|
||||
"basis": "hardware-identifier" if unique else "transport-local"},
|
||||
"execution": {"node_id": node_id, "agent_instance_id": self.instance, "platform": "linux"},
|
||||
"opened_at": d["opened"]}, "revision": self.revision, "observed_at": utc(),
|
||||
"enrollment": "enrolled" if unique else "empty", "acquisition": "idle",
|
||||
"connectivity": "connected" if available else "degraded", "message": message}})
|
||||
return {"items": items}
|
||||
|
||||
def validate(self, command):
|
||||
if not isinstance(command, dict) or command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest":
|
||||
@@ -211,9 +287,36 @@ class Service:
|
||||
raise ValueError("Explicit observation of all motors at standstill required")
|
||||
if action == "vesc.foc.calibrate" and (type(params["max_power_loss_w"]) not in (int,float) or not 10 <= params["max_power_loss_w"] <= 150):
|
||||
raise ValueError("Heating budget must be between 10 and 150 W")
|
||||
elif action == "vesc.tools.read":
|
||||
if set(params) != {'tool'} or params['tool'] not in ('adc','chuk','imu','bms'):
|
||||
raise ValueError('Unknown peripheral tool')
|
||||
elif action == "vesc.terminal.read":
|
||||
if set(params) != {'command'} or params['command'] not in ("hw_status", "faults", "fault", "ping", "mem", "threads", "rpm", "tacho", "volt", "uptime", "help"):
|
||||
raise ValueError('Only admitted read-only terminal commands are supported')
|
||||
elif action in BMS_CONFIG_ACTIONS:
|
||||
validate_bms_config(action, params)
|
||||
elif action in PACKAGE_ACTIONS:
|
||||
validate_packages(action, params)
|
||||
elif action in SAMPLE_ACTIONS:
|
||||
validate_samples(action, params)
|
||||
elif action in QML_ACTIONS:
|
||||
validate_qml(action, params)
|
||||
elif action in CODE_ACTIONS:
|
||||
validate_code(action, params)
|
||||
elif action in BMS_ACTIONS:
|
||||
validate_bms(action, params)
|
||||
elif action in FIRMWARE_ACTIONS:
|
||||
validate_firmware(action, params)
|
||||
elif action.startswith("vesc.configuration.") and action != "vesc.configuration.read":
|
||||
from .config_editor import validate
|
||||
validate(action, params)
|
||||
elif action == "vesc.link.check":
|
||||
if set(params) != {"sessions"} or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128:
|
||||
raise ValueError("Controller sessions required")
|
||||
elif action == "vesc.transport.configure":
|
||||
if not isinstance(params, dict) or set(params) != {"revision", "drive_revision", "routes"}:
|
||||
raise ValueError("Invalid control transport profile")
|
||||
validate_routes(params["routes"], self.drive.value)
|
||||
elif action in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"):
|
||||
validate_drive(action, params)
|
||||
elif params != {}:
|
||||
@@ -228,6 +331,29 @@ class Service:
|
||||
deadline = self.validate(command)
|
||||
path = self.root / (command["operation_id"] + ".json")
|
||||
digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest()
|
||||
if command["action_id"] in ("vesc.firmware.status", "vesc.firmware.cancel"):
|
||||
# Status/cancel are RAM/file operations and remain available while
|
||||
# the uploading request holds the exclusive hardware lock.
|
||||
with self.journal_lock:
|
||||
if path.exists():
|
||||
previous = json.loads(path.read_text())
|
||||
if previous['digest'] != digest: raise ValueError('Operation identity conflict')
|
||||
return self.read_cache.get(command['operation_id']) if previous.get('snapshot_only') else previous['receipt']
|
||||
if deadline <= datetime.now(timezone.utc): raise ValueError('Operation expired')
|
||||
identifier = command['session']['device_id']
|
||||
with self.lock:
|
||||
if not any(d.id == identifier for d in self.devices.values()):
|
||||
raise ValueError('Device no longer present')
|
||||
result = (self.firmware_update.status(identifier) if command['action_id'].endswith('.status')
|
||||
else self.firmware_update.cancel(identifier, command['parameters']['operation_id']))
|
||||
receipt = {'state':'complete','result':result}
|
||||
if command['action_id'].endswith('.status'):
|
||||
if sum(p.stat().st_size for p in self.root.glob('*.json')) > 32 * 1024 * 1024:
|
||||
raise ValueError('Read journal is full')
|
||||
self.read_cache.put(command['operation_id'], receipt)
|
||||
atomic(path, {'digest':digest,'snapshot_only':True,'receipt':EXPIRED})
|
||||
else: atomic(path, {'digest':digest,'receipt':receipt})
|
||||
return receipt
|
||||
if command["action_id"] == "vesc.motor.stop":
|
||||
with self.journal_lock:
|
||||
if path.exists():
|
||||
@@ -239,13 +365,19 @@ class Service:
|
||||
result = {"state": "complete", "result": {"stop_requested": True, "interruptible": self.motor.mode not in ("hall", "foc"), "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "test_active": self.motor.active}}
|
||||
atomic(path, {"digest": digest, "receipt": result})
|
||||
return result
|
||||
if not self.operation_lock.acquire(blocking=False):
|
||||
# Observer samples own the same lock for a short exchange. Read requests
|
||||
# wait at most half a second, within their remaining read budget.
|
||||
# Powered operations keep immediate admission; no delayed motor start.
|
||||
wait = max(0.0, min(.5, (deadline-datetime.now(timezone.utc)).total_seconds()-8)) if command["action_id"] in READ_ACTIONS or command["action_id"] == "vesc.transport.configure" else 0.0
|
||||
if not self.operation_lock.acquire(timeout=wait):
|
||||
raise ValueError("Another VESC operation is running")
|
||||
try:
|
||||
if path.exists():
|
||||
previous = json.loads(path.read_text())
|
||||
if previous["digest"] != digest:
|
||||
raise ValueError("Operation identity conflict")
|
||||
if command["action_id"] in SNAPSHOT_ACTIONS and previous.get("snapshot_only"):
|
||||
return self.read_cache.get(command["operation_id"])
|
||||
return previous["receipt"]
|
||||
if deadline <= datetime.now(timezone.utc):
|
||||
raise ValueError("Operation expired")
|
||||
@@ -262,6 +394,12 @@ class Service:
|
||||
if path.exists(): raise ValueError("Operation identity already reserved")
|
||||
atomic(path, record)
|
||||
try:
|
||||
if self.samples.active(device) and command["action_id"] in {
|
||||
"vesc.firmware.apply", "vesc.firmware.target", "vesc.firmware.backup", "vesc.configuration.apply",
|
||||
"vesc.bms.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview",
|
||||
"vesc.bms.read", "vesc.bms.apply", "vesc.code.apply", "vesc.code.control_apply",
|
||||
"vesc.packages.apply", "vesc.hall.measure", "vesc.foc.calibrate"}:
|
||||
raise Rejected("Сначала остановите Sample Data или дождитесь окончания захвата.")
|
||||
if command["action_id"] == "vesc.link.check":
|
||||
from .link_check import measure
|
||||
with self.lock: devices = list(self.devices.values())
|
||||
@@ -269,6 +407,15 @@ class Service:
|
||||
record["receipt"] = {"state": "complete", "result": result}
|
||||
atomic(path, record)
|
||||
return record["receipt"]
|
||||
if command["action_id"] == "vesc.transport.configure":
|
||||
try:
|
||||
result = self.transport.update(command["parameters"], self.drive.value, active=self.motor.active or (getattr(self, "remote", None) is not None and self.remote.state == "preparing"))
|
||||
self.transports.select()
|
||||
except ValueError as error:
|
||||
raise Rejected(str(error)) from error
|
||||
record["receipt"] = {"state": "complete", "result": {"control_transport": result}}
|
||||
atomic(path, record)
|
||||
return record["receipt"]
|
||||
if command["action_id"] in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"):
|
||||
if device.identity is None: raise Rejected("Сначала подтвердите личность VESC.")
|
||||
try:
|
||||
@@ -296,10 +443,18 @@ class Service:
|
||||
with device.lock:
|
||||
if device.link is None:
|
||||
raise OSError("Device disconnected")
|
||||
if command["action_id"] not in READ_ACTIONS | CODE_ACTIONS | BMS_CONFIG_ACTIONS | PACKAGE_ACTIONS and (self.bms_configuration.pending(device) or self.code_tools.blocked(device)):
|
||||
raise Rejected("Сначала подтвердите изменение BMS/кода и остановите Lisp.")
|
||||
remaining = (deadline - datetime.now(timezone.utc)).total_seconds()
|
||||
if remaining < 8:
|
||||
raise TimeoutError("Insufficient time for bounded read")
|
||||
actual = firmware(device.link.query(0))
|
||||
# Local QML staging/input never interrogates USB; retain
|
||||
# the binding to this exact live attachment and session.
|
||||
if command["action_id"] in QML_ACTIONS:
|
||||
device.link.check()
|
||||
actual = device.identity
|
||||
else:
|
||||
actual = firmware(device.link.query(0))
|
||||
if actual != device.identity:
|
||||
device.link.close()
|
||||
device.link = None
|
||||
@@ -308,11 +463,60 @@ class Service:
|
||||
raise ValueError("Controller identity changed")
|
||||
result = {"identity": actual, "device_id": device.id, "observed_at": utc()}
|
||||
action = command["action_id"]
|
||||
if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup"} and not device.readable:
|
||||
if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read", "vesc.config.backup"} and not device.readable:
|
||||
raise ValueError("Firmware read layout is unsupported")
|
||||
if action == "vesc.telemetry.read":
|
||||
result.update(values=values(device.link.query(4)), monotonic_at=time.monotonic())
|
||||
device.telemetry = result
|
||||
elif action == 'vesc.tools.read':
|
||||
result.update(device.link.device_tool(command['parameters']['tool']))
|
||||
if command['parameters']['tool']=='bms':
|
||||
# FW5.02 proxy omits these fields. Native decoder defaults
|
||||
# are not measurements or evidence of a connected BMS.
|
||||
result['source']='controller_cache'
|
||||
result['source_age_known']=False
|
||||
if actual['version']=='5.02':
|
||||
for key in ('can_id','ah_cnt_chg_total','wh_cnt_chg_total','ah_cnt_dis_total','wh_cnt_dis_total','pressure','data_version','status'):
|
||||
result.get('values',{}).pop(key,None)
|
||||
elif action == 'vesc.terminal.read':
|
||||
result.update(device.link.diagnostic(command['parameters']['command']))
|
||||
elif action in BMS_CONFIG_ACTIONS:
|
||||
if action.endswith(".apply") and self.code_tools.blocked(device): raise Rejected("Сначала подтвердите запись кода и остановите Lisp.")
|
||||
result.update(self.bms_configuration.execute(device,action,command["parameters"],command["operation_id"],deadline))
|
||||
elif action in PACKAGE_ACTIONS:
|
||||
result.update(self.packages.execute(device,action,command["parameters"],command["operation_id"],deadline))
|
||||
elif action in SAMPLE_ACTIONS:
|
||||
result.update(self.samples.execute(device, action, command["parameters"]))
|
||||
elif action in QML_ACTIONS:
|
||||
result.update(self.qml.execute(device, action, command["parameters"]))
|
||||
elif action in CODE_ACTIONS:
|
||||
result.update(self.code_tools.execute(device,action,command["parameters"],command["operation_id"],deadline))
|
||||
elif action in BMS_ACTIONS:
|
||||
if not device.readable:raise Rejected('Бортовой VESC не поддерживает адресный BMS.')
|
||||
if action=='vesc.bms.read': result.update(self.bms.read(device,command['parameters']['can_id']))
|
||||
elif action=='vesc.bms.prepare': result.update(self.bms.prepare(device,command['parameters']))
|
||||
else: result.update(self.bms.apply(device,command['parameters'],command['operation_id']))
|
||||
elif action in FIRMWARE_ACTIONS:
|
||||
if action == 'vesc.firmware.apply':
|
||||
result.update(self.firmware_update.apply(device,command['parameters'],command['operation_id'],deadline))
|
||||
elif action == 'vesc.firmware.reconcile':
|
||||
result.update(self.firmware_update.reconcile(device))
|
||||
else: result.update(self.firmware_update.stage(device,action,command['parameters']))
|
||||
elif action == "vesc.configuration.read":
|
||||
result["configuration"] = device.link.configuration()
|
||||
if firmware(device.link.query(0)) != actual:
|
||||
raise ValueError("Controller changed during configuration read")
|
||||
elif action == "vesc.configuration.preview":
|
||||
result.update(self.config_editor.preview(device, command["parameters"]))
|
||||
elif action == "vesc.configuration.apply":
|
||||
result.update(self.config_editor.apply(device, command["parameters"], command["operation_id"], deadline))
|
||||
elif action == "vesc.configuration.reconcile":
|
||||
result.update(self.config_editor.reconcile(device))
|
||||
elif action == "vesc.diagnostics.read":
|
||||
from .controller_diagnostics import read_diagnostics
|
||||
result.update(read_diagnostics(device))
|
||||
if firmware(device.link.query(0)) != actual:
|
||||
raise ValueError("Controller changed during diagnostic read")
|
||||
elif action == "vesc.limits.read":
|
||||
from .limits_view import read_limits
|
||||
result.update(parameters=read_limits(device.link))
|
||||
@@ -357,7 +561,11 @@ class Service:
|
||||
"type": type(error).__name__, "native_rpc": error.native_rpc,
|
||||
"native_history": getattr(error, "native_history", []),
|
||||
}}
|
||||
atomic(path, record)
|
||||
if command["action_id"] in SNAPSHOT_ACTIONS:
|
||||
self.read_cache.put(command["operation_id"], record["receipt"])
|
||||
atomic(path, {"digest": digest, "snapshot_only": True, "receipt": EXPIRED})
|
||||
else:
|
||||
atomic(path, record)
|
||||
return record["receipt"]
|
||||
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Opt-in onboard JSONL evidence. Disk never runs on the motor worker.
|
||||
|
||||
RAM is bounded; full files have no duration/size cutoff and are never rotated.
|
||||
Backpressure and I/O failures are explicit, rather than silently losing evidence.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
class SessionLog:
|
||||
SYNC_INTERVAL = 1.0
|
||||
MAX_RECORD_BYTES = 8192
|
||||
MAX_QUEUE_BYTES = 4 * 1024 * 1024
|
||||
def __init__(self,root):
|
||||
self.root=Path(root)/'Session Logs'
|
||||
self.lock=threading.RLock();self.queue=queue.Queue(maxsize=4096)
|
||||
self.path=None;self.id=None;self.thread=None
|
||||
self.error=None;self.dropped=0;self.written=0;self.closed=True;self.closing=False
|
||||
self.external_ack={}
|
||||
self.queued_bytes=0;self.drop_reasons={}
|
||||
|
||||
def start(self,identifier,vehicle,create=True,options=None):
|
||||
if not isinstance(identifier,str) or not re.fullmatch(r'[a-f0-9]{32}',identifier):raise ValueError('Invalid capture ID')
|
||||
with self.lock:
|
||||
if self.id==identifier:return # A closed capture can never reopen.
|
||||
if not self.closed:raise ValueError('Finish the current diagnostic session first')
|
||||
label=re.sub(r'[^A-Za-z0-9А-Яа-яЁё_. -]','_',str(vehicle))[:100].strip(' .') or 'Rover'
|
||||
folder=self.root/label
|
||||
if create:folder.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
if folder.is_symlink():raise ValueError('Invalid log directory')
|
||||
prior=list(folder.glob('*_'+identifier+'.jsonl'))
|
||||
self.id=identifier;self.external_ack={};self.dropped=self.written=0
|
||||
self.path=None;self.error=None;self.closed=True;self.closing=False
|
||||
if prior:
|
||||
self.path=prior[0];self.error='CaptureInterrupted'
|
||||
# Inspect only a bounded tail. Never append, repair or scan an hour-long file.
|
||||
with self.path.open('rb') as stream:
|
||||
stream.seek(max(0,self.path.stat().st_size-16384));tail=stream.read(16384)
|
||||
try:
|
||||
end=json.loads(tail.splitlines()[-1]) if tail.endswith(b'\n') else {}
|
||||
if end.get('type')=='session_end':
|
||||
self.written=int(end['written_records']);self.dropped=int(end['dropped_records']);self.error=None
|
||||
except (ValueError,KeyError,IndexError,TypeError):pass
|
||||
return
|
||||
if not create:self.error='CaptureNotFound';return
|
||||
stamp=datetime.now(timezone.utc).strftime('%Y-%m-%d_%H-%M-%S_UTC')
|
||||
self.path=folder/(stamp+'_'+identifier+'.jsonl')
|
||||
fd=os.open(self.path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600)
|
||||
self.file=os.fdopen(fd,'wb',buffering=65536)
|
||||
self.error=None;self.closed=False;self.closing=False
|
||||
self.queue=queue.Queue(maxsize=4096)
|
||||
self.queued_bytes=0;self.drop_reasons={}
|
||||
self.file.write((json.dumps({'type':'manifest','schema':'missioncore.rover-session/v1',
|
||||
'capture_id':identifier,'options':options,'vehicle':str(vehicle)[:128],'started_at':datetime.now(timezone.utc).isoformat(),
|
||||
'clock_note':'UTC and monotonic clocks are per source; receive order is not synchronized measurement.'},ensure_ascii=False)+'\n').encode())
|
||||
self.file.flush();os.fsync(self.file.fileno())
|
||||
self.thread=threading.Thread(target=self._write,daemon=True,name='vesc-session-log');self.thread.start()
|
||||
|
||||
def append(self,row):
|
||||
with self.lock:
|
||||
if self.closed or self.closing or self.error:return False
|
||||
try:raw=(json.dumps(row,ensure_ascii=False,allow_nan=False,separators=(',',':'))+'\n').encode()
|
||||
except (ValueError,TypeError):
|
||||
self._drop('invalid_record');return False
|
||||
if len(raw)>self.MAX_RECORD_BYTES:
|
||||
self._drop('record_too_large');return False
|
||||
if self.queued_bytes+len(raw)>self.MAX_QUEUE_BYTES or self.queue.full():
|
||||
self._drop('queue_full');return False
|
||||
try:self.queue.put_nowait(raw)
|
||||
except queue.Full:self._drop('queue_full');return False
|
||||
self.queued_bytes+=len(raw)
|
||||
return True
|
||||
|
||||
def _drop(self,reason):
|
||||
self.dropped+=1;self.drop_reasons[reason]=self.drop_reasons.get(reason,0)+1
|
||||
|
||||
def _write(self):
|
||||
last_sync=time.monotonic();dirty=False
|
||||
try:
|
||||
while True:
|
||||
# Finish is an out-of-band signal, so a full data queue cannot
|
||||
# lose it. Every accepted record drains before the footer.
|
||||
with self.lock:
|
||||
if self.closing and self.queue.empty():break
|
||||
try:row=self.queue.get(timeout=.5)
|
||||
except queue.Empty:
|
||||
if dirty and time.monotonic()-last_sync>=self.SYNC_INTERVAL:
|
||||
self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False
|
||||
continue
|
||||
if isinstance(row,threading.Event):
|
||||
self.file.flush();row.set();continue
|
||||
with self.lock:self.queued_bytes-=len(row)
|
||||
self.file.write(row)
|
||||
self.written+=1;dirty=True
|
||||
if time.monotonic()-last_sync>=self.SYNC_INTERVAL:
|
||||
self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False
|
||||
self.file.write((json.dumps({'type':'session_end','at_utc':datetime.now(timezone.utc).isoformat(),
|
||||
'written_records':self.written,'dropped_records':self.dropped,'drop_reasons':self.drop_reasons})+'\n').encode())
|
||||
self.file.flush();os.fsync(self.file.fileno())
|
||||
except (OSError,ValueError,TypeError) as error:self.error=type(error).__name__
|
||||
finally:
|
||||
try:self.file.close()
|
||||
except OSError as error:self.error=type(error).__name__
|
||||
finally:self.closed=True
|
||||
|
||||
def finish(self):
|
||||
with self.lock:
|
||||
if self.closed or self.closing:return
|
||||
self.closing=True
|
||||
# Completion is polled. Never hold a request or a motor worker for disk.
|
||||
|
||||
def external(self,origin,rows):
|
||||
if not isinstance(rows,list) or len(rows)>64:raise ValueError('Invalid external trace')
|
||||
for row in rows:
|
||||
if not isinstance(row,dict) or type(row.get('record_sequence')) is not int:continue
|
||||
seq=row['record_sequence'];previous=self.external_ack.get(origin,0)
|
||||
if seq<=previous:continue
|
||||
if len(json.dumps(row))>8192:continue
|
||||
if seq>previous+1 and origin=='core':
|
||||
if not self.append({'source':'recorder','event':'transport_gap','origin':origin,'after':previous,'before':seq}):break
|
||||
if not self.append(row):break
|
||||
self.external_ack[origin]=seq
|
||||
|
||||
def status(self):
|
||||
return {'file':str(self.path.relative_to(self.root)) if self.path else None,
|
||||
'closed':self.closed,'error':self.error,'written':self.written,'dropped':self.dropped,
|
||||
'external_ack':dict(self.external_ack),'queued_bytes':self.queued_bytes,
|
||||
'queued_records':self.queue.qsize(),'drop_reasons':dict(self.drop_reasons)}
|
||||
|
||||
def chunk(self,identifier,offset,total=None,*,limit=4096,snapshot=None):
|
||||
if identifier!=self.id or self.path is None:raise ValueError('Unknown session log')
|
||||
if type(limit) is not int or not 1<=limit<=65536:raise ValueError('Invalid export block size')
|
||||
if type(offset) is not int or offset<0:raise ValueError('Invalid file offset')
|
||||
if self.closing and not self.closed:
|
||||
self.thread.join(1)
|
||||
if not self.closed:raise OSError("Writer is closing")
|
||||
if total is None and not self.closed:
|
||||
flushed=threading.Event()
|
||||
self.queue.put(flushed,timeout=1)
|
||||
if not flushed.wait(1):raise OSError('Writer flush timed out')
|
||||
size=self.path.stat().st_size
|
||||
if total is None:total=size
|
||||
if type(total) is not int or not 0<=offset<=total<=size:raise ValueError('Invalid export snapshot')
|
||||
with self.path.open('rb') as stream:
|
||||
stat=os.fstat(stream.fileno())
|
||||
prefix=stream.read(min(4096,total))
|
||||
identity=hashlib.sha256(f'{identifier}:{stat.st_dev}:{stat.st_ino}:{total}:'.encode()+prefix).hexdigest()
|
||||
if snapshot is not None and snapshot!=identity:raise ValueError('Export snapshot changed')
|
||||
stream.seek(offset);raw=stream.read(min(limit,total-offset))
|
||||
if len(raw)!=min(limit,total-offset):raise OSError('Export snapshot truncated')
|
||||
return {'capture_id':identifier,'offset':offset,'total_bytes':total,'next':offset+len(raw),
|
||||
'data':base64.b64encode(raw).decode(),'file':self.path.name,
|
||||
'snapshot':identity,'sha256':hashlib.sha256(raw).hexdigest()}
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Declared main-flash SWD jobs. Staging never connects or halts a target."""
|
||||
TARGETS=[(1,'STM32F40x',2048),(2,'NRF51822 · 128K / 16K',128),
|
||||
(3,'NRF51822 · 256K / 16K',256),(4,'NRF51822 · 256K / 32K',256),
|
||||
(5,'NRF52832 · 256K / 32K',256),(6,'NRF52832 · 256K / 64K',256),
|
||||
(7,'NRF52832 · 512K / 64K',512),(8,'NRF52840 · 1M / 256K',1024),
|
||||
(9,'STM32F30x',2048),(10,'STM32L47x',2048),(11,'STM32G43',2048),
|
||||
(12,'STM32G47',2048),(13,'STM32G49',2048)]
|
||||
|
||||
|
||||
def validate(p):
|
||||
if not isinstance(p,dict) or set(p)!={'target_code','pins','address','flash_bytes'}:
|
||||
raise ValueError('Exact SWD target, pins and main flash range required')
|
||||
code=p['target_code']
|
||||
if type(code) is not int or not 1<=code<=13 or p['pins'] not in ('default','nrf5x'):
|
||||
raise ValueError('Unsupported SWD target or pin mapping')
|
||||
base=0 if 2<=code<=8 else 0x08000000
|
||||
cap=TARGETS[code-1][2]*1024
|
||||
if (type(p['address']) is not int or type(p['flash_bytes']) is not int or p['address']<base
|
||||
or p['flash_bytes']<256 or p['address']+p['flash_bytes']>base+cap):
|
||||
raise ValueError('SWD image must remain inside declared main flash')
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Physical transports and stable controller projections; no movement commands."""
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import copy
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .can_bridge import Attachment as CanAttachment
|
||||
from .can_bridge import inventory
|
||||
from .configuration import decode
|
||||
from .serial import device_id
|
||||
|
||||
BAUD = (125000, 250000, 500000, 1000000, 10000, 20000, 50000, 75000, 100000)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Missing:
|
||||
uuid: str
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return device_id("uuid:" + self.uuid)
|
||||
|
||||
@property
|
||||
def binding(self):
|
||||
return "missing:" + self.uuid
|
||||
|
||||
usb = "—"
|
||||
address = "unavailable"
|
||||
tty = "unavailable"
|
||||
speed = "—"
|
||||
|
||||
|
||||
class TransportHub:
|
||||
def __init__(self, service, atomic, can_inventory=None):
|
||||
self.s, self.atomic = service, atomic
|
||||
self.fetch = can_inventory or (
|
||||
inventory
|
||||
if getattr(service.link_factory, "__name__", "") == "NativeLink"
|
||||
else lambda: []
|
||||
)
|
||||
self.pool = service.devices
|
||||
self.missing = {}
|
||||
self.adapters = []
|
||||
self.hint_retry = {}
|
||||
self.path = service.root / "controller-identities.json"
|
||||
self.known = json.loads(self.path.read_text()) if self.path.exists() else {}
|
||||
# Reuse verified immutable backups to find a previously USB-connected VESC.
|
||||
for binding in service.drive.value["bindings"].values():
|
||||
identifier = binding["device_id"]
|
||||
if identifier in self.known:
|
||||
continue
|
||||
records = service.archive.listing("local", identifier)["items"]
|
||||
if not records:
|
||||
continue
|
||||
document = service.archive.read("local", identifier, records[0]["id"])
|
||||
try:
|
||||
config = decode(
|
||||
base64.b64decode(document["configs"]["application"]["payload"]), "application"
|
||||
)
|
||||
self.remember(document["identity"], config)
|
||||
except (KeyError, ValueError, IndexError):
|
||||
pass
|
||||
|
||||
def remember(self, identity, config=None):
|
||||
identifier = device_id("uuid:" + identity["uuid"])
|
||||
value = {**self.known.get(identifier, {}), "identity": copy.deepcopy(identity)}
|
||||
if config is not None:
|
||||
value.update(
|
||||
can_id=int(config["controller_id"]), bitrate=BAUD[int(config["can_baud_rate"])]
|
||||
)
|
||||
if self.known.get(identifier) != value:
|
||||
self.known[identifier] = value
|
||||
self.atomic(self.path, self.known)
|
||||
|
||||
@staticmethod
|
||||
def route(device):
|
||||
a = device.attachment
|
||||
if isinstance(a, CanAttachment):
|
||||
return a.route
|
||||
return {"kind": "usb", "uuid": device.identity["uuid"]} if device.identity else None
|
||||
|
||||
def endpoints(self):
|
||||
return [
|
||||
{
|
||||
"device_id": d.id,
|
||||
"attachment_id": d.attachment.id,
|
||||
"uuid": d.identity["uuid"],
|
||||
"route": self.route(d),
|
||||
"verified": bool(
|
||||
d.link and getattr(d.link, "alive", True) and d.identified_session == d.session
|
||||
),
|
||||
"session_id": d.session,
|
||||
}
|
||||
for d in list(self.pool.values())
|
||||
if d.identity
|
||||
]
|
||||
|
||||
def select(self):
|
||||
s = self.s
|
||||
profile = s.transport.snapshot(s.drive.value, self.endpoints())
|
||||
assigned = {b["device_id"]: b for b in s.drive.value["bindings"].values()}
|
||||
chosen = {
|
||||
k: d
|
||||
for k, d in self.pool.items()
|
||||
if d.id not in assigned and not isinstance(d.attachment, CanAttachment)
|
||||
}
|
||||
for identifier, binding in assigned.items():
|
||||
matches = [
|
||||
(k, d)
|
||||
for k, d in self.pool.items()
|
||||
if d.id == identifier and self.route(d) == profile["routes"].get(identifier)
|
||||
]
|
||||
if matches:
|
||||
chosen.update(matches)
|
||||
else:
|
||||
if identifier not in self.missing:
|
||||
d = self.s.device_type(Missing(binding["uuid"]))
|
||||
d.identity = copy.deepcopy(self.known.get(identifier, {}).get("identity"))
|
||||
d.id = identifier
|
||||
d.error = "Выбранное подключение недоступно."
|
||||
self.missing[identifier] = d
|
||||
chosen[self.missing[identifier].attachment.binding] = self.missing[identifier]
|
||||
with s.lock:
|
||||
s.devices = {k: chosen[k] for k in self.pool if k in chosen}
|
||||
s.devices.update({k: d for k, d in chosen.items() if k not in self.pool})
|
||||
|
||||
def scan(self):
|
||||
s = self.s
|
||||
usb = {a.binding: a for a in s.discover_fn()}
|
||||
try:
|
||||
self.adapters = self.fetch()
|
||||
except (OSError, ValueError, KeyError):
|
||||
self.adapters = []
|
||||
wanted = dict(usb)
|
||||
bindings = s.drive.value["bindings"]
|
||||
explicit = s.transport.value["routes"]
|
||||
from .control_transport import BITRATES
|
||||
|
||||
for i, b in enumerate(bindings.values()):
|
||||
known = self.known.get(b["device_id"], {})
|
||||
route = explicit.get(b["device_id"], {})
|
||||
for adapter in self.adapters:
|
||||
candidates = []
|
||||
if route.get("kind") == "can" and route["adapter_id"] == adapter["id"]:
|
||||
candidates.append((route["channel"], route["can_id"], route["bitrate"]))
|
||||
elif "can_id" in known and known["bitrate"] in BITRATES:
|
||||
candidates.extend(
|
||||
(ch, known["can_id"], known["bitrate"]) for ch in range(adapter["channels"])
|
||||
)
|
||||
for ch, target, bitrate in candidates:
|
||||
sender = 254 - i
|
||||
if sender == target:
|
||||
sender = 245 - i
|
||||
a = CanAttachment(
|
||||
adapter["id"], adapter["session_id"], ch, target, bitrate, sender, b["uuid"]
|
||||
)
|
||||
wanted[a.binding] = a
|
||||
removed = [
|
||||
self.pool.pop(k) for k, d in list(self.pool.items()) if wanted.get(k) != d.attachment
|
||||
]
|
||||
for key, a in wanted.items():
|
||||
if key not in self.pool:
|
||||
d = s.device_type(a)
|
||||
if isinstance(a, CanAttachment):
|
||||
d.identity = copy.deepcopy(self.known.get(a.id, {}).get("identity"))
|
||||
self.pool[key] = d
|
||||
self.select() # Invalidate old generations before waiting on a hardware lock.
|
||||
for d in removed:
|
||||
d.close()
|
||||
owned = s.operation_lock.acquire(False)
|
||||
if not owned:
|
||||
return
|
||||
try:
|
||||
can_attempted = False
|
||||
for d in list(self.pool.values()):
|
||||
if d.link and not getattr(d.link, "alive", True):
|
||||
with d.lock:
|
||||
error = (d.link.failure_error() if hasattr(d.link, "failure_error")
|
||||
else OSError("Native transport exited"))
|
||||
d.failed(error, "connection-exit")
|
||||
if d.link is None and time.monotonic() >= d.retry_at:
|
||||
is_can = isinstance(d.attachment, CanAttachment)
|
||||
if is_can and can_attempted:
|
||||
continue
|
||||
can_attempted |= is_can
|
||||
d.connect(s.link_factory)
|
||||
if d.identity and d.link:
|
||||
self.remember(d.identity)
|
||||
if (
|
||||
self.adapters
|
||||
and d.id in {b["device_id"] for b in bindings.values()}
|
||||
and not isinstance(d.attachment, CanAttachment)
|
||||
and d.identity["version"] == "5.02"
|
||||
and time.monotonic() >= self.hint_retry.get(d.session, 0)
|
||||
):
|
||||
self.hint_retry = {
|
||||
d.session: time.monotonic() + 60,
|
||||
**{k: v for k, v in self.hint_retry.items() if v > time.monotonic()},
|
||||
}
|
||||
with d.lock, contextlib.suppress(OSError, ValueError, KeyError, IndexError):
|
||||
self.remember(d.identity, decode(d.link.query(17), "application"))
|
||||
self.select()
|
||||
finally:
|
||||
s.operation_lock.release()
|
||||
|
||||
def profile(self):
|
||||
return self.s.transport.snapshot(self.s.drive.value, self.endpoints())
|
||||
|
||||
def assert_devices(self, devices, pinned):
|
||||
if pinned is not None:
|
||||
self.s.transport.assert_pinned(pinned, self.s.drive.value, self.endpoints())
|
||||
usb = set(self.s.discover_fn())
|
||||
if all(not isinstance(d.attachment, CanAttachment) for d in devices) and usb != {
|
||||
d.attachment for d in devices
|
||||
}:
|
||||
raise ValueError("Состав USB-контроллеров изменился.")
|
||||
for d in devices:
|
||||
if not d.link:
|
||||
raise ValueError("Выбранное подключение недоступно.")
|
||||
if isinstance(d.attachment, CanAttachment):
|
||||
d.link.check()
|
||||
elif d.attachment not in usb:
|
||||
raise ValueError("Подключение USB изменилось.")
|
||||
Reference in New Issue
Block a user