Python

import sys
import serial
import time
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from urlparse import urlparse, parse_qs

class MyHTTPServer(HTTPServer):

def __init__(self, commandHandler, *args, **kw):
HTTPServer.__init__(self, *args, **kw)
self.context = commandHandler

class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200, ‘OK’)
self.send_header(‘Content-type’, ‘text/html’)
self.end_headers()
query_components = parse_qs(urlparse(self.path).query)
if not query_components:
return
cmd = query_components[“cmd”][0]
cmd_result = self.server.context.executeCommand(cmd)
self.wfile.write(cmd_result)
self.wfile.close()
def end_headers (self):
self.send_header(‘Access-Control-Allow-Origin’, ‘*’)
BaseHTTPRequestHandler.end_headers(self)
def finish(self,*args,**kw):
try:
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
except socket.error:
pass
self.rfile.close()

class CommandHandler():
def __init__(self, serialConnection):
self.serialConnection = serialConnection
self.sensorDataCache = {}

def executeCommand(self,command):
print “command handler ” + command
if(command.startswith(‘GET_’)):
if(self.sensorDataCache.get(command)== None):
self.serialConnection.sendCommand(command + “;”)
resp = self.serialConnection.read()
self.sensorDataCache.update({command:[time.time(),resp]})
elif(self.sensorDataCache.get(command)[0] + 3 < time.time()): #the values of each sensor stays in cache for 3 seconds, then will ask Arduino
self.serialConnection.sendCommand(command + “;”)
resp = self.serialConnection.read()
self.sensorDataCache.update({command:[time.time(),resp]})
return self.sensorDataCache.get(command)[1]
else:
self.serialConnection.sendCommand(command + “;”)

class SerialConnection():
def __init__(self):
self.arduino = serial.Serial(‘/dev/ttyACM0′, 9600, timeout = 1)
self.arduino.write(b’HELLO;’)
time.sleep(3)
def sendCommand(self, command):
self.arduino.write(command)
def read(self):
print “WAITING FOR ARDUINO…..”
return self.arduino.readline()

print time.asctime(), “Starting Server…”
conn = SerialConnection()
cmd = CommandHandler(conn)
server = MyHTTPServer(cmd,(”, 8888), MyHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
server.server_close()
print time.asctime(), “Server Stops”