-
Notifications
You must be signed in to change notification settings - Fork 0
/
motion-server.py
58 lines (53 loc) · 1.66 KB
/
motion-server.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
#!/usr/bin/python3
import socket as sock
from datetime import datetime
from christmastree import ChristmasTree
tree = ChristmasTree()
# TODO: Write code to parse the command line arguments for '--host' or '-h' and ...
# ... '--port' or '-p' options. Assuming they are found, set the 'HOST' and 'PORT' ...
# ... variables accordingly.
# Address Info.
HOST = '127.0.0.1'
PORT = 9001
ADDR = (HOST, PORT)
# Create server socket bound to HOST and listening on port PORT.
ss = sock.socket()
ss.bind(ADDR)
ss.listen(5)
# Begin main server loop.
try:
while True:
# Accept new connections.
s, addr = ss.accept()
s.settimeout(2)
# Receive message.
try:
msg = s.recv(1024)
except sock.timeout:
print(f'ERROR {str(datetime.today())[:-3]}:\tConnection timeout error occurred with client \'{addr[0]}:{addr[1]:d}\'.')
s.close()
continue
# Reflect message back to client.
sent = s.send(msg)
# Print message from client.
smsg = str(msg, encoding='utf-8')
print(f'{str(datetime.today())[:-3]}:\tClient \'{addr[0]}:{addr[1]:d}\' sent message \'{smsg}\'.')
# Cleanup
s.close()
# Perform appropriate action.
if smsg == 'Motion ON.':
tree.on()
elif smsg == 'Motion OFF.':
tree.off()
else:
print('Received message was neither \'Motion ON.\' nor \'Motion OFF.\'. No action was performed.')
except KeyboardInterrupt:
print('Server stopped by keyboard interrupt.')
s.close(); ss.close()
tree.off(); tree.close()
exit(0)
except Exception as e:
print(e)
s.close(); ss.close()
tree.off(); tree.close()
exit(1)