Dynamically generate node sonos presets bash script
Posted: Tuesday 17 July 2018 12:37
Created this bash script to generate node sonos preset's dynamically from within Domoticz events and launch them.
This makes it significantly easier for me to control groups of speakers and play favorites from within Domoticz.
generate.sh
Domoticz Lua event example:
The above example starts playing my Sonos Favorite called "SmoothJazz.com" at 12 volume in both the Living Room and Kitchen.
I could add more speakers just by entering their names as more variables eg:
Makes it very, very easy. 
Notes:
1) The generate.sh script is set to delete everything in the presets path after each run, if you have any existing presets you may not want this! Change if necessary.
This makes it significantly easier for me to control groups of speakers and play favorites from within Domoticz.

generate.sh
Code: Select all
#!/bin/bash
# Requirements: apt-get install uuid-runtime
# Example usage: ./generate.sh 'SmoothJazz.com' '12' 'false' 'all' 'false' 'true' 'yes' 'Living Room' 'Kitchen'
# Configuration
nodesonosip="192.168.0.5"
nodesonosport="5005"
path="/root/node-sonos-http-api/presets"
# Variables
favorite=$(echo ${1})
volume=$(echo ${2})
shuffle=$(echo ${3})
repeat=$(echo ${4})
crossfade=$(echo ${5})
pauseothers=$(echo ${6})
playaftergenerate=$(echo ${7})
total=$(echo $(($#))) # Counts total number of args provided
unique=$(uuidgen)
# Print in terminal
echo "Generating dynamic $unique.json..."
# Echo top section
echo -e "{\
\n "players": [" > $path/$unique.json
# Generate section for each speaker
argcount="8"
for i in "${@:argcount}"; do
echo -e " {\
\n \"roomName\": \"${i}\",\
\n \"volume\": "$volume"\
\n }"$(if (( $argcount != "$total" )); then echo ',' ; fi) >> $path/$unique.json
argcount=$((${argcount}+1))
shift
done
# Echo the rest of the json
echo -e "],\
\n "playMode": {\
\n "shuffle": \"${shuffle}\",\
\n "repeat": \"${repeat}\",\
\n "crossfade": \"${crossfade}\"\
\n },\
\n "pauseOthers": \"${pauseothers}\",\
\n "favorite": \"${favorite}\"\
\n}" >> $path/$unique.json
# Tell node sonos to play the dynamically generated file?
if [ "$playaftergenerate" == "yes" ]; then
echo "Playing"
sleep 0.5
curl -s "http://$nodesonosip:$nodesonosport/preset/$unique"
fi
sleep 3
rm -rf $path/*
Code: Select all
commandArray = {}
if (devicechanged['Smoothjazz.com'] == 'On') then
os.execute("/root/scripts/sonos/generate.sh 'SmoothJazz.com' '12' 'false' 'all' 'false' 'true' 'yes' 'Living Room' 'Kitchen' &")
end
return commandArray
I could add more speakers just by entering their names as more variables eg:
Code: Select all
os.execute("/root/scripts/sonos/generate.sh 'SmoothJazz.com' '12' 'false' 'all' 'false' 'true' 'yes' 'Living Room' 'Kitchen' 'Main Bathroom' 'Bedroom Hallway' &")

Notes:
1) The generate.sh script is set to delete everything in the presets path after each run, if you have any existing presets you may not want this! Change if necessary.