forked from nikivanov/watney
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
220 lines (173 loc) · 6.17 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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from audiomanager import AudioManager
from offcharger import OffCharger
from powerplant import PowerPlant
from aiohttp import web
from motorcontroller import MotorController
from servocontroller import ServoController
from lightscontroller import LightsController
from heartbeat import Heartbeat
from subprocess import call
import os
import pigpio
from configparser import ConfigParser
from alsa import Alsa
import ssl
import sys
from externalrunner import ExternalProcess
import asyncio
from januseventhandler import JanusEventHandler
from tts import TTSSpeaker
from startupSequence import StartupSequenceController
routes = web.RouteTableDef()
motorController = None
servoController = None
heartbeat = None
signalingServer = None
alsa = None
tts = None
powerPlant = None
startupController = None
audioManager = None
audioManagerThread = None
janusEventHandler = None
offCharger = None
@routes.get("/")
async def getPageHTML(request):
return web.FileResponse("index.html")
@routes.post("/sendCommand")
async def setCommand(request):
commandObj = await request.json()
newBearing = commandObj['bearing']
newLook = commandObj['look']
newSlow = commandObj['slow']
if newBearing in MotorController.validBearings:
motorController.setBearing(newBearing, newSlow)
else:
print("Invalid bearing {}".format(newBearing))
return web.Response(status=400, text="Invalid")
if newLook == 0:
await servoController.lookStop()
elif newLook == -1:
await servoController.forward()
elif newLook == 1:
await servoController.backward()
else:
print("Invalid look at {}".format(newLook))
return web.Response(status=400, text="Invalid")
return web.Response(text="OK")
@routes.post("/shutDown")
async def shutDown(request):
call("sudo halt", shell=True)
@routes.post("/restart")
async def restart(request):
call("sudo reboot", shell=True)
@routes.post("/sendTTS")
async def sendTTS(request):
ttsObj = await request.json()
ttsString = ttsObj['str']
tts.sayText(ttsString)
return web.Response(text="OK")
@routes.post("/setVolume")
async def setVolume(request):
volumeObj = await request.json()
volume = int(volumeObj['volume'])
alsa.setVolume(volume)
return web.Response(text="OK")
@routes.post("/heartbeat")
async def onHeartbeat(request):
stats = heartbeat.onHeartbeatReceived()
return web.json_response(stats)
@routes.post("/lights")
async def onLights(request):
lightsObj = await request.json()
on = bool(lightsObj['on'])
if on:
lightsController.lightsOn()
else:
lightsController.lightsOff()
return web.Response(text="OK")
async def onJanusEvent(request):
try:
eventObj = await request.json()
janusEventHandler.handleEvent(eventObj)
except Exception as e:
print('Error handling janus event: {}'.format(e))
finally:
return web.Response(text="OK")
# Python 3.7 is overly wordy about self-signed certificates, so we'll suppress the error here
def loopExceptionHandler(loop, context):
exception = context.get('exception')
if isinstance(exception, ssl.SSLError) and exception.reason == 'SSLV3_ALERT_CERTIFICATE_UNKNOWN':
pass
else:
loop.default_exception_handler(context)
def createSSLContext(homePath):
# Create an SSL context to be used by the websocket server
print('Using TLS with keys in {!r}'.format(homePath))
chain_pem = os.path.join(homePath, 'cert.pem')
key_pem = os.path.join(homePath, 'key.pem')
sslctx = ssl.create_default_context()
try:
sslctx.load_cert_chain(chain_pem, keyfile=key_pem)
except FileNotFoundError:
print("Certificates not found, did you run generate_cert.sh?")
sys.exit(1)
# FIXME
sslctx.check_hostname = False
sslctx.verify_mode = ssl.CERT_NONE
return sslctx
runners = []
async def start_site(app, address, port, sslContext=None):
runner = web.AppRunner(app)
runners.append(runner)
await runner.setup()
if sslContext is not None:
site = web.TCPSite(runner, host=address, port=port, ssl_context=sslContext)
else:
site = web.TCPSite(runner, host=address, port=port)
await site.start()
if __name__ == "__main__":
homePath = os.path.dirname(os.path.abspath(__file__))
sslctx = createSSLContext(os.path.dirname(homePath))
gpio = pigpio.pi()
if not gpio.connected:
print('GPIO not connected')
exit()
config = ConfigParser()
config.read(os.path.join(homePath, "rover.conf"))
audioConfig = config["AUDIO"]
videoConfig = config["VIDEO"]
loop = asyncio.get_event_loop()
loop.set_exception_handler(loopExceptionHandler)
audioManager = AudioManager(config)
motorController = MotorController(config, gpio, audioManager)
alsa = Alsa(gpio, config)
servoController = ServoController(gpio, config, audioManager)
lightsController = LightsController(gpio, config)
tts = TTSSpeaker(config, alsa, audioManager)
powerPlant = PowerPlant(config)
startupController = StartupSequenceController(config, servoController, lightsController, tts)
heartbeat = Heartbeat(config, servoController, motorController, alsa, lightsController, powerPlant)
offCharger = OffCharger(config, tts, motorController)
janus = ExternalProcess(videoConfig["JanusStartCommand"], False, False, "janus.log")
videoStream = ExternalProcess(videoConfig["GStreamerStartCommand"], True, False, "video.log")
janusEventHandler = JanusEventHandler()
mainApp = web.Application()
mainApp.add_routes(routes)
mainApp.router.add_static('/js/', path=os.path.join(homePath, 'js'))
loop.create_task(start_site(mainApp, '0.0.0.0', 5000, sslctx))
eventListenerApp = web.Application()
eventListenerApp.add_routes([web.post('/janusEvent', onJanusEvent)])
loop.create_task(start_site(eventListenerApp, 'localhost', 5001))
try:
loop.run_forever()
except:
pass
finally:
servoController.stop()
lightsController.stop()
gpio.stop()
janus.endProcess()
videoStream.endProcess()
for runner in runners:
loop.run_until_complete(runner.cleanup())