Chromecast Radio with station and player selection

cheers. I don’t see gmusic in the general HA components and noticed you have ‘DEPENDS ON: pip gmusicapi’ at the top of your Git code. Is this something that needs to be added separately to a normal HA component? (I’m using HassIO so is this possible?)

You’ll need the gmusic stuff and the custom component, this thread explains it…

I haven’t re-read the thread before pasting the link so have no idea about hass.io integration.

unfortunately after just reading through it all it looks like it wont work in HassIO :frowning:

Maybe time to ditch the stabilisers and ride a two-wheeler :stuck_out_tongue_winking_eye:

hahahaha! Sometimes I do think I should have started with Hassbian, but before I started out, reading the HA page I honestly thought that HassIO was going to be the long term solution that Home Assistant would become… now its not looking quite so definitive. Not sure I can be bothered changing now. There are a few things like this gmusic functionality that I really do want though. Maybe someone like the HassIO genius @frenck can fix it for us :wink:

1 Like

In case it helps anyone (I know @Bob_NL was interested) I finally manage to “hack” a picture in the media_player entity.
It’s a little bit flaky (status changes multiple times before it settles) but it works.
It also means the off button will disappear, but once you press the stop button it’ll come back

I’ll see if I can improve it to make it better but for now here is what you’ll need in addition to what was described on this page.
***Disclaimer
will need adjusting, no garanties it’ll work

shell_command:

chromecast_radio_picture: /home/cctv/.homeassistant/shell_scripts/ChromeCast_Radio.py {{ my_media_player }} {{ my_radio_station }}

automation:

- alias: Set Chromecast Radio Picture
  trigger:
    - platform: event
      event_type: state_changed
  condition:
    - condition: or
      conditions:
        #list all chromecast media players here
        - condition: template 
          value_template: "{{ trigger.event.data.entity_id == 'media_player.kitchen' }}"
        - condition: template
          value_template: "{{ trigger.event.data.entity_id == 'media_player.bedroom' }}"
        - condition: template
          value_template: "{{ trigger.event.data.entity_id == 'media_player.house' }}"
        - condition: template
          value_template: "{{ trigger.event.data.entity_id == 'media_player.downstairs' }}"
        - condition: template
          value_template: "{{ trigger.event.data.entity_id == 'media_player.onkyo' }}"
    - condition: template
      value_template: "{{ trigger.event.data.new_state.state  == 'playing' }}"
    - condition: template
      value_template: "{{ trigger.event.data.new_state.attributes is not none }}"
    #only run if script triggered in last 30 sec to not overwrite other music services
    - condition: template
      value_template: "{{(as_timestamp(now()) - as_timestamp(states.script.radio538.attributes.last_triggered | default(0)) | int < 30 )}}"
  action:
    - service: shell_command.chromecast_radio_picture
      data_template:
        my_media_player: '{{ trigger.event.data.entity_id }}'
        my_radio_station: '{{ states.input_select.radio_station.state | replace(" ", "_") }}'

ChromeCast_Radio.py python script to be saved under shell_scripts folder

#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime
import sys
import json, requests, simplejson

HA_URL = "HA PUBLIC URL"
HA_PWD = "secret password"

##########################################
# Call the script with 2 parameters:
# parameter 1 is the full media_player entity name, e.g. media_player.bedroom
# Parameter 2 is the input_select of the selected radio station with spaces replaced with underscores, e.g. Absolute_Radio
##########################################

def HASS_API_State(Entity, State, Media_Title, Entity_Picture, media_content_id, friendly_name):
	url = HA_URL + "/api/states/" + str(Entity) + "?api_password=" + HA_PWD
	data={"state":"" + str(State) + "", "attributes": {"media_title": "" + str(Media_Title) + "", "entity_picture": "" + str(Entity_Picture) + "", "is_volume_muted": "false", "media_content_id": "" + str(media_content_id) + "", "friendly_name": "" + str(friendly_name) + "", "supported_features: ": "21437", "app_name: ": "ChromeCast Radio", "media_position: ": "0"}}
	headers = {'Content-type':'application/json', 'Accept-Encoding': 'text/plain', 'Accept': 'text/plain'}
	r = requests.post(url, data=json.dumps(data), headers=headers)
	c = r.content
	result = simplejson.loads(c)


if(sys.argv[2]=="RTL2"):
	HASS_API_State(sys.argv[1],"playing",sys.argv[2].replace("_"," "), HA_URL +"/local/RTL2.jpg", "http://streaming.radio.rtl2.fr:80/rtl2-1-44-96", sys.argv[1].replace("media_player.","").capitalize())

elif(sys.argv[2]=="Absolute_Radio"):
	HASS_API_State(sys.argv[1],"playing",sys.argv[2].replace("_"," "), HA_URL +"/local/Absolute_Radio.jpg", "http://icy-e-bab-04-cr.sharp-stream.com/absoluteradio.mp3", sys.argv[1].replace("media_player.","").capitalize())

