Port manager

From SweepMe! Wiki
Jump to navigation Jump to search

SweepMe! supports and simplifies communication with devices via RS-232/RS-485 (COM port), GPIB, USBTMC, TCPIP, SOCKET and PXI by using SweepMe!'s port manager.

Introduction

The communication with the hardware is usually done in each driver (formerly called "Device Class"). In order to simplify the process of creating the communication channel, i.e. establish a connection, SweepMe! provides the port manager for easy handling.

Supported port types

  • COM: standard PC serial port using RS-232 or RS-485 protocol (via pyserial)
  • GPIB: IEEE-488 bus via a VISA runtime, or via a Prologix GPIB-USB controller
  • USBTMC: USB test and measurement class devices via a VISA runtime ("USB" can be used as an alias in self.port_types)
  • TCPIP: network instruments registered with the VISA runtime, e.g. TCPIP0::192.168.0.10::INSTR
  • SOCKET: raw TCP socket connection without VISA, given as IP:port, e.g. 192.168.0.10:5025
  • PXI: PXI instruments via a VISA runtime
  • (VB: a National Instruments VirtualBench device, deprecated from 1.5.5: please find and create port objects yourself)

See Supported ports for details and troubleshooting.

Usage

Configuration

The following variables have to be set within the __init__ function of a driver:

In order to get the available ports listed in the GUI of the corresponding Module, choose desired port types by:

self.port_types = ["COM", "GPIB", "USBTMC", "TCPIP", "SOCKET"]

A port object is automatically created by

self.port_manager = True

Port properties

You can set port properties during __init__ of the driver or before connect() is called by modifying the self.port_properties dictionary.

These parameters can be changed through

self.port_properties = {
    "baudrate" : 9600, 
    "EOL": "\n",
    ...
}

or change a parameter of self.port_properties as done in the the following example

self.port_properties["EOL"] = "\r"

In order to see all properties of an established port object, add the following code

print(self.port.port_properties)

in the semantic function "connect" of your driver.

Some important and commonly used parameters are explained here:

Property Interface Type Default value Explanation
EOL COM String "\n" "End of line"-character, will be added to each command sent by self.port.write() and defines the end of each message read by self.port.read()
EOLwrite COM String None replaces the character which will be added to each command sent by self.port.write(), overwrites "EOL"
EOLread COM String None replace the character which defines the end of each message read by self.port.read(), overwrites "EOL"
GPIB_EOLwrite GPIB String None sets the character which will be added to each command sent by self.port.write()
GPIB_EOLread GPIB String None sets the character which defines the end of each message read by self.port.read()
TCPIP_EOLwrite TCPIP String None sets the character which will be added to each command sent by self.port.write()
TCPIP_EOLread TCPIP String None sets the character which defines the end of each message read by self.port.read()
SOCKET_EOLwrite SOCKET String None sets the character which will be added to each command sent by self.port.write()
SOCKET_EOLread SOCKET String None sets the character which defines the end of each message read by self.port.read()
fixed_port SOCKET Integer "" the standard port number to be used for SOCKET communication if the port string only contains the IP address
baudrate COM Integer 9600 The Baudrate defines the speed of the COM port communication, must be identical to the value of the instrument
bytesize COM Integer 8 length of one byte, must be identical to value of the instrument
stopbits COM Integer 1
parity COM String "N" None = "N", Odd = "O", Even = "E", Mark = "M", Space = "S"
xonxoff COM Bool False
rtscts COM Bool False
dsrdtr COM Bool False
rts COM Bool True
dtr COM Bool True
raw_write COM Bool False send the argument as is without further encoding, an eol/terminator-character is still added if specified.
raw_read COM Bool False receive the answer as is without further decoding
rstrip COM Bool True strips trailing characters such as whitespaces, line feeds, carriage return or tab character.
timeout all Float 2 time in seconds before a timeout error is raised
clear all Bool True Send a clear command to the port after opening the port (SweepMe! 1.5.6.15+ / pysweepme 1.5.6.10+)
delay COM, GPIB, PXI, TCPIP, SOCKET Float 0.0 waiting time in seconds after writing a command before the next command is sent, to allow an instrument to process the current command
debug all Bool False print every write and read command of this port to the Debug widget
encoding COM, SOCKET String 'latin-1' encoding used to encode and decode byte based messages
Exception COM Bool True If True, an empty answer without end-of-line character raises an error and the run is stopped. If False, an empty string is returned instead. VISA based ports (GPIB, USBTMC, TCPIP, PXI) always raise a pyvisa VisaIOError on a timeout, SOCKET ports raise a TimeoutError.

Users can override some port properties in the Port Manager (menu "Tools" → "Port Manager"), e.g. the baudrate of a COM port, and switch on the debug output of a port with the checkbox in the column "Debug". These settings override the port properties defined in the driver.

Communication

If the port manager is activated, the port is available in all functions of the sequencer procedure as self.port:

self.port.write("*RST")            # the terminator (EOL) is added automatically
answer = self.port.read()          # one message as a stripped string; convert with float() or int() if needed
answer = self.port.query("*IDN?")  # write and read in one call
self.port.clear()                  # clear the port, e.g. in initialize()

Raw bytes: self.port.write_raw(b"...") sends bytes unchanged, self.port.read_raw() returns one message as bytes including its terminator, and self.port.read_bytes(count) returns exactly count bytes, e.g. for binary blocks. From SweepMe! 1.6.1.8 (pysweepme 1.6.1.4), these functions work with every port type except PXI and GPIB via a Prologix controller, which raise a NotImplementedError. In earlier versions, read_raw() is only available for COM and USBTMC ports.

The underlying pyserial, pyvisa or socket object is available as self.port.port. Calls through it bypass the port manager (no terminator handling, no debug output, not visible in the port terminal), so use it only where no wrapper exists. Set terminators with the port properties, e.g. GPIB_EOLwrite and GPIB_EOLread, which also work with a Prologix GPIB controller.

Exceptions and timeouts

If an exception occurs during port communication and is not caught by the driver, SweepMe! stops the run and prints the message in the Debug widget. VISA based ports (GPIB, USBTMC, TCPIP, PXI) raise pyvisa.errors.VisaIOError on a timeout, SOCKET ports a TimeoutError, and COM ports raise on an empty answer unless the port property Exception is set to False. If an instrument does not answer in time, do not send the query again, because many instruments queue commands and answer each copy later; retry only the read and check self.is_run_stopped(). Reading binary blocks, terminator mismatches and retries are described in section 6.3 of the driver guide.

Using the port manager with pysweepme

The port manager and the port objects are part of the open-source pysweepme package (submodules PortManager and Ports). This means you can open and use the same ports from your own Python scripts, outside of SweepMe!. The port properties and the communication methods (write, read, query, read_raw, write_raw, ...) are exactly the ones documented in the sections above.

Opening a port directly

The quickest way is the top-level get_port / close_port functions. The port type is derived from the resource string (COM1 → serial, GPIB0::1::INSTR → GPIB, an IP:port string → SOCKET, ...):

import pysweepme

port = pysweepme.get_port("COM1")   # creates and opens the port
print(port.query("*IDN?"))          # write + read
pysweepme.close_port(port)

Port properties can be passed as a dictionary, using the same keys as in the Port properties table above:

port = pysweepme.get_port("COM1", {
    "baudrate": 115200,
    "timeout": 5,
    "EOL": "\r\n",
})

The current values of an open port are accessible as port.port_properties.

Managing several ports

The PortManager keeps track of all open ports so that several drivers can share a single physical interface. It is a singleton and mirrors how SweepMe! itself manages ports:

from pysweepme import PortManager

pm = PortManager.PortManager()

resources = pm.find_resources(["COM", "GPIB"])   # {"COM": [...], "GPIB": [...]}
port = pm.get_port("GPIB0::1::INSTR")
print(pm.get_identification("GPIB0::1::INSTR"))
pm.close_all_ports()

Note: VISA-based port types (GPIB, USBTMC, TCPIP, PXI, ...) require a VISA runtime and pyvisa to be installed; COM/serial ports use pyserial. See VISA runtime and Supported ports.

If you like to see how the exact communication is done, feel free to download pysweepme and read the source code of the Ports submodule.

See also