forked from iakoubtchik/Quirky-Connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quirky-Connect-Service-Manager.groovy
1533 lines (1288 loc) · 48.5 KB
/
Quirky-Connect-Service-Manager.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
/**
* Quirky (Connect)
*
* Author: [email protected]
* Date: 2014-02-15
*
* Update: 2014-02-22
* Added eggtray
* Added device specific methods called from poll (versus in poll)
*
* Update2:2014-02-22
* Added nimbus
*
* Update3:2014-02-26
* Improved eggtray integration
* Added notifications to hello home
* Introduced Quirky Eggtray specific icons (Thanks to Dane)
* Added an Egg Report that outputs to hello home.
* Switched to Dan Lieberman's client and secret
* Still not browser flow (next update?)
*
* Update4:2014-03-08
* Added Browser Flow OAuth
*
*
* Update5:2014-03-14
* Added dynamic icon/tile updating to the nimbus. Changes the device icon from app.
*
* Update6:2014-03-31
* Stubbed out creation and choice of nimbus, eggtray and porkfolio per request.
*
* Update7:2014-04-01
* Renamed to 'Quirky (Connect)' and updated device names
*
*
* Update8:2014-04-08 (dlieberman)
* Stubbed out Spotter
*
* Update9:2014-04-08 (twackford)
* resubscribe to events on each poll
*
* Update10:2014-04-24 (twackford)
* fixed null battery and temperature errors in spotter
*
* Update11:2014-04-26 (twackford)
* fixed multiple instances of same device getting installed
*
* Update12:2014-05-20 (twackford)
* Added Aros
*
* Update13:2014-06-05 (twackford)
* Multiple Aros bug fixes after initial QA
*
* Update14:2014-09-22 (twackford)
* Added Refuel
*
* Update14:2014-10-04 (twackford)
* Added enum of sub-child devices
* added renew subscription every 12 hours
* Added ability to delete from child device and reflect in parent
* Added delete of child if unselected in device list
* un-stubbed spotter, nimbus, eggtray and porkfolio
* Fixed page display of quirky and ST icons on connection
* Fixed deleting the last device from parent
* Fixed bad login handling
*
* Update15:2014-11-29 (twackford)
* Added check for token expiration (wink just set to 6 weeks)
*/
import java.text.DecimalFormat
import groovy.json.JsonSlurper
// Wink API stuff
private apiUrl() { "https://winkapi.quirky.com/" }
private getVendorName() { "Quirky Wink" }
private getVendorAuthPath() { "https://winkapi.quirky.com/oauth2/authorize?" }
private getVendorTokenPath(){ "https://winkapi.quirky.com/oauth2/token?" }
private getVendorIcon() { "https://s3.amazonaws.com/smartapp-icons/Partner/[email protected]" }
private getClientId() { "c22d82a7fc3d6faf06dcff1bcf0feb52" } // Dan Lieberman's
private getClientSecret() { "bd44c524a1df9dce134235d174350603" }
private getServerUrl() { "https://graph.api.smartthings.com" }
// Automatically generated. Make future change here.
definition(
name: "Quirky (Connect)",
namespace: "wackford",
author: "Todd Wackford",
description: "Connect your Quirky to SmartThings.",
category: "My Apps",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Partner/quirky.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Partner/[email protected]",
oauth: true
)
mappings {
path("/receivedToken") { action:[ POST: "receivedToken", GET: "receivedToken"] }
path("/receiveToken") { action:[ POST: "receiveToken", GET: "receiveToken"] }
path("/propaneTankCallback") { action:[ POST: "propaneTankEventHandler", GET: "subscriberIdentifyVerification"]}
path("/airConditionerCallback") { action:[ POST: "airConditionerEventHandler", GET: "subscriberIdentifyVerification"]}
path("/powerstripCallback") { action:[ POST: "powerstripEventHandler", GET: "subscriberIdentifyVerification"]}
path("/sensor_podCallback") { action:[ POST: "sensor_podEventHandler", GET: "subscriberIdentifyVerification"]}
path("/piggy_bankCallback") { action:[ POST: "piggy_bankEventHandler", GET: "subscriberIdentifyVerification"]}
path("/eggtrayCallback") { action:[ POST: "eggtrayEventHandler", GET: "subscriberIdentifyVerification"]}
path("/cloud_clockCallback") { action:[ POST: "cloud_clockEventHandler", GET: "subscriberIdentifyVerification"]}
}
preferences {
page(name: "Credentials", title: "Fetch OAuth2 Credentials", content: "authPage", install: false)
page(name: "listDevices", title: "Quirky Devices", content: "listDevices", install: false)
}
def installed() {
log.debug "Installed with settings: ${settings}"
schedule("5 0,12 * * * ?", updateWinkSubscriptions) //renew subscriptions every 12 hours
listDevices()
}
def updated() {
log.debug "Updated with settings: ${settings}"
unschedule()
schedule("5 0,12 * * * ?", updateWinkSubscriptions) //renew subscriptions every 12 hours
initialize()
listDevices()
}
def listDevices()
{
log.debug "In listDevices"
def devices = getDeviceList()
log.debug "Device List = ${devices}"
log.debug "Settings List = ${settings}"
dynamicPage(name: "listDevices", title: "Choose devices", install: true) {
section("Devices") {
input "devices", "enum", title: "Select Device(s)", required: false, multiple: true, options: devices
}
}
}
def getDeviceList()
{
log.debug "In getDeviceList"
def deviceList = [:]
state.deviceDataArr = []
apiGet("/users/me/wink_devices") { response ->
response.data.data.each() {
if ( it.propane_tank_id ) {
deviceList["${it.propane_tank_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.propane_tank_id,
'type' : "propane_tank",
'serial' : it.serial,
'data' : it,
'subsSuff': "/propaneTankCallback",
'subsPath': "/propane_tanks/${it.propane_tank_id}/subscriptions"
])
}
if ( it.air_conditioner_id ) {
deviceList["${it.air_conditioner_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.air_conditioner_id,
'type' : "air_conditioner",
'serial' : it.serial,
'data' : it,
'subsSuff': "/airConditionerCallback",
'subsPath': "/air_conditioners/${it.air_conditioner_id}/subscriptions"
])
}
if ( it.cloud_clock_id ) {
//log.debug "${it.dials[0]}"
def dial1Data = it.dials[0]
deviceList[dial1Data.dial_id] = it.name + " Dial 1"
state.deviceDataArr.push(['name' : it.name + " Dial 1",
'id' : dial1Data.dial_id,
'type' : "nimbusDial",
'serial' : it.serial,
'data' : it,
'subsSuff': "/cloud_clockCallback",
'subsPath': "/cloud_clocks/${it.cloud_clock_id}/subscriptions"
])
def dial2Data = it.dials[1]
deviceList[dial2Data.dial_id] = it.name + " Dial 2"
state.deviceDataArr.push(['name' : it.name + " Dial 2",
'id' : dial2Data.dial_id,
'type' : "nimbusDial",
'serial' : it.serial,
'data' : it,
'subsSuff': "/cloud_clockCallback",
'subsPath': "/cloud_clocks/${it.cloud_clock_id}/subscriptions"
])
def dial3Data = it.dials[2]
deviceList[dial3Data.dial_id] = it.name + " Dial 3"
state.deviceDataArr.push(['name' : it.name + " Dial 3",
'id' : dial3Data.dial_id,
'type' : "nimbusDial",
'serial' : it.serial,
'data' : it,
'subsSuff': "/cloud_clockCallback",
'subsPath': "/cloud_clocks/${it.cloud_clock_id}/subscriptions"
])
def dial4Data = it.dials[3]
deviceList[dial4Data.dial_id] = it.name + " Dial 4"
state.deviceDataArr.push(['name' : it.name + " Dial 4",
'id' : dial4Data.dial_id,
'type' : "nimbusDial",
'serial' : it.serial,
'data' : it,
'subsSuff': "/cloud_clockCallback",
'subsPath': "/cloud_clocks/${it.cloud_clock_id}/subscriptions"
])
//dials are handled individually now, commented out
/*deviceList["${it.cloud_clock_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.cloud_clock_id,
'type' : "cloud_clock",
'serial' : it.serial,
'data' : it,
'subsSuff': "/cloud_clockCallback",
'subsPath': "/cloud_clocks/${it.cloud_clock_id}/subscriptions"
])*/
}
if ( it.powerstrip_id ) {
def outlet1Data = it.outlets[0]
deviceList[outlet1Data.outlet_id] = it.name + " " + outlet1Data.name
state.deviceDataArr.push(['name' : it.name + " " + outlet1Data.name,
'id' : outlet1Data.outlet_id,
'type' : "powerstripOutlet",
'serial' : it.serial,
'data' : it,
'subsSuff': "/powerstripCallback",
'subsPath': "/powerstrips/${it.powerstrip_id}/subscriptions"
])
def outlet2Data = it.outlets[1]
deviceList[outlet2Data.outlet_id] = it.name + " " + outlet2Data.name
state.deviceDataArr.push(['name' : it.name + " " + outlet2Data.name,
'id' : outlet2Data.outlet_id,
'type' : "powerstripOutlet",
'serial' : it.serial,
'data' : it,
'subsSuff': "/powerstripCallback",
'subsPath': "/powerstrips/${it.powerstrip_id}/subscriptions"
])
//this is commented out cuz we install and handle outlets individualy
/*
deviceList["${it.powerstrip_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.powerstrip_id,
'type' : "powerstrip",
'serial' : it.serial,
'data' : it,
'subsSuff': "/powerstripCallback",
'subsPath': "/powerstrips/${it.powerstrip_id}/subscriptions"
])*/
}
if ( it.sensor_pod_id ) {
deviceList["${it.sensor_pod_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.sensor_pod_id,
'type' : "sensor_pod",
'serial' : it.serial,
'data' : it,
'subsSuff': "/sensor_podCallback",
'subsPath': "/sensor_pods/${it.sensor_pod_id}/subscriptions"
])
}
if ( it.piggy_bank_id ) {
deviceList["${it.piggy_bank_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.piggy_bank_id,
'type' : "piggy_bank",
'serial' : it.serial,
'data' : it,
'subsSuff': "/piggy_bankCallback",
'subsPath': "/piggy_banks/${it.piggy_bank_id}/subscriptions"
])
}
if ( it.eggtray_id ) {
deviceList["${it.eggtray_id}"] = it.name
state.deviceDataArr.push(['name' : it.name,
'id' : it.eggtray_id,
'type' : "eggtray",
'serial' : it.serial,
'data' : it,
'subsSuff': "/eggtrayCallback",
'subsPath': "/eggtrays/${it.eggtray_id}/subscriptions"
])
}
}
}
return deviceList
}
def initialize()
{
log.debug "Initialized with settings: ${settings}"
settings.devices.each {
def deviceId = it
state.deviceDataArr.each {
if ( it.id == deviceId ) {
switch(it.type) {
case "propane_tank":
log.debug "we have a Refuel"
createChildDevice("Quirky Refuel", deviceId, it.name, it.label)
createWinkSubscription( it.subsPath, it.subsSuff )
pollPropaneTank(getChildDevice(deviceId))
break
case "air_conditioner":
log.debug "we have an Aros"
createChildDevice("Quirky Aros", deviceId, it.name, it.label)
createWinkSubscription( it.subsPath, it.subsSuff )
pollAros(getChildDevice(deviceId))
break
case "powerstrip":
log.debug "we have a Pivot Power Genius"
createPowerstripChildren(it.data) //has sub-devices, so we call out to create kids
createWinkSubscription( it.subsPath, it.subsSuff )
break
case "powerstripOutlet":
log.debug "we have a Pivot Power Genius Outlet"
createChildDevice( "Quirky Pivot Power Genius", deviceId, it.name, it.name )
createWinkSubscription( it.subsPath, it.subsSuff )
pollOutlet(getChildDevice(deviceId))
break
case "nimbusDial":
log.debug "we have a Nimbus Dial"
//createNimbusChildren(it.data) //has sub-devices, so we call out to create kids
createChildDevice( "Quirky Nimbus", deviceId, it.name, it.name )
createWinkSubscription( it.subsPath, it.subsSuff )
pollNimbus(getChildDevice(deviceId))
break
case "cloud_clock":
log.debug "we have a Nimbus"
createNimbusChildren(it.data) //has sub-devices, so we call out to create kids
createWinkSubscription( it.subsPath, it.subsSuff )
pollNimbus(getChildDevice(deviceId))
break
case "sensor_pod":
log.debug "we have a Spotter"
createChildDevice("Quirky Spotter", deviceId, it.name, it.label)
createWinkSubscription( it.subsPath, it.subsSuff )
getSensorPodUpdate(getChildDevice(deviceId))
break
case "piggy_bank":
log.debug "we have a Piggy Bank"
createChildDevice("Quirky Porkfolio", deviceId, it.name, it.label)
createWinkSubscription( it.subsPath, it.subsSuff )
getPiggyBankUpdate(getChildDevice(deviceId))
break
case "eggtray":
log.debug "we have an Egg Minder"
createChildDevice("Quirky Eggtray", deviceId, it.name, it.label)
createWinkSubscription( it.subsPath, it.subsSuff )
getEggtrayUpdate(getChildDevice(deviceId))
break
}
}
}
}
// Delete any that are no longer in settings
def delete = getChildDevices().findAll { !settings.devices?.contains(it.deviceNetworkId) }
log.debug "deleting ${delete}"
delete.each() {
uninstallChildDevice(it)
deleteChildDevice(it.deviceNetworkId)
}
}
def createChildDevice(deviceFile, dni, name, label)
{
log.debug "In createChildDevice"
try {
def existingDevice = getChildDevice(dni)
log.debug "existingDevice = ${existingDevice}"
if(!existingDevice) {
log.debug "Creating child"
def childDevice = addChildDevice(app.namespace, deviceFile, dni, null, [name: name, label: label, completedSetup: true])
} else {
log.debug "Device $dni already exists"
}
}
catch (e) {
log.error "Error creating device: ${e}"
}
}
def createWinkSubscription(path, suffix)
{
log.debug "In createWinkSubscription"
def callbackUrl = buildCallbackUrl(suffix)
httpPostJson([
uri : apiUrl(),
path: path,
body: ['callback': callbackUrl],
headers : ['Authorization' : 'Bearer ' + state.vendorAccessToken]
],)
{ response ->
log.debug "Created subscription ID ${response.data.data.subscription_id}"
}
}
def subscriberIdentifyVerification()
{
log.debug "In subscriberIdentifyVerification"
def challengeToken = params.hub.challenge
render contentType: 'text/plain', data: challengeToken
}
def uninstalled()
{
log.debug "In uninstalled"
removeWinkSubscriptions()
removeChildDevices(getChildDevices())
unschedule()
}
def removeWinkSubscriptions()
{
log.debug "In removeWinkSubscriptions"
state.deviceDataArr.each() {
if (it.subsPath) {
def path = it.subsPath
apiGet(it.subsPath) { response ->
response.data.data.each {
if ( it.subscription_id ) {
log.debug "Deleting Subscription: ${path}" + "/" + "${it.subscription_id}"
deleteWinkSubscription(path + "/", it.subscription_id)
}
}
}
}
}
}
private removeChildDevices(delete)
{
log.debug "In removeChildDevices"
log.debug "deleting ${delete.size()} devices"
delete.each {
deleteChildDevice(it.deviceNetworkId)
}
}
def uninstallChildDevice(childDevice)
{
log.debug "in uninstallChildDevice"
// Remove the childs subscription
def deviceData = state.deviceDataArr.findAll { it.id == childDevice.device.deviceNetworkId }
deviceData.each() {
def path = it.subsPath
apiGet(it.subsPath) { response ->
response.data.data.each {
if ( it.subscription_id ) {
deleteWinkSubscription(path + "/", it.subscription_id)
}
}
}
}
//now remove the child from settings. Unselects from list of devices, not delete
log.debug "Settings size = ${settings['devices']}"
if (!settings['devices']) //empty list, bail
return
def newDeviceList = settings['devices'] - childDevice.device.deviceNetworkId
app.updateSetting("devices", newDeviceList)
}
def updateWinkSubscriptions()
{ //since we don't know when wink subscription dies, call this from a scheduled job
log.debug "In updateWinkSubscriptions"
state.deviceDataArr.each() {
if (it.subsPath) {
def path = it.subsPath
def suffix = it.subsSuff
apiGet(it.subsPath) { response ->
response.data.data.each {
if ( it.subscription_id ) {
deleteWinkSubscription(path + "/", it.subscription_id)
createWinkSubscription(path, suffix)
}
}
}
}
}
}
def deleteWinkSubscription(path, subscriptionId)
{
httpDelete([
uri : apiUrl(),
path: path + subscriptionId,
headers : [ 'Authorization' : 'Bearer ' + state.vendorAccessToken ]
],)
{ response ->
log.debug "Subscription ${subscriptionId} deleted"
}
}
def buildCallbackUrl(suffix)
{
log.debug "In buildRedirectUrl"
def serverUrl = getServerUrl()
return serverUrl + "/api/token/${state.accessToken}/smartapps/installations/${app.id}" + suffix
}
def checkToken() {
log.debug "In checkToken"
def tokenStatus = "bad"
//check existing token by calling user device list
try {
httpGet([ uri : apiUrl(),
path : "/users/me/wink_devices",
headers : [ 'Authorization' : 'Bearer ' + state.vendorAccessToken ]
])
{ response ->
debugOut "Response is: ${response.status}"
if ( response.status == 200 ) {
debugOut "The current token is good"
tokenStatus = "good"
}
}
}
catch(Exception e) {
debugOut "Current access token did not work. Trying refresh Token now."
}
if ( tokenStatus == "bad" ) {
//Let's try the refresh token now
debugOut "Trying to refresh tokens"
def tokenParams = [ client_id : getClientId(),
client_secret : getClientSecret(),
grant_type : "refresh_token",
refresh_token : state.vendorRefreshToken ]
def tokenUrl = getVendorTokenPath() + toQueryString(tokenParams)
def params = [
uri: tokenUrl,
]
try {
httpPost(params) { response ->
debugOut "Successfully refreshed tokens with code: ${response.status}"
state.vendorRefreshToken = response.data.refresh_token
state.vendorAccessToken = response.data.access_token
tokenStatus = "good"
}
}
catch(Exception e) {
debugOut "Unable to refresh token. Error ${e}"
}
}
if ( tokenStatus == "bad" ) {
return "Error: Unable to refresh Token"
} else {
return null //no errors
}
}
def apiGet(String path, Closure callback)
{
log.debug "In apiGet with path: $path"
//check to see if our token has expired
def status = checkToken()
debugOut "Status of checktoken: ${status}"
if ( status ) {
debugOut "Error! Status: ${status}"
return
} else {
debugOut "Token is good. Call the command"
}
httpGet([
uri : apiUrl(),
path : path,
headers : [ 'Authorization' : 'Bearer ' + state.vendorAccessToken ]
])
{
response ->
callback.call(response)
}
}
def apiPut(String path, cmd, Closure callback)
{
log.debug "In apiPut with path: $path and cmd: $cmd"
//check to see if our token has expired
def status = checkToken()
debugOut "Status of checktoken: ${status}"
if ( status ) {
debugOut "Error! Status: ${status}"
return
} else {
debugOut "Token is good. Call the command"
}
httpPutJson([
uri : apiUrl(),
path: path,
body: cmd,
headers : [ 'Authorization' : 'Bearer ' + state.vendorAccessToken ]
])
{
response ->
callback.call(response)
}
}
def poll(childDevice)
{
log.debug "In poll" //we should not ever get here, devices have unique polls
}
def cToF(temp) {
return temp * 1.8 + 32
}
def fToC(temp) {
return (temp - 32) / 1.8
}
def debugOut(msg) {
log.debug msg
//sendNotificationEvent(msg) //Uncomment this for troubleshooting only
}
def dollarize(int money)
{
def value = money.toString()
if ( value.length() == 1 )
value = "00" + value
if ( value.length() == 2 )
value = "0" + value
def newval = value.substring(0, value.length() - 2) + "." + value.substring(value.length()-2, value.length())
value = newval
def pattern = "\$0.00"
def moneyform = new DecimalFormat(pattern)
String output = moneyform.format(value.toBigDecimal())
return output
}
def debugEvent(message, displayEvent) {
def results = [
name: "appdebug",
descriptionText: message,
displayed: displayEvent
]
log.debug "Generating AppDebug Event: ${results}"
sendEvent (results)
}
String toQueryString(Map m) {
return m.collect { k, v -> "${k}=${URLEncoder.encode(v.toString())}" }.sort().join("&")
}
/////////////////////////////////////////////////////////////////////////
// START REFUEL SPECIFIC CODE HERE
/////////////////////////////////////////////////////////////////////////
def pollPropaneTank(childDevice)
{
log.debug "Polling Refuel ${childDevice.device.deviceNetworkId}"
apiGet("/propane_tanks/" + childDevice.device.deviceNetworkId) { response ->
def status = response.data.data.last_reading
log.debug "Got tank data!"
childDevice?.sendEvent(name:"battery", value:status.battery * 100, unit:"")
childDevice?.sendEvent(name:"tankLevel", value:status.remaining * 100, unit:"")
//childDevice?.sendEvent(name:"tankChanged", value:new Date((status.tank_changed_at as long)*1000), unit:"")
}
}
def propaneTankEventHandler()
{
log.debug "In propaneTankEventHandler..."
def json = request.JSON
def dni = getChildDevice(json.propane_tank_id)
pollPropaneTank(dni) //sometimes events are stale, poll for all latest states
def html = """{"code":200,"message":"OK"}"""
render contentType: 'application/json', data: html
}
/////////////////////////////////////////////////////////////////////////
// START SENSOR POD SPECIFIC CODE HERE
/////////////////////////////////////////////////////////////////////////
def getSensorPodUpdate(childDevice)
{
apiGet("/sensor_pods/" + childDevice.device.deviceNetworkId) { response ->
def status = response.data.data.last_reading
status.loudness ? childDevice?.sendEvent(name:"sound",value:"active",unit:"") :
childDevice?.sendEvent(name:"sound",value:"inactive",unit:"")
status.brightness ? childDevice?.sendEvent(name:"light",value:"active",unit:"") :
childDevice?.sendEvent(name:"light",value:"inactive",unit:"")
status.vibration ? childDevice?.sendEvent(name:"acceleration",value:"active",unit:"") :
childDevice?.sendEvent(name:"acceleration",value:"inactive",unit:"")
status.external_power ? childDevice?.sendEvent(name:"powerSource",value:"powered",unit:"") :
childDevice?.sendEvent(name:"powerSource",value:"battery",unit:"")
childDevice?.sendEvent(name:"humidity",value:status.humidity,unit:"")
if (status.battery != null)
childDevice?.sendEvent(name:"battery",value:(status.battery * 100).toInteger(),unit:"")
else
childDevice?.sendEvent(name:"battery",value:0,unit:"")
// Need to get users pref of temp scale here
if ( status.temperature != null )
childDevice?.sendEvent(name:"temperature",value:cToF(status.temperature),unit:"F")
}
}
def sensor_podEventHandler()
{
log.debug "In sensor_podEventHandler..."
def json = request.JSON
def dni = getChildDevice(json.sensor_pod_id)
log.debug "event received from ${dni}"
getSensorPodUpdate(dni) //sometimes events are stale, poll for all latest states
def html = """{"code":200,"message":"OK"}"""
render contentType: 'application/json', data: html
}
/////////////////////////////////////////////////////////////////////////
// START NIMBUS SPECIFIC CODE HERE
/////////////////////////////////////////////////////////////////////////
def createNimbusChildren(deviceData)
{
log.debug "In createNimbusChildren"
def nimbusName = deviceData.name
def deviceFile = "Quirky Nimbus"
def index = 1
deviceData.dials.each {
log.debug "creating dial device for ${it.dial_id}"
def dialName = "Dial ${index}"
def dialLabel = "${nimbusName} ${dialName}"
createChildDevice( deviceFile, it.dial_id, dialName, dialLabel )
index++
}
}
def cloud_clockEventHandler()
{
log.debug "In Nimbus Event Handler..."
def json = request.JSON
def dials = json.dials
def html = """{"code":200,"message":"OK"}"""
render contentType: 'application/json', data: html
if ( dials ) {
dials.each() {
def childDevice = getChildDevice(it.dial_id)
if (!childDevice) // not a smartthings device, user did not pick it
return
childDevice?.sendEvent( name : "dial", value : it.label , unit : "" )
childDevice?.sendEvent( name : "info", value : it.name , unit : "" )
}
}
}
def pollNimbus(dni)
{
log.debug "In pollNimbus using dni # ${dni}"
def dials = null
apiGet("/users/me/wink_devices") { response ->
response.data.data.each() {
if (it.cloud_clock_id ) {
log.debug "Found Nimbus #" + it.cloud_clock_id
dials = it.dials
//log.debug dials
}
}
}
if ( dials ) {
dials.each() {
def childDevice = getChildDevice(it.dial_id)
if (!childDevice) //this is not a SmartThings dial (user did not pick)
return
//log.debug "Dial event ${childDevice}"
childDevice?.sendEvent( name : "dial", value : it.label, unit : "" )
childDevice?.sendEvent( name : "info", value : it.name , unit : "" )
//Change the tile/icon to what info is being displayed
switch(it.name) {
case "Weather":
childDevice?.setIcon("dial", "dial" , "st.quirky.nimbus.quirky-nimbus-weather")
break
case "Traffic":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-traffic")
break
case "Time":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-time")
break
case "Twitter":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-twitter")
break
case "Calendar":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-calendar")
break
case "Email":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-mail")
break
case "Facebook":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-facebook")
break
case "Instagram":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-instagram")
break
case "Fitbit":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-fitbit")
break
case "Egg Minder":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-egg")
break
case "Porkfolio":
childDevice?.setIcon("dial", "dial", "st.quirky.nimbus.quirky-nimbus-porkfolio")
break
}
childDevice.save()
}
}
return
}
/////////////////////////////////////////////////////////////////////////
// START EGG TRAY SPECIFIC CODE HERE
/////////////////////////////////////////////////////////////////////////
def getEggtrayUpdate(childDevice)
{
log.debug "In getEggtrayUpdate"
apiGet("/eggtrays/" + childDevice.device.deviceNetworkId) { response ->
def data = response.data.data
def freshnessPeriod = data.freshness_period
def trayName = data.name
log.debug data
int totalEggs = 0
int oldEggs = 0
def now = new Date()
def nowUnixTime = now.getTime()/1000
data.eggs.each() { it ->
if (it != 0)
{
totalEggs++
def eggArriveDate = it
def eggStaleDate = eggArriveDate + freshnessPeriod
if ( nowUnixTime > eggStaleDate ){
oldEggs++
}
}
}
int freshEggs = totalEggs - oldEggs
if ( oldEggs > 0 ) {
childDevice?.sendEvent(name:"inventory",value:"haveBadEgg")
def msg = "${trayName} says: "
msg+= "Did you know that all it takes is one bad egg? "
msg+= "And it looks like I found one.\n\n"
msg+= "You should probably run an Egg Report before you use any eggs."
sendNotificationEvent(msg)
}
if ( totalEggs == 0 ) {
childDevice?.sendEvent(name:"inventory",value:"noEggs")
sendNotificationEvent("${trayName} says:\n'Oh no, I'm out of eggs!'")
sendNotificationEvent(msg)
}
if ( (freshEggs == totalEggs) && (totalEggs != 0) ) {
childDevice?.sendEvent(name:"inventory",value:"goodEggs")
}
childDevice?.sendEvent( name : "totalEggs", value : totalEggs , unit : "" )
childDevice?.sendEvent( name : "freshEggs", value : freshEggs , unit : "" )
childDevice?.sendEvent( name : "oldEggs", value : oldEggs , unit : "" )
}
}
def runEggReport(childDevice)
{
apiGet("/eggtrays/" + childDevice.device.deviceNetworkId) { response ->
def data = response.data.data
def trayName = data.name
def freshnessPeriod = data.freshness_period
def now = new Date()
def nowUnixTime = now.getTime()/1000
def eggArray = []
def i = 0
data.eggs.each() { it ->
if (it != 0 ) {
def eggArriveDate = it
def eggStaleDate = eggArriveDate + freshnessPeriod
if ( nowUnixTime > eggStaleDate ){
eggArray.push("Bad ")
} else {
eggArray.push("Good ")
}
} else {
eggArray.push("Empty")
}
i++