IOServiceAddMatchingNotification()
および関連する機能を見てください。私はシリアルポート(実際にはUSBからシリアルへのアダプターですが、それは問題ではありません)のコンテキストでのみ使用しましたが、IOKitにアクセス可能なすべてのデバイスに適用できるはずです。Bluetoothについてはよくわかりませんが、少なくともUSBデバイスでは機能するはずです。これが私が使用するコードの抜粋です:
IONotificationPortRef notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notificationPort),
kCFRunLoopDefaultMode);
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOSerialBSDServiceValue);
CFRetain(matchingDict); // Need to use it twice and IOServiceAddMatchingNotification() consumes a reference
CFDictionaryAddValue(matchingDict, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDRS232Type));
io_iterator_t portIterator = 0;
// Register for notifications when a serial port is added to the system
kern_return_t result = IOServiceAddMatchingNotification(notificationPort,
kIOPublishNotification,
matchingDictort,
SerialDeviceWasAddedFunction,
self,
&portIterator);
io_object_t d;
// Run out the iterator or notifications won't start (you can also use it to iterate the available devices).
while ((d = IOIteratorNext(iterator))) { IOObjectRelease(d); }
// Also register for removal notifications
IONotificationPortRef terminationNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(terminationNotificationPort),
kCFRunLoopDefaultMode);
result = IOServiceAddMatchingNotification(terminationNotificationPort,
kIOTerminatedNotification,
matchingDict,
SerialPortWasRemovedFunction,
self, // refCon/contextInfo
&portIterator);
io_object_t d;
// Run out the iterator or notifications won't start (you can also use it to iterate the available devices).
while ((d = IOIteratorNext(iterator))) { IOObjectRelease(d); }
MySerialPortDeviceWasAddedFunction()
とSerialPortWasRemovedFunction()
は、シリアルポートがシステムで使用可能になるか、削除されたときにそれぞれ呼び出されます。
関連するドキュメントはここにあり、特に見出しの下にありGetting Notifications of Device Arrival and Departure
ます。