import sys
import time
import gpib
import prologix


class HP3562dumper(prologix.GPIB):

    MODES = {'trace': 'DD',
             'state': 'DS',
             'coord': 'DC',
             }
    
    FORMATS = {'binary': 'BN',
               'ascii': 'AS',
               'ansi': 'AN'}
            
    def __init__(self, device="/dev/ttyUSB0", baudrate=115200, timeout=0.1,
                 address=0):
        super(HP3562dumper, self).__init__(device, baudrate, timeout, address, mode=1)

    def dump(self, mode='trace', format="binary"): 
        format = format.lower()
        mode = mode.lower()
        assert mode in self.MODES
        assert format in self.FORMATS
        cmd = self.MODES[mode] + self.FORMATS[format]

        res = ""
        print "command = ", cmd
        self._cnx.write('%s\r'%cmd)
        i = 0
        while i<self._retries:
            l = self._cnx.readline()
            if l.strip() == "":
                i += 1
                time.sleep(self._timeout)
                continue
            res += l 
            i = 0
        return res

    

def main():
    import optparse
    opt = optparse.OptionParser("A simple tool for dumping the current trace")
    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('-a', '--address', default=0,
                   dest='address',
                   help='GPIB address of the device',
                   )
    opt.add_option('-b', '--block', default='trace',
                   dest='block',
                   help='Data block to dump (may be "trace" [default], "state" or "coord")',
                   )
    opt.add_option('-m', '--mode', default='binary',
                   dest='mode',
                   help='Dumping mode (may be "binary" [default], "ascii" or "ansi")',
                   )
    options, argv = opt.parse_args(sys.argv)

    cnx = HP3562dumper(device=options.device, address=int(options.address))
    res = cnx.dump(mode=options.block, format=options.mode)
    sys.stderr.write("read %s bytes\n"%(len(res)))
    if options.filename:
        open(options.filename, 'w').write(res)
    else:
        print res
    
if __name__=='__main__':
    main()
