@nebulahome/integration-sdk 1.5.0 → 1.6.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.
@@ -1,8 +1,749 @@
1
- import { n as __toESM } from "./node-rolldown-runtime.js";
2
- import { f as defineAccount, r as require_semver } from "./node-dist.js";
1
+ import { n as __exportAll, r as __toESM } from "./node-rolldown-runtime.js";
2
+ import { S as ValidationError, _ as infraredCodeSchema, f as defineAccount, g as INFRARED_MAXIMUM_PULSES, r as require_semver, v as bluetoothAdvertSchema, y as serialLineSchema } from "./node-dist.js";
3
3
  import { z } from "zod";
4
4
  import { readFile, stat } from "node:fs/promises";
5
5
  import path from "node:path";
6
+ //#region ../package-runtime/dist/infrared-codes.js
7
+ /**
8
+ * Infrared and radio codes in the formats people bring them in, and the protocols they carry: pure.
9
+ *
10
+ * The platform keeps a code as timings - {@link InfraredCode}: microseconds, a mark then a space in
11
+ * turn, starting with a mark - with the protocol beside them when one is recognised. Everything
12
+ * else is a way of writing those timings down: the base64 packets a Broadlink learns and sends, the
13
+ * Pronto hex that remote databases list, plain lists of microseconds, and the `.ir` files a Flipper
14
+ * Zero saves. The hub reads an import and writes "Copy as" through this module, and a blaster's
15
+ * integration converts to and from its own format through the SDK, which re-exports it - so a
16
+ * remote learned on one blaster sends through another brand's without being learned again.
17
+ *
18
+ * The protocols - NEC and its extended form, Samsung32, Sony SIRC in its three lengths, RC5 - are
19
+ * read off timings with the slack receivers allow, and written back as timings, which is what turns
20
+ * a Flipper file's `type: parsed` entry into something a blaster can send.
21
+ */
22
+ var infrared_codes_exports = /* @__PURE__ */ __exportAll({
23
+ BROADLINK_TICK_US: () => BROADLINK_TICK_US,
24
+ DEFAULT_IR_CARRIER_HZ: () => DEFAULT_IR_CARRIER_HZ,
25
+ decodeBroadlink: () => decodeBroadlink,
26
+ decodeInfraredProtocol: () => decodeInfraredProtocol,
27
+ decodePronto: () => decodePronto,
28
+ decodeRawTimings: () => decodeRawTimings,
29
+ encodeBroadlink: () => encodeBroadlink,
30
+ encodeInfraredProtocol: () => encodeInfraredProtocol,
31
+ encodePronto: () => encodePronto,
32
+ encodeRawTimings: () => encodeRawTimings,
33
+ parseFlipperIr: () => parseFlipperIr,
34
+ withInfraredProtocol: () => withInfraredProtocol
35
+ });
36
+ /**
37
+ * One Broadlink tick: 8192/269 µs, about 30.45 µs - a duration in µs times 269/8192 is ticks,
38
+ * as measured against real firmware (broadlink-async). The inverse, 32.84 µs, made codes from
39
+ * other sources about 7 % short on the air.
40
+ */
41
+ const BROADLINK_TICK_US = 8192 / 269;
42
+ /** The carrier an infrared code is on when its format does not say: 38 kHz, as most remotes. */
43
+ const DEFAULT_IR_CARRIER_HZ = 38e3;
44
+ /** The type byte of a Broadlink infrared packet. */
45
+ const BROADLINK_IR = 38;
46
+ /** The type byte of a Broadlink packet sent on 433 MHz. */
47
+ const BROADLINK_RF433 = 178;
48
+ /** The type byte of a Broadlink packet sent on 315 MHz. */
49
+ const BROADLINK_RF315 = 215;
50
+ /** The frequencies the two radio type bytes stand for. */
51
+ const RF433_HZ = 43392e4;
52
+ const RF315_HZ = 315e6;
53
+ /** Pronto's reference clock: one period of its frequency word is that many of these, in µs. */
54
+ const PRONTO_CLOCK_US = .241246;
55
+ /** The pause given to a code that ends on a mark where a format needs it to end on a space. */
56
+ const LEAD_OUT_US = 5e4;
57
+ /** The shortest pause a protocol's frame is padded with, however long the frame. */
58
+ const MINIMUM_PAUSE_US = 1e4;
59
+ /** How far a timing may be from the protocol's and still be read as it: a quarter, as receivers allow. */
60
+ const TOLERANCE = .25;
61
+ /**
62
+ * A code that does not hold, as the import lists it.
63
+ *
64
+ * @param message - Why, in a sentence.
65
+ * @returns The error.
66
+ */
67
+ function invalid(message) {
68
+ return new ValidationError(message, { details: { reason: message } });
69
+ }
70
+ /**
71
+ * A code checked against what the platform keeps: its pulses' number and lengths.
72
+ *
73
+ * @param code - The code.
74
+ * @returns The same code.
75
+ * @throws {ValidationError} When it does not hold.
76
+ */
77
+ function checked(code) {
78
+ if (code.pulses.length === 0) throw invalid("It holds no pulses");
79
+ const parsed = infraredCodeSchema.safeParse(code);
80
+ if (!parsed.success) {
81
+ const [issue] = parsed.error.issues;
82
+ throw invalid(code.pulses.length > 2048 ? `It holds ${String(code.pulses.length)} pulses, and a code ${String(INFRARED_MAXIMUM_PULSES)} at most` : issue?.message ?? "It is not a code");
83
+ }
84
+ return parsed.data;
85
+ }
86
+ /**
87
+ * A train of pulses sent several times, as a packet's repeat byte asks: as many times as fit.
88
+ *
89
+ * @param once - The train.
90
+ * @param times - How many times in all.
91
+ * @returns The pulses.
92
+ */
93
+ function repeated(once, times) {
94
+ const copies = once.length % 2 === 1 ? 1 : Math.max(1, Math.min(times, Math.floor(INFRARED_MAXIMUM_PULSES / once.length)));
95
+ return Array.from({ length: copies }, () => once).flat();
96
+ }
97
+ /**
98
+ * Reads a Broadlink packet, as its app and similar open-source implementations write one: base64
99
+ * of a type byte, a repeat count, the length of what follows, and each pulse in ticks - one byte,
100
+ * or 0x00 and two bytes big-endian for a longer one - closed by 0x0d 0x05.
101
+ *
102
+ * @param text - The base64.
103
+ * @returns The code, its protocol recognised where it can be.
104
+ * @throws {ValidationError} When it is not a packet, or its pulses do not hold.
105
+ */
106
+ function decodeBroadlink(text) {
107
+ const compact = text.replaceAll(/\s+/gu, "");
108
+ if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(compact)) throw invalid("It is not base64");
109
+ const bytes = Buffer.from(compact, "base64");
110
+ const type = bytes[0];
111
+ const signal = type === BROADLINK_IR ? "ir" : type === BROADLINK_RF433 || type === BROADLINK_RF315 ? "rf" : void 0;
112
+ if (bytes.length < 4 || signal === void 0) throw invalid("It is not a Broadlink packet: those start 0x26 (infrared) or 0xb2, 0xd7 (radio)");
113
+ const end = Math.min(4 + ((bytes[2] ?? 0) | (bytes[3] ?? 0) << 8), bytes.length);
114
+ const ticks = [];
115
+ let index = 4;
116
+ while (index < end) {
117
+ if (index === end - 2 && bytes[index] === 13 && bytes[index + 1] === 5) break;
118
+ let value = bytes[index] ?? 0;
119
+ index += 1;
120
+ if (value === 0) {
121
+ if (index + 2 > end) throw invalid("It is cut short: a long pulse lacks its two bytes");
122
+ value = (bytes[index] ?? 0) << 8 | (bytes[index + 1] ?? 0);
123
+ index += 2;
124
+ }
125
+ if (value === 0) break;
126
+ ticks.push(value);
127
+ }
128
+ const pulses = repeated(ticks.map((tick) => Math.round(tick * BROADLINK_TICK_US)), (bytes[1] ?? 0) + 1);
129
+ return signal === "ir" ? withInfraredProtocol(checked({
130
+ signal,
131
+ carrierHz: DEFAULT_IR_CARRIER_HZ,
132
+ pulses
133
+ })) : checked({
134
+ signal,
135
+ carrierHz: 0,
136
+ frequencyHz: type === BROADLINK_RF315 ? RF315_HZ : RF433_HZ,
137
+ pulses
138
+ });
139
+ }
140
+ /**
141
+ * Writes a code as a Broadlink packet: sent once, closed by 0x0d 0x05 and filled out to whole
142
+ * 16-byte blocks, as a Broadlink learns one. Radio goes on 315 MHz for a code nearer that than
143
+ * 433.
144
+ *
145
+ * @param code - The code.
146
+ * @returns The base64.
147
+ */
148
+ function encodeBroadlink(code) {
149
+ const type = code.signal === "ir" ? BROADLINK_IR : (code.frequencyHz ?? RF433_HZ) < 37446e4 ? BROADLINK_RF315 : BROADLINK_RF433;
150
+ const data = [];
151
+ for (const pulse of code.pulses) {
152
+ const ticks = Math.min(65535, Math.max(1, Math.round(pulse / BROADLINK_TICK_US)));
153
+ data.push(...ticks < 256 ? [ticks] : [
154
+ 0,
155
+ ticks >> 8,
156
+ ticks & 255
157
+ ]);
158
+ }
159
+ data.push(13, 5);
160
+ const packet = [
161
+ type,
162
+ 0,
163
+ data.length & 255,
164
+ data.length >> 8,
165
+ ...data
166
+ ];
167
+ const padding = (16 - packet.length % 16) % 16;
168
+ return Buffer.from([...packet, ...Array.from({ length: padding }, () => 0)]).toString("base64");
169
+ }
170
+ /**
171
+ * Reads Pronto hex in its learned form: `0000`, the frequency word, the number of pairs sent once
172
+ * and of those repeated, then each pair's mark and space in periods of the carrier. What is sent
173
+ * once comes first, then the repeated part once.
174
+ *
175
+ * @param text - The words, four hex digits each.
176
+ * @returns The code, its protocol recognised where it can be.
177
+ * @throws {ValidationError} When it is not learned Pronto, or its pulses do not hold.
178
+ */
179
+ function decodePronto(text) {
180
+ const words = text.trim().split(/\s+/u);
181
+ if (!words.every((word) => /^[0-9A-Fa-f]{4}$/u.test(word))) throw invalid("Pronto is words of four hex digits");
182
+ const [form = 0, frequency = 0, once = 0, repeat = 0] = words.map((word) => parseInt(word, 16));
183
+ if (form !== 0) throw invalid("Only learned Pronto, starting 0000, is read");
184
+ if (frequency === 0) throw invalid("Its frequency word is 0");
185
+ const end = 4 + 2 * (once + repeat);
186
+ if (words.length < end) throw invalid(`It says ${String(once + repeat)} pairs and holds ${String(Math.floor((words.length - 4) / 2))}`);
187
+ const period = frequency * PRONTO_CLOCK_US;
188
+ const pulses = words.slice(4, end).map((word) => Math.max(1, Math.round(parseInt(word, 16) * period)));
189
+ return withInfraredProtocol(checked({
190
+ signal: "ir",
191
+ carrierHz: Math.round(1e6 / period),
192
+ pulses
193
+ }));
194
+ }
195
+ /**
196
+ * Writes a code as learned Pronto hex, every pair sent once; a code ending on a mark gets a pause
197
+ * after it, since Pronto counts pairs.
198
+ *
199
+ * @param code - The code.
200
+ * @returns The words, upper case; null for a radio code, which Pronto cannot carry.
201
+ */
202
+ function encodePronto(code) {
203
+ if (code.signal !== "ir") return null;
204
+ const frequency = Math.min(65535, Math.max(1, Math.round(1e6 / (code.carrierHz * PRONTO_CLOCK_US))));
205
+ const period = frequency * PRONTO_CLOCK_US;
206
+ const pulses = code.pulses.length % 2 === 0 ? code.pulses : [...code.pulses, LEAD_OUT_US];
207
+ return [
208
+ 0,
209
+ frequency,
210
+ pulses.length / 2,
211
+ 0,
212
+ ...pulses.map((pulse) => Math.min(65535, Math.max(1, Math.round(pulse / period))))
213
+ ].map((word) => word.toString(16).toUpperCase().padStart(4, "0")).join(" ");
214
+ }
215
+ /**
216
+ * Reads a list of microseconds: unsigned, a mark and a space in turn - `9000 4500 560 …` - or
217
+ * signed, a mark positive and a space negative - `[9000, -4500, 560, …]` - where two of a kind in
218
+ * a row are one pulse and a leading space is dropped. Spaces, commas, semicolons and brackets all
219
+ * separate.
220
+ *
221
+ * @param text - The list.
222
+ * @param carrierHz - The carrier, which a list does not say.
223
+ * @returns The infrared code, its protocol recognised where it can be.
224
+ * @throws {ValidationError} When a value is not a whole number of microseconds above 0.
225
+ */
226
+ function decodeRawTimings(text, carrierHz = DEFAULT_IR_CARRIER_HZ) {
227
+ const tokens = text.replaceAll(/[[\]]/gu, " ").split(/[\s,;]+/u).filter((token) => token !== "");
228
+ const wrong = tokens.find((token) => !/^[+-]?\d{1,8}$/u.test(token) || Number(token) === 0);
229
+ if (wrong !== void 0) throw invalid(`${wrong.slice(0, 16)} is not a pulse: a whole number of microseconds above 0`);
230
+ const values = tokens.map(Number);
231
+ const pulses = [];
232
+ if (tokens.some((token) => token.startsWith("-"))) {
233
+ let isLastMark = false;
234
+ for (const value of values) {
235
+ const isMark = value > 0;
236
+ if (pulses.length > 0 && isMark === isLastMark) pulses[pulses.length - 1] = (pulses.at(-1) ?? 0) + Math.abs(value);
237
+ else if (pulses.length > 0 || isMark) pulses.push(Math.abs(value));
238
+ isLastMark = isMark;
239
+ }
240
+ } else pulses.push(...values);
241
+ return withInfraredProtocol(checked({
242
+ signal: "ir",
243
+ carrierHz,
244
+ pulses
245
+ }));
246
+ }
247
+ /**
248
+ * Writes a code as a signed list: a mark positive, a space negative.
249
+ *
250
+ * @param code - The code.
251
+ * @returns `9000, -4500, 560, …`.
252
+ */
253
+ function encodeRawTimings(code) {
254
+ return code.pulses.map((pulse, index) => String(index % 2 === 0 ? pulse : -pulse)).join(", ");
255
+ }
256
+ /** NEC: a 9 ms mark, a 4.5 ms space, 32 bits, a stop mark; a frame every 108 ms. */
257
+ const NEC = {
258
+ leaderMark: 9e3,
259
+ leaderSpace: 4500
260
+ };
261
+ /** Samsung32: NEC's bits after a 4.5 ms mark and a 4.5 ms space. */
262
+ const SAMSUNG = {
263
+ leaderMark: 4500,
264
+ leaderSpace: 4500
265
+ };
266
+ /** The mark of a NEC or Samsung bit, and the spaces of a 0 and a 1. */
267
+ const BIT_MARK = 560;
268
+ const ZERO_SPACE = 560;
269
+ const ONE_SPACE = 1690;
270
+ /** How often NEC and Samsung frames start. */
271
+ const NEC_FRAME_US = 108e3;
272
+ /** Sony SIRC: a 2.4 ms mark, then each bit a 1.2 ms (1) or 0.6 ms (0) mark and a 0.6 ms space. */
273
+ const SIRC_LEADER = 2400;
274
+ const SIRC_ONE = 1200;
275
+ const SIRC_UNIT = 600;
276
+ /** How often SIRC frames start, and how many a press sends: Sony sets want three. */
277
+ const SIRC_FRAME_US = 45e3;
278
+ const SIRC_FRAMES = 3;
279
+ /** RC5: half a bit, Manchester-coded; a frame every 64 bits. */
280
+ const RC5_HALF = 889;
281
+ const RC5_FRAME_US = 113778;
282
+ /** The carrier each protocol is sent on. */
283
+ const CARRIERS = {
284
+ nec: 38e3,
285
+ "nec-ext": 38e3,
286
+ samsung32: 38e3,
287
+ sirc: 4e4,
288
+ sirc15: 4e4,
289
+ sirc20: 4e4,
290
+ rc5: 36e3
291
+ };
292
+ /** The largest address and command each protocol carries. */
293
+ const LIMITS = {
294
+ nec: [255, 255],
295
+ "nec-ext": [65535, 65535],
296
+ samsung32: [255, 255],
297
+ sirc: [31, 127],
298
+ sirc15: [255, 127],
299
+ sirc20: [8191, 127],
300
+ rc5: [31, 127]
301
+ };
302
+ /**
303
+ * Whether a timing reads as the protocol's.
304
+ *
305
+ * @param value - The timing, if there is one.
306
+ * @param expected - The protocol's.
307
+ * @returns True within the tolerance.
308
+ */
309
+ function near(value, expected) {
310
+ return value !== void 0 && Math.abs(value - expected) <= expected * TOLERANCE;
311
+ }
312
+ /**
313
+ * Reads the 32 bits of a NEC or Samsung frame, the lowest first, and its stop mark.
314
+ *
315
+ * @param pulses - The pulses.
316
+ * @param leader - The frame's leader.
317
+ * @returns Its four bytes, or undefined when the pulses are not such a frame.
318
+ */
319
+ function readPulseDistance(pulses, leader) {
320
+ if (!near(pulses[0], leader.leaderMark) || !near(pulses[1], leader.leaderSpace)) return;
321
+ let bits = 0;
322
+ for (let bit = 0; bit < 32; bit += 1) {
323
+ const mark = pulses[2 + bit * 2];
324
+ const space = pulses[3 + bit * 2];
325
+ if (!near(mark, BIT_MARK)) return;
326
+ if (near(space, ONE_SPACE)) bits += 2 ** bit;
327
+ else if (!near(space, ZERO_SPACE)) return;
328
+ }
329
+ if (!near(pulses[66], BIT_MARK)) return;
330
+ return [
331
+ bits & 255,
332
+ bits >>> 8 & 255,
333
+ bits >>> 16 & 255,
334
+ bits >>> 24
335
+ ];
336
+ }
337
+ /**
338
+ * Writes a NEC or Samsung frame, the lowest bit first, padded to its frame time.
339
+ *
340
+ * @param leader - The frame's leader.
341
+ * @param bytes - The four bytes.
342
+ * @returns The pulses, ending on the pause.
343
+ */
344
+ function writePulseDistance(leader, bytes) {
345
+ const pulses = [leader.leaderMark, leader.leaderSpace];
346
+ for (const byte of bytes) for (let bit = 0; bit < 8; bit += 1) pulses.push(BIT_MARK, (byte >> bit & 1) === 1 ? ONE_SPACE : ZERO_SPACE);
347
+ pulses.push(BIT_MARK);
348
+ return withPause(pulses, NEC_FRAME_US);
349
+ }
350
+ /**
351
+ * A frame's pulses followed by the pause that fills it out to its frame time.
352
+ *
353
+ * @param pulses - The frame, ending on a mark.
354
+ * @param frameUs - How often frames start.
355
+ * @returns The pulses, ending on the pause.
356
+ */
357
+ function withPause(pulses, frameUs) {
358
+ const used = pulses.reduce((sum, pulse) => sum + pulse, 0);
359
+ return [...pulses, Math.max(MINIMUM_PAUSE_US, frameUs - used)];
360
+ }
361
+ /**
362
+ * Reads a NEC frame: NEC when the address and the command each come with their inverse, extended
363
+ * NEC - a 16-bit address and command, as a Flipper Zero reads them - otherwise.
364
+ *
365
+ * @param pulses - The pulses.
366
+ * @returns The protocol, or undefined.
367
+ */
368
+ function decodeNec(pulses) {
369
+ const bytes = readPulseDistance(pulses, NEC);
370
+ if (bytes === void 0) return;
371
+ const [address, addressInverse, command, commandInverse] = bytes;
372
+ return address === (~addressInverse & 255) && command === (~commandInverse & 255) ? {
373
+ name: "nec",
374
+ address,
375
+ command
376
+ } : {
377
+ name: "nec-ext",
378
+ address: address | addressInverse << 8,
379
+ command: command | commandInverse << 8
380
+ };
381
+ }
382
+ /**
383
+ * Reads a Samsung32 frame: the address twice, the command and its inverse.
384
+ *
385
+ * @param pulses - The pulses.
386
+ * @returns The protocol, or undefined.
387
+ */
388
+ function decodeSamsung(pulses) {
389
+ const bytes = readPulseDistance(pulses, SAMSUNG);
390
+ if (bytes === void 0) return;
391
+ const [address, again, command, inverse] = bytes;
392
+ return address === again && command === (~inverse & 255) ? {
393
+ name: "samsung32",
394
+ address,
395
+ command
396
+ } : void 0;
397
+ }
398
+ /**
399
+ * Reads a Sony SIRC frame - 12, 15 or 20 bits, the lowest first: a 7-bit command, then a 5-bit
400
+ * address, an 8-bit one, or a 5-bit one and 8 extended bits, read as one 13-bit address.
401
+ *
402
+ * @param pulses - The pulses.
403
+ * @returns The protocol, or undefined.
404
+ */
405
+ function decodeSirc(pulses) {
406
+ if (!near(pulses[0], SIRC_LEADER) || !near(pulses[1], SIRC_UNIT)) return;
407
+ let bits = 0;
408
+ let count = 0;
409
+ for (let index = 2; count <= 20; index += 2) {
410
+ if (near(pulses[index], SIRC_ONE)) bits += 2 ** count;
411
+ else if (!near(pulses[index], SIRC_UNIT)) return;
412
+ count += 1;
413
+ if (!near(pulses[index + 1], SIRC_UNIT)) break;
414
+ }
415
+ const command = bits & 127;
416
+ const address = bits >>> 7;
417
+ switch (count) {
418
+ case 12: return {
419
+ name: "sirc",
420
+ address,
421
+ command
422
+ };
423
+ case 15: return {
424
+ name: "sirc15",
425
+ address,
426
+ command
427
+ };
428
+ case 20: return {
429
+ name: "sirc20",
430
+ address,
431
+ command
432
+ };
433
+ default: return;
434
+ }
435
+ }
436
+ /**
437
+ * Reads an RC5 frame: 14 Manchester bits, the highest first - two start bits, a toggle, a 5-bit
438
+ * address and a 6-bit command. A second start bit of 0 is RC5's extended form, the command's
439
+ * seventh bit set.
440
+ *
441
+ * @param pulses - The pulses.
442
+ * @returns The protocol, or undefined.
443
+ */
444
+ function decodeRc5(pulses) {
445
+ const halves = [false];
446
+ for (const [index, pulse] of pulses.entries()) {
447
+ const isMark = index % 2 === 0;
448
+ const count = near(pulse, RC5_HALF) ? 1 : near(pulse, RC5_HALF * 2) ? 2 : 0;
449
+ if (count === 0) {
450
+ if (isMark) return;
451
+ break;
452
+ }
453
+ halves.push(...Array.from({ length: count }, () => isMark));
454
+ if (halves.length >= 28) break;
455
+ }
456
+ if (halves.length === 27) halves.push(false);
457
+ if (halves.length < 28) return;
458
+ let bits = 0;
459
+ for (let bit = 0; bit < 14; bit += 1) {
460
+ const first = halves[bit * 2];
461
+ const second = halves[bit * 2 + 1];
462
+ if (first === second) return;
463
+ bits = bits * 2 + (second === true ? 1 : 0);
464
+ }
465
+ if (bits >> 13 !== 1) return;
466
+ const isExtended = (bits >> 12 & 1) === 0;
467
+ return {
468
+ name: "rc5",
469
+ address: bits >> 6 & 31,
470
+ command: bits & 63 | (isExtended ? 64 : 0)
471
+ };
472
+ }
473
+ /**
474
+ * Recognises the protocol a train of pulses was sent in.
475
+ *
476
+ * @param pulses - The pulses, a mark first.
477
+ * @returns The protocol with its address and command, or undefined for one not recognised.
478
+ */
479
+ function decodeInfraredProtocol(pulses) {
480
+ return decodeNec(pulses) ?? decodeSamsung(pulses) ?? decodeSirc(pulses) ?? decodeRc5(pulses);
481
+ }
482
+ /**
483
+ * A code with its protocol, when its pulses are one the codec recognises.
484
+ *
485
+ * @param code - The code.
486
+ * @returns The code, with `protocol` when an infrared code's pulses are recognised.
487
+ */
488
+ function withInfraredProtocol(code) {
489
+ const protocol = code.signal === "ir" ? decodeInfraredProtocol(code.pulses) : void 0;
490
+ return protocol === void 0 ? code : {
491
+ ...code,
492
+ protocol
493
+ };
494
+ }
495
+ /**
496
+ * Writes a Sony SIRC press: three frames, each padded to 45 ms.
497
+ *
498
+ * @param protocol - The protocol.
499
+ * @returns The pulses.
500
+ */
501
+ function writeSirc(protocol) {
502
+ const count = protocol.name === "sirc" ? 12 : protocol.name === "sirc15" ? 15 : 20;
503
+ const bits = protocol.command + protocol.address * 128;
504
+ const frame = [SIRC_LEADER, SIRC_UNIT];
505
+ for (let bit = 0; bit < count; bit += 1) frame.push(Math.floor(bits / 2 ** bit) % 2 === 1 ? SIRC_ONE : SIRC_UNIT, SIRC_UNIT);
506
+ frame.pop();
507
+ return Array.from({ length: SIRC_FRAMES }, () => withPause(frame, SIRC_FRAME_US)).flat();
508
+ }
509
+ /**
510
+ * Writes an RC5 frame, the toggle bit 0, padded to its frame time.
511
+ *
512
+ * @param protocol - The protocol.
513
+ * @returns The pulses.
514
+ */
515
+ function writeRc5(protocol) {
516
+ const bits = [
517
+ 1,
518
+ protocol.command < 64 ? 1 : 0,
519
+ 0
520
+ ];
521
+ for (let bit = 4; bit >= 0; bit -= 1) bits.push(protocol.address >> bit & 1);
522
+ for (let bit = 5; bit >= 0; bit -= 1) bits.push(protocol.command >> bit & 1);
523
+ const halves = bits.flatMap((bit) => bit === 1 ? [false, true] : [true, false]);
524
+ const pulses = [];
525
+ let isMark = true;
526
+ for (const half of halves.slice(halves.indexOf(true))) if (pulses.length > 0 && half === isMark) pulses[pulses.length - 1] = (pulses.at(-1) ?? 0) + RC5_HALF;
527
+ else {
528
+ pulses.push(RC5_HALF);
529
+ isMark = half;
530
+ }
531
+ if (!isMark) pulses.pop();
532
+ return withPause(pulses, RC5_FRAME_US);
533
+ }
534
+ /**
535
+ * Writes a protocol's address and command as a code to send: what a Flipper Zero's `parsed` entry
536
+ * becomes.
537
+ *
538
+ * @param protocol - The protocol, its address and its command.
539
+ * @returns The code, on the protocol's carrier, the protocol beside it.
540
+ * @throws {ValidationError} When the address or the command does not fit the protocol.
541
+ */
542
+ function encodeInfraredProtocol(protocol) {
543
+ const [maximumAddress, maximumCommand] = LIMITS[protocol.name];
544
+ if (protocol.address > maximumAddress || protocol.command > maximumCommand) throw invalid(`${protocol.name} carries an address up to 0x${maximumAddress.toString(16)} and a command up to 0x${maximumCommand.toString(16)}`);
545
+ const { address, command } = protocol;
546
+ let pulses;
547
+ switch (protocol.name) {
548
+ case "nec":
549
+ pulses = writePulseDistance(NEC, [
550
+ address,
551
+ ~address & 255,
552
+ command,
553
+ ~command & 255
554
+ ]);
555
+ break;
556
+ case "nec-ext":
557
+ pulses = writePulseDistance(NEC, [
558
+ address & 255,
559
+ address >> 8,
560
+ command & 255,
561
+ command >> 8
562
+ ]);
563
+ break;
564
+ case "samsung32":
565
+ pulses = writePulseDistance(SAMSUNG, [
566
+ address,
567
+ address,
568
+ command,
569
+ ~command & 255
570
+ ]);
571
+ break;
572
+ case "rc5":
573
+ pulses = writeRc5(protocol);
574
+ break;
575
+ default: pulses = writeSirc(protocol);
576
+ }
577
+ return {
578
+ signal: "ir",
579
+ carrierHz: CARRIERS[protocol.name],
580
+ pulses,
581
+ protocol
582
+ };
583
+ }
584
+ /** The protocols a Flipper Zero names that the codec writes, by the platform's names. */
585
+ const FLIPPER_PROTOCOLS = {
586
+ NEC: "nec",
587
+ NECext: "nec-ext",
588
+ Samsung32: "samsung32",
589
+ SIRC: "sirc",
590
+ SIRC15: "sirc15",
591
+ SIRC20: "sirc20",
592
+ RC5: "rc5",
593
+ RC5X: "rc5"
594
+ };
595
+ /** The file types a Flipper Zero saves infrared signals as: one remote's, or a library's. */
596
+ const FLIPPER_FILE_TYPES = ["IR signals file", "IR library file"];
597
+ /**
598
+ * A number a Flipper Zero writes as its bytes, the lowest first: `07 00 00 00`.
599
+ *
600
+ * @param value - The bytes, in hex.
601
+ * @returns The number, or undefined when they are not one to four bytes.
602
+ */
603
+ function flipperNumberOf(value) {
604
+ if (!/^[0-9A-Fa-f]{2}(?: [0-9A-Fa-f]{2}){0,3}$/u.test(value.trim())) return;
605
+ return value.trim().split(" ").reduceRight((number, byte) => number * 256 + parseInt(byte, 16), 0);
606
+ }
607
+ /**
608
+ * Turns one entry of a Flipper Zero file into a code.
609
+ *
610
+ * @param entry - The entry.
611
+ * @returns The code, or the problem with it.
612
+ */
613
+ function flipperCodeOf(entry) {
614
+ /**
615
+ * One field of the entry.
616
+ *
617
+ * @param key - Its key.
618
+ * @returns Its value and line, or undefined when the entry has none.
619
+ */
620
+ const field = (key) => entry.fields.get(key);
621
+ /**
622
+ * A problem of the entry.
623
+ *
624
+ * @param reason - Why, in a sentence.
625
+ * @param at - The field it is on; the entry's first line when none.
626
+ * @param at.line - The field's line.
627
+ * @returns The problem.
628
+ */
629
+ const problem = (reason, at) => ({
630
+ line: at?.line ?? entry.line,
631
+ text: entry.text.slice(0, 256),
632
+ reason
633
+ });
634
+ const type = field("type");
635
+ try {
636
+ if (type?.value === "parsed") {
637
+ const protocol = field("protocol");
638
+ const name = protocol === void 0 ? void 0 : FLIPPER_PROTOCOLS[protocol.value];
639
+ if (protocol === void 0 || name === void 0) return problem(protocol === void 0 ? "A parsed entry names no protocol" : `Nebula does not read ${protocol.value.slice(0, 32)} codes yet`, protocol);
640
+ const address = flipperNumberOf(field("address")?.value ?? "");
641
+ const command = flipperNumberOf(field("command")?.value ?? "");
642
+ if (address === void 0 || command === void 0) return problem("An address and a command are each one to four hex bytes", field(address === void 0 ? "address" : "command"));
643
+ const isExtended = protocol.value === "RC5X";
644
+ return {
645
+ name: entry.name,
646
+ line: entry.line,
647
+ code: encodeInfraredProtocol({
648
+ name,
649
+ address,
650
+ command: isExtended ? command | 64 : command
651
+ })
652
+ };
653
+ }
654
+ if (type?.value === "raw") {
655
+ const frequency = Number(field("frequency")?.value);
656
+ const data = field("data");
657
+ if (!Number.isInteger(frequency) || frequency <= 0) return problem("A raw entry needs its frequency in Hz", field("frequency"));
658
+ if (data === void 0) return problem("A raw entry needs its data", type);
659
+ return {
660
+ name: entry.name,
661
+ line: entry.line,
662
+ code: decodeRawTimings(data.value, frequency)
663
+ };
664
+ }
665
+ return problem(type === void 0 ? "An entry says no type" : `An entry is parsed or raw, not ${type.value.slice(0, 32)}`, type);
666
+ } catch (error) {
667
+ return problem(error instanceof Error ? error.message : String(error), field("data"));
668
+ }
669
+ }
670
+ /**
671
+ * Reads a Flipper Zero `.ir` file - one remote's signals, or a library's - every entry a button:
672
+ * `name`, then `type: parsed` with a `protocol`, an `address` and a `command`, or `type: raw` with
673
+ * a `frequency`, a `duty_cycle` and the `data` in microseconds.
674
+ *
675
+ * @param text - The file.
676
+ * @returns The codes, each named as its entry, and every line that could not be used, with why.
677
+ */
678
+ function parseFlipperIr(text) {
679
+ const codes = [];
680
+ const problems = [];
681
+ let entry;
682
+ /** Ends the entry being read, as a code or a problem. */
683
+ const finish = () => {
684
+ if (entry !== void 0) {
685
+ const found = flipperCodeOf(entry);
686
+ if ("code" in found) codes.push(found);
687
+ else problems.push(found);
688
+ }
689
+ };
690
+ for (const [index, raw] of text.split(/\r?\n/u).entries()) {
691
+ const line = index + 1;
692
+ const trimmed = raw.trim();
693
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
694
+ const match = /^([A-Za-z_]+):\s*(.*)$/u.exec(trimmed);
695
+ if (match === null) {
696
+ problems.push({
697
+ line,
698
+ text: trimmed.slice(0, 256),
699
+ reason: "Not a \"key: value\" line"
700
+ });
701
+ continue;
702
+ }
703
+ const [, key = "", value = ""] = match;
704
+ if (key === "Filetype" && !FLIPPER_FILE_TYPES.includes(value)) return {
705
+ codes: [],
706
+ problems: [{
707
+ line,
708
+ text: trimmed.slice(0, 256),
709
+ reason: "Not a Flipper Zero infrared file"
710
+ }]
711
+ };
712
+ if (key === "Filetype" || key === "Version") continue;
713
+ if (key === "name") {
714
+ finish();
715
+ entry = {
716
+ name: value.slice(0, 64),
717
+ line,
718
+ text: trimmed,
719
+ fields: /* @__PURE__ */ new Map()
720
+ };
721
+ continue;
722
+ }
723
+ if (entry === void 0) {
724
+ problems.push({
725
+ line,
726
+ text: trimmed.slice(0, 256),
727
+ reason: "A field before the first name"
728
+ });
729
+ continue;
730
+ }
731
+ const known = entry.fields.get(key);
732
+ entry.fields.set(key, key === "data" && known !== void 0 ? {
733
+ ...known,
734
+ value: `${known.value} ${value}`
735
+ } : {
736
+ value,
737
+ line
738
+ });
739
+ }
740
+ finish();
741
+ return {
742
+ codes,
743
+ problems
744
+ };
745
+ }
746
+ //#endregion
6
747
  //#region ../package-runtime/dist/stream.js
