-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHomebridge Status.js
1045 lines (941 loc) · 30.1 KB
/
Homebridge Status.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
let configurationFileName = "<INSERT CONFIG FILE NAME>";
const usePersistedConfiguration = true;
const overwritePersistedConfig = true;
const CONFIGURATION_JSON_VERSION = 3;
// Begin configuration setup
class Configuration {
hbServiceMachineBaseUrl = "<INSERT HOSTNAME AND PORT";
userName = "<INSERT HOMEBRIDGE USERNAME>";
password = "<INSERT HOMEBRIDGE PASSWORD";
notificationEnabled = true;
notificationIntervalInDays = 1;
disableStateBackToNormalNotifications = true;
requestTimeoutInterval = 15;
chartColor_dark = "#FFFFFF";
fontColor_dark = "#FFFFFF";
failIcon = "❌";
bulletPointIcon = "▫️";
decimalChar = ".";
jsonVersion = CONFIGURATION_JSON_VERSION;
logoUrl = "https://raw.githubusercontent.com/homebridge/branding/latest/logos/homebridge-silhouette-round-white.png";
// Icons:
icon_statusGood = "checkmark.circle.fill";
icon_colorGood = "#" + Color.green().hex;
icon_statusBad = "exclamationmark.triangle.fill";
icon_colorBad = "#" + Color.red().hex;
icon_statusUnknown = "questionmark.circle.fill";
icon_colorUnknown = "#" + Color.yellow().hex;
// Internationalization:
status_hbRunning = "Running";
status_hbUtd = "UTD";
status_pluginsUtd = "Plugins UTD ";
status_nodejsUtd = "Node.js UTD ";
spacer_beforeFirstStatusColumn = 8;
spacer_betweenStatusColumns = 5;
spacer_afterSecondColumn = 0;
title_cpuLoad = "CPU Load: ";
title_cpuTemp = "CPU Temp: ";
title_ramUsage = "RAM Usage: ";
title_uptimes = "Uptimes:";
title_uiService = "UI-Service: ";
title_systemGuiName = "Raspberry Pi: ";
notification_title = "Homebridge Status changed:";
notification_expandedButtonText = "Details";
notification_ringTone = "event";
notifyText_hbNotRunning = "Your Homebridge instance stopped";
notifyText_hbNotUtd = "Update available for Homebridge";
notifyText_pluginsNotUtd = "Update available for one of your Plugins";
notifyText_nodejsNotUtd = "Update available for Node.js";
notifyText_hbNotRunning_backNormal =
"Your Homebridge instance is back online";
notifyText_hbNotUtd_backNormal = "Homebridge is now up to date";
notifyText_pluginsNotUtd_backNormal = "Plugins are now up to date";
notifyText_nodejsNotUtd_backNormal = "Node.js is now up to date";
error_noConnectionText =
" " +
this.failIcon +
" UI-Service not reachable!\n " +
this.bulletPointIcon +
" Server started?\n " +
this.bulletPointIcon +
" UI-Service process started?\n " +
this.bulletPointIcon +
" Server-URL " +
this.hbServiceMachineBaseUrl +
" correct?\n " +
this.bulletPointIcon +
" Are you in the same network?";
widgetTitle = " Homebridge ";
dateFormat = "MM-dd-yyyy HH:mm:ss";
hbLogoFileName = Device.model() + "hbLogo.png";
headerFontSize = 12;
informationFontSize = 10;
chartAxisFontSize = 7;
dateFontSize = 7;
notificationJsonFileName = "notificationState.json";
}
// End of configuration setup
let CONFIGURATION = new Configuration();
const noAuthUrl = () =>
CONFIGURATION.hbServiceMachineBaseUrl + "/api/auth/noauth";
const authUrl = () => CONFIGURATION.hbServiceMachineBaseUrl + "/api/auth/login";
const cpuUrl = () => CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/cpu";
const overallStatusUrl = () =>
CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/homebridge";
const ramUrl = () => CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/ram";
const uptimeUrl = () =>
CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/uptime";
const pluginsUrl = () => CONFIGURATION.hbServiceMachineBaseUrl + "/api/plugins";
const hbVersionUrl = () =>
CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/homebridge-version";
const nodeJsUrl = () =>
CONFIGURATION.hbServiceMachineBaseUrl + "/api/status/nodejs";
const timeFormatter = new DateFormatter();
const maxLineWidth = 300;
const normalLineHeight = 35;
let headerFont, infoFont, chartAxisFont, updatedAtFont, token, fileManager;
let infoPanelFont = Font.semiboldMonospacedSystemFont(10);
let iconSize = 13;
let verticalSpacerInfoPanel = 5;
const purpleBgGradient_light = createLinearGradient("#421367", "#481367");
const purpleBgGradient_dark = createLinearGradient("#250b3b", "#320d47");
const blackBgGradient_light = createLinearGradient("#707070", "#3d3d3d");
const blackBgGradient_dark = createLinearGradient("#111111", "#222222");
const UNAVAILABLE = "UNAVAILABLE";
const NOTIFICATION_JSON_VERSION = 1;
const INITIAL_NOTIFICATION_STATE = {
jsonVersion: NOTIFICATION_JSON_VERSION,
hbRunning: { status: true },
hbUtd: { status: true },
pluginsUtd: { status: true },
nodeUtd: { status: true },
};
class LineChart {
constructor(width, height, values) {
this.ctx = new DrawContext();
this.ctx.size = new Size(width, height);
this.values = values;
}
_calculatePath() {
let maxValue = Math.max(...this.values);
let minValue = Math.min(...this.values);
let difference = maxValue - minValue;
let count = this.values.length;
let step = this.ctx.size.width / (count - 1);
let points = this.values.map((current, index, all) => {
let x = step * index;
let y =
this.ctx.size.height -
((current - minValue) / difference) * this.ctx.size.height;
return new Point(x, y);
});
return this._getSmoothPath(points);
}
_getSmoothPath(points) {
let path = new Path();
path.move(new Point(0, this.ctx.size.height));
path.addLine(points[0]);
for (let i = 0; i < points.length - 1; i++) {
let xAvg = (points[i].x + points[i + 1].x) / 2;
let yAvg = (points[i].y + points[i + 1].y) / 2;
let avg = new Point(xAvg, yAvg);
let cp1 = new Point((xAvg + points[i].x) / 2, points[i].y);
let next = new Point(points[i + 1].x, points[i + 1].y);
let cp2 = new Point((xAvg + points[i + 1].x) / 2, points[i + 1].y);
path.addQuadCurve(avg, cp1);
path.addQuadCurve(next, cp2);
}
path.addLine(new Point(this.ctx.size.width, this.ctx.size.height));
path.closeSubpath();
return path;
}
configure(fn) {
let path = this._calculatePath();
if (fn) {
fn(this.ctx, path);
} else {
this.ctx.addPath(path);
this.ctx.fillPath(path);
}
return this.ctx;
}
}
class HomeBridgeStatus {
overallStatus;
hbVersionInfos;
hbUpToDate;
pluginVersionInfos;
pluginsUpToDate;
nodeJsVersionInfos;
nodeJsUpToDate;
constructor() {}
async initialize() {
this.overallStatus = await getOverallStatus();
this.hbVersionInfos = await getHomebridgeVersionInfos();
this.hbUpToDate =
this.hbVersionInfos === undefined
? undefined
: !this.hbVersionInfos.updateAvailable;
this.pluginVersionInfos = await getPluginVersionInfos();
this.pluginsUpToDate =
this.pluginVersionInfos === undefined
? undefined
: !this.pluginVersionInfos.updateAvailable;
this.nodeJsVersionInfos = await getNodeJsVersionInfos();
this.nodeJsUpToDate =
this.nodeJsVersionInfos === undefined
? undefined
: !this.nodeJsVersionInfos.updateAvailable;
return this;
}
}
// Begin widget creation
await initializeFileManager_Configuration_TimeFormatter_Fonts_AndToken();
if (token === UNAVAILABLE) {
await showNotAvailableWidget();
return;
}
const homeBridgeStatus = await new HomeBridgeStatus().initialize();
await handleNotifications(
homeBridgeStatus.overallStatus,
homeBridgeStatus.hbUpToDate,
homeBridgeStatus.pluginsUpToDate,
homeBridgeStatus.nodeJsUpToDate
);
await createAndShowWidget(homeBridgeStatus);
return;
// End of widget creation
async function initializeFileManager_Configuration_TimeFormatter_Fonts_AndToken() {
fileManager =
CONFIGURATION.fileManagerMode === "LOCAL"
? FileManager.local()
: FileManager.iCloud();
if (args.widgetParameter) {
if (args.widgetParameter.length > 0) {
let foundCredentialsInParameter = useCredentialsFromWidgetParameter(
args.widgetParameter
);
let fileNameSuccessfullySet = false;
if (!foundCredentialsInParameter) {
fileNameSuccessfullySet = checkIfConfigFileParameterIsProvided(
args.widgetParameter
);
}
if (!foundCredentialsInParameter && !fileNameSuccessfullySet) {
throw "Format of provided parameter not valid\n2 Valid examples: 1. USE_CONFIG:yourfilename.json\n2. admin,,mypassword123,,http://192.168.178.33:8581";
}
}
}
if (usePersistedConfiguration && !overwritePersistedConfig) {
CONFIGURATION = await getPersistedObject(
getFilePath(configurationFileName),
CONFIGURATION_JSON_VERSION,
CONFIGURATION,
false
);
log(
"Configuration " +
configurationFileName +
" is used! Trying to authenticate..."
);
}
timeFormatter.dateFormat = CONFIGURATION.dateFormat;
initializeFonts();
await initializeToken();
}
async function createAndShowWidget(homeBridgeStatus) {
let widget = new ListWidget();
handleSettingOfBackgroundColor(widget);
if (!config.runsWithSiri) {
await buildUsualGui(widget, homeBridgeStatus);
} else if (config.runsWithSiri) {
await buildSiriGui(widget, homeBridgeStatus);
}
finalizeAndShowWidget(widget);
}
function buildStatusPanelInHeader(titleStack, homeBridgeStatus) {
titleStack.addSpacer(CONFIGURATION.spacer_beforeFirstStatusColumn);
let statusInfo = titleStack.addStack();
let firstColumn = statusInfo.addStack();
firstColumn.layoutVertically();
addStatusInfo(
firstColumn,
homeBridgeStatus.overallStatus,
CONFIGURATION.status_hbRunning
);
firstColumn.addSpacer(verticalSpacerInfoPanel);
addStatusInfo(
firstColumn,
homeBridgeStatus.pluginsUpToDate,
CONFIGURATION.status_pluginsUtd
);
statusInfo.addSpacer(CONFIGURATION.spacer_betweenStatusColumns);
let secondColumn = statusInfo.addStack();
secondColumn.layoutVertically();
addStatusInfo(
secondColumn,
homeBridgeStatus.hbUpToDate,
CONFIGURATION.status_hbUtd
);
secondColumn.addSpacer(verticalSpacerInfoPanel);
addStatusInfo(
secondColumn,
homeBridgeStatus.nodeJsUpToDate,
CONFIGURATION.status_nodejsUtd
);
titleStack.addSpacer(CONFIGURATION.spacer_afterSecondColumn);
}
async function showNotAvailableWidget() {
if (!config.runsInAccessoryWidget) {
let widget = new ListWidget();
handleSettingOfBackgroundColor(widget);
let mainStack = widget.addStack();
await initializeLogoAndHeader(mainStack);
addNotAvailableInfos(widget, mainStack);
finalizeAndShowWidget(widget);
} else {
let widget = new ListWidget();
handleSettingOfBackgroundColor(widget);
widget.addSpacer(2);
addStyledText(
widget,
updatedAtFont
);
await widget.presentSmall();
Script.setWidget(widget);
Script.complete();
}
}
async function finalizeAndShowWidget(widget) {
if (!config.runsInWidget) {
await widget.presentMedium();
}
Script.setWidget(widget);
Script.complete();
}
async function initializeToken() {
token = await getAuthToken();
if (token === undefined) {
throw "Credentials not valid";
}
}
async function initializeLogoAndHeader(titleStack) {
titleStack.size = new Size(maxLineWidth, normalLineHeight);
const logo = await getHbLogo();
const imgWidget = titleStack.addImage(logo);
imgWidget.imageSize = new Size(40, 30);
let headerText = addStyledText(
titleStack,
CONFIGURATION.widgetTitle,
headerFont
);
headerText.size = new Size(60, normalLineHeight);
}
function initializeFonts() {
headerFont = Font.boldMonospacedSystemFont(CONFIGURATION.headerFontSize);
infoFont = Font.systemFont(CONFIGURATION.informationFontSize);
chartAxisFont = Font.systemFont(CONFIGURATION.chartAxisFontSize);
updatedAtFont = Font.systemFont(CONFIGURATION.dateFontSize);
}
async function buildUsualGui(widget, homeBridgeStatus) {
widget.addSpacer(10);
let titleStack = widget.addStack();
await initializeLogoAndHeader(titleStack);
buildStatusPanelInHeader(titleStack, homeBridgeStatus);
widget.addSpacer(10);
let cpuData = await fetchData(cpuUrl());
let ramData = await fetchData(ramUrl());
let usedRamText = getUsedRamString(ramData);
let uptimesArray = await getUptimesArray();
if (cpuData && ramData) {
let mainColumns = widget.addStack();
mainColumns.size = new Size(maxLineWidth, 77);
mainColumns.addSpacer(4);
let cpuColumn = mainColumns.addStack();
cpuColumn.layoutVertically();
addStyledText(
cpuColumn,
CONFIGURATION.title_cpuLoad +
getAsRoundedString(cpuData.currentLoad, 1) +
"%",
infoFont
);
addChartToWidget(cpuColumn, cpuData.cpuLoadHistory);
cpuColumn.addSpacer(7);
let temperatureString = getTemperatureString(cpuData?.cpuTemperature.main);
if (temperatureString) {
let cpuTempText = addStyledText(
cpuColumn,
CONFIGURATION.title_cpuTemp + temperatureString,
infoFont
);
cpuTempText.size = new Size(150, 30);
setTextColor(cpuTempText);
}
mainColumns.addSpacer(11);
let ramColumn = mainColumns.addStack();
ramColumn.layoutVertically();
addStyledText(
ramColumn,
CONFIGURATION.title_ramUsage + usedRamText + "%",
infoFont
);
addChartToWidget(ramColumn, ramData.memoryUsageHistory);
ramColumn.addSpacer(7);
if (uptimesArray) {
let uptimesStack = ramColumn.addStack();
let upStack = uptimesStack.addStack();
addStyledText(upStack, CONFIGURATION.title_uptimes, infoFont);
let vertPointsStack = upStack.addStack();
vertPointsStack.layoutVertically();
addStyledText(
vertPointsStack,
CONFIGURATION.bulletPointIcon +
CONFIGURATION.title_systemGuiName +
uptimesArray[0],
infoFont
);
addStyledText(
vertPointsStack,
CONFIGURATION.bulletPointIcon +
CONFIGURATION.title_uiService +
uptimesArray[1],
infoFont
);
}
widget.addSpacer(10);
// Display last refresh timestamp
let updatedAt = addStyledText(
widget,
"Last refreshed: " + timeFormatter.string(new Date()),
updatedAtFont
);
updatedAt.centerAlignText();
}
}
function addUpdatableElement(
stackToAdd,
elementTitle,
versionCurrent,
versionLatest
) {
let itemStack = stackToAdd.addStack();
itemStack.addSpacer(17);
addStyledText(itemStack, elementTitle, infoFont);
let vertPointsStack = itemStack.addStack();
vertPointsStack.layoutVertically();
let versionStack = vertPointsStack.addStack();
addStyledText(versionStack, versionCurrent, infoFont);
versionStack.addSpacer(3);
addIcon(
versionStack,
CONFIGURATION.siriGui_icon_version,
new Color(CONFIGURATION.siriGui_icon_version_color)
);
versionStack.addSpacer(3);
addStyledText(versionStack, versionLatest, infoFont);
}
function handleSettingOfBackgroundColor(widget) {
switch (CONFIGURATION.bgColorMode) {
case "CUSTOM":
setGradient(
widget,
createLinearGradient(
CONFIGURATION.customBackgroundColor1_light,
CONFIGURATION.customBackgroundColor2_light
),
createLinearGradient(
CONFIGURATION.customBackgroundColor1_dark,
CONFIGURATION.customBackgroundColor2_dark
)
);
break;
case "BLACK_LIGHT":
case "BLACK_DARK":
setGradient(widget, blackBgGradient_light, blackBgGradient_dark);
break;
case "PURPLE_DARK":
case "PURPLE_LIGHT":
default:
setGradient(widget, purpleBgGradient_light, purpleBgGradient_dark);
}
}
function setGradient(widget, lightOption, darkOption) {
widget.backgroundGradient = darkOption;
}
function getChartColorToUse() {
return new Color(CONFIGURATION.chartColor_dark);
}
function setTextColor(textWidget) {
textWidget.textColor = new Color(CONFIGURATION.fontColor_dark);
}
function createLinearGradient(color1, color2) {
const gradient = new LinearGradient();
gradient.locations = [0, 1];
gradient.colors = [new Color(color1), new Color(color2)];
return gradient;
}
function addStyledText(stackToAddTo, text, font) {
let textHandle = stackToAddTo.addText(text);
textHandle.font = font;
setTextColor(textHandle);
return textHandle;
}
function addChartToWidget(column, chartData) {
let horizontalStack = column.addStack();
horizontalStack.addSpacer(5);
let yAxisLabelsStack = horizontalStack.addStack();
yAxisLabelsStack.layoutVertically();
addStyledText(
yAxisLabelsStack,
getMaxString(chartData, 2) + "%",
chartAxisFont
);
yAxisLabelsStack.addSpacer(6);
addStyledText(
yAxisLabelsStack,
getMinString(chartData, 2) + "%",
chartAxisFont
);
yAxisLabelsStack.addSpacer(6);
horizontalStack.addSpacer(2);
let chartImage = new LineChart(500, 100, chartData)
.configure((ctx, path) => {
ctx.opaque = false;
ctx.setFillColor;
ctx.setFillColor(getChartColorToUse());
ctx.addPath(path);
ctx.fillPath(path);
})
.getImage();
let vertChartImageStack = horizontalStack.addStack();
vertChartImageStack.layoutVertically();
let chartImageHandle = vertChartImageStack.addImage(chartImage);
chartImageHandle.imageSize = new Size(100, 25);
let xAxisStack = vertChartImageStack.addStack();
xAxisStack.size = new Size(100, 10);
addStyledText(xAxisStack, "t-10m", chartAxisFont);
xAxisStack.addSpacer(75);
addStyledText(xAxisStack, "t", chartAxisFont);
}
function checkIfConfigFileParameterIsProvided(givenParameter) {
if (
givenParameter.trim().startsWith("USE_CONFIG:") &&
givenParameter.trim().endsWith(".json")
) {
configurationFileName = givenParameter.trim().split("USE_CONFIG:")[1];
if (!fileManager.fileExists(getFilePath(configurationFileName))) {
throw (
"Config file with provided name " +
configurationFileName +
" does not exist!\nCreate it first by running the script once providing the name in variable configurationFileName and maybe with variable overwritePersistedConfig set to true"
);
}
return true;
}
return false;
}
function useCredentialsFromWidgetParameter(givenParameter) {
if (givenParameter.includes(",,")) {
let credentials = givenParameter.split(",,");
if (
credentials.length === 3 &&
credentials[0].length > 0 &&
credentials[1].length > 0 &&
credentials[2].length > 0 &&
credentials[2].startsWith("http")
) {
CONFIGURATION.userName = credentials[0].trim();
CONFIGURATION.password = credentials[1].trim();
CONFIGURATION.hbServiceMachineBaseUrl = credentials[2].trim();
return true;
}
}
return false;
}
async function getAuthToken() {
if (
CONFIGURATION.hbServiceMachineBaseUrl === ">enter the ip with the port <"
) {
throw "Base URL to machine not entered! Edit variable called hbServiceMachineBaseUrl";
}
let req = new Request(noAuthUrl());
req.timeoutInterval = CONFIGURATION.requestTimeoutInterval;
const headers = {
accept: "*/*",
"Content-Type": "application/json",
};
req.method = "POST";
req.headers = headers;
req.body = JSON.stringify({});
let authData;
try {
authData = await req.loadJSON();
} catch (e) {
return UNAVAILABLE;
}
if (authData.access_token) {
// No credentials needed
return authData.access_token;
}
req = new Request(authUrl());
req.timeoutInterval = CONFIGURATION.requestTimeoutInterval;
let body = {
username: CONFIGURATION.userName,
password: CONFIGURATION.password,
otp: "string",
};
req.body = JSON.stringify(body);
req.method = "POST";
req.headers = headers;
try {
authData = await req.loadJSON();
} catch (e) {
return UNAVAILABLE;
}
return authData.access_token;
}
async function fetchData(url) {
let req = new Request(url);
req.timeoutInterval = CONFIGURATION.requestTimeoutInterval;
let headers = {
accept: "*/*",
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
req.headers = headers;
let result;
try {
result = req.loadJSON();
} catch (e) {
return undefined;
}
return result;
}
async function getOverallStatus() {
const statusData = await fetchData(overallStatusUrl());
if (statusData === undefined) {
return undefined;
}
return statusData.status === "up";
}
async function getHomebridgeVersionInfos() {
const hbVersionData = await fetchData(hbVersionUrl());
if (hbVersionData === undefined) {
return undefined;
}
return hbVersionData;
}
async function getNodeJsVersionInfos() {
const nodeJsData = await fetchData(nodeJsUrl());
if (nodeJsData === undefined) {
return undefined;
}
nodeJsData.name = "node.js";
return nodeJsData;
}
async function getPluginVersionInfos() {
const pluginsData = await fetchData(pluginsUrl());
if (pluginsData === undefined) {
return undefined;
}
for (plugin of pluginsData) {
if (plugin.updateAvailable) {
return { plugins: pluginsData, updateAvailable: true };
}
}
return { plugins: pluginsData, updateAvailable: false };
}
function getUsedRamString(ramData) {
if (ramData === undefined) return "unknown";
return getAsRoundedString(
100 - (100 * ramData.mem.available) / ramData.mem.total,
2
);
}
async function getUptimesArray() {
const uptimeData = await fetchData(uptimeUrl());
if (uptimeData === undefined) return undefined;
return [
formatSeconds(uptimeData.time.uptime),
formatSeconds(uptimeData.processUptime),
];
}
function formatSeconds(value) {
if (value > 60 * 60 * 24 * 10) {
return getAsRoundedString(value / 60 / 60 / 24, 0) + "d";
} else if (value > 60 * 60 * 24) {
return getAsRoundedString(value / 60 / 60 / 24, 1) + "d";
} else if (value > 60 * 60) {
return getAsRoundedString(value / 60 / 60, 1) + "h";
} else if (value > 60) {
return getAsRoundedString(value / 60, 1) + "m";
} else {
return getAsRoundedString(value, 1) + "s";
}
}
async function loadImage(imgUrl) {
let req = new Request(imgUrl);
req.timeoutInterval = CONFIGURATION.requestTimeoutInterval;
let image = await req.loadImage();
return image;
}
async function getHbLogo() {
let path = getFilePath(CONFIGURATION.hbLogoFileName);
if (fileManager.fileExists(path)) {
const fileDownloaded = await fileManager.isFileDownloaded(path);
if (!fileDownloaded) {
await fileManager.downloadFileFromiCloud(path);
}
return fileManager.readImage(path);
} else {
const logo = await loadImage(CONFIGURATION.logoUrl);
fileManager.writeImage(path, logo);
return logo;
}
}
function getFilePath(fileName) {
let dirPath = fileManager.joinPath(
fileManager.documentsDirectory(),
"homebridgeStatus"
);
if (!fileManager.fileExists(dirPath)) {
fileManager.createDirectory(dirPath);
}
return fileManager.joinPath(dirPath, fileName);
}
function addNotAvailableInfos(widget, titleStack) {
let statusInfo = titleStack.addText(
" "
);
setTextColor(statusInfo);
statusInfo.size = new Size(150, normalLineHeight);
let errorText = widget.addText(CONFIGURATION.error_noConnectionText);
errorText.size = new Size(410, 130);
errorText.font = infoFont;
setTextColor(errorText);
widget.addSpacer(15);
let updatedAt = widget.addText(
"Last refreshed: " + timeFormatter.string(new Date())
);
updatedAt.font = updatedAtFont;
setTextColor(updatedAt);
updatedAt.centerAlignText();
return widget;
}
function getAsRoundedString(value, decimals) {
let factor = Math.pow(10, decimals);
return (Math.round((value + Number.EPSILON) * factor) / factor)
.toString()
.replace(".", CONFIGURATION.decimalChar);
}
function getMaxString(arrayOfNumbers, decimals) {
let factor = Math.pow(10, decimals);
return (
Math.round((Math.max(...arrayOfNumbers) + Number.EPSILON) * factor) / factor
)
.toString()
.replace(".", CONFIGURATION.decimalChar);
}
function getMinString(arrayOfNumbers, decimals) {
let factor = Math.pow(10, decimals);
return (
Math.round((Math.min(...arrayOfNumbers) + Number.EPSILON) * factor) / factor
)
.toString()
.replace(".", CONFIGURATION.decimalChar);
}
function getTemperatureString(temperatureInCelsius) {
return (
getAsRoundedString(((temperatureInCelsius * 9) / 5 + 32), 1) + "°F"
);
}
function addStatusIcon(widget, statusBool) {
let name = "";
let color;
if (statusBool === undefined) {
name = CONFIGURATION.icon_statusUnknown;
color = new Color(CONFIGURATION.icon_colorUnknown);
} else if (statusBool) {
name = CONFIGURATION.icon_statusGood;
color = new Color(CONFIGURATION.icon_colorGood);
} else {
name = CONFIGURATION.icon_statusBad;
color = new Color(CONFIGURATION.icon_colorBad);
}
addIcon(widget, name, color);
}
function addStatusInfo(lineWidget, statusBool, shownText) {
let itemStack = lineWidget.addStack();
addStatusIcon(itemStack, statusBool);
itemStack.addSpacer(2);
let text = itemStack.addText(shownText);
text.font = infoPanelFont;
setTextColor(text);
}
async function handleNotifications(hbRunning, hbUtd, pluginsUtd, nodeUtd) {
if (!CONFIGURATION.notificationEnabled) {
return;
}
let path = getFilePath(CONFIGURATION.notificationJsonFileName);
let state = await getPersistedObject(
path,
NOTIFICATION_JSON_VERSION,
INITIAL_NOTIFICATION_STATE,
true
);
let now = new Date();
let shouldUpdateState = false;
if (
shouldNotify(
hbRunning,
state.hbRunning.status,
state.hbRunning.lastNotified
)
) {
state.hbRunning.status = hbRunning;
state.hbRunning.lastNotified = now;
shouldUpdateState = true;
scheduleNotification(CONFIGURATION.notifyText_hbNotRunning);
} else if (hbRunning && !state.hbRunning.status) {
state.hbRunning.status = hbRunning;
state.hbRunning.lastNotified = undefined;
shouldUpdateState = true;
if (!CONFIGURATION.disableStateBackToNormalNotifications) {
scheduleNotification(CONFIGURATION.notifyText_hbNotRunning_backNormal);
}
}
if (shouldNotify(hbUtd, state.hbUtd.status, state.hbUtd.lastNotified)) {
state.hbUtd.status = hbUtd;
state.hbUtd.lastNotified = now;
shouldUpdateState = true;
scheduleNotification(CONFIGURATION.notifyText_hbNotUtd);
} else if (hbUtd && !state.hbUtd.status) {
state.hbUtd.status = hbUtd;
state.hbUtd.lastNotified = undefined;
shouldUpdateState = true;
if (!CONFIGURATION.disableStateBackToNormalNotifications) {
scheduleNotification(CONFIGURATION.notifyText_hbNotUtd_backNormal);
}
}
if (
shouldNotify(
pluginsUtd,
state.pluginsUtd.status,
state.pluginsUtd.lastNotified
)
) {
state.pluginsUtd.status = pluginsUtd;
state.pluginsUtd.lastNotified = now;
shouldUpdateState = true;
scheduleNotification(CONFIGURATION.notifyText_pluginsNotUtd);
} else if (pluginsUtd && !state.pluginsUtd.status) {
state.pluginsUtd.status = pluginsUtd;
state.pluginsUtd.lastNotified = undefined;
shouldUpdateState = true;
if (!CONFIGURATION.disableStateBackToNormalNotifications) {
scheduleNotification(CONFIGURATION.notifyText_pluginsNotUtd_backNormal);
}
}
if (shouldNotify(nodeUtd, state.nodeUtd.status, state.nodeUtd.lastNotified)) {
state.nodeUtd.status = nodeUtd;
state.nodeUtd.lastNotified = now;
shouldUpdateState = true;
scheduleNotification(CONFIGURATION.notifyText_nodejsNotUtd);
} else if (nodeUtd && !state.nodeUtd.status) {
state.nodeUtd.status = nodeUtd;
state.nodeUtd.lastNotified = undefined;
shouldUpdateState = true;
if (!CONFIGURATION.disableStateBackToNormalNotifications) {
scheduleNotification(CONFIGURATION.notifyText_nodejsNotUtd_backNormal);
}
}
if (shouldUpdateState) {
persistObject(state, path);
}
}
function shouldNotify(currentBool, boolFromLastTime, lastNotifiedDate) {
return (
!currentBool && (boolFromLastTime || isTimeToNotifyAgain(lastNotifiedDate))
);
}
function isTimeToNotifyAgain(dateToCheck) {
if (dateToCheck === undefined) return true;
let dateInThePast = new Date(dateToCheck);
let now = new Date();
let timeBetweenDates = parseInt(
(now.getTime() - dateInThePast.getTime()) / 1000
); // seconds
return (
timeBetweenDates > CONFIGURATION.notificationIntervalInDays * 24 * 60 * 60
);
}
function scheduleNotification(text) {
let not = new Notification();
not.title = CONFIGURATION.notification_title;
not.body = text;
not.addAction(
CONFIGURATION.notification_expandedButtonText,
CONFIGURATION.hbServiceMachineBaseUrl,
false
);
not.sound = CONFIGURATION.notification_ringTone;
not.schedule();
}
async function getPersistedObject(
path,
versionToCheckAgainst,
initialObjectToPersist,
createIfNotExisting
) {
if (fileManager.fileExists(path)) {
const fileDownloaded = await fileManager.isFileDownloaded(path);
if (!fileDownloaded) {
await fileManager.downloadFileFromiCloud(path);
}
let raw, persistedObject;
try {
raw = fileManager.readString(path);
persistedObject = JSON.parse(raw);