-
Notifications
You must be signed in to change notification settings - Fork 1
/
hue-callionica.js
3019 lines (2581 loc) · 101 KB
/
hue-callionica.js
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
// deno-lint-ignore-file require-await no-unused-vars no-constant-condition
"use strict";
import { lightXY, lightCT, ctToXY, Point } from "./hue-callionica-color.js";
/**
* Generates a unique ID
* @returns { string }
*/
export function uuid() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
export class Timeout {}
export class TimeoutExpired extends Timeout {}
export class TimeoutCanceled extends Timeout {}
// Timeout expiry and timeout cancelation are not errors
/**
*
* @param { number } ms
* @param { AbortSignal } signal
* @returns { Promise<TimeoutCanceled> | Promise<TimeoutExpired> }
*/
export function delay(ms, signal) {
let timeoutHandle;
let resolve;
if (signal !== undefined) {
signal.addEventListener("abort", () => {
if (timeoutHandle !== undefined) {
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
resolve(new TimeoutCanceled());
}
});
}
return new Promise((res) => {
resolve = res;
timeoutHandle = setTimeout(() => {
timeoutHandle = undefined;
resolve(new TimeoutExpired());
}, ms);
});
}
// In case we ever decide to redefine 'fetch', we keep track of the original
const original = (() => {
const fetch = globalThis.fetch.bind(globalThis);
return { fetch };
})();
// Throws TimeoutExpired or TimeoutCanceled
export async function fetchJSON(input, init = undefined, timeoutMS = 2000) {
const fetchController = new AbortController();
const signal = fetchController.signal;
const timeoutController = new AbortController();
const timeout = delay(timeoutMS, timeoutController.signal);
if (init?.signal !== undefined) {
// A signal from the outside is treated like a timeout cancelation
// The connection will be aborted naturally, like a timeout expiry
init.signal.addEventListener("abort", () => {
timeoutController.abort();
});
}
try {
// Race the fetch and the timeout
const response = await Promise.race([original.fetch(input, { ...init, signal }), timeout]);
// If the winner of the race was the timeout (either expired or canceled),
// abort the fetch and convert the result to an exception
if (response instanceof Timeout) {
fetchController.abort();
throw response;
}
// Otherwise the winner of the race was the fetch, so continue obtaining the data
const json = await Promise.race([response.json(), timeout]);
// If the winner of the race was the timeout (either expired or canceled),
// abort the fetch and convert the result to an exception
if (json instanceof Timeout) {
fetchController.abort();
throw json;
}
// Otherwise the winner of the race was the json, so return the result
return json;
} finally {
// Aborting the timeout in all cases is safe
timeoutController.abort();
}
}
export async function retry(fn, delays) {
try {
return await fn();
} catch (e) {
if (delays.length === 0) {
throw e;
}
// console.log("RETRY", new Date(), delays[0]);
await delay(delays[0]);
return await retry(fn, delays.slice(1));
}
}
// Component classid for use in resourcelinks
const COMPONENT_CLASSID = 9090;
// Dimmer constants
const BTN_initial_press = 0;
const BTN_repeat = 1;
const BTN_short_release = 2;
const BTN_long_release = 3;
const BTN_ON = 1000;
const BTN_STAR_UP = 2000;
const BTN_STAR_DOWN = 3000;
const BTN_OFF = 4000;
function describeButtonGesture(gesture) {
switch (gesture) {
case BTN_initial_press:
return "Initial press";
case BTN_repeat:
return "Repeat";
case BTN_short_release:
return "Short release";
case BTN_long_release:
return "Long release";
default:
return "Unknown";
}
}
function describeButtonItself(gesture) {
switch (gesture) {
case BTN_ON:
return "On";
case BTN_STAR_UP:
return "Big star";
case BTN_STAR_DOWN:
return "Little star";
case BTN_OFF:
return "Off";
default:
return "Unknown";
}
}
function describeButton(value) {
let button;
if (value >= BTN_OFF) {
button = BTN_OFF;
} else if (value >= BTN_STAR_DOWN) {
button = BTN_STAR_DOWN;
} else if (value >= BTN_STAR_UP) {
button = BTN_STAR_UP;
} else if (value >= BTN_ON) {
button = BTN_ON;
} else {
return { button: "Unknown", gesture: "Unknown" };
}
const gesture = value - button;
return { button: describeButtonItself(button), gesture: describeButtonGesture(gesture) };
}
// Power Managed Zone constants
const PMZ_OFF = 0;
const PMZ_LOW_POWER = 1;
const PMZ_FULL_POWER = 2;
const PMZ_DISABLED = 0;
const PMZ_ENABLED = 1;
const ACTION_BASE = 0;
// Scene Cycle constants
const SC_OFF = ACTION_BASE + PMZ_OFF; // Turn off the lights
const SC_LOW_POWER = ACTION_BASE + PMZ_LOW_POWER; // Activate the low power version of the current scene
const SC_FULL_POWER = ACTION_BASE + PMZ_FULL_POWER; // Activate the full power version of the current scene
const SC_BRIGHTER = SC_FULL_POWER + 1; // Make the scene brighter
const SC_DIMMER = SC_FULL_POWER + 2; // Make the scene dimmer
const SC_ACTIVATE = SC_FULL_POWER + 3; // Activate the appropriate version of the current scene for the zone's power state
const SC_NEXT = SC_FULL_POWER + 4; // Move to the next scene and activate it
// Motion sensor constants
const PMM_DO_NOTHING = 0;
const PMM_KEEP_ON = 1;
const PMM_TURN_ON = 2;
const PMM_ACTIVATE = 2000 + 100; // Activate according to the motion sensor activation setting
// Sleeping 11PM-7AM, Waking 7AM-8AM, Working 8AM-4PM, Relaxing 4PM-11PM
// A power managed zone is:
// 0. Config: Low power after period A
// 0. Config: Turn off after further period B
// 1. A ClipGenericStatus sensor that represents on(2)/lowpower(1)/off(0)
// 2. A rule: status == on(2) and lastupdate ddx A, change status to lowpower(1)
// 3. A rule: status == lowpower(1) and status ddx B, change status to off(0)
// 4. A ClipGenericFlag sensor to represent enabled state of power management
// Keep light in current state and ignore timer by setting flag to false
// Turn light on (or keep it on & reset timer) by setting status to on(2)
// Go to power saving (but not reset timer if already power-saving) by setting status to lowpower(1)
// Turn light off by setting status to off(0)
// For changes:
// A rule: status == on(2) to change light state
// A rule: status == lowpower(1) to change light state
// A rule: status == off(0) to change light state
// Low power state is useful as a visual aid even if only interested in turning off because it gives users a chance to boost power again.
// To use with a motion sensor or switch:
// A. Motion or switch turns zone on, zone turns itself off
// B. Switch can also turn zone to lowpower or off
// To use with motion sensor & override switch:
// A. Motion turns zone on
// B. Switch turns zone on and disables power management
// C. Switch turns zone off and enables power management
// How to deal with different timeouts like 1 min day & 5 mins night?
// A shared resource is:
// 1. A ClipGenericStatus sensor which represents the number of users
// 2. A ClipGenericFlag sensor that can be used to trigger an increment of the user count
// 3. A ClipGenericFlag sensor that can be used to trigger a decrement of the user count
// 4. N rules that increment/decrement the user count in response to the triggers (where N is the maximum number of users).
// 5. N ClipGenericFlag sensors: one for each potential user indicating whether they are using the resource or not
// 6. 2N rules that fire the triggers to update the user count on the shared resource (2 rules for each user sensor: one to increment the shared count, one to decrement it)
// 7. A ClipGenericFlag sensor that can be used as an override to switch all the user sensors off or on
// There are so many rules because the Hue hub does not have an action for incrementing or decrementing an integer. The triggers are here so that the rules only need to be implemented once (and not once for each user; with the triggers we have N + 2N rules; without the triggers we'd have 2N^2 rules; if increment was implemented natively, we'd have 2N rules)
// An example of a shared resource is lighting in a hallway
// You want the lights in the hallway to remain on while there is anyone using or intending to use the hallway and you want the lights to turn off when there's no one using it
// You achieve this by removing the ability to directly turn on and turn off lights in the hallway from users and instead give them the ability to say that they are using or not using the hallway. Rules turn on the lights when the hallway is in use and turn off the lights when it's no longer in use.
// This gets rid of any confusion around motion detection and multiple users
// The motion detector is just another user who can let the hallway know it's being used, but is not responsible for turning lights off
export async function send(method, address, body) {
if (typeof body !== "string") {
body = JSON.stringify(body, null, " ");
}
let bridgeResult;
try {
bridgeResult = await fetchJSON(address, { method, body });
} catch (e) {
console.log(body);
console.log(e);
throw { body, e };
}
if (Array.isArray(bridgeResult) && (bridgeResult.length >= 1) && bridgeResult[0].success) {
return bridgeResult;
}
console.log(body);
console.log(bridgeResult);
throw { body, bridgeResult };
}
export async function put(address, body) {
return send("PUT", address, body);
}
export async function create(address, body) {
const bridgeResult = await send("POST", address, body);
return bridgeResult[0].success.id;
}
export function Address(connection, suffix) {
return `https://${connection.bridge.ip}/api/${connection.token}/` + suffix;
}
export async function createSensor(connection, body) {
const address = Address(connection, `sensors`);
return create(address, body);
}
export async function setSensorValue(connection, id, value) {
const store = (typeof value === "boolean") ? "flag" : "status";
const address = Address(connection, `sensors/${id}/state`);
const body = `{ "${store}": ${value} }`;
return put(address, body);
}
export async function setSensorName(connection, id, value) {
const address = Address(connection, `sensors/${id}`);
const body = JSON.stringify({ "name": value });
return put(address, body);
}
export async function setItemName(connection, kind, id, value) {
const address = Address(connection, `${kind}/${id}`);
const body = JSON.stringify({ "name": value });
return put(address, body);
}
// buttonevent is not modifiable
// export async function setSensorButtonEvent(connection, id, value) {
// const store = "buttonevent";
// const address = Address(connection, `sensors/${id}/state`);
// const body = `{ "${store}": ${value} }`;
// return put(address, body);
// }
export async function setLightOn(connection, id, value) {
const address = Address(connection, `lights/${id}/state`);
const body = { on: value };
return put(address, body);
}
export async function setLightCT(connection, id, value) {
const address = Address(connection, `lights/${id}/state`);
const body = { ct: value };
return put(address, body);
}
export async function setGroupOn(connection, id, value) {
const address = Address(connection, `groups/${id}/action`);
const body = { on: value };
return put(address, body);
}
export async function setGroupBrightness(connection, id, value, extras) {
const address = Address(connection, `groups/${id}/action`);
const body = extras ? { bri: value, ...extras } : { bri: value };
return put(address, body);
}
export async function setGroupCT(connection, id, value) {
const address = Address(connection, `groups/${id}/action`);
const body = { ct: value };
return put(address, body);
}
export async function setGroupScene(connection, id, sceneID) {
const address = Address(connection, `groups/${id}/action`);
const body = { scene: sceneID };
return put(address, body);
}
export async function setRuleActions(connection, id, actions) {
const address = Address(connection, `rules/${id}`);
const body = { actions };
return put(address, body);
}
export async function createSchedule(connection, body) {
const address = Address(connection, `schedules`);
return create(address, body);
}
export async function createRule(connection, body) {
const address = Address(connection, `rules`);
return create(address, body);
}
export async function createResourceLink(connection, body) {
const address = Address(connection, `resourcelinks`);
return create(address, body);
}
export async function deleteRule(connection, id) {
const address = Address(connection, `rules/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function deleteResourceLink(connection, id) {
const address = Address(connection, `resourcelinks/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function deleteSensor(connection, id) {
const address = Address(connection, `sensors/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function deleteSchedule(connection, id) {
const address = Address(connection, `schedules/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function deleteGroup(connection, id) {
const address = Address(connection, `groups/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function deleteScene(connection, id) {
const address = Address(connection, `scenes/${id}`);
const method = "DELETE";
return fetchJSON(address, { method });
}
export async function getCategory(connection, category) {
const address = Address(connection, `${category}`);
let bridgeResult;
try {
bridgeResult = await fetchJSON(address);
} catch (e) {
console.log(e);
throw { address, e };
}
return bridgeResult;
}
class Cache {
constructor(name) {
this.name = name;
// Must be https for the cache API to work
this.root = "https://callionica.com";
}
async cache() {
if (this.cache_ === undefined) {
this.cache_ = await caches.open(this.name);
}
return this.cache_;
}
async setItem(key, value) {
const cache = await this.cache();
const k = new URL(key, this.root);
const v = { stored: new Date().toISOString(), value };
const response = new Response(JSON.stringify(v));
return await cache.put(k, response);
}
async getItem(key) {
const cache = await this.cache();
const k = new URL(key, this.root);
const result = await cache.match(k) ?? undefined;
if (result === undefined) {
return result;
}
const o = await result.json();
o.stored = new Date(o.stored);
return o;
}
async removeItem(key) {
const cache = await this.cache();
const k = new URL(key, this.root);
await cache.delete(k);
}
}
const CACHE_NAME = "hue-callionica";
const cache = new Cache(CACHE_NAME);
export async function getAllCategories(connection, maximumCacheAgeMS = 0) {
// Cache here because we still have non-cyclic data that can be stringified
const key = `${connection.bridge.id}`;
if (maximumCacheAgeMS > 0) {
const o = await cache.getItem(key);
if (o !== undefined) {
const now = new Date();
const milliseconds = now - o.stored;
if (milliseconds < maximumCacheAgeMS) {
return o.value;
}
}
}
const result = await getCategory(connection, "");
// await here so that the caller doesn't change our data before we save it
await cache.setItem(key, result);
return result;
}
export async function getConfig(connection) {
return getCategory(connection, "config");
}
export async function getCapabilities(connection) {
return getCategory(connection, "capabilities");
}
// More useful to have an array of objects
export async function getCategory_(connection, category) {
return Object.entries(await getCategory(connection, category)).map(([id, value]) => { return { id, ...value }; });
}
export async function getRules(connection) {
return getCategory_(connection, "rules");
}
export async function getSchedules(connection) {
return getCategory_(connection, "schedules");
}
export async function getAppSchedules(connection) {
return (await getSchedules(connection)).filter(schedule => schedule.command.address.startsWith(`/api/${connection.app}/`));
}
export async function getGroups(connection) {
return getCategory_(connection, "groups");
}
export async function getScenes(connection) {
return getCategory_(connection, "scenes");
}
const bridgeSceneCache = {};
export async function getSceneComplete(connection, sceneID, lastUpdated) {
const bridgeID = connection.bridge.id;
let sceneCache = bridgeSceneCache[bridgeID];
if (sceneCache === undefined) {
sceneCache = {};
bridgeSceneCache[bridgeID] = sceneCache;
}
let scene = sceneCache[sceneID];
if ((scene !== undefined) && (scene.lastupdated === lastUpdated)) {
return scene;
}
const key = `{bridge:"${bridgeID}",scene:"${sceneID}"}`;
const s = sessionStorage.getItem(key) || localStorage.getItem(key) || undefined;
if (s !== undefined) {
scene = JSON.parse(s);
if (scene.lastupdated === lastUpdated) {
sceneCache[sceneID] = scene;
return scene;
}
}
scene = await getCategory(connection, `scenes/${sceneID}`);
sceneCache[sceneID] = scene;
const storableValue = JSON.stringify(scene, null, 2);
sessionStorage.setItem(key, storableValue);
function storedSceneCount(storage, bridgeID) {
return Object.entries(storage).filter(([name, value]) => name.startsWith(`{bridge:"${bridgeID}",scene:`)).length;
}
// Store some scenes for each bridge to localStorage for performance
const maxStoredScenes = 200;
if (localStorage.getItem(key) || storedSceneCount(localStorage, bridgeID) < maxStoredScenes) {
localStorage.setItem(key, storableValue);
}
return scene;
}
export async function getScene(connection, groupID, name) {
console.log(name);
const scenes = await getScenes(connection);
const result = scenes.filter(scene => scene.group === groupID && scene.name === name)[0].id;
return result;
}
export async function getResourceLinks(connection) {
return getCategory_(connection, "resourcelinks");
}
export async function getSensors(connection) {
return getCategory_(connection, "sensors");
}
export async function getLights(connection) {
return getCategory_(connection, "lights");
}
export async function getDimmers(connection) {
const sensors = await getSensors(connection);
return sensors.filter(sensor => sensor.productname === "Hue dimmer switch");
}
export async function getMotionSensors(connection) {
const sensors = await getSensors(connection);
return sensors.filter(sensor => sensor.productname === "Hue motion sensor");
}
export async function touchlink(connection) {
const address = Address(connection, `config/`);
const body = `{"touchlink": true}`;
return put(address, body);
}
export async function deleteAppRules(connection) {
const rules = await getRules(connection);
for (const rule of rules) {
if (rule.owner === connection.app) {
await deleteRule(connection, rule.id);
}
}
}
export async function deleteDescriptionSchedules(connection, description) {
const schedules = await getSchedules(connection);
for (const schedule of schedules) {
if (schedule.description === description) {
await deleteSchedule(connection, schedule.id);
}
}
}
export async function deleteAppSchedules(connection) {
const schedules = await getAppSchedules(connection);
for (const schedule of schedules) {
await deleteSchedule(connection, schedule.id);
}
}
export async function deleteManufacturerSensors(connection, manufacturer) {
const sensors = await getSensors(connection);
for (const sensor of sensors) {
if (sensor.manufacturername === manufacturer) {
await deleteSensor(connection, sensor.id);
}
}
}
export async function deleteAppSensors(connection) {
return deleteManufacturerSensors(connection, connection.app);
}
export async function deleteAppLinks(connection) {
const links = await getResourceLinks(connection);
for (const link of links) {
if (link.owner === connection.app) {
await deleteResourceLink(connection, link.id);
}
}
}
// export async function registerApp(hub, appName, user) {
// user = user || "";
// const address = `https://${hub}/api/`;
// const body = `{"devicetype": "${appName}#${user}"}`;
// const method = "POST";
// let bridgeResult = await send(method, address, body);
// return { hub, app: bridgeResult[0].success.username };
// }
// export async function connect(hub, appName) {
// const key = "hue-connection:" + hub;
// const json = localStorage.getItem(key);
// let connection;
// if (json) {
// connection = JSON.parse(json);
// if (connection && connection.hub === hub) {
// return connection;
// }
// }
// connection = await registerApp(hub, appName);
// localStorage.setItem(key, JSON.stringify(connection));
// return connection;
// }
// =============================
function statusSensorBody(name, model, value) {
value = value || 0;
const body = `{
"name": "${name}",
"state": {
"status": ${value}
},
"config": {
"on": true,
"reachable": true
},
"type": "CLIPGenericStatus",
"modelid": "${model}",
"manufacturername": "Callionica",
"swversion": "1.0",
"uniqueid": "${uuid()}",
"recycle": false
}`;
return body;
}
function flagSensorBody(name, model, value) {
const body = `{
"name": "${name}",
"state": {
"flag": ${value}
},
"config": {
"on": true,
"reachable": true
},
"type": "CLIPGenericFlag",
"modelid": "${model}",
"manufacturername": "Callionica",
"swversion": "1.0",
"uniqueid": "${uuid()}",
"recycle": false
}`;
return body;
}
function isPresent(id) {
return `{
"address": "/sensors/${id}/state/presence",
"operator": "eq",
"value": "true"
}`;
}
function isEqual(id, value) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `{
"address": "/sensors/${id}/state/${store}",
"operator": "eq",
"value": "${value}"
}`;
}
function isChanged(id, store) {
return `{
"address": "/sensors/${id}/state/${store}",
"operator": "dx"
}`;
}
function isUpdated(id) {
return `{
"address": "/sensors/${id}/state/lastupdated",
"operator": "dx"
}`;
}
function isChangedTo(id, value) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `${isEqual(id, value)},
${isChanged(id, store)}`;
}
function isUpdatedTo(id, value) {
return `${isEqual(id, value)},
${isUpdated(id)}`;
}
function wasChangedTo(id, value, hms) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `${isEqual(id, value)},
{
"address": "/sensors/${id}/state/${store}",
"operator": "ddx",
"value": "PT${hms}"
}`;
}
function wasUpdatedTo(id, value, hms) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `${isEqual(id, value)},
{
"address": "/sensors/${id}/state/lastupdated",
"operator": "ddx",
"value": "PT${hms}"
}`;
}
function notUpdatedSince(id, value, hms) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `${isEqual(id, value)},
{
"address": "/sensors/${id}/state/lastupdated",
"operator": "stable",
"value": "PT${hms}"
}`;
}
function notChangedSince(id, value, hms) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `${isEqual(id, value)},
{
"address": "/sensors/${id}/state/${store}",
"operator": "stable",
"value": "PT${hms}"
}`;
}
function isButton(id, value) {
return `{
"address": "/sensors/${id}/state/buttonevent",
"operator": "eq",
"value": "${value}"
},
${isUpdated(id)}`;
}
function setValue(id, value) {
const store = (typeof value === "boolean") ? "flag" : "status";
return `{
"address": "/sensors/${id}/state",
"method": "PUT",
"body": {
"${store}": ${value}
}
}`;
}
// function setButton(id, value) {
// return `{
// "address": "/sensors/${id}/state",
// "method": "PUT",
// "body": {
// "buttonevent": ${value}
// }
// }`;
// }
function setScene(groupID, sceneID) {
return `{
"address": "/groups/${groupID}/action",
"method": "PUT",
"body": {
"scene": "${sceneID}"
}
}`;
}
// =============================
// export async function createUserCount(connection, resourceName, userNames) {
// const hub = connection.hub;
// const app = connection.app;
// const maximumUserCount = userNames.length;
// async function createTriggerRule(countID, triggerID, oldValue, newValue) {
// const body = `{
// "name": "(${resourceName}${oldValue > newValue ? "-" : "+"})",
// "conditions": [
// ${isUpdated(triggerID)},
// ${isEqual(countID, oldValue)}
// ],
// "actions": [
// ${setValue(countID, newValue)}
// ]
// }`;
// return createRule(connection, body);
// }
// async function createTriggerSensor(countID, value) {
// const id = await createFlagSensor(connection, `${resourceName}${value > 0 ? "+" : "-"}`, "(User Count Trigger)", false);
// const rules = [];
// for (var i = 0; i < maximumUserCount; ++i) {
// const oldValue = (value > 0) ? i : i - value;
// const newValue = oldValue + value;
// const ruleID = await createTriggerRule(countID, id, oldValue, newValue);
// rules.push(ruleID);
// }
// return { id, rules };
// }
// async function createUserCountSensor() {
// return createStatusSensor(connection, resourceName, "User Count");
// }
// async function createUserRule(userID, userName, value, triggerID) {
// const body = `{
// "name": "(${userName})",
// "conditions": [
// ${isEqual(userID, value)}
// ],
// "actions": [
// ${setValue(triggerID, true)}
// ]
// }`;
// return createRule(connection, body);
// }
// async function createUserSensor(userName, increment, decrement) {
// const id = await createFlagSensor(connection, userName, "User Count User", false);
// const inc = await createUserRule(id, userName, true, increment.id);
// const dec = await createUserRule(id, userName, false, decrement.id);
// const rules = [inc, dec];
// return { id, name: userName, rules };
// }
// async function createOverrideRule(triggerID, users, value) {
// const actions = users.map(user => setValue(user.id, value)).join(",\n");
// const body = `{
// "name": "(${resourceName} Override)",
// "conditions": [
// ${isUpdatedTo(triggerID, value)}
// ],
// "actions": [
// ${actions}
// ]
// }`;
// return createRule(connection, body);
// }
// async function createOverrideSensor(users) {
// const id = await createFlagSensor(connection, `${resourceName} Override`, "User Count Override", false);
// const rules = [
// await createOverrideRule(id, users, false),
// await createOverrideRule(id, users, true)
// ];
// return { id, rules };
// }
// const id = await createUserCountSensor();
// const increment = await createTriggerSensor(id, +1);
// const decrement = await createTriggerSensor(id, -1);
// const users = [];
// for (const userName of userNames) {
// const user = await createUserSensor(userName, increment, decrement);
// users.push(user);
// }
// const override = await createOverrideSensor(users);
// return { id, name: resourceName, triggers: [increment, decrement], users, override };
// }
// export async function deleteUserCount(connection, uc) {
// for (const rule of uc.override.rules) {
// await deleteRule(connection, rule);
// }
// await deleteSensor(connection, uc.override.id);
// for (const user of uc.users) {
// for (const rule of user.rules) {
// await deleteRule(connection, rule);
// }
// await deleteSensor(connection, user.id);
// }
// for (const trigger of uc.triggers) {
// for (const rule of trigger.rules) {
// await deleteRule(connection, rule);
// }
// await deleteSensor(connection, trigger.id);
// }
// await deleteSensor(connection, uc.id);
// }
// =============================
export async function createStatusSensor(connection, name, model, value) {
const body = statusSensorBody(name, model, value)
return createSensor(connection, body);
}
export async function createFlagSensor(connection, name, model, value) {
const body = flagSensorBody(name, model, value)
return createSensor(connection, body);
}
export async function createLinks(connection, name, description, links) {
const body = `{
"name": "${name}",
"description": "${description}",
"classid": ${COMPONENT_CLASSID},
"links": [