comparison scpi.py @ 17:20df02be818a

Work out the header using an RE and scrub it automatically. Add a function to fetch 1 data item of a given type.
author Daniel O'Connor <darius@dons.net.au>
date Wed, 10 Aug 2011 15:17:57 +0930
parents 37d6ceb4850f
children a124aa7067e7
comparison
equal deleted inserted replaced
16:c2c13d804fce 17:20df02be818a
25 # SUCH DAMAGE. 25 # SUCH DAMAGE.
26 # 26 #
27 27
28 import exceptions 28 import exceptions
29 import numpy 29 import numpy
30 import re
30 31
31 def bindecode(data, header = '', dtype = numpy.float32): 32 headerre = re.compile('^(:[A-Z:]+ ).*')
33
34 def clean(data):
35 # The instrument might return some header before the data (TEK 2024B does this)
36 m = headerre.match(data)
37 if m == None:
38 return data
39 else:
40 hlen = len(m.groups()[0])
41 return(data[hlen:])
42
43 def getdata(data, dtype = float):
44 '''Get a single data item'''
45 data = clean(data)
46 return dtype(data)
47
48 def bindecode(data, dtype = numpy.float32):
32 '''Decode binary data, returns numpy array''' 49 '''Decode binary data, returns numpy array'''
33 if data[0:len(header)] != header: 50
34 raise exceptions.ValueError('data header incorrect') 51 data = clean(data)
35 ofs = len(header) 52
36 if data[ofs] != '#': 53 if data[0] != '#':
37 raise exceptions.ValueError('data length header incorrect') 54 raise exceptions.ValueError('data length header incorrect')
38 dlenlen = int(data[ofs + 1]) 55 dlenlen = int(data[1])
39 dlen = int(data[ofs + 2:ofs + dlenlen + 2]) 56 dlen = int(data[2:dlenlen + 2])
40 if len(data) != len(header) + dlen + 2 + dlenlen: 57 if len(data) != dlen + 2 + dlenlen:
41 raise exceptions.ValueError('length mismatch, header says %d, actually got %d bytes' % (len(header) + dlen + 2 + dlenlen, len(data))) 58 raise exceptions.ValueError('length mismatch, header says %d, actually got %d bytes' % (dlen + 2 + dlenlen, len(data)))
42 return numpy.frombuffer(data[len(header) + 2 + dlenlen:], dtype = dtype) 59 return numpy.frombuffer(data[2 + dlenlen:], dtype = dtype)
43 60
44 def ascdecode(data, dtype = numpy.float32): 61 def ascdecode(data, dtype = numpy.float32):
45 '''Decode ASCII data, returns numpy array''' 62 '''Decode ASCII data, returns numpy array'''
63
64 data = clean(data)
46 return numpy.fromstring(data, dtype = dtype, sep = ',') 65 return numpy.fromstring(data, dtype = dtype, sep = ',')
47 66