forked from gandie/NXT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensor_service.py
72 lines (57 loc) · 2.2 KB
/
sensor_service.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
import socket
import RPi.GPIO as GPIO
import subprocess
import json
import traceback
from threading import Thread
def getip():
ip = subprocess.check_output("hostname -I", shell=True).decode('utf-8') # get ip
ip = ip[:-2] # eliminate unwanted characters
return ip
def server_program():
# get the hostname
host = getip()
port = 8092 # initiate port no above 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
print("listening on: {0}:{1}".format(host,port))
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(3)
while True:
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
t = Thread(target=listen, args=(conn,))
t.start()
def listen(conn):
try:
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
if(str(data) == 'avoid'):
print("avoid: "+str(GPIO.input(avoid)))
conn.send(bytes(str(GPIO.input(avoid)),'utf-8'))
else:
data = json.dumps(shocksDetect)
conn.send(bytes(data,'utf-8')) # send data to the client
except Exception as e:
conn.close() # close the connection
print(e)
traceback.print_exc()
conn.close() # close the connection
shock = 33
avoid = 10
GPIO.setmode(GPIO.BOARD)
GPIO.setup(shock, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(avoid, GPIO.IN)
shocksDetect = 0
def p(ev=None):
global shocksDetect
shocksDetect +=1
print("detect")
GPIO.add_event_detect(shock, GPIO.FALLING, callback=p, bouncetime=200) # wait for falling
server_program()