-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDPClient.py
66 lines (62 loc) · 1.58 KB
/
UDPClient.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
import serial
import socket
import time
FROM_GATEWAY = 0
FIRE_ALARM = 1
API_VERSION = 2
MODE = 3
DURATION = 4
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8',80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def alert_operation(mode, duration):
if(mode == 1):
conn.write('RO')
time.sleep(duration)
conn.write('FQ')
elif(mode == 2):
conn.write('1P')
time.sleep(duration)
conn.write('FQ')
elif(mode == 3):
conn.write('RO1P')
time.sleep(duration)
conn.write('FQ')
else:
print('unrecognized mode')
# setup serial port
conn = serial.Serial('/dev/ttyUSB0',timeout=.2)
time.sleep(3)
conn.write('FQ')
# setup UDP client port
IP = get_host_ip()
serverAddressPort = (IP, 20001)
bufferSize = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(serverAddressPort)
print('Start UDP Server Listening at port: {}'.format(IP))
while True:
bytesAddressPair = sock.recvfrom(bufferSize)
# print(bytesAddressPair[0], bytesAddressPair[1])
message = bytesAddressPair[0]
address = bytesAddressPair[1]
API_ver = None
print('received message: {}, from: {}'.format(message, address))
splitted_message = message.split(';')
if(splitted_message[FROM_GATEWAY] != '6'):
print('Data aren\'t from Gateway')
continue
elif(splitted_message[FIRE_ALARM] != '7'):
print('FIRE_ALARM Error')
continue
else:
API_ver = splitted_message[API_VERSION]
mode = int(splitted_message[MODE])
duration = int(splitted_message[DURATION])
alert_operation(mode, duration)
# time.sleep(0.3)