node-red-contrib-relink 0.0.0-stage → 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.
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 };
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
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
7
+ const NAMES = Object.keys(TYPES);
8
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
9
+ for (let i = 0; i < 8; i++) n = (n & 1) ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
10
+ return n >>> 0;
11
+ });
12
+
13
+ function crc32(data) {
14
+ let crc = 0xffffffff;
15
+ for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 255] ^ (crc >>> 8);
16
+ return (crc ^ 0xffffffff) >>> 0;
17
+ }
18
+
19
+ function pinNumber(value) {
20
+ if (typeof value === "string" && /^(?:V)?\d{1,3}$/i.test(value)) value = Number(value.replace(/^v/i, ""));
21
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new Error("Pin must be V0–V255");
22
+ return value;
23
+ }
24
+
25
+ function encodeEntry(pin, value, type = "auto") {
26
+ pin = pinNumber(pin);
27
+ if (type === "auto") {
28
+ if (Buffer.isBuffer(value)) type = "bytes";
29
+ else if (typeof value === "string") type = "string";
30
+ else if (typeof value === "boolean") type = "int16";
31
+ else if (typeof value === "number") type = Number.isInteger(value) ? (value >= -32768 && value <= 32767 ? "int16" : "int32") : "float";
32
+ else throw new Error("Payload must be a number, boolean, string, or Buffer");
33
+ }
34
+ if (!Object.hasOwn(TYPES, type)) throw new Error("Unsupported Relink data type");
35
+ let body;
36
+ if (type === "bytes" || type === "string") {
37
+ if (type === "bytes" && !Buffer.isBuffer(value)) throw new Error("ByteArray payload must be a Buffer");
38
+ if (type === "string" && typeof value !== "string") throw new Error("String payload must be text");
39
+ const bytes = type === "bytes" ? value : Buffer.from(value, "utf8");
40
+ if (bytes.length > 255) throw new Error("Text and ByteArray values must be at most 255 bytes");
41
+ body = Buffer.concat([Buffer.from([bytes.length]), bytes]);
42
+ } else {
43
+ if (typeof value === "boolean") value = Number(value);
44
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("Numeric payload must be a finite number");
45
+ if (type === "int16" || type === "int32" || type === "uint8") {
46
+ const [min, max] = { int16: [-32768, 32767], int32: [-2147483648, 2147483647], uint8: [0, 255] }[type];
47
+ if (!Number.isInteger(value) || value < min || value > max) throw new Error("Integer payload is outside its data type range");
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);
53
+ } else {
54
+ body = Buffer.alloc(4);
55
+ body.writeFloatLE(value);
56
+ if (!Number.isFinite(body.readFloatLE())) throw new Error("Float payload exceeds float32 range");
57
+ }
58
+ }
59
+ return Buffer.concat([Buffer.from([pin, TYPES[type]]), body]);
60
+ }
61
+
62
+ // Declared datastream kinds from the signed allowed-pins reply ("types": "0:2,1:1").
63
+ const KINDS = Object.freeze({ 1: "int", 2: "float", 3: "string", 4: "bytes", 5: "uint8", 6: "double" });
64
+
65
+ // The value as the pin's declared type -- same rule as relink_udp and the
66
+ // other libraries: numbers convert (Integer rounds half away from zero and
67
+ // must fit Int32), numbers become text on a String pin, text is accepted on
68
+ // a ByteArray pin. Returns { value, type } with the wire type name, or null
69
+ // when the value can't be the declared type. kind undefined = no conversion.
70
+ function coerceKind(kind, value, type) {
71
+ if (!kind) return null;
72
+ if (typeof value === "boolean") value = Number(value);
73
+ const isNum = typeof value === "number";
74
+ switch (KINDS[kind]) {
75
+ case "int": {
76
+ if (!isNum || !Number.isFinite(value)) return null;
77
+ let i = Math.sign(value) * Math.round(Math.abs(value));
78
+ if (i === 0) i = 0;
79
+ if (i < -2147483648 || i > 2147483647) return null;
80
+ return { value: i, type: i >= -32768 && i <= 32767 ? "int16" : "int32" };
81
+ }
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;
89
+ case "string":
90
+ if (typeof value === "string") return { value, type: "string" };
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;
93
+ case "bytes":
94
+ if (Buffer.isBuffer(value)) return { value, type: "bytes" };
95
+ return typeof value === "string" ? { value: Buffer.from(value, "utf8"), type: "bytes" } : null;
96
+ }
97
+ return null;
98
+ }
99
+
100
+ function parseKinds(text) {
101
+ const kinds = new Map();
102
+ for (const item of String(text || "").split(",")) {
103
+ const m = /^(\d{1,3}):([1-6])$/.exec(item);
104
+ if (m && Number(m[1]) <= 255) kinds.set(Number(m[1]), Number(m[2]));
105
+ }
106
+ return kinds;
107
+ }
108
+
109
+ function decodeValue(type, body) {
110
+ if (type === 0 && body.length === 2) return body.readInt16LE();
111
+ if (type === 1 && body.length === 4) return body.readInt32LE();
112
+ if (type === 2 && body.length === 4) {
113
+ const value = body.readFloatLE();
114
+ if (Number.isFinite(value)) return value;
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
+ }
121
+ if (type === 3) return body.toString("utf8");
122
+ if (type === 4) return Buffer.from(body);
123
+ throw new Error("Invalid pin value");
124
+ }
125
+
126
+ // Validate the entire batch before exposing any value to a flow.
127
+ function decodeBatch(data, mesh = false) {
128
+ if (data.length < 2) throw new Error("Truncated pin batch");
129
+ const entries = [];
130
+ let p = 2;
131
+ for (let i = 0; i < data[1]; i++) {
132
+ if (p + 2 > data.length) throw new Error("Truncated pin entry");
133
+ const pin = data[p++], type = data[p++];
134
+ let length;
135
+ if (!mesh || type === 3 || type === 4) {
136
+ if (p >= data.length) throw new Error("Truncated value length");
137
+ length = data[p++];
138
+ } else length = FIXED[type];
139
+ if (type > 6 || p + length > data.length) throw new Error("Invalid pin entry");
140
+ entries.push({ pin, type: NAMES[type], value: decodeValue(type, data.subarray(p, p + length)) });
141
+ p += length;
142
+ }
143
+ if (p !== data.length) throw new Error("Unexpected pin batch trailer");
144
+ return entries;
145
+ }
146
+
147
+ function seal(key, deviceId, nonce, inner, salt = 0) {
148
+ const header = Buffer.alloc(12);
149
+ header.writeUInt32LE(deviceId);
150
+ header.writeBigUInt64LE(nonce, 4);
151
+ const iv = Buffer.from(header);
152
+ iv.writeUInt32LE((deviceId ^ salt) >>> 0);
153
+ const cipher = crypto.createCipheriv("chacha20-poly1305", key, iv, { authTagLength: 16 });
154
+ return Buffer.concat([Buffer.from("E"), header, cipher.update(inner), cipher.final(), cipher.getAuthTag()]);
155
+ }
156
+
157
+ function open(key, deviceId, data) {
158
+ if (data.length < 30 || data[0] !== 69 || data.readUInt32LE(1) !== deviceId) throw new Error("Invalid encrypted envelope");
159
+ const decipher = crypto.createDecipheriv("chacha20-poly1305", key, data.subarray(1, 13), { authTagLength: 16 });
160
+ decipher.setAuthTag(data.subarray(-16));
161
+ return { nonce: data.readBigUInt64LE(5), inner: Buffer.concat([decipher.update(data.subarray(13, -16)), decipher.final()]) };
162
+ }
163
+
164
+ module.exports = { crc32, pinNumber, encodeEntry, decodeValue, decodeBatch, seal, open, NAMES, coerceKind, parseKinds };
@@ -0,0 +1,165 @@
1
+ <script type="text/javascript">
2
+ (function() {
3
+ function validPin(v) { return v === "" || /^(?:V)?(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$/i.test(String(v)); }
4
+ RED.nodes.registerType("relink-connection", {
5
+ category: "config",
6
+ defaults: {
7
+ name: { value: "" },
8
+ server: { value: "relink-iot.com", required: true },
9
+ port: { value: 7445, required: true, validate: function(v) { return /^\d+$/.test(String(v)) && Number(v) > 0 && Number(v) <= 65535; } },
10
+ apiBase: { value: "" },
11
+ mesh: { value: true }
12
+ },
13
+ credentials: { token: { type: "password", required: true }, key: { type: "password", required: true } },
14
+ label: function() { return this.name || this.server; }
15
+ });
16
+ RED.nodes.registerType("relink in", {
17
+ category: "network", color: "#c4d7c0",
18
+ defaults: {
19
+ name: { value: "" },
20
+ connection: { value: "", type: "relink-connection", required: true },
21
+ pin: { value: "", validate: validPin }
22
+ },
23
+ inputs: 0, outputs: 1, icon: "font-awesome/fa-exchange",
24
+ label: function() { return this.name || (this.pin === "" ? "relink in" : "relink V" + String(this.pin).replace(/^v/i, "")); }
25
+ });
26
+ RED.nodes.registerType("relink out", {
27
+ category: "network", color: "#c4d7c0",
28
+ defaults: {
29
+ name: { value: "" },
30
+ connection: { value: "", type: "relink-connection", required: true },
31
+ pin: { value: "", validate: validPin },
32
+ dtype: { value: "auto", required: true }
33
+ },
34
+ inputs: 1, outputs: 0, icon: "font-awesome/fa-exchange", align: "right",
35
+ label: function() { return this.name || (this.pin === "" ? "relink out" : "relink V" + String(this.pin).replace(/^v/i, "")); }
36
+ });
37
+ function mediaNode(kind, dir, icon, extra) {
38
+ var defaults = {
39
+ name: { value: "" },
40
+ connection: { value: "", type: "relink-connection", required: true },
41
+ pin: { value: "", required: true, validate: function(v) { return v !== "" && validPin(v); } }
42
+ };
43
+ for (var k in extra || {}) defaults[k] = extra[k];
44
+ RED.nodes.registerType("relink " + kind + " " + dir, {
45
+ category: "network", color: "#c4d7c0", defaults: defaults,
46
+ inputs: dir === "out" || kind === "camera" ? 1 : 0, outputs: dir === "in" ? 1 : 0,
47
+ icon: icon, align: dir === "out" ? "right" : "left",
48
+ label: function() { return this.name || ("relink " + kind + (this.pin === "" ? "" : " V" + String(this.pin).replace(/^v/i, ""))); }
49
+ });
50
+ }
51
+ mediaNode("camera", "in", "font-awesome/fa-video-camera");
52
+ mediaNode("camera", "out", "font-awesome/fa-video-camera");
53
+ mediaNode("audio", "in", "font-awesome/fa-volume-up", { quality: { value: "0" } });
54
+ mediaNode("audio", "out", "font-awesome/fa-volume-up", { rate: { value: 8000, validate: function(v) { return /^\d+$/.test(String(v)) && v >= 4000 && v <= 192000; } } });
55
+ })();
56
+ </script>
57
+
58
+ <script type="text/html" data-template-name="relink-connection">
59
+ <div class="form-row"><label for="node-config-input-name">Name</label><input type="text" id="node-config-input-name" placeholder="My device"></div>
60
+ <div class="form-row"><label for="node-config-input-server">Server</label><input type="text" id="node-config-input-server" placeholder="relink-iot.com"></div>
61
+ <div class="form-row"><label for="node-config-input-port">UDP port</label><input type="number" id="node-config-input-port" min="1" max="65535"></div>
62
+ <div class="form-row"><label for="node-config-input-apiBase">API URL</label><input type="text" id="node-config-input-apiBase" placeholder="http://relink-iot.com:8000"></div>
63
+ <div class="form-row"><label for="node-config-input-token">Device token</label><input type="password" id="node-config-input-token" autocomplete="new-password"></div>
64
+ <div class="form-row"><label for="node-config-input-key">Encryption key</label><input type="password" id="node-config-input-key" autocomplete="new-password"></div>
65
+ <div class="form-row"><label for="node-config-input-mesh">Direct mesh</label><input type="checkbox" id="node-config-input-mesh" style="display:inline-block;width:auto;vertical-align:middle"></div>
66
+ <div class="form-tips">Copy the token and 64-character key from your Relink device page. Nodes sharing this connection share one endpoint. Leave API URL blank to use http://server:8000, or enter your API's HTTPS origin.</div>
67
+ </script>
68
+
69
+ <script type="text/html" data-template-name="relink in">
70
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
71
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
72
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="All pins, or V0"></div>
73
+ </script>
74
+
75
+ <script type="text/html" data-template-name="relink out">
76
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
77
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
78
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="From msg.pin or msg.topic"></div>
79
+ <div class="form-row"><label for="node-input-dtype">Data type</label><select id="node-input-dtype">
80
+ <option value="auto">Automatic</option><option value="int16">Int16</option><option value="int32">Int32</option>
81
+ <option value="float">Float</option><option value="string">String</option><option value="bytes">ByteArray</option><option value="uint8">UInt8</option><option value="double">Double</option>
82
+ </select></div>
83
+ </script>
84
+
85
+ <script type="text/html" data-help-name="relink-connection">
86
+ <p>Connects Node-RED to one Relink device as an encrypted UDP endpoint. Use the same token and key as your ESP32, C++, or Python program to share virtual pins.</p>
87
+ <p>The token and key use Node-RED credentials and are omitted from exported flows. Encryption is required; an invalid key never falls back to plaintext.</p>
88
+ <p>UDP defaults to port 7445. The API URL is an origin, such as <code>https://relink-iot.com</code>, without <code>/api</code>. Signed API requests fetch declared datastreams. Direct mesh starts after that list is available, and falls back to the relay when a peer becomes unreachable.</p>
89
+ <p>This package handles virtual pins, numeric history summaries, camera and audio. It does not flash firmware.</p>
90
+ </script>
91
+
92
+ <script type="text/html" data-help-name="relink in">
93
+ <p>Receives changes from the dashboard and other endpoints of a Relink device. Leave Pin blank for all pins, or choose V0–V255.</p>
94
+ <h3>Outputs</h3>
95
+ <dl class="message-properties">
96
+ <dt>payload <span class="property-type">number | string | Buffer</span></dt><dd>The pin value. ByteArray values are Buffers.</dd>
97
+ <dt>topic <span class="property-type">string</span></dt><dd>Pin name, for example <code>V0</code>.</dd>
98
+ <dt>pin <span class="property-type">number</span></dt><dd>Pin number, 0–255.</dd>
99
+ <dt>dtype <span class="property-type">string</span></dt><dd>int16, int32, float, string, bytes, uint8 or double.</dd>
100
+ <dt>transport <span class="property-type">string</span></dt><dd>relay or p2p.</dd>
101
+ <dt>checksum <span class="property-type">number</span></dt><dd>The device's numeric identifier.</dd>
102
+ </dl>
103
+ <p>Own writes are not echoed locally. Register the pins as datastreams on the Relink dashboard before using them.</p>
104
+ </script>
105
+
106
+ <script type="text/html" data-help-name="relink out">
107
+ <p>Queues <code>msg.payload</code> as a virtual-pin write. Select a fixed pin, or leave it blank to use <code>msg.pin</code>, then <code>msg.topic</code> (for example <code>V1</code>).</p>
108
+ <p>Automatic type chooses Int16 or Int32 for whole numbers, Float for fractional numbers, String for text, and ByteArray for Buffer. Booleans become 0 or 1. Select Float explicitly for a Float datastream when sending whole numbers.</p>
109
+ <p>Text and ByteArray payloads are limited to 255 bytes. Invalid values trigger a Catch node. During a network outage, the latest queued value per pin is retained in memory; a redeploy clears it. At high input rates, writes to the same pin are coalesced.</p>
110
+ <p>Completion means queued, not delivery confirmed. Sending to a control pin can affect real hardware.</p>
111
+ </script>
112
+
113
+ <script type="text/html" data-template-name="relink camera in">
114
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
115
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
116
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="V10"></div>
117
+ </script>
118
+ <script type="text/html" data-template-name="relink camera out">
119
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
120
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
121
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="V10"></div>
122
+ </script>
123
+ <script type="text/html" data-template-name="relink audio in">
124
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
125
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
126
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="V10"></div>
127
+ <div class="form-row"><label for="node-input-quality">Quality</label><select id="node-input-quality">
128
+ <option value="0">Voice (8 kHz)</option><option value="1">Standard (16 kHz)</option><option value="2">High (48 kHz)</option>
129
+ </select></div>
130
+ </script>
131
+ <script type="text/html" data-template-name="relink audio out">
132
+ <div class="form-row"><label for="node-input-name">Name</label><input type="text" id="node-input-name"></div>
133
+ <div class="form-row"><label for="node-input-connection">Connection</label><input type="text" id="node-input-connection"></div>
134
+ <div class="form-row"><label for="node-input-pin">Pin</label><input type="text" id="node-input-pin" placeholder="V10"></div>
135
+ <div class="form-row"><label for="node-input-rate">Sample rate</label><input type="number" id="node-input-rate" min="4000" max="192000" placeholder="8000"></div>
136
+ </script>
137
+
138
+ <script type="text/html" data-help-name="relink camera in">
139
+ <p>Live camera frames from a device on this token (an ESP32 camera, or a C++ / Python / Node-RED program sending on this pin). Each message is one JPEG.</p>
140
+ <h3>Outputs</h3>
141
+ <dl class="message-properties">
142
+ <dt>payload <span class="property-type">Buffer</span></dt><dd>One JPEG frame.</dd>
143
+ <dt>frameId <span class="property-type">number</span></dt><dd>Frame counter from the sender, 0–65535.</dd>
144
+ <dt>pin <span class="property-type">number</span></dt><dd>The Camera datastream's pin.</dd>
145
+ </dl>
146
+ <p>Frames go directly between the two endpoints and never through the server. Without a direct link no frames arrive. A device streams to one viewer at a time: whoever started watching last. If another viewer takes over, the status says so; send any message to this node to take the stream back.</p>
147
+ </script>
148
+ <script type="text/html" data-help-name="relink camera out">
149
+ <p>Streams JPEG frames from <code>msg.payload</code> (a Buffer) on a Camera pin, like an ESP32 camera does. Up to 400 KB per frame.</p>
150
+ <p>Frames are sent only while someone watches (the Android app, or another program with relink camera in). Otherwise they are dropped and the status shows <i>nobody watching</i>. The web dashboard's Live Camera widget needs the ESP32 or C++ / Python sender; Node-RED cannot reach a browser directly.</p>
151
+ </script>
152
+ <script type="text/html" data-help-name="relink audio in">
153
+ <p>Live sound from a device on this token. Each message is one packet: 20 ms at 8 or 16 kHz, 10 ms at 48 kHz.</p>
154
+ <h3>Outputs</h3>
155
+ <dl class="message-properties">
156
+ <dt>payload <span class="property-type">Buffer</span></dt><dd>Signed 16-bit little-endian mono samples.</dd>
157
+ <dt>rate <span class="property-type">number</span></dt><dd>8000, 16000 or 48000. Trust this rather than the quality you chose: an ESP32 always sends 8000.</dd>
158
+ <dt>samples <span class="property-type">number</span></dt><dd>Number of samples in the payload.</dd>
159
+ </dl>
160
+ <p>Peer-to-peer only, like the camera. The device only reads its microphone while someone listens.</p>
161
+ </script>
162
+ <script type="text/html" data-help-name="relink audio out">
163
+ <p>Sends sound to every device on this token that has a direct link. <code>msg.payload</code> is 16-bit mono samples: a Buffer (s16le), an Int16Array or an array of numbers. The rate comes from <code>msg.rate</code>, else the node's setting.</p>
164
+ <p>Each listener gets the quality it asked for: Voice (8 kHz), Standard (16 kHz) or High (48 kHz), resampled once per quality. ESP32s always get Voice. A partial packet waits for the next message.</p>
165
+ </script>
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+
3
+ const { RelinkClient } = require("../lib/client");
4
+ const { pinNumber } = require("../lib/protocol");
5
+
6
+ module.exports = function(RED) {
7
+ function Connection(config) {
8
+ RED.nodes.createNode(this, config);
9
+ this.users = new Set();
10
+ this.closed = false;
11
+ this.connectionState = "connecting";
12
+ this.setState = state => {
13
+ this.connectionState = state;
14
+ for (const user of this.users) user.status(statusFor(state));
15
+ };
16
+ try {
17
+ const credentials = this.credentials || {};
18
+ this.client = new RelinkClient({ token: credentials.token, key: credentials.key,
19
+ server: config.server, port: config.port, apiBase: config.apiBase, mesh: config.mesh !== false });
20
+ this.client.setMaxListeners(0); // a shared configuration may feed many input nodes
21
+ this.client.on("status", ({ state }) => this.setState(state));
22
+ this.client.on("warning", error => this.warn(error.message));
23
+ const start = () => this.client.start().catch(error => {
24
+ if (this.closed) return;
25
+ this.setState("connecting"); this.warn(error.message);
26
+ this.retryTimer = setTimeout(start, 5000);
27
+ });
28
+ start();
29
+ } catch (error) { this.connectionState = "error"; this.error(error.message); }
30
+ this.on("close", (removed, done) => {
31
+ this.closed = true;
32
+ clearTimeout(this.retryTimer);
33
+ // Also handle runtimes invoking close with just its completion callback.
34
+ if (typeof removed === "function") done = removed;
35
+ Promise.resolve(this.client && this.client.stop()).then(() => { this.users.clear(); if (done) done(); });
36
+ });
37
+ }
38
+
39
+ function statusFor(state) {
40
+ return { fill: state === "connected" ? "green" : state === "error" ? "red" : "grey",
41
+ shape: state === "connected" ? "dot" : "ring", text: state };
42
+ }
43
+
44
+ function attach(node, config) {
45
+ const connection = RED.nodes.getNode(config.connection);
46
+ if (!connection || !connection.client || connection.connectionState === "error") {
47
+ node.status(statusFor("error")); node.error("Configure a valid Relink connection"); return null;
48
+ }
49
+ connection.users.add(node);
50
+ node.status(statusFor(connection.connectionState));
51
+ node.on("close", () => connection.users.delete(node));
52
+ return connection;
53
+ }
54
+
55
+ function InNode(config) {
56
+ RED.nodes.createNode(this, config);
57
+ const connection = attach(this, config);
58
+ if (!connection) return;
59
+ let pin;
60
+ try { pin = config.pin === "" || config.pin === undefined ? null : pinNumber(config.pin); }
61
+ catch (error) { this.error(error.message); this.status(statusFor("error")); return; }
62
+ const listener = event => {
63
+ if (pin !== null && pin !== event.pin) return;
64
+ this.send({ topic: `V${event.pin}`, payload: event.value, pin: event.pin,
65
+ dtype: event.type, transport: event.transport, checksum: event.checksum });
66
+ };
67
+ connection.client.on("pin", listener);
68
+ this.on("close", () => connection.client.removeListener("pin", listener));
69
+ }
70
+
71
+ function OutNode(config) {
72
+ RED.nodes.createNode(this, config);
73
+ const connection = attach(this, config);
74
+ this.on("input", (msg, send, done) => {
75
+ try {
76
+ if (!connection) throw new Error("Configure a valid Relink connection");
77
+ const selected = config.pin !== "" && config.pin !== undefined ? config.pin : (msg.pin !== undefined ? msg.pin : msg.topic);
78
+ connection.client.write(pinNumber(selected), msg.payload, config.dtype || "auto");
79
+ if (done) done();
80
+ } catch (error) { if (done) done(error); else this.error(error.message, msg); }
81
+ });
82
+ }
83
+
84
+ // Camera and audio go peer-to-peer only (never through the relay), so they
85
+ // need a direct link to the other endpoint: the status says when there is none.
86
+ function mediaPin(node, config) {
87
+ try { return pinNumber(config.pin); }
88
+ catch (error) { node.error("Choose a pin, V0–V255"); node.status(statusFor("error")); return null; }
89
+ }
90
+
91
+ function CameraInNode(config) {
92
+ RED.nodes.createNode(this, config);
93
+ const connection = attach(this, config);
94
+ if (!connection) return;
95
+ const pin = mediaPin(this, config);
96
+ if (pin === null) return;
97
+ const client = connection.client;
98
+ client.watchCamera(pin);
99
+ let frames = 0;
100
+ const listener = event => {
101
+ if (event.pin !== pin) return;
102
+ frames++;
103
+ this.send({ topic: `V${pin}`, payload: event.frame, pin, frameId: event.frameId, checksum: event.checksum });
104
+ };
105
+ const kicked = () => this.status({ fill: "yellow", shape: "ring", text: "another viewer took the camera" });
106
+ // A frame count each 2 s while frames arrive; otherwise the connection state.
107
+ const timer = setInterval(() => {
108
+ if (frames) this.status({ fill: "green", shape: "dot", text: `${(frames / 2).toFixed(1)} fps` });
109
+ else if (!client.camKicked) this.status(statusFor(connection.connectionState));
110
+ frames = 0;
111
+ }, 2000);
112
+ client.on("camera", listener);
113
+ client.on("camera-kicked", kicked);
114
+ this.on("input", (msg, send, done) => { // any message takes the stream back
115
+ client.watchCamera(pin); this.status(statusFor(connection.connectionState)); if (done) done();
116
+ });
117
+ this.on("close", () => {
118
+ clearInterval(timer);
119
+ client.removeListener("camera", listener); client.removeListener("camera-kicked", kicked);
120
+ client.watchCamera(pin, false);
121
+ });
122
+ }
123
+
124
+ function CameraOutNode(config) {
125
+ RED.nodes.createNode(this, config);
126
+ const connection = attach(this, config);
127
+ const pin = mediaPin(this, config);
128
+ let sent = 0, dropped = 0;
129
+ const timer = setInterval(() => {
130
+ if (!connection || pin === null) return;
131
+ if (sent) this.status({ fill: "green", shape: "dot", text: `watched, ${(sent / 2).toFixed(1)} fps` });
132
+ else if (dropped) this.status({ fill: "grey", shape: "ring", text: "nobody watching" });
133
+ else this.status(statusFor(connection.connectionState));
134
+ sent = dropped = 0;
135
+ }, 2000);
136
+ this.on("input", (msg, send, done) => {
137
+ try {
138
+ if (!connection || pin === null) throw new Error("Configure a valid Relink connection and pin");
139
+ if (connection.client.cameraWrite(pin, msg.payload)) sent++; else dropped++;
140
+ if (done) done();
141
+ } catch (error) { if (done) done(error); else this.error(error.message, msg); }
142
+ });
143
+ this.on("close", () => clearInterval(timer));
144
+ }
145
+
146
+ function AudioInNode(config) {
147
+ RED.nodes.createNode(this, config);
148
+ const connection = attach(this, config);
149
+ if (!connection) return;
150
+ const pin = mediaPin(this, config);
151
+ if (pin === null) return;
152
+ const client = connection.client;
153
+ client.listenAudio(pin, true, Number(config.quality) || 0);
154
+ const listener = event => {
155
+ if (event.pin !== pin) return;
156
+ const s = event.samples;
157
+ this.send({ topic: `V${pin}`, payload: Buffer.from(s.buffer, s.byteOffset, s.byteLength), rate: event.rate,
158
+ samples: s.length, pin, checksum: event.checksum });
159
+ };
160
+ client.on("audio", listener);
161
+ this.on("close", () => { client.removeListener("audio", listener); client.listenAudio(pin, false); });
162
+ }
163
+
164
+ function AudioOutNode(config) {
165
+ RED.nodes.createNode(this, config);
166
+ const connection = attach(this, config);
167
+ const pin = mediaPin(this, config);
168
+ this.on("input", (msg, send, done) => {
169
+ try {
170
+ if (!connection || pin === null) throw new Error("Configure a valid Relink connection and pin");
171
+ const p = msg.payload;
172
+ if (!Buffer.isBuffer(p) && !Array.isArray(p) && !(p instanceof Int16Array)) throw new Error("Audio payload must be 16-bit samples: a Buffer (s16le), Int16Array or array");
173
+ connection.client.audioWrite(pin, Array.isArray(p) ? Int16Array.from(p) : p, Number(msg.rate) || Number(config.rate) || 8000);
174
+ if (done) done();
175
+ } catch (error) { if (done) done(error); else this.error(error.message, msg); }
176
+ });
177
+ }
178
+
179
+ RED.nodes.registerType("relink-connection", Connection, { credentials: { token: { type: "password" }, key: { type: "password" } } });
180
+ RED.nodes.registerType("relink in", InNode);
181
+ RED.nodes.registerType("relink out", OutNode);
182
+ RED.nodes.registerType("relink camera in", CameraInNode);
183
+ RED.nodes.registerType("relink camera out", CameraOutNode);
184
+ RED.nodes.registerType("relink audio in", AudioInNode);
185
+ RED.nodes.registerType("relink audio out", AudioOutNode);
186
+ };