home assistant android shortcut

Quick Home Assistant Shortcuts for Android

This week’s post is going to be a little shorter than normal, since I’ve been working on projects which aren’t ready to share yet. However, I did want to share a quick, but useful approach to controlling smart devices directly from the home screen of your Android device via some Android shortcuts and Home Assistant.

home assistant android shortcut
The home screen housing my HASS shortcuts

Let’s Get Started

The app I’m using to do this is called HTTP Shortcuts. It’s both free (as in beer) and Open Source. You could accomplish the same thing with Tasker and even though I also use Tasker, I still use this app. This is because it’s just a nice simple app that does one thing well. You can also execute these shortcuts from within Tasker if you would like.

home assistant android shortcut
Our HTTP Shortcuts variables

Before we create a shortcut, we’re going to add a couple of variables to make life a bit easier when creating multiple shortcuts. To do this press the {} icon in the top left corner. We are going to add two variables, one for the the HASS server name and another for the authentication token.

The first of these is easy, simply add a new variable with the plus icon and enter the key as ha_server. Leave the type as constant and add the hostname of your HASS server as the value. Make sure to not include the URL scheme here (http:// or https://) since this appears to throw off the regex validation when creating the shortcut.

For the second variable follow the same process, however you’ll want to insert the value of the long lived access token you get from your Home Assistant user’s profile page in the value field.

Creating Shortcuts

With that bit of prep done we can navigate back to the main page. Here we will add a new shortcut by again clicking the plus icon. First give your shortcut a name and description. These are only for your own use. You might also want to choose an icon at this point.

Next, hit the ‘Basic Request Settings’ item to and set the method to POST. In the URL field we enter the value:

https://{ha_server}/api/services/[domain]/[service]

Here you’ll replace [domain] with the entity type e.g. switch and [service] with the service name, e.g. turn_on. I find that using the toggle service is the most useful for these shortcuts, since you are usually using them in visual range of the device and it basically gives you two shortcuts in one.

The {ha_server} notation should be left as it is. This is using the variable we created earlier. Variables can actually be easily inserted with the {} button so there is no need to type it. You’ll also want to adjust my example above if you are using plain HTTP rather than HTTPS.

Adding Headers

The next stage of this is to add a custom header to our request. This is the Authorization header which has the value Bearer {ha_auth_token}. You’ll see here that we use the other of our variables to include the authentication token.

home assistant android shortcut
Our HTTP Header

Request Body

Finally we come to the request body. Here we set the request body type to ‘Custom Text’. The content type field here should again be set to application/json and the value should be the JSON to pass to the service. In the simple case this would just contain the entity ID you want to operate on, e.g {"entity_id": "switch.myswitch"}. Of course this might contain more data depending on the service you are calling. The data is exactly the same as that passed to the services developer tool in HASS, so you can test your calls there and then copy the data over.

home assistant android shortcut
Our finished shortcut

Final Steps

Once you’ve finished you can add the shortcut to the home screen via the long press menu on the main listing page. You can also export a copy of all your shortcuts via the settings page for use on another device. I don’t think this exports the values of your variables unless you checked the ‘Allow Share…’ advanced setting for the variable itself. This is most likely a good thing, since you’re going to want to use a different authentication token on each device.

I hope you’ve found this useful. I use these shortcuts every day and find them invaluable. The app has quite a bit more functionality which I haven’t covered here, including cURL import/export and processing of responses using Javascript.

For my regular readers, I apologise for the shorter post. It’s going to be a busy month coming up, but hopefully I’ll be back to my usual schedule soon. Thanks for sticking with me!

Home Assistant NFC Script

Home Assistant Automation in Depth: Multi-function NFC Tags

This post may contain affiliate links. Please see the disclaimer for more information.

This post is part of my “Home Assistant Automation in Depth” series. Here is the series index:

Welcome to the latest installment in my Home Assistant Automation in Depth series! In this article we’re going to explore how I’m using NFC tags with Home Assistant to control various aspects of my home automation. Specifically, I’m going to show my approach to making an NFC tag perform different actions depending on context.

I’m not going to dive headlong into an explanation of what NFC is. If you managed to somehow arrive at this page without knowing that, go and read the Wikipedia page! For our purposes it is sufficient to say that we can scan these little tags with our phone and some code will react to the scanning event.

How is NFC useful in Home Assistant?

Hopefully, you are already joining the dots in seeing how this is useful. Basically an NFC tag is a nice way to provide an input to a system. Think of it like a magic wireless button, that doesn’t need batteries! (assuming you charge your phone of course).

There is actually a little more to it than that. Since we won’t store anything sensitive on the tag itself we can safely leave them in public places. For example you could place one outside your front door. Only a phone which has been pre-configured with our setup will be able to execute the actions we have specified. Also, Android phones must be unlocked to scan the tags giving an extra layer of security.

There is a wrinkle with this, however. If someone knows the location of your tag they could potentially re-write it with some other (malicious?) data. There appears to be a way to write protect tags in the NFC Tools app I use below. However, I haven’t tried it yet. Make sure you do this if you want to place tags in areas where someone untrusted may have access!

Of course, the price of this is that you must have your phone on you which isn’t such a big deal. It may mean that you might not want to use these for tasks which need to be done very quickly or potentially with your hands full.

Connecting to HASS

There are at least two ways to connect NFC tags into Home Assistant. We can either use a dedicated app, or we can use Tasker with a plugin to accomplish the same thing. I’m going to describe the Tasker route, since I already had this in place before the HASS NFC app became available. Tasker is also allows you to do much more, so is a good app to have in any case.

The plugin we need for Tasker is called NFC Tasks and is free. In addition, we’ll need it’s companion app NFC Tools (also free) to configure our tags. You’ll also need Tasker and some NFC tags (obviously). I like the sticker variety (alternative link) for home automation purposes. However, they come in all kinds of shapes and sizes.

Once you have all the software installed it’s time to start connecting things up. First we’re going to want to setup Tasker to talk to Home Assistant via the REST API. This has got a little more complex if you want to use the new authentication system. However, there is a useful tutorial on the Home Assistant forum (thanks to @bokub for that!). This involves creating a specific task which can be re-used to talk to HASS. Go away and follow the instructions to do that now!

Welcome Back!

Once you’ve done that, you’ll need to set up another task (as detailed in the tutorial) which will be called when our NFC tag is scanned. I’m going to call a script, so mine looks like the screenshot below, but you can call any service in Home Assistant.

Home Assistant NFC
My task to be called when the tag is scanned

At this point you can test your task by executing it in Tasker and making sure it calls the right thing in HASS. You’ll then need to back right out of Tasker in order for it to apply the settings. If you don’t do this the task won’t show up later. Press the back button until you land back at the home screen, don’t just press the home button!

Writing the Tag

For the next part, we open the NFC Tools app and head to the tab called ‘Tasks’. Click the ‘Add a Task’ button, then navigate to ‘Various’ and ‘Tasker’. Hit the magnifier/search icon next to the task name input, then select the task you just created from the pop-up and press the ‘OK’ button. When you’re done, you should land at a screen like the one below. Hitting the write button will prompt you to scan the tag to write it.

Home Assistant NFC
Ready to write to the tag

If you now exit the NFC Tools app and scan the tag, you should see that your Tasker task is executed. This in turn performs your Home Assistant action.

At this point it should be noted that you can execute more than one task from a single tag. NFC Tool/Tasks also have a whole load of tasks built in, most of which I’ve not tried. Feel free to have a play around!

UPDATE: /u/databoy2k on reddit suggested an alternative way of doing this, which centralises more of the logic on the HASS server and so scales better to more tags/phones. I haven’t had time to try it fully yet, but I’ll probably switch over to it in future.

On the Home Assistant side

So now we have an NFC tag which can perform an action in Home Assistant. I’m now going to share how I’m using one particular tag as a multi-function switch for different modes in my house. I’ll start with an input_select to define the different modes I want:

input_select:
  home_mode:
    name: "Home Mode"
    options:
      - "None"
      - "Coffee Time!"
      - "Lunchtime"
      - "Bedtime"
      - "Night"

I’ve placed my tag on the door frame of the door between our kitchen/living area and the rest of the house. This means I can scan the tag when I go through the door to select a different mode.

The question now is, how does the system know which mode to select? I’m doing this based on time of day, since my modes are mostly based around different events which fit within a rough timeframe. You can use pretty much any state or information from Home Assistant via a template. Here is my script which achieves this:

script:
  home_mode:
    alias: Home Mode Switch
    sequence:
      - alias: Select Home Mode
        service: input_select.select_option
        data_template:
          entity_id: input_select.home_mode
          option: >
            {% if now().hour < 7 %}
            Bedtime
            {% elif now().hour < 12 %}
            Coffee Time!
            {% elif now().hour < 18 %}
            Lunchtime
            {% else %}
            Bedtime
            {% endif %}

The keen eyed among you would have noticed that this is the script which is being called when my NFC tag is scanned. Here I simply set the value of the input select based on time of day. You’ll see that ‘Bedtime’ appears twice in order to handle the before and after midnight cases. With this setup:

  • Scanning the tag between 7am and 12pm will set the mode to ‘Coffee Time!’
  • A scan of the tag between 12pm and 6pm will set the mode to ‘Lunchtime’
  • Scanning at any other time will set the mode to ‘Bedtime’.

Handling the Modes

I handle each mode via an automation. Firstly, let’s go with the ones for my coffee and lunchtimes:

automation:
  - alias: Coffee/Lunchtime Lights
    trigger:
      - platform: state
        entity_id: input_select.home_mode
        to: "Coffee Time!"
      - platform: state
        entity_id: input_select.home_mode
        to: "Lunchtime"
    action:
      - service: light.turn_on
        entity_id: light.kitchen_downlights

  - alias: End of Coffee/Lunch Time
    trigger:
      - platform: state
        entity_id: input_select.home_mode
        to: "Coffee Time!"
        for:
          minutes: 10
      - platform: state
        entity_id: input_select.home_mode
        to: "Lunchtime"
        for:
          minutes: 30
    action:
      - service: light.turn_off
        entity_id: light.kitchen_downlights
      - service: input_select.select_option
        data:
          entity_id: input_select.home_mode
          option: None

This basically implements some timed lighting for my break times during the day. I was always forgetting to turn off the kitchen lights when going back to work, so now I don’t have to. The timed lights also serve as a nice reminder that it is actually time to go back to work!

Since we already stored the state in the input_select we can use this as the timed trigger for the lighting off rule. This avoids the need for an external timer. Once we are done, we set the mode back to ‘None’

Next, we’ll tackle the bedtime mode. This is pretty simple, it just calls a script which turns off the lights and other appliances:

automation:
  - alias: Bedtime
    trigger:
      - platform: state
        entity_id: input_select.home_mode
        to: "Bedtime"
    action:
      - service: script.turn_on
        entity_id: script.bedtime
      - service: input_select.select_option
        data:
          entity_id: input_select.home_mode
          option: Night

Conclusion

So there we have it – a multi-functional NFC tag which triggers different actions in Home Assistant, depending on the time of day. This approach has been working really well for me for quite some time. I’ve only recently upgraded it to the new authentication scheme, but it works flawlessly.

With the power of Home Assistant scripts, particularly the templating options, this approach could be taken a lot further than the simple examples I’ve shown here. One idea would be to turn on or off different appliances dependent on the state of other sensors. Another is to perform different actions depending on who is home at the time.

There are also probably further extensions, like doing different actions depending on the phone which scans the tag. I suspect the logic for this would have to be built into the Tasker task on the phone. For example each phone could call a different script on the server.

I’d also like to give these a try for outdoor use, with the write protect enabled of course. I think I might need to find some more durable tags for that experiment however, the stickers don’t feel very weather proof.

I’m interested to see what else people are doing with NFC and Home Assistant. Please get in touch via the comments and Twitter to let me know!

If you liked this post and want to see more, please consider subscribing to the mailing list (below) or the RSS feed. You can also follow me on Twitter. If you want to show your appreciation, feel free to buy me a coffee.

Home Assistant Automation for My Mornings

Home Assistant Automation in Depth: Making my mornings a little easier

This post may contain affiliate links. Please see the disclaimer for more information.

I was recently asked by someone at work if I had succeeded in completely automating my house yet. My reply was something along the lines of: “Not yet, but I have got a few awesome automations running”. I then proceeded to give an explanation of my morning Home Assistant automation, which I’m going to document here.

Basically, when I get up in the morning and unplug my phone, the following Home Assistant automation is triggered:

  1. Turn on the lights in the kitchen
  2. Turn on the kettle (which has been set ready to go the night before)
  3. Wait five minutes (giving me time to stumble sleepily into the kitchen and it also happens to be roughly how long the kettle takes to boil)
  4. Turn on the TV
  5. Play a TTS based briefing, which includes the days weather forecast and current indoor temperature
  6. Play a two minute news summary from the BBC
  7. Five minutes after the news finishes, another automation kicks in, turning off the TV

Needless to say, my colleague was suitably impressed by this.

How does the house know I’m getting up?

I mentioned above that one of the first things I do when I get up is unplug my phone from its charger. This is key to triggering this Home Assistant automation. On my phone I have a Tasker profile running which will send a HTTP POST request to Home Assistant when the power state of the phone changes. This is used to update the status of a binary sensor in HASS, which reflects the charging state of my phone. Pretty simple.

Of course this wouldn’t work if I didn’t unplug my phone when getting up, or didn’t charge it overnight. Luckily I do, so this approach works well for me. I did initially play around with using a Baysian sensor to attempt to infer when I was in bed. However, that didn’t work very well for me due to lack of data. Most of the data points I had to use in the inference were things that I wanted to turn on from the automation, like the lights and kettle, which was unhelpful. Having extra sensors here, like motion sensors, would help.

The only downside of this approach (at least for me) is that Tasker is not Open Source and there is no viable FOSS replacement. I’m actively looking for replacements to Tasker for this. I’ll post an update if I ever find something that fits all my requirements.

Home Assistant Automation for My Mornings

The YAML code for this Home Assistant automation can be found in my HASS config, but I’ll go through it here. The first part is pretty standard:

automation:  
  - alias: 'Getting Up'
    trigger:
      platform: state
      entity_id: !secret device1_charge_status
      from: 'on'
      to: 'off'
    condition:
      condition: and
      conditions:
        - condition: state
          entity_id: group.presence
          state: home
        - condition: time
          after: "07:00:00"
          before: "10:00:00"

Here we see the trigger from the charging status of my phone. This is followed by a couple of conditions which restrict when the automation runs. If we’re not home for any reason it doesn’t make sense for the house to start turning things on and talking to itself, so that’s the first condition. The second is there just in case I need to charge my phone at other times of day. This only allows the automation to run between 7am and 10am. If my phone needs recharging (and is then unplugged again) before 10am then I’d probably be more worried about what is happening to my battery than the house starting talking.

The second part of the automation just turns things on and waits for me:

    action:
      - service: script.turn_on
        entity_id: script.downlights_bright
      - service: switch.turn_on
        data:
          entity_id: switch.kettle
      - delay:
          minutes: 5

The first script call there is a simple script to set the colour temperature of the kitchen downlight bulbs depending on the time of day, bluer during the day, redder in the evening. I use this script wherever these lights are turned on so that they are always at the right colour temperature. They also switch over in the evening, even if they are already on, thanks to my sunset automations.

Automating the Kettle

The next call there is simply turning on the kettle. This is connected to a dumb 433Mhz socket (controlled by OpenMQTTGateway). The reason for the dumb socket, rather than something smarter, there is that it’s the only one that I’ve found that is rated for the actual power draw of the kettle. It’s heating water from a 10A supply, so it actually pulls 10A. At 230V this is 2300W. Before anyone asks, I’m not taking account of the power factor here since I’d expect the kettle to be an almost purely resistive load. This socket is rated to 2400W and I’ve measured with a power monitor to make sure it stays below this. Most smart sockets on the market seem to only be rated up to 2200W for some reason.

Of course the kettle has to be set up with water in it and turned on at the base for this to work. The only approach to this is to program myself to do this before I go to bed. With this in mind I have another automation which turns off the kettle and sends me a notification to remind me to set it up.

The final call here is the delay. I played around for a while with the value and 5 minutes seems to be about right. Once I get some more sensors installed (door and/or motion sensors), I’ll tweak the rest of the automation to be triggered on the first time someone enters the kitchen.

Making the house talk

Now we get to something more interesting:

      - service: input_boolean.turn_on
        entity_id: input_boolean.tts_enabled
      - condition: state
        entity_id: media_player.tv
        state: idle
      - service: script.turn_on
        entity_id: script.tts_status_report
      - delay:
          seconds: 33
      - service: tts.picotts_say
        entity_id: media_player.tv
        data_template:
          message: "The latest news from the BBC follows:"
      - delay:
          seconds: 5
      - service: script.turn_on
        entity_id: script.play_news_summary

Most of this references my TTS package, which manages TTS announcements in my home. TTS here is provided by PicoTTS for its offline capability. I don’t want anyone listening in to my highly private weather forecast announcements. I’ve been told the voice is a little robotic, but I’d rather my computer sounds like a computer than a real person. Right now all my TTS announcements are sent to the Kodi instance running on the living room TV for playback.

The first thing to do here is to enable TTS notifications which are turned off overnight via an input boolean. All my TTS notifications go through a script which checks this is enabled before talking. This also handles turning on the TV ready to speak:

script:
  tts_living_room:
    alias: "Living room TTS announcement"
    sequence:
      - condition: state
        entity_id: input_boolean.tts_enabled
        state: 'on'
      - service: switch.turn_on
        entity_id: switch.living_room_tv
      - delay:
          seconds: 3
      - service: tts.picotts_say
        entity_id: media_player.tv
        data_template:
          message: "{{ message }}"

Before we get to the actual morning briefing there is one more check to do. This handles the case that I get a lie in and the rest of the family are up before me (rare!). In this case it’s likely that the TV is already playing something, so we can check if it is idle before continuing.

The Morning TTS Briefing

Now comes the TTS briefing, which is implemented by the following script:

tts_status_report:
    alias: Morning
    sequence:
    - service: script.tts_living_room
      data_template:
        message: >
          {% if now().strftime("%H")|int < 12 %}
          Good morning.
          {% elif now().strftime("%H")|int < 18 %}
          Good afternoon.
          {% else %}
          Good evening.
          {% endif %}
          It's currently {{states.sensor.dark_sky_summary.state}} and {{states.sensor.dark_sky_temperature.state|round}} degrees. The weather for the next 24 hours will be {{states.sensor.dark_sky_hourly_summary.state|replace(".", "")}}, with a high of {{states.sensor.dark_sky_daytime_high_temperature.state|round}} and a low of {{states.sensor.dark_sky_overnight_low_temperature.state|round}}.
          The current average indoor temperature is {{ states.sensor.average_indoor_temperature.state }} degrees.

This gives me a pretty good overview of the day. At some stage I’d like to add notification of upcoming calendar events from Nextcloud via CalDav, but I haven’t got around to it yet. The variable greetings based on time of day add some complexity to the templating. These aren’t necessary for this application, but they enable easy reuse of the script for other purposes. Perhaps a returning home announcement?

The next part of the automation is a bit of a hack. The problem appears to be that HASS will continue executing the automation without waiting for the TTS to finish. For now I wait a fixed delay after each part of the announcement before starting the next. Waiting for the media player to change state back to idle would be better, but I haven’t worked out how to do that yet. I haven’t got the timings quite right since the announcement time varies slightly (depending on the weather!). There is a little bit of delay between each part, but it’s acceptable.

The next part does a simple TTS announcement which introduces the news, bypassing the main TTS script because we just ran it. In this case everything is ready and we don’t want the extra delay that script introduces.

Playing the news

The BBC have a nice two minute news summary, which is available as an MP3 file. This will play fine directly from the web via Kodi and Home Assistant’s media_player.play_media service, if you can get the URL, which is something the BBC don’t make particularly easy. There is no podcast RSS feed for this as there are for many other BBC shows. They also seem to be going out of their way to deliberately obfuscate the URL. My script has broken once already in the <6 months I’ve had it running. Since it’s probably subject to change in the future I won’t embed my URL extraction script here, just follow the link to the latest version. Suffice to say Python+BeautifulSoup to the rescue!

This script is run via a command line sensor in HASS, which updates once per hour. Again, this is to make the resulting script more re-usable – it will always play the latest news:

sensor:
  - platform: command_line
    name: BBC News Summary URL
    scan_interval: 3600
    command: "/home/homeassistant/.homeassistant/shell_commands/extract_news_link.py"

Then there is the corresponding HASS script, which sends the URL to the media player:

script:
  play_news_summary:
     alias: "Play a BBC News Summary"
     sequence:
       - service: switch.turn_on
         entity_id: switch.living_room_tv
       - service: media_player.play_media
         entity_id: media_player.tv
         data_template:
           media_content_id: "{{ states('sensor.bbc_news_summary_url') }}"
           media_content_type: "music"

And that’s pretty much it.

Conclusion

This setup has been working pretty well for the last few months, with a couple of minor hicups caused by external factors. The change to the BBC news obfuscation was one. The other was an issue with Node-RED on the Pi connected to the TV, which caused it not to be able to turn on automatically).

