Skip to content

Commit 2ab0af5

Browse files
committed
improving file interface
1 parent 235fc1f commit 2ab0af5

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
@@ -306,122 +306,110 @@ def _sending_commands(self):
306306
time.sleep(0.05)
307307

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

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

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

427415
def get_json(self, path, timeout=1):
@@ -678,4 +666,4 @@ def __exit__(self, exc_type, exc_val, exc_tb):
678666
#response = monitor.waitForResponse(command_id)
679667

680668
if response:
681-
print("Response:", response)
669+
print("Response:", response)

0 commit comments

Comments
 (0)