Skip to content

Instantly share code, notes, and snippets.

@coreequip
Last active March 18, 2024 13:19
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
import Foundation
class AppDelegateFinal: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_: Notification) {
print("dimmtrigger active")
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: nil,
using: notificationRecieved)
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.screensDidWakeNotification, object: nil, queue: nil,
using: notificationRecieved)
}
func notificationRecieved(n: Notification) {
switch n.name {
case NSWorkspace.screensDidSleepNotification:
print("screen did SLEEP.")
executeShellCommand("~/.sleep")
case NSWorkspace.screensDidWakeNotification:
print("screen did WAKE.")
executeShellCommand("~/.wake")
default:
print("unknown notification")
}
}
}
func executeShellCommand(_ command: String) {
let process = Process()
process.arguments = ["-c", command]
process.launchPath = "/bin/bash"
process.launch()
process.waitUntilExit()
}
let appDelegate = AppDelegateFinal()
NSApplication.shared.delegate = appDelegate
NSApp.activate()
NSApp.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