I was wondering if it could be possible to control the power of usb ports in Python, using vendor ids and product ids. It should be controlling powers instead of just enabling and disabling the ports. It would be appreciated if you could provide some examples.
Look into the subprocess module in the standard library:
What commands you need will depend on the OS.
Windows
For windows you will want to look into devcon
This has been answered in previous posts
import subprocess
# Fetches the list of all usb devices:
result = subprocess.run(['devcon', 'hwids', '=usb'],
capture_output=True, text=True)
# ... add code to parse the result and get the hwid of the device you want ...
subprocess.run(['devcon', 'disable', parsed_hwid]) # to disable
subprocess.run(['devcon', 'enable', parsed_hwid]) # to enable
Linux
import subprocess
# determine desired usb device
# to disable
subprocess.run(['echo', '0', '>' '/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms'])
subprocess.run(['echo', 'auto', '>' '/sys/bus/usb/devices/usbX/power/control'])
# to enable
subprocess.run(['echo', 'on', '>' '/sys/bus/usb/devices/usbX/power/control'])
So far I came to the conclusion that you cannot control the power of a USB port. The 5V USB is always provided, and it's up to the device to use it or not. You can check this with a 5V fan or light. I've tried various methods (disconnect/reconnect/bind/unbind/reset). Best so far are bind/unbind as it forces a cold restart of the device (but no power cycle).
I came up with a solution to reset USB devices, ports and controllers in a python script, which supports all of the above methods. You can find the script at my Github page
Usage:
usb_reset.py -d 8086:1001 --reset-hub
The script uses among others the following solution to reset USB hubs/controllers:
Unbindind a USB port / controller works best via:
echo "myhub" > "/sys/bus/usb/drivers/usb/unbind"
echo "myhub" > "/sys/bus/usb/drivers/usb/bind"
Where myhub is found in /sys/bus/usb/devices/*
Or litteral controllers:
echo "mycontroller" > "/sys/bus/pci/drivers/unbind"
echo "mycontroller" > "/sys/bus/pci/drivers/bind"
Where mycontroller is found in /sys/bus/pci/drivers/[uoex]hci_hcd/*:*
© 2022 - 2024 — McMap. All rights reserved.