Skip to content

Instantly share code, notes, and snippets.

@agmm
Last active April 16, 2024 13:56
Show Gist options
  • Save agmm/fe24747a85d2d8c1afdefded803b9ab2 to your computer and use it in GitHub Desktop.
Save agmm/fe24747a85d2d8c1afdefded803b9ab2 to your computer and use it in GitHub Desktop.
Ambient light sensor reader (macOS)
// References:
// https://stackoverflow.com/questions/17625495/how-do-you-programmatically-access-the-ambient-light-sensor-on-mac-os-x-10-5
// https://stackoverflow.com/a/73955907
// Build command:
// clang -o lightsensor lightsensor.mm -F /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/PrivateFrameworks -framework Foundation -framework IOKit -framework CoreFoundation -framework BezelServices
#include <mach/mach.h>
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/hidsystem/IOHIDServiceClient.h>
typedef struct __IOHIDEvent *IOHIDEventRef;
#define kAmbientLightSensorEvent 12
#define IOHIDEventFieldBase(type) (type << 16)
extern "C" {
IOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef, int64_t, int32_t, int64_t);
double IOHIDEventGetFloatValue(IOHIDEventRef, int32_t);
IOHIDServiceClientRef ALCALSCopyALSServiceClient(void);
}
int main(void) {
IOHIDServiceClientRef client = ALCALSCopyALSServiceClient();
if (!client) {
fprintf(stderr, "failed to find ambient light sensors\n");
return 1;
}
IOHIDEventRef event = IOHIDServiceClientCopyEvent(client, kAmbientLightSensorEvent, 0, 0);
if (!event) {
fprintf(stderr, "failed to get ambient light sensor event\n");
return 1;
}
double value = IOHIDEventGetFloatValue(event, IOHIDEventFieldBase(kAmbientLightSensorEvent));
printf("%f\n", value);
CFRelease(event);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment