Communication entre Blender et Qt5 (point d'étape)

This commit is contained in:
Philippe Roy 2023-01-16 07:48:01 +01:00
parent 298337663b
commit 618c8250b8
6 changed files with 84 additions and 134 deletions

View File

@ -51,7 +51,8 @@ def commandes():
# mot_f(False) # mot_f(False)
# gyr(False) # gyr(False)
plot(['gyr']) # plot(['gyr'])
plot(['bp_ext'])
# plot(['gyr', 'bp_ext', 'bp_int']) # plot(['gyr', 'bp_ext', 'bp_int'])
while True: while True:
gyr(True) gyr(True)

View File

@ -2,6 +2,7 @@ import bge # Bibliothèque Blender Game Engine (UPBGE)
import subprocess # Multiprocessus import subprocess # Multiprocessus
from twin_threading import thread_cmd_start, thread_cmd_stop, thread_cmd_end # Multithreading (multitâches) from twin_threading import thread_cmd_start, thread_cmd_stop, thread_cmd_end # Multithreading (multitâches)
from twin_serial import jumeau, jumeau_stop, serial_close # Liaison série from twin_serial import jumeau, jumeau_stop, serial_close # Liaison série
from twin_plot import plot # Visualisation des données
import os import os
import sys import sys
import time import time
@ -123,57 +124,3 @@ def fin():
def quit(): def quit():
end() end()
###############################################################################
# Visualisation des données
###############################################################################
# Lancement du grapheur
def plot(data):
# subprocess.run([sys.executable, os.path.join(os.getcwd(), "twin_plot.py")], , stdin=subprocess.PIPE) # Process bloquant
# Terminer le processus précédent
if scene.objects['System']['plot_proc'] is not None:
if scene.objects['System']['plot_proc'].poll()==None:
scene.objects['System']['plot_proc'].terminate()
scene.objects['System']['plot_draw'] = True
scene.objects['System']['plot_time'] = 0
scene.objects['System']['plot_data'] = data # FIXME : conversion mémonique -> 3D
scene.objects['System']['plot_proc'] = subprocess.Popen([sys.executable, os.path.join(os.getcwd(), "twin_plot.py")], stdin=subprocess.PIPE, encoding = 'utf8')
scene.objects['System']['plot']=True
# Communication avec Qt5
def plot_maj(cont):
if cont.sensors['Plot'].positive :
# Affichage du graphique
if scene.objects['System']['plot_draw']:
# Préparation du message
# FIXME : ajouter les valeurs réelles et valeurs numériques ('activated_real')
msg=str(scene.objects['System']['plot_time'])
for obj in scene.objects['System']['plot_data']:
if scene.objects[obj]['activated']:
msg = msg+",1"
else:
msg = msg+",0"
msg = msg+"\n"
# Envoi (Pipe)
if scene.objects['System']['plot_proc'].poll()==None:
# scene.objects['System']['plot_proc'].communicate(input=time_send.encode())[0] # Communication bloquante
scene.objects['System']['plot_proc'].stdin.write(msg)
else:
print ("Stop")
scene.objects['System']['plot']=False
scene.objects['System']['plot_draw'] =False
scene.objects['System']['plot_proc'].terminate()
# Arret de l'affichage du graphique
else :
if scene.objects['System']['plot_proc'].poll()==None:
pass
else:
print ("Stop")
scene.objects['System']['plot']=False
scene.objects['System']['plot_draw'] =False
scene.objects['System']['plot_proc'].terminate()

View File

@ -1,7 +1,7 @@
<data> <data>
<screen> <screen>
<width>1609</width> <width>1039</width>
<height>905</height> <height>585</height>
<quality>1</quality> <quality>1</quality>
</screen> </screen>
</data> </data>

View File

@ -1,10 +1,9 @@
import bge # Bibliothèque Blender Game Engine (UPBGE)
import os
import sys import sys
import random import importlib
import matplotlib import subprocess # Multiprocessus
matplotlib.use('Qt5Agg') import time
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
############################################################################### ###############################################################################
# twin_plot.py # twin_plot.py
@ -17,83 +16,84 @@ from matplotlib.figure import Figure
############################################################################### ###############################################################################
# UPBGE scene # UPBGE scene
# scene = bge.logic.getCurrentScene() scene = bge.logic.getCurrentScene()
# Récupérer le brochage du jumeau réel # Récupérer la configuration du graphique
# system=importlib.import_module(scene.objects['Doc']['system']) # Système system=importlib.import_module(scene.objects['Doc']['system']) # Système
# pin_config = system.get_pin_config() plot_config = system.get_pin_config()
############################################################################### ###############################################################################
# Fenêtre dynamique # Création du graphique
############################################################################### ###############################################################################
class MplCanvas(FigureCanvasQTAgg): def plot(data):
# subprocess.run([sys.executable, os.path.join(os.getcwd(), "twin_plot.py")], , stdin=subprocess.PIPE) # Process bloquant
def __init__(self, parent=None, width=5, height=4, dpi=100): # pin_config = {
fig = Figure(figsize=(width, height), dpi=dpi) # 'bp_ext' : [['d','i'],['Bp cote rue','pin'],['o','-', 'blue', 1]],
self.subplot = fig.add_subplot(111) # 'bp_int' : [['d','i'],['Bp cote cour','pin'],['o','-', 'darkblue', 1]],
super(MplCanvas, self).__init__(fig) # 'fdc_o' : [['d','i'],['Microrupteur fdc ouvert','pin'],['o','-', 'violet', 1]],
# 'fdc_f' : [['d','i'],['Microrupteur fdc ferme','pin'],['o','-', 'darkviolet', 1]],
# 'mot_o' : [['d','o'],['Moteur','pin_o'],['o','-', 'green', 1]],
# 'mot_f' : [['d','o'],['Moteur','pin_f'],['o','-', 'darkgreen', 1]],
# 'gyr' : [['d','o'],['Led','pin'],['o','-', 'orange', 1]],
# 'ir_emet' : [['d','o'],['Emetteur IR','pin'],['o','-', 'red', 1]],
# 'ir_recep' : [['d','i'],['Recepteur IR','pin'],['o','-', 'darkred', 1]]}
class MainWindow(QtWidgets.QMainWindow): # Terminer le processus précédent
if scene.objects['System']['plot_proc'] is not None:
if scene.objects['System']['plot_proc'].poll()==None:
scene.objects['System']['plot_proc'].terminate()
scene.objects['System']['plot_draw'] = True
scene.objects['System']['plot_time'] = 0
# Création du graphique # Configuration des données
def __init__(self, *args, **kwargs): scene.objects['System']['plot_data'] =[]
super(MainWindow, self).__init__(*args, **kwargs) for obj in data:
self.canvas = MplCanvas(self, width=5, height=4, dpi=100) scene.objects['System']['plot_data'].append(plot_config[obj][1][0])
self.setCentralWidget(self.canvas)
n_data = 50
# self.xdata = list(range(n_data))
# self.ydata = [random.randint(0, 10) for i in range(n_data)]
self.xdata = [0]
self.ydata = [0]
self.update_plot()
self.show()
# Timer pour le update_plot # Démarrer le processus
fps = 60 scene.objects['System']['plot_proc'] = subprocess.Popen([sys.executable, os.path.join(os.getcwd(), "twin_plot_qt.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding = 'utf8')
self.timer = QtCore.QTimer() stout, sterr = scene.objects['System']['plot_proc'].communicate() # FIXME : attente du message retour pour lancer l'acquisition
self.timer.setInterval(1000/fps) scene.objects['System']['plot']=True
self.timer.timeout.connect(self.update_plot)
self.timer.start()
# Lecture des données et mise à jour du graphique
def update_plot(self):
plt = self.canvas.subplot
# Données
# donnees = ([0,1,2,3,4], [10,1,20,3,40])
# print (self.xdata[len(self.xdata)-1]+1)
# new_x=self.xdata[len(self.xdata)-1]+1
# self.xdata.append(new_x)
# self.ydata.append(random.randint(0, 10))
# Lecture du Pipe
for line in sys.stdin:
msg = line.rstrip()
break
# X et Y
# FIXME : temps et une valeur
msg_list=msg.split(',')
print('Output:', msg, msg_list)
self.xdata = self.xdata + [float(msg_list[0])]
self.ydata = self.ydata + [float(msg_list[1])]
# self.ydata = self.ydata + [random.randint(0, 10)]
# Drop off the first y element, append a new one.
# self.ydata = self.ydata[1:] + [random.randint(0, 10)]
# Redraw
plt.cla()
plt.plot(self.xdata, self.ydata, 'r')
self.canvas.draw()
############################################################################### ###############################################################################
# Application # Mise à jour du graphique
############################################################################### ###############################################################################
app = QtWidgets.QApplication(sys.argv) def plot_maj(cont):
w = MainWindow() if cont.sensors['Plot'].positive :
app.exec_()
# Affichage du graphique
if scene.objects['System']['plot_draw']:
# Préparation du message
# FIXME : ajouter les valeurs réelles et valeurs numériques ('activated_real')
# msg=str(round(scene.objects['System']['plot_time'], 2))
msg=format(scene.objects['System']['plot_time'],".2f")
for obj in scene.objects['System']['plot_data']:
if scene.objects[obj]['activated']:
msg = msg+",1"
else:
msg = msg+",0"
msg = msg+"\n"
# Envoi (Pipe)
if scene.objects['System']['plot_proc'].poll()==None:
# scene.objects['System']['plot_proc'].communicate(input=time_send.encode())[0] # Communication bloquante
scene.objects['System']['plot_proc'].stdin.write(msg)
else:
print ("Stop")
scene.objects['System']['plot']=False
scene.objects['System']['plot_draw'] =False
scene.objects['System']['plot_proc'].terminate()
# Arret de l'affichage du graphique
else :
if scene.objects['System']['plot_proc'].poll()==None:
pass
else:
print ("Stop")
scene.objects['System']['plot']=False
scene.objects['System']['plot_draw'] =False
scene.objects['System']['plot_proc'].terminate()

View File

@ -70,6 +70,7 @@ class MainWindow(QtWidgets.QMainWindow):
# self.ydata.append(random.randint(0, 10)) # self.ydata.append(random.randint(0, 10))
# Lecture du Pipe # Lecture du Pipe
msg=""
for line in sys.stdin: for line in sys.stdin:
msg = line.rstrip() msg = line.rstrip()
break break
@ -77,7 +78,8 @@ class MainWindow(QtWidgets.QMainWindow):
# X et Y # X et Y
# FIXME : temps et une valeur # FIXME : temps et une valeur
msg_list=msg.split(',') msg_list=msg.split(',')
print('Output:', msg, msg_list) print(msg_list)
if msg_list[0] != "":
self.xdata = self.xdata + [float(msg_list[0])] self.xdata = self.xdata + [float(msg_list[0])]
self.ydata = self.ydata + [float(msg_list[1])] self.ydata = self.ydata + [float(msg_list[1])]