poe-svelte-ui-lib 2.7.1 → 2.8.1
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.
- package/README.md +13 -12
- package/dist/Button/Button.svelte +6 -3
- package/dist/Button/README.md +2 -2
- package/dist/FileAttach/FileAttach.svelte +6 -5
- package/dist/FileAttach/README.md +20 -19
- package/dist/Graph/Graph.svelte +58 -23
- package/dist/Graph/README.md +2 -1
- package/dist/InfoHint.svelte +2 -1
- package/dist/Input/Input.svelte +9 -4
- package/dist/Input/README.md +2 -2
- package/dist/Select/README.md +1 -1
- package/dist/Select/Select.svelte +5 -4
- package/dist/Table/README.md +5 -1
- package/dist/Table/Table.svelte +56 -12
- package/dist/Table/TableProps.svelte +4 -3
- package/dist/Table/XPoeDebugModal.svelte +6 -3
- package/dist/Table/xPoeDebugColumns.d.ts +1 -1
- package/dist/Table/xPoeDebugColumns.js +35 -4
- package/dist/Tabs/README.md +1 -0
- package/dist/Tabs/Tabs.svelte +6 -5
- package/dist/WidgetDeviceInfo/WidgetDeviceInfo.svelte +1 -1
- package/dist/WidgetFileSystem/WidgetFileSystem.svelte +1 -1
- package/dist/dictionaries/README.md +77 -0
- package/dist/{protocols/dictionary.yaml → dictionaries/commands.yaml} +1 -1
- package/dist/dictionaries/firmware/api_har.h +109 -0
- package/dist/dictionaries/firmware/api_msg.h +57 -0
- package/dist/{protocols/dictionaryCodes.js → dictionaries/generated/commands.js} +1 -1
- package/dist/dictionaries/generated/messages.d.ts +19 -0
- package/dist/dictionaries/generated/messages.js +84 -0
- package/dist/dictionaries/messages.yaml +57 -0
- package/dist/libIcons/ArrowIcon.svelte +1 -1
- package/dist/libIcons/ButtonClear.svelte +1 -1
- package/dist/libIcons/InfoIcon.svelte +1 -1
- package/dist/libIcons/Library.svelte +1 -1
- package/dist/libIcons/MoveVerticalIcon.svelte +1 -1
- package/dist/locales/translations.d.ts +20 -0
- package/dist/locales/translations.js +4 -0
- package/dist/options.js +1 -1
- package/dist/popup.d.ts +1 -0
- package/dist/popup.js +12 -0
- package/dist/protocols/PROTOCOL.md +168 -32
- package/dist/protocols/dictionary.d.ts +1 -1
- package/dist/protocols/dictionary.js +2 -2
- package/dist/protocols/index.d.ts +2 -1
- package/dist/protocols/index.js +4 -2
- package/dist/protocols/messages.d.ts +15 -0
- package/dist/protocols/messages.js +31 -0
- package/dist/protocols/xPoeDebug.d.ts +6 -1
- package/dist/protocols/xPoeDebug.js +41 -17
- package/dist/protocols/xPoeDebugView.d.ts +4 -1
- package/dist/protocols/xPoeDebugView.js +37 -65
- package/dist/protocols/xPoeYaml.d.ts +6 -0
- package/dist/protocols/xPoeYaml.js +294 -0
- package/package.json +2 -2
- /package/dist/{protocols/dictionaryCodes.d.ts → dictionaries/generated/commands.d.ts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEFAULT_ARGUMENT_CODES } from "
|
|
1
|
+
import { DEFAULT_ARGUMENT_CODES } from "../dictionaries/generated/commands.js";
|
|
2
2
|
export { DEFAULT_ARGUMENT_CODES };
|
|
3
3
|
export declare const HEADER_CODES: Record<string, number>;
|
|
4
4
|
export declare const parseArgumentDictionary: (text: string) => Record<string, number>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* Словарь заголовков и аргументов протокола - заголовок и аргумент поля HAR (makeHar/splitHar) на шине и в WebSocket-конверте {HAR, VAL}. Аргументы по умолчанию - из мастер-словаря
|
|
2
|
-
import { DEFAULT_ARGUMENT_CODES } from "
|
|
1
|
+
/* Словарь заголовков и аргументов протокола - заголовок и аргумент поля HAR (makeHar/splitHar) на шине и в WebSocket-конверте {HAR, VAL}. Аргументы по умолчанию - из мастер-словаря команд src/lib/dictionaries/commands.yaml (единственный источник; .framework/Dictionary.yaml прошивок - его справочные копии), DEFAULT_ARGUMENT_CODES генерируется из него (dictionaries/generated/commands.ts, npm run Dictionary); у устройства словарь может быть свой - его загружают из файла (parseArgumentDictionary) и передают в createDictionary, своих копий словаря в приложениях не держим */
|
|
2
|
+
import { DEFAULT_ARGUMENT_CODES } from "../dictionaries/generated/commands.js";
|
|
3
3
|
import { makeHar, splitHar } from "./packet.js";
|
|
4
4
|
export { DEFAULT_ARGUMENT_CODES };
|
|
5
5
|
export const HEADER_CODES = {
|
|
@@ -6,7 +6,8 @@ export { crc16Kermit, crc32 } from "./crc.js";
|
|
|
6
6
|
export { BUS_ID_REGEXP, parseBusId, formatBusId, makeHar, splitHar, packetObjectCrc, encodePacketBytesPayload, encodePacket, decodePacket, createPacketStreamParser, type PacketObject, type DecodedPacketObject, type PacketParse, } from "./packet.js";
|
|
7
7
|
export { createPlotGroups, debugPlotValues, DEBUG_PLOT_ARGUMENT, type PlotPoint } from "./plotGroups.js";
|
|
8
8
|
export { encodeXPoeDebugFrame, createXPoeDebugParser, xPoeDebugValueFromText, xPoeDebugRow, DEBUG_LOG_ARGUMENT, type XPoeDebugItem, type XPoeDebugRow, } from "./xPoeDebug.js";
|
|
9
|
-
export { formatXPoeDebugValue, formatXPoeDebugPretty } from "./xPoeDebugView.js";
|
|
9
|
+
export { formatXPoeDebugValue, formatXPoeDebugPretty, xPoeDebugMessage } from "./xPoeDebugView.js";
|
|
10
10
|
export { CAN_FINAL_BIT, CAN_PACKET_ID_MASK, canFragments, encodeSlcanFrame, encodeCanPacket, createCanParser, slcanOpenCommands, type CanFrame, type CanMessage, } from "./can.js";
|
|
11
11
|
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY, parseArgumentDictionary, createDictionary, encodeHar, decodeHar, type Dictionary, type HarParts, } from "./dictionary.js";
|
|
12
12
|
export { encodeWsEnvelope, decodeWsEnvelope, type WsEnvelope, type WsMessage } from "./wsEnvelope.js";
|
|
13
|
+
export { formatDeviceMessage, parseDebugLogMessage, DEVICE_MESSAGES, MESSAGE_CODES, MESSAGE_GROUPS, type DeviceMessage, type DeviceMessageEntry, type DeviceMessageGroup, type DeviceMessageLevel, type FormattedDeviceMessage, } from "./messages.js";
|
package/dist/protocols/index.js
CHANGED
|
@@ -13,10 +13,12 @@ export { createPlotGroups, debugPlotValues, DEBUG_PLOT_ARGUMENT } from "./plotGr
|
|
|
13
13
|
/* xPOE-Debug - UART-консоль как шина: пакеты вперемешку с текстом загрузчика, логи OK! DebugLog */
|
|
14
14
|
export { encodeXPoeDebugFrame, createXPoeDebugParser, xPoeDebugValueFromText, xPoeDebugRow, DEBUG_LOG_ARGUMENT, } from "./xPoeDebug.js";
|
|
15
15
|
/* Вид Payload xPOE-Debug: кратко для строки таблицы и развёрнуто для окна */
|
|
16
|
-
export { formatXPoeDebugValue, formatXPoeDebugPretty } from "./xPoeDebugView.js";
|
|
16
|
+
export { formatXPoeDebugValue, formatXPoeDebugPretty, xPoeDebugMessage } from "./xPoeDebugView.js";
|
|
17
17
|
/* CAN/CAN FD через slcan-адаптер: нарезка пакета на кадры как в can_service прошивки, кадры slcan, потоковый разбор со сборкой фрагментов */
|
|
18
18
|
export { CAN_FINAL_BIT, CAN_PACKET_ID_MASK, canFragments, encodeSlcanFrame, encodeCanPacket, createCanParser, slcanOpenCommands, } from "./can.js";
|
|
19
|
-
/* Словарь заголовков и аргументов HAR - по умолчанию из мастер-словаря
|
|
19
|
+
/* Словарь заголовков и аргументов HAR - по умолчанию из мастер-словаря команд dictionaries/commands.yaml библиотеки (устройства и облако), разбор файла словаря, словарь устройства с обратным поиском; HAR из слов и обратно */
|
|
20
20
|
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY, parseArgumentDictionary, createDictionary, encodeHar, decodeHar, } from "./dictionary.js";
|
|
21
21
|
/* Конверт WebSocket {HAR, VAL} на всех соединениях: сборка из заголовка и аргумента (имя или код), разбор в слова по словарю */
|
|
22
22
|
export { encodeWsEnvelope, decodeWsEnvelope } from "./wsEnvelope.js";
|
|
23
|
+
/* Сообщения устройств: Message - код из мастер-словаря dictionaries/messages.yaml (коды по группам MESSAGE_GROUPS), Args - параметры; текст на языке, уровень и группа */
|
|
24
|
+
export { formatDeviceMessage, parseDebugLogMessage, DEVICE_MESSAGES, MESSAGE_CODES, MESSAGE_GROUPS, } from "./messages.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type LanguageCode } from "../locales/languages.js";
|
|
2
|
+
import { type DeviceMessageLevel } from "../dictionaries/generated/messages.js";
|
|
3
|
+
export { DEVICE_MESSAGES, MESSAGE_CODES, MESSAGE_GROUPS, type DeviceMessageEntry, type DeviceMessageGroup, type DeviceMessageLevel, } from "../dictionaries/generated/messages.js";
|
|
4
|
+
export type DeviceMessage = {
|
|
5
|
+
Message: number;
|
|
6
|
+
Args?: (string | number)[];
|
|
7
|
+
};
|
|
8
|
+
export type FormattedDeviceMessage = {
|
|
9
|
+
text: string;
|
|
10
|
+
level: DeviceMessageLevel;
|
|
11
|
+
group: string | null;
|
|
12
|
+
groupName: string | null;
|
|
13
|
+
};
|
|
14
|
+
export declare const formatDeviceMessage: (code: number | null | undefined, args?: readonly (string | number)[], lang?: LanguageCode) => FormattedDeviceMessage | null;
|
|
15
|
+
export declare const parseDebugLogMessage: (text: string) => DeviceMessage | null;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/* Сообщения устройств: в VAL ответа и push поле Message - код из мастер-словаря src/lib/dictionaries/messages.yaml (0 или нет поля - сообщения нет), Args - параметры шаблона {0}, {1}... Коды разбиты на группы с диапазонами (MESSAGE_GROUPS). Текст на языке интерфейса, уровень и группу собирает formatDeviceMessage; DEVICE_MESSAGES, MESSAGE_GROUPS и MESSAGE_CODES генерируются из словаря (dictionaries/generated/messages.ts, npm run Dictionary) */
|
|
2
|
+
import { DEFAULT_LANGUAGE } from "../locales/languages.js";
|
|
3
|
+
import { DEVICE_MESSAGES, MESSAGE_GROUPS } from "../dictionaries/generated/messages.js";
|
|
4
|
+
export { DEVICE_MESSAGES, MESSAGE_CODES, MESSAGE_GROUPS, } from "../dictionaries/generated/messages.js";
|
|
5
|
+
/* Текст на языке lang, нет перевода - английский */
|
|
6
|
+
const translate = (entry, lang) => entry[lang] || entry.en;
|
|
7
|
+
/* Текст сообщения на языке lang (по умолчанию - DEFAULT_LANGUAGE; приложение передаёт getLanguage()), уровень и группа. 0, нет кода, не число - null. Неизвестный код - "#код: параметры" с уровнем info, группа - по диапазону кода */
|
|
8
|
+
export const formatDeviceMessage = (code, args = [], lang = DEFAULT_LANGUAGE) => {
|
|
9
|
+
if (typeof code !== "number" || !Number.isInteger(code) || code <= 0)
|
|
10
|
+
return null;
|
|
11
|
+
const list = Array.isArray(args) ? args : [];
|
|
12
|
+
const entry = DEVICE_MESSAGES[code];
|
|
13
|
+
const group = entry?.group ?? Object.keys(MESSAGE_GROUPS).find((name) => code >= MESSAGE_GROUPS[name].from && code <= MESSAGE_GROUPS[name].to) ?? null;
|
|
14
|
+
const groupName = group && MESSAGE_GROUPS[group] ? translate(MESSAGE_GROUPS[group], lang) : null;
|
|
15
|
+
if (!entry)
|
|
16
|
+
return { text: list.length ? `#${code}: ${list.join(", ")}` : `#${code}`, level: "info", group, groupName };
|
|
17
|
+
/* Параметра нет в Args - "?", чтобы нехватка была видна */
|
|
18
|
+
return {
|
|
19
|
+
text: translate(entry, lang).replace(/\{(\d+)\}/g, (_, index) => (list[Number(index)] === undefined ? "?" : String(list[Number(index)]))),
|
|
20
|
+
level: entry.level,
|
|
21
|
+
group,
|
|
22
|
+
groupName,
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/* Сообщение в тексте DebugLog консоли xPOE-Debug: "MSG <код>[ <арг1>[<TAB><арг2>...]]" - пробел после кода, TAB между параметрами (в SSID бывают пробелы); другой текст - null */
|
|
26
|
+
export const parseDebugLogMessage = (text) => {
|
|
27
|
+
const match = /^MSG (\d+)(?: ([\s\S]*))?$/.exec(text);
|
|
28
|
+
if (!match)
|
|
29
|
+
return null;
|
|
30
|
+
return match[2] === undefined ? { Message: Number(match[1]) } : { Message: Number(match[1]), Args: match[2].split("\t") };
|
|
31
|
+
};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type Dictionary } from "./dictionary.js";
|
|
2
|
+
import { type LanguageCode } from "../locales/languages.js";
|
|
2
3
|
import { type FramerOptions } from "./framer.js";
|
|
4
|
+
import type { DeviceMessageLevel } from "./messages.js";
|
|
3
5
|
export declare const DEBUG_LOG_ARGUMENT = "DebugLog";
|
|
4
6
|
export type XPoeDebugItem = {
|
|
5
7
|
type: "frame";
|
|
@@ -25,13 +27,16 @@ export interface XPoeDebugRow {
|
|
|
25
27
|
har: string;
|
|
26
28
|
header: string;
|
|
27
29
|
argument: string;
|
|
30
|
+
reply: boolean;
|
|
28
31
|
value: string;
|
|
29
32
|
valueBytes: Uint8Array;
|
|
30
33
|
payload: unknown;
|
|
31
34
|
crc: string;
|
|
32
35
|
freeHeap: string;
|
|
36
|
+
message?: string;
|
|
37
|
+
level?: DeviceMessageLevel;
|
|
33
38
|
}
|
|
34
|
-
export declare const xPoeDebugRow: (item: XPoeDebugItem) => XPoeDebugRow;
|
|
39
|
+
export declare const xPoeDebugRow: (item: XPoeDebugItem, lang?: LanguageCode) => XPoeDebugRow;
|
|
35
40
|
export declare const createXPoeDebugParser: ({ dictionary, ...options }?: FramerOptions & {
|
|
36
41
|
dictionary?: Dictionary;
|
|
37
42
|
}) => {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/* xPOE-Debug - UART-консоль как ещё одна шина: пакеты poe_cbor_pkt [[TrgBusID, SrcBusID, HAR, Payload, CRC16], …] вперемешку с текстом загрузчика. Логи - OK! DebugLog, Payload [уровень, тег, текст|байты, FHS]; графики - OK! DebugPlot, Payload {"Группа.Имя": float32} */
|
|
2
2
|
import { cborToValue } from "./cbor/value.js";
|
|
3
|
-
import { jsonToCbor } from "./cbor/json.js";
|
|
4
3
|
import { DEFAULT_DICTIONARY } from "./dictionary.js";
|
|
4
|
+
import { DEFAULT_LANGUAGE } from "../locales/languages.js";
|
|
5
5
|
import { createFramer } from "./framer.js";
|
|
6
6
|
import { hexToBytes } from "./hex.js";
|
|
7
|
-
import { formatXPoeDebugValue } from "./xPoeDebugView.js";
|
|
7
|
+
import { formatXPoeDebugValue, xPoeDebugMessage } from "./xPoeDebugView.js";
|
|
8
|
+
import { yamlFlowToCbor } from "./xPoeYaml.js";
|
|
8
9
|
import { decodePacket, encodePacket, formatBusId, packetStart } from "./packet.js";
|
|
9
10
|
export const DEBUG_LOG_ARGUMENT = "DebugLog";
|
|
10
11
|
const MAX_TEXT_TAIL = 4096;
|
|
@@ -46,20 +47,38 @@ const frameItem = (object, dictionary) => {
|
|
|
46
47
|
freeHeap: argument === DEBUG_LOG_ARGUMENT && Array.isArray(payload) && typeof payload[3] === "number" ? String(payload[3]) : "",
|
|
47
48
|
};
|
|
48
49
|
};
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
/* lang - язык сообщений устройства (приложение передаёт getLanguage()) */
|
|
51
|
+
export const xPoeDebugRow = (item, lang = DEFAULT_LANGUAGE) => {
|
|
52
|
+
if (item.type === "raw")
|
|
53
|
+
return {
|
|
54
|
+
trgId: "",
|
|
55
|
+
srcId: "",
|
|
56
|
+
har: "",
|
|
57
|
+
header: "RAW",
|
|
58
|
+
argument: "",
|
|
59
|
+
reply: false,
|
|
60
|
+
value: item.text,
|
|
61
|
+
valueBytes: new Uint8Array(),
|
|
62
|
+
payload: undefined,
|
|
63
|
+
crc: "",
|
|
64
|
+
freeHeap: "",
|
|
65
|
+
};
|
|
66
|
+
const message = xPoeDebugMessage(item.payload, lang);
|
|
67
|
+
return {
|
|
52
68
|
trgId: formatBusId(item.trgId),
|
|
53
69
|
srcId: formatBusId(item.srcId),
|
|
54
70
|
har: item.har.toString(16).toUpperCase().padStart(4, "0"),
|
|
55
71
|
header: item.crcOk ? item.header : "⚠️",
|
|
56
72
|
argument: item.argument,
|
|
73
|
+
reply: item.reply,
|
|
57
74
|
value: formatXPoeDebugValue(item.payload, item.valueBytes),
|
|
58
75
|
valueBytes: item.valueBytes,
|
|
59
76
|
payload: item.payload,
|
|
60
77
|
crc: item.crc,
|
|
61
78
|
freeHeap: item.freeHeap,
|
|
79
|
+
...(message && { message: message.text, level: message.level }),
|
|
62
80
|
};
|
|
81
|
+
};
|
|
63
82
|
/* Потоковый разбор: пакеты в любом месте разреза, текст - построчно, мусор сдвигается по байту; пауза дольше gapMs обрывает недособранный пакет, а недописанную строку текста выдаёт как есть. Имена аргументов - из dictionary (по умолчанию встроенного) */
|
|
64
83
|
export const createXPoeDebugParser = ({ dictionary = DEFAULT_DICTIONARY, ...options } = {}) => {
|
|
65
84
|
const framer = createFramer(options);
|
|
@@ -92,26 +111,31 @@ export const createXPoeDebugParser = ({ dictionary = DEFAULT_DICTIONARY, ...opti
|
|
|
92
111
|
reset: framer.reset,
|
|
93
112
|
};
|
|
94
113
|
};
|
|
95
|
-
/* Готовые байты Payload
|
|
96
|
-
const
|
|
97
|
-
/* Поле Value:
|
|
114
|
+
/* Готовые байты Payload (CBOR как есть) - только 0x0A1B */
|
|
115
|
+
const RAW_VALUE = /^0[xX]([0-9A-Fa-f]*)$/;
|
|
116
|
+
/* Поле Value: 0x.. - готовые байты Payload как есть; поток YAML, как в строке VALUE, и JSON как его часть (в JSON строки Base64 под ключами на BIN - байты): «A: 1, B: [1, 2]» (корневая карта без скобок), h'0A1B' - байтовая строка, «12» - число, "12" - строка; пусто - пустой Payload */
|
|
98
117
|
export const xPoeDebugValueFromText = (text) => {
|
|
99
118
|
const trimmed = (text ?? "").trim();
|
|
100
119
|
if (!trimmed)
|
|
101
120
|
return new Uint8Array();
|
|
102
|
-
const
|
|
103
|
-
if (
|
|
104
|
-
const bytes = hexToBytes(
|
|
105
|
-
if (!bytes)
|
|
106
|
-
throw new Error(`Value:
|
|
121
|
+
const raw = RAW_VALUE.exec(trimmed);
|
|
122
|
+
if (raw) {
|
|
123
|
+
const bytes = hexToBytes(raw[1]);
|
|
124
|
+
if (!bytes?.length)
|
|
125
|
+
throw new Error(`Value: после 0x нужны HEX-цифры парами: ${trimmed}`);
|
|
107
126
|
return bytes;
|
|
108
127
|
}
|
|
109
|
-
let
|
|
128
|
+
let json = true;
|
|
110
129
|
try {
|
|
111
|
-
|
|
130
|
+
JSON.parse(trimmed);
|
|
112
131
|
}
|
|
113
132
|
catch {
|
|
114
|
-
|
|
133
|
+
json = false;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
return yamlFlowToCbor(trimmed, json);
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
throw new Error(`Value не разобран (YAML, JSON или 0x..): ${err instanceof Error ? err.message : err}: ${trimmed}`);
|
|
115
140
|
}
|
|
116
|
-
return jsonToCbor(parsed);
|
|
117
141
|
};
|
|
@@ -1,2 +1,5 @@
|
|
|
1
|
+
import { type LanguageCode } from "../locales/languages.js";
|
|
2
|
+
import { type FormattedDeviceMessage } from "./messages.js";
|
|
3
|
+
export declare const xPoeDebugMessage: (payload: unknown, lang?: LanguageCode) => FormattedDeviceMessage | null;
|
|
1
4
|
export declare const formatXPoeDebugValue: (payload: unknown, bytes: Uint8Array) => string;
|
|
2
|
-
export declare const formatXPoeDebugPretty: (payload: unknown, html?: boolean) => string | null;
|
|
5
|
+
export declare const formatXPoeDebugPretty: (payload: unknown, html?: boolean, bytes?: Uint8Array) => string | null;
|
|
@@ -1,55 +1,54 @@
|
|
|
1
|
-
/* Вид Payload xPOE-Debug: кратко в строку таблицы и развёрнуто для
|
|
1
|
+
/* Вид Payload xPOE-Debug: кратко в строку таблицы и развёрнуто для окна как пришёл, сообщение устройства - отдельно (xPoeDebugMessage); Payload декодирован один раз при разборе (xPoeDebugRow) */
|
|
2
2
|
import { escapeHtml } from "../html.js";
|
|
3
|
+
import { DEFAULT_LANGUAGE } from "../locales/languages.js";
|
|
4
|
+
import { decodeCbor } from "./cbor/decoder.js";
|
|
3
5
|
import { bytesToHex } from "./hex.js";
|
|
6
|
+
import { formatYamlBlock, formatYamlFlow } from "./xPoeYaml.js";
|
|
7
|
+
import { formatDeviceMessage, parseDebugLogMessage } from "./messages.js";
|
|
4
8
|
const LOG_LEVELS = { 1: "🔴", 2: "🟡", 3: "🟢", 4: "🔵" };
|
|
5
|
-
/*
|
|
6
|
-
const
|
|
7
|
-
if (
|
|
8
|
-
return
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
/* Payload для вида - как на проводе (порядок пар, ключи-числа, uint64), из исходных байт; без байт - декодированный payload */
|
|
10
|
+
const wireValue = (payload, bytes) => {
|
|
11
|
+
if (!bytes?.length)
|
|
12
|
+
return payload;
|
|
13
|
+
try {
|
|
14
|
+
return decodeCbor(bytes);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return payload;
|
|
13
18
|
}
|
|
14
|
-
return value;
|
|
15
|
-
};
|
|
16
|
-
const normalizeCborValue = (value) => {
|
|
17
|
-
if (typeof value === "number")
|
|
18
|
-
return shortNumber(value);
|
|
19
|
-
if (typeof value === "bigint")
|
|
20
|
-
return String(value);
|
|
21
|
-
if (value instanceof Uint8Array)
|
|
22
|
-
return `h'${bytesToHex(value, " ")}'`;
|
|
23
|
-
if (Array.isArray(value))
|
|
24
|
-
return value.map(normalizeCborValue);
|
|
25
|
-
if (value instanceof Map)
|
|
26
|
-
return Object.fromEntries([...value].map(([key, item]) => [String(key), normalizeCborValue(item)]));
|
|
27
|
-
if (value && typeof value === "object")
|
|
28
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeCborValue(item)]));
|
|
29
|
-
return value;
|
|
30
|
-
};
|
|
31
|
-
const compactValue = (value) => {
|
|
32
|
-
if (typeof value === "string")
|
|
33
|
-
return value;
|
|
34
|
-
if (value instanceof Uint8Array)
|
|
35
|
-
return `bytes(${value.length}): ${bytesToHex(value, " ")}`;
|
|
36
|
-
return JSON.stringify(normalizeCborValue(value)) ?? String(value);
|
|
37
19
|
};
|
|
20
|
+
/* Байты DebugLog - с длиной, HEX через пробел */
|
|
21
|
+
const logBytes = (bytes) => `bytes(${bytes.length}): ${bytesToHex(bytes, " ")}`;
|
|
38
22
|
const isDebugLog = (value) => Array.isArray(value) &&
|
|
39
23
|
value.length === 4 &&
|
|
40
24
|
typeof value[0] === "number" &&
|
|
41
25
|
!!LOG_LEVELS[value[0]] &&
|
|
42
26
|
typeof value[1] === "string" &&
|
|
43
27
|
(typeof value[2] === "string" || value[2] instanceof Uint8Array);
|
|
44
|
-
/*
|
|
28
|
+
/* Поле карты Payload (CBOR-карта приходит Map или объектом) */
|
|
29
|
+
const mapField = (value, key) => value instanceof Map ? value.get(key) : value && typeof value === "object" && !Array.isArray(value) ? value[key] : undefined;
|
|
30
|
+
/* Сообщение устройства в Payload на языке lang: DebugLog с текстом "MSG <код> ..." или карта {Message, Args} (ответ ER!); нет - null. В строку VALUE не входит */
|
|
31
|
+
export const xPoeDebugMessage = (payload, lang = DEFAULT_LANGUAGE) => {
|
|
32
|
+
if (isDebugLog(payload)) {
|
|
33
|
+
const message = typeof payload[2] === "string" ? parseDebugLogMessage(payload[2]) : null;
|
|
34
|
+
return message && formatDeviceMessage(message.Message, message.Args, lang);
|
|
35
|
+
}
|
|
36
|
+
const code = mapField(payload, "Message");
|
|
37
|
+
if (typeof code !== "number")
|
|
38
|
+
return null;
|
|
39
|
+
const args = mapField(payload, "Args");
|
|
40
|
+
return formatDeviceMessage(code, Array.isArray(args) ? args.filter((a) => typeof a === "string" || typeof a === "number") : [], lang);
|
|
41
|
+
};
|
|
42
|
+
/* Payload в строку таблицы как пришёл: DebugLog [уровень, тег, текст|байты, FHS] - уровень · тег · текст, CBOR - поток YAML (корневая карта без скобок: «A: 1, B: [1, 2]»; читается обратно полем Value), не CBOR - HEX байт */
|
|
45
43
|
export const formatXPoeDebugValue = (payload, bytes) => {
|
|
46
44
|
if (payload === undefined)
|
|
47
45
|
return bytesToHex(bytes, " ");
|
|
48
46
|
if (!isDebugLog(payload))
|
|
49
|
-
return
|
|
50
|
-
const detail =
|
|
47
|
+
return formatYamlFlow(wireValue(payload, bytes));
|
|
48
|
+
const detail = typeof payload[2] === "string" ? payload[2] : logBytes(payload[2]);
|
|
51
49
|
return `${LOG_LEVELS[payload[0]]} · ${payload[1]}${detail ? ` · ${detail}` : ""}`;
|
|
52
50
|
};
|
|
51
|
+
/* Цвета развёрнутого вида - палитра темы: ключи, строки, числа, логические, null, байты */
|
|
53
52
|
const PRETTY_COLORS = {
|
|
54
53
|
key: "--blue-text",
|
|
55
54
|
string: "--purple-text",
|
|
@@ -62,41 +61,14 @@ const plain = (_kind, text) => text;
|
|
|
62
61
|
const colored = (kind, text) => `<span style="color:var(${PRETTY_COLORS[kind]})">${escapeHtml(text)}</span>`;
|
|
63
62
|
/* Байты строками по 16 - для дампа DebugLog */
|
|
64
63
|
const hexRows = (bytes) => (bytesToHex(bytes, " ").match(/.{1,48}/g) ?? []).map((row) => row.trim()).join("\n");
|
|
65
|
-
/*
|
|
66
|
-
const
|
|
67
|
-
if (value === null || value === undefined)
|
|
68
|
-
return paint("null", "null");
|
|
69
|
-
if (typeof value === "string")
|
|
70
|
-
return paint("string", JSON.stringify(value));
|
|
71
|
-
if (typeof value === "number")
|
|
72
|
-
return paint("number", String(shortNumber(value)));
|
|
73
|
-
if (typeof value === "bigint")
|
|
74
|
-
return paint("number", String(value));
|
|
75
|
-
if (typeof value === "boolean")
|
|
76
|
-
return paint("boolean", String(value));
|
|
77
|
-
if (value instanceof Uint8Array)
|
|
78
|
-
return paint("bytes", `h'${bytesToHex(value, " ")}'`);
|
|
79
|
-
const inner = `${indent} `;
|
|
80
|
-
if (Array.isArray(value)) {
|
|
81
|
-
if (!value.length)
|
|
82
|
-
return "[]";
|
|
83
|
-
return `[\n${value.map((item) => inner + prettyValue(item, paint, inner)).join(",\n")}\n${indent}]`;
|
|
84
|
-
}
|
|
85
|
-
const entries = value instanceof Map ? [...value.entries()] : Object.entries(value);
|
|
86
|
-
if (!entries.length)
|
|
87
|
-
return "{}";
|
|
88
|
-
return `{\n${entries.map(([key, item]) => `${inner}${paint("key", `${JSON.stringify(String(key))}:`)} ${prettyValue(item, paint, inner)}`).join(",\n")}\n${indent}}`;
|
|
89
|
-
};
|
|
90
|
-
/* Payload развёрнуто: карты и массивы с отступами, DebugLog - уровень и тег, ниже текст или дамп по 16 байт и FHS; html - готовый HTML в цветах темы (данные экранированы); не CBOR - null */
|
|
91
|
-
export const formatXPoeDebugPretty = (payload, html = false) => {
|
|
64
|
+
/* Payload развёрнуто: блочный YAML с отступом 2 (скаляр - как в строке таблицы), DebugLog - уровень и тег, ниже текст как пришёл или дамп по 16 байт и FHS; html - готовый HTML в цветах темы (данные экранированы); bytes - исходные байты Payload (порядок пар как на проводе); не CBOR - null */
|
|
65
|
+
export const formatXPoeDebugPretty = (payload, html = false, bytes) => {
|
|
92
66
|
if (payload === undefined)
|
|
93
67
|
return null;
|
|
94
68
|
const paint = html ? colored : plain;
|
|
95
69
|
const raw = (text) => (html ? escapeHtml(text) : text);
|
|
96
|
-
if (typeof payload === "string")
|
|
97
|
-
return raw(payload);
|
|
98
70
|
if (!isDebugLog(payload))
|
|
99
|
-
return
|
|
71
|
+
return formatYamlBlock(wireValue(payload, bytes), paint);
|
|
100
72
|
const [level, tag, detail, fhs] = payload;
|
|
101
73
|
const body = detail instanceof Uint8Array ? `${raw(`bytes(${detail.length}):`)}\n${paint("bytes", hexRows(detail))}` : raw(detail);
|
|
102
74
|
return [`${LOG_LEVELS[level]} ${paint("key", tag)}`, body, typeof fhs === "number" ? `FHS: ${paint("number", String(fhs))}` : ""].filter(Boolean).join("\n");
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type YamlKind = "key" | "string" | "number" | "boolean" | "null" | "bytes";
|
|
2
|
+
export type YamlPaint = (kind: YamlKind, text: string) => string;
|
|
3
|
+
export declare const shortNumber: (value: number) => number;
|
|
4
|
+
export declare const formatYamlFlow: (value: unknown, paint?: YamlPaint) => string;
|
|
5
|
+
export declare const formatYamlBlock: (value: unknown, paint?: YamlPaint) => string;
|
|
6
|
+
export declare const yamlFlowToCbor: (text: string, binBase64?: boolean) => Uint8Array;
|