7
748
  /**
8
749
  * Turns a stream source written against its own configuration into one a registry can hold,
@@ -89,7 +830,7 @@ function defineTransport(spec) {
89
830
  * bundle built with this SDK says `^<major>.<minor>.0`.
90
831
  */
91
832
  /** The SDK's own version: `1.0.0`, or a prerelease of it. */
92
- const SDK_VERSION = "1.5.0";
833
+ const SDK_VERSION = "1.6.1";
93
834
  /**
94
835
  * The runtime range a bundle built with this SDK declares: this version's major and minor, so a
95
836
  * platform with the same contract or a later one of the same major loads it.
@@ -105,12 +846,14 @@ function sdkRangeOf(version) {
105
846
  //#region src/testing/fake-sdk.ts
106
847
  /**
107
848
  * A {@link BundleSdk} for tests: the real pieces where they are pure - zod, `defineTransport`,
108
- * `defineAccount`, `defineStreamSource` - a logger that keeps what it was told, UDP sockets and
109
- * WebSockets that keep what was sent and take what a test delivers, and nothing else. A WebSocket
110
- * here connects to nothing: the test opens it, drops it and opens it again, as the network and the
111
- * hub's reconnection would. An MQTT session, an RTSP stream and the codecs are the hub's; a test
112
- * that needs one passes its own in `overrides`, and one that reaches for a piece nobody passed is
113
- * told so by name.
849
+ * `defineAccount`, `defineStreamSource`, the infrared codec - a logger that keeps what it was
850
+ * told, UDP sockets, WebSockets and serial ports that keep what was sent and take what a test
851
+ * delivers, Bluetooth scanners that keep what a proxy reported, and nothing else. A WebSocket here
852
+ * connects to nothing: the test opens it, drops it and opens it again, as the network and the
853
+ * hub's reconnection would; a serial port is any port the code names, held by it alone. An MQTT
854
+ * session, a Modbus session, an RTSP stream and the other codecs are the hub's; a test that needs
855
+ * one passes its own in `overrides`, and one that reaches for a piece nobody passed is told so by
856
+ * name.
114
857
  */
