dump_as_ascii.py

Mon, 10 Dec 2007 20:05:39 +0100

author
David Douard <david.douard@logilab.fr>
date
Mon, 10 Dec 2007 20:05:39 +0100
changeset 0
9af1509775b6
permissions
-rw-r--r--

initial import

import sys
import time
import serial

MODE = {'binary': 'DDBN',
        'ascii': 'DDAS',
        'ansi': 'DDAN',
        }
class ConnectionError(Exception):
    pass

def read_trace(cnx, mode="binary"): 
    mode = mode.lower()
    assert mode in MODE
    mode = MODE[mode]
    res = ""
    cnx.write('%s\r'%mode)
    i = 0
    while i<5:
        l = cnx.readline()
        if l.strip() == "":
            i += 1
            time.sleep(0.1)
            continue
        #print "got a new line (%s chars) [i=%s]"%(len(l), i)
        res += l 
        i = 0
    return res

def open_connection(device="/dev/ttyUSB0", baudrate=115200, timeout=0.1,
                    address=0, mode=1):
    p = serial.Serial(port=device, baudrate=baudrate, timeout=timeout)

    p.write('++addr %d\r'%address) # set address to 0
    p.write('++mode %d\r'%mode) # read listen only mode
    p.write('++mode\r')
    i = 0
    for i in range(10):    
        rmode = p.readline().strip()
        if rmode != "":
            break
        time.sleep(timeout)
        
    if rmode == '' or int(rmode) != mode:
        raise ConnectionError("Can't set GPIB mode to %s"%mode)
    return p


import optparse
opt = optparse.OptionParser()
opt.add_option('-f', '--filename', default=None,
               dest='filename',
               help='Output filename. If not set, write to stdout')
opt.add_option('-d', '--device', default='/dev/ttyUSB0',
               dest='device',
               help='Device of the RS232 connection (default: /dev/ttyUSB0)',
               )
opt.add_option('-m', '--mode', default='binary',
               dest='mode',
               help='Dumping mode (may be "binary" [default], "ascii" or "ansi")',
               )
opt.add_option('-a', '--address', default=0,
               dest='address',
               help='GPIB address of the device',
               )
options, argv = opt.parse_args(sys.argv)

cnx = open_connection(device=options.device,
                      address=int(options.address), mode=1)
res = read_trace(cnx, mode=options.mode)

if options.filename:
    open(options.filename, 'w').write(res)
else:
    print res
    

mercurial