The only other issue I have with this is with regards to the TV volume. The TV remote control does not pass through button presses of the volume keys via HDMI CEC. Therefore, we use the TV volume as the master, with the other volume controls in Kodi/Alsa set to maximum. The problem with this is if it is left on a high volume the night before you’ll get a very loud TTS announcement in the morning! Since the volume level on the TV is not controllable from HASS I can’t adjust the volume to an acceptable level before playing the TTS. The solution to this is to use the Kodi volume control as the master volume, which is controllable from HASS. This requires a new remote for use with Kodi and I’m still looking into options here.

Further Improvements

Aside from the improvements listed above, I’d also like to expand the information given in the TTS briefing. I’ve already touched on adding calendar events. Adding UV exposure information would also be very useful, given the lethal NZ sun.

Hopefully, someone will find some of the approaches and information in this post useful. There are a lot of example configurations available for HASS now. However, it’s often hard to piece the parts together that make everything work for a specific Home Assistant automation without a detailed explanation. This is something I’d like to do more of for my own setup, so hopefully there will be some more posts covering other parts of my configuration in future. Until then, bye.

If you liked this post and want to see more, please consider subscribing to the mailing list (below) or the RSS feed. You can also follow me on Twitter. If you want to show your appreciation, feel free to buy me a coffee.