forked from LordAur/yeelight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yeelight.go
843 lines (663 loc) · 18.2 KB
/
yeelight.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
package yeelight
import (
"bufio"
"encoding/json"
"fmt"
"math"
"math/rand"
"net"
"net/netip"
"strings"
"time"
)
type Config struct {
conn net.Conn
IpAddress string
Port int
}
type Request struct {
ID int `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
type Response struct {
ID int `json:"id"`
Result []interface{} `json:"result"`
}
type ListenResponse struct {
Method string `json:"method"`
Params struct {
Name string `json:"name"`
Power string `json:"power"`
ColorTemperature int `json:"ct"`
Brightness int `json:"bright"`
Flowing int `json:"flowing"`
FlowParams string `json:"flow_params"`
ColorMode int `json:"color_mode"`
Rgb int `json:"rgb"`
Hue int `json:"hue"`
Saturation int `json:"sat"`
DelayOff int `json:"delayoff"`
} `json:"params"`
}
type FlowExpression struct {
Duration int
Mode int
Value int
Brightness int
}
type Scene struct {
Action string
Color int
ColorTemperature int
Hue int
Saturation int
ColorFlow []FlowExpression
Mode int
Brightness int
Duration int
}
func generateID() int {
rand.Seed(time.Now().UTC().UnixNano())
id := math.Floor((rand.Float64() * 100000) + 1)
return int(id)
}
func New(c *Config) Config {
conn, _ := net.Dial("tcp", fmt.Sprintf("%s:%v", c.IpAddress, c.Port))
return Config{
conn,
c.IpAddress,
c.Port,
}
}
/*
After you run the tcp you should close the tcp connection.
*/
func (c *Config) Close() {
c.conn.Close()
}
/*
This function is used to scan Xiaomi Yeelight device in your Local Area Network with CIDR IP Address.
*/
func Discovery(cidr string) ([]string, error) {
prefix, err := netip.ParsePrefix(cidr)
if err != nil {
panic(err)
}
var ipDevice []string
for addr := prefix.Addr(); prefix.Contains(addr); addr = addr.Next() {
timeout := time.Duration(10 * time.Millisecond)
_, err = net.DialTimeout("tcp", fmt.Sprintf("%s:%d", addr, 55443), timeout)
if err == nil {
ipDevice = append(ipDevice, addr.String())
}
}
return ipDevice, nil
}
/*
This function is used to Listen Yeelight device by IP Address. You should use ReadMessage function to read tcp message.
Example:
conn, err := yeelight.Listen("192.168.100.7")
if err != nil {
...
}
defer conn.Close()
for {
_, err := yeelight.ReadMessage(conn)
if err != nil {
...
}
}
*/
func Listen(ip string) (net.Conn, error) {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", ip, 55443))
if err != nil {
return nil, err
}
return conn, nil
}
/*
This function is used to read TCP message from function Listen.
Example:
for {
_, err := yeelight.ReadMessage(conn)
if err != nil {
...
}
}
*/
func ReadMessage(conn net.Conn) (ListenResponse, error) {
data := ListenResponse{}
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return data, err
}
//fmt.Printf("Test :%v \n", message)
err = json.Unmarshal([]byte(message), &data)
if err != nil {
return data, err
}
return data, err
}
/*
This function is used to generate RGB to decimal integer to represent the color.
You should fill red, green and blue with integer.
*/
func (c *Config) GenerateRGB(red, green, blue int) int {
color := (red * 65536) + (green * 256) + blue
return color
}
/*
This function is used to retrieve current property. The allowed values is "power", "bright", "ct", "rgb", "hue",
"sat", "color_mode", "flowing", "delayoff", "flow_params", "music_on", "name", "bg_power", "bg_flowing", "bg_flow_params",
"bg_ct", "bg_lmode", "bg_bright", "bg_rgb", "bg_hue", "bg_sat", "nl_br", "active_mode"
*/
func (c *Config) GetProps(p ...interface{}) (Response, error) {
id := generateID()
request := Request{
ID: int(id),
Method: "get_prop",
Params: p,
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to change the color temperature. The allowed value for temp is in range 1700 ~ 6500.
The allowed value effect is "sudden" and "smooth". For the duration action, it's should be more than 30 milliseconds.
*/
func (c *Config) SetColorTemp(temp int, effect string, duration int) (Response, error) {
id := generateID()
if effect != "smooth" && effect != "sudden" {
return Response{}, fmt.Errorf("effect values is wrong, yeelight only supports effects 'smooth' and 'sudden'")
}
if temp < 1700 {
temp = 1700
}
if temp > 6500 {
temp = 6500
}
if duration < 30 {
duration = 30
}
request := Request{
ID: int(id),
Method: "set_ct_abx",
Params: []interface{}{temp, effect, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to change the color. The allowed value effect is "sudden" and "smooth".
For the duration action, it's should be more than 30 milliseconds.
*/
func (c *Config) SetRGB(red int, green int, blue int, effect string, duration int) (Response, error) {
id := generateID()
if red < 0 || red > 255 {
return Response{}, fmt.Errorf("rgb should be in range 0-255")
}
if green < 0 || green > 255 {
return Response{}, fmt.Errorf("rgb should be in range 0-255")
}
if blue < 0 || blue > 255 {
return Response{}, fmt.Errorf("rgb should be in range 0-255")
}
if effect != "smooth" && effect != "sudden" {
return Response{}, fmt.Errorf("effect values is wrong, yeelight only supports effects 'smooth' and 'sudden'")
}
if duration < 30 {
duration = 30
}
color := (red * 65536) + (green * 256) + blue
request := Request{
ID: int(id),
Method: "set_rgb",
Params: []interface{}{color, effect, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to change the color with hue and saturation.
The allowed value hue is in range 0 ~ 359.
The allowed value sat is in range 0 ~ 100.
The allowed value effect is "sudden" and "smooth".
For the duration action, it's should be more than 30 milliseconds.
*/
func (c *Config) SetHueSaturation(hue int, sat int, effect string, duration int) (Response, error) {
id := generateID()
if hue < 0 || hue > 359 {
return Response{}, fmt.Errorf("hue value should be in range 0-359")
}
if sat < 0 || sat > 100 {
return Response{}, fmt.Errorf("saturation value should be in range 0-100")
}
if effect != "smooth" && effect != "sudden" {
return Response{}, fmt.Errorf("effect values is wrong, yeelight only supports effects 'smooth' and 'sudden'")
}
if duration < 30 {
duration = 30
}
request := Request{
ID: int(id),
Method: "set_hsv",
Params: []interface{}{hue, sat, effect, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to change the brightness.
The allowed value brightness is in range 1 ~ 100.
The allowed value effect is "sudden" and "smooth".
For the duration action, it's should be more than 30 milliseconds.
*/
func (c *Config) SetBright(brightness int, effect string, duration int) (Response, error) {
id := generateID()
if effect != "smooth" && effect != "sudden" {
return Response{}, fmt.Errorf("effect values is wrong, yeelight only supports effects 'smooth' and 'sudden'")
}
if brightness < 1 {
brightness = 1
}
if brightness > 100 {
brightness = 100
}
if duration < 30 {
duration = 30
}
request := Request{
ID: int(id),
Method: "set_bright",
Params: []interface{}{brightness, effect, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to switch on or off. The allowed value effect is "sudden" and "smooth".
For the duration action, it's should be more than 30 milliseconds.
*/
func (c *Config) SetPower(power bool, effect string, duration int) (Response, error) {
id := generateID()
p := "off"
if power {
p = "on"
}
if duration < 30 {
duration = 30
}
if effect != "smooth" && effect != "sudden" {
return Response{}, fmt.Errorf("effect values is wrong, yeelight only supports effects 'smooth' and 'sudden'")
}
request := Request{
ID: int(id),
Method: "set_power",
Params: []interface{}{p, effect, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to save current state.
*/
func (c *Config) SetDefault() (Response, error) {
id := generateID()
request := Request{
ID: int(id),
Method: "set_default",
Params: []interface{}{},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to start a color flow. "count" is the number of visible state changing before color flow stopped.
"action" is the action taken after the flow is stopped.
0 means smart LED recover to the state before the color flow started.
1 means smart LED stay at the state when the flow is stopped.
2 means turn off the smart LED after the flow is stopped.
"exprs" is the expression of the state changing series. Fill with "mode" 1 - color, 2 - color temperature,
"duration" for the duration in milliseconds, "value" is following the "mode", color or color temperature.
*/
func (c *Config) SetColorFlow(count, action int, exprs []FlowExpression) (Response, error) {
id := generateID()
if action < 0 && action > 2 {
return Response{}, fmt.Errorf("action should be in range 0-2")
}
var exprStrArr []string
for _, expr := range exprs {
if expr.Duration < 30 {
expr.Duration = 30
}
if expr.Mode != 1 && expr.Mode != 2 && expr.Mode != 7 {
return Response{}, fmt.Errorf("flow expression mode should be 1, 2 or 7. 1 - color, 2 - color temperature, 7 - sleep")
}
if expr.Brightness < 1 {
expr.Brightness = 1
} else if expr.Brightness > 100 {
expr.Brightness = 100
}
exprStrArr = append(exprStrArr, fmt.Sprintf("%d,%d,%d,%d", expr.Duration, expr.Mode, expr.Value, expr.Brightness))
}
request := Request{
ID: int(id),
Method: "start_cf",
Params: []interface{}{count, action, strings.Join(exprStrArr, ",")},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
The function is used to stop current color flow.
*/
func (c *Config) StopColorFlow() (Response, error) {
id := generateID()
request := Request{
ID: int(id),
Method: "stop_cf",
Params: []interface{}{},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to set scene with color, hue saturation, color temperature or color flow.
*/
func (c *Config) SetScene(scene Scene) (Response, error) {
id := generateID()
var params []interface{}
if scene.Action == "color" {
params = []interface{}{scene.Action, scene.Color, scene.Brightness}
} else if scene.Action == "hsv" {
params = []interface{}{scene.Action, scene.Hue, scene.Saturation, scene.Brightness}
} else if scene.Action == "ct" {
params = []interface{}{scene.Action, scene.ColorTemperature, scene.Brightness}
} else if scene.Action == "cf" {
params = []interface{}{scene.Action, scene.Duration, scene.Mode, scene.ColorFlow}
}
request := Request{
ID: id,
Method: "set_scene",
Params: params,
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to added a cron job to turn off the lamp.
*/
func (c *Config) CronAdd(timer int) (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "cron_add",
Params: []interface{}{0, timer},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to get cron jobs in queue.
*/
func (c *Config) CronGet() (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "cron_get",
Params: []interface{}{0},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to delete cron job in queue.
*/
func (c *Config) CronDelete() (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "cron_del",
Params: []interface{}{0},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to adjust brightness, color tempterature or color.
The allowed value "action" is increase, decrease and circle.
The allowed value "prop" is bright, ct and color.
*/
func (c *Config) SetAdjust(action, prop string) (Response, error) {
id := generateID()
if action != "increase" && action != "decrease" && action != "circle" {
return Response{}, fmt.Errorf("action should be increase, decrease or circle")
}
if prop != "bright" && prop != "ct" && prop != "color" {
return Response{}, fmt.Errorf("prop should be bright, ct or color")
}
if prop == "color" && action != "circle" {
return Response{}, fmt.Errorf("when props is color, the action can only be circle")
}
request := Request{
ID: id,
Method: "set_adjust",
Params: []interface{}{action, prop},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
The function is used to change the device name, stored in device not cloud.
*/
func (c *Config) SetName(name string) (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "set_name",
Params: []interface{}{name},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to adjust the brightness by specified bright percentage within specified duration.
"bright" should fill with range -100 ~ 100.
"duration" set the action duration with milisecond.
*/
func (c *Config) AdjustBright(bright, duration int) (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "adjust_bright",
Params: []interface{}{bright, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}
/*
This function is used to adjust the color temperature by specified bright percentage within specified duration.
"bright" should fill with range -100 ~ 100.
"duration" set the action duration with milisecond.
*/
func (c *Config) AdjustColorTemperature(bright, duration int) (Response, error) {
id := generateID()
request := Request{
ID: id,
Method: "adjust_ct",
Params: []interface{}{bright, duration},
}
bytes, _ := json.Marshal(request)
_, err := c.conn.Write([]byte(string(bytes) + "\r\n"))
if err != nil {
return Response{}, err
}
message, _ := bufio.NewReader(c.conn).ReadString('\n')
var r Response
err = json.Unmarshal([]byte(message), &r)
if err != nil {
return Response{}, err
}
return r, nil
}