-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
68 lines (51 loc) · 1.52 KB
/
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
59
60
61
62
63
64
65
66
67
68
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from api import Api
from config import *
import os
import signal
# Protocol for managing MovingRaspiRemote commands
class MovingRaspi(Protocol):
def __init__(self):
self.api = Api("carrito")
def connectionMade(self):
print("A client connected")
def dataReceived(self, data):
coordinates = []
dataRec = data.decode()
print(dataRec)
coordinates = dataRec.split(',')
if coordinates[1] == "Angle":
angleVar = float(coordinates[2])
angle = int(angleVar)
self.api.POSTDir(angle)
elif coordinates[1] == "Speed":
speedVar = float(coordinates[2])
speed = int(speedVar)
self.api.POSTVel(speed)
# print("Angle: ", angleVar + " Speed: ", speedVar)
def stop():
print("STOP")
# Called on process interruption. Set all pins to "low level" output.
def endProcess(signalnum = None, handler = None):
stop()
reactor.stop()
# Get current pid
pid = os.getpid()
# Save current pid for later use
try:
fhandle = open('/var/run/movingraspi.pid', 'w')
except IOError:
print ("Unable to write /var/run/movingraspi.pid")
exit(1)
fhandle.write(str(pid))
fhandle.close()
# Prepare handlers for process exit
signal.signal(signal.SIGTERM, endProcess)
signal.signal(signal.SIGINT, endProcess)
signal.signal(signal.SIGHUP, endProcess)
# Init and start server
factory = Factory()
factory.protocol = MovingRaspi
reactor.listenTCP(PORT, factory, 50, IFACE)
reactor.run()