Created
March 18, 2014 23:05
-
-
Save theterg/9631705 to your computer and use it in GitHub Desktop.
A simple python 3.0 script to log data from two different serial ports at one time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import serial | |
| import sys | |
| import time | |
| import argparse | |
| parser = argparse.ArgumentParser(description='Dump serial data from basis') | |
| parser.add_argument('portA', type=str, help='Serial port A') | |
| parser.add_argument('portB', type=str, help='Serial port B') | |
| parser.add_argument('--baud', type=int, default=1000000, help='The baud rate of both devices') | |
| parser.add_argument('--labelA', type=str, default='A') | |
| parser.add_argument('--labelB', type=str, default='B') | |
| parser.add_argument('--log', action='store_true', default=False) | |
| args = parser.parse_args() | |
| porta = serial.Serial(args.portA, args.baud, timeout=1) | |
| portb = serial.Serial(args.portB, args.baud, timeout=1) | |
| astr = bytearray() | |
| bstr = bytearray() | |
| gota = 0.0 | |
| gotb = 0.0 | |
| logfile = None | |
| if args.log: | |
| logfile = open(time.strftime('serial_logfile_%d%m%y_%H%M%S.txt', time.gmtime()), 'w') | |
| def parseLine(src, line): | |
| ret = [] | |
| for byte in line: | |
| ret.append('%02x' % byte) | |
| outline = '[%.3f] %s: %s' % (time.time(), src, ''.join(ret)) | |
| print(outline) | |
| if args.log: | |
| logfile.write(outline+'\n') | |
| logfile.flush() | |
| try: | |
| while(True): | |
| while(porta.inWaiting()): | |
| if len(bstr) > 0: | |
| parseLine(args.labelB, bstr) | |
| bstr = bytearray() | |
| astr.append(ord(porta.read(1))) | |
| gota = time.time() | |
| while(portb.inWaiting()): | |
| if len(astr) > 0: | |
| parseLine(args.labelA, astr) | |
| astr = bytearray() | |
| bstr.append(ord(portb.read(1))) | |
| gotb = time.time() | |
| if (time.time() - gota > 0.9) and (len(astr) > 0): | |
| parseLine(args.labelA, astr) | |
| astr = bytearray() | |
| if (time.time() - gotb > 0.9) and (len(bstr) > 0): | |
| parseLine(args.labelB, bstr) | |
| bstr = bytearray() | |
| except KeyboardInterrupt: | |
| porta.close() | |
| portb.close() | |
| if args.log: | |
| logfile.close() | |
| sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment