Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
## Quick and dirty serial logger. Logs data received from a serial port.
## Port and baud rate selection
monitorPort = 'COM29'
monitorBaud = 115200
##
import serial
import time
import signal
terminate = False
def logger(port, baud):
global terminate
## open the port
try:
serialConnection = serial.Serial(port, baud, timeout=1)
## if it fails due to I/O error (e.g. file not found)..
except IOError:
## complain about it
print('The serial port ' + port + ' is not available for use. Script terminating.')
## terminate the script
sys.exit('The requested COM port is not available for use, therefore the script can not continue')
## if it fails due to an unknown exception
except:
## complain about it
print('An unknown error occured while trying to open ' + port)
## return (it might be non-fatal)
sys.exit('An unknown error occured when trying to open the COM port, therefore the script can not continue')
## open the logfile
timeString = time.strftime("%Y%m%d-%H%M%S", time.localtime())
fileName = timeString + '_' + port[-4:] + '_receive.log'
logFile = open(fileName, 'a+')
## put a header in the logfile
timeStamp = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
logFile.write('### Logging ' + monitorPort + ' (' + str(monitorBaud) + 'bps). Started ' + str(timeStamp) + ' ###')
logFile.flush()
## poll until terminated
while terminate == False:
## check if there is data available. enclose in a try because sometimes this fails.
try:
waitingCharacters = serialConnection.inWaiting()
except:
## i don't remember why this was set to 9, but serial reading is unreliable if it set to 0
waitingCharacters = 9
## if there is data available
if waitingCharacters >= 1:
try:
## get the line
line = serialConnection.readline()
except:
## if we didn't get the line, just go to the next loop
break
## strip endline characters and excess start/end whitespace
cleanLine = line.decode('utf-8', errors='ignore').rstrip().replace('\n', '').replace('\r', '')
## replace tabs with single spaces
cleanLine.expandtabs(1)
## only proceed if the data isn't a blank line
if cleanLine != '':
## log the received line
timeStamp = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
logFile.write('\n[' + str(timeStamp) + '] ' + cleanLine)
logFile.flush()
print('\n[' + str(timeStamp) + ' RX] ' + cleanLine)
## terminated, (try to) clean up
try:
logFile.write('### Logging ' + monitorPort + ' (' + str(monitorBaud) + 'bps). Ended ' + str(timeStamp) + ' ###')
logFile.close()
serialConnection.close()
except:
pass
## ctrl + c handling
def handle_sigint(signal, frame):
global terminate
print('Ctrl + C detected. Terminating..')
terminate = True
signal.signal(signal.SIGINT, handle_sigint)
## setup a logger for the port
print('Logging ' + monitorPort + ' at ' + str(monitorBaud) + 'bps')
logger(monitorPort, monitorBaud)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment