#!/usr/bin/python
from __future__ import division
import gi, struct, time
from math import sin, pi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject,Gtk


import matplotlib
matplotlib.use('GTK3Agg')
from matplotlib import pyplot

GObject.threads_init()

from scipy import *
import subprocess


port = '/dev/ttyUSB0'

cmd = '''stty -F %s clocal cread -crtscts cs8 -cstopb hup -parenb parodd -brkint -icrnl ignbrk -igncr ignpar imaxbel -inlcr inpck -istrip -iuclc -ixany ixoff -ixon bs0 cr0 ff0 nl0 -ocrnl -ofdel -ofill -olcuc -onlcr -onlret onocr -opost tab0 vt0 -crterase crtkill -ctlecho -echo -echok -echonl -echoprt -icanon -iexten -isig -noflsh -tostop -xcase time 5 min 1 38400''' %port
cmd = cmd.split()
print 'Initializing serial port', port
subprocess.call(cmd)


class Livegraph:
    def __init__(self):
        self.start = time.time()
        self.x = [0]
        self.y = [0]
        self.plot1 = pyplot.plot(self.x, self.y, 'o', linewidth=3)[0]
        self.plot2 = pyplot.plot(self.x, self.y, linewidth=3)[0]

        self.fr = file(port)
        GObject.io_add_watch(self.fr, GObject.IO_IN, self.data_to_read)
        pyplot.ylim(-0.01, 300)
        pyplot.xlabel('time')
        pyplot.ylabel('concentration')
        pyplot.show()

    def data_to_read(self, a, b):
        line = self.fr.readline()
        try:
            a, b = line.split()
            a = float(a)
            b = float(b)
            r = b/a
            conc = 1.1*r**3-3.8*r**2+520*r+0.62
            self.x.append(time.time() - self.start)
            self.y.append(conc)

            self.plot1.set_xdata(self.x) # new data to plot
            self.plot1.set_ydata(self.y) # new data to plot
            self.plot2.set_xdata(self.x) # new data to plot
            self.plot2.set_ydata(self.y) # new data to plot


            xmax = max(self.x)
            pyplot.xlim(0, xmax*1.2)
            pyplot.draw() # redraw the graph

        except:
            pass
        return True



Livegraph()
