Attachment 'readSerial.py'

Download

   1 #! /usr/bin/env python
   2 
   3 import sys, serial, csv
   4 
   5 
   6 class SerialRead(object):
   7     def __init__(self, options):
   8         self._options = options
   9         self.__header = False
  10 
  11     def read(self, stream=sys.stdout):
  12         csvFile = None
  13         writer = None
  14         ser = serial.Serial(self._options.device, 9600, timeout=1)
  15 
  16         if hasattr(self._options, "csvFile") and self._options.csvFile:
  17             csvFile = self.openFile(self._options.csvFile, 'wb')
  18             writer = csv.writer(csvFile, lineterminator='\n')
  19 
  20         if ser: print "Serial port " + ser.portstr + " opened.\n"
  21         loop = True
  22 
  23         while loop:
  24             try:
  25                 line = ''
  26                 char = ser.read(1)
  27 
  28                 while char != '\r':
  29                     stream.flush()
  30 
  31                     if char != '\n':
  32                         line += char
  33 
  34                     char = ser.read(1)
  35 
  36                 line = '%s\n' % line
  37                 stream.write(line)
  38                 if writer: self._parseLine(writer, line)
  39             except KeyboardInterrupt:
  40                 ser.close()
  41                 loop = False
  42 
  43         if csvFile: csvFile.close()
  44 
  45     def _parseLine(self, writer, line):
  46         if "Starting" not in line:
  47             lineList = [x.strip('):,\r \n') for x in line.strip().split()]
  48             if len(lineList) < 13: return
  49 
  50             if not self.__header:
  51                 newLine = (
  52                     'Count', lineList[1], lineList[3], lineList[5],
  53                     lineList[7], lineList[9], lineList[11]
  54                     )
  55                 writer.writerow(newLine)
  56                 self.__header = True
  57 
  58             newLine = (
  59                 int(lineList[0]), int(lineList[2]), float(lineList[4]),
  60                 float(lineList[6]), float(lineList[8]), float(lineList[10]),
  61                 float(lineList[12])
  62                 )
  63 
  64             writer.writerow(newLine)
  65 
  66     def openFile(self, filePath, how='rb'):
  67         fp = None
  68 
  69         try:
  70             fp = open(filePath, how)
  71         except IOError, e:
  72             msg = "Error: Could not open file: %s, %s."
  73             raise IOError(msg % (filePath, e))
  74 
  75         return fp
  76 
  77 
  78 if __name__ == '__main__':
  79     import traceback
  80     from optparse import OptionParser
  81 
  82     # argparse is only available in Python version 2.7.0 and up.
  83     ## from argparse import ArgumentParser
  84 
  85     ## parser = ArgumentParser(description='Serial console')
  86     ## parser.add_argument('-v', '--verbose', action='store_true', default=False,
  87     ##                     dest='verbose', help='Verbose messages to stdout.')
  88     ## parser.add_argument('-d', '--device', dest='device', help='Serial device')
  89     ## options = parser.parse_args()
  90 
  91     usage = "usage: %prog [h] -d <device> -c <CSV File> " + \
  92             "-s <Raw data dump file>"
  93     parser = OptionParser(usage=usage)
  94     parser.add_option('-d', '--device', dest='device', help='Serial device')
  95     parser.add_option('-c', '--csv', dest='csvFile', help='CSV output filename')
  96     parser.add_option('-s', '--stream', dest='stream',
  97                       help='Raw stream filename')
  98 
  99     options, args = parser.parse_args()
 100     stream = sys.stdout
 101 
 102     if hasattr(options, "device") and options.device:
 103         try:
 104             sr = SerialRead(options)
 105 
 106             if hasattr(options, "stream") and options.stream:
 107                 stream = sr.openFile(options.stream, 'wb')
 108 
 109             sr.read(stream=stream)
 110             if stream is not sys.stdout: stream.close()
 111         except Exception:
 112             tb = sys.exc_info()[2]
 113             traceback.print_tb(tb)
 114             print "%s: %s\n" % (sys.exc_info()[0], sys.exc_info()[1])
 115             sys.exit(1)
 116     else:
 117         print "Must pass the device."
 118         sys.exit(1)
 119 
 120     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.