#!/usr/bin/python3 #trouvé sur https://stackoverflow.com/questions/48389470/python-update-matplotlib-from-threads import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np import threading import random import time import socket HOST = '127.0.0.1' # The server's hostname or IP address PORT = 30000 # The port used by the server class MyDataClass(): def __init__(self): self.XData = [0] self.YData = [0] #self.Y2Data = [0] class MyPlotClass(): def __init__(self, dataClass): self._dataClass = dataClass self.hLine, = plt.plot(0, 0) self.ani = FuncAnimation(plt.gcf(), self.run, interval = 30, repeat=True) #30 ms entre affichage def run(self, i): print("plotting data") self.hLine.set_data(self._dataClass.XData, self._dataClass.YData) self.hLine.axes.relim() self.hLine.axes.autoscale_view() class MyDataFetchClass(threading.Thread): def __init__(self, dataClass): threading.Thread.__init__(self) self._dataClass = dataClass self._period = 0.1 #durée d'attente entre lecture sur socket self._nextCall = time.time() # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.s: #todo gérer probleme de connexion self.s= socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((HOST, PORT)) def run(self): # while True: # print("updating data") # # add data to data class # self._dataClass.XData.append(self._dataClass.XData[-1] + 1) # self._dataClass.YData.append(random.randint(0, 256)) # # sleep until next execution # self._nextCall = self._nextCall + self._period; # time.sleep(self._nextCall - time.time()) while True: print("updating data") modeYT=True if modeYT: self.s.sendall(b'r 1 2 3') else: s.sendall(b'r 6 7 3') data = self.s.recv(1024) # print('Received', repr(data)) print(repr(data)) ti = time.time() listfields = data.split() if modeYT: self._dataClass.XData.append(self._dataClass.XData[-1] + 1) self._dataClass.YData.append(float(listfields[0])) # sleep until next execution self._nextCall = self._nextCall + self._period; time.sleep(self._nextCall - time.time()) #x.append(i) #y.append(float(listfields[0])) #y2.append(float(listfields[1])) # # else: # x.append(float(listfields[0])) # y.append(float(listfields[1])) #if ((float)(listfields[2])==1.0): # bouton pressé, on efface #x.clear() #y.clear() # il faudrait effacer la figure # i+=1 # y.append(psutil.cpu_percent()) # ax.plot(x,y,color='b') # if modeYT: # ax.plot(x, y2, color='r') # ax.set_xlim(left=max(0,i-50),right=i+50) # fig.canvas.draw() # time.sleep(0.01) # except KeyboardInterrupt: # print("bye") data = MyDataClass() plotter = MyPlotClass(data) fetcher = MyDataFetchClass(data) fetcher.start() plt.show() #fetcher.join()