@@ -12,6 +12,7 @@ class LightSystemStateController {
12
12
category: " LightSystemStateController "
13
13
)
14
14
private var screenLockMonitor : Any ?
15
+ private var lightsWereTurnedOff = false
15
16
16
17
init ( deviceManager: ElgatoDeviceManager , appState: AppState ) {
17
18
self . deviceManager = deviceManager
@@ -42,6 +43,18 @@ class LightSystemStateController {
42
43
name: NSWorkspace . screensDidSleepNotification,
43
44
object: nil
44
45
)
46
+ NotificationCenter . default. addObserver (
47
+ self ,
48
+ selector: #selector( handleWakeUp) ,
49
+ name: NSWorkspace . didWakeNotification,
50
+ object: nil
51
+ )
52
+ NotificationCenter . default. addObserver (
53
+ self ,
54
+ selector: #selector( handleWakeUp) ,
55
+ name: NSWorkspace . screensDidWakeNotification,
56
+ object: nil
57
+ )
45
58
}
46
59
47
60
private func setupScreenLockMonitor( ) {
@@ -53,6 +66,14 @@ class LightSystemStateController {
53
66
) { [ weak self] _ in
54
67
self ? . handleScreenLock ( )
55
68
}
69
+
70
+ distributed. addObserver (
71
+ forName: . init( " com.apple.screenIsUnlocked " ) ,
72
+ object: nil ,
73
+ queue: . main
74
+ ) { [ weak self] _ in
75
+ self ? . handleWakeUp ( notification: Notification ( name: Notification . Name ( " screenUnlock " ) ) )
76
+ }
56
77
}
57
78
58
79
deinit {
@@ -91,6 +112,7 @@ class LightSystemStateController {
91
112
Task {
92
113
do {
93
114
try await device. turnOff ( )
115
+ lightsWereTurnedOff = true
94
116
logger
95
117
. info (
96
118
" Turned off device: \( device. name, privacy: . public) due to \( reason, privacy: . public) "
@@ -104,4 +126,39 @@ class LightSystemStateController {
104
126
}
105
127
}
106
128
}
129
+
130
+ @objc private func handleWakeUp( notification: Notification ) {
131
+ guard appState. lightsOffOnSleep, lightsWereTurnedOff else { return }
132
+
133
+ let reason : String
134
+ switch notification. name {
135
+ case NSWorkspace . didWakeNotification:
136
+ reason = " computer wake "
137
+ case NSWorkspace . screensDidWakeNotification:
138
+ reason = " screen wake "
139
+ default :
140
+ reason = " unknown reason "
141
+ }
142
+
143
+ logger. info ( " System waking up due to \( reason, privacy: . public) . Turning on lights. " )
144
+
145
+ for device in deviceManager. devices where device. isOnline {
146
+ Task {
147
+ do {
148
+ try await device. turnOn ( )
149
+ logger
150
+ . info (
151
+ " Turned on device: \( device. name, privacy: . public) due to \( reason, privacy: . public) "
152
+ )
153
+ } catch {
154
+ logger
155
+ . error (
156
+ " Failed to turn on device: \( device. name) due to \( reason) . Error: \( error. localizedDescription) "
157
+ )
158
+ }
159
+ }
160
+ }
161
+
162
+ lightsWereTurnedOff = false
163
+ }
107
164
}
0 commit comments