You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.9 KiB

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
# To handle requests
import json
# Get the host IP
import netifaces as ni
ni.ifaddresses("wlan0")
ip = ni.ifaddresses("wlan0")[ni.AF_INET][0]["addr"]
print("Host IP address:", ip)
# Get the host port
from tornado.options import define, options
define("port", default=8080, help="run on the given port", type=int)
# Our program for reading/writing to our output
import led
class IndexHandler(tornado.web.RequestHandler):
def get(self):
# TODO: render all the controls automatically depending on what we have connected
self.render("index.html", ip = ip, port = options.port)
ws_clients = []
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
if self not in ws_clients:
print("New connection")
ws_clients.append(self)
#self.write_message("Connected")
def on_message(self, message):
print("Message received:", message)
#self.write_message("Message received: " + message)
message = json.loads(message) #load the json
if message["message_type"] == "io_request":
# We have something that we need to do
if message["io_type"] == "led":
colour = message["led_colour"]
operation = message["operation"]
if operation == "toggle":
result = led.toggle(colour)
response = {"message_type": "io_response",
"io_type": "led",
"led_colour": colour,
"led_state": result}
send_to_all(json.dumps(response))
if operation == "read":
result = led.read(colour)
response = {"message_type": "io_response",
"io_type": "led",
"led_colour": colour,
"led_state": result}
send_to_all(json.dumps(response))
# if message == "BUTTON_PRESS":
# result = led.toggle()
# send_to_all("LED_STATE " + str(result))
# if message == "GET_STATES":
# states = led.read("R")
# send_to_all("LED_STATE" + str(states))
def on_close(self):
if self in ws_clients:
ws_clients.remove(self)
print("Connection closed")
def send_to_all(message):
for c in ws_clients:
c.write_message(message)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[
(r"/", IndexHandler),
(r"/ws", WebSocketHandler)
]
)
httpServer = tornado.httpserver.HTTPServer(app)
httpServer.listen(options.port)
print("Listening on port:", options.port)
tornado.ioloop.IOLoop.instance().start()