-
Notifications
You must be signed in to change notification settings - Fork 8
/
udp_client.py
95 lines (71 loc) · 2.5 KB
/
udp_client.py
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
import socket
import sys
import json
class UdpClient:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.sock = None
def send_request(self, cmd):
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.connect((self.ip, self.port))
if sys.version_info < (3, 0):
self.sock.sendall(cmd)
data = self.sock.recvfrom(2048)
self.sock.close()
# print(cmd + ' : ' + data[0])
return data[0]
else:
self.sock.sendall(cmd.encode('UTF-8'))
data = self.sock.recv(2048)
self.sock.close()
# print(cmd + ' : ' + str(data.decode('UTF-8')))
return str(data.decode('UTF-8'))
except:
print('UDP Connection Error: ', sys.exc_info()[0])
raise
def set_light(self, bright, red, green, blue, status, active_bulb):
cmd = '{"cmd":"light_ctrl",' \
'"r":"' + str(red) + '",' \
'"g":"' + str(green) + '",' \
'"b":"' + str(blue) + '",' \
'"bright":"' + str(bright) + '",' \
'"effect":"9",' \
'"iswitch":"' + str(status) + '",' \
'"matchValue":"0",' \
'"sn_list":[' \
'{"sn":"' + active_bulb + '"}' \
']}'
data = self.send_request(cmd)
def set_title(self, sn, title):
cmd = '{"cmd":"set_title","sn":"' + sn + '","title":"' + title + '"}'
data = self.send_request(cmd)
def get_lights(self):
cmd = '{"cmd":"light_list"}'
data = self.send_request(cmd)
try:
json_data = json.loads(data)
return json_data
except:
print('JSON Parsing Error: ', sys.exc_info()[0])
raise
def get_groups(self):
cmd = '{"cmd":"group_list"}'
data = self.send_request(cmd)
try:
json_data = json.loads(data)
return json_data
except:
print('JSON Parsing Error: ', sys.exc_info()[0])
raise
def get_group_lights(self, group_id):
cmd = '{"cmd":"group_leds_list",' \
'"group_id":' + group_id + '"}'
data = self.send_request(cmd)
try:
json_data = json.loads(data)
return json_data
except:
print('JSON Parsing Error: ', sys.exc_info()[0])
raise