我有一个不会使用SERIAL
或HID
设备通信的USB设备。它处于DFU模式。我怎样才能开始检测它?我阅读了很多文章并查看了一些例子,但它们对我没有帮助。
据我所知,我应该使用IOKit.usb
库吗?如果有人告诉我如何能够检测到这个设备,那将是很棒的:(
答案 0 :(得分:3)
感谢您的回答,我建立了自己的解决方案:
class DFUDevice: NSObject {
let vendorId = 0x0483
let productId = 0xdf11
static let sharedInstance = DFUDevice()
private func reloadMonitor(iterator:io_iterator_t) {
repeat {
let nextService = IOIteratorNext(iterator)
guard nextService != 0 else { break }
IOObjectRelease(nextService)
} while (true)
}
func connected(iterator:io_iterator_t) {
self.reloadMonitor(iterator: iterator)
}
func disconnected(iterator:io_iterator_t) {
self.reloadMonitor(iterator: iterator)
}
func initUsb() {
var matchedIterator:io_iterator_t = 0
var removalIterator:io_iterator_t = 0
let notifyPort:IONotificationPortRef = IONotificationPortCreate(kIOMasterPortDefault)
IONotificationPortSetDispatchQueue(notifyPort, DispatchQueue(label: "IODetector"))
let matchingDict = IOServiceMatching(kIOUSBDeviceClassName)
as NSMutableDictionary
matchingDict[kUSBVendorID] = NSNumber(value: self.vendorId)
matchingDict[kUSBProductID] = NSNumber(value: self.productId)
let matchingCallback:IOServiceMatchingCallback = { (userData, iterator) in
let this = Unmanaged<DFUDevice>
.fromOpaque(userData!).takeUnretainedValue()
this.connected(iterator: iterator)
}
let removalCallback: IOServiceMatchingCallback = {
(userData, iterator) in
let this = Unmanaged<DFUDevice>
.fromOpaque(userData!).takeUnretainedValue()
this.disconnected(iterator: iterator)
};
let selfPtr = Unmanaged.passUnretained(self).toOpaque()
IOServiceAddMatchingNotification(notifyPort, kIOFirstMatchNotification, matchingDict, matchingCallback, selfPtr, &matchedIterator)
IOServiceAddMatchingNotification(notifyPort, kIOTerminatedNotification, matchingDict, removalCallback, selfPtr, &removalIterator)
if matchedIterator != 0 {
self.connected(iterator: matchedIterator)
matchedIterator = 0
}
if removalIterator != 0 {
self.reloadMonitor(iterator: removalIterator)
removalIterator = 0
}
self.reloadMonitor(iterator: matchedIterator)
self.reloadMonitor(iterator: removalIterator)
RunLoop.current.run();
}
}
运行它:
let DFUDeviceDaemon = Thread(target: DFUDevice.sharedInstance, selector:#selector(DFUDevice.initUsb), object: nil)
DFUDeviceDaemon.start()