Created
December 26, 2023 18:34
-
-
Save lemmy/54e511fc305da55cab7815ca9e8385b2 to your computer and use it in GitHub Desktop.
Turn of lights when the display sleeps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreGraphics | |
// Define the URL for the HTTP GET request | |
let baseURL = "http://tasmota-f72dd5-3541.fritz.box/cm?cmnd=Power%20" | |
// Create a URLSession | |
let session = URLSession.shared | |
// Define a function to create a task with a URL | |
func createTask(with suffix: String) -> URLSessionDataTask { | |
let url = URL(string: baseURL + suffix)! | |
return session.dataTask(with: url) { (data, response, error) in | |
if error != nil || data == nil { | |
print("Client error!") | |
return | |
} | |
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else { | |
print("Server error!") | |
return | |
} | |
guard let mime = response.mimeType, mime == "application/json" else { | |
print("Wrong MIME type!") | |
return | |
} | |
} | |
} | |
// Start an infinite loop | |
while true { | |
let mainDisplayID = CGMainDisplayID(); | |
let isAsleep = CGDisplayIsAsleep(mainDisplayID); | |
if (isAsleep != 0) { | |
// The display is asleep, issue the HTTP GET request | |
// print("Display is asleep, turning off lights...") | |
// Create and start the task | |
createTask(with: "Off").resume() | |
} else { | |
// The display is not asleep, issue the HTTP GET request | |
// print("Display is awake, turning on lights...") | |
// Create and start the task | |
createTask(with: "On").resume() | |
} | |
// Sleep for a second before checking again | |
sleep(5) | |
} | |
/* | |
Inspired by and pieced together with: | |
https://arstechnica.com/civis/threads/tasmota-smart-plugs-are-nice.1490152/ | |
https://www.bernhard-baehr.de | |
https://github.com/luckman212/dstat/blob/main/main.m | |
https://stackoverflow.com/questions/69066960/in-macos-is-there-a-way-to-be-notified-when-the-display-not-the-whole-system | |
https://developer.apple.com/documentation/appkit/nsworkspace/1530288-screensdidsleepnotification | |
https://github.com/psieg/Lightpack/issues/98 | |
https://stackoverflow.com/questions/4929731/check-if-display-is-at-sleep-or-receive-sleep-notifications | |
https://stackoverflow.com/questions/32913789/cannot-receive-nsworkspacedidwakenotification-in-swift-os-x | |
https://github.com/home-assistant/iOS/issues/1317 | |
*/ |
Author
lemmy
commented
Dec 26, 2023
- sleepwatch's display events don't work on m1/silicon macs
- https://developer.apple.com/documentation/appkit/nsworkspace/1530288-screensdidsleepnotification didn't work for me on Ventura either
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment