Skip to content

Instantly share code, notes, and snippets.

@coreequip
Last active October 31, 2024 12:46
Show Gist options
  • Save coreequip/0fff94da2ffabb123fa3f80e620754c2 to your computer and use it in GitHub Desktop.
Save coreequip/0fff94da2ffabb123fa3f80e620754c2 to your computer and use it in GitHub Desktop.
DimmTrigger™

DimmTrigger™

A little daemon that detect screen sleep and wakeup and triggers shell script(s) to run an action. Here to toggle the power state of a connected Android TV.

0. Prerquisites

Get ADB for MacOS: brew install android-platform-tools

1. Compile dimmtrigger.sh

swiftc dimmtrigger.swift

Should create a dimmtrigger file.

2. Edit your trigger.sh file

See the trigger.sh. Edit your absolute path to the adb binary.
Give it exec rights: chmod +x trigger.sh

3. Symlink the shell script

ln -s /path/to/your/trigger.sh ~/.wake
ln -s /path/to/your/trigger.sh ~/.sleep

4. Edit and place the PLIST

Edit line 9 and line 16 to point to your in 1. compiled dimmtrigger binary and a log textfile collecting errors (line 16).

Place the plist file in ~/Library/LaunchAgents folder.

5. Run daemon

Run in shell: launchctl load ~/Library/LaunchAgents/de.corequip.dimmtrigger.plist

Have fun.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>de.corequip.dimmtrigger</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/your/dimmtrigger</string>
</array>
<key>KeepAlive</key>
<true/>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/path/to/your/error.log</string>
</dict>
</plist>
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
private let workspace = NSWorkspace.shared
func applicationDidFinishLaunching(_: Notification) {
print("[\(ISO8601DateFormatter().string(from: Date()))] dimmtrigger active")
[NSWorkspace.screensDidSleepNotification, NSWorkspace.screensDidWakeNotification].forEach { notification in
workspace.notificationCenter.addObserver(forName: notification, object: nil, queue: nil, using: handleScreenNotification)
}
}
func handleScreenNotification(notification: Notification) {
let isScreenSleep = notification.name == NSWorkspace.screensDidSleepNotification
print("[\(ISO8601DateFormatter().string(from: Date()))] screen did \(isScreenSleep ? "sleep" : "wake").")
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/bash")
process.arguments = ["-c", isScreenSleep ? "~/.sleep" : "~/.wake"]
try? process.run()
}
}
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
NSApplication.shared.run()
#!/usr/bin/env bash
/path/to/your/adb connect <IP_OF_YOUR_TV>
/path/to/your/adb shell input keyevent KEYCODE_POWER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment