Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Create an application that can work with the CMD4 add-on to Homebridge in order to control a SONOS speaker.



CMD4 


AnyDevice < Get > < AccessoryName > < Characteristic >
AnyDevice < Set > < AccessoryName > < Characteristic > < Value >


Lightbulb Characteristics

  • On
  • Brightness
  • Name


Fan Characteristics

  • Active
  • RotationSpeed



Javascript Script

Code Block
//  playMusic.js
//
// > SONOS_HOST=192.168.1.21 node playCBC.js Get anything On 1
//
// Parameters are:
//    Get <accessory name> <characteristic>
//    Set <accessory name> <characteristic> <value>
//
// SONOS_HOST=192.168.1.21 node playCBC.js Set BLAH On true

'use strict';

// Lightbulb
const CHARACTERISTIC_ON="On"
const CHARACTERISTIC_VOLUME="Brightness"
const CHARACTERISTIC_NAME="Name"

// Fan
//const CHARACTERISTIC_ON="Active"
//const CHARACTERISTIC_VOLUME="RotationSpeed"

//Sonos variables
const Sonos = require('sonos').Sonos
const sonos = new Sonos(process.env.SONOS_HOST)

//https://open.spotify.com/playlist/37i9dQZF1DXebxttQCq0zA?si=a5d96d1b91cb4e1e

const spotifyUri = 'spotify:user:spotify:playlist:37i9dQZF1DXebxttQCq0zA'
const volume = 10
const stopVolume = 10
const uriCheck = '37i9dQZF1DXebxttQCq0zA'

var length = process.argv.length;
var device = "";
var io = "";
var characteristic = "";
var option = "";

if (length == 2) process.exit(0);

if (length <= 2) {
   console.log("Usage: " + __filedevice + " <Get|Set> <AccessoryName> [Value]");
   process.exit(-1);
}

if (length >= 2) io = process.argv[2];
if (length >= 3) device = process.argv[3];
if (length >= 4) characteristic  = process.argv[4];
if (length >= 5) option  = process.argv[5];

// var sonos
//
// //determine device
// switch(device)
// {
//    case "KitchenSonos":
//       sonos = new Sonos('192.168.1.21')
//       break;
//    case "DinningRoomSonos":
//      sonos = new Sonos('192.168.1.26')
//       break;
//    default:
//      console.log("playMusic: Unknown Device '" + device  + "'");
//      process.exit(-1);;
// }



/*
* playMusic
*
*/
const playMusic = function(){


  sonos.currentTrack().then(track => {
      sonos.getCurrentState().then(state => {

          if (state == "playing" && track.uri.includes(uriCheck) ){
              console.log("No Action Required");
              return;
          }


          sonos.removeTracksFromQueue(1, 500)

          // const playmodes = ['NORMAL', 'REPEAT_ONE', 'REPEAT_ALL', 'SHUFFLE', 'SHUFFLE_NOREPEAT', 'SHUFFLE_REPEAT_ONE']
          sonos.setPlayMode('SHUFFLE').then(success => {
            console.log('Changed playmode success')
          }).catch(err => { console.log('Error occurred %s', err) })

          setVolume(0)

          //play
          sonos.play(spotifyUri)
          .then(success => {
            console.log('Yeay')
            setVolume(volume)
            return sonos.currentTrack()
          })
          .then(track => {
            console.log(JSON.stringify(track, null, 2))
          })
          .catch(err => { console.log('Error occurred %j', err) })


      });
  }).catch(err => { console.log('Error occurred %j', err) })

}

/*
* stop
*
*/
const stop = function(){

  sonos.stop().then(success => {
      console.log("Stop music on device: " + device + " done! ");
      setVolume(stopVolume)
  }).catch(err => {
    console.log('Error occurred %j', err)
  });

}

/*
* getState
*
*/
const getState = function(){


  sonos.currentTrack().then(track => {
      sonos.getCurrentState().then(state => {
        //console.log('uri: %s', track.uri)
        if (track.uri.includes(uriCheck) && state == "playing" ){
        //if (state == "playing" ){
          console.log('1');
        }else{
          console.log('0');
        }

      });

  }).catch(err => { console.log('Error occurred %j', err) })

}

/*
* getVolume
*
*/
const getVolume = function(){

  sonos.getVolume().then(volume => {
      console.log(volume);
  }).catch(err => { console.log('Error occurred %j', err) })

}

/*
* setVolume
*
*/
const setVolume = function(volume){

  if(volume <= 50){
    sonos.setVolume(volume).then(success => {
        console.log("Volume on device: " + device + " set to " + volume);
    }).catch(err => {
      console.log('Error occurred %j', err)
    });
  }else{
      console.log('Too Loud!')
    }
}

switch(io)
{
   case "Get":
   {
            switch(characteristic)
            {
               case CHARACTERISTIC_ON:
               {
                  getState();
                  break;
               }
               case CHARACTERISTIC_VOLUME:
               {
                  getVolume();
                  break;
               }
               case CHARACTERISTIC_NAME:
               {
                  console.log(device);
                  break;
               }
               default:
                 console.log("Unknown Characteristic for:"  + io  +  " Device:" + device  +  " Characteristic:" + characteristic);
                 process.exit(-1);
            }
            break;

   } // End of Switch for "Get"
   case "Set":
   {
            switch(characteristic)
            {
               case CHARACTERISTIC_ON:
               {
                  switch(option)
                  {
                    case "false":
                    case "0":
                      stop();
                      break;
                    case "true":
                    case "1":
                      playMusic();
                      break;
                    default:
                      console.log("Unknown Option '" + option + "' for:"  + io  +  " Device:" + device  +  " Characteristic:" + characteristic);
                      process.exit(-1);
                  }
                  break;
               }
               case CHARACTERISTIC_VOLUME:
               {
                  setVolume(option);
                  break;
               }
               default:
                 console.log("Unknown Characteristic for:"  + io  +  " Device:" + device  +  " Characteristic:" + characteristic);
                 process.exit(-1);
            }
            break;

   } // End of Switch Device for "Set"
   default:
      console.log("Unknown IO" + io );
      process.exit(-1);
}


...