import matplotlib.pyplot as plt import matplotlib.animation as animation import math import requests import datetime as dt # Persist HTTP connection (reduce requests/second). session = requests.Session() # Parameters x_length = 600 # No. of readings show at one time. y_range = [-80, 65] # Light reading range. # Figure/Graph Details fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ys1 = [0] * x_length ys2 = [0] * x_length ax.set_ylim(y_range) line1, = ax.plot(ys1, label='factory1 (Andy)') line2, = ax.plot(ys2, label='factory2 (Tony)') plt.title("Personal Flash in Real-Time -- Light Meter Readings in Ritherdon") plt.xlabel("<--- Oldest (Time) Latest --->") plt.ylabel("Light") plt.legend(loc='lower left') ax.set_xticklabels(()) ax.grid(b=True, linestyle='dashdot', which='major', color='grey', linewidth=0.5) # Minor grid marks -- uncomment to display # ax.grid(b=True, linestyle='dashdot', which='minor', color='grey', linewidth=0.5) # plt.minorticks_on() # Updates the line chart for factory1 def animate1(i, ys): try: f1_request = session.get( "http://ritherdon.abbether.net/api/readings/latest/1", timeout=5) f1_data = f1_request.json() f1_reading = f1_data.get("reading") ys.append(f1_reading) ys = ys1[-x_length:] line1.set_ydata(ys) except requests.exceptions.ConnectionError: pause = 60 time.sleep(60) print( f"[WARNING] MAX. REQUESTS EXCEEDED: Pausing requests for {pause} seconds...") pass except requests.exceptions.Timeout: t_stamp = datetime.datetime.now() print(f"[WARNING] TIMEOUT EXCEPTION: Request timed-out at {t_stamp}.") time.sleep(60) pass except Exception as e: print(f"[ERROR] GENERAL EXCEPTION: {e}") finally: return line1, # Updates the line chart for factory2 def animate2(i, ys): try: f2_request = session.get( "http://ritherdon.abbether.net/api/readings/latest/2", timeout=5) f2_data = f2_request.json() f2_reading = f2_data.get("reading") ys.append(f2_reading) ys = ys2[-x_length:] line2.set_ydata(ys) except requests.exceptions.ConnectionError: pause = 60 time.sleep(60) print( f"[WARNING] MAX. REQUESTS EXCEEDED: Pausing requests for {pause} seconds...") pass except requests.exceptions.Timeout: t_stamp = datetime.datetime.now() print(f"[WARNING] TIMEOUT EXCEPTION: Request timed-out at {t_stamp}.") time.sleep(60) pass except Exception as e: print(f"[ERROR] GENERAL EXCEPTION: {e}") finally: return line2, # Starts the animations and shows the graph (I.E. 'main') ani1 = animation.FuncAnimation( fig, animate1, fargs=(ys1,), interval=100, blit=False) ani2 = animation.FuncAnimation( fig, animate2, fargs=(ys2,), interval=100, blit=False) plt.show()