Start stereo and select source in Spotify, Play

Hi,

I have installed Home Assistant, and I can see that Spotify works great, I am able to see what I am playing, change songs and select my devices in Source. I have two Android TV units, if I start them and select them in source, then press play it will play on the Android TV.

I want to make an automation, which first starts my android TV, via Harmony Hub or Broadlink IR signal. Then select the unit in the source list, wait for it to start and then press play. All with a single button.

How do I script this, I am new to this and this is my first project!

Delays are your friend!
I have something kind of similar for my morning announcement.
At 6am I turn on my stereo using the harmony hub, get a summary of the day over Apple TV and then switch to the radio, again using the harmony hub. After 1.5h the radio turns off again. I use delays between the steps to make sure that the device is actually on before the message starts.

See code below

- alias: Morning announcement
  trigger: 
    platform: time
    at: "06:00:00"
  condition:
    condition: and
    conditions:
    - condition: state
      entity_id: binary_sensor.workday_sensor
      state: 'on'
    - condition: state
      entity_id: input_boolean.vacation_mode
      state: 'off'
  action:
    - service: remote.turn_on   #turn on the receiver and set to apple tv
      data:
        activity: 29051799
    - delay: "00:00:20"
    - service: tts.google_say
      entity_id: media_player.family_room_apple_tv
      data_template: 
        message: "Good morning. The weather today will be {{states('sensor.pws_weather')}}. The high temperature will be {{states('sensor.pws_temp_c')}}. The chance of rain today is {{states('sensor.pws_precip_1d')}} percent. A drive to the airport will take {{states('sensor.travel_time_to_airport')}} minutes. A drive to the city will take {{states('sensor.travel_time_to_work')}} minutes. " 
    - delay: "00:00:45"
    - service: remote.turn_on   #turn on the normal radio
      data:
        activity: 29176372
    - delay: "01:30:00"
    - service: remote.turn_off   #turn it off after 1.5 hour as by then i will have left
      data:
        activity: 29176372

I’m on iPad at the moment so can’t put a proper example in for you, but if you wanted to improve this a bit - instead of delays, check out wait_template