node-red-contrib-relink 0.1.1 → 0.1.2

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.
@@ -0,0 +1,76 @@
1
+ [
2
+ {
3
+ "id": "relink-schedule",
4
+ "type": "tab",
5
+ "label": "Relink — schedule",
6
+ "disabled": false,
7
+ "info": "Switch V1 on at 06:00 and off at 06:30 every day. Add V1 Integer; edit the times in the two Inject nodes."
8
+ },
9
+ {
10
+ "id": "sc_on",
11
+ "type": "inject",
12
+ "name": "Every day 06:00",
13
+ "props": [
14
+ {
15
+ "p": "payload"
16
+ }
17
+ ],
18
+ "repeat": "",
19
+ "crontab": "00 06 * * *",
20
+ "once": false,
21
+ "payload": "1",
22
+ "payloadType": "num",
23
+ "x": 160,
24
+ "y": 80,
25
+ "wires": [
26
+ [
27
+ "sc_out"
28
+ ]
29
+ ],
30
+ "z": "relink-schedule"
31
+ },
32
+ {
33
+ "id": "sc_off",
34
+ "type": "inject",
35
+ "name": "Every day 06:30",
36
+ "props": [
37
+ {
38
+ "p": "payload"
39
+ }
40
+ ],
41
+ "repeat": "",
42
+ "crontab": "30 06 * * *",
43
+ "once": false,
44
+ "payload": "0",
45
+ "payloadType": "num",
46
+ "x": 160,
47
+ "y": 160,
48
+ "wires": [
49
+ [
50
+ "sc_out"
51
+ ]
52
+ ],
53
+ "z": "relink-schedule"
54
+ },
55
+ {
56
+ "id": "sc_out",
57
+ "type": "relink out",
58
+ "name": "Pump V1",
59
+ "connection": "rl_conn",
60
+ "pin": "V1",
61
+ "dtype": "auto",
62
+ "x": 420,
63
+ "y": 120,
64
+ "wires": [],
65
+ "z": "relink-schedule"
66
+ },
67
+ {
68
+ "id": "rl_conn",
69
+ "type": "relink-connection",
70
+ "name": "My Relink device",
71
+ "server": "relink-iot.com",
72
+ "port": 7445,
73
+ "apiBase": "https://relink-iot.com",
74
+ "mesh": true
75
+ }
76
+ ]
package/lib/client.js CHANGED
@@ -8,6 +8,10 @@ const http = require("node:http");
8
8
  const https = require("node:https");
9
9
  const { performance } = require("node:perf_hooks");
10
10
  const { crc32, pinNumber, encodeEntry, decodeValue, decodeBatch, seal, open, NAMES, coerceKind, parseKinds } = require("./protocol");
11
+ const { CAM_CHUNK, AUDIO_RATES, AUDIO_PER, ulawEncode, ULAW_DEC, CamAssembly, Resampler } = require("./media");
12
+
13
+ const CAM_SUB_EVERY = 1000; // viewer / listener refreshes its subscribe ('C' / 'a')
14
+ const CAM_SUB_TIMEOUT = 3000; // sender: a viewer that stopped refreshing has left
11
15
 
12
16
  const MASK48 = (1n << 48n) - 1n;
13
17
  const WINDOW_MASK = (1n << 1024n) - 1n;
@@ -61,6 +65,25 @@ class RelinkClient extends EventEmitter {
61
65
  this.lastSummary = monotonic();
62
66
  this.retry = 500;
63
67
  this.state = "disconnected";
68
+ // Our public addresses as STUN servers see them. Some networks pick a
69
+ // public IP per destination, so peers hello every one (sent as 'T').
70
+ this.myPublic = [];
71
+ this.lastStun = -Infinity;
72
+ this.stunTid = null;
73
+ // Camera and audio: peer-to-peer only (never through the relay), like
74
+ // the other libraries. Viewer side: pins we watch / listen to.
75
+ this.camWatch = new Set();
76
+ this.camKicked = false; // another viewer took the stream (one at a time)
77
+ this.camAsm = new Map();
78
+ this.lastCamSub = -Infinity;
79
+ this.audListen = new Set();
80
+ this.audQuality = 0; // 0 Voice 8 kHz, 1 Standard 16 kHz, 2 High 48 kHz
81
+ this.lastAudSub = -Infinity;
82
+ // Sender side: the peer that watches our camera, our audio stream state.
83
+ this.camOwner = null;
84
+ this.camFid = 0;
85
+ this.audSid = 0; this.audSeq = 0;
86
+ this.audOut = new Map(); // "pin:quality" -> Resampler
64
87
  }
65
88
 
