From da03d2650a6240ef1364bce789f72cc48cb75807 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 7 Oct 2018 05:48:00 +0200 Subject: Try listening to Bluetooth headphone buttons Second attempt at getting events from Bluetooth headphone buttons. This time with some code from KillerDeMouches and Josh Guice. The magic numbers make no sense to me. Would have loved to have constants, but hypothesizing that maybe they were gathered from direct input and event monitoring using Karabiner's event monitor. Unfortunately, this code didn't work for me. I still have to try it on a < 10.12 machine, as maybe it'll work there (_hopefully_, as there was very scarce material online about how to do this). My next attempt is going to be using `MPRemoteCommandCenter`. Hoping that will work, but it's only going to be a solution for >= 10.12. --- DomeKey/AppDelegate.m | 1 + DomeKey/HeadphoneKey.h | 1 + DomeKey/HeadphoneKey.m | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/DomeKey/AppDelegate.m b/DomeKey/AppDelegate.m index 3e4f3d8..318aeee 100644 --- a/DomeKey/AppDelegate.m +++ b/DomeKey/AppDelegate.m @@ -13,6 +13,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification { _headphone_key = [[HeadphoneKey alloc] init]; + [_headphone_key startMonitoringBluetoothEvents]; } @end diff --git a/DomeKey/HeadphoneKey.h b/DomeKey/HeadphoneKey.h index 861621f..586c40b 100644 --- a/DomeKey/HeadphoneKey.h +++ b/DomeKey/HeadphoneKey.h @@ -29,5 +29,6 @@ static const unsigned int TIMEOUT_MILLISECONDS = 1000; - (void)handleDeadKey:(HeadphoneButton)button; - (void)runAction; +- (void)startMonitoringBluetoothEvents; @end diff --git a/DomeKey/HeadphoneKey.m b/DomeKey/HeadphoneKey.m index ef90560..5a062fc 100644 --- a/DomeKey/HeadphoneKey.m +++ b/DomeKey/HeadphoneKey.m @@ -57,6 +57,45 @@ } } +- (void)startMonitoringBluetoothEvents +{ + // https://github.com/jguice/mac-bt-headset-fix/blob/master/Spotify%20Bluetooth%20Headset%20Listener/KDMAppDelegate.m + [NSEvent + addGlobalMonitorForEventsMatchingMask:(NSKeyDownMask | NSSystemDefinedMask) + handler:^(NSEvent *theEvent) { + int key_code = (([theEvent data1] & 0xFFFF0000) >> 16); + int key_flags = ([theEvent data1] & 0x0000FFFF); + int key_state = (((key_flags & 0xFF00) >> 8)) == 0xA; + + // TODO: Fix magic numbers + if (key_code == 10 && key_flags == 6972) { + switch ([theEvent data2]) { + case 786608: + case 786637: + NSLog(@"Play"); + + break; + case 786611: + NSLog(@"Next"); + + break; + case 786612: + NSLog(@"Previous"); + + break; + case 786613: + NSLog(@"Fast-forward"); + + break; + case 786614: + NSLog(@"Rewind"); + + break; + } + } + }]; +} + - (void)handleDeadKey:(HeadphoneButton)button { NSNumber *storable_button = [NSNumber numberWithUnsignedInteger:button]; -- cgit v1.2.3