1

I have a python application that uses the hid module to interface with a couple bluetooth devices on macos. Right now, the only way I can detect that the device has been connected is to poll hid.enumerate and see if it's there. This wastes a lot of CPU.

I would like to get a notification from the OS when a new bluetooth device is connected. This seems possible with IOKit, according to this answer: How to know when a HID USB/Bluetooth device is connected in Cocoa?

I've been trying to replicate this from python, using the Cocoa, pyobjc, or even ctypes modules, but I don't know enough to know where to start. Can anyone suggest an approach?

Thank you!

FWIW, this seems like the relevant objc snippet: `

- (void) startHIDNotification
{
ioHIDManager = IOHIDManagerCreate ( kCFAllocatorDefault, kIOHIDManagerOptionNone  );

CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOHIDDeviceKey);
CFDictionaryAddValue(matchingDict, CFSTR(kIOHIDManufacturerKey), CFSTR("Apple"));

IOHIDManagerSetDeviceMatching (ioHIDManager, matchingDict);

IOHIDManagerRegisterDeviceMatchingCallback( ioHIDManager, AppleHIDDeviceWasAddedFunction, (__bridge void *)(self) );
IOHIDManagerRegisterDeviceRemovalCallback( ioHIDManager, AppleHIDDeviceWasRemovedFunction, (__bridge void *)(self) );

hidNotificationRunLoop = CFRunLoopGetCurrent();

IOHIDManagerScheduleWithRunLoop(ioHIDManager,
                                hidNotificationRunLoop,
                                kCFRunLoopDefaultMode);
}

`

foobar42
  • 11
  • 1

0 Answers0