Skip to content

Instantly share code, notes, and snippets.

@lemmy
Created December 26, 2023 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lemmy/54e511fc305da55cab7815ca9e8385b2 to your computer and use it in GitHub Desktop.
Save lemmy/54e511fc305da55cab7815ca9e8385b2 to your computer and use it in GitHub Desktop.
Turn of lights when the display sleeps
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
*/
@lemmy
Copy link
Author

lemmy commented Dec 26, 2023

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