-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
1362 lines (1153 loc) · 32.2 KB
/
main.go
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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/lnquy/cron"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
)
// this key is basically useless, as it's hardcoded into the open source code...
// but some encryption is better than none
var encodedKey = "gM4NSmqvYb5ajCxsDwWz5W/+b+RM1LXs11e0zw4gwVY="
var encryptionKey []byte
func init() {
var err error
encryptionKey, err = base64.StdEncoding.DecodeString(encodedKey)
if err != nil {
panic(err)
}
}
func saveAPIKey(apiKey string, name string) error {
// Get the user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
// Specify the file path
filePath := filepath.Join(homeDir, ".duux-"+name+".enc")
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return err
}
ciphertext := make([]byte, aes.BlockSize+len(apiKey))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(apiKey))
encodedStr := base64.StdEncoding.EncodeToString(ciphertext)
err = ioutil.WriteFile(filePath, []byte(encodedStr), 0644)
if err != nil {
return err
}
fmt.Println("API key saved")
return nil
}
func getAPIKey(name string) (string, error) {
// Get the user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
// Specify the file path
filePath := filepath.Join(homeDir, ".duux-"+name+".enc")
encodedStr, err := ioutil.ReadFile(filePath)
if err != nil {
// the file doesn't exist
return "", errors.New("API key file not found")
}
ciphertext, err := base64.StdEncoding.DecodeString(string(encodedStr))
if err != nil {
return "", err
}
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
return string(ciphertext), nil
}
func saveUserData(userData UserResponseSubset) error {
// Get the user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
// Specify the file path
filePath := filepath.Join(homeDir, ".duux-user.json")
// Marshal the userData into JSON
jsonData, err := json.MarshalIndent(userData, "", " ")
if err != nil {
return err
}
// Write the JSON data to the file
err = os.WriteFile(filePath, jsonData, 0644)
if err != nil {
return err
}
fmt.Printf("User data saved to %s\n", filePath)
return nil
}
func sendLoginCode() {
fmt.Println("Logging in...")
// ask for email
fmt.Println("\nEnter your email: ")
var email string
fmt.Scanln(&email)
url := "https://v4.api.cloudgarden.nl/tenants/44/auth/passwordlessLogin/code"
method := "POST"
// Parameters from the iOS app.
// Effectively, we are emulating the iOS app here.
payload := strings.NewReader(`{
"email": "` + email + `",
"client_id": "83f34a5fa5faca9023c78980a57a87b41f6972fc4ee45e9c",
"redirect_uri": "https://duux-deeplink.vercel.app/login/verify",
"code_challenge_method": "sha256",
"code_challenge": "NzyryiS6cQ7w7ZjwXmFkM4a3ZU0wZ8tLKe1VfuRaYCY"
}`)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Host", "v4.api.cloudgarden.nl")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("If-None-Match", "W/\"66-H6c9DH7yr0xVY8YpuhpYVXVKCCw\"")
req.Header.Add("Accept", "*/*")
req.Header.Add("Accept-Language", "en-GB,en;q=0.9")
req.Header.Add("User-Agent", "Duux/154 CFNetwork/1335.0.3.4 Darwin/21.6.0")
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
loginCodeResponse := LoginCodeResponse{}
json.Unmarshal(body, &loginCodeResponse)
if loginCodeResponse.Success {
fmt.Println("Successfully sent login code!\nPlease check your email.")
// ask for login code
fmt.Println("\nEnter your login code: ")
var loginCode string
fmt.Scanln(&loginCode)
// pass login code to getAuthToken()
getAuthToken(loginCode)
} else {
fmt.Println("Failed!")
fmt.Println("Message: " + loginCodeResponse.Message)
}
}
func getAuthToken(loginCode string) {
fmt.Println("Getting auth token...")
url := "https://v4.api.cloudgarden.nl/auth/oauth2/token"
method := "POST"
// Parameters from the iOS app.
// Effectively, we are emulating the iOS app here.
payload := strings.NewReader(`{
"grant_type": "authorization_code",
"code": "` + loginCode + `",
"code_verifier": "j2yOyLB3KbdFE3ZjYtm6QGMDBL8-_5FWo0UMYkRVdljLYATNMFa4fJ86vwe3jsVHPsuZcZXGLkezJqHnvhLrRMJjymjDnw-LvCA8WVAFQZNWwFmiUULgNsldc29ZyI36",
"client_id": "83f34a5fa5faca9023c78980a57a87b41f6972fc4ee45e9c",
"redirect_uri": "https://duux-deeplink.vercel.app/login/verify",
"makeAccessTokenLongLasting": true
}`)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Host", "v4.api.cloudgarden.nl")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Accept", "*/*")
req.Header.Add("User-Agent", "Duux/154 CFNetwork/1335.0.3.4 Darwin/21.6.0")
req.Header.Add("Accept-Language", "en-GB,en;q=0.9")
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
authTokenResponse := AuthTokenResponse{}
json.Unmarshal(body, &authTokenResponse)
if authTokenResponse.AccessToken != "" {
fmt.Println("Successfully got auth token!")
saveAPIKey(authTokenResponse.AccessToken, "access_token")
saveAPIKey(authTokenResponse.RefreshToken, "refresh_token")
// get the user data
getUserData()
} else {
fmt.Println("Failed!")
fmt.Println("Message: " + authTokenResponse.AccessToken)
}
}
func getUserData() {
fmt.Println("Getting user...")
url := "https://v4.api.cloudgarden.nl/users/current"
method := "GET"
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
userResponse := UserResponseSubset{}
json.Unmarshal(body, &userResponse)
// save the user data to a file
saveUserData(userResponse)
fmt.Println("Successfully got user!")
}
// get the user data from the file
func getUserDataFromFile() UserResponseSubset {
// Get the user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
return UserResponseSubset{}
}
// Specify the file path
filePath := filepath.Join(homeDir, ".duux-user.json")
// read the file
jsonData, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println(err)
return UserResponseSubset{}
}
userResponse := UserResponseSubset{}
json.Unmarshal(jsonData, &userResponse)
return userResponse
}
// devices are called "sensors" in the API
func getSensors() []SensorResponse {
fmt.Println("Getting sensors...\n")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return nil
}
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors"
method := "GET"
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return nil
}
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return nil
}
req.Header.Add("Authorization", "Bearer "+apiKey)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return nil
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return nil
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return nil
}
sensorResponse := []SensorResponse{}
json.Unmarshal(body, &sensorResponse)
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.Debug)
// for each sensor, get the specific data
for _, sensor := range sensorResponse {
url = "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fmt.Sprint(sensor.ID)
method = "GET"
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return nil
}
// no need to get again - we already have API key from prev request
req.Header.Add("Authorization", "Bearer "+apiKey)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return nil
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return nil
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return nil
}
// unmarshal the response
sensorResponseIndividual := SensorResponseIndividual{}
json.Unmarshal(body, &sensorResponseIndividual)
// replace ints with strings
// power - 0 = off, 1 = on
// mode - 0 = normal, 1 = natural, 2 = night
// swing - 0 = off, 1 = on
// tilt - 0 = off, 1 = on
if sensorResponseIndividual.LatestData.FullData.Power != nil {
if *sensorResponseIndividual.LatestData.FullData.Power == 0 {
sensorResponseIndividual.LatestData.FullData.PowerString = new(string)
*sensorResponseIndividual.LatestData.FullData.PowerString = "Off"
} else if *sensorResponseIndividual.LatestData.FullData.Power == 1 {
sensorResponseIndividual.LatestData.FullData.PowerString = new(string)
*sensorResponseIndividual.LatestData.FullData.PowerString = "On"
}
} else {
sensorResponseIndividual.LatestData.FullData.PowerString = new(string)
*sensorResponseIndividual.LatestData.FullData.PowerString = "Unknown"
}
if sensorResponseIndividual.LatestData.FullData.Mode != nil {
if *sensorResponseIndividual.LatestData.FullData.Mode == 0 {
sensorResponseIndividual.LatestData.FullData.ModeString = new(string)
*sensorResponseIndividual.LatestData.FullData.ModeString = "Normal"
} else if *sensorResponseIndividual.LatestData.FullData.Mode == 1 {
sensorResponseIndividual.LatestData.FullData.ModeString = new(string)
*sensorResponseIndividual.LatestData.FullData.ModeString = "Natural"
} else if *sensorResponseIndividual.LatestData.FullData.Mode == 2 {
sensorResponseIndividual.LatestData.FullData.ModeString = new(string)
*sensorResponseIndividual.LatestData.FullData.ModeString = "Night"
}
} else {
sensorResponseIndividual.LatestData.FullData.ModeString = new(string)
*sensorResponseIndividual.LatestData.FullData.ModeString = "Unknown"
}
// swing - 0 = off, 1 = on
if sensorResponseIndividual.LatestData.FullData.Swing == 0 {
sensorResponseIndividual.LatestData.FullData.SwingString = new(string)
*sensorResponseIndividual.LatestData.FullData.SwingString = "Off"
} else if sensorResponseIndividual.LatestData.FullData.Swing == 1 {
sensorResponseIndividual.LatestData.FullData.SwingString = new(string)
*sensorResponseIndividual.LatestData.FullData.SwingString = "On"
} else {
sensorResponseIndividual.LatestData.FullData.SwingString = new(string)
*sensorResponseIndividual.LatestData.FullData.SwingString = "Unknown"
}
// tilt - 0 = off, 1 = on
if sensorResponseIndividual.LatestData.FullData.Tilt == 0 {
sensorResponseIndividual.LatestData.FullData.TiltString = new(string)
*sensorResponseIndividual.LatestData.FullData.TiltString = "Off"
} else if sensorResponseIndividual.LatestData.FullData.Tilt == 1 {
sensorResponseIndividual.LatestData.FullData.TiltString = new(string)
*sensorResponseIndividual.LatestData.FullData.TiltString = "On"
} else {
sensorResponseIndividual.LatestData.FullData.TiltString = new(string)
*sensorResponseIndividual.LatestData.FullData.TiltString = "Unknown"
}
// capitalise the colour
sensorResponseIndividual.Colour = strings.Title(sensorResponseIndividual.Colour)
// add 'hours' to the timer text
sensorResponseIndividual.LatestData.FullData.TimerString = new(string)
*sensorResponseIndividual.LatestData.FullData.TimerString = fmt.Sprint(sensorResponseIndividual.LatestData.FullData.Timer) + " hours"
fmt.Fprintln(w, "ID\tType\tName\tColour\tPower\tMode\tSpeed\tVertical\tHorizontal\tTimer\tMAC Address")
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%s\n", sensorResponseIndividual.ID, sensorResponseIndividual.Type, sensorResponseIndividual.Name, sensorResponseIndividual.Colour, *sensorResponseIndividual.LatestData.FullData.PowerString, *sensorResponseIndividual.LatestData.FullData.ModeString, sensorResponseIndividual.LatestData.FullData.Speed, *sensorResponseIndividual.LatestData.FullData.TiltString, *sensorResponseIndividual.LatestData.FullData.SwingString, *sensorResponseIndividual.LatestData.FullData.TimerString, sensorResponseIndividual.LatestData.FullData.Sensor)
}
w.Flush()
return sensorResponse
}
func logout() {
fmt.Println("Logging out...")
// delete the API key files
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
return
}
// Access token
filePath := filepath.Join(homeDir, ".duux-access_token.enc")
err = os.Remove(filePath)
if err != nil {
fmt.Println(err)
return
}
// Refresh token
filePath = filepath.Join(homeDir, ".duux-refresh_token.enc")
err = os.Remove(filePath)
if err != nil {
fmt.Println(err)
return
}
// User data
filePath = filepath.Join(homeDir, ".duux-user.json")
err = os.Remove(filePath)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Successfully logged out!")
}
func setPower(fanID string, power string) {
fmt.Println("Setting power...")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return
}
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fanID + "/command"
method := "POST"
if power == "on" {
power = "01"
} else if power == "off" {
power = "00"
} else {
fmt.Println("Invalid power state: " + power)
return
}
formData := "command=tune+set+power+" + power
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(formData))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
// if success = true
successResponse := SuccessResponse{}
json.Unmarshal(body, &successResponse)
if successResponse.Response.Success {
fmt.Println("Successfully set power!")
} else {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
}
}
func setSpeed(fanID string, speed string) {
fmt.Println("Setting speed...")
// convert speed to int
speedInt := 0
fmt.Sscanf(speed, "%d", &speedInt)
// check if speed is between 1 and 26
if speedInt < 1 || speedInt > 26 {
fmt.Println("Invalid speed: " + speed)
return
}
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return
}
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fanID + "/command"
method := "POST"
formData := "command=tune+set+speed+" + speed
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(formData))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
// if success = true
successResponse := SuccessResponse{}
json.Unmarshal(body, &successResponse)
if successResponse.Response.Success {
fmt.Println("Successfully set speed!")
} else {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
}
}
func setMode(fanID string, mode string) {
fmt.Println("Setting mode...")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return
}
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fanID + "/command"
method := "POST"
if mode == "normal" {
mode = "0"
} else if mode == "natural" {
mode = "1"
} else if mode == "night" {
mode = "2"
} else {
fmt.Println("Invalid mode: " + mode)
return
}
formData := "command=tune+set+mode+" + mode
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(formData))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
// if success = true
successResponse := SuccessResponse{}
json.Unmarshal(body, &successResponse)
if successResponse.Response.Success {
fmt.Println("Successfully set mode!")
} else {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
}
}
func setTimer(fanID string, hours string) {
fmt.Println("Setting timer...")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return
}
// between 1 and 12 hours
hoursInt := 0
fmt.Sscanf(hours, "%d", &hoursInt)
if hoursInt < 1 || hoursInt > 12 {
fmt.Println("Invalid hours: " + hours)
return
}
// turn fan on first
setPower(fanID, "on")
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fanID + "/command"
method := "POST"
formData := "command=tune+set+timer+" + hours
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(formData))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
// if success = true
successResponse := SuccessResponse{}
json.Unmarshal(body, &successResponse)
if successResponse.Response.Success {
fmt.Println("Successfully set timer!")
} else {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
}
}
func setOscillation(fanID string, direction string, state string) {
fmt.Println("Setting oscillation...")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {
tenantID = tenant.ID
break
}
}
// check if tenantID is still 0
if tenantID == 0 {
fmt.Println("Failed!")
fmt.Println("Tenant ID is 0")
return
}
// check if direction is valid
if direction != "vertical" && direction != "horizontal" {
fmt.Println("Invalid direction: " + direction)
return
}
url := "https://v4.api.cloudgarden.nl/tenants/" + fmt.Sprint(tenantID) + "/sensors/" + fanID + "/command"
method := "POST"
// horizontal: swing
// vertical: tilt
if direction == "horizontal" {
direction = "swing"
} else if direction == "vertical" {
direction = "tilt"
}
// on/off
if state == "on" {
state = "1"
} else if state == "off" {
state = "0"
} else {
fmt.Println("Invalid state: " + state)
return
}
formData := "command=tune+set+" + direction + "+" + state
// get the API key
apiKey, err := getAPIKey("access_token")
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(formData))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "Bearer "+apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
// check if there is content in the body
if len(body) == 0 {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
return
}
// if success = true
successResponse := SuccessResponse{}
json.Unmarshal(body, &successResponse)
if successResponse.Response.Success {
fmt.Println("Successfully set oscillation!")
} else {
fmt.Println("Failed!")
fmt.Println("Body: " + string(body))
}
}
func getSchedule(fanID string) {
fmt.Println("Getting schedule...")
// get the tenant from the user data
userData := getUserDataFromFile()
// get the first tenant that isn't id '44' (this is duux default)
var tenantID int
for _, tenant := range userData.User.Tenants {
if tenant.ID != 44 {