Skip to content

Instantly share code, notes, and snippets.

@Coopeh
Last active November 30, 2021 14:37
Show Gist options
  • Save Coopeh/7233d4d1fb8d6bf031d46ac88c416fa2 to your computer and use it in GitHub Desktop.
Save Coopeh/7233d4d1fb8d6bf031d46ac88c416fa2 to your computer and use it in GitHub Desktop.
Quick fish shell script to run a HASS trigger when a microphone is active on MacOS, in this case to turn an On Air light on and off.
<?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>com.onair.app</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/fish</string>
<string>/opt/scripts/onair.fish</string>
</array>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>ThrottleInterval</key>
<integer>1</integer>
<key>StandardOutPath</key>
<string>/opt/scripts/onair.log</string>
<key>StandardErrorPath</key>
<string>/opt/scripts/onair.log</string>
</dict>
</plist>
#!/usr/local/bin/fish
# Fish script to toggle Elgato Key Light Air and ON AIR light on or off dependant if the microphone is in use.
# Requires Home Assistant
# Create the variables for turning the light on and off. Bearer token created in your profile section in HASS
set bearer_token ''
set webhook 'http://192.168.x.x:8123/api/services'
set switch 'switch.on_air_light'
set light 'light.elgato_key_light_air'
set dir '/opt/scripts'
# Remove leftover files before starting
rm $dir/up $dir/down 2> /dev/null
# Build the onair function to run later
function onair
set -l onair_status (ioreg -k IOAudioEngineState -n AppleUSBAudioEngine -c AppleUSBAudioEngine -rd 1 | grep -m1 -o "\"IOAudioEngineState\" = 1" | wc -l | tr -d " ")
switch $onair_status
case '0'
if not test -e $dir/down
touch $dir/down
rm $dir/up 2> /dev/null
curl -s -X POST -H "Authorization: Bearer $bearer_token" -H "Content-Type: application/json" -d "{\"entity_id\": \"$switch\"}" $webhook/switch/turn_off > /dev/null
curl -s -X POST -H "Authorization: Bearer $bearer_token" -H "Content-Type: application/json" -d "{\"entity_id\": \"$light\"}" $webhook/light/turn_off > /dev/null
end
case '*'
if not test -e $dir/up
touch $dir/up
rm $dir/down 2> /dev/null
curl -s -X POST -H "Authorization: Bearer $bearer_token" -H "Content-Type: application/json" -d "{\"entity_id\": \"$switch\"}" $webhook/switch/turn_on > /dev/null
curl -s -X POST -H "Authorization: Bearer $bearer_token" -H "Content-Type: application/json" -d "{\"entity_id\": \"$light\"}" $webhook/light/turn_on > /dev/null
end
end
end
# Run script forever, but sleep after each run to conserve CPU
while true
onair
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment