# HG changeset patch # User Daniel O'Connor # Date 1312955277 -34200 # Node ID 20df02be818a130b8f23b06a6f64e580a3371dca # Parent c2c13d804fce36702acc27b1e159fd96ffb0ac0f Work out the header using an RE and scrub it automatically. Add a function to fetch 1 data item of a given type. diff -r c2c13d804fce -r 20df02be818a scpi.py --- a/scpi.py Wed Aug 10 12:51:07 2011 +0930 +++ b/scpi.py Wed Aug 10 15:17:57 2011 +0930 @@ -27,21 +27,40 @@ import exceptions import numpy +import re -def bindecode(data, header = '', dtype = numpy.float32): +headerre = re.compile('^(:[A-Z:]+ ).*') + +def clean(data): + # The instrument might return some header before the data (TEK 2024B does this) + m = headerre.match(data) + if m == None: + return data + else: + hlen = len(m.groups()[0]) + return(data[hlen:]) + +def getdata(data, dtype = float): + '''Get a single data item''' + data = clean(data) + return dtype(data) + +def bindecode(data, dtype = numpy.float32): '''Decode binary data, returns numpy array''' - if data[0:len(header)] != header: - raise exceptions.ValueError('data header incorrect') - ofs = len(header) - if data[ofs] != '#': + + data = clean(data) + + if data[0] != '#': raise exceptions.ValueError('data length header incorrect') - dlenlen = int(data[ofs + 1]) - dlen = int(data[ofs + 2:ofs + dlenlen + 2]) - if len(data) != len(header) + dlen + 2 + dlenlen: - raise exceptions.ValueError('length mismatch, header says %d, actually got %d bytes' % (len(header) + dlen + 2 + dlenlen, len(data))) - return numpy.frombuffer(data[len(header) + 2 + dlenlen:], dtype = dtype) + dlenlen = int(data[1]) + dlen = int(data[2:dlenlen + 2]) + if len(data) != dlen + 2 + dlenlen: + raise exceptions.ValueError('length mismatch, header says %d, actually got %d bytes' % (dlen + 2 + dlenlen, len(data))) + return numpy.frombuffer(data[2 + dlenlen:], dtype = dtype) def ascdecode(data, dtype = numpy.float32): '''Decode ASCII data, returns numpy array''' + + data = clean(data) return numpy.fromstring(data, dtype = dtype, sep = ',')