115
858
  /** The first port a fake socket says it is bound to, when the bundle asks for none. */
116
859
  const FIRST_FREE_PORT = 4e4;
@@ -126,6 +869,16 @@ function notFaked(name) {
126
869
  };
127
870
  }
128
871
  /**
872
+ * An error the Serial broker refuses with, named as the hub names it.
873
+ *
874
+ * @param name - `SerialPortHeld`, `SerialClosed`.
875
+ * @param message - The sentence.
876
+ * @returns The error.
877
+ */
878
+ function serialFailure(name, message) {
879
+ return Object.assign(new Error(message), { name });
880
+ }
881
+ /**
129
882
  * A logger that keeps what it is told.
130
883
  *
131
884
  * @param logs - Where it keeps it.
@@ -182,6 +935,10 @@ function createFakeSdk(options = {}) {
182
935
  const logs = [];
183
936
  const udpSockets = [];
184
937
  const webSockets = [];
938
+ const serialPorts = [];
939
+ const bluetoothScanners = [];
940
+ /** Closes each scanner opened, by the proxy it is: opening another for it closes the first. */
941
+ const scannerClosers = [];
185
942
  /** Closes each socket opened, for the release. */
186
943
  const closers = [];
187
944
  /**
@@ -380,6 +1137,113 @@ function createFakeSdk(options = {}) {
380
1137
  }
381
1138
  };
382
1139
  };
1140
+ /**
1141
+ * Opens a fake serial port: any port, held by the bundle alone - a second open of one still
1142
+ * open is refused, as the broker refuses it.
1143
+ *
1144
+ * @param portId - The port.
1145
+ * @param input - How it is spoken.
1146
+ * @returns The session.
1147
+ * @throws {ValidationError} When the line is not one.
1148
+ * @throws {Error} `SerialPortHeld` when the port is open already.
1149
+ */
1150
+ const openSerial = async (portId, input) => {
1151
+ const parsed = serialLineSchema.safeParse(input);
1152
+ if (!parsed.success) throw new ValidationError("The serial line is not one", { details: { portId } });
1153
+ if (serialPorts.some((port) => port.portId === portId && !port.isClosed)) throw serialFailure("SerialPortHeld", "The port is open already");
1154
+ const written = [];
1155
+ const dataListeners = /* @__PURE__ */ new Set();
1156
+ const closeListeners = /* @__PURE__ */ new Set();
1157
+ let isClosed = false;
1158
+ /**
1159
+ * Ends the session once, telling the bundle why.
1160
+ *
1161
+ * @param reason - Why.
1162
+ */
1163
+ const finish = (reason) => {
1164
+ if (isClosed) return;
1165
+ isClosed = true;
1166
+ for (const listener of closeListeners) listener(reason);
1167
+ };
1168
+ serialPorts.push({
1169
+ portId,
1170
+ line: parsed.data,
1171
+ written,
1172
+ /**
1173
+ * Whether it was closed.
1174
+ *
1175
+ * @returns True once it was.
1176
+ */
1177
+ get isClosed() {
1178
+ return isClosed;
1179
+ },
1180
+ /**
1181
+ * Hands the bundle bytes.
1182
+ *
1183
+ * @param bytes - What the port read.
1184
+ * @throws {Error} When the port is closed.
1185
+ */
1186
+ feed: (bytes) => {
1187
+ if (isClosed) throw new Error(`The serial port ${portId} is closed`);
1188
+ const chunk = Buffer.from(bytes);
1189
+ for (const listener of dataListeners) listener(chunk);
1190
+ },
1191
+ /**
1192
+ * Takes the port away.
1193
+ *
1194
+ * @param reason - Why.
1195
+ */
1196
+ unplug: (reason = "Unplugged") => {
1197
+ finish(reason);
1198
+ }
1199
+ });
1200
+ closers.push(() => {
1201
+ isClosed = true;
1202
+ });
1203
+ return Promise.resolve({
1204
+ /**
1205
+ * Keeps bytes the bundle writes.
1206
+ *
1207
+ * @param bytes - What it writes.
1208
+ * @returns Once kept.
1209
+ * @throws {Error} `SerialClosed` once the session is closed.
1210
+ */
1211
+ write: async (bytes) => {
1212
+ if (isClosed) throw serialFailure("SerialClosed", "The port is closed");
1213
+ written.push(Buffer.from(bytes));
1214
+ return Promise.resolve();
1215
+ },
1216
+ /**
1217
+ * Hears what the test feeds.
1218
+ *
1219
+ * @param listener - Called with each chunk.
1220
+ * @returns Stops hearing.
1221
+ */
1222
+ onData: (listener) => {
1223
+ dataListeners.add(listener);
1224
+ return () => dataListeners.delete(listener);
1225
+ },
1226
+ /**
1227
+ * Hears the port go, once.
1228
+ *
1229
+ * @param listener - Called with why.
1230
+ * @returns Stops hearing.
1231
+ */
1232
+ onClose: (listener) => {
1233
+ closeListeners.add(listener);
1234
+ return () => closeListeners.delete(listener);
1235
+ },
1236
+ /**
1237
+ * Lets go of the port.
1238
+ *
1239
+ * @returns Once closed.
1240
+ */
1241
+ close: async () => {
1242
+ finish("Closed");
1243
+ return Promise.resolve();
1244
+ }
1245
+ });
1246
+ };
383
1247
  return {
384
1248
  sdk: {
385
1249
  version: SDK_VERSION,
@@ -392,15 +1256,73 @@ function createFakeSdk(options = {}) {
392
1256
  openWebSocket,
393
1257
  openMqtt: notFaked("openMqtt"),
394
1258
  openModbus: notFaked("openModbus"),
1259
+ openSerial,
1260
+ bluetooth: {
1261
+ /**
1262
+ * Opens a fake proxy's scanner, closing the one opened before for the same proxy.
1263
+ *
1264
+ * @param scannerOptions - The proxy: its connection's key and its device key.
1265
+ * @returns The scanner.
1266
+ */
1267
+ scanner: (scannerOptions) => {
1268
+ const reports = [];
1269
+ const adverts = [];
1270
+ let isClosed = false;
1271
+ /** Stops it taking reports. */
1272
+ const close = () => {
1273
+ isClosed = true;
1274
+ };
1275
+ for (const earlier of scannerClosers) if (earlier.options.key === scannerOptions.key && earlier.options.deviceKey === scannerOptions.deviceKey) earlier.close();
1276
+ bluetoothScanners.push({
1277
+ options: scannerOptions,
1278
+ reports,
1279
+ adverts,
1280
+ /**
1281
+ * Whether it was closed.
1282
+ *
1283
+ * @returns True once it was.
1284
+ */
1285
+ get isClosed() {
1286
+ return isClosed;
1287
+ }
1288
+ });
1289
+ scannerClosers.push({
1290
+ options: scannerOptions,
1291
+ close
1292
+ });
1293
+ closers.push(close);
1294
+ return {
1295
+ /**
1296
+ * Keeps a report, and what of it the house keeps; nothing once closed, as the broker
1297
+ * takes nothing then.
1298
+ *
1299
+ * @param heard - The advertisements.
1300
+ */
1301
+ report: (heard) => {
1302
+ if (isClosed) return;
1303
+ reports.push([...heard]);
1304
+ for (const advert of heard.slice(0, 1024)) {
1305
+ const parsed = bluetoothAdvertSchema.safeParse(advert);
1306
+ if (parsed.success) adverts.push(parsed.data);
1307
+ }
1308
+ },
1309
+ close
1310
+ };
1311
+ } },
395
1312
  openRtsp: notFaked("openRtsp"),
396
1313
  platform: options.platform ?? { mqtt: null },
397
- codecs: { lzma: notFaked("codecs.lzma") },
1314
+ codecs: {
1315
+ lzma: notFaked("codecs.lzma"),
1316
+ infrared: infrared_codes_exports
1317
+ },
398
1318
  images: { png: notFaked("images.png") },
399
1319
  ...options.overrides
400
1320
  },
401
1321
  logs,
402
1322
  udpSockets,
403
1323
  webSockets,
1324
+ serialPorts,
1325
+ bluetoothScanners,
404
1326
  /**
405
1327
  * Closes what the bundle left open.
406
1328
  *