Websocket Server

From Lantronix Wiki!
Revision as of 01:06, 18 November 2014 by Vlkd2103 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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()

Sample HTML File

Upload the HTML file provided inline below (websocket_server.html) via FTP to the PremierWave user file system partition.

<head>
<title>Web to serial</title>
<!-- <script src="js/jquery-1.8.3.min.js"></script> -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var ws = new WebSocket("ws://"+location.hostname+":"+location.port+"/websocket");
ws.onopen = function() {
   ws.send("Hello, world");
};
ws.onmessage = function (evt) {
	$('#output').val($('#output').val()+evt.data);
};

var runningLen = 0;
var interval;

function newText(){
	var form = document.getElementById("textInput");
	var len = form.value.length;
	if (len > runningLen) {
		ws.send(form.value.substring(runningLen));
		runningLen = len;
	} else if (len < runningLen) {
		runningLen = len;
	};
}
function addTextAreaCallback(textArea, callback, delay) {
	var timer = null;
	textArea.onkeyup = function() {
		if (timer) {
			window.clearTimeout(timer);
		}
		timer = window.setTimeout( function() {
			timer = null;
			callback();
		}, delay);
	};
	textArea = null;
}

$(document).ready(function() {
	addTextAreaCallback(document.getElementById("textInput"), newText,500);
});
	
</script>
</head>
<body>

<div id="mainbody" style="background-color:#FFFFFF;margin-left:auto;margin-right:auto;">
	<textarea id="textInput" rows="10" cols="50"></textarea> Text to send to serial port
	<textarea id="output" rows="10" cols="50" readonly></textarea> Text from serial port

</div>

</body>
</html>