poe-svelte-ui-lib 2.31.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,10 +64,11 @@ node.messages(125) // последние сообщения узла с част
64
64
  ```
65
65
 
66
66
  - 💓 Раз в секунду шлёт свой `NodeStatus` и отвечает на `GetNodeInfo` своим именем.
67
- - 🆔 Сервер назначения номеров (DNA), как у ArduPilot: узел без номера (например, GNSS без автопилота на шине) получает свободный номер сверху от 125, при повторном запросе - тот же.
67
+ - 🆔 Сервер назначения номеров (DNA), как у ArduPilot: узел без номера (например, GNSS без автопилота на шине) получает свободный номер сверху от 125. Тот же модуль после перезагрузки получает прежний номер: сервер помнит уникальный ID каждого выданного номера и каждого узла из его GetNodeInfo.
68
68
  - 🔎 Новый узел по `NodeStatus` сам опрашивается `GetNodeInfo`: имя, версии прошивки и железа, уникальный ID. Перезагрузку узла видно по сбросу времени работы.
69
69
  - ⏳ Запросы одному узлу уходят по одному, следующий - после ответа или тайм-аута: простые устройства теряют запросы, идущие вплотную. Нет ответа - повтор, потом ошибка.
70
70
  - ⚠️ Узел с нашим номером на шине - `onConflict`.
71
+ - 💾 Обновление прошивки: `updateFirmware(node, data, { onProgress })`. Узел получает `BeginFirmwareUpdate` с нашим номером и путём файла, перезагружается в загрузчик и сам читает файл с нашего узла (`file.Read` по 256 байт, ответ короче - конец файла). Ход - по чтениям: `start`, `read` (байты из размера), `reboot`, `done` (узел снова прислал `NodeStatus` в рабочем режиме). Узел отказал - ошибка с кодом и текстом узла, перестал читать на 20 с - ошибка. Свой файл для других узлов - `serveFile(path, data)`, отвечаем и на `file.GetInfo`.
71
72
 
72
73
  ### 📈 Автографики
73
74
 
@@ -9,7 +9,7 @@ export * from "./node.js";
9
9
  export * from "./plot.js";
10
10
  export declare const droneCanTypeOf: (id: Pick<DroneCanId, "type" | "dataTypeId" | "source">) => DroneCanTypeDef | undefined;
11
11
  export declare const createDroneCanTransferReceiver: (timeoutMs?: number) => {
12
- push(canId: number, data: Uint8Array, now?: number): DroneCanTransfer | undefined;
12
+ push(canId: number, data: Uint8Array, now?: number, fd?: boolean): DroneCanTransfer | undefined;
13
13
  reset(): void;
14
14
  };
15
15
  export interface DroneCanDecoded {
@@ -20,7 +20,8 @@ export const decodeDroneCanTransfer = (t) => {
20
20
  if (!t.crcOk)
21
21
  return { typeName: def.name, error: "CRC" };
22
22
  try {
23
- return { typeName: def.name, value: decodeDroneCan(droneCanStruct(def, t.type), t.payload) };
23
+ /* CAN FD - без TAO: хвостовой массив передаётся с длиной, нули дополнения в конце не мешают */
24
+ return { typeName: def.name, value: decodeDroneCan(droneCanStruct(def, t.type), t.payload, !t.fd) };
24
25
  }
25
26
  catch (error) {
26
27
  return { typeName: def.name, error: error instanceof Error ? error.message : String(error) };
@@ -5,6 +5,7 @@ export declare const DRONECAN_OFFLINE_MS = 3000;
5
5
  export declare const DRONECAN_OPCODE_SAVE = 0;
6
6
  export declare const DRONECAN_OPCODE_ERASE = 1;
7
7
  export declare const DRONECAN_RESTART_MAGIC = 742196058910;
8
+ export declare const DRONECAN_FILE_CHUNK = 256;
8
9
  export type DroneCanParamKind = "empty" | "integer" | "real" | "boolean" | "string";
9
10
  export type DroneCanParamScalar = number | bigint | boolean | string | null;
10
11
  export interface DroneCanParam {
@@ -68,6 +69,11 @@ export declare const droneCanParamValue: (union: unknown) => {
68
69
  value: DroneCanParamScalar;
69
70
  };
70
71
  export declare const droneCanParamUnion: (kind: DroneCanParamKind, value: unknown) => Record<string, unknown>;
72
+ export interface DroneCanFirmwareProgress {
73
+ phase: "start" | "read" | "reboot" | "done";
74
+ bytes: number;
75
+ size: number;
76
+ }
71
77
  export interface DroneCanNodeOptions {
72
78
  nodeId: number;
73
79
  write: (canId: number, frames: Uint8Array[]) => Promise<unknown>;
@@ -98,6 +104,13 @@ export interface DroneCanNode {
98
104
  nodes(): DroneCanBusNode[];
99
105
  messages(id: number): DroneCanMessage[];
100
106
  allocations(): Map<string, number>;
107
+ serveFile(path: string, data: Uint8Array | null): void;
108
+ updateFirmware(node: number, data: Uint8Array, options?: {
109
+ path?: string;
110
+ onProgress?: (p: DroneCanFirmwareProgress) => void;
111
+ idleTimeoutMs?: number;
112
+ rebootTimeoutMs?: number;
113
+ }): Promise<void>;
101
114
  dispose(): void;
102
115
  }
103
116
  export declare const createDroneCanNode: ({ nodeId, write, name, allocator, onTransmit, onNodes, onConflict, onAllocate, requestTimeoutMs, now, }: DroneCanNodeOptions) => DroneCanNode;
@@ -1,6 +1,6 @@
1
1
  /* src/lib/protocols/dronecan/node.ts - свой узел на шине DroneCAN: NodeStatus раз в секунду, ответ на GetNodeInfo, сервер динамического назначения Node ID (DNA, как у ArduPilot),
2
2
  узлы шины (NodeStatus, GetNodeInfo по первому появлению), последние сообщения узлов с частотой, запросы сервисов с ожиданием ответа (по одному на узел - простые устройства теряют запросы вплотную),
3
- параметры узла: список, чтение, запись, сохранение, сброс, перезагрузка */
3
+ параметры узла: список, чтение, запись, сохранение, сброс, перезагрузка; файловый сервер (file.Read, file.GetInfo) и обновление прошивки узла (BeginFirmwareUpdate) */
4
4
  import { droneCanType } from "./codec.js";
5
5
  import { decodeDroneCanTransfer, encodeDroneCanTransfer } from "./index.js";
6
6
  /* Состояние узла из NodeStatus: health 0..3, mode 0..7 */
@@ -13,6 +13,14 @@ export const DRONECAN_OPCODE_SAVE = 0;
13
13
  export const DRONECAN_OPCODE_ERASE = 1;
14
14
  /* Магическое число RestartNode */
15
15
  export const DRONECAN_RESTART_MAGIC = 0xacce551b1e;
16
+ /* file.Read отдаёт до 256 байт; ответ короче - конец файла */
17
+ export const DRONECAN_FILE_CHUNK = 256;
18
+ /* Коды uavcan.protocol.file.Error */
19
+ const FILE_OK = 0;
20
+ const FILE_NOT_FOUND = 2;
21
+ /* Ответы BeginFirmwareUpdate: 0 - начал, 2 - уже обновляется (тоже годится: загрузчик продолжит читать) */
22
+ const FW_OK = 0;
23
+ const FW_IN_PROGRESS = 2;
16
24
  /* Значение параметра union uavcan.protocol.param.Value -> {kind, value} */
17
25
  export const droneCanParamValue = (union) => {
18
26
  if (!union || typeof union !== "object")
@@ -131,6 +139,10 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
131
139
  software: info.software_version,
132
140
  hardware: info.hardware_version,
133
141
  };
142
+ /* Уникальный ID узла - его номер для DNA: тот же модуль после перезагрузки получит прежний номер */
143
+ const uid = uidBytes(entry.info.hardware?.unique_id);
144
+ if (uid.length === 16)
145
+ allocations.set(uidKey(uid), id);
134
146
  })
135
147
  .catch(() => { })
136
148
  .finally(() => {
@@ -139,10 +151,12 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
139
151
  });
140
152
  };
141
153
  /* Сервер DNA: узел без номера шлёт анонимно Allocation с уникальным ID частями (6+6+4 байта), сервер после каждой части повторяет собранное;
142
- собрано 16 байт - номер: тот же, что раньше этому ID, желаемый, если свободен, иначе свободный сверху от 125 */
154
+ собрано 16 байт - номер: тот же, что раньше этому ID (выданный нами или из GetNodeInfo узла), желаемый, если свободен, иначе свободный сверху от 125 */
143
155
  const allocations = new Map();
144
156
  let uidBuffer = [];
145
157
  const uidKey = (uid) => uid.map((b) => b.toString(16).padStart(2, "0")).join("");
158
+ /* Уникальный ID из кодека: массив байт или строка, если байты печатные */
159
+ const uidBytes = (raw) => Array.from(typeof raw === "string" ? new TextEncoder().encode(raw) : Array.isArray(raw) ? raw : []);
146
160
  const freeId = (preferred) => {
147
161
  const busy = new Set([nodeId, ...nodes.keys(), ...allocations.values()]);
148
162
  if (preferred >= 1 && preferred <= 125 && !busy.has(preferred))
@@ -153,8 +167,7 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
153
167
  return 0;
154
168
  };
155
169
  const allocate = (msg) => {
156
- const raw = msg.unique_id;
157
- const part = Array.from(typeof raw === "string" ? new TextEncoder().encode(raw) : Array.isArray(raw) ? raw : []);
170
+ const part = uidBytes(msg.unique_id);
158
171
  if (msg.first_part_of_unique_id)
159
172
  uidBuffer = part;
160
173
  else if (uidBuffer.length)
@@ -180,6 +193,30 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
180
193
  if (uidBuffer.length >= 16)
181
194
  uidBuffer = [];
182
195
  };
196
+ /* Файловый сервер: путь -> данные; чтения - чтобы обновление прошивки видело ход */
197
+ const files = new Map();
198
+ const readWatchers = new Set();
199
+ const pathText = (path) => {
200
+ const raw = path?.path;
201
+ return typeof raw === "string" ? raw : Array.isArray(raw) ? String.fromCharCode(...raw) : "";
202
+ };
203
+ const respond = (t, typeName, value) => void transmit({ typeName, type: "res", destination: t.source, transferId: t.transferId, priority: t.priority, value }, true).catch(() => { });
204
+ const serveFileRequest = (t, typeName, value) => {
205
+ const path = pathText(value.path);
206
+ const data = files.get(path);
207
+ if (typeName === "uavcan.protocol.file.GetInfo") {
208
+ respond(t, typeName, data
209
+ ? { size: data.length, error: { value: FILE_OK }, entry_type: { flags: 1 | 8 } }
210
+ : { size: 0, error: { value: FILE_NOT_FOUND }, entry_type: { flags: 0 } });
211
+ return;
212
+ }
213
+ const offset = Number(value.offset ?? 0);
214
+ if (!data)
215
+ return respond(t, typeName, { error: { value: FILE_NOT_FOUND }, data: [] });
216
+ respond(t, typeName, { error: { value: FILE_OK }, data: data.subarray(offset, offset + DRONECAN_FILE_CHUNK) });
217
+ for (const watch of readWatchers)
218
+ watch(path, offset, t.source);
219
+ };
183
220
  let conflict = false;
184
221
  const statusTimer = setInterval(() => {
185
222
  void transmit({ typeName: "uavcan.protocol.NodeStatus", type: "msg", value: status(), transferId: nextTransferId("msg:NodeStatus"), priority: 30 }, true).catch(() => { });
@@ -211,6 +248,13 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
211
248
  }
212
249
  return;
213
250
  }
251
+ if (t.type === "req" &&
252
+ t.destination === nodeId &&
253
+ decoded?.value &&
254
+ (decoded.typeName === "uavcan.protocol.file.Read" || decoded.typeName === "uavcan.protocol.file.GetInfo")) {
255
+ serveFileRequest(t, decoded.typeName, decoded.value);
256
+ return;
257
+ }
214
258
  if (t.type === "req" && t.destination === nodeId && decoded?.typeName === "uavcan.protocol.GetNodeInfo") {
215
259
  void transmit({
216
260
  typeName: "uavcan.protocol.GetNodeInfo",
@@ -289,6 +333,67 @@ export const createDroneCanNode = ({ nodeId, write, name = "pro.xpoe.node", allo
289
333
  })
290
334
  .sort((a, b) => a.typeName.localeCompare(b.typeName)),
291
335
  allocations: () => new Map(allocations),
336
+ serveFile(path, data) {
337
+ if (data)
338
+ files.set(path, data);
339
+ else
340
+ files.delete(path);
341
+ },
342
+ /* Узел перезагружается в загрузчик и читает файл с нас; номер у загрузчика может смениться (DNA) - ход считается по чтениям нашего файла от любого узла */
343
+ async updateFirmware(node, data, { path = `fw/${node}.bin`, onProgress, idleTimeoutMs = 20000, rebootTimeoutMs = 60000 } = {}) {
344
+ files.set(path, data);
345
+ onProgress?.({ phase: "start", bytes: 0, size: data.length });
346
+ try {
347
+ let bytes = 0;
348
+ let lastRead = now();
349
+ let done = false;
350
+ /* Время чтения последнего куска: NodeStatus в рабочем режиме после него - прошивка встала */
351
+ let doneAt = 0;
352
+ const watch = (readPath, offset) => {
353
+ if (readPath !== path)
354
+ return;
355
+ lastRead = now();
356
+ bytes = Math.max(bytes, Math.min(offset + DRONECAN_FILE_CHUNK, data.length));
357
+ if (offset + DRONECAN_FILE_CHUNK >= data.length && !done) {
358
+ done = true;
359
+ doneAt = now();
360
+ }
361
+ onProgress?.({ phase: "read", bytes, size: data.length });
362
+ };
363
+ readWatchers.add(watch);
364
+ try {
365
+ const res = await request("uavcan.protocol.file.BeginFirmwareUpdate", node, { source_node_id: nodeId, image_file_remote_path: { path } }, { timeoutMs: 3000, retries: 1 });
366
+ const code = Number(res.error ?? 0);
367
+ if (code !== FW_OK && code !== FW_IN_PROGRESS) {
368
+ const message = typeof res.optional_error_message === "string" ? res.optional_error_message : "";
369
+ throw new Error(`DroneCAN: узел ${node} отказал в обновлении прошивки (код ${code}${message ? `, ${message}` : ""})`);
370
+ }
371
+ lastRead = now();
372
+ while (!done) {
373
+ await new Promise((resolve) => setTimeout(resolve, 200));
374
+ if (now() - lastRead > idleTimeoutMs)
375
+ throw new Error(`DroneCAN: узел ${node} перестал читать прошивку (${bytes} из ${data.length} байт)`);
376
+ }
377
+ }
378
+ finally {
379
+ readWatchers.delete(watch);
380
+ }
381
+ /* Файл прочитан: ждём, что узел снова пришлёт NodeStatus в рабочем режиме */
382
+ onProgress?.({ phase: "reboot", bytes: data.length, size: data.length });
383
+ while (now() - doneAt < rebootTimeoutMs) {
384
+ const entry = nodes.get(node);
385
+ if (entry && entry.lastSeen >= doneAt && entry.mode === 0) {
386
+ onProgress?.({ phase: "done", bytes: data.length, size: data.length });
387
+ return;
388
+ }
389
+ await new Promise((resolve) => setTimeout(resolve, 250));
390
+ }
391
+ throw new Error(`DroneCAN: узел ${node} не вернулся в рабочий режим после прошивки`);
392
+ }
393
+ finally {
394
+ files.delete(path);
395
+ }
396
+ },
292
397
  dispose() {
293
398
  clearInterval(statusTimer);
294
399
  clearInterval(offlineTimer);
@@ -15,12 +15,13 @@ export interface DroneCanTransfer extends DroneCanId {
15
15
  payload: Uint8Array;
16
16
  timestamp: number;
17
17
  crcOk: boolean;
18
+ fd?: boolean;
18
19
  frames: number;
19
20
  }
20
21
  export declare const createDroneCanReceiver: ({ timeoutMs, signatureOf }: {
21
22
  timeoutMs?: number;
22
23
  signatureOf: (id: DroneCanId) => bigint | undefined;
23
24
  }) => {
24
- push(canId: number, data: Uint8Array, now?: number): DroneCanTransfer | undefined;
25
+ push(canId: number, data: Uint8Array, now?: number, fd?: boolean): DroneCanTransfer | undefined;
25
26
  reset(): void;
26
27
  };
@@ -68,7 +68,7 @@ export const droneCanFrames = (canId, payload, transferId, signature) => {
68
68
  export const createDroneCanReceiver = ({ timeoutMs = 2000, signatureOf }) => {
69
69
  const states = new Map();
70
70
  return {
71
- push(canId, data, now = Date.now()) {
71
+ push(canId, data, now = Date.now(), fd = false) {
72
72
  if (data.length < 1)
73
73
  return undefined;
74
74
  const id = parseDroneCanId(canId);
@@ -78,7 +78,7 @@ export const createDroneCanReceiver = ({ timeoutMs = 2000, signatureOf }) => {
78
78
  const end = !!(tail & TAIL_END);
79
79
  const body = data.subarray(0, data.length - 1);
80
80
  if (start && end)
81
- return { ...id, transferId: tid, payload: body.slice(), timestamp: now, crcOk: true, frames: 1 };
81
+ return { ...id, transferId: tid, payload: body.slice(), timestamp: now, crcOk: true, frames: 1, fd };
82
82
  const key = `${id.type}:${id.dataTypeId}:${id.source}:${id.destination}`;
83
83
  for (const [k, s] of states)
84
84
  if (now - s.last > timeoutMs)
@@ -121,7 +121,7 @@ export const createDroneCanReceiver = ({ timeoutMs = 2000, signatureOf }) => {
121
121
  payload.set(part, offset);
122
122
  offset += part.length;
123
123
  }
124
- return { ...id, transferId: tid, payload, timestamp: state.timestamp, crcOk: state.crc === state.expected, frames: state.frames };
124
+ return { ...id, transferId: tid, payload, timestamp: state.timestamp, crcOk: state.crc === state.expected, frames: state.frames, fd };
125
125
  },
126
126
  reset() {
127
127
  states.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poe-svelte-ui-lib",
3
- "version": "2.31.0",
3
+ "version": "2.32.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Oleg-Perevyshin/ElementsUI.git"