diff options
Diffstat (limited to 'server.py')
-rw-r--r-- | server.py | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/server.py b/server.py new file mode 100644 index 0000000..766cc5f --- /dev/null +++ b/server.py | |||
@@ -0,0 +1,74 @@ | |||
1 | import os | ||
2 | import subprocess | ||
3 | import tornado.web | ||
4 | import tornado.ioloop | ||
5 | import tornado.options | ||
6 | import tornado.process | ||
7 | import tornado.template | ||
8 | import tornado.httpserver | ||
9 | from tornado.options import define, options | ||
10 | |||
11 | define("port", default=8888, help="run on the given port", type=int) | ||
12 | |||
13 | |||
14 | STATUSES = { | ||
15 | 'relay1': True, # Fan | ||
16 | 'relay2': False, # Light | ||
17 | 'relay3': False, | ||
18 | } | ||
19 | |||
20 | |||
21 | # for relay in STATUSES.keys(): | ||
22 | # caller = subprocess.Popen(["ssh","admin@10.0.1.15", | ||
23 | # "cat /proc/power/{}".format(relay)], stdout=subprocess.PIPE) | ||
24 | # output = caller.communicate()[0] | ||
25 | # STATUSES[relay] = output.startswith("1") | ||
26 | |||
27 | |||
28 | class PowerStatusHandler(tornado.web.RequestHandler): | ||
29 | |||
30 | def get(self): | ||
31 | self.finish(STATUSES) | ||
32 | |||
33 | @tornado.web.asynchronous | ||
34 | def _trigger_relay(self, relay, value): | ||
35 | STATUSES[relay] = value | ||
36 | value = 1 if value is True else 0 | ||
37 | tornado.process.Subprocess(["ssh","admin@10.0.1.15", | ||
38 | "echo {} > /proc/power/{}".format(value, relay)], | ||
39 | stdout=tornado.process.Subprocess.STREAM) | ||
40 | |||
41 | def post(self): | ||
42 | for key, value in self.request.arguments.items(): | ||
43 | self._trigger_relay(key, value[0] == "on") | ||
44 | |||
45 | self.finish(STATUSES) | ||
46 | |||
47 | |||
48 | class IndexHandler(tornado.web.RequestHandler): | ||
49 | |||
50 | def get(self): | ||
51 | self.render("index.html") | ||
52 | |||
53 | |||
54 | class Application(tornado.web.Application): | ||
55 | |||
56 | def __init__(self): | ||
57 | handlers = [ | ||
58 | (r"/power-status/?", PowerStatusHandler), | ||
59 | (r"/?", IndexHandler), | ||
60 | ] | ||
61 | settings = dict( | ||
62 | template_path=os.path.join(os.path.dirname(__file__), "templates"), | ||
63 | static_path=os.path.join(os.path.dirname(__file__), "static"), | ||
64 | debug=True, | ||
65 | autoescape=None, | ||
66 | ) | ||
67 | tornado.web.Application.__init__(self, handlers, **settings) | ||
68 | |||
69 | |||
70 | if __name__ == "__main__": | ||
71 | tornado.options.parse_command_line() | ||
72 | http_server = tornado.httpserver.HTTPServer(Application()) | ||
73 | http_server.listen(options.port) | ||
74 | tornado.ioloop.IOLoop.instance().start() | ||