2. Instrument control

The instrument control API provides functions that allow Python to communicate with instrument on the Labber Instrument server.

2.1. Labber client

The instrument control API uses a client object to communicate with the Instrument server. To initialize the client, use the connectToServer -function. The following example will connect to an instrument server on the local computer and list all available instruments.

import Labber
# connect to server
client = Labber.connectToServer('localhost')
# get list of instruments
instruments = client.getListOfInstrumentsString()
for instr in instruments:
    print(instr)
# close connection
client.close()

2.2. Connecting to instruments

To set or read values from an individual instrument, first use the function connectToInstrument of the Labber client object to access the instrument. The function will return an instance of a InstrumentClient object, from which the entire configuration or individual quantities of the instrument can be set or read.

The following example will first connect to a Labber Instrument server, and then connect to a dc voltage source and a volt meter using a GPIB interface. Next, it will output voltages with the dc source, and measure the corresponding response with the volt meter.

import Labber
import time, numpy as np
# connect to server
client = Labber.connectToServer('localhost')
# connect to specific instruments
volt_source = client.connectToInstrument('Yokogawa 7651 DC Source',
              dict(interface='GPIB', address='6'))
volt_meter = client.connectToInstrument('Agilent 34401 Multimeter',
             dict(interface='GPIB', address='1'))

# start drivers
volt_meter.startInstrument()
volt_source.startInstrument()

# put zero voltage to source and turn on the output
volt_source.setValue('Voltage', 0.0)
volt_source.setValue('Output', True)

# do a loop from zero to one volt
for volt in np.linspace(0.0, 1.0, 11):
    # set value to voltage source and wait
    volt_source.setValue('Voltage', volt)
    time.sleep(0.2)
    # read value from voltmeter
    measVolt = volt_meter.getValue('Voltage')
    # print result
    print('Set value: %.2f V, measured value: %.2f V' % (volt, measVolt))

# close client
client.close()

See the reference documentation below for more information on functions available in the InstrumentClient class.

2.3. Blocking vs. non-blocking clients

Labber supports two types of clients. The standard client type discussed so far is a blocking client, which will block program execution while waiting for a response from the server. Blocking clients are typically used in scripts where a number of instrument values are set or read in a pre-defined sequential order.

Function calls to a non-blocking client, on the other hand, will not wait for a response from the instrument server. Instead, the client uses a system of callback functions to notify the program that a new instrument value has been set or read. The advantage of a non-blocking client is that the main program thread will not be blocked while waiting for a result, and that multiple instrument operations can be performed in parallel. Non-blocking clients are typically used in user-interface driven applications, where the dialogs and user-interface elements need to remain responsive.

To create a non-blocking client, use the same connectToServer-function described above but with the argument wait_for_reply set to False. The following script will perform the same procedure of setting and reading voltages as the blocking-client script shown above, but it will do it in a non-blocking framework. Instead of directly returning values, the connectToServer, connectToInstrument, setValue and getValue functions will use callback functions to retrieve values.

Note that the event handling of the non-blocking client and the callback functionality is handled by the Qt framework.

import Labber
from qtpy.QtCore import QCoreApplication
import functools
import numpy as np

class TestNonBlockClient():
    def __init__(self):
        # keep track of instrument references
        self.dInstr = dict()

    def connect(self):
        # connect to server, call 'connectionOpen' upon completion
        self.client = Labber.connectToServer('localhost', wait_for_reply=False,
                      callback_open=self.connectionOpen,
                      callback_network_error=self.on_error,
                      callback_instrument_error=self.on_error)

    def connectionOpen(self, data):
        # callback after connection has been established
        print('Connection open')
        self.nStart = 0
        # connect to instruments, call 'connected' upon completion
        newCallback = functools.partial(self.connected, 'Agilent 34401')
        self.client.connectToInstrument('Agilent 34401 Multimeter',
                                        dict(address='1', interface='GPIB'),
                                        callback=newCallback)
        newCallback = functools.partial(self.connected, 'Yokogawa 7651')
        self.client.connectToInstrument('Yokogawa 7651 DC Source',
                                        dict(address='3', interface='GPIB'),
                                        callback=newCallback)

    def on_error(self, message):
        # print error
        print('Error: %s.\n\n' % message)

    def connected(self, sHardware, instr):
        # keep track of instruments
        self.dInstr[sHardware] = instr
        # start driver, call 'started' upon completion
        newCallback = functools.partial(self.started, sHardware)
        instr.startInstrument(callback=newCallback)

    def started(self, sHardware, data):
        # check that both instruments have been started
        self.nStart += 1
        if self.nStart==2:
            self.yoko = self.dInstr['Yokogawa 7651']
            self.volt = self.dInstr['Agilent 34401']
            # set yoko loop
            self.lLoop = np.linspace(0.0, 1.0, 11)
            self.nIndex = -1
            # start loop
            self.loop()

    def loop(self):
        # check if looping is done
        self.nIndex += 1
        if self.nIndex < len(self.lLoop):
            # keep looping
            self.yoko.setValue('Value', self.lLoop[self.nIndex],
                               callback=self.stepDone)
        else:
            print('Finished!')

    def stepDone(self, data):
        # voltage has been set, read response
        self.yoko.getValue('Value', callback=self.logDone)

    def logDone(self, measVolt):
        # print result
        volt = self.lLoop[self.nIndex]
        print('Set value: %.2f V, measured: %.2f V' % (volt, measVolt))
        # keep looping
        self.loop()


if __name__ == '__main__':
    # start Qt event loop
    app = QCoreApplication([])
    # create test object and connect to server
    test = TestNonBlockClient()
    test.connect()

2.4. Function definitions

Labber.connectToServer(address=u'localhost', wait_for_reply=True, port=9406, timeout=10, callback_open=None, callback_network_error=None, callback_instrument_error=None, binary_transfer_format=True)

Connect to Labber Instrument server and return a Labber client object.

There are two version of Labber clients, blocking and non-blocking ones. Blocking clients will wait for the instrument server to send a reply before returning, whereas non-blocking client will return immediately and call callback functions once the values are available.

Parameters:
  • address (str, optional) – IP address of Labber Instrument server. Default is localhost.
  • wait_for_reply (bool, optional) – If True, the function will return a blocking client. Default is True.
  • port (int, optional) – Port number for server communication. Default is 9406.
  • timeout (int or float, optional) – Longest time to wait for the server to reply. Default is 10 seconds.
  • callback_open (function, optional) – Callback function called after communication has been established. The function should have a single boolean argument, which will state if the connection was successful or not. Only relevant if wait_for_reply is False, ie for non-blocking clients.
  • callback_network_error (function, optional) – Callback function called in case of network error. The function should take a single argument that will contain the error message. Only relevant if wait_for_reply is False, ie for non-blocking clients.
  • callback_instrument_error (function, optional) – Callback function called in case of instrument error. The function should take a single argument that will contain the error message. Only relevant if wait_for_reply is False, ie for non-blocking clients.
  • binary_transfer_format (bool, optional) – If True, data between the client and the server is sent as binary data instead of text. The value must match the Data transfer format in the Labber Instrument server preferences. Default is True.
Returns:

client – Labber client object, either blocking or non-blocking version.

Return type:

Client object

Examples

Open connection to server and list connected instruments.

>>> import Labber
>>> client = Labber.connectToServer('localhost')
>>> instruments = client.getListOfInstrumentsString()
>>> print(instruments)
>>> client.close()

2.5. Class definitions

2.5.1. Blocking client

The client object should not be initialized directly. Instead, use the connectToServer()-function defined above.

class Labber.LabberBlockingClient(sAddress=u'localhost', port=9406, timeout=10, binary_transfer_format=None, convert_to_unicode_if_py2=True)

Bases: object

Labber client, blocking execution while waiting for server response.

Parameters:
  • sAddress (str, optional) – IP address of Labber Instrument server. Default is localhost.
  • port (int, optional) – Port number for server communication. Default is 9406.
  • timeout (int or float, optional) – Longest time to wait for the server to reply. Default is 10 seconds.
  • binary_transfer_format (bool, optional) – If True, data between the client and the server is sent as binary data instead of text. Default is True.
close()

Close the connection to the server.

connectToInstrument(sHardware, dComCfg, bCreateNew=False)

Connect to an instrument object on the instrument server.

Parameters:
  • sHardware (str) – Name of instrument hardware to connect to.
  • dComCfg (dict) –

    Dictionary describing the communication address of the instrument. Either the name key or the interface`+`address keys must be defined. The dictionary is defined by the following keys:

    name
    : str
    Name of instrument.
    interface
    : {‘GPIB’, ‘TCPIP’, ‘USB’, ‘Serial’, ‘VISA’, ‘Other’, ‘None’}
    Communication interface.
    address
    : str
    Instrument address string
    startup
    : {‘Set config’, ‘Get config’, ‘Do nothing’}
    Operation to perform at instrument startup.
    lock
    : bool
    If True, instrument will be locked while in use.
  • bCreateNew (bool, optional) – If True, a new instrument will be created if the requested one is not already present. Default is False.
Returns:

instr – Object representing an instrument on the Labber instrument server.

Return type:

InstrumentClient object

createInstrument(sHardware, dComCfg)

Create an instrument on the instrument server.

Parameters:
  • sHardware (str) – Name of instrument hardware to connect to.
  • dComCfg (dict) –

    Dictionary describing the communication address of the instrument. The dictionary is defined by the following keys:

    name
    : str
    Name of instrument.
    interface
    : {‘GPIB’, ‘TCPIP’, ‘USB’, ‘Serial’, ‘VISA’, ‘Other’, ‘None’}
    Communication interface.
    address
    : str
    Instrument address string.
    startup
    : {‘Set config’, ‘Get config’, ‘Do nothing’}
    Operation to perform at instrument startup.
    lock
    : bool
    If True, instrument will be locked while in use.
getListOfInstruments()

Get a list of instruments present on the Labber instrument server.

Returns:instruments – List of instruments on the server. Each element of the list is a two-element tuple (name, comcfg), where name is the hardware name and comcfg is a dict with communication settings.
Return type:list of tuple
getListOfInstrumentsString()

Get a list of instruments present on the Labber instrument server.

Returns:instruments – List of strings describing instruments on the server.
Return type:list of str

2.5.2. Non-blocking client

The client object should not be initialized directly. Instead, use the connectToServer()-function defined above.

class Labber.LabberClient(callbackNetworkError, callbackInstrError, sAddress=u'localhost', port=None, timeout=None, callbackOpen=None, callbackMessage=None, parent=None, convert_to_unicode_if_py2=True, binary_transfer_format=None)

Bases: PyQt4.QtCore.QObject

Labber client, non-blocking version.

Parameters:
  • callbackNetworkError (function) – Callback function called in case of network error. The function should take a single argument that will contain the error message.
  • callbackInstrError (function) – Callback function called in case of instrument error. The function should take a single argument that will contain the error message.
  • sAddress (str, optional) – IP address of Labber Instrument server. Default is localhost.
  • port (int, optional) – Port number for server communication. Default is 9406.
  • timeout (int or float, optional) – Longest time to wait for the server to reply. Default is 10 seconds.
  • callbackOpen (function, optional) – Callback function called after communication has been established. The function should have a single boolean argument, which will state if the connection was successful or not.
  • callbackMessage (function, optional) – Callback function for status updates from the server. The function should have a single string argument with the status.
  • binary_transfer_format (bool, optional) – If True, data between the client and the server is sent as binary data instead of text. Default is True.
close(bForce=False)

Close the connection to the server.

Parameters:bForce (bool, optional) – If True, the connection is shut down without waiting for it to close. Default is False.
connectToInstrument(sHardware, dComCfg, callback, bCreateNew=False)

Connect to an instrument object on the instrument server.

Parameters:
  • sHardware (str) – Name of instrument hardware to connect to.
  • dComCfg (dict) –

    Dictionary describing the communication address of the instrument. Either the name key or the interface`+`address keys must be defined. The dictionary is defined by the following keys:

    name
    : str
    Name of instrument.
    interface
    : {‘GPIB’, ‘TCPIP’, ‘USB’, ‘Serial’, ‘VISA’, ‘Other’, ‘None’}
    Communication interface.
    address
    : str
    Instrument address string
    startup
    : {‘Set config’, ‘Get config’, ‘Do nothing’}
    Operation to perform at instrument startup.
    lock
    : bool
    If True, instrument will be locked while in use.
  • callback (function) – Callback function called after the instruments has been created. The first argument will be an InstrumentClient object representing the instrument on the Labber instrument server.
  • bCreateNew (bool, optional) – If True, a new instrument will be created if the requested one is not already present. Default is False.
createInstrument(sHardware, dComCfg, callback=None)

Create an instrument on the instrument server.

Parameters:
  • sHardware (str) – Name of instrument hardware to connect to.
  • dComCfg (dict) –

    Dictionary describing the communication address of the instrument. The dictionary is defined by the following keys:

    name
    : str
    Name of instrument.
    interface
    : {‘GPIB’, ‘TCPIP’, ‘USB’, ‘Serial’, ‘VISA’, ‘Other’, ‘None’}
    Communication interface.
    address
    : str
    Instrument address string
    startup
    : {‘Set config’, ‘Get config’, ‘Do nothing’}
    Operation to perform at instrument startup.
    lock
    : bool
    If True, instrument will be locked while in use.
  • callback (function, optional) – Callback function called after the instruments has been created. The first argument will be an InstrumentClient object representing the instrument on the Labber instrument server.
firstCallbackStatus(callbackProgress, callbackCurrentValue, data)

First callback occurring after the server sends back status updates. The function will handle errors and then call the next callback

getListOfInstruments(callback)

Get a list of instruments present on the Labber instrument server.

Parameters:callback (function) – Callback function called after the list of instruments has been retrieved. The first argument will be the list of instruments.
Returns:instruments – List of instruments on the server. Each element of the list is a two-element tuple (name, comcfg), where name is the hardware name and comcfg is a dict with communication settings.
Return type:list of tuple
getListOfInstrumentsString(callback)

Get a list of instruments present on the Labber instrument server.

Parameters:callback (function) – Callback function called after the list of instruments has been retrieved. The first argument will be the list of instruments.
Returns:instruments – List of strings describing instruments on the server.
Return type:list of str

2.5.3. Instrument client

The InstrumentClient represents an instrument on the server. Note that the InstrumentClient object should not be initialized directly, but rather created using the connectToInstrument or createInstrument functions of a LabberClient object.

class Labber.InstrumentClient(client, instrRef, ldQuant, dOption, block=True)

The InstrumentClient is representing an instrument on the server.

abortCurrentOperation(callback=None)

Abort current operation, but keep instrument running.

Parameters:callback (function, optional) – Callback function called after the instruments has been aborted. Only relevant for non-blocking clients.
arm(quantities, callback=None, options={})

Arm instrument to prepare for later hardware-triggered data acquisition

Parameters:
  • quantities (list of str) – Name of quantities that will be acquired when the instrument is triggered.
  • callback (function, optional) – Callback function called after the instrument has been armed. Only relevant for non-blocking clients.
disconnectFromInstr(callback=None)

Disconnect from instrument.

Parameters:callback (function, optional) – Callback function called after the instruments has been disconnected. Only relevant for non-blocking clients.
getInstrConfig(callback=None)

Get values from the driver.

Parameters:callback (function, optional) – Callback function called after the instrument config has been retrieved. Only relevant for non-blocking clients.
Returns:values – Dictionary with instrument values. The keys are names of instrument quantities. Note that only blocking clients will return a value.
Return type:dict
getLocalInitValuesDict()

Get instrument values as recorded at instrument initialization.

Returns:values – Dictionary with instrument values. The dict keys are names of the instrument quantities.
Return type:dict
getLocalOptionsDict()

Get instrument options as recorded at instrument initialization.

Returns:options – Dictionary representing instrument options. The dictionary is defined by the following keys:
model
: str
Instrument model number/name.
options
: list of str
List of strings describing installed options.
Return type:dict
getValue(sQuant, callback=None, callbackProgress=None, callbackCurrentValue=None, options={})

Get value of the specified quantity

Parameters:
  • sQuant (str) – Name of quantity to set.
  • callback (function, optional) – Callback function called after the instrument value has been retrieved. Only relevant for non-blocking clients.
  • callbackProgress (function, optional) – Callback function for progress updates from the server. The function must take a single argument, which will be a float between 0.0 and 1.0 indicating progress. Only relevant for non-blocking clients.
  • callbackCurrentValue (function, optional) – Callback function for value updates from the server. The function must take a single argument (current value), and is used to show the current value during slow operations, like averaging. Only relevant for non-blocking clients.
Returns:

value – Value of the instrument. Note that only blocking clients will return a value.

Return type:

float, bool or numpy array.

isRunning(callback=None)

Check if instrument driver is running.

Parameters:callback (function, optional) – Callback function called after the instruments has been checked. Only relevant for non-blocking clients.
Returns:isRunning – True if instrument is running. Note that only blocking clients will return a value.
Return type:bool
setInstrConfig(dValues={}, callback=None)

Send values to the driver.

Parameters:
  • dValues (dict) – Dictionary with new values. The keys are names of instrument quantities.
  • callback (function, optional) – Callback function called after the instrument config has been set. Only relevant for non-blocking clients.
Returns:

values – Dictionary with actual values. The keys are names of instrument quantities.

Return type:

dict. Note that only blocking clients will return a value

setValue(sQuant, value, rate=0.0, wait_for_sweep=True, callback=None, callbackProgress=None, callbackCurrentValue=None, options={})

Set new value to the specified quantity

Parameters:
  • sQuant (str) – Name of quantity to set.
  • value (float, bool or numpy array) – New value.
  • rate (float, optional) – Sweep rate.
  • wait_for_sweep (bool, optional) – If True and rate is non-zero, the instrument is waiting for a sweep to finish.
  • callback (function, optional) – Callback function called after the instrument value has been set. Only relevant for non-blocking clients.
  • callbackProgress (function, optional) – Callback function for progress updates from the server. The function must take a single argument, which will be a float between 0.0 and 1.0 indicating progress. Only relevant for non-blocking clients.
  • callbackCurrentValue (function, optional) – Callback function for value updates from the server. The function must take a single argument (current value), and is used to show the current value during slow operations (sweeping). Only relevant for non-blocking clients.
Returns:

value – Actual value of the instrument. Note that only blocking clients will return a value.

Return type:

float, bool or numpy array.

startInstrument(dOption=None, callback=None)

Start the instrument.

Parameters:
  • dOption (dict, optional) –

    Dictionary representing instrument options. The dictionary is defined by the following keys:

    model
    : str
    Instrument model number/name.
    options
    : list of str
    List of strings describing installed options.
  • callback (function, optional) – Callback function called after the instruments has been started. Only relevant for non-blocking clients.
stopInstrument(bForceQuit=False, callback=None)

Start the instrument.

Parameters:
  • bForceQuit (bool, optional) – If True, the instrument is shut down without waiting for it to close. Default is False.
  • callback (function, optional) – Callback function called after the instruments has been stopped. Only relevant for non-blocking clients.
waitForSweep(sQuant, value=None, callback=None, options={}, callbackCurrentValue=None)

Wait for swept instrument to reach final point or certain value