我正在用 Python 为 USB HID 设备编写 Linux 驱动程序。设备有两种发送数据的方式,这两种方式都是必需的:特征报告(同步)和输入报告(异步)。使用 hidapi Cython 库,我只有一个设备实例可以使用,但我需要为 hid.read() 设置一个监听器,它将持续运行并允许应用程序随意调用同步方法来发送功能报告。
目前我在一个线程中有监听器,在另一个线程中有同步调用。当我运行程序时,我的同步调用没有发生,尽管如果我从不启动监听器它们工作正常;所以看起来监听器线程正在接管。
下面是一段令人不安的代码:
应用程序.py
# app.py
import threading
import time
import myhiddriver
# Code that sets mydevice
class Reader:
def start(self, device):
self.requests = myhiddriver.DeviceRequest(device)
# Wait a bit before firing, for testing
time.sleep(3)
self.requests.request_swipe_card()
def start_listener(self, device):
self.listener = myhiddriver.DeviceListener(device)
reader = Reader()
thread1 = threading.Thread(target=reader.start, args=(mydevice,))
thread1.daemon = True
thread2 = threading.Thread(target=reader.start_listener, args=(mydevice,))
thread2.daemon = True
thread1.start()
thread2.start()
# Keep this puppy running
while True:
pass
myhiddriver.py
import threading
LOCK = threading.Lock()
class DeviceRequest:
def __init__(self, device):
# Lock it up first
LOCK.acquire()
self.device = device
LOCK.release()
def request_swipe_card(self):
# Lock this up too
LOCK.acquire()
self.device.set_feature_report(insert data here)
LOCK.release()
class DeviceListener:
def __init__(self, device):
# Lock me up
LOCK.acquire()
self.device = device
self.start_listener()
LOCK.release()
def start_listener(self):
while True:
# Should I be locking this up?
LOCK.acquire()
data = self.device.read(255)
LOCK.release()
if data:
print data
else:
pass
我的问题:为什么我的同步调用(request_swipe_card)没有通过?或者,我怎样才能更好地构建它以拥有一个无穷无尽的监听器以及对同一个对象进行同步调用的能力?