Skip to content

Commit 1bd2777

Browse files
committed
Merge branch 'master' into mergemaster
2 parents 8e0f057 + 34ee595 commit 1bd2777

1 file changed

Lines changed: 101 additions & 113 deletions

File tree

uc2rest/mserial.py

Lines changed: 101 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -308,122 +308,110 @@ def _sending_commands(self):
308308
time.sleep(0.05)
309309

310310
def _process_commands(self):
311-
# create file writer object so save all self._read to a txt
312-
f = None
313-
try:
314-
f = open("serial_log.txt", "w", buffering=1) # Line buffering
315-
f.write("Serial Log Start\n")
316-
f.flush()
317-
buffer = ""
318-
reading_json = False
319-
currentIdentifier = 0
320-
nLineCountTimeout = 50 # maximum number of lines read before timeout
321-
lineCounter = 0
322-
nFailedCommands = 0
323-
nFailedCommandsMax = 10
324-
while self.running:
325-
if self.manufacturer == "UC2Mock":
326-
self.running = False
327-
return
328-
329-
# device not ready yet
330-
if self.serialdevice is None:
331-
self.is_connected = False
332-
continue
333-
else:
334-
self.is_connected = True
311+
buffer = ""
312+
reading_json = False
313+
currentIdentifier = 0
314+
nLineCountTimeout = 50 # maximum number of lines read before timeout
315+
lineCounter = 0
316+
nFailedCommands = 0
317+
nFailedCommandsMax = 10
318+
while self.running:
319+
if self.manufacturer == "UC2Mock":
320+
self.running = False
321+
return
335322

336-
# if we just want to send but not even wait for a response
337-
with self.serialLock:
338-
try:
339-
mReadline = self._read(self.serialdevice)
340-
if mReadline == False :
341-
nFailedCommands += 1
342-
if nFailedCommands > nFailedCommandsMax:
343-
raise Exception("Failed to read the line in serial: "+str(mReadline))
344-
line = mReadline.decode('utf-8').strip()
345-
if line!="":
346-
f.write(line+"\n")
347-
f.flush() # Ensure data is written immediately
348-
if self.DEBUG:
349-
self._logger.debug("[ProcessLines]:"+str(line))
350-
except Exception as e:
351-
self._logger.error("Failed to read the line in serial: "+str(e))
323+
# device not ready yet
324+
if self.serialdevice is None:
325+
self.is_connected = False
326+
continue
327+
else:
328+
self.is_connected = True
329+
330+
# if we just want to send but not even wait for a response
331+
with self.serialLock:
332+
try:
333+
mReadline = self._read(self.serialdevice)
334+
if mReadline == False :
352335
nFailedCommands += 1
353-
line = ""
354-
355-
# if we have a problem with the serial connection, we need to reconnect
356-
if nFailedCommands>5:
357-
for i in range(4):
358-
nFailedCommands=0
359-
if self.reconnect():
360-
self._logger.debug("Reconnected to the serial device")
361-
break
362-
else:
363-
self._logger.debug("Failed to reconnect to the serial device")
364-
time.sleep(1)
365-
366-
if line.find("++")>=0:
367-
reading_json = True
368-
continue
369-
elif line.find("error") != -1 and currentIdentifier is not None and currentIdentifier >=0 :
370-
# if we have an error, we need to reset the last command
371-
self._logger.debug("Error - last command did not match the firmware: "+str(self.commands[currentIdentifier]))
372-
self.resetLastCommand = True
373-
buffer = ""
374-
lineCounter = 0
375-
reading_json = False
376-
self.responses[currentIdentifier].append({"error": 1})
377-
self.responses[currentIdentifier].append({"qid": currentIdentifier})
378-
elif line.find("--")>=0 or lineCounter>nLineCountTimeout:
379-
lineCounter = 0
380-
reading_json = False
381-
try:
382-
json_response = json.loads(buffer)
383-
if self.DEBUG: self._logger.debug("[ProcessCommands]: "+str(json_response))
384-
if len(self.callBackList) > 0:
385-
for callback in self.callBackList:
386-
# check if json has key
387-
try:
388-
if callback["pattern"] in json_response:
389-
callback["callbackfct"](json_response)
390-
except Exception as e:
391-
self._logger.error("[ProcessCommands Casting Callbacks]: "+str(e))
336+
if nFailedCommands > nFailedCommandsMax:
337+
raise Exception("Failed to read the line in serial: "+str(mReadline))
338+
line = mReadline.decode('utf-8').strip()
339+
if self.DEBUG and line!="":
340+
self._logger.debug("[ProcessLines]:"+str(line))
341+
except Exception as e:
342+
self._logger.error("Failed to read the line in serial: "+str(e))
343+
nFailedCommands += 1
344+
line = ""
345+
346+
# if we have a problem with the serial connection, we need to reconnect
347+
if nFailedCommands>5:
348+
for i in range(4):
349+
nFailedCommands=0
350+
if self.reconnect():
351+
self._logger.debug("Reconnected to the serial device")
352+
break
353+
else:
354+
self._logger.debug("Failed to reconnect to the serial device")
355+
time.sleep(1)
356+
357+
if line.find("++")>=0:
358+
reading_json = True
359+
continue
360+
elif line.find("error") != -1 and currentIdentifier is not None and currentIdentifier >=0 :
361+
# if we have an error, we need to reset the last command
362+
self._logger.debug("Error - last command did not match the firmware: "+str(self.commands[currentIdentifier]))
363+
self.resetLastCommand = True
364+
buffer = ""
365+
lineCounter = 0
366+
reading_json = False
367+
self.responses[currentIdentifier].append({"error": 1})
368+
self.responses[currentIdentifier].append({"qid": currentIdentifier})
369+
elif line.find("--")>=0 or lineCounter>nLineCountTimeout:
370+
lineCounter = 0
371+
reading_json = False
372+
try:
373+
json_response = json.loads(buffer)
374+
if self.DEBUG: self._logger.debug("[ProcessCommands]: "+str(json_response))
375+
if len(self.callBackList) > 0:
376+
for callback in self.callBackList:
377+
# check if json has key
378+
try:
379+
if callback["pattern"] in json_response:
380+
callback["callbackfct"](json_response)
381+
except Exception as e:
382+
self._logger.error("[ProcessCommands Casting Callbacks]: "+str(e))
383+
384+
except Exception as e:
385+
self._logger.error("Failed to load the json from serial %s" % buffer)
386+
self._logger.error("Error: %s" % str(e))
387+
json_response = {}
388+
#reading_json = True
392389

