1
+ import json
2
+
1
3
import webcolors
2
4
3
- from udp import UDP
4
5
from constants import *
5
- from message import Params , Request
6
+ from message import Config , Params , Request
7
+ from udp import UDP
6
8
7
9
8
10
class Light :
9
11
def __init__ (self , ip : str ):
10
12
# TODO: get ip from network auto
11
13
self .ip = ip
12
14
self .udp = UDP (ip )
15
+ self .config = self .get_config ()
13
16
14
17
def send (self , message ):
15
- self .udp .call (message )
18
+ result = self .udp .call (message )
19
+ if message .params :
20
+ self .update_config (message .params )
21
+ return result
16
22
17
23
def on (self ):
18
24
params = Params (state = True )
@@ -22,9 +28,14 @@ def on(self):
22
28
def off (self ):
23
29
params = Params (state = False )
24
30
message = self .message (params )
25
- # print(message)
26
31
self .send (message )
27
32
33
+ def switch (self ):
34
+ if self .config .state :
35
+ self .off ()
36
+ else :
37
+ self .on ()
38
+
28
39
def color (self , ** kwargs ):
29
40
params = Params ()
30
41
if HEXCODE in kwargs :
@@ -41,7 +52,6 @@ def color(self, **kwargs):
41
52
if GREEN in kwargs :
42
53
params ['g' ] = kwargs [GREEN ]
43
54
message = self .message (params )
44
- print (params , message )
45
55
self .send (message )
46
56
47
57
def brightness (self , value : int ):
@@ -61,7 +71,27 @@ def speed(self, value: int):
61
71
62
72
def get_config (self ):
63
73
message = Request (GET_PILOT )
64
- return self .udp .call (message )
74
+ result_json = self .send (message ).decode ('UTF-8' )
75
+ result = json .loads (result_json )['result' ]
76
+ config = Config (state = result ['state' ], scene = result ['sceneId' ], brightness = result ['dimming' ])
77
+ if 'r' in result :
78
+ config .red = result ['r' ]
79
+ config .green = result ['g' ]
80
+ config .blue = result ['b' ]
81
+ return config
82
+
83
+ def update_config (self , params ):
84
+ for key , value in params .items ():
85
+ if key == 'r' :
86
+ self .config .red = params ['r' ]
87
+ elif key == 'g' :
88
+ self .config .green = params ['g' ]
89
+ elif key == 'b' :
90
+ self .config .blue = params ['b' ]
91
+ elif key == 'dimming' :
92
+ self .config .brightness = params ['dimming' ]
93
+ elif key == 'state' :
94
+ self .config .state = params ['state' ]
65
95
66
96
@staticmethod
67
97
def message (params : Params ):
@@ -71,3 +101,4 @@ def message(params: Params):
71
101
if __name__ == '__main__' :
72
102
light = Light (IP )
73
103
light .color (red = 255 )
104
+ light .switch ()
0 commit comments