-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
149 lines (111 loc) · 4.26 KB
/
server.py
File metadata and controls
149 lines (111 loc) · 4.26 KB
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
import asyncio
import json
import os
import socket
from huey import Huey
app_path = os.path.dirname(os.path.realpath(__file__))
sock_path = app_path + '/var/huey.sock'
address_list_path = app_path + '/address-list.txt'
busy = False
ready = False
exiting = False
huey = Huey()
async def serve():
global ready
addresses = []
with open(address_list_path, "r") as file:
for line in file:
addresses.append(line.strip())
await huey.start(addresses)
if not os.path.exists(app_path + '/var'):
os.makedirs(app_path + '/var')
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.setblocking(False)
server.bind(sock_path)
os.chmod(sock_path, 0o777)
loop = asyncio.get_running_loop()
ready = True
while not exiting:
print("Waiting for connection ...")
server.listen()
client_connection, client_address = await loop.sock_accept(server)
print('Client connected ... ')
client_connection.settimeout(.1)
try:
message = client_connection.recv(1024)
except TimeoutError:
print('Client had nothing to say. Moving on.')
continue
command = message.decode()
if command:
if command == 'list':
print('Returning device list ...')
response_message = json.dumps(huey.get_list())
try:
client_connection.sendall(response_message.encode())
except BrokenPipeError:
print("Unable to send response: client went away.")
finally:
continue
args = command.split('|')
device = args[0]
action = args[1]
del args[0]
del args[0]
match action:
case 'poll':
asyncio.create_task(huey.poll(device))
case 'info':
info = json.dumps(huey.get_light_by_address(device))
print(f"[{device}] Returning info {info} ... ")
try:
client_connection.sendall(info.encode())
except BrokenPipeError:
print("Unable to send response: client went away.")
finally:
continue
case 'power':
state = 'Off'
if args[0] == 'true':
state = 'On'
print(f"[{device}] Setting power to {state} ... ")
asyncio.create_task(huey.set_power(device, args[0] == 'true'))
case 'brightness':
print(f"[{device}] Setting brightness to {args[0]} ... ")
asyncio.create_task(huey.set_brightness(device, int(args[0])))
case 'temperature':
print(f"[{device}] Setting temp to {args[0]} ... ")
asyncio.create_task(huey.set_temp(device, int(args[0])))
case 'color':
x = float(args[0])
y = float(args[1])
print(f"[{device}] Setting color to {x},{y} ... ")
asyncio.create_task(huey.set_color(device, x, y))
case 'connect':
print(f"[{device}] Explicitly connecting ...")
asyncio.create_task(huey.connect(device))
case 'name':
print(f"[{device}] Setting name to {args[0]} ... ")
asyncio.create_task(huey.set_name(device, args[0]))
client_connection.close()
async def clean_up():
global exiting
if os.path.exists(sock_path):
os.remove(sock_path)
exiting = True
while busy:
await asyncio.sleep(1)
await huey.disconnect_all()
if __name__ == "__main__":
try:
if os.path.exists(sock_path):
os.remove(sock_path)
if not os.path.exists(address_list_path):
print(f"Missing file: {address_list_path}")
exit()
asyncio.get_event_loop().run_until_complete(serve())
except KeyboardInterrupt:
print('Shutting down ...')
finally:
asyncio.get_event_loop().run_until_complete(clean_up())
print('Goodbye! :)')