Attachment 'sterm.py'

Download

   1 #! /usr/bin/env python
   2 
   3 import sys, serial, csv
   4 
   5 
   6 class SerialRead(object):
   7     __CSV_DELIMITER = ','
   8 
   9     def __init__(self, options):
  10         self._options = options
  11         self.__numCol = 0
  12 
  13     def read(self, stream=sys.stdout):
  14         csvFile = None
  15         writer = None
  16         ser = serial.Serial(self._options.device, self._options.baud, timeout=1)
  17 
  18         if self._options.csvFile:
  19             csvFile = self.openFile(self._options.csvFile, 'wb')
  20             writer = csv.writer(csvFile, lineterminator='\n')
  21 
  22         if ser:
  23             print "Serial port {} opened at {} baud.\n".format(
  24                 ser.portstr, self._options.baud)
  25 
  26         loop = 1
  27 
  28         while loop:
  29             try:
  30                 line = ''
  31                 char = ser.read(1)
  32 
  33                 while char != '\r':
  34                     stream.flush()
  35 
  36                     if char != '\n':
  37                         line += char
  38 
  39                     char = ser.read(1)
  40 
  41                 line = '{}\n'.format(line)
  42 
  43                 if self._options.line_numbers:
  44                     line = "{}: {}".format(loop, line)
  45 
  46                 stream.write(line)
  47 
  48                 if writer:
  49                     lineList = self._flattenLine(line, loop)
  50                     self._parseLine(writer, lineList)
  51 
  52                 loop += 1
  53             except KeyboardInterrupt:
  54                 loop = 0
  55                 print
  56 
  57         #print "%s" % self._dataList
  58         if csvFile: csvFile.close()
  59 
  60     def _flattenLine(self, line, loop):
  61         if self._options.line_numbers:
  62             colon = line.find(':')
  63 
  64             if line[0: colon].isdigit():
  65                 line = line[0: colon] + self.__CSV_DELIMITER + line[colon + 1:]
  66 
  67         lineList = [x.strip() for x in line.strip().split(self.__CSV_DELIMITER)]
  68 
  69         if loop == 1:
  70             self.__numCol = len(lineList)
  71 
  72         #print lineList
  73         if len(lineList) != self.__numCol:
  74             lineList = []
  75 
  76         return lineList
  77 
  78     def _parseLine(self, writer, lineList):
  79         newLine = []
  80 
  81         for item in lineList:
  82             if not isinstance(item, int):
  83                 if item.isdigit():
  84                     item = int(item)
  85                 elif item.replace('.', '').isdigit():
  86                     item = float(item)
  87                 else:
  88                     item = "'{}'".format(item)
  89 
  90             newLine.append(item)
  91 
  92         # If nothing in line fake the line.
  93         if not newLine:
  94             newLine = ['',] * self.__numCol
  95 
  96         writer.writerow(newLine)
  97 
  98     def openFile(self, filePath, how='rb'):
  99         fp = None
 100 
 101         try:
 102             fp = open(filePath, how)
 103         except IOError, e:
 104             msg = "Error: Could not open file: {}, {}."
 105             raise IOError(msg.format(filePath, e))
 106 
 107         return fp
 108 
 109 
 110 if __name__ == '__main__':
 111     import traceback
 112     from argparse import ArgumentParser
 113 
 114     baudList = ((1, 4800), (2, 9600), (3, 19200), (4, 38400), (5, 57600),
 115                 (6, 115200), (7, 230400), (8, 250000),)
 116 
 117     parser = ArgumentParser(description='Serial console')
 118     parser.add_argument(
 119         '-b', '--baud', dest='baud', type=int, help="Baud rate number, use "
 120         "-l to display available baud rates.")
 121     parser.add_argument(
 122         '-c', '--csv', dest='csvFile', help='CSV output filename')
 123     parser.add_argument(
 124         '-D', '--debug', dest='debug', action='store_true', default=False,
 125         help='Debug output')
 126     parser.add_argument(
 127         '-d', '--device', dest='device', help='Serial device')
 128     parser.add_argument(
 129         '-l', '--blist', dest='blist', action='store_true', default=False,
 130         help='List available baud rates.')
 131     parser.add_argument(
 132         '-n', '--line-numbers', dest='line_numbers', action='store_true',
 133         default=False, help="Prefix line numbers to each line.")
 134     parser.add_argument(
 135         '-s', '--stream', dest='stream', help='Raw stream filename')
 136     options = parser.parse_args()
 137     #print "Options: {}".format(options)
 138     stream = sys.stdout
 139 
 140     if options.blist:
 141         for n, b in baudList:
 142             print "{} {}".format(n, b)
 143 
 144         sys.exit(0)
 145 
 146     if options.baud:
 147         options.baud = dict(baudList).get(options.baud)
 148     else:
 149         options.baud = 9600
 150 
 151     if options.baud is None:
 152         print ("Invalid baud rate, can only use numbers between 1 "
 153                "and {}.").format(len(baudList))
 154         sys.exit(1)
 155 
 156     if options.debug:
 157         print "Options: {}".format(options)
 158 
 159     if options.device:
 160         try:
 161             sr = SerialRead(options)
 162 
 163             if options.stream:
 164                 stream = sr.openFile(options.stream, 'wb')
 165 
 166             sr.read(stream=stream)
 167             if stream is not sys.stdout: stream.close()
 168         except serial.serialutil.SerialException as e:
 169             print "Exiting with: {}".format(e)
 170             sys.exit(1)
 171         except Exception:
 172             tb = sys.exc_info()[2]
 173             traceback.print_tb(tb)
 174             print "%s: %s\n" % (sys.exc_info()[0], sys.exc_info()[1])
 175             sys.exit(1)
 176     else:
 177         print "Must pass the device."
 178         sys.exit(1)
 179 
 180     sys.exit(0)

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.