-
Notifications
You must be signed in to change notification settings - Fork 3
/
MQTT app
7172 lines (6652 loc) · 346 KB
/
MQTT app
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
/*
Copyright Kevin Hawkins 2019 [email protected]
RESTRICTED LICENCE:
See associated licence file.
By usage of this application you accept the terms of the licence.
Currently no part of this code may be copied, redistributed, altered or used in any way without my express written/email permission.
This code may be installed for the express purpose of testing and reporting issues. You may also
alter and adapt this code for your own personal useage, but it may not be onwardly distributed to anyone in any form, or portions used in any other available application.
My current intention is to relax the terms of this licence upon general release.
No representation of any form is made to the suitability of this code or it's fitness for any purpose at all. Use entirly at your own discretion and risk . No liability accepted.
Logging code was adapted from Eric Vitale's ST LIFX application, with thanks. Copyright 2016 [email protected]
Many thanks for contributions from Casey, Jeff, Cody, Kirk, Andy and more. Much appreciated.
Support via Hubitat community beta threads
https://community.hubitat.com/t/beta-mqtt-app/32750
You can contact me via PM on that forum @kevin
Bug reports to this GitHub repository please (issues)
*/
/* #########################################################################################################
This application is provided free of charge .. enjoy.
Should you wish you can help keep me awake longer via this link
https://www.buymeacoffee.com/xAPPO
Many thanks .. much appreciated
######################################################################################################### */
import java.security.MessageDigest
//import groovy.json.JsonSlurper
definition(
name: "MQTT",
namespace: "ukusa",
author: "Kevin Hawkins",
importUrl: "https://raw.githubusercontent.com/xAPPO/MQTT/beta3/MQTT%20app",
description: "Links MQTT with HE devices",
category: "Intranet Connectivity",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/App-BigButtonsAndSwitches.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]",
installOnOpen: true,
iconX3Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]"
)
preferences { // can't use atomicState vars in this section
//page(name: "Configuration", title: "<h2><b>MQTT</b></h2>", nextPage: "vMQTT", uninstall: false, hideable: true,hideWhenEmpty: true){
page(name: "configuration", title: "<h2><b>MQTT</b></h2>",install: true, uninstall: true, hideable: true,hideWhenEmpty: true){
section ("<b>MQTT Broker</b>", hideable: true, hidden: true){
//createMQTTclient()
//input "mqtt2", "device.MQTTClient", required: false, multiple: false, title: ""
//input "mqtt", "device.MQTTClient", required: false, multiple: false, title: "<b>MQTT Broker</b>", submitOnChange: false
input name: "hubName", type: "text", title: "<b>Hub Name</b>", description: " choose a unique name for this Hubitat Hub", required: true, displayDuringSetup: true, submitOnChange: false
input name: "MQTTBroker", type: "text", title: "<b>MQTT Broker Address</b>      prefixed tcp://...", description: "e.g. tcp://192.168.1.17:1883 - NB you must include tcp://...", required: true, displayDuringSetup: true
input name: "username", type: "text", title: "<b>MQTT Username</b>", description: "(leave blank if none)", required: false, displayDuringSetup: true
input name: "password", type: "password", title: "<b>MQTT Password</b>", description: "(leave blank if none)", required: false, displayDuringSetup: true
//input "newMQTTDev", "button", title: "Create MQTT broker device driver", textColor: "green"
}
section ("<b>Configuration</b>", hideable: true, hidden: true) {
input "mqttRemoveDevices", "bool", title: "<b>Purge Discovered Devices</b><br> WARNING: Setting this will delete all your 'discovered devices' when you click 'Done'. However your selected devices from HA and homie discovery will be re-added automatically when app is run again but you will need to re-add them manually in your Dashboards. Your selected 'published' devices and any manually created 'ad-hoc' devices will not be affected", required: true, defaultValue: false, submitOnChange: false
input "WipeDevices", "bool", title: "Forget enabled devices; Warning you will have to manually re-enable your devices for export and import from MQTT", submitOnChange: false
input "logging", "enum", title: "<b>Log Level</b>", required: false, defaultValue: "INFO", options: ["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "DISABLED"]
input "tempUnits", "enum", title: "<b>Temperature units</b>", required: false, defaultValue: "Celsius x.xx°C", options: ["Celsius x.xx°C", "Celsius x.x°C", "Fahrenheit °F","Fahrenheit x.x°F"]
input "lengthUnits", "enum", title: "<b>Length units (not yet functional)</b>", required: false, defaultValue: "Metric (mm,m,km)", options: ["Metric (mm,m,km)", "Imperial (inches/feet/miles)"]
input "allowMqttUnlock", "bool", title: "<b>Allow Unlock via MQTT</b><br>WARNING: Setting this will allow unlocking locks via MQTT. It is recommended that your MQTT instance requires username/password & is protected by SSL", required: false, defaultValue: false, submitOnChange: false
input "allowHSMDisarm", "bool", title: "<b>Allow HSM disarm via MQTT</b><br>WARNING: Setting this will allow HSM disarm via MQTT, provided 'Allow HSM control' is ON", required: false, defaultValue: false, submitOnChange: false
input "allowHSMControl", "bool", title: "<b>Allow HSM control via MQTT</b><br>WARNING: Setting this will allow all HSM control via MQTT (except disarming if 'Allow HSM disarm' is OFF)", required: false, defaultValue: false, submitOnChange: false
input "mqttKeypadMode", "enum", title: "<b>Allow Keypad control and specify when a code is needed</b><br>WARNING: Setting this will allow controlling Keypade code via MQTT. It is recommended that your MQTT instance requires username/password & is protected by SSL", required: false, defaultValue: "No control of keypad", options: ["No control of keypad", "No Keycode needed", "Keycode to Arm only","Keycode to Arm/Disarm"]
input name: "mqttKeypadCode", type: "text", title: "Keypad Code", description: " Code to be used via HA", submitOnChange: false, required: false
}
section ("<b>MQTT Publish Formats</b>", hideable: true, hidden: true){
//input "HEBasic", "bool", title: "<b>Hubitat basic MQTT</b>", required: true, defaultValue: false, submitOnChange: false
input "homiePublish", "bool", title: "<b>homie 3 protocol</b>", required: true, defaultValue: true, submitOnChange: false
input "minHomie", "bool", title: "<b>Complete & compliant homie topics</b>", required: true, defaultValue: true, submitOnChange: false
input "homieStatesPersist","bool",title: "<b>    ... retain homie states</b>", required: false, defaultValue: true, submitOnChange: false
input "HADiscovery", "bool", title: "<b>Home Assistant MQTT discovery protocol (requires homie3 publish enabled)</b>", required: true, defaultValue: false, submitOnChange: false
input name: "HADiscoveryTopic", type: "text", title: "<b>Home Assistant Discovery Topic</b>", description: " as configured in HA", required: false, displayDuringSetup: true, submitOnChange: false
input "HARemember", "enum", title: "<b>Home Assistant MQTT discovered devices</b>", required: false, defaultValue: "Remember",options: ["Forget", "Remember"], submitOnChange: false
}
section ("<b>Discovery into HE</b>",hideWhenEmpty: true, hideable: true, hidden: true) {
href(name: "href2",
title: "Discovery Protocols",
required: false,
page: "discovery")
}
section ("<b>Virtual Devices</b>",hideWhenEmpty: true, hideable: true, hidden: true) {
href(name: "href",
title: "HE Virtual devices associated with arbitrary MQTT topics",
required: false,
page: "vMQTT")
}
section ("<b>Publish these HE devices to MQTT</b>",hideWhenEmpty: true, hideable: true, hidden: true) {
input "modes", "bool", title: "Mode changes", required: false
input "hsm", "bool", title: "Hubitat Security Monitor", required: false
input "everything", "capability.*",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Everything (all capabilities/attributes a selected device supports)</b>", submitOnChange: false
input "alarms", "capability.alarm",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Alarms</b>", submitOnChange: false
// input "actuators", "capability.actuator",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Actuators</b>", submitOnChange: false
input "batterysensors", "capability.battery",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Battery sensors</b>", submitOnChange: false
input "bulbs", "capability.bulb",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Bulbs</b>", submitOnChange: false
input "buttons", "capability.button",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Buttons</b>", submitOnChange: false
input "buttonshold", "capability.holdableButton",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Buttons holdable</b>", submitOnChange: false
input "buttonspush", "capability.pushableButton",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Buttons pushable</b>", submitOnChange: false
input "buttonsrelease", "capability.releasableButton",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Buttons releasable</b>", submitOnChange: false
input "buttonsdtap", "capability.doubleTapableButton",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Buttons double tapable</b>", submitOnChange: false
input "carbonmonoxidesensors", "capability.carbonMonoxideDetector",hideWhenEmpty: true,multiple: true, required: false, title: "<b>Carbon monoxide detectors</b>", submitOnChange: false
input "chimes", "capability.chime",hideWhenEmpty: true,multiple: true, required: false, title: "<b>Chimes</b>", submitOnChange: false
input "colour", "capability.colorControl",hideWhenEmpty: true,multiple: true, required: false, title: "<b>Colour control light devices</b>", submitOnChange: false
input "colourT", "capability.colorTemperature",hideWhenEmpty: true,multiple: true, required: false, title: "<b>Colour temperature light devices</b>", submitOnChange: false
input "colourMode", "capability.colorMode",hideWhenEmpty: true,multiple: true, required: false, title: "<b>Colour Mode devices</b>", submitOnChange: false
input "contactsensors", "capability.contactSensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Contact sensors</b>", submitOnChange: false
input "dimmers", "capability.switchLevel",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Dimmers</b>", submitOnChange: false
input "fans", "capability.fanControl",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Fans</b>", submitOnChange: false
input "garagedoors", "capability.garageDoorControl",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Garage Door</b>", submitOnChange: false
input "humiditysensors", "capability.relativeHumidityMeasurement",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Humidity sensors</b>", submitOnChange: false
input "illuminancesensors", "capability.illuminanceMeasurement",hideWhenEmpty: false, multiple: true, required: false, title: "<b>Illuminance sensors</b>", submitOnChange: false
input "keypads", "capability.securityKeypad",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Keypads</b>", submitOnChange: false
input "locks", "capability.lock",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Locks</b>", submitOnChange: false //Casey
input "lights", "capability.light",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Lights</b>", submitOnChange: false //Casey
input "motionsensors", "capability.motionSensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Motion sensors</b>", submitOnChange: false
input "mqtttext", "capability.telnet",hideWhenEmpty: true, multiple: true, required: false, title: "<b>MQTT Text</b>", submitOnChange: false
input "musicplayers", "capability.musicPlayer",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Music Players</b>", submitOnChange: false
input "outlets", "capability.outlet",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Outlets</b>", submitOnChange: false
input "powersensors", "capability.powerMeter",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Power sensors</b>", submitOnChange: false
input "presencesensors", "capability.presenceSensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Presence sensors</b>", submitOnChange: false
input "ramp", "capability.switchLevel",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Ramp control via MQTT</b>", submitOnChange: false
input "refresh", "capability.*",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Refresh (if supported by device)</b>", submitOnChange: false //Casey
input "relayswitches", "capability.relaySwitch",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Relay Switches</b>", submitOnChange: false
input "sensors", "capability.sensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Sensors</b>", submitOnChange: false
input "shocksensors", "capability.shockSensor",hideWhenEmpty: true, title: "<b>Shock sensors</b>", multiple: true, required: false
input "smokesensors", "capability.smokeDetector",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Smoke detectors</b>", submitOnChange: false
input "speechsynthesis", "capability.speechSynthesis",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Speech Synthesis</b>", submitOnChange: false
input "switches", "capability.switch",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Switches</b>", submitOnChange: false
input "tempsensors", "capability.temperatureMeasurement",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Temperature sensors</b>", submitOnChange: false
input "thermostats", "capability.thermostat",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Thermostats</b>", submitOnChange: false
input "valves", "capability.valve",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Valves</b>", submitOnChange: false
input "globVars", "device.VirtualOmniSensor", required: false, title: "<b>Global Variables</b>",hideWhenEmpty: true, multiple: true, submitOnChange: false
input "gVars", "device.RMConnectorVariable", required: false, title: "<b>New Global Vars</b>",hideWhenEmpty: true, multiple: true, submitOnChange: false
//input "variables", "device.VirtualOmniSensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Variables</b>", submitOnChange: false
input "voltagesensors", "capability.voltageMeasurement",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Voltage sensors</b>", submitOnChange: false
input "watersensors", "capability.waterSensor",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Water Sensors</b>", submitOnChange: false
input "windowshades", "capability.windowShade",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Window Shades</b>", submitOnChange: false
input "listAll", "capability.*",hideWhenEmpty: true, title: "<b>List devices Capabilities and Attributes to Hubitat Topic</b>", multiple: true, required: false
//TODO add remaining sensors type (as and if requested)
}
}
//page(name: "vMQTT", nextPage: "discovery")
page(name: "vMQTT", nextPage: "configuration")
//page(name: "discovery", title: "Select MQTT discovered devices",nextPage: "vMQTT", install: true, uninstall: true)
page(name: "discovery", title: "Select MQTT discovered devices",nextPage: "configuration")
}
def vMQTT() {
//dynamicPage(name: "vMQTT", title: "<h2><b>Virtual MQTT Devices and Data</b></h2>(optional)", nextPage: "discovery") {
dynamicPage(name: "vMQTT", title: "<h2><b>Virtual MQTT Devices and Data</b></h2>(optional)", nextPage: "configuration") {
// Removing virtual Button as inpractical to implement
//atomicState.vList=["RM Connector Variable", "MQTT Text", "Virtual audioVolume", "Virtual Button","Virtual CO Detector", "Virtual Color Temperature Light", "Virtual Contact Sensor", "Virtual Dimmer", "Virtual Fan Controller", "Virtual Garage Door Controller", "Virtual Humidity Sensor", "Virtual Illuminance Sensor", "Virtual Lock", "Virtual Moisture Sensor", "Virtual Motion Sensor", "Virtual Multi Sensor", "Virtual Omni Sensor", "Virtual Presence", "Virtual RGB Light", "Virtual RGBW Light", "Virtual Shade","Virtual Smoke Detector", "Virtual Switch", "Virtual Temperature Sensor", "Virtual Thermostat" ]
atomicState.vList=["RM Connector Variable", "MQTT Text", "Virtual audioVolume","Virtual CO Detector", "Virtual Color Temperature Light", "Virtual Contact Sensor", "Virtual Dimmer", "Virtual Fan Controller", "Virtual Garage Door Controller", "Virtual Humidity Sensor", "Virtual Illuminance Sensor", "Virtual Lock", "Virtual Moisture Sensor", "Virtual Motion Sensor", "Virtual Multi Sensor", "Virtual Omni Sensor", "Virtual Presence", "Virtual RGB Light", "Virtual RGBW Light", "Virtual Shade","Virtual Smoke Detector", "Virtual Switch", "Virtual Temperature Sensor", "Virtual Thermostat" ]
//atomicState.attList=[:]
//def attmap = ['acceleration':'active|inactive','contact':'open|closed', 'water':"wet|dry"]
section {
//input "resetMappings", "button", title: "Reset Mappings", textColor: "red"
input "virtuals", "capability.virtual",hideWhenEmpty: true, multiple: true, required: false, title: "<b>Virtual Devices</b>", submitOnChange: false
input(name: "capability", type: "enum", title: "Device Type",description: null, multiple: false, required: false, submitOnChange: true, options: atomicState.vList)
}
//atomicState.attList=[]
attList=[]
//atomicState.edit=false
/*
List myDeviceList = []
lots.each { myDevice ->
if(myDevice.displayName != 'xyz') {
myDeviceList.add(myDevice.id)
}
}
switches.each { myDevice ->
if(myDevice.displayName != 'xyz') {
myDeviceList.add(myDevice.id)
}
}
dimmers.each { myDevice ->
if(myDevice.displayName != 'xyz') {
myDeviceList.add(myDevice.id)
}
}
carbonmonoxidesensors.each { myDevice ->
if(myDevice.displayName != 'xyz') {
myDeviceList.add(myDevice.id)
}
}
app.updateSettingWithType("lots", myDeviceList, "capability")
*/
//app.removeSetting(var)
// atomicState.Mappings=[:]
if (atomicState.Mappings==null) atomicState.Mappings=[:]
/* // No longer used ??? TODO check
for (i=0; i < atomicState.vList.size(); i++) { //this loops through all the HE virtual drivers (names held in vList)
def String varCap2="var_" + atomicState.vList[i].replaceAll("\\s","")
MQTTvirt = settings[varCap2]
if (MQTTvirt != null){
MQTTvirt.each { dev ->
data2=dev.getData()
if ((data2['mqtt']=="true")||(data2['mqtt']=="enabled")) { // these are the MQTT enabled devices for this driver type
data2.each { key, value ->
if ((value != null) && (value != "") && (value != " ")) {
if (key.endsWith ("_Topic")) { abort is
localMap=atomicState.Mappings
localMap.put (value, dev.deviceNetworkId)
atomicState.Mappings=localMap
}
// }
}
//Map Invert = data2.collectEntries { e -> [(e.value): e.key] }
}
}
log("Original data for $dev.displayName was $data2 ","DEBUG")
log ("Complete Topic Mappings are now $atomicState.Mappings", "DEBUG")
}
}
} //end for i loop
*/
if (capability) {
def String varCap = "var_" + "${capability}".replaceAll("\\s","")
sensor=false
settings[varCap].each { virtDev ->
if (virtDev !=null) virtDev.updateDataValue("mqtt", "enabled")
log ("Subscribe to events from virtual device $virtDev","KH")
registerAll (virtDev,0,'auto')
}
dType = "capability.nowt"
if (capability.contains("Sensor")||capability.contains("Presence")) sensor=true
dType="device."+capability.replaceAll("\\s","")
// TODO iNVESTIGATE IMPACT OF USING NON VIRTUAL DEVICES
//else if (capability == "All Switches") dType= "capability.switch"
//else if (capability == "All Dimmers") dType= "capability.switchLevel"
section {
// if (atomicState.tete==null)
atomicState.tete =[]
//atomicState.virtList=[]
input(name: varCap, type: dType, title: "MQTT enabled $capability devices",description: null, multiple: true, required: false, submitOnChange: true)
}
section {
//app.updateSetting("vDev",["none"])
app.removeSetting("vDev")
input(name: "vDev", type: dType, title: "Edit this $capability device",description: null, multiple: false, required: false, submitOnChange: true)
if (vDev == null) {
app.updateSetting("vDevName","")
input (name: "vDevName",type: "text", title: "... or create a new virtual $capability device called ..." , required: false, submitOnChange: true)
if (vDevName != null){
atomicState.newDevName=vDevName // This isn't enough to identify it from an incoming MQTT message - can only identify by topic
atomicState.newDevType=capability
input "newVDev", "button", title: "Create device $vDevName", textColor: "green"
}
else atomicState.vDevName=""
}
else {
input "oldVDev", "button", title: "Delete device $vDev", textColor: "red"
// input "editVDev", "button", title: "Edit device $vDev", textColor: "blue"
}
}
}
atomicState.first=false
if (atomicState.first) { // entry from another page
//atomicState.first=false
}
else {
if (vDev) { // && atomicState.edit) { // this is the whole page
log ("Selected Device is ${vDev.displayName} - last was {$atomicState.vDev}","DEBUG")
if (vDev.displayName==atomicState.vDev) newDev=false else newDev=true
// log ("newDev is $newDev","LOG")
if (newDev) {
log("#### Blocking any data updates to device from previous screen ####","INFO")
atomicState.attList=[]
temp=atomicState.attList
if (vDev.getTypeName()=="RM Connector Variable") temp.add("variable")
else if (vDev.getTypeName()=="MQTT Text") temp.add("text")
vDev.capabilities.each { cap ->
log ("Found $cap in vDev $vDev.displayName","INFO")
cap.attributes.each { attr ->
log ("Found attribute $attr in $vDev.displayName [$cap]", "WARN")
temp.add("${attr}")
}
}
log ("Attribute list is now $temp","WARN")
atomicState.attList=temp
// atomicState.attList now contains every attribute that the newly selected device has but caution - may not align with attrList=vDev.getSupportedAttributes()
// this is because 1) I force text values into atomicState.attList e.g. 'variable' and 'text' and also attrList has ALL (custom) attributes not just those within a capability
}
//else log ("Refresh of page with no change of device","KH") //something changed or F5
section {
// input(name: "atts", type: "enum", title: "Device Attributes",description: null, multiple: false, required: false, submitOnChange: true, options: ["Hi","you"])
}
atomicState.vDev=vDev.displayName
dEnabled=null
try {
dEnabled = (vDev.getDataValue("mqtt"))
if (dEnabled==null) {
vDev.updateDataValue("mqtt", "default")
log ("Updated mqtt to 'default'","WARN")
dEnabled="default"
}
}
catch (e) {
log ("Added and updated mqtt to 'false'","WARN")
vDev.updateDataValue("mqtt", "false")
dEnabled="false"
}
if (dEnabled=="enabled") { // don't display if not mqtt enabled
section {
temp=atomicState.attList.sort()
atomicState.attList=temp
//input(name: "atts", type: "enum", title: "Device atomic Attributes",description: null, multiple: false, required: false, submitOnChange: true, options: atomicState.attList)
/*
input(name: "dMode", type: "enum", title: "Method to add device attribute topics",description: null, defaultValue: "Manual", multiple: false, required: true, submitOnChange: true, options: ["Manual", "Assisted from MQTT"]) //, "Create new device"])
if (dMode=="Assisted from MQTT") assisted=true else assisted=false
*/
assisted=false // beta2 and beta3 .. disabling this feature temporarily as confusing
if (assisted) input (name: "devWildcard", type: "text", title: "Please enter a wildcarded topic encompassing the whole device but no others", submitOnChange: true)
if ((assisted) && (devWildcard != null)) {
atomicState.dTopic=devWildcard
atomicState.devTopics = (atomicState.devTopics != null)?atomicState.devTopics:[]
input "topics", "button", title: "Get device topics from MQTT for ${devWildcard}"
input "deviceTopics", "enum", multiple: false, title: "<b>MQTT discovered topics within ${devWildcard} device</b>", options: atomicState.devTopics.sort()
if (!sensor){
input(name: "cmdSuffix", type: "text", title: "Command suffix for topics eg /set or /cmd", required: false, submitOnChange: true)
}
}
} //end section
atomicState.devTopics = (atomicState.devTopics != null)?atomicState.devTopics:[]
temp2=atomicState.devTopics
for (i=0; i < temp2.size(); i++) {
temp2[i]=temp2[i]+ "${cmdSuffix}"
}
section { //data value update section
for (i = 0; i < atomicState.attList.size(); i++) { // loops for every attribute device has
def String var = "var" + "${i}"
def String varCmd = "varCmd" + "${i}"
def String varAtt = "varAtt" + "${i}"
//def String varJSON = "varJSON" + "${i}"
// TODO Check - if this is a new device what happens
// Purge previous device settings
//log ( "var is " + var + " and attribute is "+ atomicState.attList[i],"LOG")
try {
data=vDev.getDataValue("${atomicState.attList[i]}_Topic")
if (newDev) app.updateSetting (var,data)
dataAtt=vDev.getDataValue("${atomicState.attList[i]}_MAP")
log ("Recovered data for map $i $dataAtt","LOG")
if (newDev) app.updateSetting (varAtt,dataAtt)
//dataJSON=vDev.getDataValue("${atomicState.attList[i]}_JSON")
// if (newDev) app.updateSetting (varJSON,dataJSON) //could be null
}
catch (e) {
log ("No state for $i","DEBUG")
}
if (!sensor){
try {
dataC=vDev.getDataValue("${atomicState.attList[i]}_Cmd")
if (newDev) app.updateSetting (varCmd,dataC)
}
catch (e) {
log ("No cmd for $i","DEBUG")
}
}
if (!newDev){ // this happens when a data value was updated and the device is redisplayed (it also happens when page two is originally entered too)
//app.removeSetting(var)
//app.removeSetting(varCmd)
//app.removeSetting(varAtt)
//app.removeSetting(varJSON)
//try {
temp=atomicState.topicLink
if (temp==null) temp=[:]
//log ("Settings for $var is ${settings[var]} ~ ${attList[i]}", "KH")
if ((settings[var]!=null) && (settings[var]!=data)) {
/*
log (" ","KH")
log ("[$i] UPDATE device $vDev.displayName - ${atomicState.attList[i]}_Topic","KH")
log ("[$i] UPDATING - from " + vDev.getDataValue("${atomicState.attList[i]}_Topic"),"KH")
*/
vDev.updateDataValue("${atomicState.attList[i]}_Topic", settings[var].trim())
myVal=settings[var].trim()
// ############################# TODO need to strip JSON
// log ("Updating topicLink .. $myVal = $vDev.deviceNetworkId","LOG")
if (temp.containsKey(myVal)){
list=temp[myVal] //.add(topic)
if (list.contains("$vDev.deviceNetworkId")) {
}
else {
list.add ("$vDev.deviceNetworkId")
temp["$myVal"]=list
}
}
else {
list=["$vDev.deviceNetworkId"]
temp["$myVal"] = list
}
log ("[$i] UPDATED on add to $myVal","KH") // ${settings[var]}","KH")
jas=myVal.indexOf("{")
if ((jas>0) && (myVal.endsWith(':}'))){ //strip json
//log ("Strip JSON value $defOne for subscribe" , "KH")
myVal=myVal.substring(0, jas)
}
mqtt = getChildDevice("MQTT: Child device driver")
if (mqtt!=null) mqtt.subscribeTopic ("$myVal") // // ("${settings[var]}")
// log (" ","KH")
}
//log ("varAtt is $varAtt ${settings[varAtt]} $dataAtt", "KH")
if ((settings[varAtt]!=null) && (settings[varAtt]!=dataAtt)) {
/*
log (" ","KH")
log ("[$i] UPDATE device $vDev.displayName - ${atomicState.attList[i]}_MAP","KH")
log ("[$i] UPDATING - from " + vDev.getDataValue("${atomicState.attList[i]}_MAP"),"KH")
log ("[$i] UPDATED to ${settings[varAtt]}","KH")
log ("[$i] CHECK " + vDev.getDataValue("${atomicState.attList[i]}_MAP"),"KH")
log (" ","KH")
*/
//TODO THIS IS A TEMPORARY FIX / HACK
//===================================
//attrList=vDev.getSupportedAttributes()
//if (attrList[i]!=null && attrList[i].dataType =="ENUM") {
if (atomicState.attList[i]=='level') {
log ("Blocking adding _MAP data for $atomicState.attList[i]","KH")
}
else {
log ("Updated[$i] " + atomicState.attList[i] +"_Map to" + settings[varAtt].trim(),"LOG")
vDev.updateDataValue("${atomicState.attList[i]}_MAP", settings[varAtt].trim())
}
}
/*
if (settings[varJSON]!=null){
String vJSON= settings[varJSON].toString()
//if (settings[varJSON]!=dataJSON) {
if (vJSON!=dataJSON) {
log (" ","KH")
log ("[$i] UPDATE device $vDev.displayName - ${atomicState.attList[i]}_JSON","KH")
log ("[$i] UPDATING - from " + vDev.getDataValue("${atomicState.attList[i]}_MAP"),"KH")
vDev.updateDataValue("${atomicState.attList[i]}_JSON", vJSON)
log ("[$i] UPDATED to $vJSON","KH")
log ("[$i] CHECK " + vDev.getDataValue("${atomicState.attList[i]}_JSON"),"KH")
log (" ","KH")
}
}
*/
if (!sensor) {
if ((settings[varCmd]!=null) && (settings[varCmd]!=dataC)) {
// ToDo - be able to send a JSON command
log (" ","DEBUG")
log ("[$i] UPDATE device $vDev.displayName - ${atomicState.attList[i]}_Cmd","DEBUG")
log ("[$i] UPDATING - from " + vDev.getDataValue("${atomicState.attList[i]}_Cmd"),"DEBUG")
vDev.updateDataValue("${atomicState.attList[i]}_Cmd", settings[varCmd].trim())
//myVal=settings[varCmd].trim()
//log ("myVal cmd $myVal vDev $vDev.deviceNetworkId","DEBUG")
//temp[myVal] = vDev.deviceNetworkId // Don't get incoming messages on Cmd topics
log ("[$i] UPDATED to ${settings[varCmd]}","DEBUG")
log (" ","DEBUG")
// subscribe this device for all attributes/events
log ("Subscribing to events from device $vDev","KH")
registerAll (vDev,0,'auto')
}
// }
}
/* }
catch (e) {
log ("[$i] Device $vDev.displayName doesn't have data for topics "+e ,"WARN")
}
*/
atomicState.topicLink=temp
} // not newDev
log ("atomicState.devTopics is $atomicState.devTopics","TRACE") //maybe old - for the last looked up device
log ("atomicState.attList is $atomicState.attList","TRACE")
if (assisted) {
input(name: var, type: "enum", title: "<b> ${atomicState.attList[i]} </b> attribute MQTT status topic", description: null, multiple: false, required: false, submitOnChange: true, options: atomicState.devTopics.sort() + "/sett")
if (!sensor) input(name: varCmd, type: "enum", title: "<b> ${atomicState.attList[i]} </b> MQTT command topic", description: null, multiple: false, required: false, submitOnChange: true, options: temp2.sort())
}
else {
if (i==0){
defOne=vDev.getDataValue("${atomicState.attList[i]}_Topic")
if ((defOne != null)&&(defOne!='')){
log ("TODO This is now not a valid topic to use for ID [$i] [$defOne] ","KH")
// This is not now viable as one topic can now map to several devices
//if (i==0){
try {
jas=defOne.indexOf("{")
if ((jas>0) && (defOne.endsWith(':}'))){
// log ("Strip JSON value $defOne for DNI" , "KH")
defOne=defOne.substring(0, jas )
}
//vDev.setDeviceNetworkId("MQTT:virtual_" + defOne )
// log ("$vDev.displayName - Blocked updating DeviceNetworkId with $defOne","KH")
}
catch(e) {
log ("DNI nametopic [MQTT:virtual_$defOne already exists please choose another: " +e,"ERROR")
dup=getChildDevice("MQTT:virtual_"+defOne)
if (dup!=null) log ("You already have a HE device [$dup.displayName] mapped to this MQTT topic","ERROR")
}
}
}
//if (i>0) log ("Several state topics for $vDev","DEBUG")
}
defTwo=vDev.getDataValue("${atomicState.attList[i]}_Cmd")
input(name: var, type: "text", defaultValue: defOne,title: "<b> ${atomicState.attList[i]} </b> attribute MQTT status topic", description: null, multiple: false, required: false, submitOnChange: true)
if (!sensor) input(name: varCmd, type: "text", defaultValue: defTwo, title: "<b> ${atomicState.attList[i]} </b> MQTT command topic", description: null, multiple: false, required: false, submitOnChange: true)
// try {
// BUG TOFIX our i values aren't aligned - we might skip attributes
attrList=vDev.getSupportedAttributes() // why do this when we have atomicState.attList[] - these may not align as this misses 'text and 'varaiable' but includes custom attributes and those not within a capability
// attrList is an attribute object atomicState.AttList is a text list of attributes.
//log.warn atomicState.attList
//log.warn attrList
if (attrList[i]!=null && attrList[i].dataType =="ENUM") {
String atts = "${attrList[i].getPossibleValues()}"
log ("ENUM on " + attrList[i] + " === " +atomicState.attList[i] + " === " + atts, "LOG")
//if (vDev.getDataValue("${atomicState.attList[i]}_MAP")){
if (vDev.getDataValue("${attrList[i]}_MAP")){
// Think I already have this in dataFalse
//try {dataAtt=vDev.getDataValue("${atomicState.attList[i]}_MAP")} catch(e) {log ("FAIL OFF","WARN")}
try {dataAtt=vDev.getDataValue("${attrList[i]}_MAP")} catch(e) {log ("FAIL OFF","WARN")}
// if (newDev){
app.updateSetting(varAtt,dataAtt)
defAtt=dataAtt
// }
//if (atomicState.attList[i] != "level") { // Need to expand this to other numerics and non binaries
if ("${attrList[i]}" != "level") { // Need to expand this to other numerics and non binaries
if (attrList[i].dataType =="ENUM") {
//input(name: varJSON, type: "text", defaultValue: '', title: "JSON {attribute:} name (optional)" , required: false, submitOnChange: false, hideWhenEmpty: true, width: 4)
//input(name: varAtt, type: "text", defaultValue: defAtt, title: "        MQTT payload map values for <b>$atts</b> for the <b>${atomicState.attList[i]}</b> attribute <br>         [status] or [status][command]" , required: false, submitOnChange: true)// , width: 6)
input(name: varAtt, type: "text", defaultValue: defAtt, title: "<b>${attrList[i]}</b> attribute MQTT payload map values to <b>${atts.replace(', ',',')}</b> for separate [status][command] or [shared]" , required: false, submitOnChange: true)// , width: 6)
}
if (!newDev) {
//log ("2a Updating old ${atomicState.attList[i]}_MAP with ${settings[varAtt]} on $vDev.displayName","KH")
//if (settings[varAtt] != null) vDev.updateDataValue("${atomicState.attList[i]}_MAP", settings[varAtt])// $settings?.stateOFF)
if (settings[varAtt] != null) vDev.updateDataValue("${attrList[i]}_MAP", settings[varAtt])// $settings?.stateOFF)
//log.debug "2b Updating old ${atomicState.attList[i]}_JSON with ${settings[varJSON]} on $vDev.displayName"
//if ((settings[varJSON] != null)&&(settings[varJSON] != ' ')) vDev.updateDataValue("${atomicState.attList[i]}_JSON", settings[varJSON])// $settings?.stateOFF)
}
}
}
else {
log ("Adding the default value for ${atomicState.attList[i]}_MAP","KH")
//vDev.updateDataValue("${atomicState.attList[i]}_MAP", atts)
atts=atts.replace(', ', ',')
vDev.updateDataValue("${attrList[i]}_MAP", atts.trim())
log ("Updating with #$atts# #${atts.trim()}#","WARN")
}
} //not ENUM
/*
if (vDev.getDataValue("${atomicState.attList[i]}_JSON")){
try {dataJSON=vDev.getDataValue("${atomicState.attList[i]}_JSON")} catch(e) {log ("FAIL ON","WARN")}
//if (newDev){
if (dataJSON!=null) app.updateSetting(varJSON,dataJSON)
defJSON=dataJSON
// }
if (atomicState.attList[i] != "level") {
input(name: varJSON, type: "text",defaultValue: defJSON, title: "        JSON {attribute:} name (optional) for <b>${atomicState.attList[i]}</b> attribute" , required: false, submitOnChange: true)
if (!newDev) {
log.debug "3a Updating old ${atomicState.attList[i]}_JSON with ${settings[varJSON]} on $vDev.displayName"
if ((settings[varJSON] != null)&&(settings[varJSON] != ' ')) {
vDev.updateDataValue("${atomicState.attList[i]}_JSON", settings[varJSON])
}
}
}
}
else {
log ("Need to add a default value for ${atomicState.attList[i]}_JSON","KH")
vDev.updateDataValue("${atomicState.attList[i]}_JSON", " ")
}
*/
}// end for loop on each attribute (i)
//atomicState.edit=false
} // end data value update section
try {
if (vDev.getDataValue("max_Level")){
app.removeSetting("maxLev")
section {
currentMax=vDev.getDataValue("max_Level")
if (currentMax != "null") { //null is a text value
app.updateSetting("maxLev",currentMax)
//if (maxLev!=null) currentMax=maxLev
if (!assisted) input(name: "maxLev", type: "text",defaultValue: currentMax, title: "Please enter the maximum possible level:" , required: false, submitOnChange: true)
else input(name: "maxLev", type: "enum",defaultValue: currentMax, title: "Please enter the maximum possible level:" , required: false, submitOnChange: true,multiple: false, options: atomicState.devTopics.sort())
//if (!newDev) vDev.updateDataValue("max_Level", "$Topic6")
if (!newDev) vDev.updateDataValue("max_Level", settings?.maxLev)
}
}
}
}
catch (e) {}
//atomicState.edit=false
} // not enabled for MQTT
} //if (vDev)
else
if ($vDev!=null){
section (title: "This device <b> $vDev </b> is not enabled on MQTT") {
}
} //atomicState.first
}
} // end dynamic page (vDev)
//atomicState.edit=false
}
//=========================================================================================================================================================================================================================================
def discovery() { // can use atomicState vars in this section
//dynamicPage(name: "discovery", title: "", install: true, nextPage:"hrefPage", uninstall: false) {
//dynamicPage(name: "discovery", title: "MQTT Discovery Protocols", install: true, nextPage: "configuration", uninstall: false) {
dynamicPage(name: "discovery", title: "MQTT Discovery Protocols", nextPage: "configuration") {
section ("<h2><b>MQTT Discovery Protocols > HE </b></h2>(optional)"){
if (settings?.homieDiscovery && settings?.homieDevice!=null) homieEnabled='<font color="green">' else homieEnabled='<font color="darkred">'
if (settings?.HAStatestream && settings?.HAStatestreamTopic!=null) HAEnabled='<font color="green">' else HAEnabled='<font color="darkred">'
if (settings?.SonoffDiscovery) SonoffEnabled='<font color="green">' else SonoffEnabled='<font color="darkred">'
if (settings?.ShellyDiscovery) ShellyEnabled='<font color="green">' else ShellyEnabled='<font color="darkred">'
}
atomicState.onoffDevices = (atomicState.onoffDevices != null)?atomicState.onoffDevices:[]
atomicState.dimDevices = (atomicState.dimDevices != null)?atomicState.dimDevices:[]
atomicState.sensorDevices = (atomicState.sensorDevices != null)?atomicState.sensorDevices:[]
atomicState.buttonDevices = (atomicState.buttonDevices != null)?atomicState.buttonDevices:[]
atomicState.varDevices = (atomicState.varDevices != null)?atomicState.varDevices:[]
atomicState.lockDevices = (atomicState.lockDevices != null)?atomicState.lockDevices:[] //Casey
atomicState.ShellyDevices = (atomicState.ShellyDevices != null)?atomicState.ShellyDevices:[]
atomicState.SonoffDevices = (atomicState.SonoffDevices != null)?atomicState.SonoffDevices:[]
atomicState.HAPresenceDevices = (atomicState.HAPresenceDevices != null)?atomicState.HAPresenceDevices:[]
atomicState.HASwitchDevices = (atomicState.HASwitchDevices != null)?atomicState.HASwitchDevices:[]
atomicState.HALightDevices = (atomicState.HALightDevices != null)?atomicState.HALightDevices:[]
atomicState.HASensorDevices = (atomicState.HASensorDevices != null)?atomicState.HASensorDevices:[]
atomicState.HABinarySensorDevices = (atomicState.HABinarySensorDevices != null)?atomicState.HABinarySensorDevices:[]
atomicState.HAGroupDevices = (atomicState.HAGroupDevices != null)?atomicState.HAGroupDevices:[]
atomicState.HAInputBooleanDevices = (atomicState.HAInputBooleanDevices != null)?atomicState.HAInputBooleanDevices:[]
atomicState.HACoverDevices = (atomicState.HACoverDevices != null)?atomicState.HACoverDevices:[]
atomicState.HALockDevices = (atomicState.HALockDevices != null)?atomicState.HALockDevices:[]
atomicState.HADeviceTrackerDevices = (atomicState.HADeviceTrackerDevices != null)?atomicState.HADeviceTrackerDevices:[]
atomicState.HAClimateDevices = (atomicState.HAClimateDevices != null)?atomicState.HAClimateDevices:[]
atomicState.HAUnknownDevices = (atomicState.HAUnknownDevices != null)?atomicState.HAUnknownDevices:[]
atomicState.homieUnknownDevices = (atomicState.homieUnknownDevices != null)?atomicState.homieUnknownDevices:[]
atomicState.MQTTvirtuals = (atomicState.MQTTvirtuals != null)?atomicState.MQTTvirtuals:[]
numText=''
numhomieDevs=0 // number of homie devices
if (atomicState.onoffDevices != null) numhomieDevs+= atomicState.onoffDevices.size() // these are all homie devices
if (atomicState.dimDevices != null) numhomieDevs+= atomicState.dimDevices.size()
if (atomicState.sensorDevices != null) numhomieDevs+= atomicState.sensorDevices.size()
if (atomicState.lockDevices != null) numhomieDevs+= atomicState.lockDevices.size() //Casey
if (atomicState.buttonDevices != null) numhomieDevs+= atomicState.buttonDevices.size()
if (atomicState.varDevices != null) numhomieDevs+= atomicState.varDevices.size()
if (atomicState.homieUnknownDevices != null) numhomieDevs+= atomicState.homieUnknownDevices.size()
numHADevs=0 // number of homie devices
if (atomicState.HABinarySensorDevices != null) numHADevs+= atomicState.HABinarySensorDevices.size() // these are all homie devices
if (atomicState.HAClimateDevices != null) numHADevs+= atomicState.HAClimateDevices.size()
if (atomicState.HACoverDevices != null) numHADevs+= atomicState.HACoverDevices.size()
if (atomicState.HADeviceTrackerDevices != null) numHADevs+= atomicState.HADeviceTrackerDevices.size() //Casey
if (atomicState.HAGroupDevices != null) numHADevs+= atomicState.HAGroupDevices.size()
if (atomicState.HAInputBooleanDevices != null) numHADevs+= atomicState.HAInputBooleanDevices.size()
if (atomicState.HALightDevices != null) numHADevs+= atomicState.HALightDevices.size()
if (atomicState.HALockDevices != null) numHADevs+= atomicState.HALockDevices.size() //Casey
if (atomicState.HAPresenceDevices != null) numHADevs+= atomicState.HAPresenceDevices.size()
if (atomicState.HASensorDevices != null) numHADevs+= atomicState.HASensorDevices.size()
if (atomicState.HASwitchDevices != null) numHADevs+= atomicState.HASwitchDevices.size()
if (atomicState.HAUnknownDevices != null) numHADevs+= atomicState.HAUnknownDevices.size()
// TODO add more ? .. test for null redundant
def numEnabled=0
if (Homie_onoff!=null) numEnabled += settings?.Homie_onoff.size()
if (Homie_dim!=null) numEnabled += settings?.Homie_dim.size()
if (Homie_sensors!=null) numEnabled += settings?.Homie_sensor.size()
if (Homie_sensors!=null) numEnabled += settings?.Homie_button.size()
if (Homie_sensors!=null) numEnabled += settings?.Homie_variable.size()
if (Homie_sensors!=null) numEnabled += settings?.Homie_unknowns.size()
if (settings?.homieDiscovery){
if (atomicState.started) numText = "${numEnabled} of ${numhomieDevs} discovered devices enabled"
else numText="checking"
}
else {
numText="disabled"
}
section (homieEnabled+"<b>homie</b> [${numText}]</font>", hideable: true, hidden: true){
if (settings?.Homie_onoff != null) ho = settings?.Homie_onoff.size() else ho=0 // Elvis isnt in the house TODO
if (settings?.Homie_dim != null) hd = settings?.Homie_dim.size() else hd=0
if (settings?.Homie_sensor != null) hs = settings?.Homie_sensor.size() else hs=0
if (settings?.Homie_button != null) hb = settings?.Homie_button.size() else hb=0
if (settings?.Homie_variable != null) hv = settings?.Homie_variable.size() else hv=0
if (settings?.Homie_lock != null) hl = settings?.Homie_lock.size() else hl=0
if (settings?.Homie_unknowns != null) hu = settings?.Homie_unknowns.size() else hu=0
input "homieDiscovery", "bool", title: "<b>homie 3 protocol<b>", required: true, defaultValue: false, submitOnChange: false
input name: "homieDevice", type: "text", title: "<b>homie device topic name</b>", description: "... to import devices from", required: false, displayDuringSetup: false
input "Homie_onoff", "enum", multiple: true, title: "<b>Discovered ${atomicState.onoffDevices.size()} homie switches       [^${ho}]</b>", options: atomicState.onoffDevices.sort()
input "Homie_dim", "enum", multiple: true, title: "<b>Discovered ${atomicState.dimDevices.size()} homie dimmers       [^${hd}]</b>", options: atomicState.dimDevices.sort()
input "Homie_sensor", "enum", multiple: true, title: "<b>Discovered ${atomicState.sensorDevices.size()} homie sensors       [^${hs}]</b>", options: atomicState.sensorDevices.sort()
input "Homie_button", "enum", multiple: true, title: "<b>Discovered ${atomicState.buttonDevices.size()} homie buttons       [^${hb}]</b>", options: atomicState.buttonDevices.sort()
input "Homie_variable", "enum", multiple: true, title: "<b>Discovered ${atomicState.varDevices.size()} homie variables       [^${hv}]</b>", options: atomicState.varDevices.sort()
input "Homie_lock", "enum", multiple: true, title: "<b>Discovered ${atomicState.lockDevices.size()} homie locks       [^${hl}]</b>", options: atomicState.lockDevices.sort()
input "Homie_unknowns", "enum", multiple: true, title: "<b>Discovered ${atomicState.homieUnknownDevices.size()} homie devices that are not supported yet       [^${hu}]</b>", options: atomicState.homieUnknownDevices.sort()
}
section {}
numText=''
numEnabled=0
// TODO - below line can still error initially ....alpha
if (HA_Switches!=null) numEnabled = settings?.HA_Switches.size()
if (HA_Lights!=null) numEnabled += settings?.HA_Lights.size()
if (HA_Sensors!=null) numEnabled += settings?.HA_Sensors.size()
if (HA_BinarySensors!=null) numEnabled += settings?.HA_BinarySensors.size()
if (HA_Groups!=null) numEnabled += settings?.HA_Groups.size()
if (HA_Presence!=null) numEnabled += settings?.HA_Presence.size()
if (HA_InputBooleans!=null) numEnabled += settings?.HA_InputBooleans.size()
if (numEnabled>=0) numText = "${numEnabled} of ${numHADevs} enabled"
if (settings?.HAStatestream){
if (atomicState.started) numText = "${numEnabled} of ${numHADevs} discovered devices enabled"
else numText="checking"
}
else {
numText="disabled"
}
section (HAEnabled+"<b>Home Assistant</b> [${numText}]</font>", hideable: true, hidden: true) {
if (settings?.HA_Switches != null) HAsw = settings?.HA_Switches.size() else HAsw=0 // Elvis isnt in the house TODO
if (settings?.HA_Lights != null) HAli = settings?.HA_Lights.size() else HAli=0
if (settings?.HA_Sensors != null) HAse = settings?.HA_Sensors.size() else HAse=0
if (settings?.HA_BinarySensors != null) HAbs = settings?.HA_BinarySensors.size() else HAbs=0
if (settings?.HA_Groups != null) HAg = settings?.HA_Groups.size() else HAg=0
if (settings?.HA_Presence != null) HAp = settings?.HA_Presence.size() else HAp=0
if (settings?.HA_InputBooleans != null) HAib = settings?.HA_InputBooleans.size() else HAib=0
if (settings?.HA_Covers != null) HAco = settings?.HA_Covers.size() else HAco=0
if (settings?.HA_Locks != null) HAlo = settings?.HA_Locks.size() else HAlo=0
if (settings?.HA_DeviceTrackers != null) HAd = settings?.HA_DeviceTrackers.size() else HAd=0
if (settings?.HA_Climates != null) HAcl = settings?.HA_Climates.size() else HAcl=0
input "HAStatestream", "bool", title: "Home Assistant statestream", required: true, defaultValue: false, submitOnChange: true
input name: "HAStatestreamTopic", type: "text", title: "Home Assistant Statestream topic", description: "", required: false, displayDuringSetup: false
input "HA_Switches", "enum", multiple: true, title: "Discovered ${atomicState.HASwitchDevices.size()} Home Assistant switches       [^${HAsw}]", options: atomicState.HASwitchDevices.sort()
input "HA_Lights", "enum", multiple: true, title: "Discovered ${atomicState.HALightDevices.size()} Home Assistant lights       [^${HAli}]" , options: atomicState.HALightDevices.sort()
input "HA_Sensors", "enum", multiple: true, title: "Discovered ${atomicState.HASensorDevices.size()} Home Assistant sensors       [^${HAse}]" , options: atomicState.HASensorDevices.sort()
input "HA_BinarySensors", "enum", multiple: true, title: "Discovered ${atomicState.HABinarySensorDevices.size()} Home Assistant binary sensors       [^${HAbs}]" , options: atomicState.HABinarySensorDevices.sort()
input "HA_Groups", "enum", multiple: true, title: "Discovered ${atomicState.HAGroupDevices.size()} Home Assistant groups       [^${HAg}]" , options: atomicState.HAGroupDevices.sort()
input "HA_Presence", "enum", multiple: true, title: "Discovered ${atomicState.HAPresenceDevices.size()} Home Assistant persons       [^${HAp}]" , options: atomicState.HAPresenceDevices.sort()
input "HA_InputBooleans", "enum", multiple: true, title: "Discovered ${atomicState.HAInputBooleanDevices.size()} Home Assistant input booleans       [^${HAib}]" , options: atomicState.HAInputBooleanDevices.sort()
input "HA_Covers", "enum", multiple: true, title: "Discovered ${atomicState.HACoverDevices.size()} Home Assistant Covers       [^${HAco}]" , options: atomicState.HACoverDevices.sort()
input "HA_Locks", "enum", multiple: true, title: "Discovered ${atomicState.HALockDevices.size()} Home Assistant Locks       [^${HAlo}]" , options: atomicState.HALockDevices.sort()
input "HA_DeviceTrackers", "enum", multiple: true, title: "Discovered ${atomicState.HADeviceTrackerDevices.size()} Home Assistant Device Trackers       [^${HAd}]" , options: atomicState.HADeviceTrackerDevices.sort()
input "HA_Climates", "enum", multiple: true, title: "Discovered ${atomicState.HAClimateDevices.size()} Home Assistant Climate Devices       [^${HAcl}]" , options: atomicState.HAClimateDevices.sort()
input "HA_Unknowns", "enum", multiple: false, title: "Discovered ${atomicState.HAClimateDevices.size()} Home Assistant Devices that are not supported yet       [^${HAcl}]" , options: atomicState.HAUnknownDevices.sort()
}
}
}
def appButtonHandler(btn) {
mqtt = getChildDevice("MQTT: Child device driver")
if (btn=="newVDev") {
createVirtual()
}
else if (btn=="topics") {
atomicState.devTopics=[]
mqtt.subscribeWildcardTopic (atomicState.dTopic)
}
else if (btn=="commit") {
log ("updating the topics","TRACE")
}
else if (btn=="resetMappings") {
atomicState.Mappings=[:]
}
else if (btn=="oldVDev") {
deleteChildDevice(vDev.deviceNetworkId)
log ("Deleted virtual device $vDev","WARN")
}
else if (btn=="editVDev") {
atomicState.edit=true
}
}
//child
def createMQTTclient() { //TODO IP username password
namespace='ukusa'
log ("FYI your MQTT child devices are ${getChildDevices()} ","INFO")
childDev=getChildDevice("MQTT: Child device driver")
if (childDev == null){ //This is a carryover of the client app not being 'selected' anymore in an input dropdown.
log ("Creating MQTT client child driver" , "INFO")
try {
addChildDevice(namespace, "MQTT Client", "MQTT: Child device driver", null,[completedSetup: true,name: "MQTT: Child device driver", logging: false])
log ("MQTT child client created","INFO")
}
catch (e) {
log ("Problem creating child device " + e, "TRACE")
}
//childDev=getChildDevice("MQTT: Child device driver")
//if (childDev == null) log ("MQTT client child was never created" , "ERROR")
}
else log ("MQTT child client already exists","TRACE")
}
//child
def createVirtual () {
if (atomicState.newDevType == "MQTT Text") namespace = 'ukusa' else namespace = 'hubitat'
addChildDevice(namespace, "$atomicState.newDevType", "MQTT:virtual_${atomicState.newDevName}", null,[completedSetup: true,name: "${atomicState.newDevName}", logging: false])
childDev=getChildDevice("MQTT:virtual_${atomicState.newDevName}") //hmm seems childDevice is not a device object
if (childDev == null) log ("Child was never created" + prefix+name , "ERROR")
else log ("Created Child $atomicState.newDevType with name $atomicState.newDevName","INFO")
childDev.updateDataValue("mqtt", "manual")
childDev.updateDataValue("origin", "user")
if (childDev.typeName.contains("Sensor")||childDev.typeName.contains("Presence")) sensor=true else sensor=false
childDev.capabilities.each { cap ->
log ("Found $cap in childDev $childDev.displayName","INFO")
cap.attributes.each { attr ->
log ("Found attribute $attr in $childDev.displayName [$cap]", "INFO")
att="$attr"
data=att+"_Topic"
if ((childDev.getDataValue(data))&&(childDev.getDataValue(data)!=" ")){
log ("$childDev.displayName data $data already exists","DEBUG")
if (att=='level') {
if (!childDev.getDataValue("max_Level")) childDev.updateDataValue("max_Level", "100")
}
}
else {
childDev.updateDataValue(data, " ") // Have to add a space here so that data displays in my editor
log ("Adding data $data to $childDev.displayName","INFO")
if (att=='level') childDev.updateDataValue("max_Level", "100")
}
if (!sensor) {
data=att+"_Cmd"
if ((childDev.getDataValue(data))&&(childDev.getDataValue(data)!=" ")){
log ("$childDev.displayName data $data already exists","DEBUG")
}
else {
childDev.updateDataValue(data, " ")
log ("Adding data $data to $childDev.displayName","INFO")
}
}
}
}
attr2List=childDev.getSupportedAttributes()
for (j = 1; j < attr2List.size(); j++) {
if (attr2List[j].dataType =="ENUM") {
String atts = "${attr2List[j].getPossibleValues()}"
if ((childDev.getDataValue("${attr2List[j]}_MAP"))&&(childDev.getDataValue("${attr2List[j]}_MAP")!=" ")){
log ("$childDev.displayName ${attr2List[j]}_MAP already exists","TRACE")
}
else {
log ("Adding the default attribute values to ${attr2List[j]}_MAP","KH")
atts=atts.trim()
childDev.updateDataValue("${attr2List[j]}_MAP", atts.replace(', ', ','))
}
}
else log ("Attribute was not ENUM [${attr2List[j]}] $attr2List[j].dataType", "INFO")
} // end for
if (atomicState.newDevType == "MQTT Text") {
childDev.updateDataValue("text_Topic", "") // This attribute is not discovered within capability as it is custom
childDev.updateDataValue("text_Cmd", "")
}
}
def installed() {
log ( "${app.name} Installed","INFO")
//createMQTTclient()
atomicState.topicMap=[:]
atomicState.nameMap=[:]
//createMQTTclient()
wipe() // also initialises
initialize()
atomicState.appCount=0
}
def updated() {
log ("${app.name} Updated", "INFO")
unsubscribe()
//createMQTTclient()
atomicState.count=0
unschedule()
initialize()
}
def uninstalled() {
log ("Deleting all child devices", "WARN")
wipe()
removeAllChildDevices()
}
def reStart(evt) {
log ("===================== ReStart =====================", "INFO")
atomicState.restartPending=false
unschedule()
unsubscribe()
initialize()
}
def initialize() {
mqtt = getChildDevice("MQTT: Child device driver")
if (mqtt==null) {
createMQTTclient()
mqtt = getChildDevice("MQTT: Child device driver")
if (mqtt==null) log ("MQTT client failed to create","ERROR")
}
else log ("MQTT Client driver present","INFO")
atomicState.normHubName = normalize(settings?.hubName)
log ("Hubitat hub name is : " + settings?.hubName,"INFO")
if (mqtt==null) {
log ("FATAL: No MQTT broker configured","ERROR")
}
else {
mqtt.setHubName (normalize(settings?.hubName),settings?.hubName)
mqtt.setUserName (settings?.username)
mqtt.setPassword (settings?.password)
mqtt.setBrokerAddress (settings?.MQTTBroker)
}
if (atomicState.appcount==null) atomicState.appCount=0
log ("initialising with App count ${atomicState.appCount}","INFO")
def date1 = new Date()
atomicState.properties=[:]
atomicState.topicLink=[:]
//log.e(location.hubs[0].getZigbeeId())
atomicState.myHub=false
// This just enables more logging on my own hubs
myID=MD5(app.getHubUID())
if (myID=="d36ba7352b7fc675e7314162377a88be") atomicState.myHub=true //41
else if (myID=="8e703d9adefe69d652315cf6159671b7") atomicState.myHub=true //42
else if (myID=="e947798518d8f4b041d701d122c38b30") atomicState.myHub=true //44
else if (myID=="1234") atomicState.myHub=true //43 TODO UPDATE THIS ONE
//atomicState.myHub=false
countTry=5
aborting=false
atomicState.abort=false // just added remove later
//if (atomicState.abortable) atomicState.abort=true // JUST TO TEST - will abort if still possible
while (atomicState.abort) {
log("Awaiting earlier App to abort [$countTry]","WARN")
aborting=true