Announcement

Collapse
No announcement yet.

Webserver example, data out to serial port

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • mariano
    replied
    By the way, ftp all these files to the PremierWave after installing Python on it, or upload them via the configuration web server. Then the files will be in /ltrx_user/ (that's the base directory of the ftp server).

    You can either log into the shell and execute /usr/bin/python /ltrx_user/start.py, or before creating the firmware image with Python make sure that /etc/inittab starts /usr/bin/python /ltrx_user/start.py

    Leave a comment:


  • mariano
    started a topic Webserver example, data out to serial port

    Webserver example, data out to serial port

    File start.py sets up two queues for data. From serial to web, and from web to serial. Then it spawns two separate processes, one for the webserver and the other for the serial port. It passes the queue to those two processes so that they can communicate with each other.

    File webserver.py creates a webserver on port 8080. It serves file index.html. It handles the POST for data.txt and puts that data to the web to serial queue. It also handles GET to serial.txt by sending back the data from the serial to web queue.

    File rs232.py reads from the serial port and puts it in the serial to web queue. It also reads from the web to serial queue and writes the data to the serial port. It does this in a 1 second loop.

    File index.html creates two textareas. One is an input and another is a display. The javascript here takes what's written in the input and does an HTTP POST to the webserver as file data.txt. Every 2 seconds, it does an HTTP GET to get the serial.txt file and displays the data in the display textarea.

    start.py
    Code:
    #!/usr/bin/python
    
    import webserver
    import rs232
    import socket
    import time
    
    from multiprocessing import Process,  Queue
    
    		
    if __name__ == '__main__':
    	serToWeb = Queue()
    	webToSer = Queue()
    
    	while True:
    		try:
    			sockstat = True
    			socket.setdefaulttimeout(None)
    		except Exception:
    			sockstat = False
    
    		if sockstat:
    			break
    	
    	p = Process(target=webserver.startServer, args=(serToWeb,webToSer,))
    	p.start()
    	time.sleep(20)
    	p2 = Process(target=rs232.getData, args=(serToWeb,webToSer,))
    	p2.start()
    	p.join()
    	p2.join()
    webserver.py
    Code:
    #!/usr/bin/python
    
    import SimpleHTTPServer
    import SocketServer
    import time
    
    from os import curdir, sep
    from multiprocessing import Queue
    
    PORT = 8080
    
    # Setup a custom handler to be able to pass the nameserver
    # to the webserver.
    class myServer(SocketServer.ThreadingTCPServer):
    	def __init__(self,server_address,RequestHandlerClass,serToWeb,webToSer):
    		SocketServer.ThreadingTCPServer.__init__(self,server_address,RequestHandlerClass)
    		self.serToWeb = serToWeb
    		self.webToSer = webToSer
    
    # The actual class that implements the webserver.
    
    class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    
    	def do_POST(self):
    		# This will accept a POST with any file ending in .txt
    		# The example uses data.txt, but could be anything
    		if self.path.endswith(".txt"):
    			content_len = int(self.headers.getheader('content-length'))
    			self.server.webToSer.put(self.rfile.read(content_len))
    			self.send_response(200)
    			self.send_header('Content-type','text/plain')
    			self.end_headers()
    			outData = ""
    			try:
    				while True:
    				# we'll exit out of this infinite loop when there's no data left in the
    				# serToWeb queue and we get a Queue Empty exception
    					outData = outData + self.server.serToWeb.get_nowait()
    			except Exception:
    				pass
    			self.wfile.write(outData)
    		else:
    			self.send_response(404)
    			
    		return
    		
    	def do_GET(self):
    		if self.path == "/":
    			self.path="index.html"
    		
    		if self.path == "/serial.txt":
    			self.send_response(200)
    			self.send_header('Content-type','text/text')
    			self.end_headers()
    			outData = ""
    			try:
    				while True:
    				# we'll exit out of this infinite loop when there's no data left in the
    				# serToWeb queue and we get a Queue Empty exception
    					outData = outData + self.server.serToWeb.get_nowait()
    			except Exception:
    				pass
    			self.wfile.write(outData)
    			return
    	
            # The code inside this try..catch statement is only
            # necessary to implement a more complete webserver to
            # serve other files from the base filesystem where
            # this is run.
    		try:
    			#Check the file extension required and
    			#set the right mime type
    			sendReply = False
    			if self.path.endswith(".html"):
    				mimetype='text/html'
    				sendReply = True
    			if self.path.endswith(".jpg"):
    				mimetype='image/jpg'
    				sendReply = True
    			if self.path.endswith(".gif"):
    				mimetype='image/gif'
    				sendReply = True
    			if self.path.endswith(".js"):
    				mimetype='application/javascript'
    				sendReply = True
    			if self.path.endswith(".css"):
    				mimetype='text/css'
    				sendReply = True
    
    			if sendReply == True:
    				#Open the static file requested and send it
    				f = open('/ltrx_user' + sep + self.path)
    				#f = open(curdir + sep + self.path) 
    				self.send_response(200)
    				self.send_header('Content-type',mimetype)
    				self.end_headers()
    				self.wfile.write(f.read())
    				f.close()
    			return
    		except IOError:
    			self.send_error(404, 'File not found')
    		
    
    def startServer(serToWeb,webToSer):
    	httpd = myServer(("", PORT), Handler, serToWeb, webToSer)
    	httpd.serve_forever()
    rs232.py
    Code:
    #!/usr/bin/python
    
    import time
    import serial
    
    # This runs a continuous loop listening for lines coming from the
    # serial port and processing them.
    def getData(serToWeb,webToSer):
    	ser = setupSerial('/dev/ttyS1',9600)
    	while True:
    		try:
    			serInput = ser.read(ser.inWaiting())
    			if serInput != "":
    				serToWeb.put(serInput)
    				print serInput
    		except Exception:
    			pass
    			
    		try:
    			ser.write(webToSer.get_nowait())
    		except Exception:
    			pass
    
    		time.sleep(1)
    
    # setup the serial port. Pass the device as '/dev/ttyS1' or '/dev/ttyS2' for
    # serial port 1 and 2 (respectively) in PremierWave EN, but reversed (2 and 1 respectively)
    # for PremierWave XN
    def setupSerial(device,baud):
    	while True:
    		try:
    			serstat = True
    			ser = serial.Serial(device,baud)
    		except Exception:
    			serstat = False
    		if serstat:
    			break
    		
    	return ser
    
    # returns a list with all the lines received
    # not used, but it's here in case you want to change it to per line
    # instead of per character
    def receive_line(ser):
    	buffer = ''
    	
        # read all the characters that are in the receive buffer
    	while True:
    		try:
    			buffer = buffer + ser.read(ser.inWaiting())
    		except Exception:
    			pass
    		time.sleep(0.5)
    		
            # if we have a new line, return a list with all the
            # lines we have received until now. The list includes
            # an element with \r between each line (except at the end)
    		if '\r' in buffer:
    			lines = buffer.split('\r')
    			return lines[:-1]
    index.html
    Code:
    <!DOCTYPE html>
    <html>
    <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 runningLen = 0;
    var interval;
    
    function newText(){
    	var form = document.getElementById("textInput");
    	var len = form.value.length;
    	if (len > runningLen) {
    		$.post("data.txt", form.value.substring(runningLen), function(data){$('#output').val($('#output').val()+data)} );
    		runningLen = len;
    	} else if (len < runningLen) {
    		runningLen = len;
    	};
    }
    
    function getText(){
    	$.get("serial.txt",function(data){$('#output').val($('#output').val()+data)} );
    }
    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;
    }
    function setTimer(time)
    {
    	window.clearInterval(interval);
    	timer = time;
    	if (time != 0) {
    		interval = setInterval(function(){getText()}, time*1000);
    	}
    }
    
    $(document).ready(function() {
    	addTextAreaCallback(document.getElementById("textInput"), newText,500);
    	setTimer(2);
    });
    	
    </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>
Working...
X