-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathweb.py
115 lines (95 loc) · 3.77 KB
/
web.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
#!/usr/bin/env python3
import json
import logging
import tornado.ioloop
import tornado.web
import asyncio
from util import ir, aeha
from sensors import bme
# from switchbot import switchbot
class DefaultHandler(tornado.web.RequestHandler):
def get(self):
raise tornado.web.HTTPError(status_code=404, reason="Not Found")
def write_error(self, status_code, exc_info=None, **kwargs):
self.finish({"error": self._reason})
class IRHandler(tornado.web.RequestHandler):
"""
/api/v1/ir
"""
def initialize(self, config):
self.config = config
async def post(self):
try:
req = tornado.escape.json_decode(self.request.body)
for signal in req:
if 'interval' in signal:
# Convert to seconds
await asyncio.sleep(signal['interval']/1000)
if self.config.debug is None:
ir.send(self.config.ir_gpio, signal['signal'])
else:
arr = [signal['signal'][i:i+2]
for i in range(0, len(signal['signal']), 2)]
s = aeha.format(arr)
fmt = ""
for i in range(0, len(s)):
fmt += "{ "
for j in range(0, len(s[i])):
fmt += "0x{:02X} ".format(s[i][j])
fmt += "}\n"
logging.debug("Received IR Code: \n" + fmt)
self.write({"status": "success"})
except json.decoder.JSONDecodeError as ex:
raise tornado.web.HTTPError(
status_code=400, reason="failed decode json")
except RuntimeError as ex:
raise tornado.web.HTTPError(status_code=500, reason=str(ex))
def write_error(self, status_code, exc_info=None, **kwargs):
self.finish({"error": self._reason})
class SensorsHandler(tornado.web.RequestHandler):
"""
/api/v1/sensors
"""
def initialize(self, config, sensors):
self.config = config
self.sensors = sensors
def get(self):
if self.config.debug is not None:
self.write(self.sensors.example())
return
try:
r = self.sensors.get()
self.write(r)
except RuntimeError as ex:
raise tornado.web.HTTPError(status_code=500, reason=str(ex))
def write_error(self, status_code, exc_info=None, **kwargs):
self.finish({"error": self._reason})
# /api/v1/switchbot
# class SwitchBotHandler(tornado.web.RequestHandler):
# def post(self):
# try:
# req = tornado.escape.json_decode(self.request.body)
# mac = req['mac']
# cmd = req['command']
# switchbot.run(mac, cmd)
# except json.decoder.JSONDecodeError as ex:
# raise tornado.web.HTTPError(status_code=400, reason="failed decode json")
# except RuntimeError as ex:
# raise tornado.web.HTTPError(status_code=500, reason=str(ex))
def start(config):
try:
sensors = bme.BME280(config.bme280_address, config.debug)
web = tornado.web.Application([
(r"/api/v1/ir", IRHandler, dict(config=config)),
(r"/api/v1/sensors", SensorsHandler,
dict(config=config, sensors=sensors)),
# (r"/api/v1/switchbot", SwitchBotHandler, dict())
], default_handler_class=DefaultHandler)
# Enable no_keep_alive (Causes of 'Too many open files' Problem)
server = tornado.httpserver.HTTPServer(web)
server.listen(config.http_port)
logging.info("HTTP Server started on %d", int(config.http_port))
tornado.ioloop.IOLoop.instance().start()
except RuntimeError as ex:
logging.error("Initialize error: %s", str(ex))
raise ex