使用python中的线程从多个usbs读取数据。
大家好, 我在python中编写代码来从USB读取数据。我遵循的逻辑是
我可以通过将所有内容保存在单个.py文件中来读取单个USB中的数据。
我有许多具有相同vendorID但不同PID的usbs。如果我必须编写通用代码来使用线程从所有USB读取数据。 但是当我想到使用线程时,它不会发生在第5步以后(我的下面的代码可能正在编写启动数据包但无法读取):( 为CreateLoopObject.py和USBOjbect.py
创建了单独的文件请帮助......
我的方法是:
class CreateLoopObject(object):
def __init__(self, dev):
object.__init__(self)
self.connection = USBOjbect(dev)
self.mythread = threading.Thread(name='Mythread', target = self.beginTransaction)
def begin(self):
self.connection.open()
self.connection.DoInitialTransactions()
self.mythread.start()
def beginTransaction(self):
# Read infitely from read and process
while True:
data = self.read()
# process data.....
def read(self):
return self.connection.read()
class USBOjbect(object):
def __init__(self, dev):
self.device = dev
self.outPoint = None
self.inPoint = None
def open(self):
self.device.set_active_configuration()
cfg = self.device.get_active_configuration()
intf = cfg[(0,0)]
self.outPoint = usb.util.descriptor(..) # Get OUT END POINT
self.inPoint = usb.util.descriptor(..) # Get IN END POINT
def read(self):
return self.inPoint.read(64)
def write(self, msg):
self.outPoint.write(msg)
def DoInitialTransactions(self):
self.write(startup_packet)
while True:
try:
data = self.read(64)
break
except Exception as e:
print('not able to read')
self.write(startup_complete_packet)
data = self.read(64)
if __name__=='__main__':
devices = usb.core.find(find_all=True, idVendor=0xABCD)
Threaddict = {}
for dev in devices:
if dev.idProduct not in Threaddict:
Threaddict[dev.idProdcut] = CreateLoopObject(dev)
Threaddict[dev.idProdcut].begin()