-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgladys-integration.js
More file actions
1424 lines (1366 loc) · 61.3 KB
/
Copy pathgladys-integration.js
File metadata and controls
1424 lines (1366 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { EventEmitter } = require('events');
const net = require('net');
const WebSocket = require('ws');
const { computeBackoffDelay } = require('./backoff');
const {
WEBSOCKET_MESSAGE_TYPES,
INVALID_ACCESS_TOKEN_CLOSE_CODE,
MAX_STATES_PER_REQUEST,
MAX_TRANSPORTS_PER_REQUEST,
MAX_TRANSPORT_MESSAGE_LENGTH,
MAX_CAMERA_IMAGE_SIZE,
MAX_MESSAGE_TEXT_LENGTH,
MAX_ACTIVE_SCAN_PAYLOAD_SIZE,
MAX_WEBHOOK_SYNC_BODY_SIZE,
DEVICE_TRANSPORTS,
DEFAULT_RECONNECT_BASE_DELAY,
DEFAULT_RECONNECT_MAX_DELAY,
DEFAULT_REQUEST_TIMEOUT,
} = require('./constants');
const { debug } = require('./debug');
const { describeError } = require('./errors');
const { HttpClient } = require('./http-client');
const { createLogger } = require('./logger');
const { AUTHENTICATE, AUTHENTICATION, EXTERNAL_INTEGRATION } = WEBSOCKET_MESSAGE_TYPES;
/**
* Client of the Gladys host API + integration WebSocket (contracts C.2–C.4).
*
* Local state kept by the SDK (refreshed on every (re)connection and by the
* device-created/updated/deleted and config-updated events): `devices`,
* `config`, `connected`. Lifecycle is observable through the 'connected' and
* 'disconnected' events (the class extends EventEmitter).
*/
class GladysIntegration extends EventEmitter {
/**
* @description Create the integration client. Every option defaults to the
* environment variables injected in the integration container (contract C.7),
* and can be overridden for development outside Docker.
* @param {object} [options] - Options.
* @param {string} [options.hostApiUrl] - Host API base URL (default: GLADYS_HOST_API_URL).
* @param {string} [options.token] - Integration JWT (default: GLADYS_INTEGRATION_TOKEN).
* @param {string} [options.selector] - Integration selector (default: GLADYS_INTEGRATION_SELECTOR).
* @param {number} [options.reconnectBaseDelay] - First reconnection delay in ms (default: 1000).
* @param {number} [options.reconnectMaxDelay] - Reconnection delay cap in ms (default: 60000).
* @param {number} [options.requestTimeout] - Host API request timeout in ms (default: 15000).
* @param {object} [options.logger] - Logger used for the connection lifecycle
* logs (default: `createLogger({ name: 'gladys-sdk' })`). Pass
* `createLogger({ level: 'silent' })` to silence the SDK entirely.
* @example
* const gladys = new GladysIntegration();
*/
constructor(options = {}) {
super();
const hostApiUrl = options.hostApiUrl || process.env.GLADYS_HOST_API_URL;
const token = options.token || process.env.GLADYS_INTEGRATION_TOKEN;
const selector = options.selector || process.env.GLADYS_INTEGRATION_SELECTOR;
if (!hostApiUrl) {
throw new Error('GladysIntegration: missing "hostApiUrl" option (or GLADYS_HOST_API_URL env var)');
}
if (!token) {
throw new Error('GladysIntegration: missing "token" option (or GLADYS_INTEGRATION_TOKEN env var)');
}
if (!selector) {
throw new Error('GladysIntegration: missing "selector" option (or GLADYS_INTEGRATION_SELECTOR env var)');
}
this.hostApiUrl = hostApiUrl.replace(/\/+$/, '');
this.token = token;
this.selector = selector;
this.wsUrl = this.hostApiUrl.replace(/^http/, 'ws');
this.reconnectBaseDelay = options.reconnectBaseDelay || DEFAULT_RECONNECT_BASE_DELAY;
this.reconnectMaxDelay = options.reconnectMaxDelay || DEFAULT_RECONNECT_MAX_DELAY;
this.requestTimeout = options.requestTimeout || DEFAULT_REQUEST_TIMEOUT;
this.logger = options.logger || createLogger({ name: 'gladys-sdk' });
this.httpClient = new HttpClient(this.hostApiUrl, this.token, this.requestTimeout);
this.devices = [];
this.config = {};
this.connected = false;
this.handlers = {};
this.ws = null;
this.shouldReconnect = false;
this.reconnectAttempts = 0;
this.reconnectTimer = null;
}
/**
* @description Build a namespaced external id: `ext:<selector>:<suffix>`.
* This is the only documented way to build an external_id.
* @param {string} suffix - Integration-chosen identifier suffix.
* @returns {string} The prefixed external id.
* @example
* gladys.externalId('switch:binary'); // 'ext:my-integration:switch:binary'
*/
externalId(suffix) {
return `ext:${this.selector}:${suffix}`;
}
/**
* @description Build the external ids of ONE physical device: its device id
* and a factory for its feature ids. `platformId` must be the unique id the
* external platform gives you (serial number, cloud device id, Zigbee IEEE
* address, MAC…), never a hard-coded label: external ids must stay globally
* unique and stable across restarts, they are how Gladys matches states to
* devices.
* @param {string} type - Device type namespace, e.g. 'weather-station'.
* @param {string} platformId - Unique id from the external platform.
* @returns {object} `{ device, feature(featureKey) }`.
* @example
* const ids = gladys.externalIds('plug', '0x00158d0001a2b3c4');
* ids.device; // 'ext:my-integration:plug:0x00158d0001a2b3c4'
* ids.feature('power'); // 'ext:my-integration:plug:0x00158d0001a2b3c4:power'
*/
externalIds(type, platformId) {
const device = this.externalId(`${type}:${platformId}`);
return {
device,
feature: (featureKey) => `${device}:${featureKey}`,
};
}
/**
* @description Register the handler called when the user actions a device
* feature. `value` is a number for every feature except the `text` category
* ones, whose commands are strings — the free text of a `text`/`text`
* feature, the selected option value of a `text`/`select` dynamic select.
* Resolving acks the command with success; throwing acks it as failed
* with the error message.
* @param {Function} callback - `(device, deviceFeature, value) => Promise`.
* @example
* gladys.onSetValue(async (device, feature, value) => {});
*/
onSetValue(callback) {
this.handlers.setValue = callback;
}
/**
* @description Register the handler called when the Gladys scheduler asks to
* poll a device (devices published with a poll_frequency). Respond by
* publishing states through publishState/publishStates.
* @param {Function} callback - `(device) => Promise`.
* @example
* gladys.onPoll(async (device) => {});
*/
onPoll(callback) {
this.handlers.poll = callback;
}
/**
* @description Register the handler called when Gladys needs a FRESH image
* of one of the integration cameras (live view of the dashboard widget, chat
* intent "show me the camera"). Capture and resolve the image as an
* `image/jpg;base64,...` string (≤ 150 KB): it is acked back as `data.image`.
* The ack is awaited under 15 s (not the standard 5 s) so an ffmpeg-style
* capture fits; throwing acks the command as failed with the error message.
* @param {Function} callback - `(device) => Promise<string>`.
* @example
* gladys.onGetImage(async (device) => `image/jpg;base64,${await captureJpeg(device)}`);
*/
onGetImage(callback) {
this.handlers.getImage = callback;
}
/**
* @description Register the handler called when the user asks for a device
* scan from the Discovery screen. Respond through publishDiscoveredDevices.
* @param {Function} callback - `() => Promise`.
* @example
* gladys.onScanRequest(async () => {});
*/
onScanRequest(callback) {
this.handlers.scanRequest = callback;
}
/**
* @description Register the handler called when the user creates one of the
* discovered devices in the Gladys UI.
* @param {Function} callback - `(device) => Promise`.
* @example
* gladys.onDeviceCreated(async (device) => {});
*/
onDeviceCreated(callback) {
this.handlers.deviceCreated = callback;
}
/**
* @description Register the handler called when the user updates one of the
* integration devices in the Gladys UI.
* @param {Function} callback - `(device) => Promise`.
* @example
* gladys.onDeviceUpdated(async (device) => {});
*/
onDeviceUpdated(callback) {
this.handlers.deviceUpdated = callback;
}
/**
* @description Register the handler called when the user deletes one of the
* integration devices in the Gladys UI.
* @param {Function} callback - `(device) => Promise`.
* @example
* gladys.onDeviceDeleted(async (device) => {});
*/
onDeviceDeleted(callback) {
this.handlers.deviceDeleted = callback;
}
/**
* @description Register the handler called when the user saves the
* configuration form. Receives the complete new configuration values.
* @param {Function} callback - `(config) => Promise`.
* @example
* gladys.onConfigUpdated(async (config) => {});
*/
onConfigUpdated(callback) {
this.handlers.configUpdated = callback;
}
/**
* @description Register the handler called when the user changes the
* hardware grants of the sub-containers (contract C.4 `hardware-updated`):
* the affected sub-containers have been recreated; regenerate their
* configuration (e.g. `edgetpu` vs `cpu` detector) and (re)start what is
* needed through startContainer/restartContainer.
* @param {Function} callback - `(containers) => Promise`, `containers` being
* `[{ name, devices: [{ class, granted, available }] }]`.
* @example
* gladys.onHardwareUpdated(async (containers) => {});
*/
onHardwareUpdated(callback) {
this.handlers.hardwareUpdated = callback;
}
/**
* @description Register the handler called when the user clicks "Connect" on
* an `oauth2` or an `account_link` config field. Build and return the
* provider authorization URL — for `oauth2`: client_id from the config,
* scopes, a `state` you generate and remember for the callback. The resolved
* string is acked back to Gladys as `data.authorize_url` and opened in the
* user browser. For an `account_link` field (a provider that never redirects
* back — QR sign-in approved in the vendor app, pairing confirmed on a
* device) `redirectUri` is `undefined`, there is no callback: return the
* provider sign-in URL, watch for the approval yourself (long-poll the
* provider), then report it through setConnectionStatus(true).
* @param {Function} callback - `(key, redirectUri) => Promise<string>`.
* @example
* gladys.onOAuthAuthorizeUrl(async (key, redirectUri) => 'https://provider/authorize?...');
*/
onOAuthAuthorizeUrl(callback) {
this.handlers.oauthAuthorizeUrl = callback;
}
/**
* @description Register the handler called when the OAuth2 provider
* redirects back after the user consent. Verify `state`, exchange the code
* for the tokens, store them through setConfig (keys outside the
* config_schema), then report through setConnectionStatus(true). Throwing
* acks the command as failed with the error message.
* @param {Function} callback - `(key, { code, state, redirectUri }) => Promise`.
* @example
* gladys.onOAuthCallback(async (key, { code, state, redirectUri }) => {});
*/
onOAuthCallback(callback) {
this.handlers.oauthCallback = callback;
}
/**
* @description Register the handler called when Gladys asks a communication
* integration (manifest `type: "communication"`, contract B.15) to deliver a
* message in the external channel — a reply of the brain, or a notification
* forwarded to a user. `contact` carries the identity resolved by Gladys,
* whose shape follows the manifest `messaging.receive` flag: `{ id }` — the
* linked contact id — for a bidirectional channel linked by code
* (`receive: true`, Telegram-style), or the target user's `contact_schema`
* values for a send-only notification channel (`receive: false`, Free
* Mobile/CallMeBot-style — e.g. `{ username, access_token }`). Users
* without a configured identity are skipped by Gladys and never reach the
* handler. `message` is `{ text, file }` (`file` is a base64 image or
* null). Resolving acks the command with success; throwing acks it as
* failed with the error message.
* @param {Function} callback - `(contact, message) => Promise`.
* @example
* gladys.onSendMessage(async (contact, message) => bot.sendMessage(contact.id, message.text));
* @example
* // Send-only channel (messaging.receive: false): contact carries the
* // target user's contact_schema values.
* gladys.onSendMessage(async (contact, message) => sendSms(contact.username, contact.access_token, message.text));
*/
onSendMessage(callback) {
this.handlers.sendMessage = callback;
}
/**
* @description Register the handler called when Gladys asks a weather
* integration (manifest `type: "weather"`, contract B.18) for the weather —
* the dashboard weather widget or the chat assistant needs it. `options` is
* `{ latitude, longitude, language, units }`; `units` is the requesting
* user's preference, `'metric'` or `'us'`: return values in that unit
* system (°C, m/s, hPa, mm, km for metric; °F, mph, in, mi for us).
* Resolve the pivot weather format: `temperature`, `weather` (condition of
* WEATHER_CONDITIONS) and `datetime` required, plus the optional current
* fields (`apparent_temperature`, `humidity`, `pressure`, `dew_point`,
* `wind_speed`, `wind_direction`, `wind_gust`, `visibility`, `cloud_cover`,
* `uv_index`, `sunrise`, `sunset`, `is_day`), `hours` (≤ 24), `days` (≤ 8)
* and `alerts` (≤ 10, CAP-style `severity` + `event`, plus an optional
* phenomenon `type` of WEATHER_ALERT_TYPES). `is_day` (strict boolean, on
* the current conditions and each hour) drives the day/night rendering
* variant while `weather` keeps the meteorology — preferred over the
* deprecated 'night' condition (a rainy night stays 'rain'). The resolved
* object is acked back as `data.weather` — awaited under 15 s (not the
* standard 5 s) so a fresh third-party API call fits — then normalized and
* bounded by the Gladys core (unknown fields dropped, percentages clamped
* to 0-100, unknown conditions coerced to 'unknown'). Throwing acks the
* command as failed, and the Gladys provider loop falls through to the
* next provider.
* @param {Function} callback - `(options) => Promise<object>`.
* @example
* gladys.onWeatherGet(async ({ latitude, longitude, language, units }) => ({
* temperature: 21.5,
* weather: 'rain',
* datetime: new Date().toISOString(),
* humidity: 80,
* hours: [],
* days: [],
* }));
*/
onWeatherGet(callback) {
this.handlers.weatherGet = callback;
}
/**
* @description Register the handler called when Gladys asks a weather
* integration for one of the provider images declared in the pivot's
* `images` metadata (contract B.18: vigilance map, rain radar, satellite
* view…). Registered once for all keys; the callback receives the `key` of
* the requested image and resolves its RAW base64 (no `data:` URI prefix).
* The decoded bytes must be a PNG or a JPEG of at most 500 KB: the Gladys
* core checks the magic numbers and the size, caches the validated image
* 10 minutes per key, and serves it to the browser from its own origin —
* the browser never loads a third-party URL. The ack is awaited under 15 s
* (not the standard 5 s) so a fresh fetch at the provider fits; throwing
* acks the command as failed.
* @param {Function} callback - `(key) => Promise<string>`.
* @example
* gladys.onWeatherGetImage(async (key) => (await fetchVigilanceMapPng(key)).toString('base64'));
*/
onWeatherGetImage(callback) {
this.handlers.weatherGetImage = callback;
}
/**
* @description Send a freshness nudge to Gladys (contract B.18, weather
* integrations, "trigger, not data"): ask the core to re-pull the weather
* NOW — through the normal onWeatherGet path — and re-evaluate the
* weather-alert scene triggers, instead of waiting for the 30-minute
* scheduled check. The nudge carries no data and expects no answer
* (fire-and-forget): call it when the integration KNOWS something changed
* upstream (e.g. a vigilance poll detected a new alert). Rate-limited by
* the core to 1 per minute per integration, silently dropped beyond — and
* dropped silently too while the WebSocket is disconnected (the 30-minute
* floor catches up).
* @example
* gladys.requestWeatherRefresh();
*/
requestWeatherRefresh() {
this._send(EXTERNAL_INTEGRATION.WEATHER_REFRESH, {});
}
/**
* @description Register the handler of ONE webhook declared in the manifest
* `webhooks` field (contract B.17): third-party events pushed from the
* Internet, relayed by Gladys Plus to the local Gladys then to the
* integration. Registered per webhook `key`; the callback receives the
* relayed request `{ method, query, body, contentType }` (`body` is the raw
* body relayed by the gateway).
*
* In `fire_and_forget` mode (the Netatmo-style event stream) the caller was
* already answered: the resolved value is ignored, and errors are swallowed.
* Doctrine "trigger, not data": webhook events arrive duplicated, late or
* out of order, and their payloads are partial — use them to TRIGGER a
* refresh through the manufacturer API, never apply the payload as a state
* (that is also what makes lost events painless: the poll stays the source
* of truth).
*
* In `sync` mode (challenge/response registrations, Strava/Microsoft Graph
* style) the caller awaits the integration response: resolve with
* `{ status?, contentType?, body? }` (status 200-499, body ≤ 64 KB) and it
* is returned to the third party through Gladys Plus; resolving `undefined`
* or throwing lets Gladys answer its default empty `200`.
* @param {string} key - Webhook key, as declared in the manifest.
* @param {Function} callback - `({ method, query, body, contentType }) => Promise`.
* @example
* gladys.onWebhook('events', async ({ body }) => refreshFromApi());
* @example
* gladys.onWebhook('callback', async ({ query }) => ({
* status: 200,
* contentType: 'application/json',
* body: JSON.stringify({ 'hub.challenge': query['hub.challenge'] }),
* }));
*/
onWebhook(key, callback) {
this.handlers[`webhook:${key}`] = callback;
}
/**
* @description Register the handler called when the Gladys Plus webhook
* availability changes (contract B.17): Gladys Plus linked or unlinked, Open
* API key created or changed. Receives the same `{ available, webhooks }`
* object as getWebhooks(): re-register the fresh URLs at the third party
* when `available` turns true, or degrade to poll only when it turns false.
* @param {Function} callback - `({ available, webhooks }) => Promise`.
* @example
* gladys.onWebhookUpdated(async ({ available, webhooks }) => {});
*/
onWebhookUpdated(callback) {
this.handlers.webhookUpdated = callback;
}
/**
* @description Register the handler of ONE action declared in the manifest
* `actions` field (contract C.1) — connection test, identify, protocol
* detection… — run when the user clicks its button in the Configuration
* screen. Registered per action `key`; receives the values of the action
* `fields` mini-form. The resolved value (a string or a multi-language
* object) is acked back as `data.message` and shown under the button —
* throwing shows the error message instead. The ack is awaited under the
* action's declared `timeout_seconds` (not the standard 5 s), so long
* operations are fine.
* @param {string} key - Action key, as declared in the manifest.
* @param {Function} callback - `(fields) => Promise<string|object>`.
* @example
* gladys.onAction('detect_protocol', async (fields) => `Protocol 3.3 detected on ${fields.ip}`);
*/
onAction(key, callback) {
this.handlers[`action:${key}`] = callback;
}
/**
* @description Open the WebSocket, authenticate, resynchronize local state
* (GET /device + GET /config), then resolve. Reconnects automatically for
* life with an exponential backoff of min(1s * 2^n, 60s); every reconnection
* re-authenticates and resynchronizes. When Gladys refuses the token (close
* code 4000) the loop stays armed but jumps straight to the max delay —
* the refusal may be transient (token validation error at boot) and a live
* container that stops reconnecting is never recreated by the supervisor.
* connect() rejects when the refusal happens during the initial connection.
* @returns {Promise<void>} Resolves once authenticated and resynchronized.
* @example
* await gladys.connect();
*/
async connect() {
this.shouldReconnect = true;
return new Promise((resolve, reject) => {
const initial = {
settled: false,
resolve: () => {
if (!initial.settled) {
initial.settled = true;
resolve();
}
},
reject: (error) => {
if (!initial.settled) {
initial.settled = true;
reject(error);
}
},
};
this._openWebSocket(initial);
});
}
/**
* @description Close the connection cleanly and stop reconnecting.
* @returns {Promise<void>} Resolves once the socket is closed.
* @example
* await gladys.disconnect();
*/
async disconnect() {
this.shouldReconnect = false;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
this.connected = false;
return;
}
await new Promise((resolve) => {
this.ws.once('close', resolve);
this.ws.close(1000);
});
}
/**
* @description Exit gracefully on SIGTERM/SIGINT (sent by the supervisor
* when the container stops): run the optional cleanup, disconnect cleanly,
* then exit with code 0. Cleanup/disconnect errors are swallowed — the
* process is stopping anyway. Call it once, next to the other handlers.
* @param {Function} [cleanup] - `(signal) => Promise`, run before disconnecting.
* @example
* gladys.handleShutdown(async () => stopPolling());
*/
handleShutdown(cleanup) {
const shutdown = async (signal) => {
debug(`received ${signal}, shutting down`);
if (cleanup) {
try {
await cleanup(signal);
} catch (e) {
debug('shutdown cleanup failed', e.message);
}
}
try {
await this.disconnect();
} catch (e) {
debug('disconnect failed during shutdown', e.message);
}
process.exit(0);
};
process.once('SIGTERM', () => shutdown('SIGTERM'));
process.once('SIGINT', () => shutdown('SIGINT'));
}
/**
* @description Publish the complete list of discovered devices (replaces the
* previous one). Devices are shown in the Discovery screen of the Gladys UI,
* where the user creates them.
* @param {Array} devices - Devices in the standard Gladys format.
* @returns {Promise<object>} `{ success, count }`.
* @example
* await gladys.publishDiscoveredDevices([{ name: 'Sensor', external_id: gladys.externalId('sensor'), features: [] }]);
*/
async publishDiscoveredDevices(devices) {
return this.httpClient.post('/discovered_device', { devices });
}
/**
* @description Fetch the integration devices actually created by the user,
* and refresh `gladys.devices`.
* @returns {Promise<Array>} The devices.
* @example
* const devices = await gladys.getDevices();
*/
async getDevices() {
const devices = await this.httpClient.get('/device');
this.devices = devices;
return devices;
}
/**
* @description Publish one device feature state. `value` is a number, or
* `{ text }` for a text state, or `{ state, created_at }` for a past state.
* @param {string} featureExternalId - The feature external_id.
* @param {number|object} value - The state value.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.publishState(gladys.externalId('sensor:temperature'), 21.5);
*/
async publishState(featureExternalId, value) {
const state = { device_feature_external_id: featureExternalId };
if (value !== null && typeof value === 'object') {
if (value.text !== undefined) {
state.text = value.text;
}
if (value.state !== undefined) {
state.state = value.state;
}
if (value.created_at !== undefined) {
state.created_at = value.created_at;
}
} else {
state.state = value;
}
return this.publishStates([state]);
}
/**
* @description Publish a batch of device feature states (max 100 per request,
* contract C.3).
* @param {Array} states - States: `{ device_feature_external_id, state|text, created_at? }`.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.publishStates([{ device_feature_external_id: 'ext:demo:sensor:temperature', state: 21.5 }]);
*/
async publishStates(states) {
if (!Array.isArray(states)) {
throw new Error('publishStates: "states" must be an array');
}
if (states.length > MAX_STATES_PER_REQUEST) {
throw new Error(`publishStates: maximum ${MAX_STATES_PER_REQUEST} states per request`);
}
return this.httpClient.post('/state', { states });
}
/**
* @description Publish a new image of a camera device of the integration
* (contract C.3): a device carrying a `camera`/`image` feature, declared
* like any feature in the discovered devices. The dashboard camera widget
* updates in real time. Images never go through the states path: dedicated
* channel, out of the states history and rate limit — but limited to 150 KB
* and 12 images/minute per device (the continuous video stream is not the
* scope: this is the periodic snapshot path).
* @param {string} deviceExternalId - The camera device external_id.
* @param {string} image - The image, as an `image/jpg;base64,...` string (≤ 150 KB).
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.publishCameraImage(gladys.externalId('cam:abc'), `image/jpg;base64,${jpegBase64}`);
*/
async publishCameraImage(deviceExternalId, image) {
if (typeof image !== 'string') {
throw new Error('publishCameraImage: "image" must be an "image/jpg;base64,..." string');
}
if (image.length > MAX_CAMERA_IMAGE_SIZE) {
throw new Error(`publishCameraImage: maximum image size is ${MAX_CAMERA_IMAGE_SIZE} bytes (150 KB)`);
}
return this.httpClient.post('/camera/image', { device_external_id: deviceExternalId, image });
}
/**
* @description Publish the per-device transport status of the integration
* devices (contract C.3): `'local'`, `'cloud'` or `'unreachable'`, stored in
* the reserved GLADYS_TRANSPORT device param and rendered as a badge on the
* devices in the Gladys UI, in real time. This is the lightweight path for
* live switches (the cloud link drops → 'unreachable', the LAN comes back →
* 'local') — no need to re-publish the discovered devices. Unknown external
* ids are ignored silently by Gladys. The matching user preference arrives
* in `gladys.config.GLADYS_PREFER_LOCAL` (a wish, not an order: apply it
* when you can, and reflect the per-device reality here).
*
* An entry can also carry the degraded state — "it works, but not in the
* nominal mode", which the three transport values cannot express (field
* case: device seen by the local scan but local sessions refused → cloud
* fallback looks like a perfectly normal 'cloud' badge): `degraded: true`
* plus an optional multi-language `message` (`en` mandatory, ≤ 200
* characters per language) giving the reason. The badge keeps its transport
* color with an orange dot overlay, and the tooltip shows the message.
* Degraded is orthogonal to the transport — "which channel is in use" and
* "is this the nominal state" are two different pieces of information — and
* publishing an entry WITHOUT `degraded` explicitly clears a previously
* published degraded state (back to nominal, no ghost orange dot).
* @param {Array} transports - Entries: `{ external_id, transport, degraded, message }` (max 100).
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.publishTransports([{ external_id: gladys.externalId('plug:abc'), transport: 'local' }]);
* @example
* await gladys.publishTransports([
* {
* external_id: gladys.externalId('plug:abc'),
* transport: 'cloud',
* degraded: true,
* message: { en: 'Local session refused, falling back to cloud' },
* },
* ]);
*/
async publishTransports(transports) {
if (!Array.isArray(transports)) {
throw new Error('publishTransports: "transports" must be an array');
}
if (transports.length > MAX_TRANSPORTS_PER_REQUEST) {
throw new Error(`publishTransports: maximum ${MAX_TRANSPORTS_PER_REQUEST} transports per request`);
}
const validTransports = Object.values(DEVICE_TRANSPORTS);
const entries = transports.map((entry) => {
const deviceExternalId = entry.external_id || entry.device_external_id;
if (!deviceExternalId) {
throw new Error('publishTransports: every entry must carry an "external_id"');
}
if (!validTransports.includes(entry.transport)) {
throw new Error(`publishTransports: "transport" must be one of ${validTransports.join(', ')}`);
}
if (entry.degraded !== undefined && typeof entry.degraded !== 'boolean') {
throw new Error('publishTransports: "degraded" must be a boolean');
}
if (entry.message !== undefined && entry.degraded !== true) {
throw new Error('publishTransports: "message" is only taken into account when "degraded" is true');
}
const mapped = { device_external_id: deviceExternalId, transport: entry.transport };
if (entry.degraded === true) {
mapped.degraded = true;
if (entry.message !== undefined) {
const { message } = entry;
// Only own enumerable properties survive the JSON serialization, so
// an inherited "en" (Object.create) would reach Gladys as {} → 400.
if (
typeof message !== 'object' ||
message === null ||
Array.isArray(message) ||
!Object.prototype.propertyIsEnumerable.call(message, 'en') ||
typeof message.en !== 'string' ||
!message.en
) {
throw new Error('publishTransports: "message" must be a multi-language object with a mandatory "en" key');
}
for (const text of Object.values(message)) {
if (typeof text !== 'string' || text.length > MAX_TRANSPORT_MESSAGE_LENGTH) {
throw new Error(
`publishTransports: every "message" language must be a string of at most ${MAX_TRANSPORT_MESSAGE_LENGTH} characters`,
);
}
}
mapped.message = message;
}
}
return mapped;
});
return this.httpClient.post('/device/transport', { transports: entries });
}
/**
* @description Publish a message received in the external channel (contract
* B.15, communication integrations): Gladys resolves the contact to the
* linked user, then routes the message to the brain, the chat history and
* the answering machinery — replies come back through the onSendMessage
* handler. An incoming message carries the authority of the linked user, so
* the contact MUST have linked their account first (linkContact): an unknown
* contact is rejected with a 404 `GladysApiError`, and the integration
* should then answer in the channel "account not linked, code required".
* Bidirectional channels only: when the manifest declares
* `messaging: { receive: false }` (send-only notification channel), Gladys
* rejects the call with a 403 — a notification channel never talks to the
* brain, guaranteed server-side.
* @param {string} contactId - Id of the contact in the external channel.
* @param {string} text - Text of the message (1-4096 characters).
* @param {object} [options] - Options.
* @param {string|Date} [options.createdAt] - ISO date of the message, for
* messages received while the integration was offline.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.publishMessage('12345', 'Turn on the light');
*/
async publishMessage(contactId, text, options = {}) {
if (typeof contactId !== 'string' || contactId.length === 0) {
throw new Error('publishMessage: "contactId" must be a non-empty string');
}
if (typeof text !== 'string' || text.length === 0) {
throw new Error('publishMessage: "text" must be a non-empty string');
}
if (text.length > MAX_MESSAGE_TEXT_LENGTH) {
throw new Error(`publishMessage: maximum text length is ${MAX_MESSAGE_TEXT_LENGTH} characters`);
}
const body = { contact_id: contactId, text };
if (options.createdAt !== undefined) {
body.created_at = options.createdAt instanceof Date ? options.createdAt.toISOString() : options.createdAt;
}
return this.httpClient.post('/message', body);
}
/**
* @description Link an external contact to a Gladys user (contract B.15,
* bidirectional communication integrations — `messaging.receive: true`; a
* send-only channel has no incoming path to relay a code, its users enter
* their identity in the "My account" block of the Gladys UI instead, from
* the manifest `contact_schema`). The code proves the consent: the user
* generates it from the integration page in the Gladys UI (single use,
* 15 minutes TTL), then sends it to the bot in the external channel — the
* integration relays it here with the channel identity of the sender.
* Resolves with the linked Gladys user, e.g. to greet them in the channel;
* an invalid or expired code is rejected with a 404 `GladysApiError`.
* @param {string} code - The short code typed by the contact in the channel.
* @param {string} contactId - Id of the contact in the external channel.
* @param {string} [contactName] - Display name of the contact, shown in the
* Gladys UI next to the linked user.
* @returns {Promise<object>} The linked user: `{ selector, first_name, language }`.
* @example
* const user = await gladys.linkContact('AB23CD45', '12345', 'John');
*/
async linkContact(code, contactId, contactName) {
if (typeof code !== 'string' || code.length === 0) {
throw new Error('linkContact: "code" must be a non-empty string');
}
if (typeof contactId !== 'string' || contactId.length === 0) {
throw new Error('linkContact: "contactId" must be a non-empty string');
}
const body = { code, contact_id: contactId };
if (contactName !== undefined) {
body.contact_name = contactName;
}
const { user } = await this.httpClient.post('/contact/link', body);
return user;
}
/**
* @description Fetch the contacts linked to the integration, with the
* linked Gladys user of each one (contract B.15, communication
* integrations) — e.g. to resynchronize the channel-side state after a
* restart, or to detect that a contact was unlinked by the user from the
* Gladys UI.
* @returns {Promise<Array>} The contacts:
* `[{ contact_id, contact_name, linked_at, user: { selector, first_name, language } }]`.
* @example
* const contacts = await gladys.getContacts();
*/
async getContacts() {
return this.httpClient.get('/contact');
}
/**
* @description Fetch the Gladys Plus webhook state of the integration
* (contract B.17): whether the relay is available (the user linked Gladys
* Plus and pasted their Open API key in the Configuration screen), and the
* ready-to-register public URL of each webhook declared in the manifest.
* The Netatmo pattern: (re)register the URLs at the third party on every
* successful connection to the service, best effort. `available: false`
* (no Gladys Plus) → degrade to poll only. The `webhook-updated` event
* (onWebhookUpdated) fires when this state changes.
* @returns {Promise<object>} `{ available, webhooks: [{ key, mode, url }] }`.
* @example
* const { available, webhooks } = await gladys.getWebhooks();
*/
async getWebhooks() {
return this.httpClient.get('/webhook');
}
/**
* @description Fetch the integration configuration (all values, secrets
* included), and refresh `gladys.config`.
* @returns {Promise<object>} The configuration values.
* @example
* const config = await gladys.getConfig();
*/
async getConfig() {
const { config } = await this.httpClient.get('/config');
this.config = config;
return config;
}
/**
* @description Save configuration values (partial merge). Keys outside the
* manifest config_schema are free internal storage, never shown in the UI.
* Keys of `section` fields (presentational intro blocks, no stored value)
* are rejected by the host API.
* @param {object} partialConfig - Keys/values to merge.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.setConfig({ pairing_state: 'done' });
*/
async setConfig(partialConfig) {
return this.httpClient.post('/config', { config: partialConfig });
}
/**
* @description Fetch the Gladys version and the integration service status.
* @returns {Promise<object>} `{ gladys_version, service }`.
* @example
* const status = await gladys.getStatus();
*/
async getStatus() {
return this.httpClient.get('/status');
}
/**
* @description Publish the application-level connection status of the
* integration (contract C.3), shown in the Configuration screen of the
* Gladys UI. Distinct from the container state machine: a cloud integration
* can be RUNNING and still disconnected from its third-party service (e.g.
* expired OAuth token) — without this channel it would be silently broken.
* @param {boolean} connected - Whether the integration is connected to its service.
* @param {object} [message] - Optional multi-language message, e.g.
* `{ en: 'Token expired, please reconnect.', fr: 'Token expiré.' }`.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.setConnectionStatus(false, { en: 'Token expired, please reconnect.' });
*/
async setConnectionStatus(connected, message) {
const body = { connected };
if (message !== undefined) {
body.message = message;
}
return this.httpClient.post('/connection_status', body);
}
/**
* @description Fetch the sub-containers declared in the manifest: their
* Docker status, desired state, assigned host ports and, per requested
* hardware class, the granted/available flags (contract C.3) — how the
* integration knows what to put in its generated configs. Each port carries
* `{ container_port, protocol, host_port, label, name, browsable }`;
* `host_port` is `null` while Gladys has not allocated one yet, `name` is the
* optional manifest identifier referenced by the `{{port:<name>}}`
* placeholder of the section texts (`null` when undeclared), and
* `browsable: false` marks a port that serves no web UI (a WebSocket
* endpoint for devices, say).
* @returns {Promise<Array>} The containers; empty if none is declared.
* @example
* const containers = await gladys.getContainers();
*/
async getContainers() {
const { containers } = await this.httpClient.get('/container');
return containers;
}
/**
* @description Create (if needed) and start a sub-container declared in the
* manifest — typically after generating its config files in `/data`. The
* container enters the desired state "running" (restarted by the supervisor
* if it crashes). The optional `env` is merged over the manifest env (keys
* `GLADYS_*` are rejected); when it differs from the existing container env,
* the supervisor recreates the container before starting it.
* @param {string} name - Container name, as declared in the manifest.
* @param {object} [options] - Options.
* @param {object} [options.env] - Runtime-computed environment variables.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.startContainer('mqtt', { env: { MQTT_PASSWORD: password } });
*/
async startContainer(name, options = {}) {
const body = options.env === undefined ? {} : { env: options.env };
return this.httpClient.post(`/container/${encodeURIComponent(name)}/start`, body);
}
/**
* @description Stop a sub-container and clear its desired state: the
* supervisor will not restart it.
* @param {string} name - Container name, as declared in the manifest.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.stopContainer('mqtt');
*/
async stopContainer(name) {
return this.httpClient.post(`/container/${encodeURIComponent(name)}/stop`, {});
}
/**
* @description Restart a sub-container — typically after rewriting one of
* its config files through `/data` to apply it.
* @param {string} name - Container name, as declared in the manifest.
* @returns {Promise<object>} `{ success }`.
* @example
* await gladys.restartContainer('frigate');
*/
async restartContainer(name) {
return this.httpClient.post(`/container/${encodeURIComponent(name)}/restart`, {});
}
/**
* @description Run an on-demand mediated network scan (contract B.16).
* Bridge containers never receive LAN broadcast/mDNS/SSDP traffic, so the
* core — which runs on the host network — captures what the manifest
* `network_discovery` field declares and returns the RAW results: the core
* captures (network position), the integration interprets (protocol
* knowledge). Parse the results yourself (e.g. decode the Tuya
* `payload_base64` announcements), join the devices through unicast (which
* crosses the NAT), then publish them with publishDiscoveredDevices.
* Undeclared type/ports are rejected with a 403.
*
* 'udp-active-broadcast' is the query/response variant (TP-Link Kasa style):
* the integration forges the discovery request (`payload`, the protocol
* crypto stays on the integration side), the core broadcasts it on `port`
* and relays the raw unicast replies in the same shape as 'udp-broadcast'.
* Guardrails enforced by the core: broadcast only (never a chosen unicast
* target), port declared in the manifest, payload of at most 512 decoded
* bytes, 1 scan per 10 seconds per integration (429 otherwise).
* @param {string} type - Declared capture type: 'udp-broadcast' |
* 'udp-active-broadcast' | 'mdns' | 'ssdp'.
* @param {object} [options] - Options.
* @param {number} [options.timeoutSeconds] - Scan duration in seconds (1-30).
* @param {number} [options.port] - 'udp-active-broadcast' only (required): destination
* UDP port of the broadcast, among the manifest-declared ports.
* @param {Buffer|string} [options.payload] - 'udp-active-broadcast' only (required):
* discovery request to broadcast, as a Buffer or an already-base64-encoded
* string (≤ 512 decoded bytes).
* @returns {Promise<Array>} Raw results — 'udp-broadcast' and
* 'udp-active-broadcast': `[{ source_ip, source_port, payload_base64 }]`;
* 'mdns': `[{ name, host, addresses, port, txt }]` (every declared mdns
* entry is browsed, results merged); 'ssdp':
* `[{ source_ip, source_mac?, source_port, headers }]` — `headers` is the
* raw response text, `source_mac` a best-effort ARP-table lookup by the
* core (its absence is ordinary, not an error).
* @example
* const results = await gladys.scanNetwork('udp-broadcast', { timeoutSeconds: 10 });
* @example
* const replies = await gladys.scanNetwork('udp-active-broadcast', {
* port: 9999,
* payload: encryptKasaDiscoveryRequest(), // your protocol code, returns a Buffer
* timeoutSeconds: 5,
* });
*/
async scanNetwork(type, options = {}) {
const body = { type };
if (type === 'udp-active-broadcast') {
if (!Number.isInteger(options.port)) {
throw new Error('scanNetwork: "port" (a manifest-declared port) is required for a udp-active-broadcast scan');
}
let payloadBuffer;
if (Buffer.isBuffer(options.payload)) {
payloadBuffer = options.payload;
} else if (typeof options.payload === 'string' && options.payload.length > 0) {
payloadBuffer = Buffer.from(options.payload, 'base64');
} else {
throw new Error(
'scanNetwork: "payload" (a Buffer or a base64 string) is required for a udp-active-broadcast scan',
);
}
if (payloadBuffer.length === 0) {
throw new Error('scanNetwork: "payload" must not be empty');
}
if (payloadBuffer.length > MAX_ACTIVE_SCAN_PAYLOAD_SIZE) {
throw new Error(`scanNetwork: maximum payload size is ${MAX_ACTIVE_SCAN_PAYLOAD_SIZE} decoded bytes`);
}