diff 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
line wrap: on
line diff
--- 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 = ',')