changeset 27:e2833d081413

- Handle zero length data from the instrument. - Handle trailing newlines. - Add helper function to allow URL like instrument connections.
author Daniel O'Connor <darius@dons.net.au>
date Wed, 21 Sep 2011 14:56:21 +0930
parents 226ea06bc050
children c6be52360c2f
files scpi.py
diffstat 1 files changed, 42 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/scpi.py	Wed Sep 21 14:54:34 2011 +0930
+++ b/scpi.py	Wed Sep 21 14:56:21 2011 +0930
@@ -30,6 +30,11 @@
 import re
 
 headerre = re.compile('^(:[A-Z:]+ ).*') 
+insturlre = re.compile('([a-zA-Z0-9]+)://(([^:]+)?(:([^/]+)@))?([^:]+)(:(.+))?')
+
+def query(d, q, timeout = None):
+    d.write(q)
+    return d.read(timeout)
 
 def clean(data):
     # The instrument might return some header before the data (TEK 2024B does this)
@@ -53,9 +58,20 @@
     if data[0] != '#':
         raise exceptions.ValueError('data length header incorrect')
     dlenlen = int(data[1])
+    if dlenlen == 0:
+        return numpy.array([])
+    
     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)))
+    if dlen == 0:
+        return numpy.array([])
+
+    wanted = dlen + 2 + dlenlen
+    # Chop off the trailing \n if necessary
+    if len(data) == wanted + 1 and data[-1] == '\n':
+        data = data[0:-1]
+        
+    if len(data) != wanted:
+        raise exceptions.ValueError('length mismatch, header says %d, actually got %d bytes' % (wanted, len(data)))
     return numpy.frombuffer(data[2 + dlenlen:], dtype = dtype)
 
 def ascdecode(data, dtype = numpy.float32, sep = None):
@@ -76,3 +92,27 @@
             sep = ' '
     return numpy.fromstring(data, dtype = dtype, sep = sep)
     
+
+def instURL(url):
+    m = insturlre.match(url)
+    if m == None:
+        raise exceptions.ValueError('Unable to parse URL')
+    proto, xxx, user, xxx, pwd, address, xxx, port = m.groups()
+    if proto == 'rsib':
+        import rsib
+        return rsib.RSIBDevice(address, port)
+    elif proto == 'usb':
+        import usb488
+        return usb488.USB488Device()
+    elif proto == 'vxi':
+        import vxi
+        if port == None:
+            port = 'inst0'
+        return vxi.VXIDevice(address, device = port)
+    elif proto == 'scpi':
+        import scpisock
+        return scpisock.SCPISockDevice(address, port)
+    else:
+        raise exceptions.NotImplementedError("unknown protocol " + proto)
+    
+