Websocket Server
This example will instantiate a web server running on port 8888 with support for WebSockets enabled. The example HTML file will open a websocket and send data back and forth to Serial Port of PremierWave XN.
Prerequisites
1) Requires PySerial module - already included with the Python supported firmware
2) Download Tornado (http://tornadoweb.org) and do a manual installation.
3) Extract the "tornado" directory from the tarball (tar.gz) and upload it via FTP to the PremierWave User Filesystem partition.
Sample Code
Upload file websocket_server.py (code shown in-line) via FTP to the PremierWave User Filesystem partition.
import tornado.ioloop
import tornado.web
import tornado.websocket
import serial
import time
import threading
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("websocketexample.html")
class WSHandler(tornado.websocket.WebSocketHandler):
connections = []
def open(self):
print "WebSocket opened"
self.connections.append(self)
def on_message(self, message):
for conn in SerialPort.ports:
conn.writer(message)
def on_close(self):
print "WebSocket closed"
self.connections.remove(self)
class SerialPort():
ports = []
def __init__(self, serial_instance):
self.serial = serial_instance
self.ports.append(self)
def start(self):
self.thread_read = threading.Thread(target=self.reader)
self.thread_read.start()
def reader(self):
while True:
buffer = ''
buffer = ser.read(ser.inWaiting())
if buffer:
for conn in WSHandler.connections:
conn.write_message(buffer)
time.sleep(0.5)
def writer(self, data):
self.serial.write(str(data))
application = tornado.web.Application([
(r"/", MainHandler),
(r"/websocket",WSHandler),
])
if __name__ == "__main__":
ser = serial.Serial('/dev/ttyS1')
ser.timeout = 0
s = SerialPort(ser)
s.start()
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()