forked from GaryMilne/Hubitat-Tasmota
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Universal_Multi_Sensor.groovy.1.0.3
1968 lines (1670 loc) · 121 KB
/
Universal_Multi_Sensor.groovy.1.0.3
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
/**
* Tasmota Sync Universal Multi Sensor with configurable relays
* Version: v1.0.3
* Download: See importUrl in definition
* Description: Hubitat Driver for Tasmota Sensors. Provides Realtime and native synchronization between Hubitat and Tasmota
*
* Copyright 2022 Gary J. Milne
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This driver is one of several in the Tasmota Sync series. All of these drivers are architecturally similar and much of the code is identical.
* To simplifiy maintenance all of these drivers have two sections. Search for the phrase "END OF UNIQUE FUNCTIONS" to find the split.
* #1 The top section contains code that is UNIQUE to a specific driver such as a bulb vs a switch vs a dimmer. Although this code is UNIQUE it is very similar between drivers.
* #2 The bottom section is code that is IDENTICAL and shared across all drivers and is about 700 - 800 lines of code. This section of code is referred to as CORE.
*
* UNIVERSAL SENSOR with RELAYS - UNIQUE - CHANGELOG
* Version 0.91 - Internal version
* Version 0.92 - Added fixed logic for extracting for sensor SI7102
* Version 0.93 - Virtualized the name of the sensor and added it to settings.
* Version 0.93B - Fixed error in RULE3 where sensorname was not virtualized to the settings.sensorName but accidentally used an embedded string.
* Version 0.94 - Added support for a broad range of sensors and capabilities. Driver will look for any data in sensor field and populate the attribute if found.
* Version 0.95 - Changed sensor methodology to iterate all sensor fields, pair them with Hubitat attributes and update the data accordingly. Theoretically this makes the driver capable of working with any type of sensor and any data field with only adding a few names to the sensorMap FIELDS.
* Version 0.96.0 - Changed versioning to comply with Semantic Versioning standards (https://semver.org/). Moved CORE changelog to beginning of CORE section. Added links
* Version 0.98.0 - All versions incremented and synchronised for HPM plublication
* Version 0.98.1 - Added definitions for PM2.5 sensor data. Add logic to statusResponse() to handle a STATUSSNS "switch1" field used by some sensors.
* Version 0.98.11 - Added definitions for ANALOG sensor data. Added map for "RANGE" to "range" which is used by analog inputs.
* Version 0.98.3 - Virtualized all sensor and trigger names
* Version 0.98.4 - Added support for load sensors
* Version 0.98.5 - Added capability to evaluate sensor output for testing
* Version 0.99.1 - Added support to handle ANALOG CTENERGY JSON inputs
* Version 0.99.2 - Added support to handle two TEMPERATURE sensors. Reporting as temperature and temperature1.
* Version 0.99.3 - Added function adjustBody for pre-processing of ANALOG JSON inputs as well as de-duping Temperature fields.
* Version 0.99.31 - Changed handling for sensors and trigger mapping.
* Version 0.99.4 - Added a sorted sensorAttributes list to provide visual confirmation of mapping between sensors and attributes
* Version 0.99.51 - Added support for 2 x relays\switches to the Universal Multi Sensor Code. Linked switch and switch1 attributes together.
* Version 1.0.0 - Initial public release.
* Version 1.0.1 - Incremented Core 0.98.2.
* Version 1.0.2 - Fixed an issue with the handling of sensor switches 3 and 4 that were reporting 1 and 0 instead of on and off.
* Version 1.0.3 - Added definitions for Tasmota Counters C1, C2, C3 and C4.
*
* Authors Notes:
* For more information on Tasmota Sync drivers check out these resources:
* Original posting on Hubitat Community forum. https://community.hubitat.com/t/tasmota-sync-drivers-native-and-real-time-synchronization-between-hubitat-and-tasmota-11/93651
* How to upgrade from Tasmota 8.X to Tasmota 11.X https://github.com/GaryMilne/Hubitat-Tasmota/blob/main/How%20to%20Upgrade%20from%20Tasmota%20from%208.X%20to%2011.X.pdf
* Tasmota Sync Installation and Use Guide https://github.com/GaryMilne/Hubitat-Tasmota/blob/main/Tasmota%20Sync%20Documentation.pdf
* Tasmota Sync Sensor Driver https://github.com/GaryMilne/Hubitat-Tasmota/blob/main/Tasmota%20Sync%20Sensor%20Documentation.pdf
*
* Gary Milne - October 3rd, 2023
*
**/
import groovy.json.JsonSlurper
import groovy.transform.Field
//This determines the number of power relays that will appear within the device. These will always be switch1 and switch2 and should be configured as such in Tasmota.
//The device may also have additional sensors that act like switches. These should be configured as switch3 and switch4 in Tasmota if present.
@Field static final Integer switchCount = 0
sensorType = "All"
//sensorType = "Common" //Includes AirQuality, Energy and Environmental.
//sensorType = "Accelerometer"
//sensorType = "AirQuality"
//sensorType = "Analog"
//sensorType = "Chemical"
//sensorType = "Counters"
//sensorType = "Energy"
//sensorType = "Environmental"
//sensorType = "Flow"
//sensorType = "IR"
//sensorType = "IO"
//sensorType = "Light_Gesture_Sensor"
//sensorType = "Load"
//sensorType = "NFC"
//sensorType = "Rain"
//sensorType = "RF"
//First item in the pair is the name of the Tasmota sensor data type in uppercase form. The second name is the driver attribute that will contain the data. They may be identical in some case and very different in others.
@Field static final sensor2AttributeMap = ['TEMPERATURE' : 'temperature', 'TEMPERATURE1' : 'temperature1', 'TEMPERATURE2' : 'temperature2', 'TEMPERATURE3' : 'temperature3', 'HUMIDITY' : 'humidity',
'ACCELXAXIS' : 'accelXAxis' , 'ACCELYAXIS' : 'accelYAxis' , 'ACCELZAXIS' : 'accelZAxis' , 'GYROXAXIS' : 'gyroXAxis', 'GYROYAXIS' : 'gyroYAxis', 'GYROZAXIS' : 'gyroZAxis' , 'YAW' : 'yaw', 'PITCH' : 'pitch', 'ROLL' : 'roll', //Accelerometer - Gyro
'AIRQUALITYINDEX' : 'airQualityIndex', 'ECO2' : 'ECO2', 'ECO' : 'ECO', 'PM2.5' : 'pm25' , 'RESISTANCE' : 'resistance', 'TVOC' : 'tvoc', //Air Quality
'RANGE' : 'range', //Analog input
'PH' : 'pH', //Chemical
'DISTANCE' : 'distance', //Physical
'CURRENT' : 'current', 'POWER' : 'power' , 'VOLTAGE' : 'voltage', 'TOTAL' : 'total', 'YESTERDAY' : 'yesterday', 'TODAY' : 'today', 'APPARENTPOWER' : 'apparentPower', 'REACTIVEPOWER' : 'reactivePower' , 'FACTOR' : 'factor', 'FREQUENCY' : 'frequency', 'PERIOD' : 'period', 'TOTALSTARTTIME' : 'totalStartTime', //Electrical Energy
'DEWPOINT' : 'dewPoint', 'ILLUMINANCE' : 'illuminance' , 'PRESSURE' : 'pressure', 'GAS' : 'gas', 'ULTRAVIOLET' : 'ultraViolet', 'SOUNDPRESSURELEVEL' : 'soundPressureLevel', //Environmental
'FLOW' : 'rate', //Flow
'D0' : 'd0', 'D1' : 'd1', 'D2' : 'd2', 'D3' : 'd3', 'D4' : 'd4', 'D5' : 'd5', 'D6' : 'd6', 'D7' : 'd7', 'MS' : 'ms', // I/O Expansion
'PROTOCOL' : 'protocol', 'BITS' : 'bits', 'DATA' : 'data', //Infra Red
'RED' : 'red', 'BLUE' : 'blue', 'GREEN' : 'green', 'AMBIENT' : 'ambient', 'CCT' : 'cct' , 'PROXIMITY' : 'proximity', //Some kind of gesture sensor.
'OBJTMP' : 'objTmp', 'AMBTMP' : 'ambTmp', //Infra Red Thermometer
'EVENT' : 'event' , 'ENERGY' : 'energy', 'STAGE' : 'stage', //Lightning sensor. Note that distance is also part of lightning but is already defined.
'WEIGHT' : 'weight' , 'WEIGHTRAW' : 'weightRaw' , 'ABSRAW' : 'absRaw', //Load Sensor
'UID' : 'uid', //NFC. Note that data is also a part of NFC but has already been defined elsewhere.
'ACTIVE' : 'active', 'FLOWRATE' : 'flowRate', //Rain. Note that event and total are also part of RAIN but are defined elsewhere.
'PULSE' : 'pulse', //RF sensor. Note that data, bits and protocol are all defined elsewhere.
'TYPE' : 'type', //RFID. Note that uid and data are defined elsewhere.
'SWITCH' : 'switch', 'SWITCH1' : 'switch1', 'SWITCH2' : 'switch2', 'SWITCH3' : 'switch3', 'SWITCH4' : 'switch4', //Switches
'C1':'C1', 'C2':'C2', 'C3':'C3', 'C4':'C4'
]
//These are the types of fields that the driver will attempt to de-dupe. For example 3 temperature sensors would end up as temperature, temperature1, temperature2.
@Field static final deDupeList = ["TEMPERATURE","HUMIDITY"]
//If a Tasmota device has one of these fields in its StatusSNS then a Trigger will be created for that field.
@Field static final triggerEligibleList = ['TEMPERATURE', 'TEMPERATURE1', 'TEMPERATURE2', 'TEMPERATURE3', 'HUMIDITY', 'DEWPOINT',
'ACCELXAXIS', 'ACCELYAXIS', 'ACCELZAXIS', 'GYROXAXIS', 'GYROYAXIS', 'GYROZAXIS', 'YAW', 'ROLL', 'PITCH', //Accelerometer - Gyro
'AIRQUALITYINDEX', 'ECO2', 'ECO', 'PM2.5', 'RESISTANCE', 'TVOC', //Air Quality
'ANALOG', 'RANGE', //Analog inputs
'PH', //Chemical
'DISTANCE', //Physical
'CURRENT', 'POWER', 'VOLTAGE', //Electrical Energy
'ILLUMINANCE', 'PRESSURE', 'GAS', 'ULTRAVIOLET', 'SOUNDPRESSURELEVEL', //Environmental
'FLOW', //Flow
'D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', // I/O Expansion
'DATA', //Multiple
'RED', 'BLUE', 'GREEN', 'AMBIENT', 'CCT', 'PROXIMITY', //Some kind of gesture sensor.
'OBJTMP', 'AMBTMP', //Infra Red Thermometer
'EVENT', 'STAGE', 'ENERGY', //Lightning sensor. Note that distance is also part of lightning but is already defined.
'WEIGHT', 'WEIGHTRAW', 'ABSRAW', //Load Sensor
//NFC. Note that data is also a part of NFC but has already been defined elsewhere.
'ACTIVE', 'FLOWRATE', //Rain. Note that event and total are also part of RAIN but are defined elsewhere.
'PULSE', //RF sensor. Note that data, bits and protocol are all defined elsewhere.
'C1', 'C2','C3','C4' //These are the variables used for Tasmota counters.
]
//First item in the pair is the name of the Tasmota sensor data type in uppercase form. The second name is the name of the driver unit attribute for that type of data. For example 'tempUnit' will contain either a 'C' or 'F' if temperature is a valid data field.
@Field static final sensor2UnitMap = ['TEMPERATURE' : 'tempUnit', 'PRESSURE' : 'pressureUnit', 'SPEED' : 'speedUnit']
//First item in the pair is the name of the Tasmota sensor in uppercase form. The second name is suffix commonly associated with this type of data. For examples, degrees (°) applies to both C and F. Currently these suffixes are only used for event log entries.
@Field static final sensor2UnitSuffix = ['TEMPERATURE' : 'Degrees', 'TEMPERATURE1' : 'Degrees', 'TEMPERATURE2' : 'Degrees','TEMPERATURE3' : 'Degrees','HUMIDITY' : '% RH', 'DEWPOINT' : 'Degrees', 'ILLUMINANCE' : 'lux', 'PM2.5' : 'µg/M³']
//Tasmota<<-->>Hubitat discrepancies. This driver uses the Tasmota names but will mirror those values to the expected Hubitat attributes. First value is tasmota name followed by the Hubitat attribute
//This feature is not yet in use.
@Field static final mirroredAttributes = ['POWER' : 'energy', 'CURRENT' : 'amperage', 'ECO' : 'carbonMonoxide' , 'ECO2' : 'carbonDioxide' , 'FLOW' : 'rate']
metadata {
definition (name: "Tasmota Sync - Universal Multi Sensor", namespace: "garyjmilne", author: "Gary J. Milne", importUrl: "https://raw.githubusercontent.com/GaryMilne/Hubitat-Tasmota/main/Universal_Multi_Sensor.groovy", singleThreaded: true ) {
//definition (name: "Tasmota Sync - Universal Multi Sensor Single Relay", namespace: "garyjmilne", author: "Gary J. Milne", importUrl: "https://raw.githubusercontent.com/GaryMilne/Hubitat-Tasmota/main/Universal_Multi_Sensor_Single_Relay.groovy", singleThreaded: true ) {
//definition (name: "Tasmota Sync - Universal Multi Sensor Double Relay", namespace: "garyjmilne", author: "Gary J. Milne", importUrl: "https://raw.githubusercontent.com/GaryMilne/Hubitat-Tasmota/main/Universal_Multi_Sensor_Double_Relay.groovy", singleThreaded: true ) {
//capability "LiquidFlowRate"
//capability "PressureMeasurement"
capability "Refresh"
capability "Sensor"
command "initialize"
command "tasmotaInjectRule", [[name:"Creates and inserts Rule3 to the Tasmota device. Required for updates to be sent from Tasmota to Hubitat."]]
command "tasmotaCustomCommand", [ [name:"Enter valid Tasmota command and optional parameter.*", type: "STRING", description: "A single word command to be issued such as COLOR, CT, DIMMER etc."], [name:"Parameter", type: "STRING", description: "A single parameter that accompanies the command such as FFFFFFFF, 350, 75 etc."] ]
command "tasmotaTelePeriod", [ [name:"Period between Tasmota telemetry updates in seconds (10-3600).*", type: "STRING", description: "The number of seconds between Tasmota data updates (TelePeriod XX)."] ]
command "evaluateSensorData", [ [name:"Paste Tasmota STATUS 8 output here to test compatibility.*", type: "STRING", description: "The STATUS 8 output from a Tasmota device in the form {\"STATUSSNS\":{\"Time\": \"2019-11-03T19:34:28\",\"BME280\": {\"Temperature\": 21.7,\"Humidity\": 66.6,\"Pressure\": 988.6},\"PressureUnit\": \"hPa\",\"TempUnit\": \"C\"}}}" ] ]
command "clearAttributes", [[name:"Clears all of the Attributes. Do browser refresh."]]
command "refresh", [[name:"Requests current sensor and switch settings from Tasmota."]]
//command "test"
capability "TemperatureMeasurement"
capability "RelativeHumidityMeasurement"
//Attributes do not display in the Attribute State when they are null.
//It does not seem to matter if an attribute is declared multiple times.
//Adding a new attribute for sensor use should also be accompanied by entries in the sensor2AttributeMap, sensor2UnitMap and sensor2UnitSuffix
attribute "Status", "string"
log.info ("SwitchCount is: ${switchCount}")
//switch1 and switch2 Reserved for power relays
if (switchCount >= 1) {
attribute "switch", "string"
attribute "switch1", "string"
capability "Switch"
command "on", [[name:"'On' and 'Switch1 On' are the same. Attr switch & switch1 synchronized."]]
command "off", [[name:"'Off' and 'Switch1 Off' are the same. Attr switch & switch1 synchronized."]]
command "toggle", [[name:"Note: Reverses the state of switch\\switch1."]]
command "switch1On", [[name:"Same as 'On'. Turns on Tasmota Switch 1. (POWER1 ON)"]]
command "switch1Off", [[name:"Same as 'Off' Turns off Tasmota Switch 1. (POWER1 OFF)"]]
}
if (switchCount == 2) {
attribute "switch2", "string"
command "switch2On", [[name:"Turns on Tasmota Switch 2. (POWER2 ON)"]]
command "switch2Off", [[name:"Turns off Tasmota Switch 2. (POWER2 OFF)"]]
}
//Descriptors. These are at the top level of the STATUSSNS message.
attribute "switch3", "string" //Reserved for Tasmota sensors. example: Some "SENSOR" devices act like a switch such as a motion detector. '{"STATUSSNS":{"Time":"2022-01-07T19:43:24","Switch3":"ON","Switch4":"ON","TempUnit":"C"}}'
attribute "switch4", "string" //Reserved for Tasmota sensors. example: Some "SENSOR" devices act like a switch such as a motion detector. '{"STATUSSNS":{"Time":"2022-01-07T19:43:24","Switch3":"ON","Switch4":"ON","TempUnit":"C"}}'
attribute "pressureUnit", "string" //Tasmota example: {"Time": "2019-11-03T19:34:28","BME280": {"Temperature": 21.7,"Humidity": 66.6,"Pressure": 988.6},"PressureUnit": "hPa","TempUnit": "C"} - Change with SetOption24
attribute "tempUnit", "string" //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"} - Change with SetOption8. off is celsius and on is fahrenheit. Must do a refresh to update Hubitat.
attribute "speedUnit", "string" //Tasmota example: '{"Time": "2020-03-03T00:00:00+00:00","TX23": {"Speed": {"Act": 14.8,"Avg": 8.5,"Min": 12.2,"Max": 14.8},"Dir": {"Card": "WSW","Deg": 247.5,"Avg": 266.1,"AvgCard": "W","Min": 247.5,"Max": 247.5,"Range": 0}},"SpeedUnit": "km/h"}}}'
log.info ("Tasmota Sync - Universal Multi Sensor Driver reloaded with sensor type ${sensorType}")
//Accelerometer - '{"STATUSSNS":{"Time":"2019-12-10T19:37:50","MPU6050":{"Temperature":27.7,"AccelXAxis":-7568.00,"AccelYAxis":-776.00,"AccelZAxis":12812.00,"GyroXAxis":270.00,"GyroYAxis":-741.00,"GyroZAxis":700.00},"TempUnit":"C"}}'
if ( sensorType == "All" || sensorType == "Accelerometer") {
attribute "accelXAxis", "string" ; attribute "accelYAxis", "string" ; attribute "accelXAxis", "string" ; attribute "gyroXAxis", "string" ; attribute "gyroYAxis", "string"
attribute "gyroZAxis", "string" ; attribute "yaw", "string" ; attribute "pitch", "string" ; attribute "roll", "string"
}
//Air Quality - '{"STATUSSNS":{"Time":"2020-01-01T00:00:00","IAQ":{"eCO2":450,"TVOC":125,"Resistance":76827}}}'
if ( sensorType == "All" || sensorType == "AirQuality" || sensorType == "Common" ) {
capability "AirQuality"
capability "CarbonDioxideMeasurement"
attribute "airQualityIndex", "number" //range 0 - 500
attribute "eCO", "number" //Carbon Monoxide
attribute "eCO2", "number" //Carbon Dioxide
attribute "pm25", "number" //unit µg/M³
attribute "resistance", "number"
attribute "tvoc", "number"
//Extra attributes for compatibility with Hubitat capabilities
attribute "carbonDioxide", "number" //unit ppm carbonDioxide - NUMBER, unit:ppm
attribute "carbonMonoxide", "string" //unit carbonMonoxide - ENUM ["clear", "tested", "detected"]
}
//ANALOG - '{"StatusSNS":{"Time":"2022-05-26T00:34:18","ANALOG":{"Range":9}}}'
if ( sensorType == "All" || sensorType == "ANALOG") {
attribute "range", "number" //unit variable as this may be an analog input representing many unique things. //Tasmota example: {"StatusSNS":{"Time":"2022-05-26T00:34:18","ANALOG":{"Range":9}}}
//CTEnergy - {"STATUSSNS":{"TIME":"2022-06-26T22:06:56","ANALOG":{"CTENERGY":{"ENERGY":2.882,"POWER":49,"VOLTAGE":230,"CURRENT":0.215}}}}.
attribute "energy", "number"
attribute "power", "number"
attribute "voltage", "number"
attribute "current", "number"
}
//Chemical
if ( sensorType == "All" || sensorType == "Chemical") {
capability "pHMeasurement" ; attribute "pH", "number"
}
//Tasmota Counters
if ( sensorType == "All" || sensorType == "Counters") {
attribute "C1", "number"
attribute "C2", "number"
attribute "C3", "number"
attribute "C4", "number"
}
//Distance
if ( sensorType == "All" || sensorType == "Distance") {
attribute "distance", "number" //unit none provided
}
//Energy
if ( sensorType == "All" || sensorType == "Energy" || sensorType == "Common" ) {
capability "PowerMeter"
capability "VoltageMeasurement"
capability "CurrentMeter"
attribute "current", "number" ; attribute "power", "number" ; attribute "voltage", "number" ; attribute "total", "number" ; attribute "yesterday", "number"
attribute "today", "number" ; attribute "apparentPower", "number" ; attribute "reactivePower", "number" ; attribute "factor", "number" ; attribute "frequency", "number"
attribute "period", "number" ; attribute "totalStartTimePeriod", "string"
//Extra attributes for compatibility with Hubitat capabilities
attribute "amperage", "number" //Unit A
attribute "energy", "number" //Unit W
}
//Environmental
if ( sensorType == "All" || sensorType == "Environmental" || sensorType == "Common" ) {
capability "IlluminanceMeasurement"
capability "SoundPressureLevel"
capability "UltravioletIndex"
attribute "dewPoint", "number" //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"} - Change with SetOption8. off is celsius and on is fahrenheit. Must do a refresh to update Hubitat.
attribute "illuminance", "number" //unit lx //Tasmota example: {"Time":"2019-11-03T20:45:37","BH1750":{"Illuminance":79}} {"Time":"2019-11-03T21:04:05","TSL2561":{"Illuminance":21.180}}
attribute "pressure", "number" //unit hPa || mmHg //Tasmota example: {"Time": "2019-11-03T19:34:28","BME280": {"Temperature": 21.7,"Humidity": 66.6,"Pressure": 988.6},"PressureUnit": "hPa","TempUnit": "C"}
attribute "gas", "number" //Seems to be the same as tvoc. '{"STATUSSNS":{"Time": "2021-09-22T17:00:00","BME680": {"Temperature": 24.5,"Humidity":33.0,"DewPoint": 7.1,"Pressure": 987.7,"Gas": 1086.43 },"PressureUnit": "hPa","TempUnit": "C"}}'
attribute "ultravioletIndex", "number" //unit none provided
attribute "soundPressureLevel", "number" //unit dB
//Attributes. These are usually at the sensor level of the STATUSSNS message.
attribute "humidity", "number" //unit %rh //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"}
attribute "temperature", "number" //unit F || C //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"}
attribute "temperature1", "number" //unit F || C //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"}
attribute "temperature2", "number" //unit F || C //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"}
attribute "temperature3", "number" //unit F || C //Tasmota example: {"Time":"2022-05-17T03:33:05","SI7021":{"Temperature":69,"Humidity":28,"DewPoint":34},"TempUnit":"F"}
}
//Flow
if ( sensorType == "All" || sensorType == "Flow") {
capability "LiquidFlowRate" ; attribute "rate", "number"
}
//IO - '{"STATUSSNS":{"Time":"2018-08-18T16:13:47","MCP230XX": "D0":0,"D1":0,"D2":1,"D3":0,"D4":0,"D5":0,"D6":0,"D7":1}}}'
if ( sensorType == "All" || sensorType == "IO") {
attribute "d0", "number" ; attribute "d1", "number" ; attribute "d2", "number" ; attribute "d3", "number" ; attribute "d4", "number" ; attribute "d5", "number" ; attribute "d6", "number" ; attribute "d7", "number" ; attribute "ms", "number"
}
//IR - '{"STATUSSNS":{"Time": "2019-01-01T00:00:00","IrReceived": {"Protocol": "NEC","Bits": 32,"Data": "0x00FF00FF"}}}'
if ( sensorType == "All" || sensorType == "IR") {
attribute "protocol", "string" ; attribute "bits", "number" ; attribute "data", "string"
}
//Infra-Red (Far) Thermometer -'{"STATUSSNS":{"Time":"2019-11-11T00:03:30","MLX90614":{"OBJTMP":23.8,"AMBTMP":22.7}}}'
if ( sensorType == "All" || sensorType == "IR_Thermometer") {
attribute "objTmp", "number" ; attribute "ambTmp", "number"
}
//Light_Gesture_Sensor - '{"STATUSSNS":{"Time":"2019-10-31T21:48:51","APDS9960":{"Red":282,"Green":252,"Blue":196,"Ambient":169,"CCT":4217,"Proximity":9}}}'
if ( sensorType == "All" || sensorType == "Light_Gesture_Sensor") {
attribute "red", "number" ; attribute "green", "number" ; attribute "blue", "number" ; attribute "ambient", "number" ; attribute "cct", "number" ; attribute "proximity", "number"
}
//Lightning Sensor - '{"STATUSSNS":{"Time":"2020-01-01T17:07:07","AS3935":{"Event":4,"Distance":12,"Energy":58622,"Stage":1}}}'
if ( sensorType == "All" || sensorType == "Lightning") {
attribute "event", "number" ; attribute "distance", "number" ; attribute "energy", "number" ; attribute "stage", "number"
}
//Load Sensor - '{"StatusSNS":{"Time":"2022-06-11T10:58:18","HX711":{"Weight":0,"WeightRaw":4782,"AbsRaw":110004}}}'
if ( sensorType == "All" || sensorType == "Load") {
attribute "weight", "number" ; attribute "weightRaw", "number" ; attribute "absRaw", "number"
}
//NFC - '{"STATUSSNS":{"Time":"2019-01-10T18:31:39","PN532":{"UID":"94D8FC5F", "DATA":"ILOVETASMOTA"}}}'
if ( sensorType == "All" || sensorType == "NFC") {
attribute "uid", "string" ; attribute "data", "string"
}
//Rain - '{"STATUSSNS":{"Time": "2021-08-25T17:15:45","RG-15": {"Active": 0.01,"Event": 0.13,"Total": 26.80,"FlowRate": 0.32},"TempUnit": "C"}}'
if ( sensorType == "All" || sensorType == "Rain") {
attribute "active", "number" ; attribute "event", "number" ; attribute "total", "number" ; attribute "flowRate", "number"
}
//RF - '{"STATUSSNS":{"Time": "2019-01-01T00:00:00","RfReceived": {"Data": "0x7028D5","Bits": 24,"Protocol": 1,"Pulse": 238}}}'
if ( sensorType == "All" || sensorType == "RF") {
attribute "data", "string" ; attribute "bits", "number" ; attribute "protocol", "number" ; attribute "pulse", "number"
}
//RFID - '{"STATUSSNS":{"Time":"2021-01-23T13:10:50","RC522":{"UID":"BA839D07","Data":"","Type":"MIFARE 1KB"}}}'
if ( sensorType == "All" || sensorType == "RFID") {
attribute "uid", "string" ; attribute "data", "string" ; attribute "type", "string"
}
section("Configure the Inputs"){
input name: "destIP", type: "text", title: bold(dodgerBlue("Tasmota Device IP Address")), description: italic("The IP address of the Tasmota device."), defaultValue: "192.168.0.X", required:true, displayDuringSetup: true
input name: "HubIP", type: "text", title: bold(dodgerBlue("Hubitat Hub IP Address")), description: italic("The Hubitat Hub Address. Used by Tasmota rules to send HTTP responses."), defaultValue: "192.168.0.X", required:true, displayDuringSetup: true
input name: "timeout", type: "number", title: bold("Timeout for Tasmota reponse."), description: italic("Time in ms after which a Transaction is closed by the watchdog and subsequent responses will be ignored. Default 5000ms."), defaultValue: "5000", required:true, displayDuringSetup: false
input name: "debounce", type: "number", title: bold("Debounce Interval for Tasmota Sync."), description: italic("The period in ms from command invocation during which a Tasmota Sync request will be ignored. Default 7000ms."), defaultValue: "7000", required:true, displayDuringSetup: false
if (switchCount == 2) {
input name: "switchBehaviour", type: "enum", title: bold("Switch Behaviour."), description: italic("Whether the primary Switch affects only Relay 1 or ALL Relays."),
options: [ [1:"Turns ON\\OFF only Power1"],[2:"Turns ON\\OFF ALL Power Relays"] ], defaultValue: 1
}
input name: "logging_level", type: "number", title: bold("Level of detail displayed in log"), description: italic("Enter log level 0-3. (Default is 0.)"), defaultValue: "0", required:true, displayDuringSetup: false
input name: "loggingEnhancements", type: "enum", title: bold("Logging Enhancements."), description: italic("Allows log entries for this device to be enhanced with HTML tags for increased increased readability. (Default - All enhancements.)"),
options: [ [0:" No enhancements."],[1:" Prepend log events with device name."],[2:" Enable HTML tags on logged events for this device."],[3:" Prepend log events with device name and enable HTML tags." ] ], defaultValue: 3, required:true
input name: "pollFrequency", type: "enum", title: bold("Poll Frequency. Polling not required if using Tasmota Sync on Tasmota 11 or later."), description: italic("The time between Hubitat initiated synchronisation of values with Tasmota. Tasmota is considered authoritative (Default - 0 (Never) )"),
options: [ [0:" Never"],[60:" 1 minute"],[300:" 5 minutes"],[600:"10 minutes"],[900:"15 minutes"],[1800:"30 minutes"],[3600:" 1 hour"],[10800:" 3 hours"] ], defaultValue: 0
input name: "destPort", type: "text", title: bold("Port"), description: italic("The Tasmota webserver port. Only required if not at the default value of 80."), defaultValue: "80", required:false, displayDuringSetup: true
input name: "username", type: "text", title: bold("Tasmota Username"), description: italic("Tasmota username is required if configured on the Tasmota device."), required: false, displayDuringSetup: true
input name: "password", type: "password", title: bold("Tasmota Password"), description: italic("Tasmota password is required if configured on the Tasmota device."), required: false, displayDuringSetup: true
input name: "note", type: "text", title: bold("Notes on this device"), description: italic("Use this field to store any notes. ie switch3 is PIR, temp is outside, temp1 is attic."), required: false, displayDuringSetup: true
}
}
}
//Function used for quickly testing out SENSOR logic when I don't actually have the sensor.
//Remember Tasmota Sensor Switches should be configured as Switch3 and Switch4 if present.
def test(){
//To test out a sensor paste the result of STATUS 8
//Many of these are taken from https://tasmota.github.io/docs/Supported-Peripherals/ Others are from first hand experience or submitted by Hubitat users.
//body = '{"StatusSNS":{"Time":"2022-05-25T10:26:47","VINDRIKTNING":{"PM2.5":2}}}'
//body = '{"StatusSNS":{"Time":"2022-05-25T10:23:58","Switch3":"ON","VINDRIKTNING":{"PM2.5":17}}}'
///body = '{"StatusSNS":{"Time":"2022-05-26T00:34:18","ANALOG":{"Range":9}}}'
//body = '{"StatusSNS":{"Time":"2022-05-26T17:14:10","Switch3":"ON","ANALOG":{"Range":9},"SI7021":{"Temperature":63,"Humidity":49,"DewPoint":44},"IAQ":{"eCO2":450,"TVOC":125,"Resistance":76827},"PressureUnit": "hPa","TempUnit": "C"}}'
///body = '{"StatusSNS":{"Time":"2022-05-27T02:18:25","SI7021":{"Temperature":67,"Humidity":39,"DewPoint":41},"TempUnit":"F"}}'
//body = '{"StatusSNS":{"Time":"2022-05-27T21:23:35","ENERGY":{"TotalStartTime":"2022-03-10T23:36:04","Total":4.247,"Yesterday":0.054,"Today":0.111,"Power": 7,"ApparentPower":13,"ReactivePower":11,"Factor":0.57,"Voltage":122,"Current":0.11}}}'
///body = '{"STATUSSNS":{"Time":"2020-01-01T00:00:00","AHT1X-0x38":{"Temperature":24.7,"Humidity":61.9,"DewPoint":16.8},"TempUnit":"C"}}'
///body = '{"STATUSSNS":{"Time": "2019-01-01T00:00:00","AM2301": {"Temperature": 24.6,"Humidity": 58.2},"TempUnit": "C"}}'
///body = '{"STATUSSNS":{"Time":"2019-10-31T21:48:51","APDS9960":{"Red":282,"Green":252,"Blue":196,"Ambient":169,"CCT":4217,"Proximity":9}}}'
///body = '{"STATUSSNS":{"Time":"2020-01-01T17:07:07","AS3935":{"Event":4,"Distance":12,"Energy":58622,"Stage":1}}}'
///body = '{"STATUSSNS":{"Time":"2019-11-03T20:45:37","BH1750":{"Illuminance":79}}}'
//body = '{"STATUSSNS":{"Time": "2019-11-03T19:34:28","BME280": {"Temperature": 21.7,"Humidity": 66.6,"Pressure": 988.6},"PressureUnit": "hPa","TempUnit": "C"}}'
//body = '{"STATUSSNS":{"Time": "2021-09-22T17:00:00","BME680": {"Temperature": 24.5,"Humidity":33.0,"DewPoint": 7.1,"Pressure": 987.7,"Gas": 1086.43 },"PressureUnit": "hPa","TempUnit": "C"}}'
///body = '{"STATUSSNS":{"Time":"2021-07-17T17:29:51","DS18B20":{"Id":"000003287EF1","Temperature":24.7},"TempUnit":"C"}}'
///body = '{"STATUSSNS":{"Time":"2019-01-01T22:42:35","SR04":{"Distance":16.754}}}'
///body = '{"STATUSSNS":{"Time": "2021-08-25T17:15:45","RG-15": {"Active": 0.01,"Event": 0.13,"Total": 26.80,"FlowRate": 0.32},"TempUnit": "C"}}'
///body = '{"STATUSSNS":{"Time":"2020-01-01T00:00:00","IAQ":{"eCO2":450,"TVOC":125,"Resistance":76827}}}'
///body = '{"STATUSSNS":{"Time": "2019-01-01T00:00:00","IrReceived": {"Protocol": "NEC","Bits": 32,"Data": "0x00FF00FF"}}}'
///body = '{"STATUSSNS":{"Time":"2021-01-23T13:10:50","RC522":{"UID":"BA839D07","Data":"","Type":"MIFARE 1KB"}}}'
///body = '{"STATUSSNS":{"Time":"2019-11-11T00:03:30","MLX90614":{"OBJTMP":23.8,"AMBTMP":22.7}}}' - Infra Red Thermometer
//body = '{"STATUSSNS":{"Time":"2019-12-10T19:37:50","MPU6050":{"Temperature":27.7,"AccelXAxis":-7568.00,"AccelYAxis":-776.00,"AccelZAxis":12812.00,"GyroXAxis":270.00,"GyroYAxis":-741.00,"GyroZAxis":700.00,"Yaw":0.86,"Pitch":-1.45,"Roll":-10.76},"TempUnit":"C"}}'
///body = '{"STATUSSNS":{"Time":"2019-01-10T18:31:39","PN532":{"UID":"94D8FC5F", "DATA":"ILOVETASMOTA"}}}'
///body = '{"StatusSNS":{"Time":"2022-05-25T10:23:58","Switch3":"ON"}}'
///body = '{"STATUSSNS":{"Time": "2019-01-01T00:00:00","RfReceived": {"Data": "0x7028D5","Bits": 24,"Protocol": 1,"Pulse": 238}}}'
///body = '{"STATUSSNS":{"Time":"2019-11-03T21:04:05","TSL2561":{"Illuminance":21.180}}}'
//body = '{"STATUSSNS":{"Time":"2019-12-20T11:29:22","VL53L0X":{"Distance":263}}}'
//body = '{"STATUSSNS":{"Time":"2022-01-07T19:43:24","Switch3":"ON","Switch4":"ON","ENERGY":{"TotalStartTime":"2021-04-03T18:52:24","Total":[0.005,1.507],"Yesterday":[0.000,0.648],"Today":[0.000,0.197],"Period":[ 0, 0],"Power":[ 0,26],"ApparentPower":[ 0,43],"ReactivePower":[ 0,33],"Factor":[0.00,0.62],"Frequency":50.016,"Voltage":225,"Current":[0.000,0.189]},"ESP32":{"Temperature":65.6},"TempUnit":"C"}}'
//body = '{"STATUSSNS":{"Time": "2020-09-11T09:18:08","MLX90640": {"Temperature": [30.8, 28.5, 24.2, 25.7, 24.5, 24.6, 24.9]},"TempUnit": "C"}}' // - IR Thermal Sensor Array
//body = '{"STATUSSNS":{"Time":"2018-08-18T16:13:47","MCP230XX":{"D0":0,"D1":0,"D2":1,"D3":0,"D4":0,"D5":0,"D6":0,"D7":1}}}'
//body = '{"STATUSSNS":{"TIME":"2022-06-26T16:20:33","DS18B20-1":{"ID":"011937B1E1FD","TEMPERATURE":86.7},"DS18B20-2":{"ID":"011937D1CBA3","TEMPERATURE":-11.0},"TEMPUNIT":"F"}}'
//body = '{"STATUSSNS":{"Time": "2021-09-22T17:00:00","VINDRIKTNING":{"PM2.5":2},"BME680": {"Temperature": 24.5,"Humidity":33.0,"DewPoint": 7.1,"Pressure": 987.7,"Gas": 1086.43 },"PressureUnit": "hPa","TempUnit": "C"}}'
//body = '{"StatusSNS":{"Time":"2022-06-11T10:58:18","HX711":{"Weight":0,"WeightRaw":4782,"AbsRaw":110004}}}'
//Known non-working examples
//body = '{"STATUSSNS":{"Time": "2020-03-03T00:00:00+00:00","TX23": {"Speed": {"Act": 14.8,"Avg": 8.5,"Min": 12.2,"Max": 14.8},"Dir": {"Card": "WSW","Deg": 247.5,"Avg": 266.1,"AvgCard": "W","Min": 247.5,"Max": 247.5,"Range": 0}},"SpeedUnit": "km/h"}}}'
//body = '{"StatusSNS":{"Time":"2022-08-15T22:00:44","DS18B20-1":{"Id":"3C01F0965038","Temperature":25.0},"DS18B20-2":{"Id":"3C01F0967907","Temperature":25.1},"DS18B20-3":{"Id":"3C01F0969327","Temperature":24.8,"Humidity":59},"BME280":{"Temperature":23.8,"Humidity":57.9,"DewPoint":15.0,"Pressure":985.8},"PressureUnit":"hPa","TempUnit":"C"}}'
state.Action = "STATUS"
state.ActionValue = "8"
body = body.toUpperCase()
statusResponse(body)
}
//Used to evaluate how well the driver will translate the Tasmota Sensor Data.
void evaluateSensorData(String status8){
state.Action = "STATUS"
state.ActionValue = "8"
body = status8.toUpperCase()
log.info("Calling statusResponse with $body")
statusResponse(body)
}
def clearAttributes(){
log("clearAttributes", "Clearing All Attributes", 0)
sensor2AttributeMap.each {
log("clearAttributes", "Clearing attribute: $it.value", 3)
device.deleteCurrentState(it.value)
}
//These are the attributes not listed in the sensor2AttributeMap
device.deleteCurrentState("amperage")
device.deleteCurrentState("carbonDioxide")
device.deleteCurrentState("carbonMonoxide")
device.deleteCurrentState("pressureUnit")
device.deleteCurrentState("tempUnit")
device.deleteCurrentState("speedUnit")
device.deleteCurrentState("switch")
device.deleteCurrentState("switch1")
device.deleteCurrentState("switch2")
device.deleteCurrentState("switch3")
device.deleteCurrentState("switch4")
state.lastMessage = ""
state.thisMessage = ""
state.remove("lastTasmotaSync")
state.remove("itemNames")
state.remove("sensorData")
state.remove("sensors")
state.remove("sensorNames")
state.remove("sensorTriggers")
state.remove("sensorAttributes")
updateStatus ("Attributes Cleared - Refresh Browser!")
}
//*********************************************************************************************************************************************
//******
//****** Start of All functions that have any uniqueness to them across all of the TSync driver base.
//****** This allows for easier updates to core functions
//******
//*******************************************************************************************************************************************
//*********************************************************************************************************************************************************************
//******
//****** Start of UNIQUE standard functions
//******
//*********************************************************************************************************************************************************************
//Updated gets run when the "Initialize" button is clicked or when the device driver is selected
def initialize(){
log("Action", "Initialize/Update Device", 0)
//Cancel any existing scheduled tasks for this device
unschedule("poll")
//Make sure we are using the right address
updateDeviceNetworkID()
log("Initialize", "pollFrequency value: ${settings.pollFrequency}",1)
//Test to make sure the entered frequency is in range
switch(settings.pollFrequency) {
case "0": unschedule("poll") ; break
case "60": runEvery1Minute("poll") ; break
case "300": runEvery5Minutes("poll") ; break
case "600": runEvery10Minutes("poll") ; break
case "900": runEvery15Minutes("poll") ; break
case "1800": runEvery30Minutes("poll") ; break
case "3600": runEvery1Hours("poll") ; break
case "10800": runEvery3Hours("poll") ; break
}
//To be safe these are populated with initial values to prevent a null return if they are used as logic flags
if ( state.Action == null ) state.Action = "None"
if ( state.ActionValue == null ) state.ActionValue = "None"
if ( device.currentValue("Status") == null ) updateStatus("Complete")
//Do a refresh to sync the device driver
refresh()
}
//*********************************************************************************************************************************************************************
//******
//****** End of UNIQUE standard functions
//******
//*********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************
//******
//****** UNIQUE: Start of Power related functions. These may be UNIQUE across all Tasmota Sync drivers
//******
//*********************************************************************************************************************************************************************
//switch and switch1 are synonymous so we just call the switch1On function.
def on(){
switch1On()
}
//switch and switch1 are synonymous so we just call the switch1Off function.
def off(){
switch1Off()
}
//Turns the Power on to one or all switches based on settings. Note: Power and Power1 are synonymous in Tasmota
def switch1On() {
if (settings.switchBehaviour == "1") {
log("Action", "Turn on switch\\switch1", 0)
callTasmota("POWER", "ON")
}
else
{
log("Action", "Turn on all switches", 0)
i = 1
String command = "POWER ON;"
while ( i <= switchCount ) {
command = command + "POWER${i} ON;"
i++
}
//command = "POWER ON; POWER2 ON; POWER3 ON; POWER4 ON; POWER5 ON; POWER6 ON; POWER7 ON; POWER8 ON"
callTasmota("BACKLOG", command)
}
//Remove any left over state variables from prior versions. This will get swept into version control when added.
//clean()
}
//Turns off one or all switches.
def switch1Off() {
if (settings.switchBehaviour == "1") {
log("Action", "Turn off switch\\switch1", 0)
callTasmota("POWER", "OFF")
}
else
{
log("Action", "Turn off all switches", 0)
i = 1
String command = "POWER OFF;"
while ( i <= switchCount ) {
command = command + "POWER${i} OFF;"
i++
}
callTasmota("BACKLOG", command)
}
}
def switch2On() {
log("Action", "Turn on switch 2", 0)
callTasmota("POWER2", "ON")
}
def switch2Off() {
log("Action", "Turn off switch 2", 0)
callTasmota("POWER2", "OFF")
}
//*********************************************************************************************************************************************************************
//******
//****** End of Power related functions
//******
//*********************************************************************************************************************************************************************
//**************************************************************************************************************************************************************************
//******
//****** UNIQUE: Start of Background task run by Hubitat
//******
//**************************************************************************************************************************************************************************
//Sync the UI to the actual status of the device. The results come back to the parse function.
//This function is called from the button press and automatically via the polling method
//In drivers with SENSOR data this function is a little different.
def refresh(){
log ("Action", "Refresh started....", 0)
log("refresh", "Getting sensor data.", 1)
state.lastSensorData = new Date().format('yyyy-MM-dd HH:mm:ss')
callTasmota("STATUS", "8" )
//Calculate when the current operations should be finished and schedule the "STATE" command to run after them.
if (switchCount >= 1) {
//Not required in a sensor only device.
def parameters = ["STATE",""]
runInMillis(remainingTime() + 500, "callTasmota", [data:parameters])
}
state.LastSync = new Date().format('yyyy-MM-dd HH:mm:ss')
}
//*****************************************************************************************************************************************************************************************************
//******
//****** End of Background tasks
//******
//*****************************************************************************************************************************************************************************************************
//******************************************************************************************************************************************************************************************************
//******
//****** Start of main program section where most of the work gets done. There are 3 main functions, parse which receives all LAN input and directs it to either hubitatResponse or syncTasmota for processing.
//****** The functions callTasmota() and parse() are IDENTICAL in all Tasmota Sync drivers and are found toward the end of the file.
//****** The functions syncTasmota, hubitatResponse() and tasmotaInjectRule() are UNIQUE in all Tasmota Sync drivers and are located immediately below.
//******
//******************************************************************************************************************************************************************************************************
//******************************************************************************************************************************************************************************************************
//******
//****** Start of main program section where most of the work gets done. There are 3 main functions, parse which receives all LAN input and directs it to either hubitatResponse or syncTasmota for processing.
//****** The functions callTasmota() and parse() are IDENTICAL in all Tasmota Sync drivers and are found toward the end of the file.
//****** The functions syncTasmota, hubitatResponse() and tasmotaInjectRule() are UNIQUE in all Tasmota Sync drivers and are located immediately below.
//******
//******************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** UNIQUE: The only things that get routed here are expected responses to commands issued through Hubitat.
//******
//*************************************************************************************************************************************************************************************************************
def hubitatResponse(body){
log ("hubitatResponse", "Entering, data received", 1)
log ("hubitatResponse", "Raw data is: ${body}.", 2)
//Get the command and value that was submitted to the callTasmota function
Action = state.Action
ActionValue = state.ActionValue
log ("hubitatResponse", "Flags are Action:${state.Action} ActionValue:${state.ActionValue}", 2)
//Test to see if we got a warning from Tasmota
tasmotaWarning = false
if (body.contains("WARNING") == true ) {
tasmotaWarning = true
log ("hubitatResponse","A warning was received from Tasmota. Review the message '${body}' and make appropriate changes.", 0)
updateStatus("Complete:Failed")
}
//Now parse into JSON to extract data.
body = parseJson(body)
//Check to make sure we have some data to act on.
if (body !=null){
//If the response contains the WiFi info then we extract the RSSI value for display as a state variable.
if (body.WIFI != null ){
def wifi = body.WIFI
def RSSI = wifi.RSSI
state.RSSI = RSSI
log ("hubitatResponse", "RSSI: ${state.RSSI}", 2)
}
switch(Action.toUpperCase()) {
case ["POWER"]:
//On a single relay\plug\switch the response to "POWER1 OFF" is {"POWER":"OFF"}. On a multi-port relay the response to "POWER1 OFF" is {"POWER1":"OFF"} so we have to be ready to accept either response.
if (body?.POWER != null) log("hubitatResponse","Command: Power ${body.POWER}", 0)
if (body?.POWER1 != null) log("hubitatResponse","Command: Power ${body.POWER1}", 0)
if (ActionValue.equalsIgnoreCase(body.POWER) || ActionValue.equalsIgnoreCase(body.POWER1) ){
log ("hubitatResponse","Power state applied successfully", 0)
updateStatus("Complete:Success")
//We got the response we were looking for so we can actually change the state of the switch in the UI.
//If the switch is turned off then the power statistics must be zero. However, if TSync is enabled then it will fire a Sync anyway.
sendEvent(name: "switch", value: ActionValue.toLowerCase(), descriptionText: "Linked switch has been turned ${ActionValue.toLowerCase()}", isStateChange: true )
sendEvent(name: "switch1", value: ActionValue.toLowerCase(), descriptionText: "Switch switch1 has been turned ${ActionValue.toLowerCase()}", isStateChange: true )
}
else {
log("hubitatResponse","Power state failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["POWER2"]:
log("hubitatResponse","Command: Power2 ${body.POWER2}", 0)
if (ActionValue.equalsIgnoreCase(body.POWER2) ){
log ("hubitatResponse","Power2 state applied successfully", 0)
updateStatus("Complete:Success")
//We got the response we were looking for so we can actually change the state of the switch in the UI.
//If the switch is turned off then the power statistics must be zero. However, if TSync is enabled then it will fire a Sync anyway.
sendEvent(name: "switch2", value: ActionValue.toLowerCase(), descriptionText: "Switch switch2 has been turned ${ActionValue.toLowerCase()}", isStateChange: true )
}
else {
log("hubitatResponse","Power2 state failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["TELEPERIOD"]:
log("hubitatResponse","Command: TelePeriod ${body.TELEPERIOD}", 1)
if (ActionValue.toInteger() == body.TELEPERIOD)
{
log ("hubitatResponse","TelePeriod applied successfully", 0)
state.TelePeriod = body.TELEPERIOD
updateStatus("Complete:Success")
}
else {
log("hubitatResponse","TelePeriod failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["BACKLOG"]:
//Backlog commands do not return anything useful to indicate success or failure. A typical response might be [WARNING:Enable weblog 2 if response expected]. But the bulb may be in weblog 4 and get a different response.
//If we come back to this spot we know a BACKLOG command was issued and SOMETHING came back so we know the command at least got to the device.
log ("hubitatResponse","Backlog Command acknowledged.", 0)
updateStatus("Complete:Backlogged")
break
case ["STATE"]:
//Synchronise the UI to the values we get from the device via the STATE command. Typical response looks like this
//{"Time":"2022-04-12T06:20:36","Uptime":"0T10:05:13","UptimeSec":36313,"Heap":26,"SleepMode":"Dynamic","Sleep":50,"LoadAvg":19,"MqttCount":0,"Power":"OFF","Dimmer":68,"Color":"00000000AD",
//"HSBColor":"248,84,0","White":68,"CT":500,"Channel":[0,0,0,0,68],"Scheme":0,"Fade":"OFF","Speed":20,"LedTable":"ON","Wifi":{"AP":1,"SSId":"5441","BSSId":"A0:04:60:95:0E:62","Channel":6,"Mode":"11n",
//"RSSI":100,"Signal":-47,"LinkCount":1,"Downtime":"0T00:00:06"}}
//Does nothing really in a sensor only device but retained for compatibility with all other device drivers.
if (switchCount > 0) {
log ("hubitatResponse","Setting device handler values to match device.", 0)
if (body?.POWER ){
sendEvent(name: "switch", value: body.POWER.toLowerCase(), descriptionText: "Linked switch has been turned ${ActionValue.toLowerCase()}", displayed:false)
sendEvent(name: "switch1", value: body.POWER.toLowerCase(), descriptionText: "Switch switch1 has been turned ${ActionValue.toLowerCase()}", displayed:false)
}
if (body?.POWER1 ) {
sendEvent(name: "switch1", value: body.POWER1.toLowerCase(), descriptionText: "Switch switch1 has been turned ${ActionValue.toLowerCase()}", displayed:false)
sendEvent(name: "switch", value: body.POWER1.toLowerCase(), descriptionText: "Linked switch has been turned ${ActionValue.toLowerCase()}", displayed:false)
}
if (body?.POWER2) sendEvent(name: "switch2", value: body.POWER2.toLowerCase(), descriptionText: "Switch switch2 has been turned ${ActionValue.toLowerCase()}", displayed:false)
}
updateStatus("Complete:Success")
break
default:
//Response to any other undefined commands will come here. This is most likely because of a custom command
//If we come back to this spot we know a command was issued and SOMETHING came back so we know the command at least got to the device.
log ("hubitatResponse","Command acknowledged.", 0)
updateStatus("Complete")
break
}
}
log ("hubitatResponse","Closing Transaction", 1)
state.inTransaction = false
log ("hubitatResponse","Exiting", 1)
}
//*****************************************************************************************************************************************************************************************************
//******
//****** End of hubitatResponse()
//******
//*****************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** UNIQUE: The only things that get routed here are expected responses to commands issued through Hubitat or Sensor Updates
//******
//*************************************************************************************************************************************************************************************************************
def syncTasmota(body){
log ("syncTasmota", "Data received: ${body}", 0) // Body looks something like: {"TSYNC":"TRUE","SWITCH1":"0","TEMPERATURE":"67","HUMIDITY":"43","DEWPOINT":"44"}
//This is a special case that only happens when the rules are being injected
if (state.ruleInjection == true){
log ("syncTasmota", "Rule3 special case complete.", 1)
state.ruleInjection = false
state.inTransaction = false
log ("syncTasmota","Closing Transaction", 2)
updateStatus("Complete:Success")
return
}
//Let's see how long it's been since the last command initiated by Hubitat. If it is less than X seconds we will ignore this sync request as it is likely an "echo" of the Hubitat request.
elapsed = now() - state.startTime
if (elapsed > settings.debounce){
log ("syncTasmota", "Tasmota Sync request processing.", 1)
state.Action = "Tasmota"
state.ActionValue = "Sync"
state.lastTasmotSync = new Date().format('yyyy-MM-dd HH:mm:ss')
//Now parse into JSON to extract data.
body = parseJson(body)
//Preset the switch value for instances where the %var% is empty
switch1 = -1 ; switch2 = -1 ; switch3 = -1 ; switch4 = -1
//A value of '' for any of these means no update or not present. Probably because the device has restarted and the %vars% have not repopulated. This is expected.
//Only changes will get logged so we can report everything. In Tasmota, "power" is the switch state but we use "SWITCHX" in the TSYNC JSON.
if ( switchCount >= 1 ){
if (body?.SWITCH1 != '' && body?.SWITCH1 != null) { switch1 = body?.SWITCH1 ; log ("syncTasmota","Switch is: ${switch1}", 0) }
if ( switch1.toInteger() == 0 ) { sendEvent(name: "switch1", value: "off", descriptionText: "Switch switch1 was turned off.") ; sendEvent(name: "switch", value: "off", descriptionText: "Linked switch was turned off.") }
if ( switch1.toInteger() == 1 ) { sendEvent(name: "switch1", value: "on", descriptionText: "Switch switch1 was turned on.") ; sendEvent(name: "switch", value: "on", descriptionText: "Linked switch was turned on.") }
}
if ( switchCount >= 2 ){
if (body?.SWITCH2 != '' && body?.SWITCH2 != null) { switch2 = body?.SWITCH2 ; log ("syncTasmota","Switch is: ${switch2}", 2) }
if ( switch2.toInteger() == 0 ) sendEvent(name: "switch2", value: "off", descriptionText: "The switch was turned off.")
if ( switch2.toInteger() == 1 ) sendEvent(name: "switch2", value: "on", descriptionText: "The switch was turned on.")
}
//These lines process any sensor switches which must be placed at switch3 or switch4.
if (body?.SWITCH3 != '' && body?.SWITCH3 != null) { switch3 = body?.SWITCH3 ; log ("syncTasmota","Switch is: ${switch3}", 2) }
if ( switch3.toInteger() == 0 ) sendEvent(name: "switch3", value: "off", descriptionText: "The switch was turned off.")
if ( switch3.toInteger() == 1 ) sendEvent(name: "switch3", value: "on", descriptionText: "The switch was turned on.")
//These lines process any sensor switches which must be placed at switch3 or switch4.
if (body?.SWITCH4 != '' && body?.SWITCH4 != null) { switch4 = body?.SWITCH4 ; log ("syncTasmota","Switch is: ${switch4}", 2) }
if ( switch4.toInteger() == 0 ) sendEvent(name: "switch4", value: "off", descriptionText: "The switch was turned off.")
if ( switch4.toInteger() == 1 ) sendEvent(name: "switch4", value: "on", descriptionText: "The switch was turned on.")
//Iterate through the data values received. Because the SENSOR fields are populated every time RULE3 runs they should never be empty\null.
hubitatAttributeName = ""
body.each {
try {
//Lookup the Hubitat attribute name used for this sensor value
hubitatAttributeName = sensor2AttributeMap[it.key.trim()]
//We ignore SWITCHES 1-4 as these are processed seperately above.
if (it.key.toUpperCase() != "SWITCH1" && it.key.toUpperCase() != "SWITCH2" && it.key.toUpperCase() != "SWITCH3" && it.key.toUpperCase() != "SWITCH4"&& it.key.toUpperCase() != "TSYNC" ) {
log("syncTasmota", "${it.key} sensor data (${it.value}) mapped to Hubitat attribute: ${hubitatAttributeName}" , 1)
//Check to see if the field is blank which would inidicate no change. This should never happen but you never know.
if ( "${it.value}" == "" ) log("syncTasmota", "Sensor data blank (${it.value})" , 2)
//Hubitat will de-dupe updates that do not have changed values so we can report each time.
else {
//We have a valid attribute and data so let's get the display suffix.
unitSuffix = sensor2UnitSuffix[it.key.trim()]
log("syncTasmota", "Key: ${it.key} Value: ${it.value} unitSuffix: (${unitSuffix})" , 3)
if ( unitSuffix == null ) sendEvent(name: hubitatAttributeName, value: it.value )
else sendEvent(name: hubitatAttributeName, value: it.value , unit: unitSuffix )
}
}
}
catch (Exception e) { log ("statusResponse", "Error: Unable to match ${it.key} with a known Hubitat attribute.", -1) }
}
updateStatus ("Complete:Tasmota Sync")
log ("syncTasmota", "Sync completed. Exiting", 0)
return
}
else {
log ("syncTasmota", "Tasmota Sync request debounced. Exiting.", 0)
log ("syncTasmota", "Elapsed time of ${elapsed}ms is less than debounce limit of ${settings.debounce}. This can be adjusted in settings.", 1)
}
}
//*****************************************************************************************************************************************************************************************************
//******
//****** End of syncTasmota()
//******
//*****************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** UNIQUE: //Here we make adjustments to the Body for one off instances. This function is only present in the Universal Sensor example.
//******
//*************************************************************************************************************************************************************************************************************
def adjustBody(String body){
log("adjustBody", "Received body is: ${body}" , 3)
// An ANALOG sensor might have multi-level data as in this case with CTENERGY. I'm taking the easy approach and "un-nesting" the JSON data into 2 levels.
// Converts --> {"StatusSNS":{"Time":"2022-06-26T22:06:56","ANALOG":{"Energy":2.882,"Power":49,"Voltage":230,"Current":0.215}}}} into --> {"StatusSNS":{"Time":"2022-06-26T22:06:56","ANALOG":{"Energy":2.882,"Power":49,"Voltage":230,"Current":0.215}}}}
// Yes there is an excess '}' on the end but the JSON handler does not seem to care. Other corrections for nested ANALOG data should be added here and work in the same way.
if (body.contains('"ANALOG":{"CTENERGY"')==true ) {
body = body?.replace('"ANALOG":{"CTENERGY"','"ANALOG"')
log("statusResponse", "Modified ANALOG Body ${body}" , 3)
}
log("adjustBody", "Adjusted Body ${body}" , 3)
return(body)
}
//*****************************************************************************************************************************************************************************************************
//******
//****** End of adjustBody()
//******
//*****************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** UNIQUE: The only things that gets routed here are responses to Hubitat initiated requests for Sensor updates.
//******
//*************************************************************************************************************************************************************************************************************
def statusResponse(body){
//If we want to test some input then add a line here like the following example
//body = '{"STATUSSNS":{"TIME":"2022-06-26T16:20:33","DS18B20-1":{"ID":"011937B1E1FD","TEMPERATURE":86.7},"DS18B20-2":{"ID":"011937D1CBA3","TEMPERATURE":-11.0},"TEMPUNIT":"F"}}'
log ("statusResponse", "Entering, data Received.", 1)
log ("statusResponse", "Data is: ${body}.", 0)
body = adjustBody(body)
//Now parse into JSON to extract data.
body = parseJson(body)
//STATUS 1 - 12 calls return data fields about Tasmota. STATUS 8 returns sensor data and is probably the most important to Hubitat.
//STATUS 8 response looks something like: {"StatusSNS":{"Time":"2022-05-17T04:23:22","SI7021":{"Temperature":65,"Humidity":31,"DewPoint":33},"TempUnit":"F"}}
if ( (state.ActionValue == "8") && (body.STATUSSNS != null) )
{
state.lastSensorData = new Date().format('yyyy-MM-dd HH:mm:ss')
STATUSSNS = body?.STATUSSNS
//STATUSSNS looks like: [TIME:2022-05-17T04:26:39, TEMPUNIT:F, SI7021:[HUMIDITY:31, TEMPERATURE:64, DEWPOINT:33]] but may look like {"StatusSNS":{"Time":"2022-05-25T10:23:58","Switch1":"ON"}}
// OR {"StatusSNS":{"Time":"2022-07-24T03:55:29","DS18B20-1":{"Id":"3C01F0965038","Temperature":75.0},"DS18B20-2":{"Id":"3C01F0967907","Temperature":74.5},"TempUnit":"F"}}
log("statusResponse","STATUSSNS is: " + STATUSSNS, 1)
def sensorNames = []
def itemNames = []
def sensorTriggers = []
def sensorAttributes = []
def sensorData = []
//Go through each of the top level fields
STATUSSNS.each{
log("statusResponse", "Name: ${it.key}" , 3)
DATA = STATUSSNS?."$it.key"
String mystring = "${DATA}"
//If it is JSON format we need to iterate it for the pair data. If not in JSON we just grab the data later.
if (mystring.contains("[") == true ) {
sensorNames.add(it.key)
log("statusResponse", "Add sensor: ${it.key}" , 3)
}
else {
itemNames.add(it.key)
log("statusResponse", "Add item: ${it.key}" , 3)
}
}
sensorNames = sensorNames.sort()
//All good to here
log("statusResponse", "****************** Extracted Items and Sensors ******************" , 2)
//Go through the top level items and get the values. Switches will be added to the sensorData list
itemNames.each {
log("statusResponse", "Item is: ${it}" , 3)
switch("${it}") {
// Sensor Switches 3&4 are handled in syncTasmota
case "TEMPUNIT":
sendEvent(name: "tempUnit" , value: STATUSSNS?."$it".toUpperCase())
log("statusResponse", "STATUSSNS TempUnit is: ${STATUSSNS?.TEMPUNIT}" , 1)
break
case "PRESSUREUNIT":
sendEvent(name: "pressureUnit" , value: STATUSSNS?."$it".toUpperCase())
log("statusResponse", "STATUSSNS PressureUnit is: ${STATUSSNS?.PRESSUREUNIT}" , 1)
break
case "SPEEDUNIT":
sendEvent(name: "speedUnit" , value: STATUSSNS?."$it".toUpperCase())
log("statusResponse", "STATUSSNS SpeedUnit is: ${STATUSSNS?.SPEEDUNIT}" , 1)
break
case "TIME":
log("statusResponse", "STATUSSNS Time is: ${STATUSSNS?.TIME}" , 1)
break
}
}
log("statusResponse", "****************** Items Processed ******************" , 2)
//Now we go through the Sensors and gather the underlying data
sensorNames.any{ sensors ->
sensor = sensors
sensorFields = STATUSSNS?."$sensor"
log("statusResponse", "SENSOR is: ${sensor} and Sensor fields are: ${sensorFields}" , 1)
//Iterate through the list of data items.
sensorFields.any { data ->
try {
log("statusResponse", "Data is: ${data.key} Value: ${data.value}" , 2)
//Lookup the Hubitat attribute name used for this sensor value
attribute = sensor2AttributeMap[data.key]
//If a match is found the attribute will be processed. Otherwise it will be ignored
if ( attribute != null ){
sendEvent( name: attribute, value: data.value )
log("statusResponse", "${data.key} data (${data.value}) will be mapped to Hubitat attribute of type: ${attribute}" , 2)
//Test to see if attribute is a valid Trigger.
if ( triggerEligibleList.contains(data.key) == true ){
log("statusResponse", "${data.key} is trigger eligible" , 3)
trigger = ("Tele-${sensor}#${data.key}") //Note that we use the data.key and not data.value.
sensorTriggers.add (trigger)
//Collates all the fields that are required for a given sensor in an accessible way. Here "attribute" is a temporary placeholder that will be updated later.
sensorData.add ("${sensor}:${data.key}:${data.value}:${attribute}")
}
}
else log ("statusResponse", "Warning: Unable to match sensor data field '${data.key}' with a known Hubitat attribute. Is it missing from the attributes section and\\or the sensor2AttributeMap?", 1)
//Hubitat will de-dupe updates that do not have changed values so we can report each time.
//For some unknown reason removal of the following line caused issues with the generation of the lists. Wierd!!!
sendEvent(name: attribute, value: data.value )
}
catch (Exception e) { log ("statusResponse", "Error processing sensor ${data.key} with data ${data.value}", -1) }
}