Python API¶
本页是 SmartUSBHub Python 控制库的 API 文档入口。
Module¶
High-level driver for controlling a Smart USB Hub over a UART serial link.
The SmartUSBHub class provides robust per-port control of power and data connections, voltage/current monitoring, configuration of default states, charge-mode switching and factory reset. It is intended for automated test systems and hardware development workflows.
Wire protocol
Three framing variants share the same serial channel; frames are distinguished by their start-of-frame (SOF) bytes:
V1 (6 bytes):
0x550x5ACMDCHANNELVALUECHECKSUM, whereCHECKSUM= (CMD + CHANNEL + VALUE) & 0xFF. Used for most set/get commands.CHANNELis a bitmask (bit0 = channel 1, bit1 = channel 2, …).V2 (7 bytes):
0x550x5ACMDCHANNELVALUE0VALUE1CHECKSUM. Used for 16-bit payloads (voltage/current) and for the enable/value pairs of the default power/dataline commands.V3 (>=10 bytes):
0x550xAB0xCD0xEFSOF magic, followed byCMD,FLAGS, a little-endian 16-bitLENGTH, a little-endian 16-bit CRC16 (poly 0x8005, init 0xFFFF, computed with the CRC field zeroed), and a variable-length payload. Used for batch measurements and measurement streaming. Frames whoseFLAGScarryV3_FLAG_STREAMare unsolicited notifications and are not acknowledged by the host.
Refer to the product documentation shipped with your release package for the authoritative command reference.
SmartUSBHub¶
- class smartusbhub.SmartUSBHub(port)¶
Bases:
objectHigh-level interface to an industrial Smart USB Hub over UART.
Provides per-port control of power and data connections, voltage/current monitoring, default-state configuration, charge-mode switching and factory reset. Suitable for automated test systems and hardware development.
Instances may be used as context managers; the device is disconnected on exit:
with SmartUSBHub(port) as hub: hub.set_channel_power(1, state=1)
- close()¶
Close the connection. Alias for
disconnect.
- register_disconnect_callback(callback)¶
Register a callback invoked when the device disconnects unexpectedly.
- Parameters:
callback – Zero-argument callable executed on disconnect.
- register_callback(cmd, callback)¶
Register a callback invoked when a command’s ACK is received.
- Parameters:
cmd – Command code to attach the callback to.
callback – Callable receiving (channel, value) when the ACK arrives.
- static get_product_info(product_type_id)¶
Look up the capability record for a product-type ID.
- Parameters:
product_type_id – Product-type ID (see
PRODUCT_TYPE_TABLE).- Returns:
The product-info dict, or None if the ID is unknown.
- classmethod scan_available_ports()¶
Scan for serial ports whose USB VID/PID match a Smart USB Hub.
- Returns:
List of matching port device names.
- classmethod scan_and_connect(exclude_ports=None, device_address=None)¶
Scan for Smart USB Hub devices and connect to the first valid one.
- Parameters:
exclude_ports – Set of ports to skip; defaults to ports already connected.
device_address – If given, only connect to a device reporting this address. Note: addresses default to 0, so multiple devices may share one; prefer selecting by port. See
scan_and_connect_by_address.
- Returns:
A connected SmartUSBHub instance, or None if none was found.
- classmethod scan_and_connect_by_address(device_address)¶
Connect to a Smart USB Hub by device address.
Warning
Addresses default to 0, so multiple devices may share one address, making this selection unreliable. Prefer
scan_and_connectby port, or assign distinct addresses first.- Parameters:
device_address – Device address to match (0x0000 - 0xFFFF).
- Returns:
A connected SmartUSBHub instance, or None if no match was found.
- classmethod auto_connect(exclude_ports=None, feature_filter=None)¶
Scan and connect to the first available device, skipping busy ones.
Unlike
scan_and_connect, a busy or failing port is skipped and the next candidate is tried automatically.- Parameters:
exclude_ports – Set of ports to skip; defaults to ports already connected.
feature_filter – If given, only connect to a device supporting this feature (see
_check_feature_supportfor valid names).
- Returns:
A connected SmartUSBHub instance, or None if none is available.
- disconnect()¶
Disconnect from the device and stop the receive thread.
Idempotent and safe to call multiple times (e.g. via context-manager exit and atexit). Releases the port’s process-local and cross-process locks.
- is_connected()¶
Report whether the serial port is currently open.
- Returns:
True if connected, False otherwise.
- get_channels()¶
Return all valid 1-based channel numbers for the connected product.
Uses the cached max-channel value when available, then falls back to CMD_GET_MAX_CHANNELS and finally the product capability table.
- Returns:
Tuple such as (1, 2, 3, 4).
- Raises:
RuntimeError – If the count cannot be resolved.
- get_device_info()¶
Read and cache the hub’s identity and configuration.
Critical items (versions, operate mode, …) are retried for up to ~10 s each to tolerate a device that is still initializing. Optional items not supported by older firmware are treated as unavailable.
- Returns:
Dict describing the hub (id, address, versions, product, mode, …).
- set_operate_mode(mode)¶
Set the device operating mode.
- Parameters:
mode –
OPERATE_MODE_NORMAL(0) orOPERATE_MODE_INTERLOCK(1).- Returns:
True if acknowledged, False otherwise.
- get_operate_mode()¶
Query the current operating mode.
- Returns:
0 (normal), 1 (interlock), or None if no response.
- set_channel_power(*channels, state)¶
Set the power state of one or more channels.
- Parameters:
channels – Channel numbers (1-based) to update.
state – 1 to power on, 0 to power off.
- Returns:
True if acknowledged, False otherwise.
- get_channel_power_status(*channels)¶
Query the power status of one or more channels.
- Parameters:
channels – Channels to query.
- Returns:
For a single channel, its power state; for multiple, a dict {channel: state}; or None on timeout.
- get_channel_oc_status()¶
Query per-channel overcurrent status.
- Returns:
Dict {channel: {‘active’: bool, ‘latch’: bool}}, or None on timeout. ‘active’ is the live FLAG# state; ‘latch’ is sticky until cleared.
- clear_channel_oc_latch(*channels)¶
Clear the sticky overcurrent latch for one or more channels.
- Parameters:
channels – Channels to clear; no arguments clears all channels.
- Returns:
True if acknowledged, False otherwise.
- set_channel_power_interlock(channel)¶
Set interlock mode for a channel, or release all channels.
- Parameters:
channel – Channel to interlock, or None to turn all channels off.
- Returns:
True if acknowledged, False otherwise.
- get_channel_voltage(channel)¶
Read the voltage of a single channel.
- Parameters:
channel – Channel to query.
- Returns:
Voltage in mV, or None on timeout.
- Raises:
FeatureNotSupportedError – If the model lacks ADC monitoring.
ValueError – If a list/tuple is passed instead of a single channel.
- get_channel_current(channel)¶
Read the current of a single channel.
- Parameters:
channel – Channel to query.
- Returns:
Current in mA, or None on timeout.
- Raises:
FeatureNotSupportedError – If the model lacks ADC monitoring.
ValueError – If a list/tuple is passed instead of a single channel.
- get_channel_measurements(*channels)¶
Read voltage/current for multiple channels in one V3 request.
- Parameters:
channels – Channels to query; if omitted, all channels are queried.
- Returns:
Dict {channel: {“voltage”, “current”, “fresh”, “stale”, “valid”}}, or None on timeout.
- Raises:
FeatureNotSupportedError – If the model lacks ADC monitoring.
- get_stream_channel_measurements(*channels, timeout=None, wait_new_sample=True)¶
Wait for the next V3 measurement stream frame and return its readings.
Does not send a request; the device must already have streaming enabled via
set_channel_measurement_stream.- Parameters:
channels – Channels to include; if omitted, all channels.
timeout – Wait timeout in seconds; defaults to
self.com_timeout.wait_new_sample – If True, wait for a new sample tick; if False, accept the next stream frame even with the same tick.
- Returns:
Dict of per-channel readings (with sample_tick/sample_period_ms), or None.
- set_channel_measurement_stream(*channels, enabled=True, wait_ack=True)¶
Enable or disable V3 measurement streaming.
Stream frames are unsolicited V3 notifications and are not acknowledged by the host.
- Parameters:
channels – Channels to stream; if omitted, all channels.
enabled – True to enable streaming, False to disable.
wait_ack – If True, wait for the command ACK before returning.
- Returns:
True on success (or when
wait_ackis False), False on timeout.
- get_latest_measurements(*channels)¶
Return the most recently received measurements without blocking.
Returns whatever the background receiver has cached. Requires that streaming was started via
set_channel_measurement_stream.- Parameters:
channels – Channels to include; if omitted, all channels.
- Returns:
Dict of per-channel readings, or None if nothing has been received.
- set_channel_usb2_dataline(*channels, state)¶
Set the USB2.0 data-line state of one or more channels.
- Parameters:
channels – Channels to update.
state – 1 to connect the data line, 0 to disconnect.
- Returns:
True if acknowledged, False otherwise.
- get_channel_usb2_dataline_status(*channels)¶
Query the USB2.0 data-line status of one or more channels.
- Parameters:
channels – Channels to query; if omitted, returns all known channels.
- Returns:
Dict {channel: state} for the requested channels, or None on timeout.
- set_channel_usb3_dataline(*channels, state)¶
Set the USB3.0 data-line state of one or more channels.
Warning
Not yet publicly available; raises NotImplementedError unless
PREVIEW_API_ENABLEDis set.- Parameters:
channels – Channels to update.
state – 1 to connect the USB3 data line, 0 to disconnect.
- Returns:
True if acknowledged, False otherwise.
- Raises:
NotImplementedError – While this preview API is disabled.
- get_channel_usb3_dataline_status(*channels)¶
Query the USB3.0 data-line status of one or more channels.
Warning
Not yet publicly available; raises NotImplementedError unless
PREVIEW_API_ENABLEDis set.- Parameters:
channels – Channels to query; if omitted, returns all known channels.
- Returns:
Dict {channel: state} for the requested channels, or None on timeout.
- Raises:
NotImplementedError – While this preview API is disabled.
- set_channel_slow_charge(*channels, disconnect_before_switch=False)¶
Enable slow-charge (current-limited) mode for one or more channels.
To avoid interrupting an existing data connection, channels that are currently powered off are first powered on in fast-charge mode for 3 seconds before switching to slow charge.
- Parameters:
channels – Channels to update.
disconnect_before_switch – If True, channels already on are disconnected for 3 seconds before switching to slow charge.
- Returns:
True if the final slow-charge command was acknowledged, else False.
Warning
Not yet publicly available; raises NotImplementedError unless
PREVIEW_API_ENABLEDis set.- Raises:
NotImplementedError – While this preview API is disabled.
- set_channel_fast_charge(*channels, disconnect_before_switch=True)¶
Enable fast-charge (full-power) mode for one or more channels.
- Parameters:
channels – Channels to update.
disconnect_before_switch – If True, channels are disconnected for 3 seconds before switching, so the DUT re-detects charger capability.
- Returns:
True if the fast-charge command was acknowledged, else False.
Warning
Not yet publicly available; raises NotImplementedError unless
PREVIEW_API_ENABLEDis set.- Raises:
NotImplementedError – While this preview API is disabled.
- get_channel_charge_mode(*channels)¶
Query the charge mode of one or more channels.
Waits briefly for switching to settle and retries until the per-channel values are complete and consistent.
- Parameters:
channels – Channels to query.
- Returns:
Dict {channel: mode} where mode is 0=off, 1=fast, 2=slow; or None on timeout.
Warning
Not yet publicly available; raises NotImplementedError unless
PREVIEW_API_ENABLEDis set.- Raises:
NotImplementedError – While this preview API is disabled.
- set_button_control(enable)¶
Enable or disable the hub’s physical buttons.
- Parameters:
enable (bool) – True to enable buttons, False to disable.
- Returns:
True if acknowledged, False otherwise.
- get_button_control_status()¶
Query whether the hub’s physical buttons are enabled.
- Returns:
1 if enabled, 0 if disabled, or None if no response.
- set_default_power_status(*channels, enable, status=None)¶
Set the power-on default power state for one or more channels.
- Parameters:
channels – Channels to configure.
enable – 1 to apply a default power state, 0 to disable defaulting.
status – Default state when enabled: 1 for ON, 0 for OFF (default 0).
- Returns:
True if acknowledged, False otherwise.
- get_default_power_status(*channels)¶
Query the default power configuration for one or more channels.
- Parameters:
channels – Channels to query.
- Returns:
Dict {channel: {“enabled”, “value”}}, or None if no response.
- set_default_dataline_status(*channels, enable, status=None)¶
Set the power-on default data-line state for one or more channels.
- Parameters:
channels – Channels to configure.
enable – 1 to apply a default data-line state, 0 to disable defaulting.
status – Default state when enabled: 1 for connected, 0 for disconnected (default 0).
- Returns:
True if acknowledged, False otherwise.
- get_default_dataline_status(*channels)¶
Query the default data-line configuration for one or more channels.
- Parameters:
channels – Channels to query.
- Returns:
Dict {channel: {“enabled”, “value”}}, or None if no response.
- set_auto_restore(enable)¶
Enable or disable the auto-restore feature.
- Parameters:
enable (bool) – True to enable auto-restore, False to disable.
- Returns:
True if acknowledged, False otherwise.
- get_auto_restore_status()¶
Query whether auto-restore is enabled.
- Returns:
1 if enabled, 0 if disabled, or None if no response.
- set_device_address(address)¶
Set the 16-bit device address.
- Parameters:
address (int) – Address in the range 0x0000 - 0xFFFF.
- Returns:
True if acknowledged, False otherwise.
- Raises:
ValueError – If the address is out of range.
- get_device_address()¶
Query the current device address.
- Returns:
The 16-bit device address, or None if no response.
- reboot_mcu()¶
Reboot the device MCU.
The MCU reboots ~100 ms after acknowledging, so the connection is lost and the device must typically be reconnected afterwards.
- Returns:
True if the reboot command was acknowledged, False otherwise.
- factory_reset()¶
Reset the device to factory settings.
- Returns:
True if acknowledged, False otherwise.
- get_firmware_version()¶
Query the firmware version.
- Returns:
The firmware version, or None if no response.
- get_firmware_version_major()¶
Return the cached firmware major version, querying the device if needed.
Older firmware replies only with the minor version byte; those devices are treated as major version 1 for backward compatibility.
- get_firmware_version_string()¶
Return a display string such as
V2.03for the cached firmware.
- get_hardware_version()¶
Query the hardware version.
- Returns:
The hardware version, or None if no response.
- get_product_type()¶
Query the product-type ID.
Optional command: older firmware does not respond, in which case None is returned (logged at debug level, not as an error).
- Returns:
The product-type ID, or None if unsupported/no response.
- get_product_name()¶
Get the product name for the connected device.
- Returns:
The product name (e.g. “HBP_USB2_4CH”), an “Unknown(…)” string, or None if the product type is unavailable.
- get_max_channels()¶
Query the maximum channel count.
Optional command: older firmware does not respond, in which case None is returned (logged at debug level, not as an error).
- Returns:
The maximum channel count, or None if unsupported/no response.
- get_serial_no()¶
Query the device serial number.
- Returns:
The serial-number string (“N/A” if unavailable), or None if no response.
Exceptions¶
- class smartusbhub.SmartUSBHubError¶
Bases:
ExceptionBase class for all errors raised by this library.
Catch this to handle any SmartUSBHub-specific failure regardless of subtype.
- class smartusbhub.PortBusyError¶
Bases:
SmartUSBHubError,ValueErrorRaised when a serial port is already in use by another instance or process.
Also subclasses
ValueErrorfor backward compatibility with callers that previously caught theValueErrorraised on a busy port.
- class smartusbhub.DeviceConnectionError¶
Bases:
SmartUSBHubErrorRaised when a device does not respond during connection setup.
Typically means the port is not a SmartUSBHub or the device is unresponsive.
- class smartusbhub.FeatureNotSupportedError¶
Bases:
SmartUSBHubError,ValueErrorRaised when a requested feature is not supported by the connected product model.
Also subclasses
ValueErrorfor backward compatibility.
Helpers¶
- smartusbhub.synchronized(method)¶
Decorator that serializes access to a SmartUSBHub method via the instance lock.
When
ENABLE_SYNC_LOCKis True the wrapped method acquiresself.lockfor its whole duration; when False it runs without locking.- Parameters:
method – The instance method to wrap.
- Returns:
The wrapped method.
如果本页构建时无法导入依赖,请先安装 smartusbhub_ng/requirements.txt。