-
Notifications
You must be signed in to change notification settings - Fork 14
/
husqapp.groovy
2521 lines (2252 loc) · 93.2 KB
/
husqapp.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
/*
* 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.
*
* Husqvarna AutoMower
*
* Modified June 16, 2022
*
* Instructions:
* Go to developer.husqvarnagroup.cloud
* - Sign in with your AutoConnect credentials
* - +Create application
* - Name it, URI for redirect https://cloud.hubitat.com/oauth/stateredirect
* - Connect this to authentication api and automower api
* - after saving, note application key and application secret to enter into settings here
*
* Note: currently Husqvarna allows a total of 10K requests a month. This app must poll so this must be taken into account
* This works out to shortest poll is every 5 minutes, with little remaining headroom
*/
//file:noinspection GroovyPointlessBoolean
//file:noinspection GroovyDoubleNegation
//file:noinspection GroovyUnusedAssignment
//file:noinspection GroovySillyAssignment
//file:noinspection unused
//file:noinspection GroovyVariableNotAssigned
// lgk june 2022 add human readable next run time
// also add lastupdate and mower statistics
import groovy.json.*
import groovy.transform.Field
import java.text.SimpleDateFormat
static String getVersionNum() { return "00.00.02" }
static String getVersionLabel() { return "Husqvarna Automower Manager, version "+getVersionNum() }
static String getMyNamespace() { return "imnotbob" }
static Integer getMinMinsBtwPolls() { return 3 }
static String getAutoMowerName() { return "Husqvarna AutoMower" }
@Field static final String sNULL = (String)null
@Field static final String sBLANK = ''
@Field static final String sSPACE = ' '
@Field static final String sCLRRED = 'red'
@Field static final String sCLRGRY = 'gray'
@Field static final String sCLRORG = 'orange'
@Field static final String sLINEBR = '<br>'
@Field static final String sLOST = 'lost'
@Field static final String sFULL = 'full'
@Field static final String sBOOL = 'bool'
@Field static final String sENUM = 'enum'
definition(
name: "Husqvarna AutoMower Manager",
namespace: myNamespace,
author: "imnot_bob",
description: "Connect your Husqvarna AutoMowers, along with a Suite of Helper Apps.",
category: "Integrations",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]",
iconX3Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]",
importUrl: "https://raw.githubusercontent.com/imnotbob/AutoMower/master/automower-connect.groovy",
singleInstance: true,
oauth: true
)
preferences {
page(name: "mainPage")
page(name: "removePage")
page(name: "authPage")
page(name: "mowersPage")
page(name: "preferencesPage")
page(name: "debugDashboardPage")
page(name: "refreshAuthTokenPage")
}
mappings {
path("/oauth/initialize"){action: [GET: "oauthInitUrl"]}
path("/callback"){action: [GET: "callback"]}
path("/oauth/callback"){action: [GET: "callback"]}
}
def mainPage(){
String version=getVersionLabel()
Boolean deviceHandlersInstalled
Boolean readyToInstall //=false
deviceHandlersInstalled=testForDeviceHandlers()
readyToInstall=deviceHandlersInstalled
dynamicPage(name: "mainPage", title: pageTitle(version.replace('er, v',"er\nV")), install: readyToInstall, uninstall: false, submitOnChange: true){
// If no device Handlers we cannot proceed
if(!(Boolean)state.initialized && !deviceHandlersInstalled){
section(){
paragraph "ERROR!\n\nYou MUST add the ${getAutoMowerName()} Device Handlers to the IDE BEFORE running setup."
}
}else{
readyToInstall=true
}
if((Boolean)state.initialized && !(String)state.authToken){
section(){
paragraph(getFormat("warning", "You are no longer connected to the Husqvarna API. Please re-Authorize below."))
}
}
if((String)state.authToken && !(Boolean)state.initialized){
section(){
paragraph "Please 'click \'Done\'' to save your credentials. Then re-open the AutoMower Manager to continue the setup."
}
}
if((String)state.authToken && (Boolean)state.initialized){
if(((List<String>)settings.mowers)?.size() > 0){
/* section(sectionTitle("Helpers")){
href ("helperAppsPage", title: inputTitle("Helper Applications"), description: "'Click' to manage Helper 'Applications'")
}*/
}
section(sectionTitle("AutoMower Devices")){
Integer howManyMowersSel=((List<String>)settings.mowers)?.size() ?: 0
Integer howManyMowers=state.numAvailMowers ?: 0
// Mowers
href ("mowersPage", title: inputTitle("Mowers"), description: "'Click' to select AutoMowers [${howManyMowersSel}/${howManyMowers}]")
}
}
section(sectionTitle("Preferences")){
href ("preferencesPage", title: inputTitle("AutoMower Preferences"), description: "'Click' to manage global Preferences")
}
String authDesc=((String)state.authToken) ? "[Connected]\n" :"[Not Connected]\n"
section(sectionTitle("Authentication")){
href ("authPage", title: inputTitle("AutoMower API Authorization"), description: "${authDesc}'Click' for AutoMower Authentication")
}
if( debugLevel(5) ){
section (sectionTitle("Debug Dashboard")){
href ("debugDashboardPage", description: "${HE?'Click':'Tap'} to enter the Debug Dashboard", title: inputTitle("Debug Dashboard"))
}
}
section(sectionTitle( "Removal")){
href ("removePage", description: "'Click' to remove ${cleanAppName((String)app.label?:(String)app.name)}", title: inputTitle("Remove AutoMower Manager"))
}
section (sectionTitle("Naming")){
String defaultName="AutoMower Manager"
String defaultLabel
if(!(String)state.appDisplayName){
defaultLabel=defaultName
app.updateLabel(defaultName)
state.appDisplayName=defaultName
}else{
defaultLabel=(String)state.appDisplayName
}
label(name: "name", title: inputTitle("Assign a name"), required: false, defaultValue: defaultLabel, submitOnChange: true, width: 6)
if(!app.label){
app.updateLabel(defaultLabel)
state.appDisplayName=defaultLabel
}else{
state.appDisplayName=(String)app.label
}
if(((String)app.label).contains('<span')){
if((String)state.appDisplayName && !((String)state.appDisplayName).contains('<span ')){
app.updateLabel((String)state.appDisplayName)
}else{
String myLabel=((String)app.label).substring(0, ((String)app.label).indexOf('<span'))
state.appDisplayName=myLabel
app.updateLabel((String)state.appDisplayName)
}
}
}
section(){
paragraph(getFormat("line")+"<div style='color:#5BBD76;text-align:center'>${getVersionLabel()}<br>")
}
}
}
def removePage(){
dynamicPage(name: "removePage", title: pageTitle("AutoMower Manager\nRemove AutoMower Manager and its Children"), install: false, uninstall: true){
section (){
paragraph(getFormat("warning", "Removing AutoMower Manager also removes all Mower automations and Devices!"))
}
}
}
Boolean initializeEndpoint(Boolean disableRetry=false) {
String accessToken=(String)state.accessToken
if(!accessToken){
try {
accessToken=createAccessToken()
} catch(Exception e){
LOG("authPage() --> No OAuth Access token", 3, sERROR, e)
}
if(!accessToken && !disableRetry){
enableOauth()
return initializeEndpoint(true)
}
}
return (!!(String)state.accessToken)
}
// try to enable oauth on HE for this app
private void enableOauth(){
Map params=[
uri: "http://localhost:8080/app/edit/update?_action_update=Update&oauthEnabled=true&id=${app.appTypeId}".toString(),
headers: ['Content-Type':'text/html;charset=utf-8']
]
try{
httpPost(params){ resp ->
//LogTrace("response data: ${resp.data}")
}
} catch (e){
LOG("enableOauth something went wrong: ", 1, sERROR, e)
}
}
// Setup OAuth between HE and Husqvarna clouds
def authPage(){
LOG("authPage() --> Begin", 4, sTRACE)
//log.debug "accessToken: ${state.accessToken}, ${state.accessToken}"
Boolean success=initializeEndpoint()
if(!success) {
if(!state.accessToken){
LOG("authPage() --> OAuth", 1, sERROR, e)
LOG("authPage() --> Probable Cause: OAuth not enabled in Hubitat IDE for the 'AutoMower Manager' 'App'", 1, sWARN)
LOG("authPage() --> No OAuth Access token", 3, sERROR)
return dynamicPage(name: "authPage", title: pageTitle("AutoMower Manager\nOAuth Initialization Failure"), nextPage: sBLANK, uninstall: true){
section(){
paragraph "Error initializing AutoMower Authentication: could not get the OAuth access token.\n\nPlease verify that OAuth has been enabled in " +
"the Hubitat IDE for the 'AutoMower Manager' 'App', and then try again.\n\nIf this error persists, view Live Logging in the IDE for " +
"additional error information."
}
}
}
}
String description=sBLANK
Boolean uninstallAllowed=false
Boolean oauthTokenProvided=false
if((String)state.authToken){
description="You are connected. Click Next/Done below."
uninstallAllowed=true
oauthTokenProvided=true
apiRestored()
}else{
description="'Click' to enter AutoMower Credentials"
}
// HE OAuth process
String redirectUrl=oauthInitUrl()
// get rid of next button until the user is actually auth'd
if(!oauthTokenProvided){
LOG("authPage() --> Valid 'HE' OAuth Access token (${state.accessToken}), need AutoMower OAuth token", 3, sTRACE)
LOG("authPage() --> RedirectUrl=${redirectUrl}", 5, sINFO)
return dynamicPage(name: "authPage", title: pageTitle("AutoMower Manager\nHusqvarna API Authentication"), nextPage: sBLANK, uninstall: uninstallAllowed){
oauthSection()
if(getHusqvarnaApiKey() && getHusqvarnaApiSecret()) {
section(sectionTitle(" ")){
paragraph "'Click' below to log in to the Husqvarna service and authorize AutoMower Manager for Hubitat access. Be sure to 'Click' the 'Allow' button on the 2nd page."
href url: redirectUrl, style: "external", required: true, title: inputTitle("AutoConnect Account Authorization"), description: description
}
}
}
}else{
LOG("authPage() --> Valid OAuth token (${(String)state.authToken})", 3, sTRACE)
return dynamicPage(name: "authPage", title: pageTitle("AutoMower Manager\nHusqvarna API Authentication"), nextPage: "mainPage", uninstall: uninstallAllowed){
oauthSection()
if(getHusqvarnaApiKey() && getHusqvarnaApiSecret()) {
section(sectionTitle(" ")){
paragraph "Return to the main menu"
href url:redirectUrl, style: "embedded", state: "complete", title: inputTitle("AutoConnect Account Authorization"), description: description
}
}
}
}
}
def oauthSection(){
section(sectionTitle("Husqvarna Oauth credentials")){
paragraph "Enter Oauth you created from Husqvarna Development portal"
input(name: "apiKey", title:inputTitle("Enter Oauth Key"), type: "text", required:true, description: "Tap to choose", submitOnChange: true, width: 6)
input(name: "apiSecret", title:inputTitle("Enter Oauth Secret"), type: "text", required:true, description: "Tap to choose", submitOnChange: true, width: 6)
String msg= """
Instructions:
Go to developer.husqvarnagroup.cloud
- Sign in with your AutoConnect credentials
- +Create application
- Name it, redirect URI should be set https://cloud.hubitat.com/oauth/stateredirect
- Connect this to authentication api and automower api
- after saving, note application key and application secret to enter into settings here """
paragraph msg
}
}
def mowersPage(params){
LOG("=====> mowersPage() entered", 5)
Map mowers=getAutoMowers(true, "mowersPage")
LOG("mowersPage() -> mower list: ${mowers}",5)
LOG("mowersPage() starting settings: ${settings}",5)
LOG("mowersPage() params passed: ${params}", 5, sTRACE)
dynamicPage(name: "mowersPage", title: pageTitle("AutoMower Manager\nMowers"), params: params, nextPage: sBLANK, content: "mowersPage", uninstall: false){
section(title: sectionTitle("Mower Selection")){
if(mowers) {
paragraph("'Click' below to see the list of AutoMowers available in your AutoConnect account and select the ones you want to connect.")
LOG("mowersPage(): state.settingsCurrentMowers=${state.settingsCurrentMowers} mowers=${(List<String>)settings.mowers}", 4, sTRACE)
if((List<String>)state.settingsCurrentMowers != (List<String>)settings.mowers){
LOG("state.settingsCurrentMowers != mowers: changes detected!", 4, sTRACE)
state.settingsCurrentMowers=(List<String>)settings.mowers ?: []
checkPolls('mowersPage ', true, false)
}else{
LOG("state.settingsCurrentMowers == mowers: No changes detected!", 4, sTRACE)
}
input(name: "mowers", title:inputTitle("Select Mowers"), type: sENUM, required:false, multiple:true, description: "Tap to choose", params: params,
options: mowers, submitOnChange: true, width: 6)
} else paragraph("No mowers found to connect.")
}
}
}
def preferencesPage(){
LOG("=====> preferencesPage() entered. settings: ${settings}", 5)
dynamicPage(name: "preferencesPage", title: pageTitle("AutoMower Manager\nPreferences"), nextPage: sBLANK){
List echo=[]
section(title: sectionTitle("Notifications")){
paragraph("Notifications are only sent when the AutoConnect API connection is lost and unrecoverable, at most 1 per hour.", width: 8)
}
section(title: smallerTitle("Notification Devices")){
input(name: "notifiers", type: "capability.notification", multiple: true, title: inputTitle("Select Notification Devices"), submitOnChange: true, width: 6,
required: false /*(!settings.speak || ((settings.musicDevices == null) && (settings.speechDevices == null)))*/)
if(settings.notifiers){
echo=settings.notifiers.findAll { (it.deviceNetworkId.contains('|echoSpeaks|') && it.hasCommand('sendAnnouncementToDevices')) }
if(echo){
input(name: "echoAnnouncements", type: sBOOL, title: "Use ${echo.size()>1?'simultaneous ':''}Announcements for the Echo Speaks device${echo.size()>1?'s':''}?",
defaultValue: false, submitOnChange: true)
}
}
}
section(hideWhenEmpty: (!settings.speechDevices && !settings.musicDevices), title: smallerTitle("Speech Devices")){
input(name: "speak", type: sBOOL, title: inputTitle("Speak messages?"), required: !settings?.notifiers, defaultValue: false, submitOnChange: true, width: 6)
if((Boolean)settings.speak){
input(name: "speechDevices", type: "capability.speechSynthesis", required: (settings.musicDevices == null), title: inputTitle("Select speech devices"),
multiple: true, submitOnChange: true, hideWhenEmpty: true, width: 4)
input(name: "musicDevices", type: "capability.musicPlayer", required: (settings.speechDevices == null), title: inputTitle("Select music devices"),
multiple: true, submitOnChange: true, hideWhenEmpty: true, width: 4)
input(name: "volume", type: "number", range: "0..100", title: inputTitle("At this volume (%)"), defaultValue: 50, required: false, width: 4)
}
}
if(echo || settings.speak){
section(smallerTitle("Do Not Disturb")){
input(name: "speakModes", type: "mode", title: inputTitle('Only speak notifications during these Location Modes:'), required: false, multiple: true, submitOnChange: true, width: 6)
input(name: "speakTimeStart", type: "time", title: inputTitle('Only speak notifications<br>between...'), required: (settings.speakTimeEnd != null), submitOnChange: true, width: 3)
input(name: "speakTimeEnd", type: "time", title: inputTitle("<br>...and"), required: (settings.speakTimeStart != null), submitOnChange: true, width: 3)
String nowOK=((List)settings.speakModes || ((settings.speakTimeStart != null) && (settings.speakTimeEnd != null))) ?
(" - with the current settings, notifications WOULD ${notifyNowOK()?sBLANK:'NOT '}be spoken now") : sBLANK
paragraph(getFormat('note', "If both Modes and Times are set, both must be true" + nowOK))
}
}
section(title: sectionTitle("Configuration")){}
section(title: smallerTitle("Polling Interval")){
paragraph("How frequently do you want to poll the Husqvarna cloud for changes? For maximum responsiveness to commands, it is recommended to set this to 1 minute.", width: 8)
paragraph(sBLANK, width: 4)
input(name: "pollingInterval", title:inputTitle("Select Polling Interval")+" (minutes)", type: sENUM, required:false, multiple:false, defaultValue:"15", description: "in Minutes", width: 4,
options:["6", "10", "15", "30", "60"])
if(settings.pollingInterval == null){ app.updateSetting('pollingInterval', "15") }
}
section(title: sectionTitle("Operations")){}
section(title: smallerTitle("Debug Log Level")){
paragraph("Select the debug logging level. Higher levels send more information to IDE Live Logging. A setting of 2 is recommended for normal operations.", width: 8)
paragraph(sBLANK, width: 4)
input(name: "debugLevel", title:inputTitle("Select Debug Log Level"), type: sENUM, required:false, multiple:false, defaultValue:"2", description: "2",
options:["5", "4", "3", "2", "1", "0"], width: 4)
if(settings.debugLevel == null){ app.updateSetting('debugLevel', "2") }
generateEventLocalParams() // push down to devices
}
}
}
def debugDashboardPage(){
LOG("=====> debugDashboardPage() entered.", 5)
dynamicPage(name: "debugDashboardPage", title: sBLANK){
section(getVersionLabel()){}
section(sectionTitle("Commands")){
href(name: "refreshAuthTokenPage", title: sBLANK, required: false, page: "refreshAuthTokenPage", description: "Tap to execute: refreshAuthToken()")
}
section(sectionTitle("Settings Information")){
paragraph "debugLevel: ${getIDebugLevel()}"
paragraph "pollingInterval (Minutes): ${getPollingInterval()}"
paragraph "Selected Mowers: ${settings.mowers}"
}
section(sectionTitle("Dump of Debug Variables")){
Map debugParamList=getDebugDump()
LOG("debugParamList: ${debugParamList}", 4, sDEBUG)
//if( debugParamList?.size() > 0 ){
if( debugParamList != null ){
debugParamList.each { key, value ->
LOG("Adding paragraph: key:${key} value:${value}", 5, sTRACE)
paragraph "${key}: ${value}"
}
}
}
section(sectionTitle("Commands")){
href ("removePage", description: "Tap to remove AutoMower Manager ", title: sBLANK)
}
}
}
def refreshAuthTokenPage(){
LOG("=====> refreshAuthTokenPage() entered.", 5)
Boolean a=refreshAuthToken('refreshAuthTokenPage')
dynamicPage(name: "refreshAuthTokenPage", title: sBLANK){
section(){
paragraph "refreshAuthTokenPage() was called"
}
}
}
Boolean testForDeviceHandlers(){
// Only create the dummy devices if we aren't initialized yet
if((Boolean)state.runTestOnce != null){
if((Boolean)state.runTestOnce == false){
List myChildren=(List)getAllChildDevices()
if(myChildren) removeChildDevices( myChildren, true ) // Delete any leftover dummy (test) children
state.runTestOnce=null
return false
}else{
return true
}
}
String DNIAdder=now().toString()
String d1Str="dummyMowerDNI-${DNIAdder}"
def d1
Boolean success=false
List myChildren=(List)getAllChildDevices()
if(myChildren.size() > 0) removeChildDevices( myChildren, true ) // Delete my test children
LOG("testing for device handlers", 4, sTRACE)
try {
d1=addChildDevice(myNamespace, getAutoMowerName(), d1Str, ((List)location.hubs)[0]?.id, ["label":"AutoMower:TestingForInstall", completedSetup:true])
if((d1 != null) ) success=true
} catch(Exception e){
LOG("testForDeviceHandlers", 1, sERROR, e)
if("${e}".startsWith("com.hubitat.app.exception.UnknownDeviceTypeException")){
LOG("You MUST add the ${getAutoMowerName()} Device Handlers to the IDE BEFORE running the setup.", 1, sERROR)
}
}
LOG("device handlers=${success}", 4, sINFO)
Boolean deletedChildren=true
try {
if(d1) deleteChildDevice(d1Str)
} catch(Exception e){
LOG("Error deleting test devices (${d1})",1,sWARN, e)
deletedChildren=false
}
if(!deletedChildren) runIn(5, delayedRemoveChildren, [overwrite: true])
state.runTestOnce=success
return success
}
void delayedRemoveChildren(){
List myChildren=(List)getAllChildDevices()
if(myChildren.size() > 0) removeChildDevices( myChildren, true )
}
void removeChildDevices(List devices, Boolean dummyOnly=false){
if(!devices){
return
}
Boolean first=true
String devName=sNULL
try {
devices?.each {
devName=it.displayName
String devDNI=it.deviceNetworkId
if(!dummyOnly || devDNI?.startsWith('dummy')){
if(first) {
first=false
LOG("Removing ${dummyOnly?'test':'unused'} child devices",3,sTRACE)
}
LOG("Removing unused child: ${devDNI} - ${devName}",1,sWARN)
deleteChildDevice(devDNI)
}else{
LOG("Keeping child: ${devDNI} - ${devName}",4,sTRACE)
}
}
} catch(Exception e){
LOG("Error removing device ${devName}",1,sWARN, e)
}
}
static String getCallbackUrl() { return "https://cloud.hubitat.com/oauth/stateredirect" }
static String getMowerApiEndpoint() { return "https://api.amc.husqvarna.dev/v1" }
static String getApiEndpoint() { return "https://api.authentication.husqvarnagroup.dev/v1/oauth2" }
static String getWssEndpoint() { return "wss://ws.openapi.husqvarna.dev/v1"}
//String getBuildRedirectUrl() { return "${serverUrl}/oauth/stateredirect?access_token=${state.accessToken}" }
String getStateUrl() { return "${getHubUID()}/apps/${app?.id}/callback?access_token=${state?.accessToken}" }
String getHusqvarnaApiKey(){ return (String)settings.apiKey }
String getHusqvarnaApiSecret(){ return (String)settings.apiSecret }
// OAuth Init URL
String oauthInitUrl(){
LOG("oauthInitUrl", 4)
state.oauthInitState=getStateUrl() // HE does redirect a little differently
//log.debug "oauthInitState: ${state.oauthInitState}"
Map oauthParams=[
response_type: "code",
client_id: getHusqvarnaApiKey(), // actually, the AutoMower Manager app's client ID
scope: "app",
redirect_uri: getCallbackUrl(),
state: state.oauthInitState
]
String res= getApiEndpoint()+"/authorize?${toQueryString(oauthParams)}"
LOG("oauthInitUrl - location: ${res}", 4, sDEBUG)
return res
}
void parseAuthResponse(resp){
String msgH="Display http response | "
//log.debug "response data: ${myObj(resp.data)} ${resp.data}"
String str=sBLANK
resp.data.each {
str += "\n${it.key} --> ${it.value}, "
}
LOG(msgH+"response data: ${str}",4,sDEBUG)
LOG(msgH+"response data object type: ${myObj(resp.data)}",4,sDEBUG)
str=sBLANK
resp.getHeaders().each {
str += "\n${it.name}: ${it.value}, "
}
log.debug msgH+"response headers: ${str}"
log.debug msgH+"isSuccess: ${resp.isSuccess()} | statucode: ${resp.status}"
//str=sBLANK
//log.debug "resp param ${resp.params}"
//resp.params.each { str += "${it.name}: ${it.value}"}
//log.debug "response params: ${str}"
}
private static String encodeURIComponent(value){
// URLEncoder converts spaces to + which is then indistinguishable from any
// actual + characters in the value. Match encodeURIComponent in ECMAScript
// which encodes "a+b c" as "a+b%20c" rather than URLEncoder's "a+b+c"
return URLEncoder.encode(
"${value}".toString().replaceAll('\\+','__wc_plus__'),
'UTF-8'
).replaceAll('\\+','%20').replaceAll('__wc_plus__','+')
}
def callback(){
LOG("callback()>> params: ${params}" /* params.code ${params.code}, params.state ${params.state}, state.oauthInitState ${state.oauthInitState}"*/, 4, sDEBUG)
def code=params.code
String oauthState=params.state
String eMsg = sNULL
if(oauthState == state.oauthInitState){
LOG("callback() --> States matched!", 4)
Map rdata=[
grant_type: "authorization_code",
code : code,
client_id : getHusqvarnaApiKey(),
client_secret : getHusqvarnaApiSecret(),
state : oauthState,
redirect_uri: callbackUrl,
]
//String tokenUrl=getApiEndpoint()+"/token?${toQueryString(tokenParams)}"
String tokenUrl=getApiEndpoint()+"/token"
String data=rdata.collect{ String k,v -> encodeURIComponent(k)+'='+encodeURIComponent(v) }.join('&')
Map reqP=[
uri: tokenUrl,
query: null,
contentType: "application/x-www-form-urlencoded",
// requestContentType: "application/json",
body: data,
timeout: 30
]
LOG("callback()-->reqP ${reqP}", 4)
try {
httpPost(reqP){ resp ->
if(resp && resp.data && resp.isSuccess()){
// parseAuthResponse(resp)
String kk
resp.data.each { kk=it.key }
Map ndata=(Map)new JsonSlurper().parseText(kk)
// log.debug "ndata : ${ndata}"
state.refreshToken=ndata.refresh_token
state.authToken=ndata.access_token
Long tt= (Long)now() + (ndata.expires_in * 1000)
//log.error "tt is ${tt}"
state.authTokenExpires=tt
atomicState.refreshToken=ndata.refresh_token
atomicState.authToken=ndata.access_token
//atomicState.authTokenExpires=tt
//log.error "state.authTokenExpires is ${state.authTokenExpires}"
LOG("Expires in ${ndata.expires_in} seconds", 3)
LOG("swapped token: $ndata; state.refreshToken: ${state.refreshToken}; state.authToken: ${(String)state.authToken}", 3)
state.remove('oauthInitState')
eMsg = success()
} else { eMsg = fail() }
}
} catch(Exception e){
LOG("auth callback()", 1, sERROR, e)
//if(resp) parseAuthResponse(resp)
eMsg = fail()
}
}else{
LOG("callback() failed oauthState != state.oauthInitState", 1, sWARN)
eMsg = fail()
}
render contentType: 'text/html', data: eMsg
}
String success(){
String message="""
<p>Your AutoConnect Account is now connected!</p>
<p>Close this window and click 'Done' to finish setup.</p>
"""
return connectionStatus(message)
}
String fail(){
String message="""
<p>The connection could not be established!</p>
<p>Close this window and click 'Done' to return to the menu.</p>
"""
return connectionStatus(message)
}
String connectionStatus(String message, Boolean close=false){
String redirectHtml = close ? """<script>document.getElementsByTagName('html')[0].style.cursor = 'wait';setTimeout(function(){window.close()},2500);</script>""" : sBLANK
/*String redirectHtml=sBLANK
if(redirectUrl){
redirectHtml="""
<meta http-equiv="refresh" content="3; url=${redirectUrl}" />
"""
} */
String hubIcon='https://raw.githubusercontent.com/SANdood/Icons/master/Hubitat/HubitatLogo.png'
String html="""
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=640">
<title>Husqvarna connection</title>
<style type="text/css">
@font-face {
font-family: 'Swiss 721 W01 Thin';
src: url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-thin-webfont.eot');
src: url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-thin-webfont.eot?#iefix') format('embedded-opentype'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-thin-webfont.woff') format('woff'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-thin-webfont.ttf') format('truetype'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-thin-webfont.svg#swis721_th_btthin') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Swiss 721 W01 Light';
src: url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-light-webfont.eot');
src: url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-light-webfont.eot?#iefix') format('embedded-opentype'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-light-webfont.woff') format('woff'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-light-webfont.ttf') format('truetype'),
url('https://s3.amazonaws.com/smartapp-icons/Partner/fonts/swiss-721-light-webfont.svg#swis721_lt_btlight') format('svg');
font-weight: normal;
font-style: normal;
}
.container {
width: 90%;
padding: 4%;
/*background: #eee;*/
text-align: center;
}
img {
vertical-align: middle;
}
p {
font-size: 2.2em;
font-family: 'Swiss 721 W01 Thin';
text-align: center;
color: #666666;
padding: 0 40px;
margin-bottom: 0;
}
span {
font-family: 'Swiss 721 W01 Light';
}
</style>
</head>
<body>
<div class="container">
<img src="https://raw.githubusercontent.com/imnotbob/autoMower/master/images/husqvarna-logo.png" alt="ecobee icon" />
<img src="https://s3.amazonaws.com/smartapp-icons/Partner/support/connected-device-icn%402x.png" alt="connected device icon" />
<img src="${hubIcon}" alt="Hubitat logo" />
${message}
</div>
${redirectHtml}
</body>
</html>
""".toString()
return html
}
/* """ */
static String myObj(obj){
if(obj instanceof String){return 'String'}
else if(obj instanceof Map){return 'Map'}
else if(obj instanceof List){return 'List'}
else if(obj instanceof ArrayList){return 'ArrayList'}
else if(obj instanceof Integer){return 'Int'}
else if(obj instanceof BigInteger){return 'BigInt'}
else if(obj instanceof Long){return 'Long'}
else if(obj instanceof Boolean){return 'Bool'}
else if(obj instanceof BigDecimal){return 'BigDec'}
else if(obj instanceof Float){return 'Float'}
else if(obj instanceof Byte){return 'Byte'}
else if(obj instanceof ByteArrayInputStream){return 'ByteArrayInputStream'}
else{ return 'unknown'}
}
Boolean weAreLost(String msgH, String meth){
String msg = sBLANK
if(!(String)state.authToken) {
apiLost(msgH+"weAreLost() found no auth token, called by ${meth}")
}
if(apiConnected() == sLOST){
msg += "found connection lost to husqvarna | "
if( refreshAuthToken(meth) ){
msg += " - Was able to recover the lost connection. Please ignore any notifications received. | "
LOG(msgH+msg, 4, sINFO)
}else{
msg += " - Unable to refresh token and get mowers do to loss of API Connection. Please ensure you are authorized."
LOG(msgH+msg, 1, sERROR)
return true
}
}
return false
}
// Get the list of mowers for use in the settings pages
Map<String,String> getAutoMowers(Boolean frc=false, String meth="followup", Boolean isRetry=false){
String msgH="getAutoMowers(force: $frc, calledby: $meth, isRetry: $isRetry) | "
if(debugLevel(4)) { LOG(msgH+"====> entered ",4,sTRACE) }
else LOG(msgH, 3,sTRACE)
if(weAreLost(msgH, 'getAutoMowers')){
return null
}
String cached=sBLANK
Boolean skipIt=false
Boolean myfrc=(!state.mowerData || !state.mowersWithNames)
Integer lastU=getLastTsValSecs("getAutoUpdDt")
if( (frc && lastU < 60)) { skipIt=true }
if( (!frc && lastU < 150) ) { skiptIt=true } // related to getMinMinsBtwPolls
Map<String, String> mowers=[:]
Map mowersLocation=[:]
String msg=sBLANK
if(myfrc || !skipIt) {
updTsVal("getAutoUpdDt")
Map deviceListParams=[
uri: getMowerApiEndpoint() +"/mowers",
headers: [
"Content-Type": "application/vnd.api+json",
"Authorization": "Bearer ${(String)state.authToken}",
"Authorization-Provider": "husqvarna",
"X-Api-Key":getHusqvarnaApiKey()
],
query: null,
timeout: 30
]
if(debugLevel(4)) {
msg+="http params -- ${deviceListParams} "
}
msg +="HTTPGET "
if(msg) {
LOG(msgH + msg, 3, sTRACE)
msg=sBLANK
}
try {
httpGet(deviceListParams) { resp ->
LOG(msgH + "httpGet() ${resp.status} Response", 4, sTRACE)
String rdata
Map adata
if(resp) {
rdata=resp.data.text // need to save first time since it is a ByteArrayInputStream
if(rdata) adata=(Map)new JsonSlurper().parseText(rdata)
}
if(resp && resp.isSuccess() && resp.status == 200 && adata) {
List<Map> ndata=((List<Map>)adata.data)?.findAll { it.type == "mower" }
state.numAvailMowers=((List<Map>)ndata)?.size() ?: 0
Map<String, Map> mdata=[:]
ndata.each { Map mower ->
String dni=getMowerDNI((String) mower.id)
mowers[dni]=getMowerDisplayName(mower)
mowersLocation[dni]=getMowerLocation(mower)
mdata[dni]=mower
}
state.mowerData=mdata
//log.debug "resp: ${state.mowerData}"
}else{
LOG(msgH + "httpGet() in else: http status: ${resp.status}", 1, sTRACE)
//refresh the auth token
if(resp.status == 500) { //} && resp.data?.status?.code == 14) {
if(!isRetry){
LOG(msgH + "Refreshing auth_token!", 3, sTRACE)
if(refreshAuthToken('getAutoMowers')) return getAutoMowers(frc, meth, true)
}
}else{
LOG(msgH + "Other error. Status: ${resp.status} Response data: ${rdata} ", 1, sERROR)
}
return [:]
}
}
} catch(Exception e) {
LOG(msgH + "___exception", 1, sERROR, e)
if(!isRetry) {
Boolean a = refreshAuthToken('getAutoMowers')
}
return [:]
}
state.mowersWithNames=mowers
state.mowersLocation=mowersLocation
}else{
mowers= state.mowersWithNames
mowersLocation=state.mowersLocation
cached="cached "
}
msg += cached+"mowersWithNames: ${mowers}, locations: ${mowersLocation}"
LOG(msgH+msg, 4, sTRACE)
return (mowers) ? mowers.sort { it.value } : null
}
/*
* max 1 command per second
* Commands are queued at Husqvarna, and executed when mower checks in
*/
Boolean sendCmdToHusqvarna(String mowerId, Map data, Boolean isRetry=false, String uriend='actions') {
String msgH = "sendCmdToHusqvarna(mower: $mowerId, data: $data, isRetry: $isRetry uriend: $uriend) | "
Boolean ok = (mowerId && mowerId in (List<String>)settings.mowers)
if (!ok) {
LOG(msgH + "mower not enabled in settings: $settings.mowers", 1, sERROR)
return false
}
if (debugLevel(4)) LOG(msgH + "===> entered", 4, sTRACE)
else LOG(msgH, 3,sTRACE)
if(weAreLost(msgH, 'sendCmdToHusqvarna')){
return false
}
Map deviceListParams=[
uri: getMowerApiEndpoint() +"/mowers"+"/${mowerId}/${uriend}",
headers: [
"Content-Type": "application/vnd.api+json",
"Authorization": "Bearer ${(String)state.authToken}",
"Authorization-Provider": "husqvarna",
"X-Api-Key":getHusqvarnaApiKey()
],
query: null,
body: new JsonOutput().toJson(data),
timeout: 30
]
String msg
msg = sBLANK
if(debugLevel(4)) {
msg+="http params -- ${deviceListParams} "
}
msg +="HTTPPOST "
if(msg) {
LOG(msgH + msg, 2, sTRACE)
msg=sBLANK
}
try {
httpPost(deviceListParams) { resp ->
String rdata
/*
Map adata
if(resp) {
rdata=resp.data.text // need to save first time since it is a ByteArrayInputStream
if(rdata) adata=(Map)new JsonSlurper().parseText(rdata)
}*/
if(resp && resp.isSuccess() && resp.status >= 200 && resp.status <= 299) {
LOG(msgH + "httpPost() ${resp.status} Response", 2, sTRACE)
runIn(85, poll, [overwrite: true]) // give time for command to complete; then get new status
}else{
LOG(msgH + "httpPost() in else: http status: ${resp.status}", 1, sTRACE)
//refresh the auth token
if(resp.status == 500) { //} && resp.data?.status?.code == 14) {
//LOG(msgH + "Storing the failed action to try later", 1, sTRACE)
//state.action="getAutoMowers"
if(!isRetry){
LOG(msgH + "Refreshing auth_token!", 3, sTRACE)
if(refreshAuthToken('sendCmdToHusqvarna')) return sendCmdToHusqvarna(mowerId, data, true,uriend)
}
}else{
LOG(msgH + "Other error. Status: ${resp.status} Response data: ${rdata} ", 1, sERROR)
}
return false
}
}
} catch(Exception e) {
LOG(msgH + "___exception", 1, sERROR, e)
//state.action="getAutoMowers"
if(!isRetry) {
Boolean a = refreshAuthToken('sendCmdToHusqvarna')
}
return false
}
return true
}
Boolean sendSettingToHusqvarna(String mowerId, Map data, Boolean isRetry=false) {
return sendCmdToHusqvarna(mowerId, data, isRetry,'settings')
}
Boolean sendScheduleToHusqvarna(String mowerId, Map data, Boolean isRetry=false) {
return sendCmdToHusqvarna(mowerId, data, isRetry,'calendar')
}
Map getMowerMap(String tid) {
if(tid) {
String dni=getMowerDNI(tid)
Map<String,Map>mowerMap=(Map<String,Map>)state.mowerData
if(dni && mowerMap) {
return mowerMap[dni]
}
}
return null
}
String getMowerName(String tid){
// Get the name for this mower
String DNI=getMowerDNI(tid)
Map<String,String> mowersWithNames=state.mowersWithNames
String mowerName=(mowersWithNames?.containsKey(DNI)) ? mowersWithNames[DNI] : sBLANK
if(mowerName == sBLANK){ mowerName=getChildDevice(DNI)?.displayName } // better than displaying 'null' as the name
return mowerName
}
static String getMowerDNI(String tid){
return tid
//return 'autoconnect-mower-' + ([app.id.toString(), tid].join('.'))
}
static String getMowerDisplayName(Map mower){
String nm=(String)mower?.attributes?.system?.name ?: 'Name not found'
return nm + ' - ' + getMowerModelName(mower)
}
static String getMowerModelName(Map mower){
return (String)mower?.attributes?.system?.model ?: "Model not found"
}
static String getMowerLocation(Map mower){
if((String)mower?.attributes?.mower?.mode && (String)mower?.attributes?.mower?.activity) {
return (String)mower?.attributes?.mower?.mode+sSPACE+(String)mower?.attributes?.mower?.activity
}
return "location not found??"
}