55import time
66import threading
77
8+
9+ #Definição dos estados e eventos do sistema
810statesNum = 5
911eventsNum = 7
1012
2325 "RESUME" :5 ,
2426 "STOP" :6 }
2527
28+
29+ #Criação da matriz de transição da máquina de estados
2630transitionMatrix = [[j for i in range (eventsNum )] for j in range (statesNum )]
2731
2832transitionMatrix [states ["WAITING_TRAJ" ]][events ["TRAJ_LOADED" ]] = states ["WAITING_ORIGIN" ]
3337transitionMatrix [states ["PAUSED" ]][events ["RESUME" ]] = states ["RUNNING" ]
3438transitionMatrix [states ["PAUSED" ]][events ["STOP" ]] = states ["NOT_RUNNING" ]
3539
40+ #Habilitação dos botões para cada estado
3641buttonStates = [[] for _ in range (statesNum )]
3742
3843buttonStates [states ["WAITING_TRAJ" ]]= [ctk .DISABLED , ctk .DISABLED , ctk .DISABLED , ctk .DISABLED , ctk .DISABLED , ctk .NORMAL , ctk .NORMAL ]
4954global linhaAtual
5055linhaAtual = 0
5156
57+
58+ #Função de processamento das respostas seriais: gera eventos, realiza a transição de estados e altera a interface
5259def processResponse (response ):
5360 global state
5461 global linhaAtual
@@ -85,6 +92,7 @@ def processResponse(response):
8592
8693 buttons = buttonStates [state ]
8794
95+ #Atualização dos botões
8896 start_button .configure (state = buttons [0 ])
8997 pause_button .configure (state = buttons [1 ])
9098 resume_button .configure (state = buttons [2 ])
@@ -93,17 +101,18 @@ def processResponse(response):
93101 file_button .configure (state = buttons [5 ])
94102 params_button .configure (state = buttons [6 ])
95103
96-
104+ #Cálculo do LRC da comunicação MODBUS
97105def calculate_lrc (data ):
98106 lrc = 0
99107 for byte in data :
100- lrc = (lrc + byte ) & 0xFF # Sum the bytes and keep only the least significant byte
108+ lrc = (lrc + byte ) & 0xFF
101109 lrc -= 0x3A
102- lrc = ((lrc ^ 0xFF ) + 1 ) & 0xFF # Two's complement
110+ lrc = ((lrc ^ 0xFF ) + 1 ) & 0xFF
103111
104112 lrc_string = hex (lrc )[2 :]
105113 return lrc_string
106114
115+ #Inicialização do canal serial
107116def init_serial ():
108117 global ser
109118 ports = list (serial .tools .list_ports .comports ())
@@ -125,106 +134,96 @@ def init_serial():
125134 else :
126135 print ("COM7 is not available" )
127136
137+
138+ #Função de envio de comandos simples
128139def send_command (command ):
129140 global ser
130141 global blockFlag
131142
132-
133- blockFlag = True
134- ser .write (command )
143+ blockFlag = True #Bloqueia o serial enquanto envia
144+ ser .write (command ) #Envia o comando
135145 print ("Sent to COM7 ->" , command )
136-
137- # Optionally, read the response from the device (if needed)
138- response = ser .read (16 ) # Adjust the number of bytes to read as needed
139- blockFlag = False
140- processResponse (response )
146+ response = ser .read (16 ) #Lê a resposta
147+ blockFlag = False #Libera o serial
148+ processResponse (response ) #Processa a mensagem recebida
141149 if response :
142150 print ("Received response:" , response )
143151
144152
145153
146154
147-
155+ #Envio da string de trajetória completa
148156def send_trajectory ():
157+ #Utiliza o parseGCode para gerar a string de trajetória a ser enviada
149158 file , pointsNumber , trajectoryString = parseGCode ()
150159 pointsNumber = "{:02X}" .format (pointsNumber )
151160 global ser
152- # Send the data
153- message = b':0115'
154- message += pointsNumber .encode ()
155- message += trajectoryString .encode ()
156- message += calculate_lrc (message ).encode ()
157- message += b'\x0D \x0A '
158- ser .write (message )
159- print (message )
160-
161161
162- # Optionally, read the response from the device (if needed)
162+ message = b':0115' #Enderço e código da função 21 = 0x15
163+ message += pointsNumber .encode () #Número de pontos enviado
164+ message += trajectoryString .encode () #String de pontos que compõe a trajetória
165+ message += calculate_lrc (message ).encode () #LRC para a mensagem
166+ message += b'\x0D \x0A ' #Terminadores
167+ ser .write (message ) #Envia a mensagem
163168 time .sleep (3 )
164- response = ser .read (100 ) # Adjust the number of bytes to read as needed
165-
166- processResponse (response )
169+ response = ser .read (100 )
170+ processResponse (response ) #Processa a resposta
167171
168172 if response :
169173 print ("Received response:" , response )
170- textbox .delete ("0.0" , "end" ) # delete all text
174+ #Atualiza o texto no campo de código de G da interface
175+ textbox .delete ("0.0" , "end" )
171176 lineNumber = 0
172177 for line in file :
173178 textbox .insert (f"{ lineNumber } .0" , line )
174179 lineNumber += 1
175180 textbox .tag_remove ("highlight" , "0.0" , "end" )
176181
182+ #Envio dos parâmetros de controle
177183def send_params ():
178184 global ser
179- # Send the data
180- message = b':010806'
185+ message = b':010806' #Endereço, código da função de número de parâmetros
186+ #Inclusão dos 6 parâmetros de controle
181187 message += ("{:04.1f}" .format (float (kpA .get ("0.0" , "end" )))).encode ()
182188 message += ("{:04.1f}" .format (float (kiA .get ("0.0" , "end" )))).encode ()
183189 message += ("{:04.1f}" .format (float (kdA .get ("0.0" , "end" )))).encode ()
184190 message += ("{:04.1f}" .format (float (kpB .get ("0.0" , "end" )))).encode ()
185191 message += ("{:04.1f}" .format (float (kiB .get ("0.0" , "end" )))).encode ()
186192 message += ("{:04.1f}" .format (float (kdB .get ("0.0" , "end" )))).encode ()
187- message += calculate_lrc (message ).encode ()
188- message += b'\x0D \x0A '
193+ message += calculate_lrc (message ).encode () #Cálculo do LRC
194+ message += b'\x0D \x0A ' #Terminadores
189195 ser .write (message )
190196 print (message )
191-
192-
193- # Optionally, read the response from the device (if needed)
194197 time .sleep (1 )
195- response = ser .read (100 ) # Adjust the number of bytes to read as needed
196-
197- #processResponse(response)
198-
198+ response = ser .read (100 )
199+ processResponse (response )
199200 if response :
200201 print ("Received response:" , response )
201202
202203
203-
204+ #Leitura da linha sendo executada
204205def request_currLine ():
205- # Send the data
206206 global ser
207207 global linhaAtual
208208 global blockFlag
209209
210210 if (not blockFlag ):
211- ser .write (b':0103000379' + b'\x0D \x0A ' )
212- response = ser .read (14 ) # Adjust the number of bytes to read as needed
211+ ser .write (b':0103000379' + b'\x0D \x0A ' ) #Código para a função de ler REG_LINHA
212+ response = ser .read (14 )
213213 processResponse (response )
214214 if response :
215215 print ("Current line:" , linhaAtual )
216216
217217
218218
219219
220- # Initialize the CustomTkinter application
220+ #Inicialização da Interface Gráfica
221221app = ctk .CTk ()
222222app .geometry ("720x500" )
223223app .title ("COM7 Sender" )
224224ctk .set_appearance_mode ("dark" )
225225
226-
227-
226+ #Definição dos botões
228227start_button = ctk .CTkButton (app , text = "INICIAR" , command = lambda :send_command (b':0106000178' + b'\x0D \x0A ' ))
229228start_button .grid (row = 1 , column = 0 , pady = 10 , padx = 10 )
230229pause_button = ctk .CTkButton (app , text = "PAUSAR" , command = lambda :send_command (b':0106010177' + b'\x0D \x0A ' ))
@@ -240,8 +239,8 @@ def request_currLine():
240239params_button = ctk .CTkButton (app , text = "ENVIAR PARÂMETROS" , command = send_params )
241240params_button .grid (row = 5 , column = 2 ,columnspan = 3 , pady = 10 , padx = 10 )
242241
242+ #Atribuição do estado inicial aos botões
243243buttons = buttonStates [state ]
244-
245244start_button .configure (state = buttons [0 ])
246245pause_button .configure (state = buttons [1 ])
247246resume_button .configure (state = buttons [2 ])
@@ -250,13 +249,10 @@ def request_currLine():
250249file_button .configure (state = buttons [5 ])
251250params_button .configure (state = buttons [6 ])
252251
253- # Create a StringVar to hold the label text
252+ #Criação dos campos de texto de exibição da linha atual e do código G
254253linha_var = ctk .StringVar (value = "Linha atual: " + str (linhaAtual ))
255-
256- # Create a label to display the global variable value
257254linha_label = ctk .CTkLabel (app , textvariable = linha_var )
258255linha_label .grid (row = 0 , column = 1 , rowspan = 1 , pady = 10 , padx = 10 )
259-
260256textbox = ctk .CTkTextbox (app , width = 300 , height = 400 )
261257textbox .grid (row = 1 , column = 1 ,rowspan = 7 , pady = 10 , padx = 10 )
262258textbox .tag_config ("highlight" , background = "#0077dd" )
@@ -301,8 +297,6 @@ def request_currLine():
301297
302298
303299
304-
305-
306300def background_loop ():
307301 while True :
308302 if ((state == states ["RUNNING" ]) & (not blockFlag )):
0 commit comments