elif(sys.argv[2]=="Absolute_Radio_Classic_Rock"):
	HASS_API_State(sys.argv[1],"playing",sys.argv[2].replace("_"," "), HA_URL +"/local/Absolute_Radio_Classic_Rock.jpg", "http://icy-e-bab-04-cr.sharp-stream.com/absoluteclassicrock.mp3", sys.argv[1].replace("media_player.","").capitalize())

elif(sys.argv[2]=="HitWest"):
	HASS_API_State(sys.argv[1],"playing",sys.argv[2].replace("_"," "), HA_URL +"/local/Hitwest.png", "http://broadcast.infomaniak.ch/hitwest-high.mp3", sys.argv[1].replace("media_player.","").capitalize())

elif(sys.argv[2]=="Chill"):
	HASS_API_State(sys.argv[1],"playing",sys.argv[2].replace("_"," "), HA_URL +"/local/Chill.jpg", "http://media-the.musicradio.com/ChillMP3", sys.argv[1].replace("media_player.","").capitalize())

create pictures of the various radio stations and save them in your HA installation folder in the www folder

1 Like

image

1 Like

@lolouk44 wow, great work thanks for sharing!

1 Like

Been working on this today based on some of the input in this thread.

I’m using automation instead of a script.
Under speakers I have an ‘off’ selection, which stops all streams.

Changing the radio station, changes the stream on speakers selected.

Still working through tracking states of devices, so that this interface will get updated if the stream is stopped by another means (I have some TTS functions).

Would be nice to have the entity picture update the radio stations list…

I use individual audio controls, as the mini/home need different settings.

triple

I am havinbg trouble with getting this working. I have tried to set it up as a package but it crashes my HassIO (it wont load the frontend and has the following in the log, however I dont see the issue. Can someone please help?

LOG

2018-02-12 10:49:16 ERROR (SyncWorker_0) [homeassistant.util.yaml] while parsing a block mapping
in “/config/packages/chromecast_radio.yaml”, line 76, column 7
expected , but found ‘-’
in “/config/packages/chromecast_radio.yaml”, line 84, column 7
2018-02-12 10:49:16 ERROR (MainThread) [homeassistant.bootstrap] Error loading /config/configuration.yaml: while parsing a block mapping
in “/config/packages/chromecast_radio.yaml”, line 76, column 7
expected , but found ‘-’
in “/config/packages/chromecast_radio.yaml”, line 84, column 7

chromecast_radio.yaml

group:
  radio:
    name: Radio
    entities:
    - input_select.radio_station
    - input_select.chromecast_radio
    - script.radio
    - input_slider.volume_radio

input_select:
  radio_station:
    name: 'Select Radio Station:'
    options:
      - Hit 92-9
      - Nova 93-7
      - Mix 94-5
      - 96FM
      - 80's
      - OldSkool Hits
      - Raw FM (dance)
      - 181FM Power (Todays Hits)
      - 181FM 90's Dance
      - 181FM Star 90's
      - 181FM The Breeze
      - Heat Radio (RnB)
      - Fresh 92-7
      - DI Chill & Tropical House
      - DI Disco House
      - DI Liquid D&B
    initial: Raw FM (dance)
    icon: mdi:radio
    
  chromecast_radio:
    name: 'Select Speakers:'
    options:
      - Lounge
      - Bedroom
      - House
    initial: Lounge
    icon: mdi:speaker-wireless

input_slider: 
  volume_radio:
    name: Volume
    icon: mdi:volume-high
    min: 0
    max: 1
    step: 0.05

automation:
  - alias: Listen Radio
    hide_entity: True
    trigger:
      - platform: state
        entity_id: input_select.radio_station
    action: 
      - service: script.radio
  - alias: Set Chromecast Radio Volume
    trigger:
      platform: state
      entity_id: input_number.volume_radio
    action:
      service: media_player.volume_set
      data_template:
        entity_id: >
          {% if is_state("input_select.chromecast_radio", "Lounge") %} media_player.lounge
          {% elif is_state("input_select.chromecast_radio", "Bedroom") %} media_player.bedroom
          {% elif is_state("input_select.chromecast_radio", "House") %} media_player.house_group
          {% endif %}
        volume_level: '{{  states.input_number.volume_radio.state  }}'

script:
  radio:
    alias: Play Radio on Chromecast Audio
    sequence:
    - service: media_player.volume_set
      data_template:
        entity_id: >
          {% if is_state("input_select.chromecast_radio", "Lounge") %} media_player.lounge
          {% elif is_state("input_select.chromecast_radio", "Bedroom") %} media_player.bedroom
          {% elif is_state("input_select.chromecast_radio", "House") %} media_player.house_group
          {% endif %}
        volume_level: '{{  states.input_number.volume_radio.state  }}' 
      -  service: media_player.play_media
         data_template:
           entity_id: >
            {% if is_state("input_select.chromecast_radio", "Lounge") %} media_player.lounge
            {% elif is_state("input_select.chromecast_radio", "Bedroom") %} media_player.bedroom
            {% elif is_state("input_select.chromecast_radio", "House") %} media_player.house_group
            {% endif %}
           media_content_id: >
            {% if is_state("input_select.radio_station", "Hit 92-9") %} http://sc01.scahw.com.au/6ppm_32
            {% elif is_state("input_select.radio_station", "Nova 93-7") %} http://streaming.novaentertainment.com.au/nova937
            {% elif is_state("input_select.radio_station", "Mix 94-5") %} http://sc01.scahw.com.au/6mix_32
            {% elif is_state("input_select.radio_station", "96FM") %} https://icy.ihrcast.arn.com.au/au_012_icy
            {% elif is_state("input_select.radio_station", "80's") %} http://streaming.the80s.com.au/;stream/1
            {% elif is_state("input_select.radio_station", "OldSkool Hits") %} http://sc01.scahw.com.au/loveland_32
            {% elif is_state("input_select.radio_station", "Raw FM (dance)") %} http://stream.rawfm.com.au:8000/;stream.nsv
            {% elif is_state("input_select.radio_station", "181FM Power (Todays Hits)") %} http://listen.181fm.com/181-power_128k.mp3?
            {% elif is_state("input_select.radio_station", "181FM 90's Dance") %} http://listen.181fm.com/181-90sdance_128k.mp3
            {% elif is_state("input_select.radio_station", "181FM Star 90's") %} http://listen.181fm.com/181-star90s_128k.mp3
            {% elif is_state("input_select.radio_station", "181FM The Breeze") %} http://listen.181fm.com/181-breeze_128k.mp3
            {% elif is_state("input_select.radio_station", "Heat Radio (RnB)") %} http://174.37.159.206:8106/stream
            {% elif is_state("input_select.radio_station", "Fresh 92-7") %} http://live.fresh927.com.au/freshmp3
            {% elif is_state("input_select.radio_station", "DI Chill & Tropical House") %} http://pub1.diforfree.org:8000/di_chillntropicalhouse_hi
            {% elif is_state("input_select.radio_station", "DI Disco House") %} http://pub1.diforfree.org:8000/di_discohouse_hi
            {% elif is_state("input_select.radio_station", "DI Liquid D&B") %} http://pub1.diforfree.org:8000/di_liquiddnb_hi
            {% endif %}
           media_content_type: 'audio/mp4'

You have different indentations on the two service tags in the radio script and a space too much between the hyphen and the second service.

2 Likes

Hi Bob,

I have just received my Cube and want to use code like this to control my amplifier volume. Currently I use a Broadlink IR transmitter to send commands to the amp because its old and has no smarts. Since the IR sends separate volume up and volume down commands, would I be able to use this code in a modified way to achieve this goal?

I have tried to set up the Broadlink custom component as per this which I guess may let me use your code directly?..?

Hi @Bob_NL,

I tried using your rotate code but got the following error:

2018-02-22 07:52:54 ERROR (MainThread) [homeassistant.core] Invalid service data for media_player.volume_set: value must be at least 0 for dictionary value @ data[‘volume_level’]. Got ‘-0.05’
2018-02-22 07:52:56 ERROR (MainThread) [homeassistant.core] Invalid service data for media_player.volume_set: value must be at least 0 for dictionary value @ data[‘volume_level’]. Got ‘-0.05’

any idea why this isnt working for me? Cheers.

edit, here is my cube rotate code:

alias: Cube - Rotate
initial_state: 'on'
trigger:
  - platform: event
    event_type: cube_action
    event_data:
      entity_id: binary_sensor.cube_158d00010fd152
      action_type: rotate
action:
  - service: media_player.volume_set
    data_template:
      entity_id: media_player.lounge_amp
      volume_level: >
        {%if trigger.event.data.action_value | float > 0 %} 
        {{  states.media_player.lounge_amp.attributes.volume_level | float + 0.05 }}
        {% else %} 
        {{  states.media_player.lounge_amp.attributes.volume_level | float - 0.05 }}
        {% endif %}

what I think I need is to generate a volume_up command on a clockwise rotation and a volume_down on an anticlockwise rotation but I dont know how to do this. Would love some help please.

Try it with brackets Dave - not sure it will make a difference tho’
{{ (states.media_player.lounge_amp.attributes.volume_level | float) - 0.05 }}

I just tried it but it makes no difference unfortunately

The + = clockwise and the - = anticlockwise in other words the cube generates a +ve number for clockwise and a -ve number for anticlockwise. So as it stands because the check is for > 0 then it’s generating a vol up for clockwise and vice versa. You may find that you need to change it to +/- 0.1 rather than 0.05, depends what the state table says, mine goes from 0 to 100% in steps of 10 but in HA it goes from 0.0 to 1 therefore I step it in 0.1 incements.

1 Like

What media platform are you using? Take a look at your entity attributes while playing audio to find out the naming and steps for the volume level.

I’m using the broadlink custom component to control the amplifier

so would there be a way I can extract the >0 / <0 data from the cube to send a volume up / volume down command, rather than an increment to the volume attribute?

Yep the component just sends a broadlink vol up/down packet and does not use an attribute, just do a vol up/down, so maybe…

  volume_level: >
    {%if trigger.event.data.action_value | float > 0 %} 
        +1
    {% else %} 
        -1
    {% endif %}

or put whatever the command is, I’ve not looked at the component yet :stuck_out_tongue: well not in any detail anyway :stuck_out_tongue: