Files
bananarchy/vendor/edl/Library/usb.py
T

87 lines
3.3 KiB
Python
Raw Normal View History

2026-11-05 13:40:53 +02:00
import usb.core # pyusb
import usb.util
DEFAULT_USB_TIMEOUT_MS = 30000
2026-11-05 13:40:53 +02:00
class usb_class():
def log(self,level,msg):
if level>1:
if self.debug==True:
print(msg)
else:
print(msg)
def __init__(self,vid=0x05c6, pid=0x9008, Debug=False, timeout_ms=DEFAULT_USB_TIMEOUT_MS):
2026-11-05 13:40:53 +02:00
self.vid=vid
self.pid=pid
self.debug=Debug
self.timeout_ms=timeout_ms
2026-11-05 13:40:53 +02:00
self.connected=False
def connect(self):
self.device = usb.core.find(idVendor=self.vid, idProduct=self.pid)
if self.device is None:
self.log(2, "Couldn't detect the device. Is it connected ?")
return False
try:
if self.device.is_kernel_driver_active(0):
self.device.detach_kernel_driver(0)
except:
pass
try:
self.configuration = self.device.get_active_configuration()
except usb.core.USBError:
self.configuration = None
if self.configuration is None:
self.device.set_configuration()
self.configuration = self.device.get_active_configuration()
2026-11-05 13:40:53 +02:00
self.log(2, self.configuration)
for itf_num in [0]:
itf = usb.util.find_descriptor(self.configuration,
bInterfaceNumber=itf_num)
try:
if self.device.is_kernel_driver_active(itf_num):
self.log(2, "Detaching kernel driver")
self.device.detach_kernel_driver(itf_num)
except:
self.log(2, "No kernel driver supported.")
usb.util.claim_interface(self.device, itf_num)
self.EP_OUT = usb.util.find_descriptor(itf,
# match the first OUT endpoint
custom_match= \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT)
self.EP_IN = usb.util.find_descriptor(itf,
# match the first OUT endpoint
custom_match= \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_IN)
self.device.default_timeout = self.timeout_ms
2026-11-05 13:40:53 +02:00
self.connected=True
return True
def write(self,command,pktsize=64,timeout=None):
eff_timeout=self.timeout_ms if timeout is None else timeout
2026-11-05 13:40:53 +02:00
pos=0
if command==b'':
self.device.write(self.EP_OUT, b'', eff_timeout)
2026-11-05 13:40:53 +02:00
else:
while pos<len(command):
self.device.write(self.EP_OUT,command[pos:pos+pktsize],eff_timeout)
2026-11-05 13:40:53 +02:00
pos+=pktsize
def read(self,length=0x80000,timeout=None):
eff_timeout=self.timeout_ms if timeout is None else timeout
2026-11-05 13:40:53 +02:00
tmp=b''
while (bytearray(tmp) == b''):
tmp=self.device.read(self.EP_IN, length, eff_timeout)
2026-11-05 13:40:53 +02:00
return bytearray(tmp)