66
89
  _status(state) {
@@ -153,6 +176,8 @@ class RelinkClient extends EventEmitter {
153
176
  this.connected = false;
154
177
  this.salt = 0;
155
178
  this.allowed = null;
179
+ this.stunTid = null; this.myPublic = []; this.lastStun = -Infinity;
180
+ this.camOwner = null; this.camAsm.clear(); this.audOut.clear();
156
181
  this.offset = undefined;
157
182
  const socket = this.socket;
158
183
  this.socket = null;
@@ -173,7 +198,7 @@ class RelinkClient extends EventEmitter {
173
198
  if (relay && !this.salt && inner[0] !== 82) return;
174
199
  const destination = remote || { address: this.address, port: this.port };
175
200
  const packet = seal(this.key, this.deviceId, this._nextNonce(), inner, relay ? this.salt : 0);
176
- if (this.sendQueue.length >= 512) return; // bounded even under socket backpressure
201
+ if (this.sendQueue.length >= 1024) return; // bounded even under socket backpressure
177
202
  this.sendQueue.push({ packet, destination, ttl });
178
203
  this._drainSend();
179
204
  }
@@ -199,6 +224,56 @@ class RelinkClient extends EventEmitter {
199
224
  _register() {
200
225
  this.lastRegister = monotonic();
201
226
  this._send(Buffer.concat([Buffer.from("R" + this.token), Buffer.from([0]), Buffer.from("MS"), Buffer.from([0]), Buffer.from(this.lan)]));
227
+ if (this.mesh) this._sendPublic(); // a restarted relay lost them
228
+ }
229
+
230
+ // ['T'][k] k x [ip:4][port:2], network order.
231
+ _sendPublic() {
232
+ if (!this.myPublic.length || !this.salt) return;
233
+ const t = Buffer.alloc(2 + 6 * this.myPublic.length);
234
+ t[0] = 84; t[1] = this.myPublic.length;
235
+ this.myPublic.forEach(({ address, port }, i) => {
236
+ address.split(".").forEach((n, k) => { t[2 + i * 6 + k] = Number(n); });
237
+ t.writeUInt16BE(port, 6 + i * 6);
238
+ });
239
+ this._send(t);
240
+ }
241
+
242
+ // Binding requests go out from the main socket: that is the mapping peers need.
243
+ async _stunKick() {
244
+ const tid = crypto.randomBytes(12);
245
+ this.stunTid = tid; this.myPublic = []; // mappings drift: start over
246
+ const req = Buffer.alloc(20);
247
+ req.writeUInt16BE(1, 0); req.writeUInt32BE(0x2112A442, 4); tid.copy(req, 8);
248
+ const servers = [[this.server, 3478], ["stun.l.google.com", 19302], ["stun.cloudflare.com", 3478]];
249
+ await Promise.all(servers.map(async ([host, port]) => {
250
+ try {
251
+ const { address } = await dns.lookup(host, { family: 4 });
252
+ for (let r = 0; r < 2; r++) if (this.socket && this.stunTid === tid) this.socket.send(req, port, address, () => {});
253
+ } catch (_) { /* that STUN server is unreachable; the others may answer */ }
254
+ }));
255
+ }
256
+
257
+ // Binding success: XOR-MAPPED-ADDRESS (or MAPPED-ADDRESS) for our transaction.
258
+ _onStun(b) {
259
+ if (!this.stunTid || b.readUInt32BE(4) !== 0x2112A442 || !b.subarray(8, 20).equals(this.stunTid)) return;
260
+ const len = b.readUInt16BE(2) + 20;
261
+ if (len > b.length) return;
262
+ for (let p = 20; p + 4 <= len;) {
263
+ const type = b.readUInt16BE(p), al = b.readUInt16BE(p + 2), v = p + 4;
264
+ if (v + al > len) break;
265
+ if ((type === 0x0020 || type === 0x0001) && al >= 8 && b[v + 1] === 1) {
266
+ let port = b.readUInt16BE(v + 2), ip = b.readUInt32BE(v + 4);
267
+ if (type === 0x0020) { port ^= 0x2112; ip = (ip ^ 0x2112A442) >>> 0; }
268
+ const address = [ip >>> 24, (ip >>> 16) & 255, (ip >>> 8) & 255, ip & 255].join(".");
269
+ if (this.myPublic.length < 3 && !this.myPublic.some(a => a.address === address && a.port === port)) {
270
+ this.myPublic.push({ address, port });
271
+ this._sendPublic();
272
+ }
273
+ return;
274
+ }
275
+ p = v + ((al + 3) & ~3);
276
+ }
202
277
  }
203
278
 
204
279
  write(pin, value, type = "auto") {
@@ -207,7 +282,7 @@ class RelinkClient extends EventEmitter {
207
282
  // so the bytes are right on direct links too (Integer -> Int16 when it fits).
208
283
  const kind = this.kinds.get(pinNumber(pin));
209
284
  if (kind) {
210
- const c = coerceKind(kind, value);
285
+ const c = coerceKind(kind, value, type);
211
286
  if (!c) throw new Error("Payload doesn't fit this datastream's type");
212
287
  value = c.value; type = c.type;
213
288
  }
@@ -216,7 +291,7 @@ class RelinkClient extends EventEmitter {
216
291
  if (this.allowed && !this.allowed.has(pin)) throw new Error("Pin is not declared in this device's datastreams");
217
292
  // One latest value per pin bounds memory during outages, like the relay.
218
293
  this.pending.set(pin, entry);
219
- if (entry[1] <= 2) {
294
+ if (entry[1] <= 2 || entry[1] === 5 || entry[1] === 6) {
220
295
  const v = decodeValue(entry[1], entry.subarray(2));
221
296
  const s = this.summaries.get(pin);
222
297
  if (s) { s.n++; s.min = Math.min(s.min, v); s.max = Math.max(s.max, v); s.sum += v; s.last = v; }
@@ -332,6 +407,16 @@ class RelinkClient extends EventEmitter {
332
407
  const destinations = heard ? [peer.address] : peer.candidates;
333
408
  destinations.forEach((remote, i) => this._hello(remote, priming && i === 0 ? 2 : 0, heard));
334
409
  }
410
+ if (this.mesh && this.connected && now - this.lastStun >= 300000) { this.lastStun = now; this._stunKick(); }
411
+ if (this.mesh && this.allowed && this.salt) {
412
+ if (this.camWatch.size && !this.camKicked && now - this.lastCamSub >= CAM_SUB_EVERY) {
413
+ this.lastCamSub = now; this._ctl(Buffer.from([67, 1]));
414
+ }
415
+ if (this.audListen.size && now - this.lastAudSub >= CAM_SUB_EVERY) {
416
+ this.lastAudSub = now;
417
+ for (const pin of this.audListen) this._ctl(Buffer.from([97, pin, 1, this.audQuality]));
418
+ }
419
+ }
335
420
  this._links();
336
421
  this._flush(now);
337
422
  if (this.salt && this.connected && now - this.lastSummary >= 60000) {
@@ -350,6 +435,7 @@ class RelinkClient extends EventEmitter {
350
435
  this._status("connecting");
351
436
  return;
352
437
  }
438
+ if (data.length >= 32 && data[0] === 1 && data[1] === 1) { this._onStun(data); return; }
353
439
  const { nonce, inner } = open(this.key, this.deviceId, data);
354
440
  const instance = Number(nonce >> 48n);
355
441
  if (instance === 0) {
@@ -381,6 +467,10 @@ class RelinkClient extends EventEmitter {
381
467
  if (!wasHeard) this._hello(peer.address, 0, true);
382
468
  if (wasUp !== this._up(peer)) this._links(true);
383
469
  if (inner[0] === 68) this._dispatch(decodeBatch(inner, true), "p2p");
470
+ else if (inner[0] === 74) this._camSlice(inner);
471
+ else if (inner[0] === 65 || inner[0] === 119) this._audioIn(inner);
472
+ else if (inner[0] === 67 || (inner[0] === 97 && inner.length >= 3)) this._peerCtl(instance, peer, inner);
473
+ else if (inner[0] === 75 && !this.camKicked) { this.camKicked = true; this.emit("camera-kicked"); }
384
474
  } catch (_) { /* Invalid, forged, or truncated datagrams never reach flows. */ }
385
475
  }
386
476
 
@@ -429,6 +519,146 @@ class RelinkClient extends EventEmitter {
429
519
  if (port) peer.fwd = { address: [...frame.subarray(3, 7)].join("."), port };
430
520
  peer.fwdRx = monotonic();
431
521
  if (!was) this._links(true);
522
+ const m = frame.subarray(9);
523
+ if (m[0] === 67 || (m[0] === 97 && m.length >= 3)) this._peerCtl(frame.readUInt16LE(1), peer, m);
524
+ }
525
+
526
+ // A camera / audio subscribe to every listed peer: directly when it answers,
527
+ // and always through the relay ('F') too -- on mobile data a peer often can't
528
+ // hear us directly even while we hear it.
529
+ _ctl(msg) {
530
+ const now = monotonic();
531
+ for (const [id, peer] of this.peers) {
532
+ if (this._up(peer)) this._send(msg, peer.address);
533
+ const f = Buffer.alloc(9 + msg.length);
534
+ f[0] = 70; f.writeUInt16LE(id, 1);
535
+ if (now - peer.reachAt < 5000) peer.reach.copy(f, 3);
536
+ msg.copy(f, 9);
537
+ this._send(f);
538
+ }
539
+ }
540
+
541
+ // A viewer's camera subscribe ['C'][on] or a listener's ['a'][pin][on][quality].
542
+ // A viewer that starts watching takes the stream over; the one it replaces gets 'K'.
543
+ _peerCtl(id, peer, m) {
544
+ const now = monotonic();
545
+ if (m[0] === 97) { peer.audQ = m.length >= 4 ? Math.min(m[3], 2) : 0; peer.audRx = m[2] ? now : -Infinity; return; }
546
+ const on = m.length < 2 || !!m[1];
547
+ const starting = on && now - peer.camRx > CAM_SUB_TIMEOUT;
548
+ peer.camRx = on ? now : -Infinity;
549
+ if (starting && this.camOwner !== id) {
550
+ const old = this.peers.get(this.camOwner);
551
+ if (old && this._reachable(old)) { this._send(Buffer.from("K"), this._tx(old)); old.camRx = -Infinity; }
552
+ this.camOwner = id;
553
+ } else if (!on && this.camOwner === id) this.camOwner = null;
554
+ }
555
+
556
+ _camSlice(inner) {
557
+ if (inner.length < 8 || !this.camWatch.has(inner[1])) return;
558
+ const pin = inner[1];
559
+ let asm = this.camAsm.get(pin);
560
+ if (!asm) this.camAsm.set(pin, asm = new CamAssembly());
561
+ const frame = asm.add(inner.readUInt16LE(2), inner.readUInt16LE(4), inner.readUInt16LE(6), inner.subarray(8));
562
+ if (frame) this.emit("camera", { pin, frame, frameId: inner.readUInt16LE(2), checksum: this.deviceId });
563
+ }
564
+
565
+ _audioIn(inner) {
566
+ const pin = inner[1];
567
+ if (!this.audListen.has(pin)) return;
568
+ let samples, rate;
569
+ if (inner[0] === 65 && inner.length > 6) {
570
+ samples = Int16Array.from(inner.subarray(6), b => ULAW_DEC[b]); rate = 8000;
571
+ } else if (inner[0] === 119 && inner.length > 7 && (inner[6] === 1 || inner[6] === 2)) {
572
+ const n = Math.min((inner.length - 7) >> 1, 960);
573
+ samples = new Int16Array(n);
574
+ for (let i = 0; i < n; i++) samples[i] = inner.readInt16LE(7 + 2 * i);
575
+ rate = AUDIO_RATES[inner[6]];
576
+ } else return;
577
+ this.emit("audio", { pin, samples, rate, checksum: this.deviceId });
578
+ }
579
+
580
+ // Viewer: ask the devices on this token for camera frames on pin.
581
+ watchCamera(pin, on = true) {
582
+ pin = pinNumber(pin);
583
+ if (on) { this.camWatch.add(pin); this.camKicked = false; this.lastCamSub = -Infinity; }
584
+ else {
585
+ this.camWatch.delete(pin); this.camAsm.delete(pin);
586
+ if (!this.camWatch.size && this.salt) this._ctl(Buffer.from([67, 0]));
587
+ }
588
+ }
589
+
590
+ // Listener: ask for sound on pin at a quality (0 Voice, 1 Standard, 2 High).
591
+ listenAudio(pin, on = true, quality = this.audQuality) {
592
+ pin = pinNumber(pin);
593
+ this.audQuality = Math.max(0, Math.min(2, quality | 0));
594
+ if (on) { this.audListen.add(pin); this.lastAudSub = -Infinity; }
595
+ else { this.audListen.delete(pin); if (this.salt) this._ctl(Buffer.from([97, pin, 0, this.audQuality])); }
596
+ }
597
+
598
+ // True while a peer watches our camera: check before grabbing a frame.
599
+ cameraWanted() {
600
+ const peer = this.camOwner !== null ? this.peers.get(this.camOwner) : null;
601
+ return !!(peer && this._reachable(peer) && monotonic() - peer.camRx <= CAM_SUB_TIMEOUT);
602
+ }
603
+
604
+ // One JPEG frame to the viewer, in 1024-byte encrypted slices straight to it.
605
+ // false = nobody watches (nothing sent).
606
+ cameraWrite(pin, jpeg) {
607
+ pin = pinNumber(pin);
608
+ if (!Buffer.isBuffer(jpeg)) throw new Error("Camera frame must be a Buffer (JPEG)");
609
+ const cnt = Math.ceil(jpeg.length / CAM_CHUNK);
610
+ if (!cnt || cnt > 400 || !this.cameraWanted()) return false; // 400 KB: the send queue bound
611
+ const to = this._tx(this.peers.get(this.camOwner));
612
+ const fid = this.camFid; this.camFid = (this.camFid + 1) & 0xffff;
613
+ for (let i = 0; i < cnt; i++) {
614
+ const piece = jpeg.subarray(i * CAM_CHUNK, (i + 1) * CAM_CHUNK);
615
+ const h = Buffer.alloc(8);
616
+ h[0] = 74; h[1] = pin; h.writeUInt16LE(fid, 2); h.writeUInt16LE(i, 4); h.writeUInt16LE(cnt, 6);
617
+ this._send(Buffer.concat([h, piece]), to);
618
+ }
619
+ return true;
620
+ }
621
+
622
+ // Signed 16-bit mono samples (Int16Array, array, or s16le Buffer) at rate Hz
623
+ // to every direct peer; each gets the quality it asked for (ESP32s and
624
+ // older listeners: Voice). A partial packet waits for the next call.
625
+ audioWrite(pin, samples, rate = 8000) {
626
+ pin = pinNumber(pin);
627
+ if (Buffer.isBuffer(samples)) samples = new Int16Array(samples.buffer.slice(samples.byteOffset, samples.byteOffset + (samples.length & ~1)));
628
+ if (!Number.isInteger(rate) || rate < 4000 || rate > 192000) throw new Error("Audio rate must be 4000–192000 Hz");
629
+ if (!this.audSid) this.audSid = crypto.randomInt(1, 0xffff) | 1;
630
+ const to = [[], [], []];
631
+ const now = monotonic();
632
+ for (const peer of this.peers.values()) {
633
+ if (!this._reachable(peer)) continue;
634
+ // A peer that asked for a quality in the last 3 s gets it; others Voice.
635
+ to[now - peer.audRx <= CAM_SUB_TIMEOUT ? peer.audQ : 0].push(this._tx(peer));
636
+ }
637
+ let sent = 0;
638
+ for (let q = 0; q < 3; q++) {
639
+ const key = `${pin}:${q}`;
640
+ if (!to[q].length) { this.audOut.delete(key); continue; }
641
+ let o = this.audOut.get(key);
642
+ if (!o || o.inRate !== rate) this.audOut.set(key, o = new Resampler(rate, AUDIO_RATES[q]));
643
+ o.push(samples);
644
+ const per = AUDIO_PER[q];
645
+ while (o.pend.length >= per) {
646
+ const chunk = o.pend.splice(0, per);
647
+ let pkt;
648
+ if (q === 0) {
649
+ pkt = Buffer.alloc(6 + per); pkt[0] = 65;
650
+ chunk.forEach((x, i) => { pkt[6 + i] = ulawEncode(x); });
651
+ } else {
652
+ pkt = Buffer.alloc(7 + 2 * per); pkt[0] = 119; pkt[6] = q;
653
+ chunk.forEach((x, i) => pkt.writeInt16LE(x, 7 + 2 * i));
654
+ }
655
+ pkt[1] = pin; pkt.writeUInt16LE(this.audSid, 2); pkt.writeUInt16LE(this.audSeq, 4);
656
+ this.audSeq = (this.audSeq + 1) & 0xffff;
657
+ for (const a of to[q]) this._send(pkt, a);
658
+ sent++;
659
+ }
660
+ }
661
+ return sent;
432
662
  }
433
663
 
434
664
  _peerList(frame) {
@@ -443,12 +673,27 @@ class RelinkClient extends EventEmitter {
443
673
  const peer = this.peers.get(id);
444
674
  if (peer) peer.candidates = candidates;
445
675
  else this.peers.set(id, { id, candidates, since: monotonic(), lastHello: -Infinity, lastRx: -Infinity, gateway: false, top: 0n, bits: 0n,
446
- legacy: true, confAt: -Infinity, reach: Buffer.alloc(6), reachAt: -Infinity, fwd: null, fwdRx: -Infinity, lastPing: -Infinity });
676
+ legacy: true, confAt: -Infinity, reach: Buffer.alloc(6), reachAt: -Infinity, fwd: null, fwdRx: -Infinity, lastPing: -Infinity,
677
+ camRx: -Infinity, audQ: 0, audRx: -Infinity });
447
678
  }
448
679
  for (const id of this.peers.keys()) if (!seen.has(id)) this.peers.delete(id);
449
680
  const trailer = 2 + frame[1] * 14;
450
681
  if (frame.length >= trailer + 2) this.relayHz = frame.readUInt16LE(trailer);
451
682
  this.relayOff = frame.length >= trailer + 3 && !!(frame[trailer + 2] & 1);
683
+ // Extension: [x] x [instance:u16][k] k x [ip:4][port:2] -- a peer's other
684
+ // public addresses (its network picks one per destination); hello each.
685
+ let q = trailer + 3;
686
+ if (q < frame.length) {
687
+ const x = frame[q++];
688
+ for (let i = 0; i < x && q + 3 <= frame.length; i++) {
689
+ const peer = this.peers.get(frame.readUInt16LE(q)), k = frame[q + 2];
690
+ q += 3;
691
+ for (let j = 0; j < k && q + 6 <= frame.length; j++, q += 6) {
692
+ const a = { address: [...frame.subarray(q, q + 4)].join("."), port: frame.readUInt16BE(q + 4) };
693
+ if (peer && a.port && !peer.candidates.some(c => c.address === a.address && c.port === a.port)) peer.candidates.push(a);
694
+ }
695
+ }
696
+ }
452
697
  }
453
698
 
454
699
  _dispatch(entries, transport) {
@@ -457,7 +702,7 @@ class RelinkClient extends EventEmitter {
457
702
  // A direct peer with an old library may still send another type.
458
703
  const kind = this.kinds.get(entry.pin);
459
704
  if (kind) {
460
- const c = coerceKind(kind, entry.value);
705
+ const c = coerceKind(kind, entry.value, entry.type);
461
706
  if (!c) continue;
462
707
  entry = { ...entry, value: c.value, type: c.type };
463
708
  }
package/lib/media.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+
3
+ // Camera and audio helpers, byte-compatible with the RelinkIoT, C++ and
4
+ // Python libraries.
5
+ // camera slice ['J'][pin][fid:u16][idx:u16][cnt:u16][jpeg bytes] (LE)
6
+ // Voice audio ['A'][pin][sid:u16][seq:u16][160 x G.711 µ-law] 8 kHz, 20 ms
7
+ // other audio ['w'][pin][sid:u16][seq:u16][fmt][s16le] fmt 1 = 16 kHz, 2 = 48 kHz
8
+
9
+ const CAM_CHUNK = 1024;
10
+ const AUDIO_RATES = [8000, 16000, 48000]; // Voice, Standard, High
11
+ const AUDIO_PER = [160, 320, 480]; // samples per packet: 20, 20, 10 ms
12
+
13
+ function ulawEncode(s) {
14
+ let sign = 0;
15
+ if (s < 0) { s = -s; sign = 0x80; }
16
+ s = Math.min(s, 32635) + 0x84;
17
+ let exp = 7;
18
+ for (let m = 0x4000; exp && !(s & m); m >>= 1) exp--;
19
+ return ~(sign | (exp << 4) | ((s >> (exp + 3)) & 0x0f)) & 0xff;
20
+ }
21
+
22
+ const ULAW_DEC = Int16Array.from({ length: 256 }, (_, b) => {
23
+ const u = ~b & 0xff;
24
+ const t = (((u & 0x0f) << 3) + 0x84) << ((u & 0x70) >> 4);
25
+ return u & 0x80 ? 0x84 - t : t - 0x84;
26
+ });
27
+
28
+ // One stream's frame being put back together. A newer frame drops an
29
+ // unfinished older one; late slices of an abandoned frame are ignored.
30
+ class CamAssembly {
31
+ constructor() { this.fid = -1; this.cnt = 0; this.got = 0; this.size = 0; this.buf = Buffer.alloc(64 * CAM_CHUNK); this.seen = new Uint8Array(64); }
32
+
33
+ add(fid, idx, cnt, data) {
34
+ if (!cnt || idx >= cnt) return null;
35
+ if (fid !== this.fid) {
36
+ const behind = (this.fid - fid) & 0xffff;
37
+ if (this.fid >= 0 && behind > 0 && behind <= 64) return null;
38
+ this.fid = fid; this.cnt = cnt; this.got = 0; this.size = 0;
39
+ if (this.buf.length < cnt * CAM_CHUNK) this.buf = Buffer.alloc(cnt * CAM_CHUNK);
40
+ if (this.seen.length < cnt) this.seen = new Uint8Array(cnt); else this.seen.fill(0, 0, cnt);
41
+ }
42
+ if (cnt !== this.cnt || this.seen[idx]) return null;
43
+ data.copy(this.buf, idx * CAM_CHUNK);
44
+ this.seen[idx] = 1; this.got++;
45
+ if (idx === cnt - 1) this.size = idx * CAM_CHUNK + data.length;
46
+ // A copy: the flow keeps the frame while the next one is being assembled.
47
+ return this.got === cnt ? Buffer.from(this.buf.subarray(0, this.size)) : null;
48
+ }
49
+ }
50
+
51
+ // Streaming mono resampler: windowed-sinc low-pass at 0.45 x the lower rate when
52
+ // going down (no aliasing), then linear interpolation -- the C++ library's method.
53
+ class Resampler {
54
+ constructor(inRate, outRate) {
55
+ this.inRate = inRate; this.outRate = outRate; this.step = inRate / outRate;
56
+ this.pend = [];
57
+ this.taps = null;
58
+ if (outRate < inRate) {
59
+ const L = 63, fc = 0.45 * outRate / inRate, taps = new Float64Array(L);
60
+ let sum = 0;
61
+ for (let i = 0; i < L; i++) {
62
+ const x = i - (L - 1) / 2;
63
+ const sinc = x === 0 ? 1 : Math.sin(2 * Math.PI * fc * x) / (2 * Math.PI * fc * x);
64
+ const w = 0.42 - 0.5 * Math.cos(2 * Math.PI * i / (L - 1)) + 0.08 * Math.cos(4 * Math.PI * i / (L - 1));
65
+ taps[i] = 2 * fc * sinc * w; sum += taps[i];
66
+ }
67
+ for (let i = 0; i < L; i++) taps[i] /= sum;
68
+ this.taps = taps;
69
+ }
70
+ this.hist = []; // filtered input not yet consumed
71
+ this.fir = []; // raw input history for the FIR
72
+ this.pos = 0;
73
+ }
74
+
75
+ push(samples) {
76
+ if (this.inRate === this.outRate) { for (const s of samples) this.pend.push(s); return; }
77
+ for (const s of samples) {
78
+ if (this.taps) {
79
+ this.fir.push(s);
80
+ if (this.fir.length > this.taps.length) this.fir.shift();
81
+ let acc = 0;
82
+ for (let i = 0; i < this.fir.length; i++) acc += this.fir[i] * this.taps[this.taps.length - this.fir.length + i];
83
+ this.hist.push(acc);
84
+ } else this.hist.push(s);
85
+ }
86
+ while (this.pos + 1 < this.hist.length) {
87
+ const i = Math.floor(this.pos), f = this.pos - i;
88
+ const v = this.hist[i] * (1 - f) + this.hist[i + 1] * f;
89
+ this.pend.push(Math.max(-32768, Math.min(32767, Math.round(v))));
90
+ this.pos += this.step;
91
+ }
92
+ const drop = Math.floor(this.pos);
93
+ if (drop) { this.hist.splice(0, drop); this.pos -= drop; }
94
+ }
95
+ }
96
+
97
+ module.exports = { CAM_CHUNK, AUDIO_RATES, AUDIO_PER, ulawEncode, ULAW_DEC, CamAssembly, Resampler };
package/lib/protocol.js CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  const crypto = require("node:crypto");
4
4
 
5
- const TYPES = Object.freeze({ int16: 0, int32: 1, float: 2, string: 3, bytes: 4 });
5
+ const TYPES = Object.freeze({ int16: 0, int32: 1, float: 2, string: 3, bytes: 4, uint8: 5, double: 6 });
6
+ const FIXED = Object.freeze({ 0: 2, 1: 4, 2: 4, 5: 1, 6: 8 }); // value bytes of the unframed types
6
7
  const NAMES = Object.keys(TYPES);
7
8
  const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
8
9
  for (let i = 0; i < 8; i++) n = (n & 1) ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
@@ -41,12 +42,14 @@ function encodeEntry(pin, value, type = "auto") {
41
42
  } else {
42
43
  if (typeof value === "boolean") value = Number(value);
43
44
  if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("Numeric payload must be a finite number");
44
- if (type === "int16" || type === "int32") {
45
- const min = type === "int16" ? -32768 : -2147483648;
46
- const max = type === "int16" ? 32767 : 2147483647;
45
+ if (type === "int16" || type === "int32" || type === "uint8") {
46
+ const [min, max] = { int16: [-32768, 32767], int32: [-2147483648, 2147483647], uint8: [0, 255] }[type];
47
47
  if (!Number.isInteger(value) || value < min || value > max) throw new Error("Integer payload is outside its data type range");
48
- body = Buffer.alloc(type === "int16" ? 2 : 4);
49
- if (type === "int16") body.writeInt16LE(value); else body.writeInt32LE(value);
48
+ body = Buffer.alloc(FIXED[TYPES[type]]);
49
+ if (type === "int16") body.writeInt16LE(value); else if (type === "int32") body.writeInt32LE(value); else body[0] = value;
50
+ } else if (type === "double") {
51
+ body = Buffer.alloc(8);
52
+ body.writeDoubleLE(value);
50
53
  } else {
51
54
  body = Buffer.alloc(4);
52
55
  body.writeFloatLE(value);
@@ -57,14 +60,14 @@ function encodeEntry(pin, value, type = "auto") {
57
60
  }
58
61
 
59
62
  // Declared datastream kinds from the signed allowed-pins reply ("types": "0:2,1:1").
60
- const KINDS = Object.freeze({ 1: "int", 2: "float", 3: "string", 4: "bytes" });
63
+ const KINDS = Object.freeze({ 1: "int", 2: "float", 3: "string", 4: "bytes", 5: "uint8", 6: "double" });
61
64
 
62
65
  // The value as the pin's declared type -- same rule as relink_udp and the
63
66
  // other libraries: numbers convert (Integer rounds half away from zero and
64
67
  // must fit Int32), numbers become text on a String pin, text is accepted on
65
68
  // a ByteArray pin. Returns { value, type } with the wire type name, or null
66
69
  // when the value can't be the declared type. kind undefined = no conversion.
67
- function coerceKind(kind, value) {
70
+ function coerceKind(kind, value, type) {
68
71
  if (!kind) return null;
69
72
  if (typeof value === "boolean") value = Number(value);
70
73
  const isNum = typeof value === "number";
@@ -77,9 +80,16 @@ function coerceKind(kind, value) {
77
80
  return { value: i, type: i >= -32768 && i <= 32767 ? "int16" : "int32" };
78
81
  }
79
82
  case "float": return isNum ? { value: Math.fround(value), type: "float" } : null;
83
+ case "uint8": {
84
+ if (!isNum || !Number.isFinite(value)) return null;
85
+ const i = Math.round(value);
86
+ return i >= 0 && i <= 255 ? { value: i, type: "uint8" } : null;
87
+ }
88
+ case "double": return isNum ? { value, type: "double" } : null;
80
89
  case "string":
81
90
  if (typeof value === "string") return { value, type: "string" };
82
- return isNum ? { value: Number.isInteger(value) ? String(value) : String(Number(Math.fround(value).toPrecision(6))), type: "string" } : null;
91
+ // Text like the C++ library: %g for Float, %.15g for Double.
92
+ return isNum ? { value: Number.isInteger(value) ? String(value) : String(Number((type === "double" ? value : Math.fround(value)).toPrecision(type === "double" ? 15 : 6))), type: "string" } : null;
83
93
  case "bytes":
84
94
  if (Buffer.isBuffer(value)) return { value, type: "bytes" };
85
95
  return typeof value === "string" ? { value: Buffer.from(value, "utf8"), type: "bytes" } : null;
@@ -90,7 +100,7 @@ function coerceKind(kind, value) {
90
100
  function parseKinds(text) {
91
101
  const kinds = new Map();
92
102
  for (const item of String(text || "").split(",")) {
93
- const m = /^(\d{1,3}):([1-4])$/.exec(item);
103
+ const m = /^(\d{1,3}):([1-6])$/.exec(item);
94
104
  if (m && Number(m[1]) <= 255) kinds.set(Number(m[1]), Number(m[2]));
95
105
  }
96
106
  return kinds;
@@ -103,6 +113,11 @@ function decodeValue(type, body) {
103
113
  const value = body.readFloatLE();
104
114
  if (Number.isFinite(value)) return value;
105
115
  }
116
+ if (type === 5 && body.length === 1) return body[0];
117
+ if (type === 6 && body.length === 8) {
118
+ const value = body.readDoubleLE();
119
+ if (Number.isFinite(value)) return value;
120
+ }
106
121
  if (type === 3) return body.toString("utf8");
107
122
  if (type === 4) return Buffer.from(body);
108
123
  throw new Error("Invalid pin value");
@@ -117,11 +132,11 @@ function decodeBatch(data, mesh = false) {
117
132
  if (p + 2 > data.length) throw new Error("Truncated pin entry");
118
133
  const pin = data[p++], type = data[p++];
119
134
  let length;
120
- if (!mesh || type >= 3) {
135
+ if (!mesh || type === 3 || type === 4) {
121
136
  if (p >= data.length) throw new Error("Truncated value length");
122
137
  length = data[p++];
123
- } else length = type === 0 ? 2 : 4;
124
- if (type > 4 || p + length > data.length) throw new Error("Invalid pin entry");
138
+ } else length = FIXED[type];
139
+ if (type > 6 || p + length > data.length) throw new Error("Invalid pin entry");
125
140
  entries.push({ pin, type: NAMES[type], value: decodeValue(type, data.subarray(p, p + length)) });
126
141
  p += length;
127
142
  }