import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
plt.gca().set_prop_cycle(color = ['red', 'blue', 'green', 'lightblue'])
plt.subplots_adjust(left = .05, right = .99, top =1, bottom =.05)
log_directory = './log_piNail.txt'
plt.xscale('linear')

def animate(i):
    pullData = open(log_directory, 'r')
    dataArray = pullData.readlines()
    temp_y = [ ]
    setpoint_y = [ ]
    output_y = [ ]
    relay_y = [ ]
    xar = [ ]
    c_del_index = 0

    ##print(len(dataArray))
    if len(dataArray) > 300: #only keep x lines in the log file
        f = open(log_directory, 'w+') #Create a new log file, overwritting the previous one
        f.close()
        
    for eachLine in dataArray[len(dataArray)-500: ]: #Only read the last x lines
        if len(eachLine) > 1:
            c_temp_y, c_setpoint_y, c_output_y, c_relay_y, c_xar= eachLine.split(', ')
            temp_y.append(float(c_temp_y))
            setpoint_y.append(float(c_setpoint_y))
            output_y.append(float(c_output_y))
            relay_y.append(int(c_relay_y))
            xar.append(float(c_xar))
            ax1.set_xlim([float(c_xar) - 500000 ,float(c_xar) + 2000])

    ax1.plot(xar, temp_y, linewidth = .2)
    ax1.plot(xar, setpoint_y, linewidth = .2)
    ax1.plot(xar, output_y, linewidth = .2)
    ax1.plot(xar, relay_y)
    
ani = animation.FuncAnimation(fig, animate, interval = 500)
plt.show()
            
