/
run.py
90 lines (62 loc) · 1.87 KB
/
run.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
import sys
import json
import traceback
import asyncio
import aiohttp
from aiohttp import web
import logging as log
log.basicConfig(level=log.DEBUG, format="[%(levelname)s] %(message)s")
from cnc import CNC
async def asend(ws, msg):
await ws.send_str(msg)
class Peer:
def __init__(self, loop, ws):
self.loop = loop
self.ws = ws
def send(self, msg):
asyncio.ensure_future(asend(self.ws, json.dumps(msg)), loop=loop)
async def websocket(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
cnc = request.app["cnc"]
peer = Peer(request.app["loop"], ws)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
try:
res = cnc.handle(peer, json.loads(msg.data))
except:
log.warning("error handle request")
log.warning(traceback.format_exc())
elif msg.type == aiohttp.WSMsgType.ERROR:
log.warning("ws exception %s" % ws.exception())
cnc.disconnect(peer)
log.info("ws closed")
return ws
async def index(request):
return web.FileResponse("static/index.html")
async def periodic(app, seconds):
while True:
try:
app["cnc"].poll()
except:
log.warning("error handle request")
log.warning(traceback.format_exc())
await asyncio.sleep(seconds)
loop = asyncio.get_event_loop()
app = web.Application(loop=loop)
app.add_routes([
web.get("/", index),
web.get("/ws", websocket),
])
app.router.add_static("/", path="./static")
app["loop"] = loop
asyncio.ensure_future(periodic(app, 1.0), loop=loop)
with open("config.json", "r") as f:
config = json.load(f)
try:
port = int(sys.argv[sys.argv.index("--port") + 1])
except:
port = 8080
with CNC(config, dummy="--dummy" in sys.argv) as cnc:
app["cnc"] = cnc
web.run_app(app, port=port)