Skip to content

Instantly share code, notes, and snippets.

@nickw444
Last active January 5, 2026 02:27
Show Gist options
  • Select an option

  • Save nickw444/5eb50277e41be6a5d48bebfe51056c1c to your computer and use it in GitHub Desktop.

Select an option

Save nickw444/5eb50277e41be6a5d48bebfe51056c1c to your computer and use it in GitHub Desktop.
moOde Audio - Toggle Home Assistant Switch Entity

moOde Audio - Toggle Home Assistant Switch Entity

Script/service to monitor the playback status of moOde and toggle a Home Assistant entity when playback starts/stops.

Based off https://gist.github.com/michaelfdeberry/d3e7c9b4c4e1305be863d81a7e09f3de

Installation

Modify powertoggle.sh and fill in the relevant details. You can obtain HASS_TOKEN from your Home Assistant user account, and generate a long lived access token.

Save the contents of powertoggle.sh script to /home/pi/powertoggle.sh Save the contents of powertoggle.service to /lib/systemd/system/powertoggle.service

Run the following commands sudo systemctl enable relaytoggle sudo service relaytoggle start

[Unit]
Description=MoOde Power Toggle Daemon
[Service]
Restart=on-failure
WorkingDirectory=/home/pi
ExecStart=bash powertoggle.sh
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGINT
[Install]
WantedBy=multi-user.target
#!/bin/bash
HASS_URL='http://192.168.1.2:8123'
HASS_TOKEN='CHANGME';
HASS_ENTITY='switch.study_plug'
main() {
local currentState;
local isRunning;
currentState=false;
while true; do
cat /proc/asound/card*/pcm*/sub*/status | grep -qE "(RUNNING|PREPARED|DRAINING)";
isRunning=$?
if [[ $isRunning -eq 0 ]]; then
if ! $currentState; then
echo "Playback started. Turning power on";
currentState=true;
curl "${HASS_URL}/api/services/switch/turn_on" \
-s \
-H "Authorization: Bearer ${HASS_TOKEN}" \
-H 'Content-Type: application/json' \
-X POST \
-d "{\"entity_id\": \"${HASS_ENTITY}\"}"
fi;
elif $currentState; then
# Not running (but state is true) - monitor for 5m in case playback resumes
echo "Playback has paused";
for i in {1..60}; do
cat /proc/asound/card*/pcm*/sub*/status | grep -qE "(RUNNING|PREPARED|DRAINING)";
isRunning=$?
if [[ $isRunning -eq 0 ]]; then
break;
fi;
sleep 5
done
# Playback did not resume, turn off smart plug
if [[ $isRunning -ne 0 ]]; then
echo "Playback has stopped. Turnin power off";
currentState=false;
curl "${HASS_URL}/api/services/switch/turn_off" \
-s \
-H "Authorization: Bearer ${HASS_TOKEN}" \
-H 'Content-Type: application/json' \
-X POST \
-d "{\"entity_id\": \"${HASS_ENTITY}\"}"
else
echo "Playback has resumed";
fi;
fi;
sleep 5;
done
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment