# -*- coding: utf-8 -*-
"""
Created on Thu Jun 28 16:20:14 2018

@author: Mej
"""



import numpy as np
import matplotlib.pyplot as plt

import serial  # http://pyserial.readthedocs.io/en/latest/pyserial.html & https://gist.github.com/matdombrock/fb4833cb3b288a3530eb9a03e3550ecf
from time import sleep


#Prepare graph output
#######################################################

buff = 256 #size of the buffer to plot (data will overwritte itself at this period)
time = [] #timing of the lines
temp = np.zeros((buff,4,2)) #Temperatures of each line: 4 temperatures (4 columns) x 2 devices (2 of depth)
temp[:]=np.nan

fig=plt.figure(0)
plt.clf()
plt.suptitle("PYserial monitoring & Matplotlib display by Mej")
ax = fig.subplots(1, 1)
ax.set_xlabel("time [s]")
#ax.set_xlim(0, buff)
ax.set_ylabel("temps [°C]")
ax.set_ylim(20, 100)
ax.hold(True)
ax.grid(True)
plt.draw()
plt.pause(0.2)

#Connection to serial
#######################################################

COM = "COM18"
BAUD = 115200
ser = serial.Serial(COM, BAUD, timeout = 0.2) #100ms timeout

#Listen
print("Waiting for device with BAUD"+str(BAUD)+"...");
sleep(1) #1s
print("\t There is one on ", end='');
print(ser.name)


#sleep(1) #1s
#ser = serial.Serial(COM, BAUD, timeout = 0.1) #100ms timeout
#ser.open()




#Monitoring loop
#######################################################
loop_cnt = -1 #Python starts numerotation at 0
#while loop_cnt<128:
while True:
    loop_cnt = loop_cnt+1
    
    #Read serial
    line = str(ser.readline().decode().strip('\n'))#Capture serial output as a full line string
    
    #Print serial line on console
    if line=="":
        print("!Timeout!")
    elif len(line)>100: #check that line has the writte size, else, ignore it:
        print(line)
        #extract data from this template:
        # MCP9904 0x4C T[°C]=  33.0  39.0 33.2 33.0       MCP9904 0x1C T[°C]=  32.6  0.0 32.6 0.0 t[s]= 1467.493   t_loop[ms]= 9    
        ind = 0
########loop on devices
        for j in range(2): 
            c = line[ind]
            #go after the next "=" signe
            while c!="=":
                ind=ind+1
                c = line[ind]
#            print("'=' on ind="+str(ind))
            ind=ind+1
############loop on channels per device
            for i in range(4): 
                c = line[ind]
                #go after the last space signe
                while c==' ':
                    ind=ind+1
                    c = line[ind]
                data=float(line[ind:(ind+4)])
#                print("ind="+str(ind)+"\t",end='')
#                print(data)
                temp[len(time)%buff,i,j]=data
                ind=ind+4
############get the time
        c = line[ind]
        #go after the next "=" signe
        while c!="=":
            ind=ind+1
            c = line[ind]
#        print("'=' on ind="+str(ind))
        ind=ind+1
        #go after the last space signe
        while c==' ':
            ind=ind+1
            c = line[ind]
        data=float(line[ind:(ind+6)])
#        print("ind="+str(ind)+"\t",end='')
#        print(data)
        time.append(data) #time
    else:
        print("len(line)= "+str(len(line))+"<100")
        
    #Plot data
#    x=np.arange(buff)
    x=np.array(time)
    if len(x>0):
        x=x-x[0] #reset time
    ax.plot(x,temp[0:len(x),0,0], '.-k')
    ax.plot(x,temp[0:len(x),1,0], '.-r')
    ax.plot(x,temp[0:len(x),2,0], '.-g')
    ax.plot(x,temp[0:len(x),3,0], '.-b')
    ax.plot(x,temp[0:len(x),0,1], '--k')
    ax.plot(x,temp[0:len(x),1,1], '--r')
    ax.plot(x,temp[0:len(x),2,1], '--g')
    ax.plot(x,temp[0:len(x),3,1], '--b')
    plt.pause(0.2)

plt.draw()
plt.show()
   