Skip to content

Instantly share code, notes, and snippets.

@jvacek
Created January 7, 2023 23:52
Show Gist options
  • Save jvacek/3126e5450520433c6ced29896ef6784a to your computer and use it in GitHub Desktop.
Save jvacek/3126e5450520433c6ced29896ef6784a to your computer and use it in GitHub Desktop.
Homebridge Apple TV AirPlay Status Sensor

This setup will add a contact switch to show when your apple tv is playing music over airplay.

The config and script below will give you a contact switch which shows whether AirPlay Music is playing or not.

Follow the instructions for https://github.com/cristian5th/homebridge-appletv, and save your tokens separately from your script.

image

#!/bin/bash
# put me somewhere close to homebridge like /var/lib/homebridge/
set -e
# Exit immediately for unbound variables.
set -u
length=$#
device=""
io=""
characteristic=""
option=""
ATV_id="AA:BB:CC:DD:EE:FF"
airplay_credentials="$(cat ~/.config/atv-airplay)"
companion_credentials="$(cat ~/.config/atv-companion)"
atvremote_path="/home/pi/.local/bin/"
cmd_airplay=
if [ $length -le 1 ]; then
printf "Usage: $0 Get < AccessoryName > < Characteristic >\n"
printf "Usage: $0 Set < AccessoryName > < Characteristic > < Value >\n"
exit -1
fi
if [ $length -ge 1 ]; then
io=$1
fi
if [ $length -ge 2 ]; then
device=$2
fi
if [ $length -ge 3 ]; then
characteristic=$3
fi
if [ $length -ge 4 ]; then
option=$4
fi
if [ "${io}" == "Get" ]; then
case $device in
'AirPlay Music Playing')
case $characteristic in
'ContactSensorState')
ret=$(echo -e "app\ndevice_state\nexit" | ${atvremote_path}atvremote --id ${ATV_id} --airplay-credentials ${airplay_credentials} cli)
if $(grep 'com.apple.TVAirPlay' -q <<<$ret && grep -e 'DeviceState.Playing' -q <<<$ret); then
printf "1\n"
else
printf "0\n"
fi
exit 0
;;
*)
printf "UnHandled Get ${device} Characteristic ${characteristic}\n"
exit -1
;;
esac
;;
esac
fi
if [ "${io}" == 'Set' ]; then
echo "Set not handled"
exit -1
fi
printf "Unknown io command ${io}\n"
exit -1
{
"platform": "Cmd4",
"name": "Cmd4",
"interval": 3,
"timeout": 4000,
"debug": false,
"stateChangeResponseTime": 1,
"queueTypes": [
{
"queue": "A",
"queueType": "WoRm"
}
],
"accessories": [
{
"type": "ContactSensor",
"displayName": "AirPlay Music Playing",
"contactSensorState": "1",
"queue": "A",
"polling": true,
"state_cmd": "bash /var/lib/homebridge/appletv_query.sh"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment