Python - Problemas hilos concurrentes GUI

 
Vista:
Imágen de perfil de Jose Manuel
Val: 30
Ha aumentado su posición en 224 puestos en Python (en relación al último mes)
Gráfica de Python

Problemas hilos concurrentes GUI

Publicado por Jose Manuel (11 intervenciones) el 13/03/2021 12:16:49
Buenos dias,

Estoy realizando un pequeño programa con una GUI. He implementado 2 hilos además del hilo principal. Un hilo se encarga de monitorizar en estado de las GPIO de la raspberry (mediante bucle while) y el otro hilo se encarga de activar graficamente un label y hacer sonar un buzzer (también mediante bucle while).
Cuando ejecuto los dos hilos de forma simultanea, el programa no identifica ningun error en el código, pero no funciona de forma correcta..
He probado a ejecutar los hilos de manera independiente y cada uno realiza las funciones para la que esta programado.

¿Podría ser que la raspberry (es la Pi 4 de 8gb) se quedase pequeña para la ejecucion de los dos hilos con los bucles while?

Gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de joel
Val: 3.475
Oro
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

Problemas hilos concurrentes GUI

Publicado por joel (901 intervenciones) el 13/03/2021 12:50:34
No, no, creo recordar que dispone de 4 nucleos esa PI... puedes ejecutarlo sin ningún problema.

faltaría ver el código para ver porque razón no se ejecutan.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Jose Manuel
Val: 30
Ha aumentado su posición en 224 puestos en Python (en relación al último mes)
Gráfica de Python

Problemas hilos concurrentes GUI

Publicado por Jose Manuel (11 intervenciones) el 13/03/2021 12:57:05
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# Version PRUEBAS HILOS for Python
 
######################################################## GALERIAS IMPORTADAS ########################################################
from tkinter import *
from tkinter import messagebox
import tkinter as tk
import time
from datetime import datetime, timedelta
import RPi.GPIO as GPIO
import os
import locale
import sched
import threading
from multiprocessing import Process
import sqlite3
import urllib.request
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
 
 
 
 
######################################################## ANULACIÓN DE "X" DE CERRADO DE VENTANAS ########################################################
def botonCerrarTotal():
	pass
 
 
 
######################################################## INTERFACE GENERAL ########################################################
raiz = Tk()
raiz.resizable(False,False)
raiz.geometry("1024x768")
raiz.attributes('-fullscreen', True)
raiz.protocol('WM_DELETE_WINDOW', botonCerrarTotal)
 
 
 
######################################################## FONDO DE PANTALLA PRINCIPAL ########################################################
FramePrincipal=Frame(raiz)
FramePrincipal.pack()
FramePrincipal.config(bg="black", width="1024", height="768")
 
 
 
######################################################## ETIQUETAS DE INFORMACIÓN ########################################################
FrameLetreroFalloAlimentacion=Frame(raiz)
FrameLetreroFalloAlimentacion.pack()
FrameLetreroFalloAlimentacion = tk.Label(raiz, text="    FALLO    \n    ALIMENTACION    ", bg="white", fg="black", relief="sunken", bd=2, font=('Tahoma', 10))
FrameLetreroFalloAlimentacion.place(x=6, y=380)
 
 
######################################################## BOTON REARME MANUAL ########################################################
STBotonRearmeManual = tk.BooleanVar()
STBotonRearmeManual.set(True)
 
def pulsacionBotonRearmeManual():
	if STBotonRearmeManual.get() == True:
		STBotonRearmeManual.set(True)
		STBotonParoManual.set(False)
		BotonRearmeManual.config(image=ImagenBotonRearmeManualPulsado)
		BotonParoManual.config(image=ImagenBotonParoManualSinPulsar)
	else:
		STBotonRearmeManual.set(True)
		STBotonParoManual.set(False)
		BotonRearmeManual.config(image=ImagenBotonRearmeManualPulsado)
		BotonParoManual.config(image=ImagenBotonParoManualSinPulsar)
		EventoBotonRearmeManual = datetime.now().strftime("%A, %d de %B de %Y a las %H:%M:%S")
		print("PULSADOR REARME MANUAL ACTIVADO " + time.strftime(EventoBotonRearmeManual))
 
BotonRearmeManual=Frame(raiz)
BotonRearmeManual.pack()
ImagenBotonRearmeManualDeshabilitado = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonRearmeManualHabilitado = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonRearmeManualSinPulsar = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonRearmeManualPulsado = PhotoImage (file = "BOTON_ON_VERDE.png")
BotonRearmeManual = tk.Button(raiz, image=ImagenBotonRearmeManualDeshabilitado, command=pulsacionBotonRearmeManual)
BotonRearmeManual.config(width="120", height="120")
BotonRearmeManual.place(x=279, y=394)
 
 
 
 
######################################################## BOTON PARO EMERGENCIA ########################################################
STBotonParoManual = tk.BooleanVar()
STBotonParoManual.set(False)
 
def pulsacionBotonParoManual():
	if STBotonParoManual.get() == False:
		STBotonRearmeManual.set(False)
		STBotonParoManual.set(True)
		BotonParoManual.config(image=ImagenBotonParoManualPulsado)
		BotonRearmeManual.config(image=ImagenBotonRearmeManualSinPulsar)
		EventoBotonParoManual = datetime.now().strftime("%A, %d de %B de %Y a las %H:%M:%S")
		print("PULSADOR PARO EMERGENCIA ACTIVADO " + time.strftime(EventoBotonParoManual))
	else:
		STBotonRearmeManual.set(False)
		STBotonParoManual.set(True)
		BotonParoManual.config(image=ImagenBotonParoManualPulsado)
		BotonRearmeManual.config(image=ImagenBotonRearmeManualSinPulsar)
 
BotonParoManual=Frame(raiz)
BotonParoManual.pack()
ImagenBotonParoManualDeshabilitado = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonParoManualHabilitado = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonParoManualSinPulsar = PhotoImage (file = "BOTON_ON_STANDBY.png")
ImagenBotonParoManualPulsado = PhotoImage (file = "BOTON_ON_ROJO.png")
BotonParoManual = tk.Button(raiz, image=ImagenBotonParoManualDeshabilitado, command=pulsacionBotonParoManual)
BotonParoManual.config(width="120", height="120")
BotonParoManual.place(x=536, y=350)
 
 
 
######################################################## CERRAR EL SISTEMA NEMESIS ########################################################
def salirSistema():
	raiz.destroy()
 
 
 
######################################################## CONFIGURACIÓN SISTEMA GPIO ########################################################
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
 
GPIO.setup(3, GPIO.OUT)                         # TESTIGO LUMINOSO - FALLO ALIMENTACION   +   REPORTE CRA - FALLO ALIMENTACION
GPIO.setup(5, GPIO.OUT)                         # TESTIGO LUMINOSO - FALLO DETECCION INCENDIO   +   REPORTE CRA - FALLO DETECCION INCENDIO
GPIO.setup(7, GPIO.OUT)                         # CONTROL - BUZZER
GPIO.setup(11, GPIO.OUT)                        # TESTIGO LUMINOSO - DETECCION INCENDIO   +   REPORTE CRA - DETECCION INCENDIO
GPIO.setup(13, GPIO.OUT)                        # TESTIGO LUMINOSO - EXTINTOR SURTIDORES   +   REPORTE CRA - EXTINTOR SURTIDORES
GPIO.setup(15, GPIO.OUT)                        # TESTIGO LUMINOSO - DETECTOR DE FUGAS TANQUE   +   REPORTE CRA - DETECTOR DE FUGAS
GPIO.setup(19, GPIO.OUT)                        # TESTIGO LUMINOSO - SISTEMA FUNCIONANDO
GPIO.setup(21, GPIO.OUT)                        # TESTIGO LUMINOSO - SISTEMA PARADO   +   REPORTE CRA - NOTIFICACION PARO SISTEMA
GPIO.setup(23, GPIO.OUT)                        #
GPIO.setup(29, GPIO.OUT)                        #
GPIO.setup(31, GPIO.OUT)                        #
GPIO.setup(33, GPIO.OUT)                        #
GPIO.setup(35, GPIO.OUT)                        # CONTROL - CORTE SUMINISTRO SURTIDORES
GPIO.setup(37, GPIO.OUT)                        # CONTROL - ANULACION ALIMENTACION BUZZER
GPIO.setup(8, GPIO.IN, GPIO.PUD_UP)             # CONTROL LOCAL - REARME SISTEMA (CUADRO)
GPIO.setup(10, GPIO.IN, GPIO.PUD_UP)            # CONTROL LOCAL - PARO EMERGENCIA SISTEMA (SETA)
GPIO.setup(12, GPIO.OUT)                        #
GPIO.setup(16, GPIO.OUT)                        #
GPIO.setup(18, GPIO.IN, GPIO.PUD_UP)            # MONITORIZACION INSTALACION - DETECTOR INCENDIO
GPIO.setup(22, GPIO.IN, GPIO.PUD_UP)            # MONITORIZACION INSTALACION - FALLO DETECTOR INCENDIO
GPIO.setup(24, GPIO.IN, GPIO.PUD_UP)            # MONITORIZACION INSTALACION - EXTINTOR SURTIDORES
GPIO.setup(26, GPIO.IN, GPIO.PUD_UP)            # MONITORIZACION INSTALACION - DETECTOR DE FUGAS TANQUE
GPIO.setup(32, GPIO.IN, GPIO.PUD_UP)            # MONITORIZACION INSTALACION - FALLO ALIMENTACION
GPIO.setup(36, GPIO.IN, GPIO.PUD_UP)            # CONTROL REMOTO - REARME SISTEMA
GPIO.setup(38, GPIO.IN, GPIO.PUD_UP)            # CONTROL REMOTO - PARO EMERGENCIA SISTEMA
GPIO.setup(40, GPIO.OUT)                        # CONTROL - ANULACION ALIMENTACION GPIO
 
 
 
