Skip to content

Instantly share code, notes, and snippets.

@laclefyoshi
Created December 25, 2010 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laclefyoshi/754683 to your computer and use it in GitHub Desktop.
Save laclefyoshi/754683 to your computer and use it in GitHub Desktop.
WebSocket server for communicating Web browser and Arduino
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright : (c) SAEKI Yoshiyasu
# License : MIT-style license
# <http://www.opensource.org/licenses/mit-license.php>
# last updated: 2010/12/24
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.escape
import serial
arduino = None
ARDUINO_PORT = "/dev/tty.usbserial-A7006SSA" # need to check
class Index(tornado.web.RequestHandler):
def get(self):
self.render("sketch.html")
class Glcd(tornado.websocket.WebSocketHandler):
def open(self):
global arduino
arduino = serial.Serial(ARDUINO_PORT, 9600, timeout=3)
print("WebSocket opened")
arduino.open()
arduino.write("c")
self.write_message("ok")
def on_message(self, data):
global arduino
sequence = tornado.escape.json_decode(data)["value"]
if sequence != "":
print sequence
arduino.write(sequence)
rv = arduino.read(size=1)
while rv != b".":
rv = arduino.read(size=1)
print rv
arduino.flush()
self.write_message("ok")
def on_close(self):
global arduino
print("WebSocket closed")
arduino.close()
application = tornado.web.Application([
(r"/", Index),
(r"/glcd", Glcd),
])
def main():
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
print "Starting server..."
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment