Demo entry 6718994



Submitted by anonymous on Mar 07, 2018 at 16:08
Language: Python 3. Code size: 3.5 kB.


import os, time, sys, glob, datetime, syslog, pynmea2, serial

def logfilename():
    now =
    return 'NMEA_%0.4d-%0.2d-%0.2d_%0.2d-%0.2d-%0.2d.nmea' % \
                (now.year, now.month,,
                 now.hour, now.minute, now.second)
def _scan_ports():
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        patterns = ('/dev/tty[A-Za-z]*', '/dev/ttyUSB*')
        ports = [glob.glob(pattern) for pattern in patterns]
        ports = [item for sublist in ports for item in sublist]  # flatten
    elif sys.platform.startswith('darwin'):
        patterns = ('/dev/*serial*', '/dev/ttyUSB*', '/dev/ttyS*')
        ports = [glob.glob(pattern) for pattern in patterns]
        ports = [item for sublist in ports for item in sublist]  # flatten
        raise EnvironmentError('Unsupported platform')
    return ports

    while True:
        ports = _scan_ports()
        if len(ports) == 0:
            sys.stderr.write('No ports found, waiting 10 Ctrl-C to quit...\n')
            syslog.syslog('No ports found, waiting 10 seconds...\n')

        for port in ports:
            # try to open serial port
            sys.stderr.write('Trying port %s\n' % port)
            syslog.syslog('Trying port %s\n' % port)
                # try to read a line of data from the serial port and parse
                with serial.Serial(port, 57600, timeout=1) as ser:
                    # 'warm up' with reading some input
                    for i in range(10):
                    # try to parse (will throw an exception if input is not valid NMEA)
                    pynmea2.parse(ser.readline().decode('ascii', errors='replace'))

                    # log data
                    outfname = logfilename()
                    sys.stderr.write('Logging data on %s to %s\n' % (port, outfname))
                    syslog.syslog('Logging data on %s to %s\n' % (port, outfname))
                    with open(outfname, 'wb') as f:
                        # loop will exit with Ctrl-C, which raises a
                        # KeyboardInterrupt
                        while True:
                            line = ser.readline()
                            print(line.decode('ascii', errors='replace').strip())

            except Exception as e:
                sys.stderr.write('Error reading serial port %s: %s\n' % (type(e).__name__, e))
                syslog.syslog('Error reading serial port %s: %s\n' % (type(e).__name__, e))
            except KeyboardInterrupt as e:
                sys.stderr.write('Ctrl-C pressed, exiting log of %s to %s\n' % (port, outfname))
                syslog.syslog('Ctrl-C pressed, exiting log of %s to %s\n' % (port, outfname))

        sys.stderr.write('Scanned all ports, waiting 10 Ctrl-C to quit...\n')
        syslog.syslog('Scanned all ports, waiting 10 seconds...\n')
except KeyboardInterrupt:
    sys.stderr.write('Ctrl-C pressed, exiting port scanner\n')
    syslog.syslog('Ctrl-C pressed, exiting port scanner\n')

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).