Port manager
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 inself.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 automatically available within all functions of the sequencer procedure as the variable:
self.port
A message can be sent by using:
self.port.write("string of the message without end-of-line/terminator character")
The end-of-line character ("EOL") will be set by changing the port properties
The answer of a device is acquired by:
var = self.port.read()
The returned object is typically a string, so please do not forget to change the type if needed by using e.g. int() or float().
A command and its answer can be combined by:
var = self.port.query("*IDN?")
In case you need direct access to the port object created by the port manager, use:
self.port.port
Thus, you can use commmands as defined by pyserial for COM port communication or pyvisa for GPIB/USB communication.
For example, one can manipulate the termination character, e.g.:
self.port.port.write_termination = "\r\n"
self.port.port.read_termination = "\r\n"
# "\r\n" is here one example for using Carriage Return (CR) and Line Feed (LF) as terminator
However, it is recommended to do this using self.port_properties and the keys 'GPIB_EOLwrite' and 'GPIB_EOLread'. Otherwise, the solution only works for pyvisa related GPIB port and would break when using other GPIB port such as the one created for a Prologix GPIB controller.
COM port
In order to check the number of already received bytes, you can use:
number_of_received_bytes = self.port.in_waiting()
As SweepMe! is based on python 3, all strings that are send via self.port.write() are actually unicode strings. The Port Manager automatically converts them to bytes before sending them using the library pyserial. Similarly, received bytes are automatically converted back to unicode strings. If you like to have raw access to the bytes that are sent and received, please use the port properties 'raw_read' and 'raw_write'.
Sometimes it is needed to only read the raw answers (i.e. bytes) of a few commands. In that case you can use the functions like 'read_raw' and 'write_raw'
self.port.write_raw(...) # make sure that you send a byte string
answer = self.port.read_raw() # answer will be a byte string that you need to decode or process yourself.
answer = self.port.read_raw(10) # example to read 10 bytes
read_raw() is available for COM and USBTMC ports. For other port types, it raises a NotImplementedError; use the underlying port object self.port.port instead.
Exceptions
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.
To handle timeouts yourself, catch the exception in the driver. For VISA based ports (GPIB, USBTMC, TCPIP, PXI), a timeout raises pyvisa.errors.VisaIOError. For COM ports, you can alternatively set the port property 'Exception' to False, so that an empty answer is returned instead of raising an error:
self.port_properties = {
... # all other properties
"Exception": False,
}
If an instrument does not answer in time, do not send the query again: many instruments queue commands and answer each copy later, so the extra answers end up in the next read. Instead, retry only the read and check whether the user stopped the run:
self.port.write("READ?")
answer = ""
for _ in range(3):
if self.is_run_stopped():
break
try:
answer = self.port.read()
break
except Exception:
continue # e.g. timeout, try to read again
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.