forked from GaryMilne/Hubitat-Tasmota
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fan_with_Dimmer.groovy
1440 lines (1224 loc) Β· 78 KB
/
Fan_with_Dimmer.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Tasmota Sync Fan with Dimmer
* Version: v1.0.2
* Download: See importUrl in definition
* Description: Hubitat Driver for Tasmota Ceiling Fan with Dimmer. 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.
*
* FAN - UNIQUE - CHANGELOG
* Version 0.91 - Internal version
* Version 0.92 - Added setFanSpeedAttribute function
* Version 0.93.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 1.0.0 - All versions incremented and synchronised for HPM plublication via CSTEELE
* Version 1.0.1 - Initial release of Fan with Dimmer combination
* Version 1.0.2 - Incremented Core 0.98.2. Fixed "DIMMER" code with improved version from Dimmer implementation.
*
* 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
*
* Gary Milne - Aug 29, 2022
*
**/
import groovy.json.JsonSlurper
metadata {
definition (name: "Tasmota Sync - Fan with Dimmer", namespace: "garyjmilne", author: "Gary J. Milne", importUrl: "https://raw.githubusercontent.com/GaryMilne/Hubitat-Tasmota/main/Fan_with_Dimmer.groovy", singleThreaded: true ) {
capability "Switch"
capability "SwitchLevel"
capability "FanControl"
capability "Refresh"
//Internally named variables that must be lower case
attribute "level", "number"
attribute "speed", "string"
attribute "fanSpeed", "string"
//Driver specific variables where case does not matter.
attribute "Fade", "string"
attribute "FadeSpeed", "string"
attribute "Status", "string"
command "fanOff"
command "brighter"
command "dimmer"
command "fadeSpeed", [ [name:"Duration in seconds for a dimmer transation to complete (Persistent). FadeSpeed attribute will be 2X this number.*", type: "STRING", description: "The time in seconds (0 - 20) for any transition operation to complete. fadeSpeed will display as 2X this value as Tasmota uses 0.5 seconds intervals. Note: Fade must be turned on for this setting to have any effect."] ]
command "fadeToggle"
command "initialize"
command "tasmotaInjectRule"
command "tasmotaCustomCommand", [ [name:"Command*", type: "STRING", description: "A single word command to be issued such as COLOR, CT, DIMMER etc."], [name:"Parameter", type: "STRING", description: "An optional single parameter that accompanies the command such as FFFFFFFF, 350, 75 etc."] ]
command "toggle"
//command "test"
}
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
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."), 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
}
}
//Function used for quickly testing out logic and cleaning up.
def test(){
//state.remove("starttime")
}
//*********************************************************************************************************************************************
//******
//****** 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("Initialize", "Device initialized", 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} seconds.",0)
//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")
if ( device.fanSpeed == null ) sendEvent(name: "fanSpeed", value: 0 )
if ( device.speed == null ) sendEvent(name: "speed", value: "--" )
//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
//******
//*********************************************************************************************************************************************************************
//Turns the Power on
//Note: POWER and POWER1 are synonymous in Tasmota when issuing commands however STATE only returns "POWER"
def on() {
log("Action", "Turn on switch", 0)
callTasmota("POWER", "on")
}
//Turns the switch off
def off() {
log("Action", "Turn off switch", 0)
callTasmota("POWER", "off")
}
//Turns the fan off.
def fanOff() {
log("Action", "Turn fan off", 0)
callTasmota("FANSPEED", "0")
}
//Cycles the fan to the next position in the cycle Off, Low, Medium, High, Off.
//This is a function name expected to be present when the FanControl capability is enabled.
void cycleSpeed(){
def currSpeed = device.currentValue("fanSpeed")
switch(currSpeed) {
case ["off", "0"]:
log("Action", "cycleSpeed: Current speed: 0 - Requested speed is: 1", 0)
callTasmota("FANSPEED", "1")
break
case ["low", "1"]:
log("Action", "cycleSpeed: Current speed: 1 - Requested speed is: 2", 0)
callTasmota("FANSPEED", "2")
break
case ["medium", "2"]:
log("Action", "cycleSpeed: Current speed: 2 - Requested speed is: 3", 0)
callTasmota("FANSPEED", "3")
break
case ["high", "3"]:
log("Action", "cycleSpeed: Current speed: 3 - Requested speed is: 0", 0)
callTasmota("FANSPEED", "0")
break
}
}
//Sets the fan to the Tasmota FANSPEED corresponding to the predetermined english names within the setSpeed() tile.
//This is a function name expected to be present when the FanControl capability is enabled.
def setSpeed(String speed) {
log("Action", "cycleSpeed: Requested speed is: ${speed}", 0)
switch(speed) {
case ["off"]:
callTasmota("FANSPEED", "0")
break
case ["on", "low"]:
callTasmota("FANSPEED", "1")
break
case ["medium", "medium-low"]:
callTasmota("FANSPEED", "2")
break
case ["medium-high", "high"]:
callTasmota("FANSPEED", "3")
break
case ["auto"]:
log("cycleSpeed", "Current speed is: ${currSpeed}", 0)
break
}
}
//device.speed is not declared in the capabilities documentation however I have come across it in other drivers, specifically the ABC controller which I use presonally.
//So I have added support for this attribute for the widest compatibility
void setfanSpeedAttribute(speed){
log("setfanSpeedAttribute", "Current fan speed is: ${speed}", 2)
switch(speed) {
case 0:
sendEvent(name: "speed", value: "off" )
break
case 1:
sendEvent(name: "speed", value: "low" )
break
case 2:
sendEvent(name: "speed", value: "medium" )
break
case 3:
sendEvent(name: "speed", value: "high" )
break
}
}
//Toggles the Fade function off and on
void fadeToggle() {
log ("Action - fadeToggle", "Toggle Fade", 0)
if ( device.currentValue("Fade").equalsIgnoreCase("on") ){
newstate = "off"
}
else
{
newstate = "on"
}
callTasmota("FADE", newstate )
log ("fadeToggle", "Exiting", 1)
}
//This FadeSpeed function uses the Speed command which is a persistent value (as opposed to SPEED2)
void fadeSpeed(fadeSpeed) {
log ("Action - fadeSpeed", "Change fadeSpeed to ${fadeSpeed}", 0)
//Test to see if the fadeSpeed is a valid integer
try {
fadeSpeed = fadeSpeed.toInteger()
if (fadeSpeed > 20) {fadeSpeed = 20}
if (fadeSpeed < 0) {fadeSpeed = 0}
}
catch (Exception e) {
log ("Fade", "Error: Invalid fadeSpeed. Should be a numeric value between 0 and 20.", -1)
return
}
callTasmota("Speed", fadeSpeed * 2 )
log ("fadeSpeed", "Exiting", 1)
}
//This Brighter function increments the brightness of the dimmer setting.
void brighter() {
log ("Action - brighter", "Increasing brightness", 0)
callTasmota("DIMMER", "+" )
log ("brighter", "Exiting", 1)
}
//This Dimmer function increments the brightness of the dimmer setting.
void dimmer() {
log ("Action - dimmer", "Decreasing brightness", 0)
callTasmota("DIMMER", "-" )
log ("dimmer", "Exiting", 1)
}
//*********************************************************************************************************************************************************************
//******
//****** 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)
state.LastSync = new Date().format('yyyy-MM-dd HH:mm:ss')
callTasmota("STATE", "" )
}
//*****************************************************************************************************************************************************************************************************
//******
//****** 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.
//******
//******************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** 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.", -1)
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"]:
log("hubitatResponse","Command: Power ${body.POWER}", 1)
if (ActionValue.toUpperCase() == body.POWER){
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 (if applicable) must be zero. However, if TSync is enabled then it will fire a Sync anyway.
sendEvent(name: "switch", value: ActionValue.toLowerCase(), descriptionText: "The switch has been turned ${ActionValue.toLowerCase()}", isStateChange: true )
if ( ActionValue.toLowerCase() == "on" ) state.lastOn = new Date().format('MM-dd HH:mm:ss')
if ( ActionValue.toLowerCase() == "off" ) state.lastOff = new Date().format('MM-dd HH:mm:ss')
}
else {
log("hubitatResponse","Power state failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["DIMMER"]: //Usually referred to as Level in Hubitat
log("hubitatResponse", "Command: Dimmer ${body.DIMMER}", 1)
//We may use dimmer + or dimmer - to increment or decrement the actual dimmer brightness.
//So we need to handle a non numeric condition
try { if (ActionValue?.toInteger() == true) isInteger == true }
catch (e) {isInteger == False}
if ( isInteger == true) {
if ( ActionValue.toInteger() == body.DIMMER.toInteger() ){
log ("hubitatResponse", "Dimmer applied successfully", 0)
updateStatus("Complete:Success")
sendEvent(name: "level", value: ActionValue, displayed:true, isStateChange: true)
sendEvent(name: "switch", value: "on", displayed:true)
}
else {
updateStatus("Complete:Fail")
log("hubitatResponse","Dimmer state failed to apply", -1)
}
}
else {
//ActionValue was non numeric (Dimmer + or Dimmer -) so we have to assume the new value was a correct increment or decrement.
log ("hubitatResponse", "Dimmer ${ActionValue} applied successfully", 0)
updateStatus("Complete:Success")
sendEvent(name: "level", value: body.DIMMER.toInteger(), displayed:true, isStateChange: true)
sendEvent(name: "switch", value: "on", displayed:true)
}
break
case ["FADE"]: //This refers to the fade.
log("hubitatResponse", "Command FADE: ${body.FADE}", 1)
if (ActionValue.toUpperCase() == body.FADE){
log ("hubitatResponse","Fade applied successfully: ${body.FADE.toLowerCase()}", 0)
sendEvent(name:"Fade", value: "${body.FADE.toLowerCase()}", displayed:true, isStateChange: true)
updateStatus("Complete:Success")
}
else
{
log("hubitatResponse","Fade failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["SPEED"]: //This refers to the Speed of the fade. Larger numbers are longer.
log("hubitatResponse", "Command Speed: ${body.SPEED}", 1)
if (ActionValue.toInteger() == body.SPEED.toInteger() ){
log ("hubitatResponse","Fade Speed applied successfully: ${body.SPEED}", 0)
sendEvent(name:"FadeSpeed", value: "${body.SPEED}", displayed:true, isStateChange: true)
updateStatus("Complete:Success")
}
else
{
log("hubitatResponse","Fade Speed failed to apply", -1)
updateStatus("Complete:Fail")
}
break
case ["FANSPEED"]:
log("hubitatResponse","Command: FANSPEED ${body.FANSPEED}", 1)
if (ActionValue.toInteger() == body.FANSPEED ){
log ("hubitatResponse","Fanspeed 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.
sendEvent(name: "fanSpeed", value: body.FANSPEED)
setfanSpeedAttribute(body.FANSPEED)
}
else {
log("hubitatResponse","Power state 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"}}
log ("hubitatResponse","Setting device handler values to match device.", 0)
if (body?.FANSPEED) sendEvent(name: "fanSpeed", value: body.FANSPEED, displayed:false)
if (body?.DIMMER) sendEvent(name: "level", value: body.DIMMER.toInteger(), descriptionText: "The dimmer has been set to ${body.DIMMER.toInteger()}", isStateChange: true )
if (body?.SWITCH1) sendEvent(name: "switch", value: body.POWER.toLowerCase(), descriptionText: "The switch has been turned ${body.POWER.toLowerCase()}", isStateChange: true )
if (body?.FADE) sendEvent(name: "Fade", value: body.FADE, descriptionText: "Fade has been set to ${body.FADE}", isStateChange: true )
if (body?.SPEED) sendEvent(name: "Speed", value: body.SPEED, descriptionText: "Fade speed has been set to ${body.SPEED}", isStateChange: true )
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.
//******
//*************************************************************************************************************************************************************************************************************
def syncTasmota(body){
log ("syncTasmota", "Data received: ${body}", 0)
//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 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.lastTasmotaSync = new Date().format('yyyy-MM-dd HH:mm:ss')
//Now parse into JSON to extract data.
body = parseJson(body)
//Preset the values for when the %vars% are empty
switch1 = -1 ; dimmer = -1 ; fade = "SAME" ; fadespeed = -1 ; speed = -1
//A value of '' for any of these means no update. Probably because the device has restarted and the %vars% have not repopulated. This is expected.
if (body?.SWITCH1 != '') { switch1 = body?.SWITCH1 ; log ("syncTasmota","Switch is: ${switch1}", 2) }
if (body?.FANSPEED != '') { fanSpeed = body?.FANSPEED ; log ("syncTasmota","fanSpeed is: ${fanSpeed}", 2) }
if (body?.DIMMER != '') { dimmer = body?.DIMMER.toInteger() ; log ("syncTasmota","Dimmer is: ${dimmer}", 2) }
if (body?.FADE != '') { fade = body?.FADE.toInteger() ; log ("syncTasmota","Fade is: ${fade}", 2) }
if (body?.SPEED != '') { speed = body?.SPEED.toInteger() ; log ("syncTasmota","FadeSpeed is: ${speed}", 2) }
//Now apply any changes that have been found. In Tasmota, "power" is the switch state unless referring to sensor data.
//Only changes will get logged so we can report everything.
if ( switch1.toInteger() == 0 ) sendEvent(name: "switch", value: "off", descriptionText: "The switch was turned off.")
if ( switch1.toInteger() == 1 ) sendEvent(name: "switch", value: "on", descriptionText: "The switch was turned on.")
//Send fanSpeed event if we have new data. Ignore anything less than 0.
if ( fanSpeed >= 0 ) sendEvent(name: "fanSpeed", value: fanSpeed, descriptionText: "fanSpeed was set to ${fanSpeed}.")
//Send fade and fadespeed events if we have new data. Ignore anything less than 0.
if ( fade != "SAME" ) sendEvent(name: "Fade", value: "${fade}")
if ( speed >= 0 ) sendEvent(name: "FadeSpeed", value: "${speed}")
//Send dimmer events if we have new data. Ignore anything less than 0.
if ( dimmer >= 0 ) sendEvent(name: "level", value: dimmer, unit: "Percent" )
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: The only things that gets routed here are responses to requests for Sensor updates. Not used in this particular driver.
//******
//*************************************************************************************************************************************************************************************************************
def statusResponse(body){
log ("statusResponse", "Entering, data Received.", 1)
log ("statusResponse", "Raw data is: ${body}.", 2)
//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.
if ( (state.ActionValue == "8") && (body.STATUSSNS.ENERGY != null) )
{
state.lastSensorData = new Date().format('yyyy-MM-dd HH:mm:ss')
//Update the Power\Watts information.
if (settings.switchType.toInteger() >= 1){
if (body?.STATUSSNS?.ENERGY?.POWER != null ) {
log("updateData", "Watts is: ${body.STATUSSNS.ENERGY.POWER}" , 2)
sendEvent(name: "power", value: body.STATUSSNS.ENERGY.POWER )
}
}
//Do not send Current and Voltage events if reduced reporting has been selected
if (settings.switchType.toInteger() == 2){
if (body?.STATUSSNS?.ENERGY?.CURRENT != null ) { log("updateData", "Current is: ${body.STATUSSNS.ENERGY.CURRENT}" , 2) ; sendEvent(name: "current", value: body.STATUSSNS.ENERGY.CURRENT ) }
if (body?.STATUSSNS?.ENERGY?.VOLTAGE != null ) { log("updateData", "Voltage is: ${body.STATUSSNS.ENERGY.VOLTAGE}" , 2) ; sendEvent(name: "voltage", value: body.STATUSSNS.ENERGY.VOLTAGE ) }
}
log("statusResponse","STATUS 8 - ENERGY values processed.", 0)
updateStatus("Complete:Success")
}
else
{
log("statusResponse","STATUS 8 - NO ENERGY data found.", 0)
updateStatus("Complete:No Data")
}
log ("statusResponse","Closing Transaction", 1)
state.inTransaction = false
log ("statusResponse","Exiting", 0)
}
//******** End of statusResponse() ***************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** UNIQUE: Installs the rule onto the Tasmota device and enables it.
// Note that the variables are initially empty and the bulb has go through a change in Power, Color, Dimmer, CT, Fade and Speed before the values are all populated.
// This function is very unique on a driver by driver basis as the triggers are all different.
//******
//*************************************************************************************************************************************************************************************************************
def tasmotaInjectRule(){
log ("Action - tasmotaInjectRule","Injecting Rule3 into Tasmota Host. To verify go to Tasmota console and type: rule 3", 0)
state.ruleInjection = true
//Assemble the rule. It is broken up this way for readibility and debugging.
rule3 = "ON Power1#State DO backlog0 Var10 %value% ; RuleTimer1 1 ENDON "
rule3 = rule3 + "ON Dimmer DO backlog0 Var11 %value% ; RuleTimer1 1 ENDON "
rule3 = rule3 + "ON Fade#Data DO backlog Var12 %value% ; RuleTimer1 1 ENDON "
rule3 = rule3 + "ON Speed#Data DO backlog0 Var13 %value% ; RuleTimer1 1 ENDON "
rule3 = rule3 + "ON FanSpeed#Data DO backlog0 Var14 %value% ; RuleTimer1 1 ENDON "
rule3 = rule3 + "ON Rules#Timer=1 DO Var15 %Var10%,%Var11%,%Var12%,%Var13%,%Var14% ENDON "
//We have to use single quotes here as there is no way to pass a double quote via a URL. We will replace the single quote with a double quote when we get a response back so it can be handled as JSON.
rule3 = rule3 + "ON Var15#State\$!%Var16% DO backlog ; Var16 %Var15% ; webquery http://" + settings.HubIP + ":39501 POST {'TSync':'True','Switch1':'%Var10%','Dimmer':'%Var11%','Fade':'%Var12%','Speed':'%Var13%','FanSpeed':'%var14%'} ENDON "
//Now install the rule onto Tasmota
callTasmota("RULE3", rule3)
//and then make sure the rule is turned on.
command = "RULE3 ON"
def parameters = ["BACKLOG","${command}"]
//Runs the prepared BACKLOG command after the latest that last command could have finished.
runInMillis(remainingTime() + 50, "callTasmota", [data:parameters])
}
//*********************************************************************************************************************************************************************
//******
//****** End of main program section
//******
//*********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************
//********************** *****************************************************************************************************************
//********************** END OF UNIQUE FUNCTIONS *****************************************************************************************************************
//********************** EVERYTHING BELOW HERE IS *****************************************************************************************************************
//********************** COMMON CODE FOR ALL TSYNC *****************************************************************************************************************
//********************** FAMILY OF DRIVERS *****************************************************************************************************************
//********************** *****************************************************************************************************************
//*********************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************
/*
* CORE - IDENTICAL - CHANGELOG
* All changes to code in the CORE section will be commented here. Changes to the UNIQUE section that are made across all drivers will also be commented here.
* Version 0.91 - Internal version
* Version 0.92E - Global rename of some variables
* Version 0.93A - Enhancement of Tasmota rules to provide more granular data and less MEM usage. Although in the unique section this change was made across all drivers.
* Version 0.93B - Enhancement of Tasmota rules to use only a single MEM register.
* Version 0.94C - Tasmota rules moved to all VAR use, no MEM. Driver handles non-populated TSync fields.
* Version 0.95A - Updates to parse to handle inTransaction logic and reject lan messages after timeout window has closed.
* Version 0.95B - Added toggle function and state variables for lastOff and lastOn
* Version 0.96A - Tweaks to formatting of logging.
* Version 0.96B - Added logging enhancements with HTML tags. Added blue highlight to key fields in preferences.
* Version 0.96C - Added handling for Tasmota "WARNING" message that occurs when authentication fails and possibly other scenarios.
* Version 0.97 - Added option in settings to disable use of HTML enhancements in logging. These do not show correctly on a secondary hub in a two+ hub environment. This option allows them to be disabled.
* Version 0.98.0 - Changed versioning to comply with Semantic Versioning standards (https://semver.org/). Moved CORE changelog to beginning of CORE section.
* Version 0.98.1 - Added a "warning" category and label to the logging section.
* Version 0.98.2 - Added a "tooltip" function into the HTML area. Not yet being used.
*
*/
//*********************************************************************************************************************************************************************
//******
//****** STANDARD: Start of System Required Function
//******
//*********************************************************************************************************************************************************************
//Installed gets run when the device driver is selected and saved
def installed(){
log ("Installed", "Installed with settings: ${settings}", 0)
}
//Updated gets run when the "Save Preferences" button is clicked
def updated(){
log ("Update", "Settings: ${settings}", 0)
initialize()
}
//Uninstalled gets run when called from a parent app???
def uninstalled() {
log ("Uninstall", "Device uninstalled", 0)
}
//********************************************************************************************************************************************************************
//******
//****** End of System Required functions
//******
//********************************************************************************************************************************************************************
//**************************************************************************************************************************************************************************
//******
//****** STANDARD: Start of Background task run by Hubitat - Is executed by the polling function which syncs the state of the device with the UI. The device being considered authoritative.
//****** All of these functions are IDENTICAL across all Tasmota Sync drivers
//******
//**************************************************************************************************************************************************************************
//Runs on a frequency determined by the user. It will synchronize the Hubitat values to those of the actual device.
//This function is only called internally and is used to schedule future refreshes. Polling is not require with Tasmota 11 and Rule3 installed.
def poll(nextPoll){
log ("Poll", "Polling started.. ", 0)
refresh()
log ("Poll", "Polling ended. Next poll in ${settings.pollFrequency} seconds.", 0)
}
//This function is called settings.timeout milliseconds after the the transaction started.
//If the transaction has timed then it resets out and resets any temporary values.
def watchdog(){
if (state.inTransaction == false ) {
log ("watchdog", "All normal. Not in a transaction.", 2)
}
else
{
log ("watchdog", "Transaction timed out. Cancelled.", 2)
updateStatus("Complete:Timeout")
//If the transaction has not finished successfully then we should mark it complete now the timeout has expired.
state.inTransaction = false
}
state.remove("ruleInjection")
log ("watchdog", "Finished.", 1)
//If the last command was a backlog then we don't really know what happened so we should do a refresh.
if ( state.Action == "BACKLOG" ) {
log ("watchdog", "Last command was a BACKLOG. Initiating STATE refresh for current settings.", 0)
//Calculate when the current operations should be finished and schedule the "STATE" command to run after them.
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 located in this section.
//****** The functions syncTasmota, hubitatResponse() and tasmotaInjectRule() are UNIQUE and can be found near the beginning of the file.
//******
//*************************************************************************************************************************************************************************************************************
//*************************************************************************************************************************************************************************************************************
//******
//****** STANDARD: This function places a call to the Tasmota device using HTTP via a hubCommand. A successful call will result in an HTTP response to the parse() function. The HUB IP address must be configured.
//******
//*************************************************************************************************************************************************************************************************************
def callTasmota(action, receivedvalue){
log ("callTasmota", "Sending command: ${action} ${receivedvalue}", 0)
//Update the status to show that we are sending info to the device
def actionValue = receivedvalue.toString()
if (actionValue == "") {actionValue = "None"}
state.Action = action
state.ActionValue = actionValue
//Capture what we are doing so we can validate whether it executed successfully or not
//We are essentially using the Attribute "Action" as a container for global variables.
state.startTime = now()
log ("callTasmota","Opening Transaction", 2)
state.inTransaction = true
//Watchdog is used to ensure that the transaction state is closed after the expiration time. Subsequent data will be ignored unless it is a TSync request.
log ("callTasmota", "Starting Watchdog", 3)
runInMillis(settings.timeout, "watchdog")
path = "/cm?user=${username}&password=${password}&cmnd=${action} ${actionValue}"
def newPath = cleanURL(path)
log ("callTasmota", "Path: ${newPath}", 3)
try {
def hubAction = new hubitat.device.HubAction(
method: "GET",
path: newPath,
headers: [HOST: "${settings.destIP}:${settings.destPort}"]
)
log ("callTasmota", "hubaction: ${hubAction}", 3)
sendHubCommand(hubAction)
updateStatus("Sent:${action} ${receivedvalue}")
}
catch (Exception e) {
log ("calltasmota", "Exception $e in $hubAction", -1)
}
//The response to this HubAction request will come back to the parse function.
log ("callTasmota","Exiting", 1)
}
//*****************************************************************************************************************************************************************************************************
//******
//****** STANDARD: parse(). This function handles all communication from Tasmota, both the Hubitat and Tasmota initiated changes.
//****** When these changes originate on Hubitat they will be routed to hubitatResponse.
//****** When the changes originate on Tasmota they will be routed to syncTasmota for hubitatResponse() and statusResponse() for SENSOR data if applicable
//****** Note: A Hubitat initiated change will cause RULE3 on Tasmota to fire and ALSO send a TSync request. This is expected.....
//****** Note: .....if they are received during a transaction (inTransaction==true) then they are ignored as they are just an "echo" of the command sent from Hubitat.
//****** Note: .....These are ignored when within the debounce window.
//******
//*****************************************************************************************************************************************************************************************************
def parse(LanMessage){
log ("parse", "Entering, data received.", 1)
log ("parse","data is ${LanMessage}", 3)
def msg = parseLanMessage(LanMessage)
def body = msg.body
log ("parse","body is ${body}", 2)
state.lastMessage = state.thisMessage
state.thisMessage = msg.body
//TSync message use single quotes and must be cleaned up to be handled as JSON later
body = body?.replace("'","\"")
//Convert all the contents to upper case for consistency
body = body?.toUpperCase()
//Search body for the word STATUS while it is still in string form
StatusSync = false
if (body.contains("STATUS")==true ) StatusSync = true
log ("parse","StatusSync is: ${StatusSync}.", 2)
//Search body for the word TSYNC while it is still in string form
TSync = false
if (body.contains("TSYNC")==true ) TSync = true
log ("parse","TSync is: ${TSync}.", 2)
//If the TSync flag is true then this is a message generated by the Tasmota rules and we should send the response to syncTasmota function.
if (TSync == true) {
log ("parse","Exit to syncTasmota()", 1)
syncTasmota(body)
return
}
//For every other response we need to check to see if we are in a transaction or not.
//If inTransaction == true then we need to processs it. If inTransaction == false then the response was received after the timeout window has closed.
//If this happens we will acknowledge it and discard the data. This does not apply to TSync requests as they can occur at any time.
if (state.inTransaction == true ) {
//This is for an responses that contain the word STATUS which means they are probably responses to STATUS 1 - 12 requests.
if (StatusSync == true){
log ("parse","Exit to statusResponse()", 1)
statusResponse(body)
return
}
//If we were not routed to syncTasmota or statusResponse then everything else goes to main hubitatResponse function
log ("parse","Exit to hubitatResponse()", 1)
hubitatResponse(body)
}
else{
log ("parse","Data has been received outside the timeout window and has been ignored - exiting. (Increase the timeout window if this happens frequently.)", 0)
}
}
//*****************************************************************************************************************************************************************************************************
//****** End of parse()
//*****************************************************************************************************************************************************************************************************
//*********************************************************************************************************************************************************************
//******
//****** Start of logging related functions. These functions are IDENTICAL in all Tasmota Sync drivers
//******
//*********************************************************************************************************************************************************************
//Simple function to send event message and log them.
def updateStatus(status){
log ("updateStatus", status, 1)
sendEvent(name: "Status", value: status )
}
//*****************************************************************************************************************************************************************************************************
//******
//****** STANDARD: Start of log()
//****** Function to selectively log activity based on various logging levels. Normal runtime configuration is threshold = 0
//****** Loglevels are cumulative: -1 All errors, 0 = Action and results, 1 = Entering\Exiting modules with parameters, 2 = Key variables, 3 = Extended debugging info
//******
//*****************************************************************************************************************************************************************************************************
private log(name, message, int loglevel){
//This is a quick way to filter out messages based on loglevel
int threshold = settings.logging_level
if (loglevel > threshold) {return}
def indent = ""
def icon1 = ""
def icon2 = ""
def icon3 = ""
if (loglevel == -1) {
icon1 = "π " //This is reserved for gross errors
indent = ""
}
if (loglevel == 0) {
icon1 = "0οΈβ£" //Used for normal operations, on, off, Color change etc
indent = ""
}
if (loglevel == 1) {
icon1 = "*οΈβ£1οΈβ£" //Adds entering\exiting functions with basic parameters
indent = ".."
}
if (loglevel == 2) {
icon1 = "*οΈβ£*οΈβ£2οΈβ£" //Adds display of additional data points
indent = "...."
}
if (loglevel == 3) {
icon1 = "*οΈβ£*οΈβ£*οΈβ£3οΈβ£" //Used for diagnostic logging. Everything else that was not previously covered.
indent = "......"
}
//These will be the default icons for the primary functions. Others that may be useful in future βοΈ π π π π π¬ β°οΈ πͺ π£
if (name.toString().toUpperCase().contains("CALLTASMOTA")==true ) icon2 = "π "
if (name.toString().toUpperCase().contains("ACTION")==true ) icon2 = "β‘ "
if (name.toString().toUpperCase().contains("DELETE")==true ) icon2 = "ποΈ "
if (name.toString().toUpperCase().contains("SAVE")==true ) icon2 = "πΎ "
if (name.toString().toUpperCase().contains("WATCHDOG")==true ) icon2 = "πΆ "
//These will ovverride the secondary icons Keyword search and icon replacement. Obviously icon2 may get overwritten so order is important.
if (message.toString().toUpperCase().contains("APPLIED SUCCESSFULLY")==true ) icon2 = "β "
if (message.toString().toUpperCase().contains("FAILED TO APPLY")==true ) icon2 = "π© "
if (message.toString().toUpperCase().contains("WARNING")==true ) icon2 = "π© "
if (message.toString().toUpperCase().contains("ENTER")==true ) icon2 = "π "
if (message.toString().toUpperCase().contains("FINISH")==true ) icon3 = "π "
if (name.toString().toUpperCase().contains("SYNC")==true ) icon2 = "π "
if (message.toString().toUpperCase().contains("EXIT")==true ) icon2 = "π¨ "
if (message.toString().toUpperCase().contains("<CRLF>")==true ) { message = message.replace("<CRLF>","\nπ· ") }
if ( (name.toString().toUpperCase().contains("ACTION")==true ) && (message.toString().toUpperCase().contains("COLOR")==true ) ) icon3 = "π¨"
displayName = ""
newMessage = message
//log.info ("settings.loggingEnhancements: " + settings.loggingEnhancements )
switch(settings.loggingEnhancements) {
case "0":
break
case "1":
displayName = device.displayName + " - "
break
case "2":
break
case "3":
displayName = blue(device.displayName) + " - "
}
//For logging enhancements (2 & 3) then we make the newMessage formatted with HTML colors. 0 & 1 have no HTML
if ( settings.loggingEnhancements == "2" || settings.loggingEnhancements == "3") {
if ( loglevel <= 0 ) {
//If the logging level is 0 then we do not need to highlight the display as much as we are not trying to make it stand out against anything.
if ( settings.logging_level == 0 ) newMessage = name + ": " + green(message)
else newMessage = bold(name) + ": " + green(bold(message))
}
if ( loglevel == 1 ) newMessage = black(name) + ": " + green(message)
if ( loglevel == 2 ) newMessage = goldenrod(name) + ": " + goldenrod(message)
if ( loglevel >= 3 ) newMessage = midnightBlue(name) + ": " + midnightBlue(message)
}
if ( loglevel <= 1 ) { log.info ( displayName + icon1 + icon2 + icon3 + indent + newMessage) }
if ( loglevel >= 2 ) { log.debug ( displayName + icon1 + icon2 + icon3 + indent + newMessage) }
}
//*********************************************************************************************************************************************************************
//****** End of log function
//*********************************************************************************************************************************************************************
//*****************************************************************************************************************************************************************************************************
//******
//****** Start of HTML enhancement functions. Primarily used for logging with a few uses in settings. Most of these are unused but easier to just keep everything.
//******
//*****************************************************************************************************************************************************************************************************