Sonos: automation, scenes and specific playlists

Hi,

I’m trying to integrate my Sonos connect into my Home Assistant-aided home. There are a few things that I would like to do:

  1. Control Sonos in an automation-event [Solved]
  2. Control Sonos in a scene [Solved by @martinhjelmare]
  3. Control Sonos and play a specific radio channel [Solved]

I’ve been doing some searching but have thus far not been able to solve (2) and (3). Hoping that someone here has been successful! Will store the solution for (1) in case someone else is interested.


1. Control Sonos in an automation-event

automation:
  alias: "Turn of music when I leave home"
  trigger:
    platform: state
    entity_id: device_tracker.iphone
    from: 'home'
    to: 'not_home'
  action:
    service: media_player.turn_off

2. Control Sonos in a scene [Solved]

Here, I would like to set a dinner-scene which starts playing the Sonos and possibly runs some other stuff too. Trying to get the Sonos to work first though. The code below has been updated based on the solution provided by @martinhjelmare below and works on my configuration.

scene:
  - name: Dinner
    entities:
      media_player.kitchen:
        state: playing

3. Control Sonos and play a specific radio channel [Solved]

This is my current configuration, which unfortunately renders an error. I’m trying too play a specific playlist (tunein radio channel). Does anyone have a clever solution for this?

script:
  sonos_play_radio
    sequence:
    - alias: "Radio play"
      service: media_player.play_media
      data:
        media_content_id: x-rincon-mp3radio://fm03-icecast.mtg-r.net/fm03_mp3
        media_content_type: music

Thanks,
Patrik

1 Like

Please post your configs within code block markdown tags. That’s three back-ticks, newline, code, newline, three back-tics. It’s hard to troubleshoot format and syntax otherwise.

For number two, I suspect you have a syntax issue, perhaps indentation. State playing should be supported.

Thanks for pointing out how to comment configs, I didn’t know what syntax to use to make the code more readable.

I looked through the state.py-file and noted that playing was one of the allowed states, hence my trying it. Tried to remove the indent in the config-file as well as put playing within single quotes and typing it (without and without quotes) in large caps. None of these steps worked. Any other ideas on what I could try?

Thanks,
Patrik

For the scene you’re missing a colon after media_player.kitchen.

1 Like

It worked, thank you so much! Will update the first post with the correct solution.

1 Like

I was now able to solve the third problem too. Will update the code above accordingly. Still struggling with getting Sonos playlists to work but will look into it more tomorrow.

I had a similar issue getting sonos playlists to work, ended up resorting to using the sonos http api Component from this post http://www.makeuseof.com/tag/send-voice-notifications-sonos-speakers/ I was then able to use a script using curl to trigger playing the playlist via http://Pi_ip_address/sonos_device/playlist/playlist_name. There are probably a number of ways to achieve this, but this works for me right now!

I actually resorted to taking that route too. Works like a charm now!

Can you go into more detail on how you accomplished this, i.e. playing a specific sonos favorites station? I am a home assistant noob as I just started with it a short while ago.

Thanks!

Assuming you were able to install the sonos http api, I’ve got my whole config uploaded here:

Specifically, have a look at this file, where you will see the commands I invoke to play a playlist or a favorite:
https://github.com/ggravlingen/home-assistant/blob/master/extraconfig/shell_command.yaml

Other than the sonos-http-api, I’m also using this node-thingy to make sure the sonos-server autostarts:

Thanks,
Patrik

Were you able to create an input_select or input_boolean then?

Unfortunately not. As soon as I find the time, I’m planning to implement that too. :slight_smile:

I’ve now made a very simple Python script that queries the sonos http api for playlists and outputs them into a yaml-file that is picked up by Home Assistant. Python script below and rest of config (ie automation to start playing the playlist when it’s changed) is available on github.

Thanks,
Patrik


#!/usr/bin/python
import json, sys, urllib


# LOAD PLAYLIST-LIST IN JSON-FORMAT
url = "http://192.168.0.140:5005/kitchen/playlists"
response = urllib.urlopen(url)
data = json.loads(response.read())

f = open("/home/hass/.homeassistant/extraconfig/input_select/sonos_playlists.yaml","w")

f.write("sonos_playlist:" + "\n")
f.write("  name: Playlist" + "\n")
f.write("  options:" + "\n")
for key in data:
  f.write("   - '" + key + "'\n")

f.write("  icon: 'mdi:playlist-check'" + "\n")
f.close()


## Shell commands
f = open("/home/hass/.homeassistant/extraconfig/shell_command/sonos_playlist.yaml","w")


for key in data:
  keyname = ''.join(e for e in key if e.isalnum()).lower()
  keyvalue = urllib.quote(key)
  f.write("sonos_playlist_" + keyname + ": '/usr/bin/curl +X http://192.168.0.140:5005/kitchen/playlist/" + keyvalue + "'\n")

f.close()


@pautomate very nice, great example!! I ended up following your lead but used the SoCo library that HA already uses and straight automation. Mine looks like so:

from soco import SoCo
soco = SoCo('192.168.2.10')

favorites = soco.get_sonos_favorites()

### INPUT_SELECT ###
f = open("/config/other/input_select/sonosplaylist.yaml", "w")
f.write("sonosplaylist:" + "\n")
f.write("  name: Playlist Selection" + "\n")
f.write("  options:" + "\n")
f.write("   - \"-- Select --\"" + "\n")
for fav in favorites['favorites']:
    title = fav["title"]
    # uri = fav["uri"]
    f.write("   - \"" + title + "\"\n")

f.write("  initial: \"-- Select --\"" + "\n")

f.write("  icon: \"mdi:music-box-outline\"" + "\n")
f.close()


### AUTOMATION ###
f = open("/config/automation/sonosplaylist.yaml", "w")
for fav in favorites['favorites']:
    title = fav["title"]
    uri = fav["uri"]
    f.write("\n")
    f.write("  - alias: Playlist - " + title + "\n")
    f.write("    trigger: " + "\n")
    f.write("       platform: state" + "\n")
    f.write("       entity_id: input_select/sonosplaylist" + "\n")
    f.write("       to: \"" + title + "\"\n")
    f.write("    action: " + "\n")
    f.write("      - service: media_player.play_media" + "\n")
    f.write("        data:" + "\n")
    f.write("          entity_id: media_player.playbar" + "\n")
    f.write("          media_content_id: \"" + uri + "\"\n")
    f.write("          media_content_type: \"PLAYLIST\"" + "\n")
    f.write("      - service: input_select.select_option" + "\n")
    f.write("        data:" + "\n")
    f.write("          entity_id: input_select.sonosplaylist" + "\n")
    f.write("          option: \"-- Select --\"\n")
    f.write("      - service: notify.notifyall" + "\n")
    f.write("        data:" + "\n")
    f.write("          message: \"Playlist changed to: " + title + "\"\n")

f.close()

One thing I haven’t tested yet is whether this plays Pandora favorites correctly as I notices in the http_api source you used they have an option for credentials and I wonder if there needs to be some type of authentication going on… I’ll investigate later tonight and update as I find out more.

Playing pandora does result in an error because SoCo requires the ‘meta’ (at least a title per the docs). When I run the command manually from a .py file it starts the Pandora station just fine.

time for a feature request.

@kylerw Great to hear the base concept works in your environment, too! :slight_smile:

Has anyone managed to play a certain local mp3 file (or any audio file) as an action in an automation?

Absolutely. Just have to put it in the www directory (or somewhere where it can be accessed over the network by the Sonos device).

It can be accessed by Sonos, however I can’t find where to configure it in a HA automation.