# HG changeset patch # User David Douard # Date 1197933790 -3600 # Node ID 07e2cbf140df2927c8e4ce2a3dbc0dea1d2b8c04 # Parent 78e3e839658ba4ee133053f6626a84468af91a86 several improvements; add an internal state reader diff -r 78e3e839658b -r 07e2cbf140df HP3562A/__init__.py --- a/HP3562A/__init__.py Mon Dec 17 18:59:45 2007 +0100 +++ b/HP3562A/__init__.py Tue Dec 18 00:23:10 2007 +0100 @@ -12,8 +12,90 @@ --------- """ +import struct +import gpib -from gpib import gpib +######################################## +# HP3562A internal binary types decoders + +def decode_float(s): + assert len(s) in [4,8] + # exponential term + e = ord(s[-1]) + if e & 0x80: + e = e - 256 + + # mantissa + m = [ord(x) for x in s[:-1]] + M = 0. + for i in range(len(s)-1): + #M += m[i]<<(i*8) + M += float(m[i])/2**((i+1)*8) + # XXX how do we deal negative numbers? + #if m[0] & 0x80: + # M = M - 2^(len(s)) + return M * 2**(e+1) + +def decode_string(s): + nb = ord(s[0]) + s = s[1:nb+2] + r = "" + # XXX why do we need to do this? It's not described in the manual... + for c in s: + r += chr(ord(c) & 0x7F) + return r + + +### +# Some useful functions +def format_header(header, head_struct, columns=80): + """ + Pretty print a data block (trace, state or coord) + """ + todisp = [] + for row in head_struct: + key = row[0] + val = header.get(key, "N/A") + if isinstance(val, basestring): + val = repr(val) + else: + val = str(val) + todisp.append((key+":", val)) + maxk = max([len(k) for k, v in todisp]) + maxv = max([len(v) for k, v in todisp]) + fmt = "%%-%ds %%-%ds"%(maxk, maxv) + w = maxk+maxv+4 + ncols = columns/w + nrows = len(todisp)/ncols + res = "" + for i in range(nrows): + res += "| ".join([fmt%todisp[j*nrows+i] for j in range(ncols)]) + "\n" + return res + +def decode_header(data, header_struct): + d = data + typ = d[:2] + assert typ == "#A" + + totlen = struct.unpack('>h', d[2:4])[0] + idx = 4 + tt=0 + header = {} + for i, (nam, dtype, fmt, nbytes) in enumerate(header_struct): + if dtype == str: + val = decode_string(d[idx:]) + else: + if fmt: + v = struct.unpack('>'+fmt, d[idx: idx+nbytes])[0] + if isinstance(dtype, dict): + val = dtype.get(int(v), "N/A") + else: + val = dtype(v) + else: + val = dtype(d[idx: idx+nbytes]) + header[nam] = val + idx += nbytes + return header, idx ##################### # HP3562A constants @@ -102,3 +184,5 @@ (0x40, "ACDA", "Accept date"), #... ] + + diff -r 78e3e839658b -r 07e2cbf140df HP3562A/dump_datablock.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HP3562A/dump_datablock.py Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,78 @@ +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 ih', d[2:4])[0] - idx = 4 - tt=0 - header = {} - for i, (nam, dtype, fmt, nbytes) in enumerate(HEADER): - if dtype == str: - val = decode_string(d[idx:]) - else: - if fmt: - v = struct.unpack('>'+fmt, d[idx: idx+nbytes])[0] - if isinstance(dtype, dict): - val = dtype.get(int(v), "N/A") - else: - val = dtype(v) - else: - val = dtype(d[idx: idx+nbytes]) - header[nam] = val - idx += nbytes - resu = [] - for i in range(header["Number of elements"]): - resu.append(decode_float(d[idx: idx+4])) - idx += 4 - return header, numpy.array(resu, dtype=float) - -def format_header(header, head_struct, columns=80): - todisp = [] - for row in head_struct: - key = row[0] - val = header.get(key, "N/A") - if isinstance(val, basestring): - val = repr(val) - else: - val = str(val) - todisp.append((key+":", val)) - maxk = max([len(k) for k, v in todisp]) - maxv = max([len(v) for k, v in todisp]) - fmt = "%%-%ds %%-%ds"%(maxk, maxv) - w = maxk+maxv+4 - ncols = columns/w - nrows = len(todisp)/ncols - print "w=", w - print "ncols=", ncols - print "nrows=", nrows - res = "" - for i in range(nrows): - res += "| ".join([fmt%todisp[j*nrows+i] for j in range(ncols)]) + "\n" - return res - - -if __name__ == "__main__": - import sys - import optparse - opt = optparse.OptionParser("A simple tool for tracing a dumped trace") - opt.add_option('-f', '--filename', default=None, - dest='filename', - help='Output filename. If not set, read from stdin') - opt.add_option('-m', '--mode', default='binary', - dest='mode', - help='Dumping mode (may be "binary" [default], "ascii" or "ansi")', - ) - opt.add_option('-d', '--display-header', default=False, - action="store_true", - dest="displayheader", - help="Display the trace header") - opt.add_option('-P', '--noplot-trace', default=True, - action="store_false", - dest="plot", - help="Do not display the plot of the trace") - opt.add_option('-x', '--xmode', default='lin', - dest='xmode', - help='X coordinate mode (may be "lin" [default] or "log")') - opt.add_option('-y', '--ymode', default='lin', - dest='ymode', - help='Y coordinate mode (may be "lin" [default], "log" or "db")') - - options, argv = opt.parse_args(sys.argv) - - - if options.filename is None: - print "Can't deal stdin for now..." - sys.exit(1) - try: - header, data = decode_trace(open(options.filename, 'rb').read()) - except Exception, e: - print "ERROR: can't read %s an interpret it as a HP3562 trace"%options.filename - print e - sys.exit(1) - - if options.displayheader: - print format_header(header, HEADER, 100) - if options.plot: - f0 = header['Start freq value'] - dx = header['Delta X-axis'] - n = header['Number of elements'] - x = numpy.linspace(f0, f0+dx*n, len(data)) - y = data.copy() - - import pylab - if options.ymode != "lin": - minv = min(y[y>0]) - y[y==0] = minv - y = numpy.log10(y) - if options.ymode == "db": - y = y*10 - pylab.ylabel('db') - pylab.grid() - pylab.plot(x, y) - pylab.xlabel('frequency') - pylab.show() - - diff -r 78e3e839658b -r 07e2cbf140df HP3562A/state_decoder.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HP3562A/state_decoder.py Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +""" +state_decoder +============= + +Module for decoding the internal state of the HP3562A DSA, using the +GPIB command "DSBN" (Dump State BiNary). + +This file can be exectued as a python script. Use '-h' for more informations. +""" +from HP3562A import format_header, decode_float, decode_string, decode_header + +from HP3562A.enum_types import * + +HEADER = [("Measurement mode", EMEAS, 'h', 2), + ("Measurement 1", EMTYP, 'h', 2), + ("Measurement 2", EMTYP, 'h', 2), + ("Window type", EWINTYP, 'h', 2), + ("Force/Expon window 1", EFEXPW, 'h', 2), + ("Force/Expon window 2", EFEXPW, 'h', 2), + ("Average type", EAVGTYP, 'h', 2), + ("Overlap percentage", int, 'h', 2), + ("Number of averages", int, 'h', 2), + ("Sweep # of averages", int, 'h', 2), + ("Trigger type", ETRGTYP, 'h', 2), + ("Trigger slope", ETRGSLP, 'h', 2), + ("Preview type", EPRVTYP, 'h', 2), + ("Sample type", ESMPTYP, 'h', 2), + ("Range units chan 1", ERNGUNT, 'h', 2), + ("Range units chan 2", ERNGUNT, 'h', 2), + ("Range type 1", ERNGTYP, 'h', 2), + ("Range type 2", ERNGTYP, 'h', 2), + ("Input coupling 1", EINCPL, 'h', 2), + ("Input coupling 2", EINCPL, 'h', 2), + ("Source type", ESRCTYP, 'h', 2), + ("Chirp percent", int, 'h', 2), + ("Burst percent", int, 'h', 2), + ("Sweep direction", ESWPDIR, 'h', 2), + ("Sweep mode", ESWPMOD, 'h', 2), + ("Ext sample freq untis", EXAXIS, 'h', 2), + ("Bandwidth units", EXAXIS, 'h', 2), + ("Log span index", int, 'h', 2), + ("Log start index", int, 'h', 2), + ("Sweep rate units", EXAXIS, 'h', 2), + ("Auto gain ref chan", EDEMODCH, 'h', 2), + ("Demod channels", EDEMODCH, 'h', 2), + ("Demod type chan 1", EDEMOD, 'h', 2), + ("Demod type chan 2", EDEMOD, 'h', 2), + ("Source level units", EXAXIS, 'h', 2), + ("Source offset units", EXAXIS, 'h', 2), + ("Trigger level units", EXAXIS, 'h', 2), + ("Capt/thru length units", EXAXIS, 'h', 2), + ("EU label 1", str, 's', 6), + ("EU label 2", str, 's', 6), + ("Auto carrier on/off", bool, 'h', 2), + ("Time average on/off", bool, 'h', 2), + ("Auto/fixed resolution", bool, 'h', 2), + ("Auto gain on/off", bool, 'h', 2), + ("Auto/fixed integrate",bool, 'h', 2), + ("Fast average on/off", bool, 'h', 2), + ("Overload reject on/off", bool, 'h', 2), + ("Chan 1 float/ground", bool, 'h', 2), + ("Chan 2 float/ground", bool, 'h', 2), + ("Time throughput on/off", bool, 'h', 2), + ("Demodulation on/off", bool, 'h', 2), + ("EU/volts chan 1", bool, 'h', 2), + ("EU/volts chan 2", bool, 'h', 2), + ("Manual/auto arm", bool, 'h', 2), + ("Demod preview on/off", bool, 'h', 2), + ("Delete freq on/off", bool, 'h', 2), + ("Lin res Fstart pegged", bool, 'h', 2), + ("Swept Fstart pegged", bool, 'h', 2), + ("Force length chan 1", decode_float, None, 4), + ("Force length chan 2", decode_float, None, 4), + ("Expon time constant 1", decode_float, None, 4), + ("Expon time constant 2", decode_float, None, 4), + ("Sweep time", decode_float, None, 4), + ("Sweep rate", decode_float, None, 4), + ("Sweep resolution", decode_float, None, 4), + ("Sweep integrate time", decode_float, None, 4), + ("Auto gain level", decode_float, None, 4), + ("Auto gain limit", decode_float, None, 4), + ("Source level", decode_float, None, 4), + ("EU value chan 1", decode_float, None, 4), + ("EU value chan 2", decode_float, None, 4), + ("Trigger delay chan 1", decode_float, None, 4), + ("Trigger delay chan 2", decode_float, None, 4), + ("Integrate var thresh", decode_float, None, 4), + ("Capt/thru length", decode_float, None, 4), + ("Frequency span", decode_float, None, 4), + ("Time record length", decode_float, None, 4), + ("Frequency resolution", decode_float, None, 4), + ("Time resolution", decode_float, None, 4), + ("External sample rate", decode_float, None, 4), + ("Sample rate (actual)", decode_float, None, 4), + ("Range channel 1", decode_float, None, 4), + ("Range channel 2", decode_float, None, 4), + ("Preview time", decode_float, None, 4), + ("Trigger level", decode_float, None, 4), + ("Source dc offset", decode_float, None, 4), + ("Fixed sine frequency", decode_float, None, 8), + ("Start frequency", decode_float, None, 8), + ("Center frequency", decode_float, None, 8), + ("Sweep start", decode_float, None, 8), + ("Sweep end", decode_float, None, 8), + ("Carrier frequency", decode_float, None, 8), + ] + +def decode_state(data): + """ + Decode the data (as generated by the HP3562A DSA in response to a + "DSBN" command), and returns a dict (header) + + header is the dictionnary of the header of the dumped data block, + """ + header, idx = decode_header(data, HEADER) + return header + + +def main(): + import sys + import optparse + opt = optparse.OptionParser("A simple tool for tracing a dumped trace") + opt.add_option('-f', '--filename', default=None, + dest='filename', + help='Output filename. If not set, read from stdin') + 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) + + + if options.filename is None: + print "Can't deal stdin for now..." + sys.exit(1) + #try: + if 1: + header = decode_state(open(options.filename, 'rb').read()) + else: + #except Exception, e: + print "ERROR: can't read %s an interpret it as a HP3562 trace"%options.filename + print e + sys.exit(1) + + print format_header(header, HEADER, 100) + +if __name__ == "__main__": + main() + diff -r 78e3e839658b -r 07e2cbf140df HP3562A/trace_decoder.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HP3562A/trace_decoder.py Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +""" +trace_decoder +============= + +Module for decoding a trace generated by the HP3562A DSA, using the +GPIB command "DDBN" (Dump Data BiNary). + +This file can be exectued as a python script. Use '-h' for more informations. +""" +import struct +import numpy +from HP3562A import format_header, decode_float, decode_string, decode_header +from HP3562A.enum_types import * + + +HEADER = [ ("Display function", EDSP, 'h', 2), + ('Number of elements', int, 'h', 2), + ('Displayed elements', int, 'h', 2), + ('Number of averages', int, 'h', 2), + ('Channel selection', ECH, 'h', 2), + ('Overflow status', EOVR, 'h', 2), + ('Overlap percentage', int, 'h', 2), + ('Domain', EDOM, 'h', 2), + ('Volts peak/rms', EVLT, 'h', 2), + ('Amplitude units', EAMP, 'h', 2), + ('X axis units', EXAXIS, 'h', 2), + ('Auto math label', str, 's', 14), + ('Trace label', str, 's', 22), + ('EU label 1', str, 's', 6), + ('EU label 2', str, 's', 6), + ('Float/Interger', bool, 'h', 2), + ('Complex/Real', bool, 'h', 2), + ('Live/Recalled', bool, 'h', 2), + ('Math result', bool, 'h', 2), + ('Real/Complex input', bool, 'h', 2), + ('Log/Linear data', bool, 'h', 2), + ('Auto math', bool, 'h', 2), + ('Real time status', bool, 'h', 2), + ('Measurement mode', EMEAS, 'h', 2), + ('Window', EWIN, 'h', 2), + ('Demod type channel 1', EDEMOD, 'h', 2), + ('Demod type channel 2', EDEMOD, 'h', 2), + ('Demod active channel 1', bool, 'h', 2), + ('Demod active channel 2', bool, 'h', 2), + ('Average status', EAVG, 'h', 2), + ('Not used', int, 'hh', 4), + ('Samp freq/2 (real)', decode_float, None, 4), + ('Samp freq/2 (imag)', decode_float, None, 4), + ('Not used', decode_float, None, 4), + ('Delta X-axis', decode_float, None, 4), + ('Max range', decode_float, None, 4), + ('Start time value', decode_float, None, 4), + ('Expon wind const 1', decode_float, None, 4), + ('Expon wind const 2', decode_float, None, 4), + ('EU value chan 1', decode_float, None, 4), + ('EU value chan 2', decode_float, None, 4), + ('Trig delay chan 1', decode_float, None, 4), + ('Trig delay chan 2', decode_float, None, 4), + ('Start freq value', decode_float, None, 8), + ('Start data value', decode_float, None, 8), + ] + +def decode_trace(data): + """ + Decode the data (as generated by the HP3562A DSA in response to a + "DDBN" command), and returns a couple (header, values). + + header is the dictionnary of the header of the dumped data block, + value is a numpy array holding the trace (vector of float or + complex values). + """ + header, idx = decode_header(data, HEADER) + resu = [] + for i in range(header["Number of elements"]): + resu.append(decode_float(data[idx: idx+4])) + idx += 4 + return header, numpy.array(resu, dtype=float) + + + +def main(): + import sys + import optparse + opt = optparse.OptionParser("A simple tool for tracing a dumped trace") + opt.add_option('-f', '--filename', default=None, + dest='filename', + help='Output filename. If not set, read from stdin') + opt.add_option('-m', '--mode', default='binary', + dest='mode', + help='Dumping mode (may be "binary" [default], "ascii" or "ansi")', + ) + opt.add_option('-d', '--display-header', default=False, + action="store_true", + dest="displayheader", + help="Display the trace header") + opt.add_option('-P', '--noplot-trace', default=True, + action="store_false", + dest="plot", + help="Do not display the plot of the trace") + opt.add_option('-x', '--xmode', default='lin', + dest='xmode', + help='X coordinate mode (may be "lin" [default] or "log")') + opt.add_option('-y', '--ymode', default='lin', + dest='ymode', + help='Y coordinate mode (may be "lin" [default], "log" or "db")') + + options, argv = opt.parse_args(sys.argv) + + + if options.filename is None: + print "Can't deal stdin for now..." + sys.exit(1) + try: + header, data = decode_trace(open(options.filename, 'rb').read()) + except Exception, e: + print "ERROR: can't read %s an interpret it as a HP3562 trace"%options.filename + print e + sys.exit(1) + + if options.displayheader: + print format_header(header, HEADER, 100) + if options.plot: + f0 = header['Start freq value'] + dx = header['Delta X-axis'] + n = header['Number of elements'] + x = numpy.linspace(f0, f0+dx*n, len(data)) + y = data.copy() + + import pylab + if options.ymode != "lin": + minv = min(y[y>0]) + y[y==0] = minv + y = numpy.log10(y) + if options.ymode == "db": + y = y*10 + pylab.ylabel('db') + pylab.grid() + pylab.plot(x, y) + pylab.xlabel('frequency') + pylab.show() + + +if __name__ == "__main__": + main() diff -r 78e3e839658b -r 07e2cbf140df bin/dump_datablock --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/bin/dump_datablock Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,4 @@ +#!/usr/bin/python + +from HP3562A.dump_datablock import main +main() diff -r 78e3e839658b -r 07e2cbf140df bin/read_state --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/bin/read_state Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,4 @@ +#!/usr/bin/python + +from HP3562A.state_decoder import main +main() diff -r 78e3e839658b -r 07e2cbf140df bin/read_trace --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/bin/read_trace Tue Dec 18 00:23:10 2007 +0100 @@ -0,0 +1,4 @@ +#!/usr/bin/python + +from HP3562A.trace_decoder import main +main() diff -r 78e3e839658b -r 07e2cbf140df prologix.py --- a/prologix.py Mon Dec 17 18:59:45 2007 +0100 +++ b/prologix.py Tue Dec 18 00:23:10 2007 +0100 @@ -1,5 +1,5 @@ """ -Prologix +prologix ======== Module defining a communication object to talk to Prologix USB-GPIB controler.