forked from thebearmay/hubitat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hubInfov3Temp.groovy
1484 lines (1349 loc) · 52.7 KB
/
hubInfov3Temp.groovy
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
/*
* Hub Info
*
* Licensed Virtual the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
* Change History:
*
* Date Who What
* ---- --- ----
* 2020-12-07 thebearmay Original version 0.1.0
* ..........
* 2023-01-10 thebearmay version 3 rewrite ** minFwVersion = "2.2.8.141" **
* 2023-01-11 v3.0.1 - Poll 4 error
* 2023-01-12 v3.0.2 - Zigbee status/status2 disagreement handler (happens when radio is shut off without a reboot)
* Turn off Debug Logs after 30 minutes
* Add removeUnused method, command and preference
* v3.0.3 - Add Uptime Descriptor
* 2023-01-13 v3.0.4 - Select format for restart formatted attribute
* v3.0.5 - Missing zigbeeStatus generating warning message
* 2023-01-14 v3.0.6 - Delay baseData() on Initialize to cpature state correctly
* v3.0.7 - hubversion to v2Cleanup,
* FreeMemoryUnit option
* Add Update Check to Initialize if polled
* v3.0.8 - Fix 500 Error on device create
* 2023-01-16 v3.0.9 - Delay initial freeMemory check for 8 seconds
* 2023-01-21 v3.0.10 - lastUpdated conflict, renamed lastPollTime
* 2023-01-23 v3.0.11 - Change formatting date formatting description to match lastPollTime
* 2023-02-01 v3.0.12 - Add a try around the time zone code
* 2023-02-02 v3.0.13 - Add a null character check to time zone formatting
* v3.0.14 - US/Arizona timezone fix
* 2023-02-13 v3.0.15 - check for null SSID when hasWiFi true
* 2023-02-14 v3.0.16 - add connectCapable
* v3.0.17 - Check for html conflict at startup
* 2023-02-23 v3.0.18 - Add html attribute output file option
* 2023-02-27 v3.0.19 - Add 15 minute averages for CPU Load, CPU Percentage, and Free Memory
* 2023-03-09 v3.0.20 - Add cloud connection check
*/
import java.text.SimpleDateFormat
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.Field
@SuppressWarnings('unused')
static String version() {return "3.0.20"}
metadata {
definition (
name: "Hub Information Driver v3",
namespace: "thebearmay",
author: "Jean P. May, Jr.",
importUrl:"https://raw.githubusercontent.com/thebearmay/hubitat/main/hubInfoV3.groovy"
) {
capability "Actuator"
capability "Configuration"
capability "Initialize"
capability "Refresh"
capability "Sensor"
capability "TemperatureMeasurement"
attribute "latitude", "string"
attribute "longitude", "string"
attribute "id", "string"
attribute "name", "string"
attribute "zigbeeId", "string"
attribute "zigbeeEui", "string"
attribute "hardwareID", "string"
attribute "type", "string"
attribute "localIP", "string"
attribute "localSrvPortTCP", "string"
attribute "uptime", "number"
attribute "lastPollTime", "string"
attribute "lastPoll", "string"
attribute "lastHubRestart", "string"
attribute "firmwareVersionString", "string"
attribute "timeZone", "string"
attribute "temperatureScale", "string"
attribute "zipCode", "string"
attribute "locationName", "string"
attribute "locationId", "string"
attribute "lastHubRestartFormatted", "string"
attribute "freeMemory", "number"
attribute "temperatureF", "string"
attribute "temperatureC", "string"
attribute "formattedUptime", "string"
attribute "html", "string"
attribute "cpu5Min", "number"
attribute "cpuPct", "number"
attribute "dbSize", "number"
attribute "publicIP", "string"
attribute "zigbeeChannel","string"
attribute "maxEvtDays", "number"
attribute "maxStateDays", "number"
attribute "zwaveVersion", "string"
attribute "zwaveSDKVersion", "string"
//attribute "zwaveData", "string"
attribute "hubModel", "string"
attribute "hubUpdateStatus", "string"
attribute "hubUpdateVersion", "string"
attribute "currentMode", "string"
attribute "currentHsmMode", "string"
attribute "ntpServer", "string"
attribute "ipSubnetsAllowed", "string"
attribute "zigbeeStatus", "string"
attribute "zigbeeStatus2", "string"
attribute "zigbeeStack", "string"
attribute "zwaveStatus", "string"
attribute "hubAlerts", "string"
attribute "hubMeshData", "string"
attribute "hubMeshCount", "number"
attribute "securityInUse", "string"
attribute "sunrise", "string"
attribute "sunset", "string"
attribute "nextPoll", "string"
//HE v2.3.4.126
attribute "connectType", "string" //Ethernet, WiFi, Dual, Not Connected
attribute "dnsServers", "string"
attribute "staticIPJson", "string"
attribute "lanIPAddr", "string"
attribute "wirelessIP", "string"
attribute "wifiNetwork", "string"
attribute "connectCapable", "string" //Ethernet, WiFi, Dual
attribute "cpu15Min", "number"
attribute "cpu15Pct", "number"
attribute "freeMem15", "number"
attribute "cloud", "string"
command "hiaUpdate", ["string"]
command "reboot"
command "shutdown"
command "updateCheck"
command "removeUnused"
}
}
preferences {
if(state?.errorMinVersion || state?.errorMinVersion == "true")
input("errMsg", "string", title:"<span style='background-color:red;font-weight:bold;color:black;'>Hub does not meet the minimum of HEv$minFwVersion</span>")
input("quickref","string", title:"$ttStyleStr<a href='https://htmlpreview.github.io/?https://github.com/thebearmay/hubitat/blob/main/hubInfoQuickRef3.html' target='_blank'>Quick Reference v${version()}</a>")
input("debugEnable", "bool", title: "Enable debug logging?", width:4)
input("warnSuppress", "bool", title: "Suppress Warn Level Logging", width:4)
prefList.each { l1 ->
l1.each{
pMap = (HashMap) it.value
input ("${it.key}", "enum", title: "<div class='tTip'>${pMap.desc}<span class='tTipText'>${pMap.attributeList}</span></div>", options:pollList, submitOnChange:true, width:4, defaultValue:"0")
}
}
if(parm16 != null && parm16 != 0 && parm16 != "0")
input("makerInfo", "string", title: "MakerApi or Dashboard URL string", submitOnChange: true)
input("remUnused", "bool", title: "Remove unused attributes", defaultValue: false, submitOnChange: true, width:4)
input("attribEnable", "bool", title: "Enable HTML Attribute Creation?", defaultValue: false, required: false, submitOnChange: true, width:4)
input("alternateHtml", "string", title: "Template file for HTML attribute", submitOnChange: true, defaultValue: "hubInfoTemplate.res", width:4)
input("htmlOutput", "string", title: "HTML Attribute Output for > 1024 characters", submitOnChange:true, defaultValue:"hubInfoOutput.html", width:4)
input("forceFileOutput","bool", title:"Always use Output file for HTML Attribute", submitOnChange:true, width:4)
input("attrLogging", "bool", title: "Log all attribute changes", defaultValue: false, submitOnChange: true, width:4)
input("allowReboot","bool", title: "Allow Hub to be shutdown or rebooted", defaultValue: false, submitOnChange: true, width:4)
input("security", "bool", title: "Hub Security Enabled", defaultValue: false, submitOnChange: true, width:4)
if (security) {
input("username", "string", title: "Hub Security Username", required: false, width:4)
input("password", "password", title: "Hub Security Password", required: false, width:4)
}
input("freeMemUnit", "enum", title: "Free Memory Unit", options:["KB","MB"], defaultValue:"KB", width:4)
input("sunSdfPref", "enum", title: "Date/Time Format for Sunrise/Sunset", options:sdfList, defaultValue:"HH:mm:ss", width:4)
input("updSdfPref", "enum", title: "Date/Time Format for Last Poll Time", options:sdfList, defaultValue:"Milliseconds", width:4)
input("rsrtSdfPref", "enum", title: "Date/Time Format for Hub Restart Formatted", options:sdfList, defaultValue:"yyyy-MM-dd HH:mm:ss", width:4)
input("upTimeSep", "string", title: "Separator for Formatted Uptime", defaultValue: ", ", width:4)
input("upTimeDesc", "enum", title: "Uptime Descriptors", defaultValue:"d/h/m/s", options:["d/h/m/s"," days/ hrs/ min/ sec"," days/ hours/ minutes/ seconds"])
input("pollRate1", "number", title: "Poll Rate for Queue 1 in minutes", defaultValue:0, submitOnChange: true, width:4)
input("pollRate2", "number", title: "Poll Rate for Queue 2 in minutes", defaultValue:0, submitOnChange: true, width:4)
input("pollRate3", "number", title: "Poll Rate for Queue 3 in minutes", defaultValue:0, submitOnChange: true, width:4)
input("pollRate4", "number", title: "Poll Rate for Queue 4 in <b style='background-color:red'> hours </b>", defaultValue:0, submitOnChange: true, width:4)
}
@SuppressWarnings('unused')
void installed() {
log.trace "installed()"
xferFile("https://raw.githubusercontent.com/thebearmay/hubitat/main/hubInfoTemplate.res","hubInfoTemplate.res")
initialize()
configure()
}
void initialize() {
log.info "Hub Information v${version()} initialized"
restartCheck()
updated()
runIn(8,"initMemory")
runIn(5,"baseData")
if (settings["parm12"] != 0)
runIn(30,"updateCheck")
if(!state?.v2Cleaned)
v2Cleanup()
}
void initMemory(){
if(security) cookie = getCookie()
freeMemoryReq(cookie)
}
void configure() {
updated()
baseData()
if(!state?.v2Cleaned)
v2Cleanup()
}
void updated(){
if(debugEnable) log.debug "updated"
unschedule()
state.poll1 = []
state.poll2 = []
state.poll3 = []
state.poll4 = []
prefList.each{ l1 ->
l1.each{
if(settings["${it.key}"] != null && settings["${it.key}"] != "0") {
pMap = (HashMap) it.value
if(debugEnable) log.debug "poll${settings["${it.key}"]} ${pMap.method}"
state["poll${settings["${it.key}"]}"].add("${pMap.method}")
}
}
}
//Enforce the integer value
try{
if(pollRate1.toString().contains(".")){
pollRate1 = pollRate1.toString().substring(0,pollRate1.toString().indexOf(".")).toInteger()
device.updateSetting("pollRate1",[value:pollRate1,type:"number"])
}
if(pollRate2.toString().contains(".")){
pollRate2 = pollRate2.toString().substring(0,pollRate2.toString().indexOf(".")).toInteger()
device.updateSetting("pollRate2",[value:pollRate2,type:"number"])
}
if(pollRate3.toString().contains(".")){
pollRate3 = pollRate3.toString().substring(0,pollRate3.toString().indexOf(".")).toInteger()
device.updateSetting("pollRate3",[value:pollRate3,type:"number"])
}
if(pollRate4.toString().contains(".")){
pollRate4 = pollRate4.toString().substring(0,pollRate4.toString().indexOf(".")).toInteger()
device.updateSetting("pollRate4",[value:pollRate4,type:"number"])
}
} catch (ex) {
log.error ex
}
if(pollRate1 > 0)
runIn(pollRate1*60, "poll1")
if(pollRate2 > 0)
runIn(pollRate2*60, "poll2")
if(pollRate3 > 0)
runIn(pollRate3*60, "poll3")
if(pollRate4 > 0)
runIn(pollRate4*60*60, "poll4")
if(debugEnable)
runIn(1800,"logsOff")
if(htmlOutput == null)
device.updateSetting("htmlOutput",[value:"hubInfoOutput.html",type:"string"])
device.updateSetting("htmlOutput",[value:toCamelCase(htmlOutput),type:"string"])
if(remUnused) removeUnused()
}
void refresh(){
baseData()
poll1()
poll2()
poll3()
poll4()
}
void v2Cleanup() {
device.deleteCurrentState("data")
device.deleteCurrentState("zwaveData")
device.deleteCurrentState("nextPoll")
device.deleteCurrentState("hubVersion")
state.v2Cleaned = true
}
void poll1(){
if(security) cookie = getCookie()
state.poll1.each{
this."$it"(cookie)
}
if(pollRate1 > 0)
runIn(pollRate1*60, "poll1")
everyPoll("poll1")
}
void poll2(){
if(security) cookie = getCookie()
state.poll2.each{
this."$it"(cookie)
}
if(pollRate2 > 0)
runIn(pollRate2*60, "poll2")
everyPoll("poll2")
}
void poll3(){
if(security) cookie = getCookie()
state.poll3.each{
this."$it"(cookie)
}
if(pollRate3 > 0)
runIn(pollRate3*60, "poll3")
everyPoll("poll3")
}
void poll4(){
if(security) cookie = getCookie()
state.poll4.each{
this."$it"(cookie)
}
if(pollRate4 > 0)
runIn(pollRate4*60*60, "poll4")
everyPoll("poll4")
}
void baseData(dummy=null){
String model = getHubVersion() // requires >=2.2.8.141
updateAttr("hubModel", model)
List locProp = ["latitude", "longitude", "timeZone", "zipCode", "temperatureScale"]
locProp.each{
if(it != "timeZone")
updateAttr(it, location["${it}"])
else {
try {
tzWork=location["timeZone"].toString()
if(tzWork.indexOf("TimeZone") > -1)
tzWork=tzWork.substring(tzWork.indexOf("TimeZone")+8)
else // US/Arizona uses a shorter format
tzWork=tzWork.substring(tzWork.indexOf("ZoneInfo")+8).replace("\"","")
if(debugEnable)
log.debug "1) $tzWork"
tzWork=tzWork.replace("=",":\"")
if(debugEnable)
log.debug "2) $tzWork"
tzWork=tzWork.replace(",","\",")
if(debugEnable)
log.debug "3) $tzWork"
tzWork=tzWork.replace("]]","\"]")
if(debugEnable)
log.debug "4) $tzWork"
tzWork=tzWork.replace("null]","\"]")
if(debugEnable)
log.debug "5) $tzWork"
tzMap= (Map) evaluate(tzWork)
updateAttr("timeZone",JsonOutput.toJson(tzMap))
} catch (e) {
log.error "Time zone format error: ${location["timeZone"]}<br>$e"
}
}
}
def myHub = location.hub
List hubProp = ["id","name","zigbeeId","zigbeeEui","hardwareID","type","localIP","localSrvPortTCP","firmwareVersionString","uptime"]
hubProp.each {
updateAttr(it, myHub["${it}"])
}
if(location.hub.firmwareVersionString < minFwVersion) {
state.errorMinVersion = true
} else
state.errorMinVersion = false
if(location.hub.properties.data.zigbeeChannel != null)
updateAttr("zigbeeChannel",location.hub.properties.data.zigbeeChannel)
else
updateAttr("zigbeeChannel","Not Available")
if(location.hub.properties.data.zigbeeChannel != null){
updateAttr("zigbeeStatus", "enabled")
}else
updateAttr("zigbeeStatus", "disabled")
updateAttr("locationName", location.name)
updateAttr("locationId", location.id)
everyPoll("baseData")
}
void everyPoll(whichPoll=null){
updateAttr("currentMode", location.properties.currentMode)
updateAttr("currentHsmMode", location.hsmStatus)
SimpleDateFormat sdfIn = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
sunrise = sdfIn.parse(location.sunrise.toString())
sunset = sdfIn.parse(location.sunset.toString())
if(sunSdfPref == null) device.updateSetting("sunSdfPref",[value:"HH:mm:ss",type:"enum"])
if(sunSdfPref != "Milliseconds") {
SimpleDateFormat sdf = new SimpleDateFormat(sunSdfPref)
updateAttr("sunrise", sdf.format(sunrise))
updateAttr("sunset", sdf.format(sunset))
} else {
updateAttr("sunrise", sunrise.getTime())
updateAttr("sunset", sunset.getTime())
}
updateAttr("localIP",location.hub.localIP)
if(updSdfPref == null) device.updateSetting("updSdfPref",[value:"Milliseconds",type:"string"])
if(updSdfPref == "Milliseconds" || updSdfPref == null)
updateAttr("lastPollTime", new Date().getTime())
else {
SimpleDateFormat sdf = new SimpleDateFormat(updSdfPref)
updateAttr("lastPollTime", sdf.format(new Date().getTime()))
}
if(whichPoll != null)
updateAttr("lastPoll", whichPoll)
formatUptime()
if (attribEnable) createHtml()
}
void updateAttr(String aKey, aValue, String aUnit = ""){
aValue = aValue.toString()
/* if(aValue.length() > 1024) {
log.error "Attribute value for $aKey exceeds 1024, current size = ${aValue.length()}, truncating to 1024..."
aValue = aValue.substring(0,1023)
}*/
sendEvent(name:aKey, value:aValue, unit:aUnit)
if(attrLogging) log.info "$aKey : $aValue$aUnit"
}
void cpuTemperatureReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/internalTempCelsius",
headers: ["Cookie": cookie]
]
if (debugEnabled) log.debug params
asynchttpGet("getCpuTemperature", params)
}
void getCpuTemperature(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Double tempWork = new Double(resp.data.toString())
if(tempWork > 0) {
if(debugEnable) log.debug tempWork
if (location.temperatureScale == "F")
updateAttr("temperature",String.format("%.1f", celsiusToFahrenheit(tempWork)),"°F")
else
updateAttr("temperature",String.format("%.1f",tempWork),"°C")
updateAttr("temperatureF",String.format("%.1f",celsiusToFahrenheit(tempWork))+ " °F")
updateAttr("temperatureC",String.format("%.1f",tempWork)+ " °C")
}
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getTemp httpResp = $respStatus but returned invalid data, will retry next cycle"
}
}
void freeMemoryReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/freeOSMemory",
headers: ["Cookie": cookie]
]
if (debugEnable) log.debug params
asynchttpGet("getFreeMemory", params)
}
@SuppressWarnings('unused')
void getFreeMemory(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Integer memWork = new Integer(resp.data.toString())
if(debugEnable) log.debug memWork
if(freeMemUnit == "MB")
updateAttr("freeMemory",(new Float(memWork/1024).round(2)), "MB")
else
updateAttr("freeMemory",memWork, "KB")
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getFreeMem httpResp = $respStatus but returned invalid data, will retry next cycle"
}
}
void fifteenMinute(cookie){
if(location.hub.uptime < 900) { //if the hub hasn't been up 15 minutes use current 5 min values
updateAttr("cpu15Min",device.currentValue("cpu5Min",true))
updateAttr("cpu15Pct",device.currentValue("cpuPct",true),"%")
updateAttr("freeMem15",device.currentValue("freeMemory",true))
return
}
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/freeOSMemoryHistory",
headers: ["Cookie": cookie]
]
if (debugEnable) log.debug params
asynchttpGet("get15Min", params)
}
void get15Min(resp, data){
String loadWork
List<String> loadRec = []
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
loadWork = resp.data.toString()
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "get15min httpResp = $respStatus but returned invalid data, will retry next cycle"
}
if (loadWork) {
Integer lineCount = 0
loadWork.eachLine{
lineCount++
}
Integer lineCount2 = 0
Double cpuWork = 0.0
Long memWork = 0
loadWork.eachLine{
lineCount2++
if(lineCount2 > lineCount-3){
workSplit = it.split(",")
cpuWork+=workSplit[2].toDouble()
memWork+=workSplit[1].toLong()
}
}
memWork/=3
cpuWork/=3
updateAttr("cpu15Min",cpuWork.round(2))
cpuWork = (cpuWork/4.0D)*100.0D //Load / #Cores - if cores change will need adjusted to reflect
updateAttr("cpu15Pct",cpuWork.round(2),"%")
updateAttr("freeMem15",memWork)
}
}
void cpuLoadReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/freeOSMemoryLast",
headers: ["Cookie": cookie]
]
if (debugEnable) log.debug params
asynchttpGet("getCpuLoad", params)
}
void getCpuLoad(resp, data) {
String loadWork
List<String> loadRec = []
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
loadWork = resp.data.toString()
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getCpuLoad httpResp = $respStatus but returned invalid data, will retry next cycle"
}
if (loadWork) {
Integer lineCount = 0
loadWork.eachLine{
lineCount++
}
Integer lineCount2 = 0
loadWork.eachLine{
lineCount2++
if(lineCount==lineCount2)
workSplit = it.split(",")
}
if(workSplit.size() > 1){
Double cpuWork=workSplit[2].toDouble()
updateAttr("cpu5Min",cpuWork.round(2))
cpuWork = (cpuWork/4.0D)*100.0D //Load / #Cores - if cores change will need adjusted to reflect
updateAttr("cpuPct",cpuWork.round(2),"%")
}
}
}
void dbSizeReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/databaseSize",
headers: ["Cookie": cookie]
]
if (debugEnable) log.debug params
asynchttpGet("getDbSize", params)
}
@SuppressWarnings('unused')
void getDbSize(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Integer dbWork = new Integer(resp.data.toString())
if(debugEnable) log.debug dbWork
updateAttr("dbSize",dbWork,"MB")
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getDb httpResp = $respStatus but returned invalid data, will retry next cycle"
}
}
void publicIpReq(cookie){
params = [
uri: "https://api.ipify.org?format=json",
headers: [
Accept: "application/json"
]
]
if(debugEnable)log.debug params
asynchttpGet("getPublicIp", params)
}
@SuppressWarnings('unused')
void getPublicIp(resp, data){
try{
if (resp.getStatus() == 200){
if (debugEnable) log.debug resp.data
def jSlurp = new JsonSlurper()
Map ipData = (Map)jSlurp.parseText((String)resp.data)
updateAttr("publicIP",ipData.ip)
} else {
if (!warnSuppress) log.warn "Status ${resp.getStatus()} while fetching Public IP"
}
} catch (Exception ex){
if (!warnSuppress) log.warn ex
}
}
void evtStateDaysReq(cookie){
//Max State Days
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/maxDeviceStateAgeDays",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getStateDays", params)
//Max Event Days
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/maxEventAgeDays",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getEvtDays", params)
}
@SuppressWarnings('unused')
void getEvtDays(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Integer evtDays = new Integer(resp.data.toString())
if(debugEnable) log.debug "Max Event Days $evtDays"
updateAttr("maxEvtDays",evtDays)
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getEvtDays httpResp = $respStatus but returned invalid data, will retry next cycle"
}
}
@SuppressWarnings('unused')
void getStateDays(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Integer stateDays = new Integer(resp.data.toString())
if(debugEnable) log.debug "Max State Days $stateDays"
updateAttr("maxStateDays",stateDays)
}
} catch(ignored) {
def respStatus = resp.getStatus()
if (!warnSuppress) log.warn "getStateDays httpResp = $respStatus but returned invalid data, will retry next cycle"
}
}
void zwaveVersionReq(cookie){
if(!isCompatible(7)) {
if(!warnSuppress) log.warn "ZWave Version information not available for this hub"
return
}
param = [
uri : "http://127.0.0.1:8080",
path : "/hub/zwaveVersion",
headers: ["Cookie": cookie]
]
if (debugEnable) log.debug param
asynchttpGet("getZwaveVersion", param)
}
@SuppressWarnings('unused')
void getZwaveVersion(resp, data) {
try {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
String zwaveData = resp.data.toString()
if(debugEnable) log.debug resp.data.toString()
if(zwaveData.length() < 1024){
//updateAttr("zwaveData",zwaveData)
parseZwave(zwaveData)
}
else if (!warnSuppress) log.warn "Invalid data returned for Zwave, length = ${zwaveData.length()} will retry"
}
} catch(ignored) {
if (!warnSuppress) log.warn "getZwave Parsing Error"
}
}
@SuppressWarnings('unused')
void parseZwave(String zString){
Integer start = zString.indexOf('(')
Integer end = zString.length()
String wrkStr
if(start == -1 || end < 1 || zString.indexOf("starting up") > 0 ){ //empty or invalid string - possibly non-C7
//updateAttr("zwaveData",null)
if(!warnSuppress) log.warn "Invalid ZWave Data returned"
}else {
wrkStr = zString.substring(start,end)
wrkStr = wrkStr.replace("(","[")
wrkStr = wrkStr.replace(")","]")
HashMap zMap = (HashMap)evaluate(wrkStr)
updateAttr("zwaveSDKVersion","${((List)zMap.targetVersions)[0].version}.${((List)zMap.targetVersions)[0].subVersion}")
updateAttr("zwaveVersion","${zMap?.firmware0Version}.${zMap?.firmware0SubVersion}.${zMap?.hardwareVersion}")
}
}
void ntpServerReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/advanced/ntpServer",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getNtpServer", params)
}
@SuppressWarnings('unused')
void getNtpServer(resp, data) {
try {
if (resp.status == 200) {
ntpServer = resp.data.toString()
if(ntpServer == "No value set") ntpServer = "Hub Default(Google)"
updateAttr("ntpServer", ntpServer)
} else {
if(!warnSuppress) log.warn "NTP server check returned status: ${resp.status}"
}
}catch (ignore) {
}
}
void ipSubnetsReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub/allowSubnets",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getSubnets", params)
}
@SuppressWarnings('unused')
void getSubnets(resp, data) {
try {
if (resp.status == 200) {
subNets = resp.data.toString()
if(subNets == "Not set") subNets = "Hub Default"
updateAttr("ipSubnetsAllowed", subNets)
} else {
if(!warnSuppress) log.warn "Subnet check returned status: ${resp.status}"
}
}catch (ignore) {
}
}
void hubMeshReq(cookie){
params = [
uri : "http://127.0.0.1:8080",
path : "/hub2/hubMeshJson",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getHubMesh", params)
}
@SuppressWarnings('unused')
void getHubMesh(resp, data){
try{
if (resp.getStatus() == 200){
if (debugEnable) log.info resp.data
def jSlurp = new JsonSlurper()
Map h2Data = (Map)jSlurp.parseText((String)resp.data)
i=0
subMap2=[:]
jStr="["
h2Data.hubList.each{
if(i>0) jStr+=","
jStr+="{\"hubName\":\"$it.name\","
jStr+="\"active\":\"$it.active\","
jStr+="\"offline\":\"$it.offline\","
jStr+="\"ipAddress\":\"$it.ipAddress\","
jStr+="\"meshProtocol\":\"$h2Data.hubMeshProtocol\"}"
i++
}
jStr+="]"
updateAttr("hubMeshData", jStr)
updateAttr("hubMeshCount",i)
} else {
if (!warnSuppress) log.warn "Status ${resp.getStatus()} on H2 request"
}
} catch (Exception ex){
if (!warnSuppress) log.warn ex
}
}
void extNetworkReq(cookie){
if(location.hub.firmwareVersionString < "2.3.4.126"){
if(!warnSuppress) log.warn "Extend Network Data not available for HE v${location.hub.firmwareVersionString}"
return
}
params = [
uri : "http://127.0.0.1:8080",
path : "/hub2/networkConfiguration",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getExtNetwork", params)
}
void hub2DataReq(cookie) {
params = [
uri : "http://127.0.0.1:8080",
path : "/hub2/hubData",
headers: ["Cookie": cookie]
]
if(debugEnable)log.debug params
asynchttpGet("getHub2Data", params)
}
@SuppressWarnings('unused')
void getHub2Data(resp, data){
try{
if (resp.getStatus() == 200){
if (debugEnable) log.debug resp.data
try{
def jSlurp = new JsonSlurper()
h2Data = (Map)jSlurp.parseText((String)resp.data)
} catch (eIgnore) {
if (debugEnable) log.debug "H2: $h2Data <br> ${resp.data}"
return
}
hubAlerts = []
h2Data.alerts.each{
if(it.value == true){
if("$it.key".indexOf('Database') > -1)
hubAlerts.add("hubDatabaseSize")
else if("$it.key".indexOf('Load') > -1)
hubAlerts.add("hubLoad")
else if("$it.key" != "runAlerts")
hubAlerts.add(it.key)
}
}
updateAttr("hubAlerts",hubAlerts)
if(h2Data?.baseModel == null) {
if (debugEnable) log.debug "baseModel is missing from h2Data, ${device.currentValue('hubModel')} ${device.currentValue('firmwareVersionString')}<br>$h2Data"
return
}
if(h2Data.baseModel.zwaveStatus == "false")
updateAttr("zwaveStatus","enabled")
else
updateAttr("zwaveStatus","disabled")
if(h2Data.baseModel.zigbeeStatus == "false"){
updateAttr("zigbeeStatus2", "enabled")
if (device.currentValue("zigbeeStatus", true) != null && device.currentValue("zigbeeStatus", true) != "enabled" && "${state.errorZigbeeMismatch}" == "false" ){
//log.warn "Zigbee Status has opposing values - radio was either turned off or crashed"
state.errorZigbeeMismatch = true
} else state.errorZigbeeMismatch = false
} else {
updateAttr("zigbeeStatus2", "disabled")
if (device.currentValue("zigbeeStatus", true) != null && device.currentValue("zigbeeStatus", true) != "disabled" && "${state.errorZigbeeMismatch}" == "false"){
//log.warn "Zigbee Status has opposing values - radio was either turned off or crashed."
state.errorZigbeeMismatch = true
} else state.errorZigbeeMismatch = false
}
if(debugEnable) log.debug "securityInUse"
updateAttr("securityInUse", h2Data.baseModel.userLoggedIn)
if(debugEnable) log.debug "h2 security check"
if((!security || password == null || username == null) && h2Data.baseModel.userLoggedin == true){
log.error "Hub using Security but credentials not supplied"
device.updateSetting("security",[value:"true",type:"bool"])
}
} else {
if (!warnSuppress) log.warn "Status ${resp.getStatus()} on H2 request"
}
} catch (Exception ex){
if (!warnSuppress) log.warn ex
}
}
@SuppressWarnings('unused')
void getExtNetwork(resp, data){
try{
if (resp.getStatus() == 200){
if (debugEnable) log.info resp.data
def jSlurp = new JsonSlurper()
Map h2Data = (Map)jSlurp.parseText((String)resp.data)
if(!h2Data.usingStaticIP)
updateAttr("staticIPJson", "{}")
else {
jMap = [staticIP:"${h2Data.staticIP}", staticGateway:"${h2Data.staticGateway}", staticSubnetMask:"${h2Data.staticSubnetMask}",staticNameServers:"${h2Data.staticNameServers}"]
updateAttr("staticIPJson",JsonOutput.toJson(jMap))
}
if(h2Data.hasEthernet && h2Data.hasWiFi)
updateAttr("connectCapable","Dual")
else if(h2Data.hasEthernet)
updateAttr("connectCapable","Ethernet")
else if (h2Data.hasWiFi)
updateAttr("connectCapable","WiFi")
else
updateAttr("connectCapable", "Unknown")
if(lanIPAddr != null)
updateAttr("lanIPAddr", h2Data.lanAddr)
else
updateAttr("lanIPAddr", "None")
if(h2Data.wlanAddr != null)
updateAttr("wirelessIP",h2Data.wlanAddr)
else
updateAttr("wirelessIP","None")
if(h2Data.wifiNetwork != null)
updateAttr("wifiNetwork", h2Data.wifiNetwork)
else
updateAttr("wifiNetwork", "None")
if(h2Data.wifiNetwork && h2Data.wlanAddr && h2Data.lanAddr)
updateAttr("connectType","Dual")
else if(h2Data.wifiNetwork && h2Data.wlanAddr)
updateAttr("connectType", "WiFi")
else if(h2Data.lanAddr)
updateAttr("connectType","Ethernet")
else
updateAttr("connectType","Not Connected")
updateAttr("dnsServers", h2Data.dnsServers)
updateAttr("lanIPAddr", h2Data.lanAddr)
}
}catch (ex) {
if (!warnSuppress) log.warn ex
}
}
void updateCheck(){
if(security) cookie = getCookie()
updateCheckReq(cookie)
}
void updateCheckReq(cookie){
params = [
uri: "http://${location.hub.localIP}:8080",
path:"/hub/cloud/checkForUpdate",
timeout: 10,
headers:["Cookie": cookie]
]
asynchttpGet("getUpdateCheck", params)
}
@SuppressWarnings('unused')
void getUpdateCheck(resp, data) {
if(debugEnable) log.debug "update check: ${resp.status}"
try {
if (resp.status == 200) {
def jSlurp = new JsonSlurper()
Map resMap = (Map)jSlurp.parseText((String)resp.data)
if(resMap.status == "NO_UPDATE_AVAILABLE")