390+
try: currentIdentifier = json_response["qid"]
391+
except: pass
392+
393+
with self.lock:
394+
try: # TODO: THis looks fishy an
395+
self.responses[currentIdentifier].append(json_response.copy())
393396
except Exception as e:
394-
self._logger.error("Failed to load the json from serial %s" % buffer)
395-
self._logger.error("Error: %s" % str(e))
396-
json_response = {}
397-
#reading_json = True
398-
399-
try: currentIdentifier = json_response["qid"]
400-
except: pass
401-
402-
with self.lock:
403-
try: # TODO: THis looks fishy an
404-
self.responses[currentIdentifier].append(json_response.copy())
405-
except Exception as e:
406-
#self._logger.error("Failed to append the response: "+str(e))
407-
self.responses[currentIdentifier] = list()
408-
self.responses[currentIdentifier].append(json_response.copy())
409-
buffer = "" # reset buffer
410-
411-
# detect a reboot of the device and return the current QIDs
412-
elif line == "reboot":
413-
self._logger.warning("Device rebooted")
414-
self.resetLastCommand = True
415-
buffer = ""
416-
lineCounter = 0
417-
reading_json = False
418-
self.responses[currentIdentifier].append({"reboot": 1})
419-
self.responses[currentIdentifier].append({"qid": currentIdentifier})
420-
421-
if reading_json:
422-
buffer += line
423-
lineCounter +=1
424-
finally:
425-
if f is not None:
426-
f.close()
397+
#self._logger.error("Failed to append the response: "+str(e))
398+
self.responses[currentIdentifier] = list()
399+
self.responses[currentIdentifier].append(json_response.copy())
400+
buffer = "" # reset buffer
401+
402+
# detect a reboot of the device and return the current QIDs
403+
elif line == "reboot":
404+
self._logger.warning("Device rebooted")
405+
self.resetLastCommand = True
406+
buffer = ""
407+
lineCounter = 0
408+
reading_json = False
409+
self.responses[currentIdentifier].append({"reboot": 1})
410+
self.responses[currentIdentifier].append({"qid": currentIdentifier})
411+
412+
if reading_json:
413+
buffer += line
414+
lineCounter +=1
427415
self.running = False
428416

429417
def get_json(self, path, timeout=1):
@@ -680,4 +668,4 @@ def __exit__(self, exc_type, exc_val, exc_tb):
680668
#response = monitor.waitForResponse(command_id)
681669

682670
if response:
683-
print("Response:", response)
671+
print("Response:", response)

0 commit comments

Comments
 (0)