-
Notifications
You must be signed in to change notification settings - Fork 7
/
Evohome Connect SmartApp R3.4.txt
1680 lines (1430 loc) · 58.6 KB
/
Evohome Connect SmartApp R3.4.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2021 Andreas Christodoulou (Andremain)
*
* Name: Evohome (Connect)
*
* Author: Andreas Christodoulou (Andremain)
*
* Date: 28/01/2021
*
* Version: 2.3
*
* Description:
* - Connect your Honeywell Evohome System to SmartThings.
* - Requires the Evohome Heating Zone device handler.
* - For latest documentation see: https://github.com/andremain/EvohomeSmartthingsNew
* Version History:
*
* 2021-02-16: v3.2
* Added a clause to exit the loop when checking the integration for hot water, as if there was none, the connection would result in error.
*
* 2020-12-22: v2.1 Removed Deprecated set temperature option at the automation actions
*
* 2020-12-22: v2.0 First release of the new integration.
*
* 2020-12-20: v0.21 Removed the cooling option when creating an automation in the IF statement (DO BE DONE!!!)
*
* 2020-12-18: v0.20 Changed the links for the documentation and images to work.
*
* 2020-12-16: v0.19 Changed the owner of the smartapp and dht to Andremain (mine)
*
* 2020-12-14: v0.18 Managed to get all the modes to work with the new app's presentation
*
* 2020-12-13: v0.17 Managed to get the Auto, away, custom and off modes to work with the new app's presentation. Some list items appear wierd but this is a Smartthings issue
*
* 2020-12-11: v0.16 Managed to get the correct thermostat modes to show app in the modes list in the new app presentation
*
* 2020-12-9: v0.15 Changed the default value for window function temperature from 5.0 to 5 as it would throw a bad request error
*
* 2020-12-8: v0.14 Added an initialize function for the new thermostat capabilities
*
* 2020-12-6: v0.13 Removed the old custom and depricated capabilited from the old code
*
* 2020-12-3: v0.12 Generated the Presentation file required by the new smartthings app for correctly displaying the options for the inside the new app
*
* 2020-11-30: v0.11 Fixed the Checking Status on the dashboard tile for use with the new Smartthings app
*
* 2020-11-28: v0.10 Added The new capababilities for the depricated thermostat capability used by the new smartthings app
*
* 2020-11-02: v0.09 Fixed the API endpoint to be the new one that Honeywell Evohome uses.
*
* 2016-04-19: v0.10
* - formatTemperature() - Improved error handling.
* - Mid-development of DHW zone support.
* - To Do: Add parsing of DHW schedules. - NEED SAMPLE DATA
*
* 2016-04-17: v0.09
* - updateChildDevice() - Sends two new attribute values to child devices:
* thermostatModeMode: 'temporary' or 'permanent'.
* thermostatModeUntil: Contains date string if thermostatModeMode is temporary.
*
* 2016-04-05: v0.08
* - New 'Update Refresh Time' setting to control polling after making an update.
* - poll() - If onlyZoneId is 0, this will force a status update for all zones.
*
* 2016-04-04: v0.07
* - Additional info log messages.
*
* 2016-04-03: v0.06
* - Initial Beta Release
*
* License:
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
*/
definition(
name: "Evohome (Connect)",
namespace: "worldhouse47531",
author: "Andreas Christodoulou",
description: "Connect your Honeywell Evohome System to SmartThings.",
category: "My Apps",
iconUrl: "https://i.ibb.co/SwyYJWb/Evohome.png",
iconX2Url: "https://i.ibb.co/SwyYJWb/Evohome.png",
iconX3Url: "https://i.ibb.co/SwyYJWb/Evohome.png",
singleInstance: true
)
preferences {
section ("Evohome:") {
input "prefEvohomeUsername", "text", title: "Username", required: true, displayDuringSetup: true
input "prefEvohomePassword", "password", title: "Password", required: true, displayDuringSetup: true
input title: "Advanced Settings:", displayDuringSetup: true, type: "paragraph", element: "paragraph", description: "Change these only if needed"
input "prefEvohomeStatusPollInterval", "number", title: "Polling Interval (minutes)", range: "1..60", defaultValue: 5, required: true, displayDuringSetup: true, description: "Poll Evohome every n minutes"
input "prefEvohomeUpdateRefreshTime", "number", title: "Update Refresh Time (seconds)", range: "2..60", defaultValue: 3, required: true, displayDuringSetup: true, description: "Wait n seconds after an update before polling"
input "prefEvohomeWindowFuncTemp", "decimal", title: "Window Function Temperature", range: "0..100", defaultValue: 5, required: true, displayDuringSetup: true, description: "Must match Evohome controller setting"
input "prefEvohomeDHWTemp", "decimal", title: "Hot Water Target Temperature", range: "0..100", defaultValue: 55, required: true, displayDuringSetup: true, description: "Must match Evohome controller setting"
input title: "Thermostat Modes", description: "Configure how long thermostat modes are applied for by default. Set to zero to apply modes permanently.", displayDuringSetup: true, type: "paragraph", element: "paragraph"
input 'prefThermostatModeDuration', 'number', title: 'Away/Custom/DayOff Mode (days):', range: "0..99", defaultValue: 0, required: true, displayDuringSetup: true, description: 'Apply thermostat modes for this many days'
input 'prefThermostatEconomyDuration', 'number', title: 'Economy Mode (hours):', range: "0..24", defaultValue: 0, required: true, displayDuringSetup: true, description: 'Apply economy mode for this many hours'
}
section("General:") {
input "prefDebugMode", "bool", title: "Enable debug logging?", defaultValue: true, displayDuringSetup: true
}
}
/**********************************************************************
* Setup and Configuration Commands:
**********************************************************************/
/**
* installed()
*
* Runs when the app is first installed.
*
**/
def installed() {
atomicState.installedAt = now()
log.debug "${app.label}: Installed with settings: ${settings}"
}
/**
* uninstalled()
*
* Runs when the app is uninstalled.
*
**/
def uninstalled() {
if(getChildDevices()) {
removeChildDevices(getChildDevices())
}
}
/**
* updated()
*
* Runs when app settings are changed.
*
**/
void updated() {
if (atomicState.debug) log.debug "${app.label}: Updating with settings: ${settings}"
// General:
atomicState.debug = settings.prefDebugMode
// Evohome:
atomicState.evohomeEndpoint = 'https://mytotalconnectcomfort.com/WebApi'
atomicState.evohomeAuth = [tokenLifetimePercentThreshold : 50] // Auth Token will be refreshed when down to 50% of its lifetime.
atomicState.evohomeStatusPollInterval = settings.prefEvohomeStatusPollInterval // Poll interval for status updates (minutes).
atomicState.evohomeSchedulePollInterval = 60 // Hardcoded to 1hr (minutes).
atomicState.evohomeUpdateRefreshTime = settings.prefEvohomeUpdateRefreshTime // Wait this many seconds after an update before polling.
// Thermostat Mode Durations:
atomicState.thermostatModeDuration = settings.prefThermostatModeDuration
atomicState.thermostatEconomyDuration = settings.prefThermostatEconomyDuration
// Force Authentication:
authenticate()
// Refresh Subscriptions and Schedules:
manageSubscriptions()
manageSchedules()
// Refresh child device configuration:
getEvohomeConfig()
updateChildDeviceConfig()
// Run a poll, but defer it so that updated() returns sooner:
runIn(5, "poll")
}
/**********************************************************************
* Management Commands:
**********************************************************************/
/**
* manageSchedules()
*
* Check scheduled tasks have not stalled, and re-schedule if necessary.
* Generates a random offset (seconds) for each scheduled task.
*
* Schedules:
* - manageAuth() - every 5 mins.
* - poll() - every minute.
*
**/
void manageSchedules() {
if (atomicState.debug) log.debug "${app.label}: manageSchedules()"
// Generate a random offset (1-60):
Random rand = new Random(now())
def randomOffset = 0
// manageAuth (every 5 mins):
if (1==1) { // To Do: Test if schedule has actually stalled.
if (atomicState.debug) log.debug "${app.label}: manageSchedules(): Re-scheduling manageAuth()"
try {
unschedule(manageAuth)
}
catch(e) {
//if (atomicState.debug) log.debug "${app.label}: manageSchedules(): Unschedule failed"
}
randomOffset = rand.nextInt(60)
schedule("${randomOffset} 0/5 * * * ?", "manageAuth")
}
// poll():
if (1==1) { // To Do: Test if schedule has actually stalled.
if (atomicState.debug) log.debug "${app.label}: manageSchedules(): Re-scheduling poll()"
try {
unschedule(poll)
}
catch(e) {
//if (atomicState.debug) log.debug "${app.label}: manageSchedules(): Unschedule failed"
}
randomOffset = rand.nextInt(60)
schedule("${randomOffset} 0/1 * * * ?", "poll")
}
}
/**
* manageSubscriptions()
*
* Unsubscribe/Subscribe.
**/
void manageSubscriptions() {
if (atomicState.debug) log.debug "${app.label}: manageSubscriptions()"
// Unsubscribe:
unsubscribe()
// Subscribe to App Touch events:
subscribe(app,handleAppTouch)
}
/**
* manageAuth()
*
* Ensures authenication token is valid.
* Refreshes Auth Token if lifetime has exceeded evohomeAuthTokenLifetimePercentThreshold.
* Re-authenticates if Auth Token has expired completely.
* Otherwise, done nothing.
*
* Should be scheduled to run every 1-5 minutes.
**/
void manageAuth() {
if (atomicState.debug) log.debug "${app.label}: manageAuth()"
// Check if Auth Token is valid, if not authenticate:
if (!atomicState.evohomeAuth.authToken) {
log.info "${app.label}: manageAuth(): No Auth Token. Authenticating..."
authenticate()
}
else if (atomicState.evohomeAuthFailed) {
log.info "${app.label}: manageAuth(): Auth has failed. Authenticating..."
authenticate()
}
else if (!atomicState.evohomeAuth.expiresAt.isNumber() || now() >= atomicState.evohomeAuth.expiresAt) {
log.info "${app.label}: manageAuth(): Auth Token has expired. Authenticating..."
authenticate()
}
else {
// Check if Auth Token should be refreshed:
def refreshAt = atomicState.evohomeAuth.expiresAt - ( 1000 * (atomicState.evohomeAuth.tokenLifetime * atomicState.evohomeAuth.tokenLifetimePercentThreshold / 100))
if (now() >= refreshAt) {
log.info "${app.label}: manageAuth(): Auth Token needs to be refreshed before it expires."
refreshAuthToken()
}
else {
log.info "${app.label}: manageAuth(): Auth Token is okay."
}
}
}
/**
* poll(onlyZoneId=-1)
*
* This is the main command that co-ordinates retrieval of information from the Evohome API
* and its dissemination to child devices. It should be scheduled to run every minute.
*
* Different types of information are collected on different schedules:
* - Zone status information is polled according to ${evohomeStatusPollInterval}.
* - Zone schedules are polled according to ${evohomeSchedulePollInterval}.
*
* poll() can be called by a child device when an update has been made, in which case
* onlyZoneId will be specified, and only that zone will be updated.
*
* If onlyZoneId is 0, this will force a status update for all zones, igonoring the poll
* interval. This should only be used after setThremostatMode() call.
*
* If onlyZoneId is not specified all zones are updated, but only if the relevent poll
* interval has been exceeded.
*
**/
void poll(onlyZoneId=-1) {
if (atomicState.debug) log.debug "${app.label}: poll(${onlyZoneId})"
// Check if there's been an authentication failure:
if (atomicState.evohomeAuthFailed) {
manageAuth()
}
if (onlyZoneId == 0) { // Force a status update for all zones (used after a thermostatMode update):
getEvohomeStatus()
updateChildDevice()
}
else if (onlyZoneId != -1) { // A zoneId has been specified, so just get the status and update the relevent device:
getEvohomeStatus(onlyZoneId)
updateChildDevice(onlyZoneId)
}
else { // Get status and schedule for all zones, but only if the relevent poll interval has been exceeded:
// Adjust intervals to allow for poll() execution time:
def evohomeStatusPollThresh = (atomicState.evohomeStatusPollInterval * 60) - 30
def evohomeSchedulePollThresh = (atomicState.evohomeSchedulePollInterval * 60) - 30
// Get zone status:
if (!atomicState.evohomeStatusUpdatedAt || atomicState.evohomeStatusUpdatedAt + (1000 * evohomeStatusPollThresh) < now()) {
getEvohomeStatus()
}
// Get zone schedules:
if (!atomicState.evohomeSchedulesUpdatedAt || atomicState.evohomeSchedulesUpdatedAt + (1000 * evohomeSchedulePollThresh) < now()) {
getEvohomeSchedules()
}
// Update all child devices:
updateChildDevice()
}
}
/**********************************************************************
* Event Handlers:
**********************************************************************/
/**
* handleAppTouch(evt)
*
* App touch event handler.
* Used for testing and debugging.
*
**/
void handleAppTouch(evt) {
if (atomicState.debug) log.debug "${app.label}: handleAppTouch()"
//manageAuth()
//manageSchedules()
//getEvohomeConfig()
//updateChildDeviceConfig()
getEvohomeSchedules()
//poll()
}
/**********************************************************************
* SmartApp-Child Interface Commands:
**********************************************************************/
/**
* updateChildDeviceConfig()
*
* Add/Remove/Update child devices based on atomicState.evohomeConfig.
*
**/
void updateChildDeviceConfig() {
if (atomicState.debug) log.debug "${app.label}: updateChildDeviceConfig()"
// Build list of active DNIs, any existing children with DNIs not in here will be deleted.
def activeDnis = []
// Iterate through evohomeConfig, adding new 'Evohome Heating Zone' and 'Evohome Hot Water Zone' devices where necessary.
atomicState.evohomeConfig.each { loc ->
loc.gateways.each { gateway ->
gateway.temperatureControlSystems.each { tcs ->
// Heating Zones:
tcs.zones.each { zone ->
def dni = generateDni(loc.locationInfo.locationId, gateway.gatewayInfo.gatewayId, tcs.systemId, zone.zoneId )
activeDnis << dni
def values = [
'debug': atomicState.debug,
'updateRefreshTime': atomicState.evohomeUpdateRefreshTime,
'minHeatingSetpoint': formatTemperature(zone?.heatSetpointCapabilities?.minHeatSetpoint),
'maxHeatingSetpoint': formatTemperature(zone?.heatSetpointCapabilities?.maxHeatSetpoint),
'temperatureResolution': zone?.heatSetpointCapabilities?.valueResolution,
'windowFunctionTemperature': formatTemperature(settings.prefEvohomeWindowFuncTemp),
'zoneType': zone?.zoneType,
'locationId': loc.locationInfo.locationId,
'gatewayId': gateway.gatewayInfo.gatewayId,
'systemId': tcs.systemId,
'zoneId': zone.zoneId
]
def d = getChildDevice(dni)
if(!d) {
try {
values.put('label', "${zone.name} Heating Zone (Evohome)")
log.info "${app.label}: updateChildDeviceConfig(): Creating device: Name: ${values.label}, DNI: ${dni}"
d = addChildDevice(app.namespace, "Evohome Heating Zone R3.4", dni, null, values) //Change the name here to change the name of the device
} catch (e) {
log.error "${app.label}: updateChildDeviceConfig(): Error creating device: Name: ${values.label}, DNI: ${dni}, Error: ${e}"
}
}
if(d) {
d.generateEvent(values)
}
}
// Hot Water Zone:
if (tcs.dhw) {
def dni = generateDni(loc.locationInfo.locationId, gateway.gatewayInfo.gatewayId, tcs.systemId, tcs.dhw.dhwId )
activeDnis << dni
def values = [
'debug': atomicState.debug,
'updateRefreshTime': atomicState.evohomeUpdateRefreshTime,
'dhwTemperature': formatTemperature(settings.prefEvohomeDHWTemp),
'zoneType': 'DHW',
'locationId': loc.locationInfo.locationId,
'gatewayId': gateway.gatewayInfo.gatewayId,
'systemId': tcs.systemId,
'zoneId': tcs.dhw.dhwId
]
log.info "${app.label}: updateChildDeviceConfig(): Found a hot water zone! Values: ${values}"
def d = getChildDevice(dni)
if(!d) {
try {
values.put('label', "Hot Water (Evohome)")
log.info "${app.label}: updateChildDeviceConfig(): Creating Hot Water Zone: DNI: ${dni}"
d = addChildDevice(app.namespace, "Evohome Hot Water Zone R3.4", dni, null, values)
} catch (e) {
log.error "${app.label}: updateChildDeviceConfig(): Error creating device: Name: ${values.label}, DNI: ${dni}, Error: ${e}"
}
}
if(d) {
d.generateEvent(values)
}
}
}
}
}
if (atomicState.debug) log.debug "${app.label}: updateChildDeviceConfig(): Active DNIs: ${activeDnis}"
// Delete Devices:
def delete = getChildDevices().findAll { !activeDnis.contains(it.deviceNetworkId) }
if (atomicState.debug) log.debug "${app.label}: updateChildDeviceConfig(): Found ${delete.size} devices to delete."
delete.each {
log.info "${app.label}: updateChildDeviceConfig(): Deleting device with DNI: ${it.deviceNetworkId}"
try {
deleteChildDevice(it.deviceNetworkId)
}
catch(e) {
log.error "${app.label}: updateChildDeviceConfig(): Error deleting device with DNI: ${it.deviceNetworkId}. Error: ${e}"
}
}
}
/**
* updateChildDevice(onlyZoneId=-1)
*
* Update the attributes of a child device from atomicState.evohomeStatus
* and atomicState.evohomeSchedules.
*
* If onlyZoneId is not specified, then all zones are updated.
*
* Recalculates scheduledSetpoint, nextScheduledSetpoint, and nextScheduledTime.
*
**/
void updateChildDevice(onlyZoneId=-1) {
if (atomicState.debug) log.debug "${app.label}: updateChildDevice(${onlyZoneId})"
atomicState.evohomeStatus.each { loc ->
loc.gateways.each { gateway ->
gateway.temperatureControlSystems.each { tcs ->
// Heating Zones:
tcs.zones.each { zone ->
if (onlyZoneId == -1 || onlyZoneId == zone.zoneId) { // Filter on zoneId if one has been specified.
def dni = generateDni(loc.locationId, gateway.gatewayId, tcs.systemId, zone.zoneId)
def d = getChildDevice(dni)
if(d) {
def schedule = atomicState.evohomeSchedules.find { it.dni == dni}
def currSw = getCurrentSwitchpoint(schedule.schedule)
def nextSw = getNextSwitchpoint(schedule.schedule)
def values = [
'temperature': formatTemperature(zone?.temperatureStatus?.temperature),
//'isTemperatureAvailable': zone?.temperatureStatus?.isAvailable,
'heatingSetpoint': formatTemperature(zone?.heatSetpointStatus?.targetTemperature),
'thermostatSetpoint': formatTemperature(zone?.heatSetpointStatus?.targetTemperature),
'thermostatSetpointMode': decapitalise(zone?.heatSetpointStatus?.setpointMode),
'thermostatSetpointUntil': zone?.heatSetpointStatus?.until,
'thermostatMode': formatThermostatMode(tcs?.systemModeStatus?.mode),
'thermostatModeMode': (tcs?.systemModeStatus?.isPermanent) ? 'permanent' : 'temporary',
'thermostatModeUntil': tcs?.systemModeStatus?.timeUntil,
'scheduledSetpoint': formatTemperature(currSw.temperature),
'nextScheduledSetpoint': formatTemperature(nextSw.temperature),
'nextScheduledTime': nextSw.time
]
if (atomicState.debug) log.debug "${app.label}: updateChildDevice(): Updating Device with DNI: ${dni} with data: ${values}"
d.generateEvent(values)
} else {
if (atomicState.debug) log.debug "${app.label}: updateChildDevice(): Device with DNI: ${dni} does not exist."
}
}
}
// Hot Water Zone:
if (tcs.dhw && (onlyZoneId == -1 || onlyZoneId == tcs.dhw.dhwId)) { // Filter on zoneId if one has been specified.
def dni = generateDni(loc.locationId, gateway.gatewayId, tcs.systemId, tcs.dhw.dhwId)
def d = getChildDevice(dni)
if(d) {
//def schedule = atomicState.evohomeSchedules.find { it.dni == dni}
//def currSw = getCurrentSwitchpoint(schedule.schedule)
//def nextSw = getNextSwitchpoint(schedule.schedule)
def values = [
'temperature': formatTemperature(tcs.dhw?.temperatureStatus?.temperature),
//'isTemperatureAvailable': tcs.dhw?.temperatureStatus?.isAvailable,
'switch': tcs.dhw?.stateStatus?.state.toLowerCase(),
'switchStateMode': decapitalise(tcs.dhw?.stateStatus?.mode),
'switchStateUntil': tcs.dhw?.stateStatus?.until,
'thermostatMode': formatThermostatMode(tcs?.systemModeStatus?.mode),
'thermostatModeMode': (tcs?.systemModeStatus?.isPermanent) ? 'permanent' : 'temporary',
'thermostatModeUntil': tcs?.systemModeStatus?.timeUntil
// 'scheduledSwitchState': ??
// 'nextScheduledSwitchState': ??
// 'nextScheduledTime': ??
]
if (atomicState.debug) log.debug "${app.label}: updateChildDevice(): Updating Device with DNI: ${dni} with data: ${values}"
d.generateEvent(values)
} else {
if (atomicState.debug) log.debug "${app.label}: updateChildDevice(): Device with DNI: ${dni} does not exist."
}
}
}
}
}
}
/**********************************************************************
* Evohome API Commands:
**********************************************************************/
/**
* authenticate()
*
* Authenticate to Evohome.
*
**/
private authenticate() {
if (atomicState.debug) log.debug "${app.label}: authenticate()"
def requestParams = [
method: 'POST',
uri: 'https://mytotalconnectcomfort.com/WebApi',
path: '/Auth/OAuth/Token',
headers: [
'Authorization': 'Basic YjAxM2FhMjYtOTcyNC00ZGJkLTg4OTctMDQ4YjlhYWRhMjQ5OnRlc3Q=',
'Accept': 'application/json, application/xml, text/json, text/x-json, text/javascript, text/xml',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
],
body: [
'grant_type': 'password',
'scope': 'EMEA-V1-Basic EMEA-V1-Anonymous EMEA-V1-Get-Current-User-Account',
'Username': settings.prefEvohomeUsername,
'Password': settings.prefEvohomePassword
]
]
try {
httpPost(requestParams) { resp ->
if(resp.status == 200 && resp.data) {
// Update evohomeAuth:
// We can't just '.put' or '<<' with atomicState, we have to make a temp copy, edit, and then re-assign.
def tmpAuth = atomicState.evohomeAuth ?: [:]
tmpAuth.put('lastUpdated' , now())
tmpAuth.put('authToken' , resp?.data?.access_token)
tmpAuth.put('tokenLifetime' , resp?.data?.expires_in.toInteger() ?: 0)
tmpAuth.put('expiresAt' , now() + (tmpAuth.tokenLifetime * 1000))
tmpAuth.put('refreshToken' , resp?.data?.refresh_token)
atomicState.evohomeAuth = tmpAuth
atomicState.evohomeAuthFailed = false
if (atomicState.debug) log.debug "${app.label}: authenticate(): New evohomeAuth: ${atomicState.evohomeAuth}"
def exp = new Date(tmpAuth.expiresAt)
log.info "${app.label}: authenticate(): New Auth Token Expires At: ${exp}"
// Update evohomeHeaders:
def tmpHeaders = atomicState.evohomeHeaders ?: [:]
tmpHeaders.put('Authorization',"bearer ${atomicState.evohomeAuth.authToken}")
tmpHeaders.put('applicationId', 'b013aa26-9724-4dbd-8897-048b9aada249')
tmpHeaders.put('Accept', 'application/json, application/xml, text/json, text/x-json, text/javascript, text/xml')
atomicState.evohomeHeaders = tmpHeaders
if (atomicState.debug) log.debug "${app.label}: authenticate(): New evohomeHeaders: ${atomicState.evohomeHeaders}"
// Now get User Account info:
getEvohomeUserAccount()
}
else {
log.error "${app.label}: authenticate(): No Data. Response Status: ${resp.status}"
atomicState.evohomeAuthFailed = true
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: authenticate(): Error: e.statusCode ${e.statusCode}"
atomicState.evohomeAuthFailed = true
}
}
/**
* refreshAuthToken()
*
* Refresh Auth Token.
* If token refresh fails, then authenticate() is called.
* Request is simlar to authenticate, but with grant_type = 'refresh_token' and 'refresh_token'.
*
**/
private refreshAuthToken() {
if (atomicState.debug) log.debug "${app.label}: refreshAuthToken()"
def requestParams = [
method: 'POST',
uri: 'https://mytotalconnectcomfort.com/WebApi',
path: '/Auth/OAuth/Token',
headers: [
'Authorization': 'Basic YjAxM2FhMjYtOTcyNC00ZGJkLTg4OTctMDQ4YjlhYWRhMjQ5OnRlc3Q=',
'Accept': 'application/json, application/xml, text/json, text/x-json, text/javascript, text/xml',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
],
body: [
'grant_type': 'refresh_token',
'scope': 'EMEA-V1-Basic EMEA-V1-Anonymous EMEA-V1-Get-Current-User-Account',
'refresh_token': atomicState.evohomeAuth.refreshToken
]
]
try {
httpPost(requestParams) { resp ->
if(resp.status == 200 && resp.data) {
// Update evohomeAuth:
// We can't just '.put' or '<<' with atomicState, we have to make a temp copy, edit, and then re-assign.
def tmpAuth = atomicState.evohomeAuth ?: [:]
tmpAuth.put('lastUpdated' , now())
tmpAuth.put('authToken' , resp?.data?.access_token)
tmpAuth.put('tokenLifetime' , resp?.data?.expires_in.toInteger() ?: 0)
tmpAuth.put('expiresAt' , now() + (tmpAuth.tokenLifetime * 1000))
tmpAuth.put('refreshToken' , resp?.data?.refresh_token)
atomicState.evohomeAuth = tmpAuth
atomicState.evohomeAuthFailed = false
if (atomicState.debug) log.debug "${app.label}: refreshAuthToken(): New evohomeAuth: ${atomicState.evohomeAuth}"
def exp = new Date(tmpAuth.expiresAt)
log.info "${app.label}: refreshAuthToken(): New Auth Token Expires At: ${exp}"
// Update evohomeHeaders:
def tmpHeaders = atomicState.evohomeHeaders ?: [:]
tmpHeaders.put('Authorization',"bearer ${atomicState.evohomeAuth.authToken}")
tmpHeaders.put('applicationId', 'b013aa26-9724-4dbd-8897-048b9aada249')
tmpHeaders.put('Accept', 'application/json, application/xml, text/json, text/x-json, text/javascript, text/xml')
atomicState.evohomeHeaders = tmpHeaders
if (atomicState.debug) log.debug "${app.label}: refreshAuthToken(): New evohomeHeaders: ${atomicState.evohomeHeaders}"
// Now get User Account info:
getEvohomeUserAccount()
}
else {
log.error "${app.label}: refreshAuthToken(): No Data. Response Status: ${resp.status}"
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: refreshAuthToken(): Error: e.statusCode ${e.statusCode}"
// If Unauthorized (401) then re-authenticate:
if (e.statusCode == 401) {
atomicState.evohomeAuthFailed = true
authenticate()
}
}
}
/**
* getEvohomeUserAccount()
*
* Gets user account info and stores in atomicState.evohomeUserAccount.
*
**/
private getEvohomeUserAccount() {
log.info "${app.label}: getEvohomeUserAccount(): Getting user account information."
def requestParams = [
method: 'GET',
uri: atomicState.evohomeEndpoint,
path: '/WebAPI/emea/api/v1/userAccount',
headers: atomicState.evohomeHeaders
]
try {
httpGet(requestParams) { resp ->
if (resp.status == 200 && resp.data) {
atomicState.evohomeUserAccount = resp.data
if (atomicState.debug) log.debug "${app.label}: getEvohomeUserAccount(): Data: ${atomicState.evohomeUserAccount}"
}
else {
log.error "${app.label}: getEvohomeUserAccount(): No Data. Response Status: ${resp.status}"
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: getEvohomeUserAccount(): Error: e.statusCode ${e.statusCode}"
if (e.statusCode == 401) {
atomicState.evohomeAuthFailed = true
}
}
}
/**
* getEvohomeConfig()
*
* Gets Evohome configuration for all locations and stores in atomicState.evohomeConfig.
*
**/
private getEvohomeConfig() {
log.info "${app.label}: getEvohomeConfig(): Getting configuration for all locations."
def requestParams = [
method: 'GET',
uri: atomicState.evohomeEndpoint,
path: '/WebAPI/emea/api/v1/location/installationInfo',
query: [
'userId': atomicState.evohomeUserAccount.userId,
'includeTemperatureControlSystems': 'True'
],
headers: atomicState.evohomeHeaders
]
try {
httpGet(requestParams) { resp ->
if (resp.status == 200 && resp.data) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeConfig(): Data: ${resp.data}"
atomicState.evohomeConfig = resp.data
atomicState.evohomeConfigUpdatedAt = now()
return null
}
else {
log.error "${app.label}: getEvohomeConfig(): No Data. Response Status: ${resp.status}"
return 'error'
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: getEvohomeConfig(): Error: e.statusCode ${e.statusCode}"
if (e.statusCode == 401) {
atomicState.evohomeAuthFailed = true
}
return e
}
}
/**
* getEvohomeStatus(onlyZoneId=-1)
*
* Gets Evohome Status for specified zone and stores in atomicState.evohomeStatus.
* If onlyZoneId is not specified, all zones in all locations are updated.
*
* Calls getEvohomeLocationStatus() and getEvohomeZoneStatus().
*
**/
private getEvohomeStatus(onlyZoneId=-1) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeStatus(${onlyZoneId})"
def newEvohomeStatus = []
if (onlyZoneId == -1) { // Update all zones (which can be obtained en-masse for each location):
log.info "${app.label}: getEvohomeStatus(): Getting status for all zones."
atomicState.evohomeConfig.each { loc ->
def locStatus = getEvohomeLocationStatus(loc.locationInfo.locationId)
if (locStatus) {
newEvohomeStatus << locStatus
}
}
if (newEvohomeStatus) {
// Write out newEvohomeStatus back to atomicState:
atomicState.evohomeStatus = newEvohomeStatus
atomicState.evohomeStatusUpdatedAt = now()
}
}
else { // Only update the specified zone:
log.info "${app.label}: getEvohomeStatus(): Getting status for zone ID: ${onlyZoneId}"
def newZoneStatus = getEvohomeZoneStatus(onlyZoneId)
if (newZoneStatus) {
// Get existing evohomeStatus and update only the specified zone, preserving data for other zones:
// Have to do this as atomicState.evohomeStatus can only be written in its entirety (as using atomicstate).
// If mutiple zones are requesting updates at the same time this could cause loss of new data, but
// the worst case is having out-of-date data for a few minutes...
newEvohomeStatus = atomicState.evohomeStatus
newEvohomeStatus.each { loc ->
loc.gateways.each { gateway ->
gateway.temperatureControlSystems.each { tcs ->
tcs.zones.each { zone ->
if (onlyZoneId == zone.zoneId) {
zone.activeFaults = newZoneStatus.activeFaults
zone.heatSetpointStatus = newZoneStatus.heatSetpointStatus
zone.temperatureStatus = newZoneStatus.temperatureStatus
}
}
}
}
}
// Write out newEvohomeStatus back to atomicState:
atomicState.evohomeStatus = newEvohomeStatus
// Note: atomicState.evohomeStatusUpdatedAt is NOT updated.
}
}
}
/**
* getEvohomeLocationStatus(locationId)
*
* Gets the status for a specific location and returns data as a map.
*
* Called by getEvohomeStatus().
**/
private getEvohomeLocationStatus(locationId) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeLocationStatus: Location ID: ${locationId}"
def requestParams = [
'method': 'GET',
'uri': atomicState.evohomeEndpoint,
'path': "/WebAPI/emea/api/v1/location/${locationId}/status",
'query': [ 'includeTemperatureControlSystems': 'True'],
'headers': atomicState.evohomeHeaders
]
try {
httpGet(requestParams) { resp ->
if(resp.status == 200 && resp.data) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeLocationStatus: Data: ${resp.data}"
return resp.data
}
else {
log.error "${app.label}: getEvohomeLocationStatus: No Data. Response Status: ${resp.status}"
return false
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: getEvohomeLocationStatus: Error: e.statusCode ${e.statusCode}"
if (e.statusCode == 401) {
atomicState.evohomeAuthFailed = true
}
return false
}
}
/**
* getEvohomeZoneStatus(zoneId)
*
* Gets the status for a specific zone and returns data as a map.
*
**/
private getEvohomeZoneStatus(zoneId) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeZoneStatus(${zoneId})"
def requestParams = [
'method': 'GET',
'uri': atomicState.evohomeEndpoint,
'path': "/WebAPI/emea/api/v1/temperatureZone/${zoneId}/status",
'headers': atomicState.evohomeHeaders
]
try {
httpGet(requestParams) { resp ->
if(resp.status == 200 && resp.data) {
if (atomicState.debug) log.debug "${app.label}: getEvohomeZoneStatus: Data: ${resp.data}"
return resp.data
}
else {
log.error "${app.label}: getEvohomeZoneStatus: No Data. Response Status: ${resp.status}"
return false
}
}
} catch (groovyx.net.http.HttpResponseException e) {
log.error "${app.label}: getEvohomeZoneStatus: Error: e.statusCode ${e.statusCode}"
if (e.statusCode == 401) {
atomicState.evohomeAuthFailed = true
}
return false
}
}
/**
* getEvohomeSchedules()
*
* Gets the schedules for all hot water and temperature (heating) zones
* Gets Evohome Schedule for each zone and stores in atomicState.evohomeSchedules.
* and stores in atomicState.evohomeSchedules.
*
* Calls getEvohomeTempZoneSchedule() and getEvohomeDHWSchedule().
*
**/
private getEvohomeSchedules() {
log.info "${app.label}: getEvohomeSchedules(): Getting schedules for all zones."
def evohomeSchedules = []