Virtually plug and unplug your USB connections with the USBHub3+ and Python

2024 March 15

Did you unplug it and plug it back in?

Turning ports on and off with Python

It shouldn't have to happen, but sometimes you need to plug and unplug a USB device. Maybe the device needs to power cycle, maybe you need to enable devices one-by-one so they enumerate correctly.  Rather than having to physically unplug cables, you could use the Brainstem API to have the USBHub3+ disconnect and reconnect a port.

Follow along and see how to enable and disable ports using Python.  We'll be working interactively in a Python console so you can see the results line-by-line. For more Python examples to get started, see here

First, power on the hub and connect one of the host ports to your computer

All of the VBus LEDs on the front panel should be on. If you haven’t already, install the brainstem package (See the Quickstart Guide for more detail)

>>> !pip install brainstem --upgrade

Then import the brainstem library

>>> import brainstem

Create an instance of the USBHub3p called "hub"

>>> hub = brainstem.stem.USBHub3p()

Discover and connect to the hub

>>> hub.discoverAndConnect(brainstem.link.Spec.USB)
0

(A return value of 0 means no error)

Let's plug a Super Speed USB 3 device into port 0.  A green LED should turn on next to port 0. (The LED would be yellow for a High Speed device)

Now let's "unplug" by disabling port 0.

>>> hub.usb.setPortDisable(0)

The power and data LEDs for port 0 should both be off.  It's like we're unplugged!

Re-enable port 0:

>>> hub.usb.setPortEnable(0)

 

...and now we're plugged back in.

Let's check the port state.

>>> result=hub.usb.getPortState(0)
>>> format(result.value, 'b')
'1011'

The result is bit-packed, see the full table.

1 0 1 1
USB3 Data Enabled Reserved USB2 Data Enabled USB Vbus Enabled

Vbus, USB2 data, and USB3 data are enabled.

What else could you do with USBHub3+?

  • Independently control VBus and data for each port
    • Turn on and off VBus
    • Enable and disable data connections:
    • Independently enable SuperSpeed and High Speed data
  • Power Measurements
    • Measure current and voltage on each port
    • Monitor input power and system power
  • Switch ports between Charging Downstream Port (CDP) and Standard Downstream Port (SDP) (up to 500 mA)
  • View the enumeration speed of a connected device
  • Switch upstream hosts
    • Automatically 
    • Programatically
  • Add more ports by daisy chaining hubs

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.