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"), #... ] + +