# Access Arduino data from SheevaPlug
# Graph data and serve as web pages
#
# Copyright 2009 Ken Shirriff
# http://arcfn.com
import os
import serial
import threading
import time

from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

GNUPLOT_CMD = """\
set xdata time
set format x "%m/%d"
set xtic 86400
set timefmt "%m/%d/%Y %H:%M"
set terminal png xeeeeee x000000 size 500, 500
set output 'graph.png'
set xlabel "Date"
set ylabel "Light"
set title "Illumination"
plot "/tmp/data" using 1:3 title "" with lines
"""

GRAPH_HTML = """<html>
<head>
<link rel="stylesheet" type="text/css" href="/plug.css">
<title>Graph of light in my room</title>
</head>
<body>
<h1>Graph of light in my room</h1>
The following data is obtained by a SheevaPlug accessing an Arduino.
<img src="/graph.png">
<br>
Note: the light is in arbitrary units 0-1023
<p>
For more details see <a href="http://arcfn.com">http://arcfn.com</a>.
</body>
</html>"""

# The web server.  Supports /graph (page containing the graph)
# and static web pages
class MyHandler(SimpleHTTPRequestHandler):
  def do_GET(self):
    if self.path == '/graph':
      return self.graph()
    # Static file
    return SimpleHTTPRequestHandler.do_GET(self)

  # Generate and display the graph
  def graph(self):
    g = os.popen('gnuplot', 'w')
    print >>g, GNUPLOT_CMD
    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write(GRAPH_HTML)

# Read data from Arduino serial port a line at a time
# and dump to file with timestamps
class Arduino(threading.Thread):
  def run(self):
    f = open('/tmp/data', 'a')
    # Port may vary from /dev/ttyUSB1
    self.ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=10)
    self.ser.flushInput()
    old_timestamp = None
    while 1:
      data = self.ser.readline().strip()
      if data:
	timestamp = time.strftime("%m/%d/%Y %H:%M", time.localtime())
	if timestamp != old_timestamp:
	  # Only log once per minute
          print >>f, timestamp, data.strip()
	  old_timestamp = timestamp
	f.flush()

def main():
  ard = Arduino()
  ard.start()
  server = HTTPServer(('', 80), MyHandler)
  print 'Starting server'
  server.serve_forever()

if __name__ == '__main__':
  main()
