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)
# gyr(False)
plot(['gyr'])
# plot(['gyr'])
plot(['bp_ext'])
# plot(['gyr', 'bp_ext', 'bp_int'])
while True:
gyr(True)

View File

@ -2,6 +2,7 @@ import bge # Bibliothèque Blender Game Engine (UPBGE)
import subprocess # Multiprocessus
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_plot import plot # Visualisation des données
import os
import sys
import time
@ -122,58 +123,4 @@ def fin():
def quit():
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>
<screen>
<width>1609</width>
<height>905</height>
<width>1039</width>
<height>585</height>
<quality>1</quality>
</screen>
</data>

View File

@ -1,10 +1,9 @@
import bge # Bibliothèque Blender Game Engine (UPBGE)
import os
import sys
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import importlib
import subprocess # Multiprocessus
import time
###############################################################################
# twin_plot.py
@ -17,83 +16,84 @@ from matplotlib.figure import Figure
###############################################################################
# UPBGE scene
# scene = bge.logic.getCurrentScene()
scene = bge.logic.getCurrentScene()
# Récupérer le brochage du jumeau réel
# system=importlib.import_module(scene.objects['Doc']['system']) # Système
# pin_config = system.get_pin_config()
# Récupérer la configuration du graphique
system=importlib.import_module(scene.objects['Doc']['system']) # Système
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):
fig = Figure(figsize=(width, height), dpi=dpi)
self.subplot = fig.add_subplot(111)
super(MplCanvas, self).__init__(fig)
# pin_config = {
# 'bp_ext' : [['d','i'],['Bp cote rue','pin'],['o','-', 'blue', 1]],
# 'bp_int' : [['d','i'],['Bp cote cour','pin'],['o','-', 'darkblue', 1]],
# '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
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.canvas = MplCanvas(self, width=5, height=4, dpi=100)
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()
# Configuration des données
scene.objects['System']['plot_data'] =[]
for obj in data:
scene.objects['System']['plot_data'].append(plot_config[obj][1][0])
# Timer pour le update_plot
fps = 60
self.timer = QtCore.QTimer()
self.timer.setInterval(1000/fps)
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()
# Démarrer le processus
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')
stout, sterr = scene.objects['System']['plot_proc'].communicate() # FIXME : attente du message retour pour lancer l'acquisition
scene.objects['System']['plot']=True
###############################################################################
# Application
# Mise à jour du graphique
###############################################################################
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
app.exec_()
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(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))
# Lecture du Pipe
msg=""
for line in sys.stdin:
msg = line.rstrip()
break
@ -77,9 +78,10 @@ class MainWindow(QtWidgets.QMainWindow):
# 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])]
print(msg_list)
if msg_list[0] != "":
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.