samedi 22 juin 2019

python embedded-linux server

I am using DE1-SoC board where I have a python server running. The board has embedded linux on it. After starting the server I call it from my laptop's web browser and it displays a html web page. Also, the python server is reading data from the board's gsensor. Now, what I want to do is display this data that the server has read from the gsensor on to the web page and everytime the page is refreshed, new data would be displayed. The data is a simple string, so I was wondering if there was a way of achieving this without using Flask framework.

Here is my python server code:

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import shlex,subprocess

PORT_NUMBER = 8080

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests
def do_GET(self):
    if self.path=="/":
        self.path="/index.html"

    try:
        #Check the file extension required and
        #set the right mime

        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:
            cmd=["./gsensor", ""]
                        proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, 
 shell=True)
            line=proc.stdout.readline()
            print("linija1:",line)
            line=proc.stdout.readline()
            print("linija2:",line)
            line=proc.stdout.readline()
            print("linija3:",line)

            #Open the static file requested and send it
            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: %s' % self.path)

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER

    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()




Aucun commentaire:

Enregistrer un commentaire