######################################################## CONTROL SISTEMA GPIO ########################################################
 
 
# BUZZER ALARMAS Y LICENCIAS:
STBuzzerAlarmas = tk.BooleanVar()
STBuzzerAlarmas.set(False)
 
STBuzzerLicencias = tk.BooleanVar()
STBuzzerLicencias.set(False)
 
def LeerEstadoBuzzerAlarmas():
	STBuzzerAlarmas.get()
	print(STBuzzerAlarmas.get())
 
def LeerEstadoBuzzerLicencias():
	STBuzzerLicencias.get()
	print(STBuzzerLicencias.get())
 
def CambioEstadoBuzzer():
	while (True):
		if STBuzzerAlarmas.get() == False and STBuzzerLicencias.get() == False:
			while (STBuzzerAlarmas.get() == False and STBuzzerLicencias.get() == False):
				GPIO.output(7, GPIO.LOW)
				raiz.update()
 
		if STBuzzerAlarmas.get() == False and STBuzzerLicencias.get() == True:
			while (STBuzzerAlarmas.get() == False and STBuzzerLicencias.get() == True):
				GPIO.output(7, GPIO.HIGH)
				time.sleep(0.1)
				raiz.update()
				GPIO.output(7, GPIO.LOW)
				time.sleep(0.1)
				raiz.update()
				GPIO.output(7, GPIO.HIGH)
				time.sleep(0.1)
				raiz.update()
				GPIO.output(7, GPIO.LOW)
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
 
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
 
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
 
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
 
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
				time.sleep(0.2)
				if STBuzzerAlarmas.get() == True:
					break
				raiz.update()
 
		if STBuzzerAlarmas.get() == True and STBuzzerLicencias.get() == False:
			while (STBuzzerAlarmas.get() == True and STBuzzerLicencias.get() == False):
				GPIO.output(7, GPIO.HIGH)
				time.sleep(0.25)
				raiz.update()
				GPIO.output(7, GPIO.LOW)
				time.sleep(0.25)
				raiz.update()
		if STBuzzerAlarmas.get() == True and STBuzzerLicencias.get() == True:
			while (STBuzzerAlarmas.get() == True and STBuzzerLicencias.get() == True):
				GPIO.output(7, GPIO.HIGH)
				time.sleep(0.25)
				raiz.update()
				GPIO.output(7, GPIO.LOW)
				time.sleep(0.25)
				raiz.update()
 
def VerificacionParoEstadoBuzzerAlarmas():
	if STFalloAlimentacion.get() == True:
		pass
	else:
		ParoBuzzerAlarmas()
 
def ActivacionBuzzerAlarmas():
	lock.acquire()
	STBuzzerAlarmas.set(True)
	lock.release()
 
def ParoBuzzerAlarmas():
	lock.acquire()
	STBuzzerAlarmas.set(False)
	lock.release()
 
def ActivacionBuzzerLicencias():
	lock.acquire()
	STBuzzerLicencias.set(True)
	lock.release()
 
def ParoBuzzerLicencias():
	lock.acquire()
	STBuzzerLicencias.set(False)
	lock.release()
 
 
 
######################################################## ALARMA LUMINOSA FALLO ALIMENTACION ########################################################
STFalloAlimentacion = tk.BooleanVar()
STFalloAlimentacion.set(False)
 
def LeerEstadoFalloAlimentacion():
	STFalloAlimentacion.get()
	print(STFalloAlimentacion.get())
 
def ActivacionEstadoFalloAlimentacion():
	if (BotonRearmeManual["state"] and BotonParoManual["state"] == tk.DISABLED):
		pass
	else:
		EventoActivacionEstadoFalloAlimentacion = datetime.now().strftime("%A, %d de %B de %Y a las %H:%M:%S")
		if STFalloAlimentacion.get() == True:
			pass
		else:
			lock.acquire()
			STFalloAlimentacion.set(True)
			lock.release()
			print("FALLO DE SUMINISTRO ELECTRICO " + time.strftime(EventoActivacionEstadoFalloAlimentacion))
			ActivacionBuzzerAlarmas()
 
def ParoEstadoFalloAlimentacion():
	EventoParoEstadoFalloAlimentacion = datetime.now().strftime("%A, %d de %B de %Y a las %H:%M:%S")
	if STFalloAlimentacion.get() == False:
		pass
	else:
		lock.acquire()
		STFalloAlimentacion.set(False)
		lock.release()
		print("RESTABLECIMIENTO DE FALLO DE SUMINISTRO ELECTRICO " + time.strftime(EventoParoEstadoFalloAlimentacion))
		VerificacionParoEstadoBuzzerAlarmas()
 
def CambioEstadoFalloAlimentacion():
	if STFalloAlimentacion.get() == False:
		FrameLetreroFalloAlimentacion.config (bg="white")
		raiz.update()
	else:
		FrameLetreroFalloAlimentacion.config (bg="red")
		raiz.update()
 
 
 
# ACTIVACION / PARO SISTEMA GPIO:
def CambioEstadoInputGPIO():
	while (True):
		# CONTROL LOCAL - REARME SISTEMA (CUADRO)
		if GPIO.input(8) == False:         # ACTIVACION
			STBotonRearmeManual.set(True)
			pulsacionBotonRearmeManual()
 
		# CONTROL LOCAL - PARO EMERGENCIA (SETA)
		if GPIO.input(10) == False:        # ACTIVACION
			STBotonParoManual.set(False)
			pulsacionBotonParoManual()
 
		# CONTROL REMOTO - REARME SISTEMA
		if GPIO.input(36) == False:        # ACTIVACION
			pulsacionRearmeRemoto()
 
		# CONTROL REMOTO - PARO EMERGENCIA SISTEMA
		if GPIO.input(38) == False:        # ACTIVACION
			pulsacionParoRemoto()
 
		# MONITORIZACION INSTALACION - FALLO ALIMENTACION
		if GPIO.input(32) == False:        # ACTIVACION
			ActivacionEstadoFalloAlimentacion()
			CambioEstadoFalloAlimentacion()
			ActivacionBuzzerAlarmas()
		else:                              # DESACTIVACION
			ParoEstadoFalloAlimentacion()
			CambioEstadoFalloAlimentacion()
			VerificacionParoEstadoBuzzerAlarmas()
 
 
 
######################################################## CONFIGURACION HILOS DE PROCESOS ########################################################
lock = threading.Lock()
 
HiloBuzzer = threading.Thread(target=CambioEstadoBuzzer)
HiloBuzzer.start()
 
HiloInputGPIO = threading.Thread(target=CambioEstadoInputGPIO)
HiloInputGPIO.start()
 
def contadorHilosActivos():
	threading.active_count()
	print ("Hilos activos: " + str(threading.active_count()))
 
 
 
######################################################## BARRA DE MENÚ ########################################################
barraMenu=Menu(raiz)
raiz.config(menu=barraMenu)
 
sistemaMenu=Menu(barraMenu, tearoff=0)
sistemaMenu.add_command(label="Salir", command=salirSistema)
sistemaMenu.add_separator()
 
pruebaMenu=Menu(barraMenu, tearoff=0)
pruebaMenu.add_command(label="Activar Buzzer Alarmas", command=ActivacionBuzzerAlarmas)
pruebaMenu.add_separator()
pruebaMenu.add_command(label="Silenciar Buzzer Alarmas", command=VerificacionParoEstadoBuzzerAlarmas)
pruebaMenu.add_separator()
pruebaMenu.add_command(label="Activar Buzzer Licencias", command=ActivacionBuzzerLicencias)
pruebaMenu.add_separator()
pruebaMenu.add_command(label="Silenciar Buzzer Licencias", command=ParoBuzzerLicencias)
pruebaMenu.add_separator()
pruebaMenu.add_command(label="Activar Fallo Alimentación", command=lambda:[ActivacionEstadoFalloAlimentacion(), CambioEstadoFalloAlimentacion()])
pruebaMenu.add_separator()
pruebaMenu.add_command(label="Parar Fallo Alimentación", command=lambda:[ParoEstadoFalloAlimentacion(), CambioEstadoFalloAlimentacion()])
pruebaMenu.add_separator()
 
programacionMenu=Menu(barraMenu, tearoff=0)
programacionMenu.add_separator()
programacionMenu.add_command(label="Contador Hilos Activos", command=contadorHilosActivos)
 
barraMenu.add_cascade(label="Sistema", menu=sistemaMenu)
barraMenu.add_cascade(label="Prueba de Sistema", menu=pruebaMenu)
barraMenu.add_cascade(label="Programacion", menu=programacionMenu)
 
 
 
raiz.protocol("WM_DELETE_WINDOW", salirSistema)
raiz.mainloop()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar