1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
| import IOKit import IOKit.usb import IOKit.usb.IOUSBLib import Foundation
class USBWatcher { private var addedIterator: io_iterator_t = 0 private var removedIterator: io_iterator_t = 0 private let targetLocationID: UInt32 private var notificationPort: IONotificationPortRef? private let eventQueue = DispatchQueue(label: "com.usb.watcher.queue", attributes: .concurrent) init(targetLocationID: UInt32) { self.targetLocationID = targetLocationID eventQueue.async { [weak self] in self?.setupNotifications() RunLoop.current.run() } } deinit { IOObjectRelease(addedIterator) IOObjectRelease(removedIterator) if let port = notificationPort { IONotificationPortDestroy(port) } } private func setupNotifications() { let matchDict = IOServiceMatching(kIOUSBDeviceClassName) if #available(macOS 12.0, *) { notificationPort = IONotificationPortCreate(kIOMainPortDefault) } else { notificationPort = IONotificationPortCreate(kIOMasterPortDefault) } guard let port = notificationPort else { print("Failed to create notification port") return } let runLoopSource = IONotificationPortGetRunLoopSource(port).takeUnretainedValue() CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .defaultMode) IOServiceAddMatchingNotification( port, kIOMatchedNotification, matchDict, { (userData, iterator) in let watcher = Unmanaged<USBWatcher>.fromOpaque(userData!).takeUnretainedValue() watcher.handleUSBEvent(iterator: iterator, isConnected: true) }, Unmanaged.passUnretained(self).toOpaque(), &addedIterator ) IOServiceAddMatchingNotification( port, kIOTerminatedNotification, matchDict, { (userData, iterator) in let watcher = Unmanaged<USBWatcher>.fromOpaque(userData!).takeUnretainedValue() watcher.handleUSBEvent(iterator: iterator, isConnected: false) }, Unmanaged.passUnretained(self).toOpaque(), &removedIterator ) handleUSBEvent(iterator: addedIterator, isConnected: true) handleUSBEvent(iterator: removedIterator, isConnected: false) } private func handleUSBEvent(iterator: io_iterator_t, isConnected: Bool) { while case let device = IOIteratorNext(iterator), device != IO_OBJECT_NULL { guard let locationID = getDeviceProperty(device: device, key: kUSBDevicePropertyLocationID) as? UInt32, locationID == targetLocationID else { IOObjectRelease(device) continue } print("Thread Name == \(Thread.current)") let vendorID = getDeviceProperty(device: device, key: kUSBVendorID) as? Int ?? 0 let productID = getDeviceProperty(device: device, key: kUSBProductID) as? Int ?? 0 let serialNumber = getDeviceProperty(device: device, key: kUSBSerialNumberString) as? String ?? "N/A" let deviceName = getDeviceProperty(device: device, key: "USB Product Name") as? String ?? "N/A" DispatchQueue.main.async { let event = isConnected ? true : false let message = """ [USB 设备] \(event) ├─ Vendor ID:[0x\(String(format: "%04X", vendorID))] ├─ Product ID:[0x\(String(format: "%04X", productID))] ├─ SerialNumber:[\(serialNumber)] ├─ Location ID:[0x\(String(locationID, radix: 16))] └─ deviceName:[\(deviceName)] """ print(message) NotificationCenter.default.post( name: .USBDeviceStateChanged, object: nil, userInfo: [ "event": event, "vendorID": vendorID, "productID": productID, "serialNumber": serialNumber, "locationID": locationID, "deviceName": deviceName ] ) } IOObjectRelease(device) } } private func getDeviceProperty(device: io_object_t, key: String) -> Any? {
let cfProp = IORegistryEntryCreateCFProperty( device, key as CFString, kCFAllocatorDefault, 0 ) return cfProp?.takeUnretainedValue() } }
extension Notification.Name { static let USBDeviceStateChanged = Notification.Name("USBDeviceStateChanged") }
|