node-red-contrib-sensibo-stream 0.0.0-stage → 0.0.5

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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # node-red-contrib-sensibo-stream
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node-RED nodes for the [Sensibo API v2 Event Stream](https://support.sensibo.com/api/#event-stream):
4
+ real-time temperature/humidity measurements and AC state changes over Server-Sent Events,
5
+ instead of polling.
6
+
7
+ No runtime dependencies. Requires Node.js 18+ and Node-RED 3+.
8
+
9
+ ## Install
10
+
11
+ From your Node-RED user directory (usually `~/.node-red`):
12
+
13
+ ```sh
14
+ npm install /path/to/node-red-contrib-sensibo-stream
15
+ ```
16
+
17
+ Then restart Node-RED. An example flow is available under *Import → Examples*.
18
+
19
+ ## Nodes
20
+
21
+ ### `sensibo-stream-account`
22
+ Your Sensibo account. Get an API key at <https://home.sensibo.com/me/api>.
23
+ The key is stored as a Node-RED credential. It is the same key the older REST-based packages use:
24
+ the stream gets it in the `X-Api-Key` header, REST calls in the documented `apiKey` query parameter.
25
+
26
+ All stream nodes using the same account **share one connection** — Sensibo limits an
27
+ account to 10 open streams, and one stream already carries every device.
28
+
29
+ ### `sensibo-event-stream`
30
+ Emits a message per event. Use a *switch* on `msg.event` to route them.
31
+
32
+ | `msg.event` | When | `msg.payload` |
33
+ |----------------|----------------------------------------------------------|---------------------------------------|
34
+ | `measurements` | New readings (max once/min per device, instant for motion) | `{ id, measurements, podId? }` |
35
+ | `changed` | Something changed on a device | `{ id, fields }` |
36
+ | `device` | Full device re-read after a `changed` event | full device object from `/pods/{id}` |
37
+ | `poll` | Start-up (all devices), 15-min slow poll, or input | full device object |
38
+ | `hello` | Stream opened | `{ version, heartbeatSeconds, pods }` |
39
+ | `resync` | Server is closing the stream (auto-reconnects) | `{}` |
40
+
41
+ On start-up every device is sent once as a `poll` message, so all values are available
42
+ immediately — even if the stream itself is unavailable, or only this node was redeployed
43
+ (`msg.reason` is `hello`, `startup` or `cached`).
44
+
45
+ Other properties: `msg.topic` (`sensibo/<event>/<deviceId>`), `msg.deviceId`, `msg.podId`
46
+ (sensor measurements), `msg.fields`, and optionally `msg.device` — the cached device state
47
+ with stream measurements merged in.
48
+
49
+ You can limit output to specific device ids (comma-separated).
50
+
51
+ **Input:** `msg.payload = "reconnect"` reopens the stream; anything else re-reads all devices.
52
+
53
+ ## Sensibo's client rules, implemented
54
+
55
+ - Reconnect with exponential backoff + jitter, capped at 5 minutes
56
+ - On HTTP 429/503, wait at least `Retry-After`; keep slow-polling meanwhile
57
+ - Reconnect if nothing (not even a heartbeat) arrives for 2 heartbeat intervals
58
+ - Reopen promptly after `resync`
59
+ - Fetch all devices right after `hello`, then every ≥ 15 minutes
60
+ - gzip enabled; API key kept out of the stream URL; bad keys back off to the maximum delay
61
+
62
+ Controlling the AC (on/off, mode, temperature) is not part of the stream — use the REST API,
63
+ e.g. an *http request* node to `POST https://home.sensibo.com/api/v2/pods/{id}/acStates`
64
+ with body `{"acState":{"on":true}}`, or another Sensibo Node-RED package.
65
+
66
+ ## Development
67
+
68
+ ```sh
69
+ npm test
70
+ ```
71
+
72
+ Tests run against a local mock SSE server. Set `SENSIBO_BASE_URL` to point the nodes at a
73
+ mock API when testing inside Node-RED.
@@ -0,0 +1,11 @@
1
+ [
2
+ {"id":"ex_tab","type":"tab","label":"Sensibo stream example"},
3
+ {"id":"ex_cfg","type":"sensibo-stream-account","name":"My Sensibo","pollMinutes":15,"fetchOnChange":true},
4
+ {"id":"ex_inject","type":"inject","z":"ex_tab","name":"refresh all","props":[{"p":"payload"}],"payload":"refresh","payloadType":"str","x":130,"y":80,"wires":[["ex_stream"]]},
5
+ {"id":"ex_stream","type":"sensibo-event-stream","z":"ex_tab","name":"","account":"ex_cfg","devices":"","evHello":false,"evMeasurements":true,"evChanged":false,"evResync":false,"evDevice":true,"evPoll":true,"includeDevice":true,"x":320,"y":80,"wires":[["ex_switch"]]},
6
+ {"id":"ex_switch","type":"switch","z":"ex_tab","name":"by event","property":"event","propertyType":"msg","rules":[{"t":"eq","v":"measurements","vt":"str"},{"t":"eq","v":"device","vt":"str"},{"t":"eq","v":"poll","vt":"str"}],"checkall":"true","repair":false,"outputs":3,"x":500,"y":80,"wires":[["ex_temp"],["ex_ac"],["ex_ac"]]},
7
+ {"id":"ex_temp","type":"change","z":"ex_tab","name":"temperature","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload.measurements.temperature","tot":"msg"}],"x":690,"y":40,"wires":[["ex_dbg1"]]},
8
+ {"id":"ex_ac","type":"change","z":"ex_tab","name":"acState","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload.acState","tot":"msg"}],"x":680,"y":120,"wires":[["ex_dbg2"]]},
9
+ {"id":"ex_dbg1","type":"debug","z":"ex_tab","name":"temperature","active":true,"tosidebar":true,"complete":"false","x":880,"y":40,"wires":[]},
10
+ {"id":"ex_dbg2","type":"debug","z":"ex_tab","name":"AC state","active":true,"tosidebar":true,"complete":"false","x":870,"y":120,"wires":[]}
11
+ ]
package/lib/api.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const DEFAULT_BASE_URL = 'https://home.sensibo.com/api/v2';
4
+
5
+ class SensiboApiError extends Error {
6
+ constructor(message, status, body) {
7
+ super(message);
8
+ this.name = 'SensiboApiError';
9
+ this.status = status;
10
+ this.body = body;
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Small REST client for the parts of the Sensibo API the stream needs.
16
+ * Uses the global fetch (Node >= 18), which transparently decompresses gzip.
17
+ */
18
+ class SensiboApi {
19
+ constructor({ apiKey, baseUrl = DEFAULT_BASE_URL, fetchImpl } = {}) {
20
+ if (!apiKey) throw new Error('Sensibo API key is required');
21
+ this.apiKey = apiKey;
22
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
23
+ this.fetch = fetchImpl || globalThis.fetch;
24
+ }
25
+
26
+ // Note: only GET /stream accepts the X-Api-Key header. The REST endpoints
27
+ // authenticate with the documented `apiKey` query parameter (they return 401
28
+ // for a header-only request), so request() adds it to the URL.
29
+ headers(extra) {
30
+ return Object.assign({
31
+ 'Accept': 'application/json',
32
+ 'Accept-Encoding': 'gzip'
33
+ }, extra);
34
+ }
35
+
36
+ async request(method, path, { query, body, signal } = {}) {
37
+ const url = new URL(this.baseUrl + path);
38
+ url.searchParams.set('apiKey', this.apiKey);
39
+ if (query) {
40
+ for (const [k, v] of Object.entries(query)) {
41
+ if (v !== undefined && v !== null) url.searchParams.set(k, v);
42
+ }
43
+ }
44
+ const init = { method, headers: this.headers(), signal };
45
+ if (body !== undefined) {
46
+ init.headers['Content-Type'] = 'application/json';
47
+ init.body = JSON.stringify(body);
48
+ }
49
+ const res = await this.fetch(url, init);
50
+ const text = await res.text();
51
+ let json;
52
+ try { json = text ? JSON.parse(text) : undefined; } catch (_) { json = undefined; }
53
+ if (!res.ok) {
54
+ const reason = (json && (json.reason || json.message)) || res.statusText || 'request failed';
55
+ const err = new SensiboApiError(`Sensibo API ${method} ${path}: HTTP ${res.status} ${reason}`, res.status, json || text);
56
+ err.retryAfter = parseRetryAfter(res.headers.get('retry-after'));
57
+ throw err;
58
+ }
59
+ return json && Object.prototype.hasOwnProperty.call(json, 'result') ? json.result : json;
60
+ }
61
+
62
+ getPods({ fields = '*', signal } = {}) {
63
+ return this.request('GET', '/users/me/pods', { query: { fields }, signal });
64
+ }
65
+
66
+ getPod(id, { fields = '*', signal } = {}) {
67
+ return this.request('GET', `/pods/${encodeURIComponent(id)}`, { query: { fields }, signal });
68
+ }
69
+ }
70
+
71
+ /** Parse a Retry-After header (delta-seconds or HTTP-date) into milliseconds. */
72
+ function parseRetryAfter(value, now = Date.now()) {
73
+ if (value === null || value === undefined || value === '') return 0;
74
+ const s = String(value).trim();
75
+ if (/^\d+(\.\d+)?$/.test(s)) return Math.round(parseFloat(s) * 1000);
76
+ const t = Date.parse(s);
77
+ if (!isNaN(t)) return Math.max(0, t - now);
78
+ return 0;
79
+ }
80
+
81
+ module.exports = { SensiboApi, SensiboApiError, parseRetryAfter, DEFAULT_BASE_URL };
@@ -0,0 +1,360 @@
1
+ 'use strict';
2
+
3
+ const { EventEmitter } = require('events');
4
+ const { SSEParser } = require('./sse-parser');
5
+ const { SensiboApi, parseRetryAfter, DEFAULT_BASE_URL } = require('./api');
6
+
7
+ const MIN_POLL_MS = 15 * 60 * 1000;
8
+
9
+ /**
10
+ * One SensiboAccount = one open GET /stream connection for one API key.
11
+ *
12
+ * Implements the Sensibo "Rules for Clients":
13
+ * - reconnect with exponential backoff (capped at 5 min) plus jitter
14
+ * - honour Retry-After on 429 / 503, and keep slow-polling while the stream is down
15
+ * - treat > 2 heartbeat intervals of silence as a dead connection
16
+ * - reopen on `resync`
17
+ * - fetch all devices right after `hello`, and slow-poll every >= 15 min
18
+ * - merge `measurements` into a cached device object; re-read a device on `changed`
19
+ *
20
+ * Emits:
21
+ * 'status' { state, text }
22
+ * 'event' { event, data, id } every parsed stream event (data already JSON-parsed)
23
+ * 'device' { id, device, reason, fields } a device was (re)loaded or updated
24
+ * 'warn' Error non-fatal problems (never 'error', so nothing throws)
25
+ */
26
+ class SensiboAccount extends EventEmitter {
27
+ constructor(opts = {}) {
28
+ super();
29
+ this.setMaxListeners(0);
30
+ this.api = opts.api || new SensiboApi({ apiKey: opts.apiKey, baseUrl: opts.baseUrl, fetchImpl: opts.fetchImpl });
31
+ this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
32
+ this.fetch = opts.fetchImpl || globalThis.fetch;
33
+
34
+ this.backoffBaseMs = opts.backoffBaseMs ?? 2000;
35
+ this.backoffMaxMs = opts.backoffMaxMs ?? 5 * 60 * 1000;
36
+ this.resyncDelayMs = opts.resyncDelayMs ?? 3000;
37
+ this.jitterMs = opts.jitterMs ?? 3000;
38
+ this.pollIntervalMs = opts.allowFastPoll ? (opts.pollIntervalMs ?? MIN_POLL_MS)
39
+ : Math.max(MIN_POLL_MS, opts.pollIntervalMs ?? MIN_POLL_MS);
40
+ this.fetchOnChange = opts.fetchOnChange !== false;
41
+ this.defaultHeartbeatSeconds = opts.defaultHeartbeatSeconds ?? 120;
42
+ this.heartbeatGraceMs = opts.heartbeatGraceMs ?? 5000;
43
+
44
+ this.devices = new Map();
45
+ this.state = 'stopped';
46
+ this.failures = 0;
47
+ this.running = false;
48
+ this._abort = null;
49
+ this._reconnectTimer = null;
50
+ this._watchdog = null;
51
+ this._pollTimer = null;
52
+ this._podFetches = new Map(); // id -> { pending: bool, fields: Set }
53
+ this._loadedIds = new Set(); // devices whose full state came from the REST API
54
+ this.loaded = false; // at least one full device load succeeded
55
+ this._fallbackLoadDone = false;
56
+ }
57
+
58
+ // ---------------------------------------------------------------- lifecycle
59
+
60
+ start() {
61
+ if (this.running) return;
62
+ this.running = true;
63
+ this.failures = 0;
64
+ this._fallbackLoadDone = false;
65
+ this._schedulePoll();
66
+ this._connect();
67
+ }
68
+
69
+ stop() {
70
+ this.running = false;
71
+ clearTimeout(this._reconnectTimer);
72
+ clearTimeout(this._watchdog);
73
+ clearTimeout(this._pollTimer);
74
+ this._reconnectTimer = this._watchdog = this._pollTimer = null;
75
+ if (this._abort) this._abort.abort();
76
+ this._abort = null;
77
+ this._setStatus('stopped', 'stopped');
78
+ }
79
+
80
+ /** Force-close the current stream and reconnect promptly. */
81
+ reconnect() {
82
+ if (!this.running) return;
83
+ this.failures = 0;
84
+ this._closeStream();
85
+ clearTimeout(this._reconnectTimer);
86
+ this._reconnectTimer = setTimeout(() => this._connect(), 0);
87
+ }
88
+
89
+ getDevice(id) {
90
+ return this.devices.get(id);
91
+ }
92
+
93
+ /** Devices whose full state has been loaded from the REST API (for late subscribers). */
94
+ getLoadedDevices() {
95
+ return Array.from(this._loadedIds).map((id) => this.devices.get(id)).filter(Boolean);
96
+ }
97
+
98
+ // ---------------------------------------------------------------- stream
99
+
100
+ async _connect() {
101
+ if (!this.running) return;
102
+ this._reconnectTimer = null;
103
+ const abort = new AbortController();
104
+ this._abort = abort;
105
+ this._setStatus('connecting', 'connecting');
106
+
107
+ let res;
108
+ try {
109
+ res = await this.fetch(this.baseUrl + '/stream', {
110
+ method: 'GET',
111
+ headers: {
112
+ 'X-Api-Key': this.api.apiKey,
113
+ 'Accept': 'text/event-stream',
114
+ 'Accept-Encoding': 'gzip',
115
+ 'Cache-Control': 'no-cache'
116
+ },
117
+ signal: abort.signal
118
+ });
119
+ } catch (err) {
120
+ if (abort.signal.aborted) return;
121
+ this._emitWarn(err);
122
+ this._scheduleReconnect({ reason: err.message || 'connection failed' });
123
+ return;
124
+ }
125
+ if (abort.signal.aborted || !this.running) {
126
+ cancelBody(res);
127
+ return;
128
+ }
129
+
130
+ if (!res.ok) {
131
+ try { await res.text(); } catch (_) {}
132
+ const retryAfter = parseRetryAfter(res.headers.get('retry-after'));
133
+ if (res.status === 429 || res.status === 503) {
134
+ this._setStatus('unavailable', `stream unavailable (HTTP ${res.status}), polling`);
135
+ this._scheduleReconnect({ minDelay: retryAfter, reason: `HTTP ${res.status}`, keepStatus: true });
136
+ } else if (res.status === 401 || res.status === 403) {
137
+ this._setStatus('error', `auth failed (HTTP ${res.status}) - check API key`);
138
+ this._emitWarn(new Error(`Sensibo stream rejected the API key (HTTP ${res.status})`));
139
+ // Do not hammer the API with a bad key: go straight to the max backoff.
140
+ this.failures = 100;
141
+ this._scheduleReconnect({ minDelay: retryAfter, reason: `HTTP ${res.status}`, keepStatus: true });
142
+ } else {
143
+ this._scheduleReconnect({ minDelay: retryAfter, reason: `HTTP ${res.status}` });
144
+ }
145
+ return;
146
+ }
147
+
148
+ this._setStatus('connected', 'connected');
149
+ this._heartbeatMs = this.defaultHeartbeatSeconds * 1000;
150
+ this._armWatchdog();
151
+
152
+ let resync = false;
153
+ const parser = new SSEParser({
154
+ onComment: () => { /* heartbeat: watchdog already re-armed per chunk */ },
155
+ onEvent: (evt) => {
156
+ if (evt.event === 'resync') resync = true;
157
+ this._handleEvent(evt);
158
+ }
159
+ });
160
+
161
+ try {
162
+ const decoder = new TextDecoder('utf-8');
163
+ for await (const chunk of res.body) {
164
+ if (abort.signal.aborted) break;
165
+ this._armWatchdog();
166
+ parser.push(decoder.decode(chunk, { stream: true }));
167
+ if (resync) break;
168
+ }
169
+ } catch (err) {
170
+ if (!abort.signal.aborted) this._emitWarn(err);
171
+ } finally {
172
+ clearTimeout(this._watchdog);
173
+ this._watchdog = null;
174
+ cancelBody(res);
175
+ }
176
+
177
+ if (this._abort === abort) this._abort = null;
178
+ if (!this.running) return;
179
+ if (abort.signal.aborted && abort._reason !== 'watchdog') return; // explicit reconnect/stop
180
+ if (resync) {
181
+ this._scheduleReconnect({ fixed: this.resyncDelayMs, reason: 'resync' });
182
+ } else if (abort._reason === 'watchdog') {
183
+ this._scheduleReconnect({ reason: 'heartbeat timeout' });
184
+ } else {
185
+ this._scheduleReconnect({ reason: 'stream closed' });
186
+ }
187
+ }
188
+
189
+ _closeStream(reason) {
190
+ if (this._abort) {
191
+ this._abort._reason = reason;
192
+ this._abort.abort();
193
+ }
194
+ }
195
+
196
+ _armWatchdog() {
197
+ clearTimeout(this._watchdog);
198
+ // "If no data arrives for more than two heartbeat intervals, close and reconnect."
199
+ const ms = this._heartbeatMs * 2 + this.heartbeatGraceMs;
200
+ this._watchdog = setTimeout(() => {
201
+ this._emitWarn(new Error(`No data from Sensibo stream for ${Math.round(ms / 1000)}s, reconnecting`));
202
+ this._closeStream('watchdog');
203
+ }, ms);
204
+ if (this._watchdog.unref) this._watchdog.unref();
205
+ }
206
+
207
+ _scheduleReconnect({ minDelay = 0, fixed, reason, keepStatus } = {}) {
208
+ if (!this.running) return;
209
+ clearTimeout(this._reconnectTimer);
210
+ let delay;
211
+ if (fixed !== undefined) {
212
+ delay = fixed + Math.random() * this.jitterMs;
213
+ } else {
214
+ const exp = Math.min(this.backoffMaxMs, this.backoffBaseMs * Math.pow(2, Math.min(this.failures, 20)));
215
+ delay = Math.min(this.backoffMaxMs, exp + Math.random() * this.jitterMs);
216
+ this.failures++;
217
+ }
218
+ delay = Math.max(delay, minDelay);
219
+ if (!keepStatus) {
220
+ this._setStatus('disconnected', `${reason}, retry in ${Math.round(delay / 1000)}s`);
221
+ }
222
+ // Stream not available at start-up: load the devices once over REST so values
223
+ // are available now instead of after the first slow poll.
224
+ if (!this.loaded && !this._fallbackLoadDone) {
225
+ this._fallbackLoadDone = true;
226
+ this.refresh('startup');
227
+ }
228
+ this._reconnectTimer = setTimeout(() => this._connect(), delay);
229
+ this.emit('reconnecting', { delay, reason });
230
+ }
231
+
232
+ // ---------------------------------------------------------------- events
233
+
234
+ _handleEvent(evt) {
235
+ let data = evt.data;
236
+ try { data = JSON.parse(evt.data); } catch (_) { /* leave as string */ }
237
+ const out = { event: evt.event, data, id: evt.id };
238
+
239
+ switch (evt.event) {
240
+ case 'hello':
241
+ this.failures = 0;
242
+ if (data && data.heartbeatSeconds > 0) {
243
+ this._heartbeatMs = data.heartbeatSeconds * 1000;
244
+ this._armWatchdog();
245
+ }
246
+ this._setStatus('connected', `connected (${data && data.pods !== undefined ? data.pods + ' devices' : 'ok'})`);
247
+ this.emit('event', out);
248
+ // Changes may have happened before the stream opened: fetch everything once now.
249
+ this.refresh('hello');
250
+ return;
251
+ case 'measurements':
252
+ this._mergeMeasurements(data);
253
+ break;
254
+ case 'changed':
255
+ this.emit('event', out);
256
+ if (this.fetchOnChange && data && data.id) {
257
+ this._fetchPod(data.podId || data.id, data.fields);
258
+ }
259
+ return;
260
+ default:
261
+ break;
262
+ }
263
+ this.emit('event', out);
264
+ }
265
+
266
+ _mergeMeasurements(data) {
267
+ if (!data || !data.id || !data.measurements) return;
268
+ // For room/window sensors `id` is the sensor and `podId` its device;
269
+ // sensors are cached under their own id.
270
+ const entry = this.devices.get(data.id) || { id: data.id };
271
+ if (data.podId) entry.podId = data.podId;
272
+ entry.measurements = Object.assign({}, entry.measurements, data.measurements);
273
+ this.devices.set(data.id, entry);
274
+ }
275
+
276
+ // ---------------------------------------------------------------- REST
277
+
278
+ /** Fetch all devices and emit a 'device' event for each. */
279
+ async refresh(reason = 'poll') {
280
+ try {
281
+ const pods = await this.api.getPods();
282
+ if (!Array.isArray(pods)) return [];
283
+ for (const pod of pods) {
284
+ if (!pod || !pod.id) continue;
285
+ this.devices.set(pod.id, pod);
286
+ this._loadedIds.add(pod.id);
287
+ this.emit('device', { id: pod.id, device: pod, reason, fields: [] });
288
+ }
289
+ this.loaded = true;
290
+ return pods;
291
+ } catch (err) {
292
+ this._emitWarn(err);
293
+ return [];
294
+ }
295
+ }
296
+
297
+ _fetchPod(id, fields) {
298
+ // Coalesce: if a fetch for this device is in flight, just re-run once after it.
299
+ const inflight = this._podFetches.get(id);
300
+ const f = Array.isArray(fields) ? fields : [];
301
+ if (inflight) {
302
+ inflight.pending = true;
303
+ f.forEach((x) => inflight.fields.add(x));
304
+ if (f.length === 0) inflight.all = true;
305
+ return;
306
+ }
307
+ const entry = { pending: false, fields: new Set(f), all: f.length === 0 };
308
+ this._podFetches.set(id, entry);
309
+ const run = async () => {
310
+ const changed = entry.all ? [] : Array.from(entry.fields);
311
+ entry.fields = new Set();
312
+ entry.all = false;
313
+ entry.pending = false;
314
+ try {
315
+ const pod = await this.api.getPod(id);
316
+ if (pod) {
317
+ if (!pod.id) pod.id = id;
318
+ this.devices.set(id, pod);
319
+ this._loadedIds.add(id);
320
+ this.emit('device', { id, device: pod, reason: 'changed', fields: changed });
321
+ }
322
+ } catch (err) {
323
+ this._emitWarn(err);
324
+ }
325
+ if (entry.pending && this.running) return run();
326
+ this._podFetches.delete(id);
327
+ };
328
+ run();
329
+ }
330
+
331
+ _schedulePoll() {
332
+ clearTimeout(this._pollTimer);
333
+ if (!this.running || !(this.pollIntervalMs > 0)) return;
334
+ this._pollTimer = setTimeout(async () => {
335
+ await this.refresh('poll');
336
+ this._schedulePoll();
337
+ }, this.pollIntervalMs);
338
+ }
339
+
340
+ // ---------------------------------------------------------------- helpers
341
+
342
+ _setStatus(state, text) {
343
+ this.state = state;
344
+ this.emit('status', { state, text });
345
+ }
346
+
347
+ _emitWarn(err) {
348
+ this.emit('warn', err);
349
+ }
350
+ }
351
+
352
+ function cancelBody(res) {
353
+ try {
354
+ if (res && res.body && typeof res.body.cancel === 'function') {
355
+ Promise.resolve(res.body.cancel()).catch(() => {});
356
+ }
357
+ } catch (_) { /* already closed */ }
358
+ }
359
+
360
+ module.exports = { SensiboAccount, MIN_POLL_MS };
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Minimal, spec-compliant Server-Sent Events parser.
5
+ * https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
6
+ *
7
+ * Feed it decoded text chunks with push(); it calls
8
+ * onEvent({ event, data, id }) for every dispatched event
9
+ * onComment(text) for every comment line (":" prefix; Sensibo heartbeats)
10
+ */
11
+ class SSEParser {
12
+ constructor({ onEvent, onComment, onRetry } = {}) {
13
+ this.onEvent = onEvent || (() => {});
14
+ this.onComment = onComment || (() => {});
15
+ this.onRetry = onRetry || (() => {});
16
+ this.reset();
17
+ }
18
+
19
+ reset() {
20
+ this.buffer = '';
21
+ this.skipLF = false;
22
+ this.eventType = '';
23
+ this.dataLines = [];
24
+ this.lastEventId = '';
25
+ }
26
+
27
+ push(chunk) {
28
+ let text = chunk;
29
+ if (this.skipLF && text.length > 0) {
30
+ if (text[0] === '\n') text = text.slice(1);
31
+ this.skipLF = false;
32
+ }
33
+ this.buffer += text;
34
+
35
+ let start = 0;
36
+ for (let i = 0; i < this.buffer.length; i++) {
37
+ const ch = this.buffer[i];
38
+ if (ch !== '\n' && ch !== '\r') continue;
39
+ this._line(this.buffer.slice(start, i));
40
+ if (ch === '\r') {
41
+ if (i + 1 < this.buffer.length) {
42
+ if (this.buffer[i + 1] === '\n') i++;
43
+ } else {
44
+ // CR at the end of the chunk: a following LF belongs to it.
45
+ this.skipLF = true;
46
+ }
47
+ }
48
+ start = i + 1;
49
+ }
50
+ this.buffer = this.buffer.slice(start);
51
+ }
52
+
53
+ _line(line) {
54
+ if (line === '') {
55
+ this._dispatch();
56
+ return;
57
+ }
58
+ if (line[0] === ':') {
59
+ this.onComment(line.slice(1).replace(/^ /, ''));
60
+ return;
61
+ }
62
+ const colon = line.indexOf(':');
63
+ let field, value;
64
+ if (colon === -1) {
65
+ field = line;
66
+ value = '';
67
+ } else {
68
+ field = line.slice(0, colon);
69
+ value = line.slice(colon + 1);
70
+ if (value[0] === ' ') value = value.slice(1);
71
+ }
72
+ switch (field) {
73
+ case 'event':
74
+ this.eventType = value;
75
+ break;
76
+ case 'data':
77
+ this.dataLines.push(value);
78
+ break;
79
+ case 'id':
80
+ if (!value.includes('\0')) this.lastEventId = value;
81
+ break;
82
+ case 'retry':
83
+ if (/^\d+$/.test(value)) this.onRetry(parseInt(value, 10));
84
+ break;
85
+ default:
86
+ break; // ignore unknown fields
87
+ }
88
+ }
89
+
90
+ _dispatch() {
91
+ if (this.dataLines.length === 0) {
92
+ this.eventType = '';
93
+ return;
94
+ }
95
+ const evt = {
96
+ event: this.eventType || 'message',
97
+ data: this.dataLines.join('\n'),
98
+ id: this.lastEventId
99
+ };
100
+ this.eventType = '';
101
+ this.dataLines = [];
102
+ this.onEvent(evt);
103
+ }
104
+ }
105
+
106
+ module.exports = { SSEParser };
@@ -0,0 +1,53 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType('sensibo-stream-account', {
3
+ category: 'config',
4
+ defaults: {
5
+ name: { value: '' },
6
+ pollMinutes: { value: 15, required: true, validate: function (v) { return parseInt(v, 10) >= 15; } },
7
+ fetchOnChange: { value: true }
8
+ },
9
+ credentials: {
10
+ apiKey: { type: 'password' }
11
+ },
12
+ label: function () {
13
+ return this.name || 'Sensibo account';
14
+ }
15
+ });
16
+ </script>
17
+
18
+ <script type="text/html" data-template-name="sensibo-stream-account">
19
+ <div class="form-row">
20
+ <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
21
+ <input type="text" id="node-config-input-name" placeholder="Sensibo account">
22
+ </div>
23
+ <div class="form-row">
24
+ <label for="node-config-input-apiKey"><i class="fa fa-key"></i> API key</label>
25
+ <input type="password" id="node-config-input-apiKey">
26
+ </div>
27
+ <div class="form-row">
28
+ <label for="node-config-input-pollMinutes"><i class="fa fa-clock-o"></i> Slow poll</label>
29
+ <input type="number" id="node-config-input-pollMinutes" min="15" style="width: 80px"> minutes (min 15)
30
+ </div>
31
+ <div class="form-row">
32
+ <label for="node-config-input-fetchOnChange">&nbsp;</label>
33
+ <input type="checkbox" id="node-config-input-fetchOnChange" style="display:inline-block; width:auto; vertical-align:top;">
34
+ <label for="node-config-input-fetchOnChange" style="width:auto;">Re-read device on <code>changed</code> events</label>
35
+ </div>
36
+ </script>
37
+
38
+ <script type="text/html" data-help-name="sensibo-stream-account">
39
+ <p>A Sensibo account. All stream nodes that use the same account share a
40
+ single <code>GET /stream</code> connection (Sensibo allows at most 10 open streams per account).</p>
41
+ <h3>Properties</h3>
42
+ <dl class="message-properties">
43
+ <dt>API key <span class="property-type">string</span></dt>
44
+ <dd>Create one at <a href="https://home.sensibo.com/me/api" target="_blank">home.sensibo.com/me/api</a>.
45
+ The same key works for the stream and for the REST API used for device state.</dd>
46
+ <dt>Slow poll <span class="property-type">minutes</span></dt>
47
+ <dd>How often all devices are re-read, because not every field produces a stream event.
48
+ Sensibo asks for 15 minutes or more. Polling continues at this rate while the stream is unavailable.</dd>
49
+ <dt>Re-read device on changed</dt>
50
+ <dd>When a <code>changed</code> event arrives, fetch <code>/pods/{id}</code> and emit a
51
+ <code>device</code> message with the full new state.</dd>
52
+ </dl>
53
+ </script>
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ const { SensiboAccount } = require('../lib/sensibo-account');
4
+
5
+ module.exports = function (RED) {
6
+ function SensiboConfigNode(config) {
7
+ RED.nodes.createNode(this, config);
8
+ const node = this;
9
+ node.name = config.name;
10
+ node.pollMinutes = Math.max(15, parseInt(config.pollMinutes, 10) || 15);
11
+ node.fetchOnChange = config.fetchOnChange !== false;
12
+ node.users = new Set();
13
+ node.account = null;
14
+
15
+ const apiKey = node.credentials && node.credentials.apiKey;
16
+
17
+ function getAccount() {
18
+ if (node.account) return node.account;
19
+ if (!apiKey) return null;
20
+ node.account = new SensiboAccount({
21
+ apiKey,
22
+ // Undocumented override, intended for testing against a mock server.
23
+ baseUrl: process.env.SENSIBO_BASE_URL || undefined,
24
+ pollIntervalMs: node.pollMinutes * 60 * 1000,
25
+ fetchOnChange: node.fetchOnChange
26
+ });
27
+ node.account.on('warn', (err) => node.warn(err && err.message ? err.message : String(err)));
28
+ return node.account;
29
+ }
30
+
31
+ // One shared stream per account (Sensibo allows max 10 open streams per account).
32
+ node.register = function (user) {
33
+ const account = getAccount();
34
+ if (!account) return null;
35
+ node.users.add(user);
36
+ if (node.users.size === 1) account.start();
37
+ return account;
38
+ };
39
+
40
+ node.deregister = function (user) {
41
+ node.users.delete(user);
42
+ if (node.users.size === 0 && node.account) node.account.stop();
43
+ };
44
+
45
+ node.on('close', function (done) {
46
+ if (node.account) {
47
+ node.account.stop();
48
+ node.account.removeAllListeners();
49
+ node.account = null;
50
+ }
51
+ node.users.clear();
52
+ done();
53
+ });
54
+ }
55
+
56
+ RED.nodes.registerType('sensibo-stream-account', SensiboConfigNode, {
57
+ credentials: {
58
+ apiKey: { type: 'password' }
59
+ }
60
+ });
61
+ };
@@ -0,0 +1,106 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType('sensibo-event-stream', {
3
+ category: 'home automation',
4
+ color: '#5ac8a8',
5
+ defaults: {
6
+ name: { value: '' },
7
+ account: { value: '', type: 'sensibo-stream-account', required: true },
8
+ devices: { value: '' },
9
+ evHello: { value: true },
10
+ evMeasurements: { value: true },
11
+ evChanged: { value: true },
12
+ evResync: { value: false },
13
+ evDevice: { value: true },
14
+ evPoll: { value: true },
15
+ includeDevice: { value: true }
16
+ },
17
+ inputs: 1,
18
+ outputs: 1,
19
+ icon: 'bridge.svg',
20
+ inputLabels: 'refresh / reconnect',
21
+ outputLabels: 'events',
22
+ label: function () {
23
+ return this.name || 'sensibo stream';
24
+ },
25
+ paletteLabel: 'sensibo stream'
26
+ });
27
+ </script>
28
+
29
+ <script type="text/html" data-template-name="sensibo-event-stream">
30
+ <div class="form-row">
31
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
32
+ <input type="text" id="node-input-name" placeholder="sensibo stream">
33
+ </div>
34
+ <div class="form-row">
35
+ <label for="node-input-account"><i class="fa fa-user"></i> Account</label>
36
+ <input type="text" id="node-input-account">
37
+ </div>
38
+ <div class="form-row">
39
+ <label for="node-input-devices"><i class="fa fa-filter"></i> Devices</label>
40
+ <input type="text" id="node-input-devices" placeholder="all devices (or comma-separated device ids)">
41
+ </div>
42
+ <div class="form-row">
43
+ <label><i class="fa fa-list"></i> Output</label>
44
+ <div style="display:inline-block; width:70%;">
45
+ <label style="width:auto;"><input type="checkbox" id="node-input-evMeasurements" style="width:auto;"> <code>measurements</code> events</label><br>
46
+ <label style="width:auto;"><input type="checkbox" id="node-input-evChanged" style="width:auto;"> <code>changed</code> events</label><br>
47
+ <label style="width:auto;"><input type="checkbox" id="node-input-evDevice" style="width:auto;"> <code>device</code> &ndash; full state after a change</label><br>
48
+ <label style="width:auto;"><input type="checkbox" id="node-input-evPoll" style="width:auto;"> <code>poll</code> &ndash; full state at start-up and every slow poll</label><br>
49
+ <label style="width:auto;"><input type="checkbox" id="node-input-evHello" style="width:auto;"> <code>hello</code> events</label><br>
50
+ <label style="width:auto;"><input type="checkbox" id="node-input-evResync" style="width:auto;"> <code>resync</code> events</label>
51
+ </div>
52
+ </div>
53
+ <div class="form-row">
54
+ <label>&nbsp;</label>
55
+ <label style="width:auto;"><input type="checkbox" id="node-input-includeDevice" style="width:auto;"> Attach cached device state as <code>msg.device</code></label>
56
+ </div>
57
+ </script>
58
+
59
+ <script type="text/html" data-help-name="sensibo-event-stream">
60
+ <p>Receives real-time events from the Sensibo API v2
61
+ <a href="https://support.sensibo.com/api/#event-stream" target="_blank">Event Stream</a>
62
+ (<code>GET /stream</code>, Server-Sent Events).</p>
63
+ <p>The connection is shared by all nodes using the same account, and follows Sensibo's client rules:
64
+ backoff with jitter up to 5 minutes, <code>Retry-After</code> on 429/503, reconnect after two
65
+ missed heartbeats, reopen on <code>resync</code>, and a 15+ minute slow poll.</p>
66
+
67
+ <h3>Inputs</h3>
68
+ <dl class="message-properties">
69
+ <dt>payload <span class="property-type">string</span></dt>
70
+ <dd><code>"reconnect"</code> closes and reopens the stream. Anything else re-reads all devices
71
+ and emits <code>poll</code> messages (if enabled).</dd>
72
+ </dl>
73
+
74
+ <h3>Outputs</h3>
75
+ <dl class="message-properties">
76
+ <dt>event <span class="property-type">string</span></dt>
77
+ <dd><code>measurements</code>, <code>changed</code>, <code>device</code>, <code>poll</code>,
78
+ <code>hello</code> or <code>resync</code>.</dd>
79
+ <dt>topic <span class="property-type">string</span></dt>
80
+ <dd><code>sensibo/&lt;event&gt;/&lt;deviceId&gt;</code></dd>
81
+ <dt>deviceId <span class="property-type">string</span></dt>
82
+ <dd>The device (or sensor) id.</dd>
83
+ <dt class="optional">podId <span class="property-type">string</span></dt>
84
+ <dd>For room/window sensor measurements: the device the sensor belongs to.</dd>
85
+ <dt>payload <span class="property-type">object</span></dt>
86
+ <dd>For stream events, the event's JSON data, e.g.
87
+ <code>{"id":"AbCd1234","measurements":{"temperature":23.4,...}}</code>.
88
+ For <code>device</code> / <code>poll</code>, the full device object from
89
+ <code>/pods/{id}</code>.</dd>
90
+ <dt class="optional">reason <span class="property-type">string</span></dt>
91
+ <dd>For <code>poll</code>: why the state was loaded &ndash; <code>hello</code> (stream opened),
92
+ <code>startup</code> (stream unavailable at start-up), <code>cached</code> (node redeployed
93
+ while the connection was open), <code>poll</code> (slow poll) or <code>refresh</code> (input).</dd>
94
+ <dt class="optional">fields <span class="property-type">array</span></dt>
95
+ <dd>For <code>changed</code> / <code>device</code>: what changed, e.g. <code>["acState"]</code>.
96
+ Empty means anything may have changed.</dd>
97
+ <dt class="optional">device <span class="property-type">object</span></dt>
98
+ <dd>The cached device state, with stream measurements merged in.</dd>
99
+ </dl>
100
+
101
+ <h3>Details</h3>
102
+ <p>Use a <i>switch</i> node on <code>msg.event</code> to route event types.
103
+ A typical flow listens to <code>measurements</code> for temperature/humidity and
104
+ <code>device</code> for AC state (<code>msg.payload.acState</code>).</p>
105
+ <p>Commands (AC state, timers, schedules, Climate React) still go through the REST API.</p>
106
+ </script>
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ const STATUS = {
4
+ connecting: { fill: 'yellow', shape: 'ring' },
5
+ connected: { fill: 'green', shape: 'dot' },
6
+ disconnected: { fill: 'red', shape: 'ring' },
7
+ unavailable: { fill: 'yellow', shape: 'dot' },
8
+ error: { fill: 'red', shape: 'dot' },
9
+ stopped: { fill: 'grey', shape: 'ring' }
10
+ };
11
+
12
+ module.exports = function (RED) {
13
+ function SensiboStreamNode(config) {
14
+ RED.nodes.createNode(this, config);
15
+ const node = this;
16
+ const accountNode = RED.nodes.getNode(config.account);
17
+
18
+ const deviceFilter = new Set(String(config.devices || '')
19
+ .split(/[\s,;]+/).map((s) => s.trim()).filter(Boolean));
20
+ const wanted = {
21
+ hello: config.evHello !== false,
22
+ measurements: config.evMeasurements !== false,
23
+ changed: config.evChanged !== false,
24
+ resync: config.evResync === true,
25
+ device: config.evDevice !== false,
26
+ poll: config.evPoll !== false
27
+ };
28
+ const includeDevice = config.includeDevice !== false;
29
+
30
+ if (!accountNode) {
31
+ node.status({ fill: 'red', shape: 'ring', text: 'no account configured' });
32
+ return;
33
+ }
34
+ const account = accountNode.register(node);
35
+ if (!account) {
36
+ node.status({ fill: 'red', shape: 'ring', text: 'missing API key' });
37
+ return;
38
+ }
39
+
40
+ function matches(...ids) {
41
+ if (deviceFilter.size === 0) return true;
42
+ return ids.some((id) => id && deviceFilter.has(id));
43
+ }
44
+
45
+ function onStatus({ state, text }) {
46
+ node.status(Object.assign({ text }, STATUS[state] || STATUS.stopped));
47
+ }
48
+
49
+ function onEvent({ event, data }) {
50
+ if (!wanted[event] && ['hello', 'measurements', 'changed', 'resync'].includes(event)) return;
51
+ const id = data && data.id;
52
+ const podId = data && data.podId;
53
+ if (id && !matches(id, podId)) return;
54
+ const msg = {
55
+ topic: 'sensibo/' + event + (id ? '/' + id : ''),
56
+ event,
57
+ payload: data
58
+ };
59
+ if (id) msg.deviceId = id;
60
+ if (podId) msg.podId = podId;
61
+ if (event === 'changed' && data) msg.fields = data.fields || [];
62
+ if (includeDevice && id) {
63
+ const d = account.getDevice(id);
64
+ if (d) msg.device = RED.util.cloneMessage(d);
65
+ }
66
+ node.send(msg);
67
+ }
68
+
69
+ function onDevice({ id, device, reason, fields }) {
70
+ const kind = reason === 'changed' ? 'device' : 'poll';
71
+ if (!wanted[kind]) return;
72
+ if (!matches(id)) return;
73
+ node.send({
74
+ topic: 'sensibo/' + kind + '/' + id,
75
+ event: kind,
76
+ reason,
77
+ deviceId: id,
78
+ fields: fields || [],
79
+ payload: RED.util.cloneMessage(device)
80
+ });
81
+ }
82
+
83
+ account.on('status', onStatus);
84
+ account.on('event', onEvent);
85
+ account.on('device', onDevice);
86
+
87
+ // If the shared connection was already running (e.g. only this node was redeployed),
88
+ // replay the cached device state so this node starts with all values.
89
+ if (account.loaded) {
90
+ setImmediate(() => {
91
+ for (const device of account.getLoadedDevices()) {
92
+ onDevice({ id: device.id, device, reason: 'cached', fields: [] });
93
+ }
94
+ });
95
+ }
96
+ onStatus({ state: account.state === 'stopped' ? 'connecting' : account.state, text: account.state === 'stopped' ? 'connecting' : account.state });
97
+
98
+ node.on('input', function (msg, send, done) {
99
+ const cmd = typeof msg.payload === 'string' ? msg.payload.toLowerCase() : '';
100
+ if (cmd === 'reconnect') {
101
+ account.reconnect();
102
+ done();
103
+ } else {
104
+ account.refresh('refresh').then(() => done(), done);
105
+ }
106
+ });
107
+
108
+ node.on('close', function (done) {
109
+ account.off('status', onStatus);
110
+ account.off('event', onEvent);
111
+ account.off('device', onDevice);
112
+ accountNode.deregister(node);
113
+ done();
114
+ });
115
+ }
116
+
117
+ RED.nodes.registerType('sensibo-event-stream', SensiboStreamNode);
118
+ };
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "node-red-contrib-sensibo-stream",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.5",
4
+ "description": "Node-RED nodes for the Sensibo API v2 real-time Event Stream (Server-Sent Events)",
5
+ "main": "nodes/sensibo-stream.js",
6
+ "scripts": {
7
+ "test": "node --test test/*.test.js"
8
+ },
9
+ "keywords": [
10
+ "node-red",
11
+ "sensibo",
12
+ "air conditioner",
13
+ "sse",
14
+ "event stream",
15
+ "home automation"
16
+ ],
17
+ "license": "MIT",
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "files": [
22
+ "lib",
23
+ "nodes",
24
+ "examples",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "node-red": {
29
+ "version": ">=3.0.0",
30
+ "nodes": {
31
+ "sensibo-stream-account": "nodes/sensibo-config.js",
32
+ "sensibo-event-stream": "nodes/sensibo-stream.js"
33
+ }
34
+ }
35
+ }