Simple Serial Port Logging Utility
#
Based on pyserial
this utility helps to log data from
a Serial Port connected to a PC.
It also creates a log file with date stamps.
Download
#
Here is the Link
to the Source for download.
Save it as SerialLogger.py
.
Run
#
Details
#
One needs to change the section under # Port Configuration
to customize it for your own system.
Listed below is the full source code:
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
| #!/usr/bin/python
## Serial Port Logger Application
# We can't do any thing without Serial
try:
import serial
except (ImportError):
msg = """ERROR: pyserial library not found
Install pyserial library
pip install pyserial"""
print(msg)
exit(1)
# Other Imports
import logging, time
from signal import signal, SIGINT
from sys import exit
from queue import Queue,Empty
# Port Configuration
PORT = "COM5"
BAUD = 115200
logFileName='serial.log'
q = Queue(2)
def setupLogger(filename):
logger = logging.getLogger('Serial Logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(filename)
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s ~ %(name)s ~ %(levelname)s ~ %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
# Return the Created logger
return logger
def main(qSignal):
## Logger Configuration
global logFileName
log = setupLogger(logFileName)
## Begin
log.info("Program Started")
ser = None
try:
ser = serial.Serial(PORT, BAUD, timeout=1)
except Exception as e:
log.error("Got Fatal error - {}".format(e))
exit(4)
# Loop for Reception
while 1:
## Ctrl+C signal
try:
squit = qSignal.get(block=False, timeout=0.1)
except Empty as e:
squit = False
if squit == True:
log.info("Exiting")
ser.close()
exit(0)
# Get Data
try:
data = ser.readline()
if len(data) > 0:
log.info(data)
except KeyboardInterrupt as e:
q.put(True)
log.info("Ctrl + C pressed")
def handler(signal_received, frame):
# Handle any cleanup here
print('SIGINT or CTRL-C detected. Exiting gracefully')
q.put(True)
if __name__ == "__main__":
signal(SIGINT, handler)
print('Running. Press CTRL-C to exit.')
main(q)
|