From 8b210258ca74ee5d7221791aef97c03f85d68c2a Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:09:59 +0300 Subject: [PATCH] feat(usb-can): add isolated adapter runtime and confirmed CAN transactions Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware. --- docs/node/35_USB_CAN_ADAPTER.md | 143 +++++++ plugins/usb-can/README.md | 68 +++ plugins/usb-can/frontend/src/CanChannel.tsx | 57 +++ plugins/usb-can/frontend/src/CanDetail.tsx | 114 +++++ plugins/usb-can/frontend/src/CanTransmit.tsx | 60 +++ plugins/usb-can/frontend/src/model.ts | 29 ++ plugins/usb-can/frontend/src/plugin.ts | 8 + plugins/usb-can/frontend/src/usb-can.css | 3 + .../packaging/70-mission-core-usb-can.rules | 2 + plugins/usb-can/packaging/fetch_sdk.py | 39 ++ .../mission-core-node-usb-can-prepare.service | 7 + .../packaging/mission-core-usb-can.service | 38 ++ plugins/usb-can/packaging/native_check.py | 17 + plugins/usb-can/packaging/payload.py | 50 +++ plugins/usb-can/packaging/prepare.py | 158 +++++++ plugins/usb-can/packaging/sdk-lock.json | 16 + plugins/usb-can/runtime/__init__.py | 3 + plugins/usb-can/runtime/bridge.py | 256 ++++++++++++ plugins/usb-can/runtime/confirmed_tx.py | 71 ++++ plugins/usb-can/runtime/contracts.py | 118 ++++++ plugins/usb-can/runtime/discovery.py | 49 +++ plugins/usb-can/runtime/sdk.py | 294 +++++++++++++ plugins/usb-can/runtime/server.py | 198 +++++++++ plugins/usb-can/runtime/service.py | 389 ++++++++++++++++++ plugins/usb-can/runtime/worker.py | 266 ++++++++++++ plugins/usb-can/tests/test_bridge.py | 150 +++++++ .../tests/test_configuration_transport.py | 138 +++++++ plugins/usb-can/tests/test_confirmed_tx.py | 107 +++++ .../usb-can/tests/test_limits_transport.py | 171 ++++++++ plugins/usb-can/tests/test_runtime.py | 317 ++++++++++++++ 30 files changed, 3336 insertions(+) create mode 100644 docs/node/35_USB_CAN_ADAPTER.md create mode 100644 plugins/usb-can/README.md create mode 100644 plugins/usb-can/frontend/src/CanChannel.tsx create mode 100644 plugins/usb-can/frontend/src/CanDetail.tsx create mode 100644 plugins/usb-can/frontend/src/CanTransmit.tsx create mode 100644 plugins/usb-can/frontend/src/model.ts create mode 100644 plugins/usb-can/frontend/src/plugin.ts create mode 100644 plugins/usb-can/frontend/src/usb-can.css create mode 100644 plugins/usb-can/packaging/70-mission-core-usb-can.rules create mode 100644 plugins/usb-can/packaging/fetch_sdk.py create mode 100644 plugins/usb-can/packaging/mission-core-node-usb-can-prepare.service create mode 100644 plugins/usb-can/packaging/mission-core-usb-can.service create mode 100644 plugins/usb-can/packaging/native_check.py create mode 100644 plugins/usb-can/packaging/payload.py create mode 100644 plugins/usb-can/packaging/prepare.py create mode 100644 plugins/usb-can/packaging/sdk-lock.json create mode 100644 plugins/usb-can/runtime/__init__.py create mode 100644 plugins/usb-can/runtime/bridge.py create mode 100644 plugins/usb-can/runtime/confirmed_tx.py create mode 100644 plugins/usb-can/runtime/contracts.py create mode 100644 plugins/usb-can/runtime/discovery.py create mode 100644 plugins/usb-can/runtime/sdk.py create mode 100644 plugins/usb-can/runtime/server.py create mode 100644 plugins/usb-can/runtime/service.py create mode 100644 plugins/usb-can/runtime/worker.py create mode 100644 plugins/usb-can/tests/test_bridge.py create mode 100644 plugins/usb-can/tests/test_configuration_transport.py create mode 100644 plugins/usb-can/tests/test_confirmed_tx.py create mode 100644 plugins/usb-can/tests/test_limits_transport.py create mode 100644 plugins/usb-can/tests/test_runtime.py diff --git a/docs/node/35_USB_CAN_ADAPTER.md b/docs/node/35_USB_CAN_ADAPTER.md new file mode 100644 index 00000000..19346540 --- /dev/null +++ b/docs/node/35_USB_CAN_ADAPTER.md @@ -0,0 +1,143 @@ +# USB-CAN-FD-B — интеграция и журнал установки + +## Задача и границы проверки +2026-10-21 владелец поручил автоматически обнаруживать Waveshare USB-CAN-FD-B, +показывать адаптер в оборудовании Node и Core, перенести инструменты адаптера в +общую модалку и включить всё необходимое в стандартную установку Ubuntu. +Силовое питание VESC и их прямые USB отключены. Разрешена проверка USB-идентификации +адаптера, интерфейса и установки. Запуск CAN-каналов, отправка кадров, моторы, +новые захваты, логирование и перепрошивки не выполняются. + +## Размещение и API +Реализация: `plugins/usb-can`; существующий equipment extension slot в Node/Core. +Используется официальная userspace-библиотека Waveshare, закреплённая SHA256 +в `packaging/sdk-lock.json`. Это бинарная библиотека производителя, не open source. +Исходный открытый ZCAN_USB рассмотрен; его заявленные ограничения FD/BRS +не подходят для полного набора режимов адаптера. + +- [Документация Waveshare](https://www.waveshare.com/wiki/USB-CAN-FD) +- [API V1.3](https://files.waveshare.com/wiki/USB-CAN-FD/Manual/USB-CAN-FD-B-API-Manual.pdf) +- [Linux SDK](https://files.waveshare.com/wiki/USB-CAN-FD/USB-CAN-FD-B-Linux.zip) +- [Рассмотренный открытый драйвер](https://github.com/roema/ZCAN_USB) + +VID:PID 04d8:0053 и точная USB product string USB CANFD DEBUG определяют модель. +USB serial descriptor подключённого экземпляра некорректен; устойчивый ID строится +по серийному номеру, прочитанному через протокол. SDK выбирает устройства индексом; +перед назначением сеанса проверяется, какой USB-дескриптор он фактически открыл. +Неоднозначный или дублирующийся серийный номер блокирует операции. + +Каждый подключённый экземпляр имеет один ограниченный worker. Повторное обнаружение +идёт с задержкой до 60 секунд; зависший worker завершается, старый сеанс становится +недействительным. Настройки сохраняются, CAN-каналы и задания не возобновляются. + +## Функциональность +| Возможность | Реализация | Проверка на CAN-шине | +|---|---|---| +| USB обнаружение, идентификация, версии, два канала | SDK + Node/Core inventory | Не требует запуска шины | +| CAN/CAN FD, стандартные arbitration/data bitrates, ISO/Bosch | Настройки отдельного канала | Не проводилась | +| Listen-only / normal, start / stop/reset | Отдельное явное действие | Не проводилась | +| Диапазоны фильтрации 11/29 бит | До 64 стандартных / 32 расширенных | Не проводилась | +| RX, timestamps, RTR/BRS/ESI/error flags, счётчики | Ограниченная память, монитор | Не проводилась | +| TX classic/FD, 4 режима, повторы/интервал/инкременты | Предпросмотр, одноразовое подтверждение; до 1000 кадров/60 с | Не проводилась | +| Отмена задания, очистка буферов | Операции канала | Синтетический transport | +| Импорт/экспорт конфигурации и очереди; CSV/TXT кадров | JSON validation, файлы по действию пользователя | Не требует шины | +| DIP 120 Ω | Инструкция в UI, физические переключатели | Положение не считывается API | +| TEC/REC, bus-off, прошивка самого адаптера | Нет соответствующих функций в закреплённом Linux SDK | Недоступно | +| Произвольные bit timing / SetBaudRateCustom | Не опубликовано в UI: формат строки отсутствует в таблице API и примере | Не проверено | + +Это интеграция адаптера; она сама по себе не переводит существующий VESC transport +на CAN и не подтверждает полярность проводов, терминацию или движение моторов. + +## Воспроизводимость и хранение +Node package включает runtime, закреплённую библиотеку, systemd unit, udev rule, +native ABI check, fixed preparation unit и polkit grant для этой подготовки. +Никакие пакеты, правила доступа или библиотеки на борту вручную не устанавливаются. +Профиль Ubuntu 24.04 amd64; требуемые libc/libstdc++/libgcc уже входят в Depends. +Первая установка и hotplug обнаруживают адаптер без старта CAN. +Удаление/понижение удаляет только принадлежащее профилю неизменённое udev-правило. +Начиная с Node 0.8.49-43 штатный owner installer завершает пассивное наблюдение +через [режим обслуживания CAN](37_CAN_INSTALLER_MAINTENANCE.md), без отключения USB. +Активное управление, изменение устройства и самостоятельная передача кадров +блокируют обновление; установщик не отменяет их принудительно. + +Raw CAN frames остаются в RAM: worker 2000 кадров/5 минут, snapshot максимум256, +UI1000/5 минут. Очередь и receipts ограничены; Node/Core не сохраняют raw CAN +operation results на диск. Ежедневный reset; экспорт только по действию пользователя. +Установка на новый образ Ubuntu в этом проходе не тестируется. + +## Квалификация до установки +- 17 синтетических Python-тестов нового runtime прошли; аппаратный SDK ими не открывается. +- Ruff нового plugin и TypeScript Core прошли. +- Исходный архив 5612deeeeb45a75095ac25d5: Node/SDK ABI/unit tests прошли, + Core остановлен проверкой registry pin существующего пакета NVIDIA. +- Архив fcc8ba4f387e0457dbb2a928: Node/SDK прошли; Core1279/1283, + 3 ошибки,1 существующий пропуск. Причины: не применён штатный native Rerun + installer перед ABI tests; старый снимок simulationLayout с downlevel Set spread. + Текущий канонический simulationLayout уже использует Array.from; его отдельный + тест проходит без изменения этого файла в данной задаче. +- 9f0dc7947992b336be1b90b2: подготовленный Node-only вход не запускался, + заменён общей квалификацией. +- 7676ed18c1eba13f14749efd: окончательный кандидат; разрешён ровно pinned + NVIDIA dependency, native Rerun installer запускается до тестов, verify после + подготовки допускает исходный 350-секундный deadline Node. CAN actions остаются + ограничены60секундами. Результат и установка дописываются после подтверждения. + +Свидетельства неудач сохранены в `outputs/usb-can-20261021`. +Временные каталоги первых двух сборок очищены штатным --clean. + +## Принятый выпуск — 2026-10-21 13:18 UTC +- Node **0.8.49-33**, USB-CAN plugin **0.1.0**, прежний VESC0.18.0 и X4.16. +- 30 Ubuntu qualification jobs завершены; Core1282 tests passed,1 existing + Python/Rerun fixture test explicitly skipped. Новый runtime17 synthetic tests passed. +- Node .deb SHA256 `114e6ed0502bb23a611927444ff1a120e9e8eada93b87c1e9224829669a0eeb4`. +- Owner release `0cc1d83de91fc0bcbe47af03`, SHA256 + `8d01e4caa1a22f73e512e379faef6555c76979999ec98f63396db9b271ef69c5`. +- APT plan: один upgrade Node32→33,0 новых пакетов,0 удалений. + Fixed installer run `cbc2f7f9822a45e1824e8bd7f95918ab` завершён, + 13:13:27–13:13:47 UTC; Node UI ready, службы active, NRestarts0. +- Начальный USB-CAN profile run `96493527556a437aa8ed941e4b1b9ff0` complete: + own account, native ABI, udev, enable/start. +- В Core опубликован owner installer Node0.8.49-33 с проверенным SHA. +- Ubuntu Core dist также квалифицирован: SHA256 + `573d0b3d533dc8aeb8d818ba99c75d78b82ff56e79708101597fc2694a941e80`. + Его **не наложили поверх более нового канонического dist** от13:05 UTC. + В общей рабочей папке параллельно обновился AiEditorRuntime.ts; готовый dist + уже содержит этот USB-CAN plugin. Все исходники plugin совпали с квалифицированным + снимком. Сохранён более новый интерфейс; его bundle SHA и фактическая UI-приёмка + записаны в `core-ui-acceptance.json`. Core на127.0.0.1:8000, PID69511, + уже загрузил новый backend; дополнительный перезапуск не требовался. + +### Подтверждено на подключённой коробке +| Поле | Прочитанное значение | +|---|---| +| Модель корпуса | Waveshare USB-CAN-FD-B | +| Серийный номер протокола | USBCANFD212606183013 | +| Аппаратная версия | 2.00 | +| Прошивка | 2.13 | +| Драйвер / интерфейс | 1.21 / 1.03 | +| Тип протокола | USBCANFD | +| Каналы | 2 | +| USB | 480Мбит/с, текущий порт1-2 | +| Устойчивый ID | usbcan_c5677e29538e491d31ae9f3ce1e3256e | + +Автоматическое обнаружение прошло без отдельной кнопки добавления. +В Core открыты идентификация, CAN1/CAN2, передача и диагностика; проверены +поля FD в несохранённом черновике. Штатный can.status успешно завершился через +Core→Node→driver. Повторный prepare из модалки: +`op_b25da44382474ff0b81b57136dded3d1` complete с тем же device_id; +350-секундный deadline принят. Новый profile run +`b603d01e67334f5abe7f8a74b1344700` complete; служба active,NRestarts0. +После перезапуска один адаптер, новый session_id, оба канала stopped, +listen-only,revision0, RX0/TX0,transmission=null. +Полярность, терминация, реальный приём/передача и физическое переставление USB +не тестировались. Ничего не запускалось на VESC/моторах. + +### Свидетельства и хранение +`outputs/usb-can-20261021/core-acceptance.json`, +`profile-acceptance.json`, `owner-release.json`, `core-ui-acceptance.json`. +Квалифицированные файлы: +`apps/node-agent/build/qualified-usb-can-33-20261021/`. +Успешный source input закреплён как qualified; baseline сохранён по зависимости. +Дублирующий result.tar.gz после проверки распакованных hashes удалён. +Retention plan проверен; чужой исторический intermediate candidate не удалялся. +Удалены собственные временные build directories на Ubuntu через штатный --clean. diff --git a/plugins/usb-can/README.md b/plugins/usb-can/README.md new file mode 100644 index 00000000..0102433d --- /dev/null +++ b/plugins/usb-can/README.md @@ -0,0 +1,68 @@ +# USB-CAN-FD-B integration + +## Scope and placement +The operator connects any supported USB-CAN-FD-B instance to an onboard Linux host. +The device appears beneath that host through the existing sensor inventory and opens +one equipment settings modal in both Node UI and Core. This is class A domain content +in the admitted equipment plugin slot. A separate workspace/root was rejected because +identity, settings and tools belong to the selected physical adapter. + +Reuse FeatureSettingsWindow, SettingsCard, ResourceList/ResourceRow, Description, +TextField/TextAreaField, InspectorSelectField, Switch, Button, StatusBadge and the +network icon from NODEDC_DESIGN_GUIDELINE. Both scrollports belong to the shared +settings window. The product contains no development roadmap or synthetic live data. + +## Backend decision +Official SDK: https://www.waveshare.com/wiki/USB-CAN-FD +API: https://files.waveshare.com/wiki/USB-CAN-FD/Manual/USB-CAN-FD-B-API-Manual.pdf +Linux bundle: https://files.waveshare.com/wiki/USB-CAN-FD/USB-CAN-FD-B-Linux.zip + +The official userspace library supports the device's classic CAN and FD data phase, +ISO/Bosch variants and hardware filters without installing an out-of-tree kernel module. +It is a vendor binary, not an open-source driver. Pin its hash and ABI in sdk-lock.json; +upgrades require backend contract tests and explicit hardware qualification. + +Compared: https://github.com/roema/ZCAN_USB (GPL-2.0). Its documented FD implementation +requires equal arbitration/data rates; real BRS is unverified. It is not the chosen +runtime. A generic ZLG header contains unrelated LIN/cloud structures which do not +establish support in this two-channel adapter. + +## Required contract +- USB VID/PID 04d8:0053 + exact USB product USB CANFD DEBUG; no fixed USB port. +- Read protocol identity, not the malformed/nonunique USB serial descriptor. +- Multiple adapters require independent identity, session and transport ownership. +- Discovery opens no CAN channel. Disconnect/reconnect stops active operations; never + replay transmission or silently start a bus after hotplug or a service restart. +- Channels start stopped; listen-only is the initial configuration. +- Explicit start/stop, bitrate/data bitrate, ISO/Bosch, classic/FD, receive filters, + frame monitoring, bounded manual/timed transmit, clear/export/import and diagnostics. +- Hardware termination is controlled by physical DIP switches only. Do not expose + ZCAN_SetResistanceEnable as an effective software switch (manual says do not use). +- Report unavailable native error counters as unavailable, never manufacture zeros. +- Persistent device configuration is bounded; received frames remain bounded RAM only. +- SDK, access rules, service, dependency checks and rollback belong to the versioned + Node installer/preparation workflow from the first hardware use. +- Tests use fake transport and disconnected buses. No motor, calibration, firmware, + acquisition or logging operation is authorized by implementation acceptance. + +## Physical bench state, 2026-10-21 +Owner connected left VESC to CAN1 and right VESC to CAN2, black to H and white to L. +This polarity remains unverified. Both VESC battery and direct USB supplies are off. +Both channels measured 217 ohms with all four DIP switches OFF. +One onboard 120-ohm termination produced 78 ohms; two produced 48 ohms. +USB adapter only is powered by the independently powered onboard computer. +USB enumeration is proven; CAN communication, polarity and termination acceptance +are not yet proven. + + +## API coverage and explicit limits +The pinned Linux ABI exposes 25 functions. Device lifecycle/identity/online status, +channel init/start/reset, receive counts/receive/clear, classic and FD transmit, +standard arbitration/data rates, ISO/Bosch and range filters have application paths. +GetIProperty/ReleaseIProperty are alternative wrappers for the same settings, not +additional user tools. Hardware resistance is explicitly unsupported by the API. +Custom bit timing (SetBaudRateCustom) is not exposed: the official manual's property +table leaves its string format empty, and the Linux example supplies no working +value. Standard documented rates are available; no unvalidated native string is sent. +TEC/REC, bus-off counters and adapter firmware flashing have no callable entry in +this pinned Linux SDK. No controls pretend these capabilities exist. diff --git a/plugins/usb-can/frontend/src/CanChannel.tsx b/plugins/usb-can/frontend/src/CanChannel.tsx new file mode 100644 index 00000000..570ed967 --- /dev/null +++ b/plugins/usb-can/frontend/src/CanChannel.tsx @@ -0,0 +1,57 @@ +import {useState} from 'react'; +import {Button,Description,InspectorSelectField,ResourceList,ResourceRow,SettingsCard,TextField} from '@nodedc/ui-react'; +import {defaultConfig,hex,readFile,saveFile,validConfig,type Config,type Channel,type Run} from './model'; + +export function CanChannel({index,value,revision,run,disabled}:{index:number;value?:Channel;revision:number;run:Run;disabled:boolean}){ + const [config,setConfig]=useState(structuredClone(value?.config??defaultConfig)); + const [format,setFormat]=useState('standard');const [start,setStart]=useState('0');const [end,setEnd]=useState('7FF'); + const [error,setError]=useState(null); + const stopped=!value?.running; + const edit=(change:Partial)=>setConfig(c=>({...c,...change})); + const options=(values:number[])=>values.map(v=>({value:String(v),label:v>=1000000?`${v/1000000} Мбит/с`:`${v/1000} кбит/с`})); + function addFilter(){ + if(!/^[0-9a-f]{1,8}$/i.test(start)||!/^[0-9a-f]{1,8}$/i.test(end)){setError('Введите ID в HEX.');return;} + const a=parseInt(start,16),b=parseInt(end,16),extended=format==='extended'; + if(a>b||b>(extended?0x1fffffff:0x7ff)||config.filters.reduce((n,f)=>n+(f.extended?2:1),extended?2:1)>64){setError('Диапазон или количество фильтров недопустимы.');return;} + edit({filters:[...config.filters,{extended,start:a,end:b}]});setError(null); + } + async function imported(file:File){ + try {const v=await readFile(file) as {schema?:string;config?:Config};if(v.schema!=='missioncore.can-channel/v1'||!validConfig(v.config))throw new Error('Неизвестный формат конфигурации.');setConfig(v.config);setError('Конфигурация загружена в форму. Проверьте и сохраните её.');} + catch(e){setError(String(e));} + } + return
+ + + + }> + Прослушивание принимает кадры без подтверждения ACK. Обычный режим участвует в обмене. Запуск канала использует сохранённые параметры ниже; подключение USB само по себе канал не запускает. +
+ edit({protocol:v})} disabled={disabled||!stopped}/> + edit({mode:v})} disabled={disabled||!stopped}/> + edit({bitrate:Number(v)})} disabled={disabled||!stopped}/> + {config.protocol==='fd'&&<> + edit({data_bitrate:Number(v)})} disabled={disabled||!stopped}/> + edit({standard:v})} disabled={disabled||!stopped}/> + } +
+
+ +
+ + setStart(e.target.value)} disabled={disabled||!stopped}/> + setEnd(e.target.value)} disabled={disabled||!stopped}/> +
+ + {config.filters.map((f,i)=>
  • edit({filters:config.filters.filter((_,j)=>i!==j)})}>Удалить}/>
  • )}
    +
    + + {error&&{error}} +
    + + +
    + {const f=e.target.files?.[0];if(f)void imported(f);e.target.value='';}}/> + Импорт заполняет форму. Он не запускает канал и не отправляет кадры. +
    +
    ; +} diff --git a/plugins/usb-can/frontend/src/CanDetail.tsx b/plugins/usb-can/frontend/src/CanDetail.tsx new file mode 100644 index 00000000..7fa35baf --- /dev/null +++ b/plugins/usb-can/frontend/src/CanDetail.tsx @@ -0,0 +1,114 @@ +import {useEffect,useRef,useState} from 'react'; +import {Button,ComparisonTable,Description,FeatureSettingsWindow,InspectorSelectField,ResourceList,ResourceRow,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {perform} from '../../../../packages/sensor-ui/src/contracts'; +import {SensorGeneralSettings} from '../../../../packages/sensor-ui/src/SensorGeneralSettings'; +import {CanChannel} from './CanChannel'; +import {CanTransmit} from './CanTransmit'; +import {hex,saveFile,type Frame,type Status} from './model'; +import './usb-can.css'; + +const sections=[{id:'general',label:'Общие данные',group:'Устройство'}, + {id:'identity',label:'Адаптер и подключение',group:'Устройство'}, + {id:'can1',label:'CAN1',group:'Каналы'},{id:'can2',label:'CAN2',group:'Каналы'}, + {id:'monitor',label:'Монитор кадров',group:'Инструменты'}, + {id:'transmit',label:'Передача кадров',group:'Инструменты'}, + {id:'diagnostics',label:'Состояние и диагностика',group:'Инструменты'}]; +export function CanDetail(props:SensorDetailProps){ + const {device,transport,enabled,back,failure,refresh}=props; + const [section,setSection]=useState('general'); + const [status,setStatus]=useState((device.can_status??{}) as unknown as Status); + const [busy,setBusy]=useState(false);const running=useRef(false);const mounted=useRef(true); + const [live,setLive]=useState(false);const [frames,setFrames]=useState([]);const cursor=useRef(0); + const [filter,setFilter]=useState('');const [direction,setDirection]=useState('all');const [display,setDisplay]=useState('hex'); + const [gap,setGap]=useState(false);const [generalBusy,setGeneralBusy]=useState(false); + const available=enabled&&device.online&&device.verified; + const session=device.snapshot.context.session_id; + useEffect(()=>{mounted.current=true;setStatus((device.can_status??{}) as unknown as Status);setFrames([]);setLive(false);cursor.current=0;return()=>{mounted.current=false;};},[session]); + async function run(action:string,params:Record={}):Promise{ + if(running.current||!available)return; + running.current=true;setBusy(true);failure(null); + try{ + const result=await perform(transport,device,action,params); + if(!mounted.current)return; + if(action!=='can.transmit.preview'){ + setStatus(result); + if(result.frames?.length){cursor.current=result.frames.at(-1)!.sequence; + setFrames(old=>[...old,...result.frames!].filter(f=>Date.now()/1000-f.observed_at<300).slice(-1000));} + if(params.after!==undefined&&result.oldest_sequence!==undefined&&Number(params.after)>0&&result.oldest_sequence>Number(params.after)+1)setGap(true); + } + if(action!=='can.status'&&action!=='can.transmit.preview')await refresh(); + return result; + }catch(e){if(mounted.current){failure(e);setLive(false);}} + finally{running.current=false;if(mounted.current)setBusy(false);} + } + useEffect(()=>{ + if(!live||section!=='monitor'||!available)return; + let active=true;let timer:ReturnType; + async function poll(){await run('can.status',{after:cursor.current});if(active)timer=setTimeout(()=>void poll(),2000);} + void poll();return()=>{active=false;clearTimeout(timer);}; + },[live,section,available,session]); + useEffect(()=>{const timer=setInterval(()=>setFrames(v=>v.filter(f=>Date.now()/1000-f.observed_at<300)),5000);return()=>clearInterval(timer);},[]); + const visible=frames.filter(f=>(direction==='all'||f.direction===direction)&&hex(f.id).includes(filter.toUpperCase())); + function exportFrames(format:'csv'|'txt'){ + const rows=visible.map(f=>[f.observed_at,f.timestamp_us??'',f.channel+1,f.direction,hex(f.id),f.extended?29:11,f.fd?'FD':'CAN',f.rtr?1:0,f.brs?1:0,f.esi?1:0,f.error?1:0,f.dlc,f.data].join(format==='csv'?';':'\t')); + saveFile('can-frames.'+format,['observed_unix;device_us;channel;direction;id_hex;id_bits;protocol;rtr;brs;esi;error;length;data_hex'.replaceAll(';',format==='csv'?';':'\t'),...rows].join('\n'),'text/plain'); + } + const identity=status.identity; + const disabled=busy||generalBusy||!available; + return ({...s,disabled:(busy||generalBusy)&&s.id!==section}))} + activeSection={section} onSectionChange={setSection} onClose={()=>{if(!busy&&!generalBusy)back();}} + headerActions={{available?'Адаптер подключён':'Нет свежей связи'}}> +
    + {status.message&&{status.message}} + {section==='general'&&} + {section==='identity'&&<> + void run('can.status')}>Обновить сведения}> + {[ + ['Модель','Waveshare USB-CAN-FD-B'],['Серийный номер',identity?.serial],['Аппаратная версия',identity?.hardware], + ['Прошивка',identity?.firmware],['Версия драйвера',identity?.driver],['Версия интерфейса',identity?.interface], + ['Тип устройства по протоколу',identity?.model],['CAN-каналы',identity?String(identity.channels):undefined],['USB',device.usb] + ].map(([title,value])=>
  • )}
    +
    + CAN1 и CAN2 — независимые шины. H подключается к CAN-H, L — к CAN-L. Цвет проводов сам по себе не определяет сигнал. Положение согласующих резисторов задаётся физическими переключателями 120 Ω на корпусе; программа не считывает и не переключает их. + После переподключения USB адаптер определяется заново по серийному номеру протокола. Сохранённые параметры доступны, каналы и отправка остаются остановленными. + + } + {(section==='can1'||section==='can2')&&} + {section==='transmit'&&} + {section==='monitor'&&<> + +
    + + + +
    +
    + setFilter(e.target.value)}/> + + +
    + На экране до 1000 кадров за последние 5 минут. Буфер адаптера в приложении — до 2000 кадров; данные хранятся в памяти. Приостановка просмотра не останавливает CAN-канал. + {gap&&Часть кадров уже вышла из ограниченного буфера. Таблица не является полной записью обмена.} + ({id:String(f.sequence),label:f.sequence,cells:[ + new Date(f.observed_at*1000).toLocaleTimeString(),`CAN${f.channel+1} · ${f.direction}`,hex(f.id), + [f.fd?'FD':'CAN',f.extended?'29 бит':'11 бит',f.rtr?'RTR':'',f.brs?'BRS':'',f.esi?'ESI':'',f.error?'Ошибка':''].filter(Boolean).join(' · '), + display==='hex'?f.data.match(/../g)?.join(' '):display==='decimal'?f.data.match(/../g)?.map(v=>parseInt(v,16)).join(' '):f.data.match(/../g)?.map(v=>{const n=parseInt(v,16);return n>=32&&n<127?String.fromCharCode(n):'·';}).join('') + ]}))}/> +
    + } + {section==='diagnostics'&&<> + void run('can.status')}>Обновить}> + ({id:label,label,cells:[0,1].map(ch=>{const c=status.channels?.[ch];return !c?'Нет сведений':i===0?(c.running?'Запущен':'Остановлен'):i===1?c.counts.rx:i===2?c.counts.tx_accepted:c.counts.errors;})}))}/> + {status.error&&{status.error}} + Счётчики TEC/REC и состояние bus-off этот Linux SDK через используемый API не предоставляет. Нулевые значения RX/TX означают только отсутствие учтённых приложением кадров. + Счётчики и буфер сбрасываются при новом USB-сеансе и ежедневно. Серийный номер адаптера не описывает подключённые VESC или моторы: их идентификация выполняется отдельным протоколом. +
    {[0,1].map(ch=>)}
    +
    + } +
    +
    ; +} diff --git a/plugins/usb-can/frontend/src/CanTransmit.tsx b/plugins/usb-can/frontend/src/CanTransmit.tsx new file mode 100644 index 00000000..3d9d6d66 --- /dev/null +++ b/plugins/usb-can/frontend/src/CanTransmit.tsx @@ -0,0 +1,60 @@ +import {useState} from 'react'; +import {Button,Description,InspectorSelectField,ResourceList,ResourceRow,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react'; +import {hex,readFile,saveFile,validPlan,type Plan,type Run,type Status} from './model'; +const empty:Plan={frames:[],repeat:1,interval_ms:100,increment_id:false,increment_data:false}; +export function CanTransmit({run,status,disabled}:{run:Run;status:Status;disabled:boolean}){ + const [channel,setChannel]=useState('0');const [id,setId]=useState('0');const [data,setData]=useState('');const [dlc,setDlc]=useState('0'); + const [format,setFormat]=useState('standard');const [protocol,setProtocol]=useState('can');const [kind,setKind]=useState('data');const [brs,setBrs]=useState('no');const [sendType,setSendType]=useState('1'); + const [plan,setPlan]=useState(empty);const [preview,setPreview]=useState<{token:string;channel:number;plan:Plan;total:number}|null>(null); + const [message,setMessage]=useState(null); + function update(p:Partial){setPlan(v=>({...v,...p}));setPreview(null);} + function add(){ + const bytes=data.replace(/\s/g,''); + if(!/^[0-9a-f]{1,8}$/i.test(id)||!/^(?:[0-9a-f]{2}){0,64}$/i.test(bytes)||plan.frames.length>=64){setMessage('Проверьте HEX ID и байты данных. До 64 кадров.');return;} + const n=parseInt(id,16),fd=protocol==='fd',rtr=kind==='remote',extended=format==='extended'; + const length=rtr?Number(dlc):bytes.length/2; + if(n>(extended?0x1fffffff:0x7ff)||length>(fd?64:8)||(fd&&rtr)||(fd&&![0,1,2,3,4,5,6,7,8,12,16,20,24,32,48,64].includes(length))){setMessage('Недопустимый ID, длина или тип кадра.');return;} + update({frames:[...plan.frames,{id:n,extended,fd,rtr,brs:fd&&brs==='yes',data:rtr?'':bytes.toUpperCase(),dlc:length,send_type:Number(sendType)}]});setMessage(null); + } + async function inspect(){const result=await run('can.transmit.preview',{channel:Number(channel),plan});if(result)setPreview(result as typeof preview);} + async function imported(file:File){try{const v=await readFile(file) as {schema?:string;plan?:Plan};if(v.schema!=='missioncore.can-transmission/v1'||!validPlan(v.plan))throw new Error('Неизвестный формат задания.');update(v.plan);setMessage('Задание импортировано. Проверьте кадры перед передачей.');}catch(e){setMessage(String(e));}} + const ch=status.channels?.[Number(channel)]; + const canSend=ch?.running&&ch.config.mode==='normal'; + return
    + +
    + {setChannel(v);setPreview(null);}}/> + + setId(e.target.value)}/> + + + {protocol==='fd'&&} + {kind==='remote'&&setDlc(e.target.value)}/>} + +
    + setData(e.target.value)} disabled={kind==='remote'} placeholder="01 02 A0 FF"/> + + {message&&{message}} + {plan.frames.map((f,i)=>
  • update({frames:plan.frames.filter((_,j)=>i!==j)})}>Удалить}/>
  • )}
    +
    + +
    + update({repeat:Number(e.target.value)})}/> + update({interval_ms:Number(e.target.value)})}/> + update({increment_id:v==='yes'})}/> + update({increment_data:v==='yes'})}/> +
    +
    + +
    + {const f=e.target.files?.[0];if(f)void imported(f);e.target.value='';}}/> + {!canSend&&Для отправки выбранный канал должен быть запущен в обычном режиме.} + {preview&& + Проверьте список выше, количество повторений и режим отправки. Отмена останавливает дальнейшую постановку кадров; уже переданный в адаптер кадр отозвать нельзя. + + } + {ch?.transmission&&Задание: {ch.transmission.state}. Принято адаптером: {ch.transmission.accepted??0} / {ch.transmission.total??'—'}. {ch.transmission.message??''}} + Принятие кадра SDK не доказывает подтверждение ACK другим узлом. Автоматической повторной отправки после ошибки приложения нет. +
    +
    ; +} diff --git a/plugins/usb-can/frontend/src/model.ts b/plugins/usb-can/frontend/src/model.ts new file mode 100644 index 00000000..85016c91 --- /dev/null +++ b/plugins/usb-can/frontend/src/model.ts @@ -0,0 +1,29 @@ +export interface Filter {extended:boolean;start:number;end:number} +export interface Config {protocol:'can'|'fd';mode:'listen'|'normal';bitrate:number;data_bitrate:number;standard:'iso'|'bosch';filters:Filter[]} +export interface Frame {sequence:number;channel:number;direction:'RX'|'TX';timestamp_us:number|null;observed_at:number;id:number;extended:boolean;fd:boolean;rtr:boolean;brs:boolean;esi?:boolean;error?:boolean;data:string;dlc:number;send_type:number} +export interface Plan {frames:Omit[];repeat:number;interval_ms:number;increment_id:boolean;increment_data:boolean} +export interface Channel {index:number;config:Config;running:boolean;counts:{rx:number;tx_accepted:number;errors:number};transmission:{state:string;accepted?:number;total?:number;message?:string}|null} +export interface Status {identity?:{serial:string;model:string;channels:number;hardware:string;firmware:string;driver:string;interface:string};revision:number;channels?:Channel[];frames?:Frame[];sequence:number;oldest_sequence?:number;evicted?:number;error?:string|null;message?:string|null;session_id?:string} +export type Run=(action:string,params?:Record)=>Promise; +export const defaultConfig:Config={protocol:'can',mode:'listen',bitrate:500000,data_bitrate:2000000,standard:'iso',filters:[]}; +export function hex(value:number){return value.toString(16).toUpperCase();} +export function saveFile(name:string,data:string,type='application/json'){ + const url=URL.createObjectURL(new Blob([data],{type}));const link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); +} +export async function readFile(file:File){ + if(file.size>65536)throw new Error('Файл больше 64 КБ.');return JSON.parse(await file.text()) as unknown; +} + +export function validConfig(value:unknown):value is Config{ + if(!value||typeof value!=='object')return false; + const v=value as Config; + return ['can','fd'].includes(v.protocol)&&['listen','normal'].includes(v.mode)&&['iso','bosch'].includes(v.standard) + &&Number.isInteger(v.bitrate)&&Number.isInteger(v.data_bitrate)&&Array.isArray(v.filters)&&v.filters.length<=64 + &&v.filters.every(f=>f&&typeof f.extended==='boolean'&&Number.isInteger(f.start)&&Number.isInteger(f.end)&&f.start>=0&&f.end>=f.start&&f.end<=(f.extended?0x1fffffff:0x7ff)); +} +export function validPlan(value:unknown):value is Plan{ + if(!value||typeof value!=='object')return false;const v=value as Plan; + return Number.isInteger(v.repeat)&&v.repeat>=1&&v.repeat<=1000&&Number.isInteger(v.interval_ms)&&v.interval_ms>=10&&v.interval_ms<=60000 + &&typeof v.increment_id==='boolean'&&typeof v.increment_data==='boolean'&&Array.isArray(v.frames)&&v.frames.length<=64 + &&v.frames.every(f=>f&&Number.isInteger(f.id)&&f.id>=0&&['extended','fd','rtr','brs'].every(k=>typeof f[k as keyof typeof f]==='boolean')&&typeof f.data==='string'&&/^(?:[0-9a-f]{2}){0,64}$/i.test(f.data)&&Number.isInteger(f.dlc)&&Number.isInteger(f.send_type)); +} diff --git a/plugins/usb-can/frontend/src/plugin.ts b/plugins/usb-can/frontend/src/plugin.ts new file mode 100644 index 00000000..d78387fd --- /dev/null +++ b/plugins/usb-can/frontend/src/plugin.ts @@ -0,0 +1,8 @@ +import type {SensorUiContribution} from '../../../../packages/sensor-ui/src/extensions'; +import {CanDetail} from './CanDetail'; +export const usbCanSensorUi:SensorUiContribution={ + kind:'waveshare.usb-can-fd-b',Detail:CanDetail,icon:'network', + retainOffline:true,supportsPreparation:true,supportsRenaming:true, + settingsInDetail:true,detailPresentation:'modal',detailLabel:'Настройка USB-CAN', + status:(device,enabled)=>({tone:enabled&&device.online&&device.verified?'success':'neutral',label:enabled&&device.online&&device.verified?'Подключён':'Нет свежей связи'}), +}; diff --git a/plugins/usb-can/frontend/src/usb-can.css b/plugins/usb-can/frontend/src/usb-can.css new file mode 100644 index 00000000..5d924400 --- /dev/null +++ b/plugins/usb-can/frontend/src/usb-can.css @@ -0,0 +1,3 @@ +.usb-can-stack { display:flex; flex-direction:column; gap:var(--space-4,16px); min-width:0; } +.usb-can-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:var(--space-4,16px); } +.usb-can-actions { display:flex; flex-wrap:wrap; gap:var(--space-2,8px); } diff --git a/plugins/usb-can/packaging/70-mission-core-usb-can.rules b/plugins/usb-can/packaging/70-mission-core-usb-can.rules new file mode 100644 index 00000000..bf6da220 --- /dev/null +++ b/plugins/usb-can/packaging/70-mission-core-usb-can.rules @@ -0,0 +1,2 @@ +# Mission Core USB-CAN-FD-B profile. No port reset, bind, or channel start. +SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{idVendor}=="04d8", ATTR{idProduct}=="0053", ATTR{product}=="USB CANFD DEBUG", GROUP="mission-core-usb-can", MODE="0660" diff --git a/plugins/usb-can/packaging/fetch_sdk.py b/plugins/usb-can/packaging/fetch_sdk.py new file mode 100644 index 00000000..c6f8514d --- /dev/null +++ b/plugins/usb-can/packaging/fetch_sdk.py @@ -0,0 +1,39 @@ +"""Fetch the exact reviewed SDK; never execute vendor examples.""" + +import hashlib +import io +import json +import urllib.request +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def fetch(): + lock = json.loads((ROOT / "packaging/sdk-lock.json").read_text()) + with urllib.request.urlopen(lock["url"], timeout=30) as response: + data = response.read(lock["bytes"] + 1) + if len(data) != lock["bytes"] or hashlib.sha256(data).hexdigest() != lock["sha256"]: + raise ValueError("Vendor SDK differs from the reviewed lock") + with zipfile.ZipFile(io.BytesIO(data)) as archive: + content = archive.read(lock["library_member"]) + if len(content) != lock["library_bytes"] or content[:6] != b"\x7fELF\x02\x01": + raise ValueError("Expected the pinned 64-bit little-endian ELF") + target = ROOT / "build/sdk" + target.mkdir(parents=True, exist_ok=True) + (target / "libcontrolcanfd.so").write_bytes(content) + result = { + "file": "libcontrolcanfd.so", + "bytes": len(content), + "sha256": hashlib.sha256(content).hexdigest(), + "source_sha256": lock["sha256"], + } + (target / "manifest.json").write_text(json.dumps(result, indent=2) + "\n") + for name in ("controlcanfd.h", "config.h", "main.cpp"): + (target / name).write_bytes(archive.read("USB-CAN-FD-B-Linux/VMware/x86-c/" + name)) + print(json.dumps(result)) + + +if __name__ == "__main__": + fetch() diff --git a/plugins/usb-can/packaging/mission-core-node-usb-can-prepare.service b/plugins/usb-can/packaging/mission-core-node-usb-can-prepare.service new file mode 100644 index 00000000..51108cfe --- /dev/null +++ b/plugins/usb-can/packaging/mission-core-node-usb-can-prepare.service @@ -0,0 +1,7 @@ +[Unit] +Description=Prepare the versioned USB-CAN-FD-B profile +[Service] +Type=oneshot +ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-usb-can/prepare.py +TimeoutStartSec=90 +UMask=0022 diff --git a/plugins/usb-can/packaging/mission-core-usb-can.service b/plugins/usb-can/packaging/mission-core-usb-can.service new file mode 100644 index 00000000..4cf21035 --- /dev/null +++ b/plugins/usb-can/packaging/mission-core-usb-can.service @@ -0,0 +1,38 @@ +[Unit] +Description=Mission Core USB-CAN-FD-B service +After=systemd-udev-settle.service + +[Service] +Type=simple +User=mission-core-usb-can +Group=mission-core-node +SupplementaryGroups=mission-core-usb-can +WorkingDirectory=/usr/lib/mission-core-usb-can +ExecStart=/usr/bin/python3 -B -m runtime.server +RuntimeDirectory=mission-core-usb-can +RuntimeDirectoryMode=0750 +StateDirectory=mission-core-usb-can +StateDirectoryMode=0700 +UMask=0007 +Restart=on-failure +RestartSec=5 +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +PrivateNetwork=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +RestrictAddressFamilies=AF_UNIX AF_NETLINK +DevicePolicy=closed +DeviceAllow=char-usb_device rw +MemoryMax=512M +TasksMax=80 +LogRateLimitIntervalSec=30s +LogRateLimitBurst=30 + +[Install] +WantedBy=multi-user.target diff --git a/plugins/usb-can/packaging/native_check.py b/plugins/usb-can/packaging/native_check.py new file mode 100644 index 00000000..b291ae4a --- /dev/null +++ b/plugins/usb-can/packaging/native_check.py @@ -0,0 +1,17 @@ +"""Checks loadability and exact ABI; does not enumerate or open USB.""" + +import hashlib +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from runtime.sdk import library + +path = Path("/usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so") +if ( + hashlib.sha256(path.read_bytes()).hexdigest() + != "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c" +): + raise RuntimeError("Pinned USB-CAN SDK hash changed") +library(str(path)) +print("USB-CAN SDK load and packed ABI verified; no hardware opened") diff --git a/plugins/usb-can/packaging/payload.py b/plugins/usb-can/packaging/payload.py new file mode 100644 index 00000000..5ccd20ac --- /dev/null +++ b/plugins/usb-can/packaging/payload.py @@ -0,0 +1,50 @@ +"""Immutable USB-CAN runtime included in the standard Node package.""" + +import hashlib +from pathlib import Path + + +def payload(): + root = Path(__file__).resolve().parents[1] + files = [ + ("usr/lib/mission-core-usb-can/runtime/" + p.name, p.read_bytes(), 0o644) + for p in sorted((root / "runtime").glob("*.py")) + ] + files.append(("usr/lib/mission-core-usb-can/runtime/maintenance.py", + (root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py").read_bytes(), 0o644)) + for name in ("prepare.py", "native_check.py"): + files.append( + ( + "usr/lib/mission-core-usb-can/" + name, + (root / "packaging" / name).read_bytes(), + 0o644, + ) + ) + for name in ("mission-core-usb-can.service", "mission-core-node-usb-can-prepare.service"): + files.append( + ("usr/lib/systemd/system/" + name, (root / "packaging" / name).read_bytes(), 0o644) + ) + name = "70-mission-core-usb-can.rules" + files.append( + ( + "usr/share/mission-core-node/profiles/usb-can/" + name, + (root / "packaging" / name).read_bytes(), + 0o644, + ) + ) + data = (root / "build/sdk/libcontrolcanfd.so").read_bytes() + if ( + len(data) != 235000 + or hashlib.sha256(data).hexdigest() + != "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c" + ): + raise ValueError("USB-CAN SDK differs from the reviewed pin") + files.append(("usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so", data, 0o644)) + files.append( + ( + "usr/lib/mission-core-usb-can/sdk/source.json", + (root / "packaging/sdk-lock.json").read_bytes(), + 0o644, + ) + ) + return files diff --git a/plugins/usb-can/packaging/prepare.py b/plugins/usb-can/packaging/prepare.py new file mode 100644 index 00000000..0c1ecb64 --- /dev/null +++ b/plugins/usb-can/packaging/prepare.py @@ -0,0 +1,158 @@ +"""Versioned, idempotent USB-CAN profile; no packages downloaded and no motor I/O.""" + +import fcntl +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from runtime.discovery import discover + + +def atomic(path, value): + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False)) + temp.replace(path) + + +STATE = Path("/var/lib/mission-core-node-profiles/usb-can") + + +def prepare(): + if os.geteuid() != 0 or sys.argv[1:]: + raise RuntimeError("Fixed system profile only") + release = platform.freedesktop_os_release() + if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ( + "ubuntu", + "24.04", + "x86_64", + ): + raise RuntimeError("Ubuntu 24.04 amd64 required") + STATE.mkdir(mode=0o755, parents=True, exist_ok=True) + for directory in (STATE.parent, STATE): + info = directory.lstat() + if directory.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022: + raise RuntimeError("Untrusted profile state") + lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + report_previous = ( + json.loads((STATE / "preparation.json").read_text()) + if (STATE / "preparation.json").exists() + else {} + ) + report = { + "schema": "missioncore.node.device-preparation/v1", + "model_id": "waveshare.usb-can-fd-b", + "version": "0.2.7", + "run_id": uuid.uuid4().hex, + "started_at": time.time(), + "monotonic_started": time.monotonic(), + "state": "running", + "steps": [], + } + + def publish(): + atomic(STATE / "preparation.json", report) + os.chmod(STATE / "preparation.json", 0o644) + + def run(name, label, args): + step = {"id": name, "label": label, "state": "running"} + report["steps"].append(step) + publish() + result = subprocess.run( + args, + capture_output=True, + timeout=45, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"}, + ) + step["state"] = "complete" if result.returncode == 0 else "error" + publish() + if result.returncode: + raise RuntimeError("Не завершён этап: " + label) + + try: + import pwd + + try: + pwd.getpwnam("mission-core-usb-can") + except KeyError: + run( + "account", + "Подготовка доступа", + [ + "/usr/sbin/adduser", + "--system", + "--group", + "--home", + "/var/lib/mission-core-usb-can", + "--no-create-home", + "--disabled-login", + "mission-core-usb-can", + ], + ) + run( + "native", + "Проверка USB-CAN Tool", + [ + "/usr/sbin/runuser", + "-u", + "mission-core-usb-can", + "--", + "/usr/bin/python3", + "-I", + "/usr/lib/mission-core-usb-can/native_check.py", + ], + ) + source = Path("/usr/share/mission-core-node/profiles/usb-can/70-mission-core-usb-can.rules") + rules = source.read_bytes() + report["udev_sha256"] = hashlib.sha256(rules).hexdigest() + target = Path("/etc/udev/rules.d/70-mission-core-usb-can.rules") + if target.is_symlink(): + raise RuntimeError("Untrusted udev destination") + if target.exists() and target.read_bytes() != rules: + previous = report_previous.get("udev_sha256") + if hashlib.sha256(target.read_bytes()).hexdigest() != previous: + raise RuntimeError("Существующее USB-правило изменено вне профиля; сохранено.") + target.write_bytes(rules) + target.chmod(0o644) + run("rules", "Настройка USB-доступа", ["/usr/bin/udevadm", "control", "--reload-rules"]) + for i, device in enumerate(discover()): + run( + "usb" + str(i), + "Применение USB-доступа", + [ + "/usr/bin/udevadm", + "trigger", + "--action=change", + "/sys/bus/usb/devices/" + device.usb, + ], + ) + run("settle", "Проверка USB-доступа", ["/usr/bin/udevadm", "settle", "--timeout=10"]) + run( + "enable", + "Подготовка службы", + ["/usr/bin/systemctl", "enable", "mission-core-usb-can.service"], + ) + run( + "runtime", + "Обнаружение адаптеров", + ["/usr/bin/systemctl", "restart", "mission-core-usb-can.service"], + ) + report["state"] = "complete" + except (OSError, RuntimeError, subprocess.SubprocessError) as error: + report.update(state="error", message=str(error)[:300]) + finally: + report["duration_seconds"] = time.monotonic() - report["monotonic_started"] + publish() + os.close(lock) + return report["state"] == "complete" + + +if __name__ == "__main__": + sys.exit(0 if prepare() else 1) diff --git a/plugins/usb-can/packaging/sdk-lock.json b/plugins/usb-can/packaging/sdk-lock.json new file mode 100644 index 00000000..7848efd2 --- /dev/null +++ b/plugins/usb-can/packaging/sdk-lock.json @@ -0,0 +1,16 @@ +{ + "schema": "missioncore.usb-can.sdk/v1", + "version": "waveshare-linux-e009c7b1740d", + "url": "https://files.waveshare.com/wiki/USB-CAN-FD/USB-CAN-FD-B-Linux.zip", + "bytes": 1326766, + "sha256": "e009c7b1740d35cda6f1f68fc699d25eb363a37c8b2f2e80609732d394142a85", + "library_member": "USB-CAN-FD-B-Linux/VMware/x86-c/libcontrolcanfd.so", + "library_bytes": 235000, + "platform": { + "os": "ubuntu", + "version": "24.04", + "architecture": "x86_64" + }, + "api": "https://files.waveshare.com/wiki/USB-CAN-FD/Manual/USB-CAN-FD-B-API-Manual.pdf", + "license": "Vendor-distributed SDK; archive contains no separate open-source license." +} diff --git a/plugins/usb-can/runtime/__init__.py b/plugins/usb-can/runtime/__init__.py new file mode 100644 index 00000000..a1cd6144 --- /dev/null +++ b/plugins/usb-can/runtime/__init__.py @@ -0,0 +1,3 @@ +VERSION = "0.2.7" +MODEL = "waveshare.usb-can-fd-b" +SCHEMA = "missioncore.nodedc/plugin-sdk/v0alpha2" diff --git a/plugins/usb-can/runtime/bridge.py b/plugins/usb-can/runtime/bridge.py new file mode 100644 index 00000000..7e5c0a0e --- /dev/null +++ b/plugins/usb-can/runtime/bridge.py @@ -0,0 +1,256 @@ +"""Private, expiring ownership of CAN channels by the onboard controller service.""" + +import binascii +import copy +import math +import struct +import uuid +from collections import deque + +from .contracts import ARBITRATION, DEFAULT, channel, integer +from . import confirmed_tx + + +def acknowledged_read(frames, receive_id): + """Recognize six exact, argument-free VESC reads for confirmed transmission. + + Waveshare API 2.5: single-shot drops a frame on lost arbitration/error; + normal sending retries in the controller. This classifier never admits + arbitrary packets, forwarding or writes; exact setters use a separate path. COMM_PING_CAN (62) is the + read-only neighbour scan required before control; it needs the same normal + arbitration as identity/configuration reads. Closing the claim resets the + channel after a failed request; the application never replays a command. + """ + if len(frames) != 1: + return False + frame = frames[0] + data = bytes.fromhex(frame["data"]) + return (frame["id"] >> 8 == 8 and frame["id"] & 255 not in (255, receive_id) + and len(data) == 3 and data[:2] == bytes((receive_id, 0)) + and data[2] in (0, 4, 14, 17, 31, 62)) + + +def acknowledged_limits(frames, receive_id): + """Recognize only the pinned Tool's non-storing, non-forwarding limits packet. + + A complete 37-byte COMM_SET_MCCONF_TEMP request is six ordered fragments + plus its length/CRC commit. Native Tool validates the configuration before + emitting this packet. It requests an ACK and never emits a motor setpoint. + Reject classification on any ambiguity; arbitrary writes stay single-shot. + """ + if len(frames) != 7: + return False + target = frames[0]["id"] & 255 + if target in (255, receive_id): + return False + payload = bytearray() + for index, frame in enumerate(frames[:-1]): + data = bytes.fromhex(frame["data"]) + size = 7 if index < 5 else 2 + if (frame["id"] != (5 << 8) | target or len(data) != size + 1 + or data[0] != len(payload)): + return False + payload.extend(data[1:]) + final = frames[-1] + commit = (bytes((receive_id, 0, 0, 37)) + + binascii.crc_hqx(payload, 0).to_bytes(2, "big")) + if final["id"] != (7 << 8) | target or bytes.fromhex(final["data"]) != commit: + return False + if payload[:5] != bytes((48, 0, 0, 1, 0)): + return False + values = struct.unpack(">8f", payload[5:]) + return (all(math.isfinite(v) for v in values) + and all(0 < scale <= 1 for scale in values[:2])) + + +def acknowledged_configuration(frames, receive_id): + """Recognize one complete native configuration write and its exact ACK code. + + Motor/application configurations use the ordinary VESC fragmented transport, + including the two-byte offset after byte 255. The native Tool owns schema + validation and write admission; this boundary checks destination, contiguous + framing, length and CRC before permitting CAN-controller arbitration retry. + It never retries the application command or admits forwarded/broadcast writes. + """ + if len(frames) < 2: + return None + target = frames[0]["id"] & 255 + if target in (255, receive_id): + return None + payload = bytearray() + for index, frame in enumerate(frames[:-1]): + width, size, code = (1, 7, 5) if len(payload) <= 255 else (2, 6, 6) + data = bytes.fromhex(frame["data"]) + if (frame["id"] != (code << 8) | target or not width < len(data) <= width + size + or int.from_bytes(data[:width], "big") != len(payload) + or (index < len(frames) - 2 and len(data) != width + size)): + return None + payload.extend(data[width:]) + if len(payload) > 10000: + return None + if len(payload) < 7 or payload[0] not in (13, 16): + return None + commit = (bytes((receive_id, 0)) + len(payload).to_bytes(2, "big") + + binascii.crc_hqx(payload, 0).to_bytes(2, "big")) + if frames[-1]["id"] != (7 << 8) | target or bytes.fromhex(frames[-1]["data"]) != commit: + return None + return payload[0] + + +class Bridges: + def __init__(self, engine): + self.e = engine + self.claims = {} + self.previous = {} + + def occupied(self, ch): + return any(c["channel"] == ch for c in self.claims.values()) + + def close(self, token): + claim = self.claims.pop(token, None) + if claim and (claim["write_pending"] is not None or claim["tx_pending"]): + # A write without its exact ACK may still be queued in the adapter. + # Retire every shared claim before resetting the channel; another + # reader must not keep a timed-out mutation alive in hardware. + for other, value in list(self.claims.items()): + if value["channel"] == claim["channel"]: + self.claims.pop(other) + if claim and not self.occupied(claim["channel"]): + ch = claim["channel"] + self.e.running[ch] = False + self.e.configs[ch] = self.previous.pop(ch, copy.deepcopy(DEFAULT)) + self.e.sdk.stop(ch) + + def expire(self): + for token, claim in list(self.claims.items()): + if self.e.clock() >= claim["until"]: + self.close(token) + + def receive(self, frame): + for claim in self.claims.values(): + if ( + frame["channel"] == claim["channel"] + and frame.get("extended") + and frame["id"] & 255 == claim["receive_id"] + ): + pending = claim["write_pending"] + if (pending is not None and frame["id"] >> 8 == 8 + and not any(frame.get(k) for k in ("fd", "rtr", "error")) + and frame.get("data", "").lower() + == bytes((pending["target"], 1, pending["command"])).hex()): + claim["write_pending"] = None + if len(claim["frames"]) == 512: + claim["error"] = "Переполнение CAN. Сеанс требует повторного подключения." + claim["frames"].append(frame) + + def dispatch(self, action, p): + self.expire() + e = self.e + if action == "open": + if set(p) != {"channel", "bitrate", "receive_id"}: + raise ValueError("Invalid bridge configuration") + ch, bitrate = channel(p["channel"]), p["bitrate"] + receive_id = integer(p["receive_id"], 0, 254) + if type(bitrate) is not int or bitrate not in ARBITRATION: + raise ValueError("Unsupported CAN bitrate") + if len(self.claims) >= 8 or any( + c["channel"] == ch and c["receive_id"] == receive_id for c in self.claims.values() + ): + raise ValueError("Адрес ответа CAN уже занят.") + if self.occupied(ch): + if e.configs[ch]["bitrate"] != bitrate: + raise ValueError("На одном канале нужна одна скорость CAN.") + else: + if e.running[ch] or e.jobs[ch]: + raise ValueError( + "Остановите ручную работу CAN-канала перед подключением привода." + ) + config = {**copy.deepcopy(DEFAULT), "mode": "normal", "bitrate": bitrate} + e.sdk.start(ch, config) + self.previous[ch] = e.configs[ch] + e.configs[ch], e.running[ch] = config, True + token = uuid.uuid4().hex + self.claims[token] = { + "channel": ch, + "receive_id": receive_id, + "until": e.clock() + 0.75, + "frames": deque(maxlen=512), + "error": None, + "write_pending": None, + "tx_pending": False, + "tx_confirmation": {"kind": "adapter_echo", "confirmed": 0, "elapsed_ms": None}, + } + return {"token": token} + token = p.get("token") + claim = self.claims.get(token) + if not claim: + raise ValueError("Сеанс CAN завершён. Автоматическая передача не возобновляется.") + if action == "close": + self.close(token) + return {} + if claim["error"] or not e.running[claim["channel"]]: + self.close(token) + raise ValueError(claim["error"] or "CAN-канал остановлен.") + claim["until"] = e.clock() + 0.75 + if action == "send": + frames, deadline = p.get("frames"), p.get("deadline") + if ( + type(deadline) not in (int, float) + or not math.isfinite(deadline) + or not e.clock() < deadline <= e.clock() + 0.3 + or not isinstance(frames, list) + or not 1 <= len(frames) <= 2048 + ): + raise ValueError("Передача CAN устарела или превышает предел.") + for frame in frames: + if ( + set(frame) != {"id", "data"} + or type(frame["id"]) is not int + or not 0 <= frame["id"] <= 0x1FFFFFFF + or not isinstance(frame["data"], str) + or not 1 <= len(bytes.fromhex(frame["data"])) <= 8 + ): + raise ValueError("Invalid classic CAN frame") + if claim["write_pending"] is not None: + self.close(token) + raise ValueError( + "Подтверждение записи не получено; CAN-сеанс закрыт." + ) + ack_command = (48 if acknowledged_limits(frames, claim["receive_id"]) + else acknowledged_configuration(frames, claim["receive_id"])) + confirm = (acknowledged_read(frames, claim["receive_id"]) + or confirmed_tx.output_frame(frames, claim["receive_id"])) + send_type = 0 if ack_command is not None else 1 + if ack_command is not None: + claim["write_pending"] = {"target": frames[0]["id"] & 255, "command": ack_command} + try: + for frame in frames: + if e.clock() >= deadline: + raise ValueError("Срок передачи CAN истёк; повтор запрещён.") + value = { + **frame, + "extended": True, + "fd": False, + "rtr": False, + "brs": False, + "dlc": len(frame["data"]) // 2, + "send_type": send_type, + } + if confirm: + claim["tx_pending"] = True + confirmed_tx.send(e, claim, value, deadline) + claim["tx_pending"] = False + else: + e.sdk.transmit(claim["channel"], value) + e.counts[claim["channel"]]["tx_accepted"] += 1 + except (OSError, ValueError): + self.close(token) + raise + elif action != "poll": + raise ValueError("Unknown bridge action") + frames = list(claim["frames"]) + claim["frames"].clear() + result = {"frames": frames} + if action == "send" and confirm: + result["tx_confirmation"] = dict(claim["tx_confirmation"]) + return result diff --git a/plugins/usb-can/runtime/confirmed_tx.py b/plugins/usb-can/runtime/confirmed_tx.py new file mode 100644 index 00000000..424efeca --- /dev/null +++ b/plugins/usb-can/runtime/confirmed_tx.py @@ -0,0 +1,71 @@ +"""Stop-and-wait CAN transmission; an adapter echo is not a VESC command ACK.""" + +# Bound the adapter's normal arbitration retries inside the caller's deadline. +# One frame may be outstanding. Timeout retires the whole shared channel. +ECHO_TIMEOUT = 0.040 + + +def output_frame(frames, receive_id): + """Exact non-forwarded native setters and the existing 250 ms PPM lease.""" + if len(frames) != 1: + return False + frame = frames[0] + data = bytes.fromhex(frame["data"]) + if (frame["id"] >> 8 != 8 or frame["id"] & 255 in (receive_id, 255) + or data[:2] != bytes((receive_id, 0))): + return False + payload = data[2:] + return ((len(payload) == 5 and payload[0] in (5, 6, 8)) + or payload == bytes((63, 0, 0, 0, 0, 250))) + + +def matches(frame, sent, channel): + return (frame.get("channel") == channel and frame.get("id") == sent["id"] + and frame.get("extended") is True + and not any(frame.get(k) for k in ("fd", "rtr", "error")) + and frame.get("dlc") == sent["dlc"] + and frame.get("data", "").lower() == sent["data"].lower()) + + +def send(engine, claim, frame, deadline): + """Submit once; normal+self-reception retries are owned by the CAN controller. + + The caller must reset the entire shared channel on ANY failure, including + exceptions after SDK acceptance. Never replay or fall back to single-shot. + Drain before submission so buffered echoes cannot acknowledge a new request. + Every previous confirmed request consumed exactly one echo (no app retries). + Unrelated RX is routed normally, including traffic for other shared claims. + """ + channel = claim["channel"] + until = min(deadline, engine.clock() + ECHO_TIMEOUT) + while True: + if engine.clock() >= until: + raise OSError("Истёк срок подтверждения передачи CAN.") + received = engine.sdk.receive(channel) + for rx in received: + engine.receive(rx) + if rx.get("error"): + raise OSError("Ошибка CAN перед отправкой команды.") + if not received: + break + started = engine.clock() + engine.sdk.transmit(channel, {**frame, "send_type": 2}) + engine.counts[channel]["tx_accepted"] += 1 + while engine.clock() < until: + received = engine.sdk.receive(channel) + confirmed = False + for rx in received: + engine.receive(rx) + if rx.get("error"): + raise OSError("Ошибка CAN при подтверждении передачи.") + confirmed = confirmed or matches(rx, frame, channel) + if confirmed and engine.clock() < until: + elapsed = (engine.clock() - started) * 1000 + claim["tx_confirmation"] = { + "kind": "adapter_echo", "confirmed": claim["tx_confirmation"]["confirmed"] + 1, + "elapsed_ms": elapsed, + } + return + # Injectable sleep keeps the deadline tests deterministic. + engine.sleep(min(0.001, max(0, until - engine.clock()))) + raise OSError("Адаптер не подтвердил передачу CAN в срок; канал остановлен.") diff --git a/plugins/usb-can/runtime/contracts.py b/plugins/usb-can/runtime/contracts.py new file mode 100644 index 00000000..4fb3f671 --- /dev/null +++ b/plugins/usb-can/runtime/contracts.py @@ -0,0 +1,118 @@ +"""Validated public contract. No imported configuration can start a channel.""" + +import copy +import re + +ARBITRATION = (50000, 100000, 125000, 250000, 500000, 800000, 1000000) +DATA_RATES = (100000, 125000, 250000, 500000, 800000, 1000000, 2000000, 4000000, 5000000) +DEFAULT = { + "protocol": "can", + "mode": "listen", + "bitrate": 500000, + "data_bitrate": 2000000, + "standard": "iso", + "filters": [], +} +ACTIONS = frozenset( + ( + "details", + "verify", + "can.status", + "can.configure", + "can.start", + "can.stop", + "can.clear", + "can.transmit.preview", + "can.transmit.apply", + "can.transmit.stop", + ) +) + + +def integer(value, low, high): + if type(value) is not int or not low <= value <= high: + raise ValueError("Число вне допустимого диапазона.") + return value + + +def channel(value): + return integer(value, 0, 1) + + +def configuration(value): + if not isinstance(value, dict) or set(value) != set(DEFAULT): + raise ValueError("Неверный состав конфигурации CAN.") + if value["protocol"] not in ("can", "fd") or value["mode"] not in ("listen", "normal"): + raise ValueError("Неизвестный режим CAN.") + if type(value["bitrate"]) is not int or value["bitrate"] not in ARBITRATION: + raise ValueError("Неподдерживаемая скорость арбитража.") + if type(value["data_bitrate"]) is not int or value["data_bitrate"] not in DATA_RATES: + raise ValueError("Неподдерживаемая скорость данных.") + if value["standard"] not in ("iso", "bosch"): + raise ValueError("Неизвестный стандарт CAN FD.") + filters = value["filters"] + if not isinstance(filters, list) or len(filters) > 64: + raise ValueError("Слишком много фильтров.") + weight = 0 + for item in filters: + if ( + not isinstance(item, dict) + or set(item) != {"extended", "start", "end"} + or type(item["extended"]) is not bool + ): + raise ValueError("Неверный фильтр.") + limit = 0x1FFFFFFF if item["extended"] else 0x7FF + integer(item["start"], 0, limit) + integer(item["end"], item["start"], limit) + weight += 2 if item["extended"] else 1 + if weight > 64: + raise ValueError("До 64 стандартных или 32 расширенных диапазонов.") + return copy.deepcopy(value) + + +def frame(value): + keys = {"id", "extended", "fd", "rtr", "brs", "data", "dlc", "send_type"} + if not isinstance(value, dict) or set(value) != keys: + raise ValueError("Неверный состав CAN-кадра.") + for flag in ("extended", "fd", "rtr", "brs"): + if type(value[flag]) is not bool: + raise ValueError("Неверный флаг CAN.") + integer(value["id"], 0, 0x1FFFFFFF if value["extended"] else 0x7FF) + integer(value["send_type"], 0, 3) + integer(value["dlc"], 0, 64 if value["fd"] else 8) + if value["fd"] and value["dlc"] not in (*range(9), 12, 16, 20, 24, 32, 48, 64): + raise ValueError("Недопустимая длина CAN FD.") + if (value["fd"] and value["rtr"]) or (value["brs"] and not value["fd"]): + raise ValueError("Несовместимые флаги CAN.") + data = value["data"] + if not isinstance(data, str) or not re.fullmatch(r"[0-9a-fA-F]{0,128}", data) or len(data) % 2: + raise ValueError("Данные должны быть шестнадцатеричными байтами.") + if len(data) // 2 != (0 if value["rtr"] else value["dlc"]): + raise ValueError("Длина данных не совпадает с DLC.") + return {**value, "data": data.upper()} + + +def transmission(value): + if not isinstance(value, dict) or set(value) != { + "frames", + "repeat", + "interval_ms", + "increment_id", + "increment_data", + }: + raise ValueError("Неверное задание передачи.") + frames = value["frames"] + if not isinstance(frames, list) or not 1 <= len(frames) <= 64: + raise ValueError("В задании должно быть от 1 до 64 кадров.") + frames = [frame(item) for item in frames] + repeat = integer(value["repeat"], 1, 1000) + interval = integer(value["interval_ms"], 10, 60000) + if repeat * len(frames) > 1000 or (repeat * len(frames) - 1) * interval > 60000: + raise ValueError("Одно задание: до 1000 кадров и 60 секунд.") + for key in ("increment_id", "increment_data"): + if type(value[key]) is not bool: + raise ValueError("Неверный режим инкремента.") + if value["increment_id"]: + for item in frames: + integer(item["id"] + repeat - 1, 0, 0x1FFFFFFF if item["extended"] else 0x7FF) + return {**value, "frames": frames} diff --git a/plugins/usb-can/runtime/discovery.py b/plugins/usb-can/runtime/discovery.py new file mode 100644 index 00000000..54f19e27 --- /dev/null +++ b/plugins/usb-can/runtime/discovery.py @@ -0,0 +1,49 @@ +"""VID/PID/product discovery; a USB descriptor is not the protocol serial.""" + +import hashlib +from dataclasses import dataclass +from pathlib import Path + + +def device_id(value): + return "usbcan_" + hashlib.sha256(value.encode()).hexdigest()[:32] + + +@dataclass(frozen=True) +class Attachment: + binding: str + usb: str + path: str + speed: str + + @property + def id(self): + return device_id("provisional:" + self.binding) + + +def discover(root=Path("/sys/bus/usb/devices")): + result = [] + for path in sorted(root.glob("*")): + try: + + def read(name, path=path): + return (path / name).read_text().strip() + + if (read("idVendor"), read("idProduct"), read("product")) != ( + "04d8", + "0053", + "USB CANFD DEBUG", + ): + continue + bus, dev = int(read("busnum")), int(read("devnum")) + result.append( + Attachment( + path.name + ":" + str(dev), + path.name, + f"/dev/bus/usb/{bus:03}/{dev:03}", + read("speed") + " Мбит/с", + ) + ) + except (OSError, ValueError): + continue + return result[:8] diff --git a/plugins/usb-can/runtime/sdk.py b/plugins/usb-can/runtime/sdk.py new file mode 100644 index 00000000..56481bdd --- /dev/null +++ b/plugins/usb-can/runtime/sdk.py @@ -0,0 +1,294 @@ +"""Exact packed ABI from the pinned Waveshare x86-64 header; no demo execution.""" + +import contextlib +import ctypes as C +import os +from pathlib import Path + +U8, U16, U32, U64, PTR = C.c_uint8, C.c_uint16, C.c_uint32, C.c_uint64, C.c_void_p + + +class Packed(C.Structure): + _pack_ = 1 + + +class DeviceInfo(Packed): + _fields_ = [(name, U16) for name in ("hardware", "firmware", "driver", "interface", "irq")] + [ + ("channels", U8), + ("serial", U8 * 21), + ("model", U8 * 40), + ("reserved", U16 * 5), + ] + + +class Classic(Packed): + _fields_ = [ + ("id", U32), + ("length", U8), + ("flags", U8), + ("res0", U8), + ("res1", U8), + ("data", U8 * 8), + ] + + +class FD(Packed): + _fields_ = [ + ("id", U32), + ("length", U8), + ("flags", U8), + ("res0", U8), + ("res1", U8), + ("data", U8 * 64), + ] + + +class InitClassic(Packed): + _fields_ = [ + ("code", U32), + ("mask", U32), + ("reserved", U32), + ("filter", U8), + ("timing0", U8), + ("timing1", U8), + ("mode", U8), + ] + + +class InitFD(Packed): + _fields_ = [ + ("code", U32), + ("mask", U32), + ("abit", U32), + ("dbit", U32), + ("brp", U32), + ("filter", U8), + ("mode", U8), + ("pad", U16), + ("reserved", U32), + ] + + +class InitUnion(C.Union): + _pack_ = 1 + _fields_ = [("classic", InitClassic), ("fd", InitFD)] + + +class Init(Packed): + _fields_ = [("type", U32), ("config", InitUnion)] + + +class Tx(Packed): + _fields_ = [("frame", Classic), ("send_type", U32)] + + +class TxFD(Packed): + _fields_ = [("frame", FD), ("send_type", U32)] + + +class Rx(Packed): + _fields_ = [("frame", Classic), ("timestamp", U64)] + + +class RxFD(Packed): + _fields_ = [("frame", FD), ("timestamp", U64)] + + +SIZES = {DeviceInfo: 82, Classic: 16, FD: 72, Init: 32, Tx: 20, TxFD: 76, Rx: 24, RxFD: 80} + + +def check_abi(): + for cls, size in SIZES.items(): + if C.sizeof(cls) != size: + raise RuntimeError("SDK ABI mismatch: " + cls.__name__) + + +def library(path="/usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so"): + check_abi() + lib = C.CDLL(path) + signatures = { + "OpenDevice": (PTR, [U32, U32, U32]), + "CloseDevice": (U32, [PTR]), + "GetDeviceInf": (U32, [PTR, C.POINTER(DeviceInfo)]), + "IsDeviceOnLine": (U32, [PTR]), + "InitCAN": (PTR, [PTR, U32, C.POINTER(Init)]), + "GetReceiveNum": (U32, [PTR, U8]), + "SetBaudRateCustom": (U32, [PTR, U32, C.c_char_p]), + } + for name in ("StartCAN", "ResetCAN", "ClearBuffer", "ClearFilter", "AckFilter"): + signatures[name] = (U32, [PTR]) + for name in ("SetAbitBaud", "SetDbitBaud", "SetCANFDStandard"): + signatures[name] = (U32, [PTR, U32, U32]) + for name in ("SetFilterMode", "SetFilterStartID", "SetFilterEndID"): + signatures[name] = (U32, [PTR, U32]) + for suffix, tx, rx in (("", Tx, Rx), ("FD", TxFD, RxFD)): + signatures["Transmit" + suffix] = (U32, [PTR, C.POINTER(tx), U32]) + signatures["Receive" + suffix] = (U32, [PTR, C.POINTER(rx), U32, C.c_int]) + for name, (result, args) in signatures.items(): + fn = getattr(lib, "ZCAN_" + name) + fn.restype, fn.argtypes = result, args + return lib + + +def text(value): + return bytes(value).split(b"\0", 1)[0].decode("ascii", "strict").strip() + + +def version(value): + return f"{value >> 8:X}.{value & 255:02X}" + + +class SDK: + def __init__(self, index, expected_usb, lib=None): + self.lib = lib or library() + self.handle, self.handles = None, [None, None] + self.handle = self.lib.ZCAN_OpenDevice(41, index, 0) + if not self.handle: + raise OSError("Не удалось открыть USB-CAN. Проверьте доступ и другие программы.") + try: + # SDK selects by index. Prove its actual open device before assigning + # a physical session; USB port order is never hardware identity. + opened = set() + for entry in Path("/proc/self/fd").iterdir(): + try: + target = os.readlink(entry) + if target.startswith("/dev/bus/usb/"): + opened.add(target) + except OSError: + pass + if opened != {expected_usb}: + raise OSError("SDK не подтвердил однозначное соответствие USB-устройству.") + info = DeviceInfo() + self.ok(self.lib.ZCAN_GetDeviceInf(self.handle, C.byref(info)), "идентификация") + serial = text(info.serial) + if not serial or len(serial) > 20 or info.channels != 2: + raise OSError("Не подтверждены серийный номер и два CAN-канала.") + self.identity = { + "serial": serial, + "model": text(info.model), + "channels": int(info.channels), + **{ + key: version(getattr(info, key)) + for key in ("hardware", "firmware", "driver", "interface") + }, + } + except BaseException: + self.close() + raise + + @staticmethod + def ok(value, operation): + if value != 1: + raise OSError("SDK отклонил операцию: " + operation) + + def start(self, channel, config): + self.stop(channel) + self.ok( + self.lib.ZCAN_SetAbitBaud(self.handle, channel, config["bitrate"]), "скорость арбитража" + ) + self.ok( + self.lib.ZCAN_SetDbitBaud(self.handle, channel, config["data_bitrate"]), + "скорость данных", + ) + self.ok( + self.lib.ZCAN_SetCANFDStandard( + self.handle, channel, int(config["standard"] == "bosch") + ), + "стандарт FD", + ) + init = Init() + # The CAN-FD controller uses its FD init structure for classical frames + # too; protocol selection governs allowed TX/RX frame formats. + init.type = 1 + init.config.fd.mode = int(config["mode"] == "listen") + init.config.fd.mask = 0xFFFFFFFF + handle = self.lib.ZCAN_InitCAN(self.handle, channel, C.byref(init)) + if not handle: + raise OSError("SDK не инициализировал CAN-канал.") + self.handles[channel] = handle + try: + self.ok(self.lib.ZCAN_ClearFilter(handle), "очистка фильтров") + # Explicit full ranges when no filter was requested. + for item in config["filters"] or [ + {"extended": False, "start": 0, "end": 0x7FF}, + {"extended": True, "start": 0, "end": 0x1FFFFFFF}, + ]: + self.ok(self.lib.ZCAN_SetFilterMode(handle, int(item["extended"])), "тип фильтра") + self.ok(self.lib.ZCAN_SetFilterStartID(handle, item["start"]), "начало фильтра") + self.ok(self.lib.ZCAN_SetFilterEndID(handle, item["end"]), "конец фильтра") + self.ok(self.lib.ZCAN_AckFilter(handle), "применение фильтров") + self.ok(self.lib.ZCAN_StartCAN(handle), "запуск канала") + except BaseException: + self.stop(channel) + raise + + def stop(self, channel): + handle = self.handles[channel] + if handle: + self.ok(self.lib.ZCAN_ResetCAN(handle), "остановка канала") + self.handles[channel] = None + + def clear(self, channel): + if self.handles[channel]: + self.ok(self.lib.ZCAN_ClearBuffer(self.handles[channel]), "очистка приёмного буфера") + + def receive(self, channel): + handle = self.handles[channel] + if not handle: + return [] + frames = [] + for fd, cls, method in ( + (False, Rx, self.lib.ZCAN_Receive), + (True, RxFD, self.lib.ZCAN_ReceiveFD), + ): + data = (cls * 64)() + count = method(handle, data, 64, 0) + if count > 64: + raise OSError("SDK вернул ошибку чтения CAN.") + for item in data[:count]: + f = item.frame + if f.length > (64 if fd else 8): + raise OSError("SDK вернул повреждённый CAN-кадр.") + frames.append( + { + "channel": channel, + "direction": "RX", + "timestamp_us": int(item.timestamp), + "id": int(f.id & 0x1FFFFFFF), + "extended": bool(f.id & 0x80000000), + "rtr": bool(f.id & 0x40000000), + "error": bool(f.id & 0x20000000), + "fd": fd, + "brs": bool(f.flags & 1) if fd else False, + "esi": bool(f.flags & 2) if fd else False, + "dlc": int(f.length), + "data": bytes(f.data[: f.length]).hex().upper(), + } + ) + return frames + + def transmit(self, channel, frame): + if not self.handles[channel]: + raise ValueError("Канал остановлен.") + value = TxFD() if frame["fd"] else Tx() + value.frame.id = frame["id"] | (int(frame["extended"]) << 31) | (int(frame["rtr"]) << 30) + value.frame.length = frame["dlc"] + value.frame.flags = int(frame["brs"]) if frame["fd"] else 0 + data = bytes.fromhex(frame["data"]) + for index, byte in enumerate(data): + value.frame.data[index] = byte + value.send_type = frame["send_type"] + fn = self.lib.ZCAN_TransmitFD if frame["fd"] else self.lib.ZCAN_Transmit + self.ok(fn(self.handles[channel], C.byref(value), 1), "передача кадра") + + def online(self): + # SDK's documented STATUS_ONLINE is 2, not STATUS_OK (1). + return self.lib.ZCAN_IsDeviceOnLine(self.handle) == 2 + + def close(self): + if self.handle: + for channel in range(2): + with contextlib.suppress(OSError): + self.stop(channel) + self.lib.ZCAN_CloseDevice(self.handle) + self.handle = None diff --git a/plugins/usb-can/runtime/server.py b/plugins/usb-can/runtime/server.py new file mode 100644 index 00000000..db563030 --- /dev/null +++ b/plugins/usb-can/runtime/server.py @@ -0,0 +1,198 @@ +"""Private local USB-CAN API. No channel opens during service startup.""" + +import contextlib +import json +import os +import pwd +import re +import socket +import socketserver +import struct +import threading +from http.server import BaseHTTPRequestHandler +from pathlib import Path + +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"] + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + self.dispatch() + + def do_POST(self): + 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.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: + _, uid, _ = struct.unpack( + "3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12) + ) + if self.command == "GET" and self.path == "/prepare-safe" and uid == 0: + result = {"safe": self.server.service.prepare_safe()} + elif uid == self.server.vesc_uid and self.path in ("/bridge", "/bridge-inventory"): + if self.headers.get("Transfer-Encoding"): + raise ValueError("Invalid bridge request") + if self.command == "GET" and self.path == "/bridge-inventory": + result = self.server.service.bridge_inventory() + elif self.command == "POST" and self.path == "/bridge": + size = int(self.headers.get("Content-Length", "0")) + if ( + not 0 < size <= 196608 + or self.headers.get("Content-Type") != "application/json" + ): + raise ValueError("Invalid bridge request") + raw = self.rfile.read(size) + if len(raw) != size: + raise ValueError("Incomplete bridge request") + result = self.server.service.bridge(json.loads(raw)) + else: + raise ValueError("Invalid bridge method") + else: + node = self.headers.get("X-Node-Id", "") + if ( + uid != self.server.node_uid + or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node) + or self.headers.get("Transfer-Encoding") + ): + raise ValueError("Недопустимый запрос.") + if self.command == "GET" and self.path == "/inventory": + result = self.server.service.inventory(node) + elif self.command == "POST" and self.path == "/operation": + size = int(self.headers.get("Content-Length", "0")) + if ( + not 0 < size <= 65536 + or self.headers.get("Content-Type") != "application/json" + ): + raise ValueError("Неверный размер запроса.") + raw = self.rfile.read(size) + if len(raw) != size: + raise ValueError("Неполный запрос.") + result = self.server.service.execute(json.loads(raw)) + else: + raise ValueError("Неизвестный запрос.") + except (ValueError, KeyError, TypeError, OSError) as error: + status, result = 400, {"error": str(error)[:300]} + data = json.dumps(result, ensure_ascii=False, allow_nan=False).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(data) + + +class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + daemon_threads = True + + def __init__(self, path, handler): + self.slots = threading.BoundedSemaphore(8) + super().__init__(path, handler) + + def process_request(self, request, address): + if not self.slots.acquire(blocking=False): + self.shutdown_request(request) + return + try: + super().process_request(request, address) + except BaseException: + self.slots.release() + raise + + def process_request_thread(self, request, address): + try: + super().process_request_thread(request, address) + finally: + self.slots.release() + + def verify_request(self, request, address): + if self.vesc_uid == -1: + with contextlib.suppress(KeyError): + self.vesc_uid = pwd.getpwnam("mission-core-vesc").pw_uid + _, uid, _ = struct.unpack( + "3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12) + ) + return uid in (0, self.node_uid, self.vesc_uid) + + +def main(): + if os.geteuid() == 0: + raise RuntimeError("USB-CAN must run unprivileged") + service = Service() + stop = threading.Event() + maintenance = Maintenance() + + def scan(): + while not stop.is_set(): + try: + with maintenance.work(background=True) as admitted: + if admitted: service.scan() + except Exception: + # A transient discovery failure never kills subsequent hotplug. + import logging + + logging.exception("USB-CAN discovery failed") + stop.wait(2) + + path = Path("/run/mission-core-usb-can/driver.sock") + path.unlink(missing_ok=True) + with Server(str(path), Handler) as server: + server.node_uid = pwd.getpwnam("mission-core-node").pw_uid + try: + server.vesc_uid = pwd.getpwnam("mission-core-vesc").pw_uid + except KeyError: + server.vesc_uid = -1 + server.service = service + server.maintenance = maintenance + server.idle = lambda: None if service.prepare_safe() else "can-channel-active" + server.quiesce = lambda: None + threading.Thread(target=scan, daemon=True, name="usb-can-discovery").start() + try: + server.serve_forever() + finally: + stop.set() + for device in list(service.devices.values()): + device.close() + + +if __name__ == "__main__": + main() diff --git a/plugins/usb-can/runtime/service.py b/plugins/usb-can/runtime/service.py new file mode 100644 index 00000000..aa52e2e0 --- /dev/null +++ b/plugins/usb-can/runtime/service.py @@ -0,0 +1,389 @@ +"""USB identity/hotplug and session-bound operations. Raw frames never reach disk.""" + +import copy +import hashlib +import json +import re +import threading +import time +import uuid +from collections import OrderedDict +from datetime import UTC, datetime +from pathlib import Path + +from . import MODEL, SCHEMA, VERSION +from .contracts import ACTIONS, channel, configuration, integer, transmission +from .discovery import device_id, discover +from .worker import Link + + +def utc(): + return datetime.now(UTC).isoformat() + + +class Device: + def __init__(self, attachment): + self.attachment = attachment + self.session = "usbcan_" + uuid.uuid4().hex + self.opened = utc() + self.link = None + self.status = None + self.error = None + self.retry_at = 0 + self.failures = 0 + self.revision = 0 + self.preview = None + self.lock = threading.RLock() + self.activity = None + + @property + def id(self): + return ( + device_id("serial:" + self.status["identity"]["serial"]) + if self.status + else self.attachment.id + ) + + def call(self, action, params): + # Caller holds the device lock. Keep only bounded operation metadata, + # never frames, so a rejected poll identifies its competing owner. + self.activity = (action, time.monotonic()) + try: + return self.link.call(action, params) + finally: + self.activity = None + + def close(self): + if self.link: + self.link.close() + self.link, self.preview = None, None + self.session, self.opened = "usbcan_" + uuid.uuid4().hex, utc() + + +class Service: + def __init__(self, root="/var/lib/mission-core-usb-can", discover_fn=discover, factory=Link): + self.root = Path(root) + self.discover_fn, self.factory = discover_fn, factory + self.devices = {} + self.lock = threading.RLock() + self.receipts = OrderedDict() + self.instance = "usbcan_" + uuid.uuid4().hex + self.revision = 0 + + 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 d in removed: + with d.lock: + d.close() + # SDK indices are enumeration-local, so verify opened FD on every attempt. + for index, d in enumerate(devices): + if not d.lock.acquire(blocking=False): + continue + try: + if d.link and not d.link.alive: + d.close() + d.session, d.opened = "usbcan_" + uuid.uuid4().hex, utc() + d.status = None + if d.link is None and time.monotonic() >= d.retry_at: + d.failures += 1 + d.retry_at = time.monotonic() + min(60, 2 ** min(d.failures, 6)) + d.link = self.factory( + (index + d.failures - 1) % max(1, len(devices)), d.attachment.path + ) + d.status = d.link.initial + # Saved configuration does not enable CAN or repeat a job. + saved = self.root / (d.id + ".json") + if saved.exists(): + document = json.loads(saved.read_text()) + if ( + not isinstance(document["channels"], list) + or len(document["channels"]) != 2 + ): + raise ValueError("Сохранённая конфигурация не содержит два канала.") + for ch, config in enumerate(document["channels"]): + d.status = d.call( + "configure", + {"channel": channel(ch), "config": configuration(config)}, + ) + d.revision = integer(document["revision"], 0, 2**31 - 1) + d.error, d.failures = None, 0 + elif d.link is not None: + d.status = d.call("status", {}) + + except (OSError, ValueError, KeyError, EOFError) as error: + d.error = str(error)[:250] + d.close() + finally: + d.lock.release() + with self.lock: + self.revision += 1 + + def bridge_inventory(self): + with self.lock: + devices = list(self.devices.values()) + ids = [d.id for d in devices] + return { + "items": [ + { + "id": d.id, + "session_id": d.session, + "attachment_id": d.attachment.id, + "name": "USB-CAN-FD-B · " + d.status["identity"]["serial"], + "online": True, + "channels": 2, + } + for d in devices + if d.status and d.link and d.link.alive and ids.count(d.id) == 1 + ] + } + + def bridge(self, request): + if ( + not isinstance(request, dict) + or set(request) != {"adapter", "session", "action", "parameters"} + or request["action"] not in ("open", "close", "send", "poll") + or not isinstance(request["parameters"], dict) + ): + raise ValueError("Invalid VESC bridge request") + with self.lock: + matches = [d for d in self.devices.values() if d.id == request["adapter"]] + if len(matches) != 1: + raise ValueError("Адаптер CAN недоступен или его идентификатор повторяется.") + d = matches[0] + if not d.lock.acquire(timeout=0.2): + action, started = d.activity or ("lifecycle", time.monotonic()) + raise OSError(f"Адаптер CAN занят: {action}, {time.monotonic() - started:.3f} с.") + try: + if d.session != request["session"] or not d.link or not d.link.alive: + raise ValueError("Подключение адаптера CAN изменилось.") + return d.call("bridge." + request["action"], request["parameters"]) + except (OSError, EOFError): + d.close() + raise + finally: + d.lock.release() + + def prepare_safe(self): + with self.lock: + devices = list(self.devices.values()) + for device in devices: + if not device.lock.acquire(timeout=1): + return False + try: + if device.link: + status = device.call("status", {}) + if any(channel["running"] for channel in status["channels"]): + return False + except (OSError, EOFError): + return False + finally: + device.lock.release() + return True + + def inventory(self, node): + with self.lock: + devices = list(self.devices.values()) + ids = [d.id for d in devices] + items = [] + for d in devices: + unique = ids.count(d.id) == 1 and d.status is not None + available = unique and d.link is not None and d.link.alive + identity = d.status["identity"] if unique else None + status = copy.deepcopy(d.status) if available else None + if status: + status.pop("frames", None) + identifier = d.id if unique else d.attachment.id + message = ( + d.error + if ids.count(d.id) == 1 + else "Повторяющийся серийный номер. Управление недоступно." + ) + items.append( + { + "id": identifier, + "attachment_id": d.attachment.id, + "kind": MODEL, + "name": "USB-CAN-FD-B" + (" · " + identity["serial"] if identity else ""), + "model": "Waveshare USB-CAN-FD-B", + "firmware": identity["firmware"] if identity else None, + "initializable": True, + "prepared": True, + "configured": unique, + "verified": bool(available), + "online": True, + "usb": d.attachment.speed, + "connection_label": "USB " + d.attachment.usb, + "preparation_safe": not ( + status and any(c["running"] for c in status["channels"]) + ), + "layers": [], + "can_status": {**(status or {}), "revision": d.revision, "message": message}, + "snapshot": { + "context": { + "session_id": d.session, + "device": { + "device_id": identifier, + "model": { + "plugin_id": "missioncore.usb-can", + "plugin_version": VERSION, + "model_id": MODEL, + }, + "stability": "stable" if unique else "provisional", + "basis": "hardware-identifier" if unique else "transport-local", + }, + "execution": { + "node_id": node, + "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 execute(self, command): + if command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest": + raise ValueError("Неверный контракт.") + op = command.get("operation_id", "") + if not re.fullmatch(r"op_[0-9a-f]{32}", op) or command.get("idempotency_key") != op: + raise ValueError("Неверный идентификатор операции.") + action, params = command.get("action_id"), command.get("parameters") + if action not in ACTIONS or not isinstance(params, dict): + raise ValueError("Неподдерживаемая операция.") + start = datetime.fromisoformat(command["requested_at"].replace("Z", "+00:00")) + end = datetime.fromisoformat(command["deadline_at"].replace("Z", "+00:00")) + if ( + start.tzinfo is None + or end.tzinfo is None + or not 0 < (end - start).total_seconds() <= (360 if action == "verify" else 60) + or datetime.now(UTC) >= end + ): + raise ValueError("Срок запроса истёк.") + digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest() + with self.lock: + # Keep receipts beyond every admitted deadline. Never evict an + # unexpired identity to make room for a retry. + now = time.monotonic() + for key, entry in list(self.receipts.items()): + if now - entry[0] > 380: + del self.receipts[key] + if op in self.receipts: + entry = self.receipts[op] + if entry[1] != digest: + raise ValueError("Идентификатор уже использован.") + return entry[2] + if len(self.receipts) >= 256: + raise ValueError("Слишком много операций.") + selected = [d for d in self.devices.values() if d.id == command["session"]["device_id"]] + if ( + len(selected) != 1 + or not selected[0].link + or selected[0].session != command["session"]["session_id"] + ): + raise ValueError("Сеанс USB изменился. Обновите устройство.") + d = selected[0] + result = { + "state": "unknown", + "error": "Операция уже принята; повторная отправка запрещена.", + } + self.receipts[op] = (now, digest, result) + try: + with d.lock: + if d.session != command["session"]["session_id"] or not d.link: + raise ValueError("Сеанс USB изменился.") + result = {"state": "complete", "result": self.perform(d, action, params)} + except (OSError, ValueError, KeyError, TypeError, EOFError) as error: + result = {"state": "error", "error": str(error)[:300]} + with self.lock: + self.receipts[op] = (now, digest, result) + return result + + def perform(self, d, action, params): + if action in ("details", "verify", "can.status"): + if set(params) - {"after"}: + raise ValueError("Неизвестные параметры просмотра.") + after = integer(params.get("after", d.status["sequence"]), 0, 2**53 - 1) + status = d.call("status", {"after": after}) + else: + ch = channel(params.get("channel")) + if action == "can.configure": + if ( + set(params) != {"channel", "revision", "config"} + or params["revision"] != d.revision + ): + raise ValueError("Конфигурация изменилась. Прочитайте её заново.") + config = configuration(params["config"]) + status = d.call("configure", {"channel": ch, "config": config}) + d.revision += 1 + d.preview = None + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + saved = self.root / (d.id + ".json") + temporary = self.root / (d.id + ".tmp") + temporary.write_text( + json.dumps( + { + "revision": d.revision, + "channels": [v["config"] for v in status["channels"]], + } + ) + ) + temporary.replace(saved) + elif action == "can.transmit.preview": + if set(params) != {"channel", "plan"}: + raise ValueError("Неверные параметры передачи.") + plan = transmission(params["plan"]) + token = uuid.uuid4().hex + d.preview = (token, ch, plan, time.monotonic() + 60, d.revision, d.session) + return { + "token": token, + "channel": ch, + "plan": plan, + "expires_in": 60, + "total": len(plan["frames"]) * plan["repeat"], + } + elif action == "can.transmit.apply": + if ( + set(params) != {"channel", "token", "confirmed"} + or params["confirmed"] is not True + ): + raise ValueError("Подтвердите проверенное задание передачи.") + preview, d.preview = d.preview, None + if ( + not preview + or (preview[0], preview[1], preview[4], preview[5]) + != (params["token"], ch, d.revision, d.session) + or time.monotonic() >= preview[3] + ): + raise ValueError("Подтверждение передачи истекло.") + status = d.call("transmit", {"channel": ch, "plan": preview[2]}) + else: + if set(params) != {"channel"}: + raise ValueError("Неверные параметры канала.") + method = { + "can.start": "start", + "can.stop": "stop", + "can.clear": "clear", + "can.transmit.stop": "transmit.stop", + }[action] + d.preview = None + status = d.call(method, {"channel": ch}) + d.status = {**status, "frames": []} + return {**status, "revision": d.revision, "session_id": d.session, "device_id": d.id} diff --git a/plugins/usb-can/runtime/worker.py b/plugins/usb-can/runtime/worker.py new file mode 100644 index 00000000..4f4a7082 --- /dev/null +++ b/plugins/usb-can/runtime/worker.py @@ -0,0 +1,266 @@ +"""One isolated native-library owner per USB generation, with bounded RAM.""" + +import contextlib +import copy +import multiprocessing as mp +import threading +import time +from collections import deque +from datetime import UTC, datetime + +from .bridge import Bridges +from .contracts import DEFAULT +from .sdk import SDK + + +class Engine: + def __init__(self, sdk, clock=time.monotonic, sleep=time.sleep): + self.sdk, self.clock, self.sleep = sdk, clock, sleep + self.configs = [copy.deepcopy(DEFAULT), copy.deepcopy(DEFAULT)] + self.running = [False, False] + self.jobs = [None, None] + self.job_results = [None, None] + self.frames = deque(maxlen=2000) + self.sequence = 0 + self.evicted = 0 + self.counts = [{"rx": 0, "tx_accepted": 0, "errors": 0} for _ in range(2)] + self.day = datetime.now(UTC).date() + self.error = None + self.bridges = Bridges(self) + + def append(self, frame): + self.sequence += 1 + if len(self.frames) == self.frames.maxlen: + self.evicted += 1 + self.frames.append( + {**frame, "sequence": self.sequence, "observed_at": time.time(), "_mono": self.clock()} + ) + + def prune(self): + today = datetime.now(UTC).date() + if today != self.day: + self.frames.clear() + self.counts = [{"rx": 0, "tx_accepted": 0, "errors": 0} for _ in range(2)] + self.day = today + while self.frames and self.clock() - self.frames[0]["_mono"] >= 300: + self.frames.popleft() + + def receive(self, frame): + ch = frame["channel"] + self.counts[ch]["rx"] += 1 + self.counts[ch]["errors"] += int(frame.get("error", False)) + self.bridges.receive(frame) + if not self.bridges.occupied(ch): + self.append(frame) + + def tick(self): + self.prune() + self.bridges.expire() + for ch in range(2): + if not self.running[ch]: + continue + try: + for frame in self.sdk.receive(ch): + self.receive(frame) + job = self.jobs[ch] + if job and self.clock() >= job["next"]: + plan, index = job["plan"], job["index"] + frame = copy.deepcopy(plan["frames"][index % len(plan["frames"])]) + iteration = index // len(plan["frames"]) + if plan["increment_id"]: + frame["id"] += iteration + if plan["increment_data"] and frame["data"]: + size = len(frame["data"]) // 2 + value = (int(frame["data"], 16) + iteration) % (1 << (8 * size)) + frame["data"] = value.to_bytes(size, "big").hex().upper() + self.sdk.transmit(ch, frame) + self.counts[ch]["tx_accepted"] += 1 + self.append( + { + **frame, + "channel": ch, + "direction": "TX", + "timestamp_us": None, + "error": False, + "esi": False, + } + ) + job["index"] += 1 + job["next"] = self.clock() + plan["interval_ms"] / 1000 + self.job_results[ch] = { + "state": "running", + "accepted": job["index"], + "total": job["total"], + } + if job["index"] == job["total"]: + self.jobs[ch] = None + self.job_results[ch]["state"] = "complete" + except (OSError, ValueError) as error: + self.error = str(error)[:200] + self.job_results[ch] = {"state": "error", "message": self.error} + self.jobs[ch] = None + self.running[ch] = False + # No retry or automatic restart after uncertain transmission. + self.sdk.stop(ch) + + def dispatch(self, action, params): + if action.startswith("bridge."): + return self.bridges.dispatch(action.removeprefix("bridge."), params) + # Vendor USB enumeration can block longer than a bridge poll budget. + # Active channels already have RX error checks; Service.scan independently + # checks the exact sysfs USB generation. Status must remain a RAM snapshot + # while a bridge owns the adapter, without starving its 750 ms lease. + if action == "status" and not self.bridges.claims and not self.sdk.online(): + raise OSError("Адаптер не подтвердил связь по USB.") + ch = params.get("channel", 0) + if action != "status" and self.bridges.occupied(ch): + raise ValueError("Канал занят подключением VESC. Измените шину в настройках борта.") + if action == "configure": + if self.running[ch]: + raise ValueError("Остановите канал перед изменением параметров.") + self.configs[ch] = copy.deepcopy(params["config"]) + elif action == "start": + if self.running[ch]: + raise ValueError("Канал уже запущен.") + self.sdk.start(ch, self.configs[ch]) + self.running[ch] = True + self.error = None + elif action == "stop": + self.jobs[ch] = None + if self.job_results[ch] and self.job_results[ch]["state"] == "running": + self.job_results[ch]["state"] = "cancelled" + self.sdk.stop(ch) + self.running[ch] = False + elif action == "clear": + self.sdk.clear(ch) + self.frames = deque((f for f in self.frames if f["channel"] != ch), maxlen=2000) + self.counts[ch] = {"rx": 0, "tx_accepted": 0, "errors": 0} + elif action == "transmit": + plan = params["plan"] + if not self.running[ch] or self.configs[ch]["mode"] != "normal" or self.jobs[ch]: + raise ValueError("Для передачи нужен свободный канал в обычном режиме.") + if self.configs[ch]["protocol"] == "can" and any(f["fd"] for f in plan["frames"]): + raise ValueError("Канал настроен только на классический CAN.") + self.jobs[ch] = { + "plan": plan, + "index": 0, + "next": self.clock(), + "total": plan["repeat"] * len(plan["frames"]), + } + self.job_results[ch] = { + "state": "running", + "accepted": 0, + "total": self.jobs[ch]["total"], + } + elif action == "transmit.stop": + self.jobs[ch] = None + if self.job_results[ch] and self.job_results[ch]["state"] == "running": + self.job_results[ch]["state"] = "cancelled" + elif action != "status": + raise ValueError("Неизвестная операция.") + self.prune() + after = params.get("after", self.sequence) + frames = [ + {k: v for k, v in f.items() if k != "_mono"} + for f in self.frames + if f["sequence"] > after + ][:256] + return { + "identity": self.sdk.identity, + "channels": [ + { + "index": i, + "owner": "vesc" if self.bridges.occupied(i) else None, + "config": self.configs[i], + "running": self.running[i], + "counts": self.counts[i], + "transmission": self.job_results[i], + } + for i in range(2) + ], + "sequence": self.sequence, + "frames": frames, + "evicted": self.evicted, + "oldest_sequence": self.frames[0]["sequence"] if self.frames else self.sequence + 1, + "error": self.error, + "bus_error_counters": None, + "retention_seconds": 300, + "retention_frames": 2000, + } + + +def run(pipe, index, path): + sdk = None + try: + sdk = SDK(index, path) + engine = Engine(sdk) + pipe.send({"ok": True, "value": engine.dispatch("status", {})}) + while True: + if pipe.poll(0.02): + action, params = pipe.recv() + if action == "close": + return + try: + pipe.send({"ok": True, "value": engine.dispatch(action, params)}) + except (OSError, ValueError) as error: + pipe.send({"ok": False, "error": str(error)[:300]}) + engine.tick() + except (EOFError, BrokenPipeError): + pass + except Exception as error: + with contextlib.suppress(OSError, EOFError): + pipe.send({"ok": False, "error": str(error)[:300]}) + finally: + if sdk: + sdk.close() + pipe.close() + + +class Link: + def __init__(self, index, path): + ctx = mp.get_context("spawn") + self.pipe, child = ctx.Pipe() + self.lock = threading.Lock() + self.process = ctx.Process(target=run, args=(child, index, path), daemon=True) + self.process.start() + child.close() + try: + self.initial = self.result() + except BaseException: + self.close() + raise + + @property + def alive(self): + return self.process.is_alive() + + def result(self, timeout=6): + if not self.pipe.poll(timeout): + self.close() + raise OSError("SDK не ответил за отведённое время.") + value = self.pipe.recv() + if not value.get("ok"): + raise OSError(value.get("error", "Ошибка SDK.")) + return value["value"] + + def call(self, action, params): + with self.lock: + if not self.alive: + raise OSError("Сеанс USB завершён.") + self.pipe.send((action, params)) + return self.result(.4 if action.startswith("bridge.") else 6) + + def close(self): + if self.process.is_alive(): + try: + self.pipe.send(("close", {})) + self.process.join(0.25) + except (OSError, EOFError): + pass + if self.process.is_alive(): + self.process.terminate() + self.process.join(0.5) + if self.process.is_alive(): + self.process.kill() + self.process.join(0.5) + self.pipe.close() diff --git a/plugins/usb-can/tests/test_bridge.py b/plugins/usb-can/tests/test_bridge.py new file mode 100644 index 00000000..fbd7e728 --- /dev/null +++ b/plugins/usb-can/tests/test_bridge.py @@ -0,0 +1,150 @@ +"""Channel arbitration tests with an inert SDK only.""" + +import pytest +from test_runtime import Engine, FakeSDK + + +def setup(): + clock = [10.0] + sdk = FakeSDK() + e = Engine(sdk, lambda: clock[0], lambda seconds: clock.__setitem__(0, clock[0] + seconds)) + token = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 254})["token"] + return clock, sdk, e, token + + +def test_owner_excludes_manual_tx_and_expiry_stops_channel(): + clock, sdk, e, token = setup() + for action in ("configure", "start", "stop", "clear", "transmit", "transmit.stop"): + with pytest.raises(ValueError): + e.dispatch(action, {"channel": 0}) + clock[0] = 11 + e.tick() + assert not e.running[0] + assert not e.bridges.claims + assert not any(c[0] == "tx" for c in sdk.calls) + with pytest.raises(ValueError): + e.dispatch("bridge.poll", {"token": token}) + + +def test_confirmed_setter_and_no_replay_after_deadline(): + clock, sdk, e, token = setup() + request = {"token": token, "frames": [{"id": 0x84A, "data": "fe000500000000"}], + "deadline": 10.2} + e.dispatch("bridge.send", request) + assert sdk.calls[-1][2]["send_type"] == 2 + clock[0] = 10.3 + with pytest.raises(ValueError): + e.dispatch("bridge.send", request) + assert len([c for c in sdk.calls if c[0] == "tx"]) == 1 + + +def test_same_channel_distinct_response_addresses_and_last_close(): + clock, sdk, e, one = setup() + two = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"] + frame = {"id": 0x8FE, "channel": 0, "extended": True, "data": "4a0100"} + e.bridges.receive(frame) + assert e.dispatch("bridge.poll", {"token": one})["frames"] == [frame] + assert e.dispatch("bridge.poll", {"token": two})["frames"] == [] + e.dispatch("bridge.close", {"token": one}) + assert e.running[0] + e.dispatch("bridge.close", {"token": two}) + assert not e.running[0] + + +def test_occupied_bitrate_conflict_and_receive_overflow_end_session(): + clock, sdk, e, token = setup() + with pytest.raises(ValueError): + e.dispatch("bridge.open", {"channel": 0, "bitrate": 250000, "receive_id": 253}) + for _ in range(513): + e.bridges.receive({"id": 0x8FE, "channel": 0, "extended": True}) + with pytest.raises(ValueError): + e.dispatch("bridge.poll", {"token": token}) + assert not e.running[0] + + +def test_status_does_not_enumerate_usb_during_active_bridge(): + clock, sdk, e, token = setup() + def blocking_enumeration(): + raise AssertionError("vendor USB enumeration must not block a live CAN lease") + sdk.online = blocking_enumeration + assert e.dispatch("status", {})["channels"][0]["owner"] == "vesc" + assert e.dispatch("bridge.poll", {"token": token}) == {"frames": []} + # Status is neither a lease renewal nor a deferred command replay. + clock[0] = 11 + e.tick() + assert not e.bridges.claims and not e.running[0] + assert not any(c[0] == "tx" for c in sdk.calls) + sdk.online = lambda: False + with pytest.raises(OSError, match="USB"): + e.dispatch("status", {}) + + +def test_sysfs_detach_retires_active_bridge_even_without_sdk_online(tmp_path): + from test_runtime import Attachment, FakeLink, Service + attachments = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")] + service = Service(tmp_path, lambda: list(attachments), FakeLink) + service.scan() + device = next(iter(service.devices.values())) + link, session = device.link, device.session + request = {"adapter": device.id, "session": session, "action": "open", + "parameters": {"channel": 0, "bitrate": 500000, "receive_id": 254}} + service.bridge(request) + link.engine.sdk.online = lambda: (_ for _ in ()).throw(AssertionError("blocking USB check")) + service.scan() + assert device.link is link and device.activity is None + attachments.clear() + service.scan() + assert not link.alive and device.session != session and not service.devices + + +@pytest.mark.parametrize("code", range(256)) +def test_only_exact_read_commands_have_arbitration_retry(code): + clock, sdk, e, token = setup() + e.dispatch("bridge.send", {"token": token, + "frames": [{"id": 0x84A, "data": bytes((254, 0, code)).hex()}], + "deadline": 10.2}) + assert sdk.calls[-1][2]["send_type"] == (2 if code in (0, 4, 14, 17, 31, 62) else 1) + + +@pytest.mark.parametrize("frame", [ + {"id": 0x84A, "data": "fe000400"}, # extra argument + {"id": 0x84A, "data": "fe003e00"}, # scan with unexpected argument + {"id": 0x8FF, "data": "fe003e"}, # broadcast scan + {"id": 0x84A, "data": "fe00224a3e"}, # forwarded scan + {"id": 0x84A, "data": "fd0004"}, # different reply address + {"id": 0x84A, "data": "fe0104"}, # reply, not request + {"id": 0x84A, "data": "fe00224a04"}, # forwarded command + {"id": 0x8FF, "data": "fe0004"}, # broadcast + {"id": 0x8FE, "data": "fe0004"}, # self + {"id": 0x74A, "data": "fe0004"}, # fragmented packet completion +]) +def test_no_retry_for_ambiguous_or_forwarded_payload(frame): + clock, sdk, e, token = setup() + e.dispatch("bridge.send", {"token": token, "frames": [frame], "deadline": 10.2}) + assert sdk.calls[-1][2]["send_type"] == 1 + + +def test_read_timeout_closes_claim_without_application_replay(): + clock, sdk, e, token = setup() + request = {"token": token, "frames": [{"id": 0x84A, "data": "fe0004"}], "deadline": 10.2} + e.dispatch("bridge.send", request) + e.dispatch("bridge.close", {"token": token}) + assert not e.running[0] + with pytest.raises(ValueError): + e.dispatch("bridge.send", request) + assert len([c for c in sdk.calls if c[0] == "tx"]) == 1 + + +def test_bridge_inventory_includes_exact_os_usb_generation(tmp_path): + from test_runtime import Attachment, FakeLink, Service + attached = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")] + service = Service(tmp_path, lambda: list(attached), FakeLink) + service.scan() + first = service.bridge_inventory()["items"][0] + assert first["attachment_id"] == attached[0].id + attached[0] = Attachment("1-2:7", "1-2", "/dev/bus/usb/001/007", "480") + service.scan() + second = service.bridge_inventory()["items"][0] + assert first["id"] == second["id"] + assert first["attachment_id"] != second["attachment_id"] + assert first["session_id"] != second["session_id"] diff --git a/plugins/usb-can/tests/test_configuration_transport.py b/plugins/usb-can/tests/test_configuration_transport.py new file mode 100644 index 00000000..4af1e1ce --- /dev/null +++ b/plugins/usb-can/tests/test_configuration_transport.py @@ -0,0 +1,138 @@ +"""Configuration packet delivery and ACK fencing with an inert CAN bus.""" + +import binascii +import copy + +import pytest +from test_bridge import setup +from test_limits_transport import send + + +def configuration_frames(command=13, size=458, target=74, sender=254): + # Synthetic parameter bytes; transport does not interpret the native schema. + payload = bytes((command,)) + bytes((i * 17 + 3) % 256 for i in range(size - 1)) + frames = [] + # Upstream comm_can_send_buffer: short offsets 0..252, then long from 259. + for start in range(0, min(size, 259), 7): + frames.append({"id": 0x500 | target, "data": (bytes((start,)) + payload[start:start+7]).hex()}) + for start in range(259, size, 6): + frames.append({"id": 0x600 | target, + "data": (start.to_bytes(2, "big") + payload[start:start+6]).hex()}) + frames.append({"id": 0x700 | target, + "data": (bytes((sender, 0)) + size.to_bytes(2, "big") + + binascii.crc_hqx(payload, 0).to_bytes(2, "big")).hex()}) + return payload, frames + + +def ack(command=13, target=74, sender=254, **changes): + return {"channel": 0, "id": 0x800 | sender, "extended": True, + "data": bytes((target, 1, command)).hex(), **changes} + + +@pytest.mark.parametrize("command,size", [(13, 458), (16, 313), (13, 259), (16, 260)]) +def test_configuration_survives_arbitration_loss_and_is_submitted_only_once(command, size): + _, sdk, e, token = setup() + payload, frames = configuration_frames(command, size) + received, replies, dropped = bytearray(size), [], [] + original = sdk.transmit + + def wire(ch, value): + original(ch, value) + data, code = bytes.fromhex(value["data"]), value["id"] >> 8 + if code in (5, 6): + width = 1 if code == 5 else 2 + offset = int.from_bytes(data[:width], "big") + if offset in (14, 259) and value["send_type"] == 1: + dropped.append(offset) + return + received[offset:offset+len(data)-width] = data[width:] + elif code == 7 and binascii.crc_hqx(received, 0) == int.from_bytes(data[4:], "big"): + replies.append(ack(command)) + + sdk.transmit = wire + send(e, token, frames) + assert not dropped and bytes(received) == payload and replies == [ack(command)] + assert len([c for c in sdk.calls if c[0] == "tx"]) == len(frames) + assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": command} + e.bridges.receive(replies[0]) + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("command", [5, 6, 8, 12, 14, 17, 34, 48, 49, 58, 255]) +def test_no_arbitration_retry_for_other_long_commands(command): + _, sdk, e, token = setup() + send(e, token, configuration_frames(command)[1]) + assert all(c[2]["send_type"] == 1 for c in sdk.calls if c[0] == "tx") + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("case", ["offset", "missing", "duplicate", "crc", "target", "sender", + "broadcast", "self", "length", "short-chunk", "long-code", "extra-commit"]) +def test_incomplete_or_ambiguous_configuration_is_not_promoted(case): + _, sdk, e, token = setup() + frames = copy.deepcopy(configuration_frames()[1]) + if case == "offset": frames[37]["data"] = "0104" + frames[37]["data"][4:] + elif case == "missing": frames.pop(37) + elif case == "duplicate": frames[38] = frames[37].copy() + elif case == "crc": frames[-1]["data"] = frames[-1]["data"][:-4] + "0000" + elif case == "target": frames[37]["id"] += 1 + elif case == "sender": frames[-1]["data"] = "fd" + frames[-1]["data"][2:] + elif case == "broadcast": frames = configuration_frames(target=255)[1] + elif case == "self": frames = configuration_frames(target=254)[1] + elif case == "length": frames[-1]["data"] = frames[-1]["data"][:4] + "01cb" + frames[-1]["data"][8:] + elif case == "short-chunk": frames[2]["data"] = frames[2]["data"][:-2] + elif case == "long-code": frames[37]["id"] = 0x54A + elif case == "extra-commit": frames.append(frames[-1].copy()) + send(e, token, frames) + assert all(c[2]["send_type"] == 1 for c in sdk.calls if c[0] == "tx") + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("command", [13, 16]) +def test_only_configuration_exact_ack_releases_fence(command): + _, _, e, token = setup() + send(e, token, configuration_frames(command)[1]) + for wrong in (ack(48), ack(16 if command == 13 else 13), ack(command, target=75), + ack(command, sender=253), ack(command, fd=True), ack(command, rtr=True), + ack(command, error=True), ack(command, channel=1), ack(command, data="4a010d00")): + e.bridges.receive(wrong) + assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": command} + e.bridges.receive(ack(command)) + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("reason", ["close", "expire", "second-send"]) +def test_unconfirmed_config_discards_channel_queue_and_other_claims(reason): + clock, sdk, e, token = setup() + other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"] + frames = configuration_frames()[1] + send(e, token, frames) + if reason == "close": e.dispatch("bridge.close", {"token": token}) + elif reason == "expire": + clock[0] = 11 + e.tick() + else: + with pytest.raises(ValueError, match="Подтверждение"): + send(e, token, frames) + assert not e.running[0] and not e.bridges.claims + assert sdk.calls[-1] == ("stop", 0) + assert len([c for c in sdk.calls if c[0] == "tx"]) == len(frames) + e.bridges.receive(ack()) + for owner in (token, other): + with pytest.raises(ValueError): e.dispatch("bridge.poll", {"token": owner}) + + +def test_partial_config_deadline_drops_queued_fragments_without_commit(): + clock, sdk, e, token = setup() + original = sdk.transmit + + def slow(ch, value): + original(ch, value) + clock[0] += .11 + + sdk.transmit = slow + with pytest.raises(ValueError, match="истёк"): + send(e, token, configuration_frames()[1]) + sent = [c[2] for c in sdk.calls if c[0] == "tx"] + assert len(sent) == 2 and all(c["id"] >> 8 == 5 for c in sent) + assert not e.running[0] and not e.bridges.claims and sdk.calls[-1] == ("stop", 0) diff --git a/plugins/usb-can/tests/test_confirmed_tx.py b/plugins/usb-can/tests/test_confirmed_tx.py new file mode 100644 index 00000000..812e8d40 --- /dev/null +++ b/plugins/usb-can/tests/test_confirmed_tx.py @@ -0,0 +1,107 @@ +"""CAN arbitration and ambiguous completion, with no hardware or motor RPCs.""" +import pytest +from test_bridge import setup +from usbcan_test_runtime.confirmed_tx import ECHO_TIMEOUT + + +def request(token, payload=b'\x05\x00\x00\x4a\x38', deadline=10.2): + return {'token': token, 'frames': [{'id': 0x84a, 'data': (b'\xfe\x00'+payload).hex()}], + 'deadline': deadline} + + +@pytest.mark.parametrize('payload', [b'\x05\x00\x00\x4a\x38', b'\x06'+b'\x00'*4, + b'\x08'+(3000).to_bytes(4,'big'), b'\x3f\x00\x00\x00\x00\xfa']) +def test_lost_arbitration_waits_for_echo_before_success_without_app_replay(payload): + clock, sdk, e, token = setup() + original = sdk.receive + def receive(ch): + # Hardware controller is still arbitrating; SDK accepted already. + if sdk.echoes[ch] and clock[0] < 10.007: + return [] + return original(ch) + sdk.receive = receive + result = e.dispatch('bridge.send', request(token, payload)) + assert 10.007 <= clock[0] < 10.009 + assert result['tx_confirmation']['confirmed'] == 1 + assert result['tx_confirmation']['kind'] == 'adapter_echo' + assert len([c for c in sdk.calls if c[0]=='tx']) == 1 + assert sdk.calls[-1][2]['send_type'] == 2 + assert e.running[0] + + +@pytest.mark.parametrize('fault', ['lost', 'late', 'wrong_payload', 'wrong_id', 'wrong_channel', 'rtr', 'error', 'standard', 'fd']) +def test_no_completion_fails_closed_resets_shared_channel_and_never_replays(fault): + clock, sdk, e, token = setup() + other = e.dispatch('bridge.open', {'channel':0,'bitrate':500000,'receive_id':253})['token'] + original = sdk.receive + def receive(ch): + if fault == 'lost': return [] + frames = original(ch) + if frames: + if fault == 'late': clock[0] += .1 + elif fault == 'wrong_payload': frames[0]['data']='00' + elif fault == 'wrong_id': frames[0]['id']=0x84b + elif fault == 'wrong_channel': frames[0]['channel']=1 + elif fault == 'standard': frames[0]['extended']=False + else: frames[0][fault]=True + return frames + sdk.receive = receive + with pytest.raises(OSError): e.dispatch('bridge.send', request(token)) + assert not e.running[0] and not e.bridges.claims + assert sdk.calls[-1] == ('stop',0) + for value in (token,other): + with pytest.raises(ValueError): e.dispatch('bridge.send',request(value)) + assert len([c for c in sdk.calls if c[0]=='tx'])==1 + + +def test_request_deadline_wins_over_echo_budget(): + clock, sdk, e, token = setup() + sdk.receive=lambda ch: [] + with pytest.raises(OSError): e.dispatch('bridge.send',request(token,deadline=10.003)) + assert clock[0] < 10.004 and not e.running[0] + + +def test_stale_buffered_echo_cannot_confirm_new_send(): + clock, sdk, e, token=setup() + e.dispatch('bridge.send',request(token)) + echo=dict(sdk.calls[-1][2],channel=0,error=False) + sdk.echoes[0].append(echo) + original=sdk.transmit + def lose(ch, value): + original(ch,value) + sdk.echoes[ch].clear() + sdk.transmit=lose + with pytest.raises(OSError): e.dispatch('bridge.send',request(token)) + assert clock[0] >= 10+ECHO_TIMEOUT + + +def test_unrelated_read_response_is_preserved_during_confirmation(): + clock,sdk,e,token=setup() + rx={'channel':0,'id':0x8fe,'extended':True,'data':'4a0100','dlc':3,'error':False} + original=sdk.receive + def receive(ch): + frames=original(ch) + return [rx,*frames] if frames else [] + sdk.receive=receive + result=e.dispatch('bridge.send',request(token)) + assert result['frames']==[rx] + + +def test_sdk_exception_after_enqueue_discards_every_shared_claim(): + clock,sdk,e,token=setup() + e.dispatch('bridge.open',{'channel':0,'bitrate':500000,'receive_id':253}) + original=sdk.transmit + def broken(ch,value): + original(ch,value) + raise OSError('uncertain SDK completion') + sdk.transmit=broken + with pytest.raises(OSError):e.dispatch('bridge.send',request(token)) + assert not e.bridges.claims and not e.running[0] + + +@pytest.mark.parametrize('payload',[b'\x05',b'\x05'+b'\0'*3,b'\x05'+b'\0'*5, + b'\x3f\x01\0\0\0\xfa',b'\x3f\0\0\0\1\0',b'\x3f\0\0\0\0\0',b'\x22\x4a\x05\0\0\0']) +def test_unclassified_or_forwarded_command_never_gains_hardware_retry(payload): + clock,sdk,e,token=setup() + e.dispatch('bridge.send',request(token,payload)) + assert sdk.calls[-1][2]['send_type']==1 diff --git a/plugins/usb-can/tests/test_limits_transport.py b/plugins/usb-can/tests/test_limits_transport.py new file mode 100644 index 00000000..156bd669 --- /dev/null +++ b/plugins/usb-can/tests/test_limits_transport.py @@ -0,0 +1,171 @@ +"""Volatile configuration delivery under an inert arbitration-loss model.""" + +import binascii +import copy +import struct + +import pytest +from test_bridge import setup + + +def frames(payload=None, target=74, sender=254): + # Firmware 5.02: command, store/forward/ack/divide, eight float32 values. + payload = payload if payload is not None else bytes((48, 0, 0, 1, 0)) + struct.pack( + ">8f", .2, .2, -100000, 100000, .005, .95, -1500000, 1500000) + result = [{"id": (5 << 8) | target, + "data": (bytes((i,)) + payload[i:i+7]).hex()} + for i in range(0, len(payload), 7)] + result.append({"id": (7 << 8) | target, + "data": (bytes((sender, 0)) + len(payload).to_bytes(2, "big") + + binascii.crc_hqx(payload, 0).to_bytes(2, "big")).hex()}) + return result + + +def send(e, token, value): + return e.dispatch("bridge.send", {"token": token, "frames": value, "deadline": 10.2}) + + +def ack(target=74, sender=254, **changes): + return {"channel": 0, "id": (8 << 8) | sender, "extended": True, + "data": bytes((target, 1, 48)).hex(), **changes} + + +def test_complete_limits_survive_inert_arbitration_loss_without_application_replay(): + clock, sdk, e, token = setup() + original = sdk.transmit + received, replies, dropped = bytearray(37), [], [] + + def wire(ch, value): + original(ch, value) + # An independent bus model: single-shot loses one arbitration and is + # discarded; normal controller transmission eventually delivers it. + data = bytes.fromhex(value["data"]) + if value["id"] >> 8 == 5: + if data[0] == 7 and value["send_type"] == 1: + dropped.append(value) + return + received[data[0]:data[0]+len(data)-1] = data[1:] + else: + if binascii.crc_hqx(received, 0) == int.from_bytes(data[4:6], "big"): + replies.append(ack()) + + sdk.transmit = wire + value = frames() + send(e, token, value) + assert not dropped and replies == [ack()] + assert len([v for v in sdk.calls if v[0] == "tx"]) == 7 + assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": 48} + e.bridges.receive(replies[0]) + assert e.bridges.claims[token]["write_pending"] is None + assert e.dispatch("bridge.poll", {"token": token})["frames"] == replies + + +@pytest.mark.parametrize("change", [ + (0, 5), (0, 49), (1, 1), (2, 1), (3, 0), (4, 1), +]) +def test_mutations_other_than_exact_acknowledged_volatile_limits_stay_single_shot(change): + clock, sdk, e, token = setup() + payload = bytearray(bytes((48, 0, 0, 1, 0)) + struct.pack( + ">8f", .2, .2, -100000, 100000, .005, .95, -1500000, 1500000)) + payload[change[0]] = change[1] + send(e, token, frames(bytes(payload))) + assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx") + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("case", ["offset", "missing", "duplicate", "crc", "target", + "reply", "broadcast", "self", "length", "short-chunk"]) +def test_ambiguous_fragments_never_get_hardware_retry(case): + clock, sdk, e, token = setup() + value = copy.deepcopy(frames()) + if case == "offset": + value[1]["data"] = "08" + value[1]["data"][2:] + elif case == "missing": + value.pop(2) + elif case == "duplicate": + value[2] = value[1].copy() + elif case == "crc": + value[-1]["data"] = value[-1]["data"][:-4] + "0000" + elif case == "target": + value[1]["id"] += 1 + elif case == "reply": + value[-1]["data"] = "fd" + value[-1]["data"][2:] + elif case == "broadcast": + value = frames(target=255) + elif case == "self": + value = frames(target=254) + elif case == "length": + value[-1]["data"] = value[-1]["data"][:4]+"0026"+value[-1]["data"][8:] + elif case == "short-chunk": + value[1]["data"] = value[1]["data"][:-2] + send(e, token, value) + assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx") + + +@pytest.mark.parametrize("scale", [0., -1., 1.01, float("inf"), float("nan")]) +def test_invalid_limits_never_get_hardware_retry(scale): + clock, sdk, e, token = setup() + payload = bytes((48, 0, 0, 1, 0)) + struct.pack( + ">8f", scale, .2, -100000, 100000, .005, .95, -1500000, 1500000) + send(e, token, frames(payload)) + assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx") + + +def test_only_exact_ack_clears_pending_write(): + clock, sdk, e, token = setup() + send(e, token, frames()) + for wrong in (ack(target=75), ack(sender=253), ack(fd=True), ack(rtr=True), + ack(error=True), ack(data="4a0130ff"), ack(data="4a013e")): + e.bridges.receive(wrong) + assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": 48} + e.bridges.receive(ack()) + assert e.bridges.claims[token]["write_pending"] is None + + +@pytest.mark.parametrize("reason", ["close", "expire", "second-send"]) +def test_unconfirmed_write_resets_channel_and_retires_other_claims(reason): + clock, sdk, e, token = setup() + other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"] + send(e, token, frames()) + if reason == "close": + e.dispatch("bridge.close", {"token": token}) + elif reason == "expire": + clock[0] = 11 + e.tick() + else: + with pytest.raises(ValueError, match="Подтверждение"): + send(e, token, frames()) + assert not e.running[0] and not e.bridges.claims + assert sdk.calls[-1] == ("stop", 0) + assert len([v for v in sdk.calls if v[0] == "tx"]) == 7 + e.bridges.receive(ack()) # A late ACK cannot resurrect either owner. + for t in (token, other): + with pytest.raises(ValueError): + e.dispatch("bridge.poll", {"token": t}) + + +def test_acknowledged_write_does_not_retire_an_independent_reader(): + clock, sdk, e, token = setup() + other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"] + send(e, token, frames()) + e.bridges.receive(ack()) + e.dispatch("bridge.close", {"token": token}) + assert e.running[0] and other in e.bridges.claims + e.dispatch("bridge.close", {"token": other}) + assert not e.running[0] + + +def test_partial_send_deadline_discards_queue_and_never_replays_commit(): + clock, sdk, e, token = setup() + original = sdk.transmit + + def slow(ch, value): + original(ch, value) + clock[0] += .11 + + sdk.transmit = slow + with pytest.raises(ValueError, match="истёк"): + send(e, token, frames()) + sent = [v[2] for v in sdk.calls if v[0] == "tx"] + assert len(sent) == 2 and all(v["id"] >> 8 == 5 for v in sent) + assert sdk.calls[-1] == ("stop", 0) and not e.bridges.claims diff --git a/plugins/usb-can/tests/test_runtime.py b/plugins/usb-can/tests/test_runtime.py new file mode 100644 index 00000000..a91f1317 --- /dev/null +++ b/plugins/usb-can/tests/test_runtime.py @@ -0,0 +1,317 @@ +# Runtime lives in a hyphenated plugin directory; load the package before imports. +# ruff: noqa: E402 +"""Synthetic contract tests. These never load the SDK or open hardware.""" + +import importlib.util +import sys +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location( + "usbcan_test_runtime", + ROOT / "runtime/__init__.py", + submodule_search_locations=[str(ROOT / "runtime")], +) +runtime = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = runtime +spec.loader.exec_module(runtime) +from usbcan_test_runtime.contracts import DEFAULT, configuration, frame, transmission +from usbcan_test_runtime.discovery import Attachment, discover +from usbcan_test_runtime.sdk import check_abi +from usbcan_test_runtime.service import Service +from usbcan_test_runtime.worker import Engine + + +def sample(**updates): + return { + "id": 74, + "extended": True, + "fd": False, + "rtr": False, + "brs": False, + "data": "00FF", + "dlc": 2, + "send_type": 1, + **updates, + } + + +def plan(**updates): + return { + "frames": [sample()], + "repeat": 1, + "interval_ms": 10, + "increment_id": False, + "increment_data": False, + **updates, + } + + +class FakeSDK: + identity = { + "serial": "SYNTHETIC-ONLY", + "channels": 2, + "model": "USBCANFD0002", + "hardware": "1.00", + "firmware": "1.00", + "driver": "1.00", + "interface": "1.00", + } + + def __init__(self): + self.calls = [] + self.echoes = [[], []] + + def start(self, ch, config): + self.calls.append(("start", ch)) + + def stop(self, ch): + self.calls.append(("stop", ch)) + + def clear(self, ch): + self.calls.append(("clear", ch)) + + def receive(self, ch): + frames, self.echoes[ch] = self.echoes[ch], [] + return frames + + def transmit(self, ch, value): + self.calls.append(("tx", ch, value)) + if value["send_type"] == 2: + self.echoes[ch].append({**value, "channel": ch, "direction": "RX", "error": False}) + + def online(self): + return True + + def close(self): + self.calls.append(("close",)) + + +class FakeLink: + def __init__(self, index, path): + self.engine = Engine(FakeSDK()) + self.initial = self.engine.dispatch("status", {}) + self.alive = True + + def call(self, action, params): + return self.engine.dispatch(action, params) + + def close(self): + self.alive = False + + +def command(d, action, params=None, identifier="a" * 32): + now = datetime.now(UTC) + return { + "api_version": runtime.SCHEMA, + "kind": "OperationRequest", + "operation_id": "op_" + identifier, + "idempotency_key": "op_" + identifier, + "session": {"device_id": d.id, "session_id": d.session}, + "requested_at": now.isoformat(), + "deadline_at": (now + timedelta(seconds=50)).isoformat(), + "action_id": action, + "parameters": params or {}, + } + + +def test_exact_abi_and_safe_defaults(): + check_abi() + sdk = FakeSDK() + engine = Engine(sdk) + engine.tick() + assert not sdk.calls + assert all( + c["config"]["mode"] == "listen" and not c["running"] + for c in engine.dispatch("status", {})["channels"] + ) + + +@pytest.mark.parametrize( + "update", + [ + {"id": 0x800, "extended": False}, + {"dlc": 9}, + {"fd": True, "rtr": True}, + {"brs": True}, + {"data": "ZZ"}, + {"id": True}, + {"fd": True, "dlc": 10, "data": "00" * 10}, + ], +) +def test_reject_invalid_frames(update): + with pytest.raises(ValueError): + frame(sample(**update)) + + +def test_filter_and_job_bounds(): + with pytest.raises(ValueError): + configuration({**DEFAULT, "filters": [{"extended": True, "start": 0, "end": 10}] * 33}) + with pytest.raises(ValueError): + transmission(plan(repeat=1000, interval_ms=1000)) + with pytest.raises(ValueError): + transmission(plan(frames=[sample(id=0x7FF, extended=False)], repeat=2, increment_id=True)) + assert ( + len( + configuration({**DEFAULT, "filters": [{"extended": False, "start": 0, "end": 1}] * 64})[ + "filters" + ] + ) + == 64 + ) + + +def test_tx_requires_normal_running_channel_and_cancellation_stops_queue(): + sdk = FakeSDK() + clock = [0.0] + engine = Engine(sdk, lambda: clock[0]) + with pytest.raises(ValueError): + engine.dispatch("transmit", {"channel": 0, "plan": plan()}) + engine.dispatch("start", {"channel": 0}) + with pytest.raises(ValueError): + engine.dispatch("transmit", {"channel": 0, "plan": plan()}) + engine.dispatch("stop", {"channel": 0}) + engine.dispatch("configure", {"channel": 0, "config": {**DEFAULT, "mode": "normal"}}) + engine.dispatch("start", {"channel": 0}) + engine.dispatch("transmit", {"channel": 0, "plan": plan(repeat=2)}) + engine.tick() + engine.dispatch("transmit.stop", {"channel": 0}) + clock[0] += 1 + engine.tick() + assert len([c for c in sdk.calls if c[0] == "tx"]) == 1 + + +def test_rx_retention_is_bounded_and_expires(): + clock = [0.0] + engine = Engine(FakeSDK(), lambda: clock[0]) + for i in range(2100): + engine.append({"channel": 0, "direction": "RX", "id": i}) + assert len(engine.frames) == 2000 and engine.evicted == 100 + assert len(engine.dispatch("status", {"after": 0})["frames"]) == 256 + clock[0] = 301 + assert engine.dispatch("status", {"after": 0})["frames"] == [] + + +def test_hotplug_changes_session_preserves_identity_and_never_resumes(tmp_path): + attachments = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")] + service = Service(tmp_path, lambda: list(attachments), FakeLink) + service.scan() + old = next(iter(service.devices.values())) + old_id, old_session = old.id, old.session + service.execute( + command( + old, + "can.configure", + {"channel": 0, "revision": 0, "config": {**DEFAULT, "mode": "normal"}}, + ) + ) + service.execute(command(old, "can.start", {"channel": 0}, "b" * 32)) + stale = command(old, "can.start", {"channel": 0}, "c" * 32) + attachments.clear() + service.scan() + attachments.append(Attachment("1-7:9", "1-7", "/dev/bus/usb/001/009", "480")) + service.scan() + new = next(iter(service.devices.values())) + assert new.id == old_id and new.session != old_session + assert not any(c["running"] for c in new.status["channels"]) + assert new.status["channels"][0]["config"]["mode"] == "normal" + with pytest.raises(ValueError): + service.execute(stale) + + +def test_preview_one_use_and_repeated_request_never_duplicates(tmp_path): + attachment = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480") + service = Service(tmp_path, lambda: [attachment], FakeLink) + service.scan() + d = next(iter(service.devices.values())) + service.execute( + command( + d, + "can.configure", + {"channel": 0, "revision": 0, "config": {**DEFAULT, "mode": "normal"}}, + ) + ) + service.execute(command(d, "can.start", {"channel": 0}, "b" * 32)) + preview = service.execute( + command(d, "can.transmit.preview", {"channel": 0, "plan": plan()}, "c" * 32) + )["result"] + request = command( + d, + "can.transmit.apply", + {"channel": 0, "token": preview["token"], "confirmed": True}, + "d" * 32, + ) + first = service.execute(request) + assert service.execute(request) == first + assert ( + service.execute(command(d, "can.transmit.apply", request["parameters"], "e" * 32))["state"] + == "error" + ) + d.link.engine.tick() + assert len([c for c in d.link.engine.sdk.calls if c[0] == "tx"]) == 1 + assert not list(tmp_path.glob("op_*")) + + +def test_discovery_requires_exact_model_and_ignores_usb_serial(tmp_path): + p = tmp_path / "1-5" + p.mkdir() + for name, value in { + "idVendor": "04d8", + "idProduct": "0053", + "product": "USB CANFD DEBUG", + "serial": "Љ", + "devnum": "6", + "busnum": "1", + "speed": "480", + }.items(): + (p / name).write_text(value) + found = discover(tmp_path) + assert len(found) == 1 and found[0].binding == "1-5:6" + (p / "product").write_text("Different device") + assert discover(tmp_path) == [] + + +def test_prepare_returns_confirmed_identity_and_refuses_active_channel(tmp_path): + a = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480") + service = Service(tmp_path, lambda: [a], FakeLink) + service.scan() + d = next(iter(service.devices.values())) + result = service.execute(command(d, "verify")) + assert result["result"]["device_id"] == d.id + assert service.prepare_safe() + service.execute(command(d, "can.start", {"channel": 0}, "b" * 32)) + assert not service.prepare_safe() + + +def test_usb_owner_recovery_rejects_previous_session(tmp_path): + a = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480") + service = Service(tmp_path, lambda: [a], FakeLink) + service.scan() + d = next(iter(service.devices.values())) + stale = command(d, "can.start", {"channel": 0}) + d.link.alive = False + d.retry_at = 0 + service.scan() + with pytest.raises(ValueError): + service.execute(stale) + + + +def test_preparation_verify_accepts_node_deadline_without_widening_can_commands(tmp_path): + attachment = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480") + service = Service(tmp_path, lambda: [attachment], FakeLink) + service.scan() + d = next(iter(service.devices.values())) + request = command(d, "verify") + start = datetime.fromisoformat(request["requested_at"]) + request["deadline_at"] = (start + timedelta(seconds=350)).isoformat() + assert service.execute(request)["state"] == "complete" + assert not d.link.engine.sdk.calls + request["action_id"] = "can.start" + request["parameters"] = {"channel": 0} + request["operation_id"] = request["idempotency_key"] = "op_" + "b" * 32 + with pytest.raises(ValueError, match="Срок"): + service.execute(request)