This repository has been archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
kbrightness.swift
91 lines (69 loc) · 2.74 KB
/
kbrightness.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import Foundation
class Backlight {
private var isOn = false
private var isFlashing = false
private var numberOfToggles = 0
private var isFlashingOnce = false
private var connect: mach_port_t = 0
private var timer: Timer = Timer()
static var sharedBacklight = Backlight()
static let FastFlashingInterval = 0.02
static let MediumFlashingInterval = 0.06
static let SlowFlashingInterval = 0.2
static let MinBrightness:UInt64 = 0x0
static var MaxBrightness:UInt64 = 0xfff
init() {
// Get the AppleLMUController (thing that accesses the light hardware)
let serviceObject = IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("AppleLMUController"))
assert(serviceObject != 0, "Failed to get service object")
// Open the AppleLMUController
let status = IOServiceOpen(serviceObject, mach_task_self_, 0, &connect)
assert(status == KERN_SUCCESS, "Failed to open IO service")
// Start with the backlight off
on();
}
func startFlashing(target: AnyObject, interval: Float64, selector: Selector) {
self.timer = Timer.scheduledTimer(
timeInterval: interval, target: target, selector: selector, userInfo: nil, repeats: true)
// We need to add the timer to the mainRunLoop so it doesn't stop flashing when the menu is accessed
RunLoop.main.add(self.timer, forMode: RunLoopMode.commonModes)
self.isFlashing = true
}
func stopFlashing() {
self.isFlashing = false
self.timer.invalidate()
}
func toggle() {
if self.isOn {
self.off();
} else {
self.on();
}
self.numberOfToggles += 1
if self.numberOfToggles >= 3 && isFlashingOnce {
self.timer.invalidate()
isFlashingOnce = false
}
}
func on() {
set(brightness: Backlight.MaxBrightness)
isOn = true
}
func off() {
set(brightness: Backlight.MinBrightness)
isOn = false
}
func set(brightness: UInt64) {
var output: UInt64 = 0
var outputCount: UInt32 = 1
let setBrightnessMethodId:UInt32 = 2
let input: [UInt64] = [0, brightness]
let status = IOConnectCallMethod(connect, setBrightnessMethodId, input, UInt32(input.count),
nil, 0, &output, &outputCount, nil, nil)
assert(status == KERN_SUCCESS, "Failed to set brightness; status: \(status)")
}
func printe(vale: Int32) {
Backlight.MaxBrightness = UInt64(vale * 16)
}
}