-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreatemsg.py
More file actions
151 lines (118 loc) · 5.16 KB
/
createmsg.py
File metadata and controls
151 lines (118 loc) · 5.16 KB
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
# createmsg.py
import sys
import signal
from PySide6.QtCore import QCoreApplication, Slot, QThread, QMutex, Signal
from queue import Queue,Empty
import logging
import json
from pathlib import Path
# Importe o novo RideState
from ride_state import RideState
from comm_protocol import (
FileManagerMsg, FileMngMsgId, RideDataMsg,
ProcessedDataMsg, TelemetryOrigin, TelemetryMsg
)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class MsgCreatorThread(QThread):
update_ui = Signal(TelemetryMsg) # Sinal para atualizar a UI com dados processados
def __init__(self,
app,
ride_state: RideState, # <-- MUDANÇA: Recebe o estado
AddRideDataQueue=Queue,
SendDataQueue=Queue,
CreateMsgQueue=Queue,
parent=None):
super().__init__(parent)
self.is_running = False
self.ride_state = ride_state
self.AddRideDataQueue = AddRideDataQueue
self.SendDataQueue = SendDataQueue
self.CreateMsgQueue = CreateMsgQueue
self.app = app
self.msg = TelemetryMsg(info=None, gps=None, crank=None)
self.setObjectName("MsgCreatorThread")
self.app.aboutToQuit.connect(self.stop)
def start(self):
if self.is_running:
logging.warning("Thread MsgCreator já está em execução.")
return
self.is_running = True
super().start()
logging.info("Thread MsgCreator iniciada.")
@Slot()
def stop(self):
if not self.is_running:
return
logging.warning("Parando a thread MsgCreator...")
self.is_running = False
self.quit()
if not self.wait(5000):
logging.error("Thread MsgCreator não respondeu. Forçando finalização.")
self.terminate()
else:
logging.info("Thread MsgCreator finalizada com sucesso.")
def run(self):
while self.is_running:
try:
data = self.CreateMsgQueue.get(timeout=1) # Adicionado timeout
origem = data.data_origin
#logging.info(f"[Create Message]Mensagem recebida de CreateMsgQueue: {data.data_origin} ")
#print("\n\n\n")
match origem:
case TelemetryOrigin.GPS:
self.gps_data(data)
case TelemetryOrigin.CRANK:
self.crank_data(data)
case _:
logging.warning(f"Comando desconhecido recebido: {data}")
except Empty: # Captura o timeout
if not self.is_running:
break # Sai do loop se a thread foi parada
continue # Continua o loop se apenas estiver vazio
except Exception as e:
logging.error(f"Erro na thread createmessage: {e}")
def gps_data(self,data):
try:
self.msg.gps = data.data
self.msg.info = data.info
if self.ride_state.is_riding():
return
self.msg.crank = None
msg_to_send = TelemetryMsg(
info=self.msg.info,
gps=self.msg.gps,
crank=self.msg.crank
)
self.update_ui.emit(msg_to_send) #Update UI even if not riding
logging.debug("[MsgCreator] GPS data emitted to UI: %s", msg_to_send)
except Exception as e:
logging.error(f"Erro em GPS data: {e}")
def crank_data(self, data: ProcessedDataMsg):
try:
if data.data is None:
logging.warning("[MsgCreator] ProcessedDataMsg from Crank, but no data is available")
return
self.msg.crank = data.data
if self.msg.gps is not None and self.msg.crank is not None:
# --- MUDANÇA: Verifica o estado centralizado ---
if self.ride_state.is_riding():
logging.info("Dados de GPS e Crank recebidos (Corrida ATIVA). Montando e enviando mensagem.")
#print("\n\n\n\n\n\n\n")
msg_to_send = TelemetryMsg(
info=self.msg.info,
gps=self.msg.gps,
crank=self.msg.crank
)
logging.debug("[MsgCreator] TelemetryMsg sent to RideThread and UI: %s", msg_to_send)
self.AddRideDataQueue.put(msg_to_send)
self.update_ui.emit(msg_to_send)
# Limpa apenas depois de enviar com sucesso
self.msg.gps = None
self.msg.info = None
self.msg.crank = None
else:
logging.warning("[MsgCreator] TelemetryMsg data is not None, but the state is not riding. No data sent to UI and RideThread")
else:
logging.warning("[MsgCreator] Could not create TelemetryData. Current Msg is None")
except Exception as e:
logging.info(f"Erro no cranck: {e}")