Skip to content

Instantly share code, notes, and snippets.

@4np
Created January 24, 2017 23:33
Show Gist options
  • Save 4np/14e8d996b659795b0572a4c45159c174 to your computer and use it in GitHub Desktop.
Save 4np/14e8d996b659795b0572a4c45159c174 to your computer and use it in GitHub Desktop.
Acces Mac OS Ambient Light Sensor
func getLux() {
guard let serviceType = IOServiceMatching("AppleLMUController") else {
debugPrint("No ambient light sensor")
return
}
// get and release service
let service = IOServiceGetMatchingService(kIOMasterPortDefault, serviceType)
defer {
IOObjectRelease(service)
}
// open io connection
var dataPort: io_connect_t = 0
guard IOServiceOpen(service, mach_task_self_, 0, &dataPort) == KERN_SUCCESS else {
debugPrint("Coult not read ambient light sensor (1)")
return
}
setbuf(stdout, nil)
var outputs: UInt32 = 2
let values = UnsafeMutablePointer<UInt64>.allocate(capacity: Int(outputs))
let zero: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.allocate(capacity: 8)
guard IOConnectCallMethod(dataPort, 0, nil, 0, nil, 0, values, &outputs, nil, zero) == KERN_SUCCESS else {
debugPrint("Could not read ambient light sensor (2)")
return
}
let value = Int(values[0])
debugPrint("result: \(value)")
}
@pouyakary
Copy link

Recently, I wrote a software to manage the mac's appearance based on ambient light & time. This gist was the most helpful to let me access ambient light sensor. I wanted to say how much I appreciate it. Thanks a lot 👍

@diogot
Copy link

diogot commented Dec 29, 2018

Did you manage to make this work on MacbookPro TouchBar?
I always have Coult not read ambient light sensor (1).
It works in other machines.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment