home assistant gitlab ci

Continuous Integration/Deployment for Home Assistant with Gitlab CI

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

One of the best things about writing this blog is the interactions I have with other people. Of course it’s always nice to get feedback, whether it’s positive or (constructively) negative. It’s even better to see what similar projects other people are undertaking. Sometimes comments even start me off in a different direction than I had been taking.

This project was inspired by one such conversation. This started out rather gruff but actually ended up being really positive and motivated me to go further with an approach that I’d mostly dropped. The conversation in question was in relation to my recent “Seven Home Assistant Tips and Best Practices” post. Specifically it was around testing and deploying your Home Assistant config with Continuous Integration (via Gitlab CI).

I’m already familiar with Continuous Integration and Continuous Deployment through work. I had developed a minimal setup for validating my HASS config. However, I’d previously given up on it due to the slowness of Gitlab’s shared CI runners. What follows is my new attempt. Thanks to /u/automate_the_things and all the other commenters on that thread for the inspiration/persuasion to do this!

Setting Up a Local Runner

Ideally, I’d like to fully self host my own Gitlab instance. However, the recommended RAM requirements are between 4 and 8GB, which is a little ridiculous. Perhaps when I upgrade my server I’ll be able to spare enough RAM for this. For now I’m just running a local runner and connecting it to the cloud version of Gitlab.

I decided to go with deploying the runner as a Docker container and also executing my jobs also within their own containers. This fits with my recent Docker shenanigans and I’m familiar with this setup having deployed it for work. CI systems are one area where I’ve always felt that using containers makes sense, even before my recent Docker adventures. Each build running in it’s own container removes a lot of the complexity in managing build environments for different projects. It also means that your build machines only require Docker.

I set up my runner in a new VM on my main server. Then I pretty much just followed the official instructions to install the runner. I did convert the docker run command to a minimal docker-compose.yml file for ease of reproduction however:

Once that was done, I finished by getting the runner registered and connected to my project.

home assistant gitlab ci
Once your runner is active it should show up in your Gitlab runners page (accessible via Settings->CI/CD->Runners)

Build Pipeline Configuration

In my research for this project, I came across Frenck’s Gitlab CI configuration, which is really awesome (thanks @Frenck). I’ve based mine heavily on his with some tweaks for my configuration and environment. The finished pipeline runs the following jobs:

  • shellcheck – this job performs various checks on any shell scripts in the repository
  • yamllint – this job performs a full lint check of all my YAML files. Since I’ve never run this before it threw up loads of errors. I started fixing a few of these, but eventually marked the job with allow_failure: true to allow the pipeline to continue even with these errors. I’ll work on fixing these issues bit by bit over the next few weeks. I also remove some files which are encrypted with git-crypt
  • jsonlint – pretty much the same as yamllint, but for JSON files. Any files that are encrypted are excluded from this check.
  • markdownlint – similar as the previous jobs, but for checking of markdown files (such as the README.md file)
  • ha-latest – checks the HASS configuration against the current release of Home Assistant
  • ha-rc – runs a HASS configuration check against the next release candidate for Home Assistant
  • ha-dev – checks the HASS configuration against the development version of Home Assistant. Both of these jobs are configured to allow failure. This is just intended to give me advanced warning of and breaking configuration that may prevent HASS from starting up in a future release.
  • deploy – deploys the configuration to my HASS server. I’ll discuss this in more detail below.
home assistant gitlab ci
My full pipeline (note the yellow status of the failing yamllint job)

You can find the finished configuration in my hass-config repository.

Deployment Approaches

There are several ways I could have done the deployment, which may suit different scenarios:

  • We could use the Home Assistant Gitlab CI sensor to poll the pipeline status. We would then trigger an automation to pull down the configuration when the pipeline passes. I haven’t tried this approach. However, it is potentially useful if your HASS server and Gitlab runner are on different networks and your HASS server is not publicly available.
  • We could use a pipeline webhook from Gitlab to a webhook handler in HASS. This would trigger an automation similar to that above. Again, I haven’t tried this. It would be useful if your Home Assistant instance and Gitlab CI runner are on different networks. However, it would require your HASS instance to be publicly available.
  • Similar to the approach above you could trigger the HASS webhook handler from a job in your Gitlab runner directly with CURL (rather than using the built in webhooks). This has the advantage over the previous two approaches that it gives you an explicit deploy stage in your pipeline. This is turn gives you the ability to track deployments via environments. It’s also potentially a lot simpler, since it would only be triggered if the previous stages in the pipeline passed. You also wouldn’t have to parse the JSON payload.
  • The approach I have taken is to deploy directly from the runner container via SSH. This is because my runner and HASS machines are running in the same network and so I can easily SSH between them without having to open any ports through my firewall. It also centralises all the deployment logic in the CI configuration, without any HASS automations needed.

My Deployment Job

As per my CI configuration, the deployment job is as follows:

As you can see, this job runs in a plain Alpine Linux container and is deploying the the home-assistant environment. This allows me to track what versions were deployed and when from the Gitlab UI.

The before_script portion installs a couple of dependencies which we need for later and pulls the (password-less) SSH key we need for logging into the HASS server from the project variables. This is stored in the $DEPLOYMENT_SSH_KEY variable in the Gitlab configuration. The resulting file must have it’s permissions set to 600 to allow the SSH client to use it.

Moving on to the script portion. The first step performs the actual deployment of the repository to the server via SSH. Here we use our SSH key that we wrote out above. The public portion of this is installed on the HASS server as for the ci user. We also disable strict host key checking to prevent the SSH client prompting us to accept the fingerprint.

home assistant gitlab ci
The Gitlab CI variables page (accessible via Settings->CI/CD->Variables)

The SSH command connects to the server specified in $DEPLOYMENT_SSH_LOGIN, which is again set in the Gitlab variables configuration. This has the form ci@<hass host IP>. It should be noted here that the Alpine container defaults to using Google’s DNS. This means that resolving internal hostnames for your network will fail. I’m using the IP addresses for now to get around this.

Remote Control Commands

The SSH command sends a sequence of commands to be run on the HASS server. These commands are as follows:

  • cd /mnt/docker-data/home-assistant – change directory to the configuration directory on the server
  • git fetch – fetch all the new stuff via git
  • git checkout $CI_COMMIT_SHA – checkout the exact commit that we are running a pipeline for via one of Gitlab’s built in variables

This arrangement of commands allows me to control exactly what gets deployed to the server for each pipeline run. In this way we won’t accidentally deploy the wrong version if new code is checked into the server whilst our pipeline is running.

In order for the git fetch command to work another password-less SSH key is required. This time this is for the ci user on the HASS system. The public portion of this is installed as a deploy key for the project in Gitlab. I suppose it’s equally valid to pull changes via HTTPS (for public repos), but since the remote on my repository was already set up to use SSH I decided to continue using it.

Restarting Home Assistant from Gitlab CI

The second command in our script section is to restart Home Assistant after the configuration has been updated. Here we use CURL to call the homeassistant.restart service as per the API docs. The Home Assistant authentication token and URL are stored in Gitlab CI variables again.

Finally, we enter the after_script section, which will be executed even in the case that one of the above commands fails. Here we simply delete the id_rsa SSH key file.

I’ve restricted my deploy job to run only on pushes to the master branch. This allows me to use other branches in the repo as I please without having them deployed to the server accidentally. I’ve also used a tag of hass to prevent running on runners not intended for this job. Since I only have one runner right now this isn’t a concern, but having it in place makes things easier if/when I add more runners.


I’m really pleased with how this CI pipeline has turned out. However, I’m still a little concerned at how long all these steps take. The latest pipeline took 6 minutes and 42 seconds to run (plus the time it takes HASS to restart). This isn’t very much if it’s just a fire and forget operation. It is however, a long time if I am trying to iterate on my configuration. I’m going to play around with the runner configuration to see if I can get this down further. I also want to investigate options for testing on my local machine. In my previous attempt at this my builds could sit for longer than this waiting for one of Gitlab’s shared runners. So I’ve at least made progress in the speed department.

Next Steps

In terms of further improvements, I’d like better notifications of the pipeline progress and notifications when HASS competes it’s restart. I will implement these with Gotify. Right now I only get an email if the build fails from Gitlab. I’m also going to integrate the pipeline status into Home Assistant with the previously mentioned Gitlab CI sensor. I’m even tempted to turn one of my smart lights into a build light to alert me to problems!

I also want to take my use of CI in my infrastructure further. My next target will be building some modified Docker images for a couple of my services in CI. Deployment of the relevant Docker stacks is another thing I’d like to try out. I’ve not had chance to play with building containers via Gitlab CI before so that will be interesting.

I hope that you’ve enjoyed this post and that it’s inspired you to give something similar a go. Thanks to this pipeline I’ll never have to worry about HASS being unable to start due to a broken configuration again. I’m open to further improvements to this process. Please feel free to share any you may have via the feedback channels. Thanks for reading!

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.

automate dumb audio system

Automating My Dumb Audio System

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

Recently I’ve been on somewhat of a mission to improve the integration between my various media devices and my home automation system. One part which has until now been untouched is the main living room audio system, which is still somewhat dumb. I’m not all the way to automating this yet, but I’m making progress. In this post I’m going to detail my progress so far, the issues I ran into and how I’m planning to improve the integration in future. I’ll also partially review the different components involved.

The Audio System

As detailed previously, our living room audio is provided by a Polk Signa S2 soundbar. I really like this soundbar and it was a massive step up from the TV audio we had previously. The system was very easy to set up, pretty much plug in the HDMI ARC connection, turn it on and go. It came pre-paired with it’s wireless sub, so that just worked. I’ve had a few instances (maybe five or so the last few months) where the main unit was not able to connect to the sub on startup, which it communicates by flashing an LED. Turning the unit off and on again allows it to retry, which in my experience always works.

The audio quality is great to my ear, but I don’t consider myself an expert in audio stuff. It’s enough to fill our living space with sound and shake the walls if you turn the bass up!

automate dumb audio system
The soundbar in all it’s glory

Where this device falls down is the lack of easy integration with other devices. This is of course pretty normal in this space, but it doesn’t mean we have to accept it!

Clever, Dumb Speakers

On the surface the soundbar behaves somewhat intelligently. It will turn on when the TV comes on. Presumably this is done via HDMI CEC because it will also turn on when the TV is turned on via CEC. This means it isn’t just intercepting the IR commands from the TV remote. However, all my attempts to control the unit via CEC from the Raspberry Pi connected to the TV failed. Weirdly, the soundbar also won’t switch off when the TV is turned off via CEC, whereas it does with the remote. The soundbar also integrates the volume between the TV and itself and allows adjustment via either the TV or it’s own remote.

This is all nice for the “normal” case of just using the TV. We can just sit down and watch without having to find the extra remote and everything just works. Where it falls down is anything outside of this basic use case. The soundbar has basic preset modes for different applications, “movie”, “music” and “night mode”. It also has 3 levels of what it refers to as voice adjust, which amplifies the frequencies contained in human speech to make dialogue clearer (it actually works pretty well). None of these settings are available unless using the device’s own remote.

automate dumb audio system
The soundbar remote, most of the functions are only available via this remote

IR Control

As I couldn’t control the device via CEC, I was pretty much resigned to having to build an IR remote control device. The soundbar also has bluetooth, but it’s only for audio streaming. There doesn’t appear to be any control capability and it’s turned off when the device is in standby. I’ll come back to the bluetooth later, as I do have some ideas around it for future work.

After failing to find the time to build an IR blaster (hardware is hard), I decided to buy a Broadlink device. Specifically the Broadlink RM Mini 3, since they were fairly cheap and supported in Home Assistant.

automate dumb audio system
The Broadlink RM Mini 3, sitting happily in it’s place on the bookcase

When the RM Mini arrived I was pleased with how it looked and easily found a place for it on a bookshelf where it could see the TV and soundbar. The line of sight reaches across the whole of our living/dining area, so I was hoping the range would be sufficient to reach. As it would turn out I was right, there have been no problems so far.

OMG, That App

Setting up the Broadlink was an exercise in frustration, mainly because the IHC app is truly awful. No… that doesn’t cover it: the app is a train wreck on board a sinking ship that’s just been hit by a meteor. For example, on the sign up page, it gives you 60 seconds to both enter the validation code it sent you by email and type your new (and hopefully secure) password. Unfortunately, I don’t have a screenshot of this, since I don’t want to reinstall that natural disaster of an app to get one!

Who really thinks that one minute is enough to sign into their email (or even just switch to your mail app), grab and enter the code and generate and enter a reasonable password?! That’s even assuming the email comes through in that time. Repeat after me: Email is not a synchronous communication medium! It was not designed for real time communication, messages can be delayed for any reason. I use grey-listing on my server, which would have made it impossible for me to sign up had I not been able to temporarily disable it.

Always Remember: The Cloud is Just Someone Else’s Computer

The app will also fail to find the device if you are on separate networks and gives you no way just to enter its IP address. This meant I had to put my phone onto my IoT network, on which most outgoing traffic is blocked. I then had to punch holes in the firewall for the device and my phone, because the setup process requires Internet access. The one for the device may not be required, but it definitely didn’t work if my phone couldn’t get out.

A device like this really has no business needing Internet access in the first place. It could also be configured purely over the local network and even without an app if they just put an AP+captive portal configuration page on it. Sigh.

Anyway, I got it onto the network. Eventually. However, things didn’t get better from there.

Issues in Home Assistant

I set up the device in HASS thinking that the hard part was over and that it would be plain sailing from now on. That proved to be misguided. Upon running the broadlink.learn service via the dev-tools, nothing happened. When I checked the log via the info tab I got the message Failed to connect to device from the broadlink component.

Upon examining the code, I could see that this happens if the device fails to authenticate properly. The auth call comes from the underlying library, python-broadlink. I checked the latest version of this out (0.11.1) and tried the CLI tool with the latest version, which also didn’t work. The tool would just time out without getting any data back. Also, the little white LED on the device didn’t light up.

Fixing it… but not really

I checked out and installed the previous version (0.10) and tried the same thing and it worked! I was able to learn IR codes and send them back to control devices from the CLI. The next step was to work out what commit broke the library. I did this by git bisecting between the good version (0.10) and the bad version (0.11.1). The resulting commit was 38a40c5, where the approach to encrypting the payloads changed. By analysing the change set, I was able to come up with a patch for which I’ve submitted a PR.

I then decided to try this out by installing my version of the library inside my HASS Docker container (temporarily) to see if it resolved the issue. Weirdly, I ran into the same issue! After some debugging to make sure it’s picking up the right python module I did some packet captures with tcpdump. I could see that the authentication packet payload was different to that of the working library outside of HASS. At this point I’m a bit stumped. I’ve submitted an issue to HASS, but in the meantime I decided to come up with a workaround.

Unix to the Rescue

Since I now had a working CLI tool, I could now get the Broadlink working with HASS via the shell_command integration in HASS. I started by creating a new python virtual environment from inside my HASS container and installed my version of the python-broadlink library:

It’s necessary to do this inside the container because the command will be called from within the container by HASS, so we want to make sure that venv gives us a compatible python environment. The virtualenv will be persisted to the home assistant config volume.

The next step was to copy the Broadlink CLI tool into my shell_commands directory and update the she-bang on the first line with the output from the which command above:

I then wrote a simple wrapper script to save me from having to specify all the options in my HASS config files later (saved to shell_commands/broadlink_cli_wrapper.sh):

This just sends whatever comes in as argument 1 to the script with the broadlink_cli tool. Make sure to fill in the IP of your device and it’s MAC address (lowercase, bytes reversed).

HASS Configuration

Now we can move on to configuring this in HASS. I used the learning functionality of the CLI tool to grab the hex codes for each of the buttons on my soundbar remote. I then added them all to my HASS config (in a new package file):

Upon restarting your HASS instance this gives you a shell_command service for each button on the remote. I spent a little while testing all the commands via the dev-tools to make sure I had them all right.

Replacing the Remote

As a first step to fully automating the soundbar, I wanted to replace the remote with a card in my HASS UI. Then I don’t have to find the remote!

I started by creating several input_select entities for the source, effect and voice adjust options of the soundbar:

I then mapped the options to the correct service calls using automations:

Here, I make good use of the service_template option and the trigger object to map the services. The main downside of this approach is that the automation doesn’t trigger if you re-select the currently selected option in the UI. Since we have no idea what the actual state of the soundbar is, it would be useful to be able to do this.

I did something similar for the power state and mute state, this time using input_boolean:

This isn’t ideal, especially for the power state since because there is no state feedback it will often be out of sync. If I can get some feedback on the power state (see below) I intend to convert this to a template switch.

Creating Presets

I created a couple of scripts containing the preferred settings for both TV watching and music. These just set the settings in sequence, with some delays to allow the soundbar to react (it’s a bit slow):

I think I’ll comment out the power on step and following delay until I get the power feedback working. Currently if the state is inverted in HASS the script will not do the right thing. It’s annoying to have to make sure the states line up before triggering the script.

Lovelace UI

I created a card in Lovelace to allow me to control all of this. I don’t show the power control here, because I have another card which controls power for all my media devices.

automate dumb audio system
My Soundbar Card in Lovelace

Here’s the YAML:

That gives me pretty much full control over the soundbar from within HASS. I haven’t integrated the volume and bass controls yet, mainly due to the lack of level feedback. The volume is controllable from the TV remote and we don’t adjust the bass much. As such these aren’t really necessary right now.


Wow, that turned out to be a long post. It actually turned out to be a much larger project than I expected, given all the issues I ran into. If I’d have known how much trouble I was going to have with the RM Mini, I probably would have opted to build my own IR blaster with an ESP module. That said, now that it’s working, it’s great. The device also looks pretty good, which is a plus for something which must be located prominently.

I obviously want to get this working with the native HASS integration. Hopefully the integration will be fixed soon, but my workaround gives me a functional device in the meantime.

Further Work

I’d also like to fix the main defect in the current setup, which is the power feedback issue. This stands in the way of further automation, since currently you need to check the power state closely. I have a couple of possibilities for this. The first option is to use a power monitoring smart switch to detect when the soundbar is powered up. Whether this will be successful will depend on the power usage of the soundbar and the accuracy of the power monitoring. This also requires me to invest in further hardware.

The second option is to try and detect the soundbar via its bluetooth interface. My current plan is to do this via l2ping. I haven’t had much time to look into this yet, but if I could get it working that would be great. I already have a Raspberry Pi 3 in close proximity to the soundbar so that can do the detection. This can then be fused with the IR commands using a template switch in HASS.

If you made it this far, thanks for reading and getting through my rambling thoughts! I’ll be following up this post with further updates on fixing the problems detailed here, so please follow me if you’d like to see how I solve them.

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 tips and best practices

Seven Home Assistant Tips and Best Practices

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

I’ve been really busy with other things this week, so I haven’t had much time to work on computing projects. So, I thought I’d write a more informational post including some tips and best practices for Home Assistant configuration. I’m also starting to think more about tidying up my own configuration, so some of these are todo list items for me!

Home Assistant is rapidly moving towards being less reliant on textual configuration, with more and more configuration being available via the GUI. However, Paulus has stated that the YAML configuration will remain an option. For the time being, there is still quite a bit that absolutely needs to be configured via YAML. These tips are mostly around organising your configuration well in order to manage it’s complexity as it grows. Let’s get into it…

1. Use the secrets.yaml file (for everything)

I’ve put this one first because I believe it’s the single most important thing you can do which will allow you to manage your configuration. For anyone that’s not familiar with this, the secrets.yaml file allows you to remove all the sensitive data from your configuration files and store it in a simple key value file:

When you want to use a secret in your config, just prefix the name with !secret:

This should be used wherever you have any marginally sensitive data. Things like passwords and API keys are a given. However, host names, IP addresses, names of family members, times/dates of events and locations should also be hidden.

Separating these secrets out from your main configuration allows you to more easily share you configuration without leaking personal data. It also allows you to back up to locations where the data may become public. Your home automation configuration is a very personal thing! You can leak significant information about the operation of your home and family members.

It seems to be a common misnomer that this makes your system somehow more secure. It doesn’t! There is no protection (such as encryption) applied to the secrets file on the disk of your HASS system. What this does do is help prevent accidental data leakage. It won’t protect your secrets in the case that someone breaks into your HASS server and gets access to your raw config files. However, in that case you already have major problems.

EXTRA TIP: You can also use secrets in ESPHome, using the same syntax.

2. Store your configuration in Git

This one follows directly on from the use of the secrets file and is really enabled by it. Once you have removed all the sensitive data from your configuration, it becomes really easy to share it.

One of the best ways to share your configuration is to create a Git repository of it and publish it online via GitHub or GitLab. This forms a handy offsite backup. You also get the benefit of being able to track the history of your configuration and easily revert changes if you need to. Git was designed for managing software and your HASS configuration is software.

This is something I actually need to get much better at. Although I’ve had my configuration published for some time, I tend to let it get out of date with the local changes I make. This negates a lot of the benefits and makes it a pain to update it in one big blob. If I kept it updated better this would be more incremental and easier.

I’m not going to go into a detailed run through of how to get your config into Git. The Home Assistant documentation has a wonderful page to get you started. I go even further and use git-crypt to encrypt my sensitive files, like secrets.yaml so that even they can be included (without anyone being able to read them).

3. Group related items with packages

There are several ways to structure your configuration. Lot’s of people start out using a single large configuration.yaml file. Later on you may decide that this is unwieldy and decide to split it up.

In this case your configuration gets split by what kind of configuration it is. For example, automations go in one file (or directory), sensors in another, scripts in another and so on. The problem is that you end up with related configuration being all over the place, scattered throughout different files or directories.

Packages aim to solve this problem, by allowing related configuration to live together regardless of type. This means that you can put the configuration for an integration and any logic relating to it together. For example, here is a snippet from my vacuum package, in which I have both the vacuum integration config and the automations relating to the vacuum:

Shortly after starting with home assistant I started splitting up my configuration into directories based on configuration type. This served me well for a while, but over the last year or so I’ve been moving (slowly) towards using packages. Now all my new configuration goes into packages, but I still have a load of the older stuff to move over.

4. Use multiple triggers with and conditions

In my TV power saving automation from my last post I used multiple triggers with an and condition that checked the state of those triggers again. This is a generally useful pattern for anything where you want something to happen as soon as all relevant entities are in a given state.

For example, to run an automation when everyone goes out:

Of course, I could just use a group for that automaton. This pattern gets really useful where the states you want to check differ between entities – as in the TV example.

5. Use hass-cli for quick config checking and restart

When editing my config I prefer to use vim over SSH to the HASS server. I’ll usually also be using the Home Assistant GUI to debug and test things via the dev-tools. Switching pages in the UI every time I want to restart is a bit of a pain. This is especially annoying with the recent UI changes which put the config check and restart buttons underneath the (for me greyed out) settings for location, name, timezone, etc.

As such a quick way to check my config and restart is very useful. To this end I have this in my ~/.bashrc file on my Home Assistant server:

This relies on having hass-cli installed. The command first calls the homeassistant.check_config service and then calls the homeassistant.restart service. It would be better if hass-cli could return 0 or 1 depending on the state of the configuration check and so not call the next step. However, it seems like HASS also checks the config before restarting. Having the the config check there is still useful to alert you to an invalid config.

home assistant tips and best practices
HASS-CLI will alert you to an invalid config via a persistent notification

With this in place, all I need to do is temporarily pause my vim session (with Ctrl-Z), type hass-restart and wait for it to restart.

6. Use the trigger object for more general automations

When an automation has multiple triggers it is possible to customise its behaviour based on what entity triggered it. This is done via the trigger object, which is passed into the actions of the automation for use in templates.

Here is an example from my battery notifications:

As you can see this automation is triggered on one of several entity state changes (I shortened the list for reproduction here). The resulting notification however is customised to the particular entity which trigger the automation at that time.

7. Use entity ID lists in complex template sensors

Home Assistant has automatic state tracking logic used for determining when to update the state of a template sensor or binary sensor. However some templates, particularly those containing for loops are too tricky for it to work out. The workaround to this is to specify the entity IDs to track manually via the entity_id list.

home assistant tips and best practices
Even if your template works in the dev-tools it may not work in a sensor without specifying the entity IDs

For example:

I’m not sure why the sensor above would be useful (it’s a contrived example). I haven’t actually had the need to use a template like this so far, but it’s good to know how to make it work just in case I need it.


These are just seven items that I could think of, but I hope that you will find them useful. I’m sure there are probably many more tips and best practices for Home Assistant configuration. Feel free to share yours in the comments and other feedback channels. If I get enough suggestions I may do a crowdsourced follow up to this article!

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.

smart tv less dumb

Quick Project: Making my Smart TV Less Dumb

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

The word “smart” has become so loaded in these days of smart-this and smart-that. The question is what qualifies as “smart”? Surely the answer is some form of Internet connectivity? However, I’m not sure that goes far enough. I like to see some degree of interoperability with other systems before I call a device smart.

For me the other system in question is Home Assistant. I’m not going to call a device truly smart unless there is a way to make it integrate with HASS. Of course, HASS has a lot of integrations which should make it easy right?

Not so for my “smart” TV (a 2017 model Sony Bravia) which fits neatly into a chasm between Sony’s previous Bravia offerings and their Android TV line. As such the integration in HASS doesn’t work with it, because the service it relies on is not available on the TV and it’s not running the truly smart Android TV OS.

Sony just seem to have slapped Netflix, YouTube and a couple of other apps on the previous TV software, disabled the network control service (presumably because it didn’t work with those apps) and sold these as Smart. Seems pretty stupid to me. It’s a shame, because otherwise it’s a really nice TV. It’s high time I made this Smart TV less dumb.

Getting Smart

I’ve written previously about how I’ve integrated power switching for the TV into HASS via HDMI CEC and Node-RED. Well recently I’ve made a couple of improvements to this which have increased it’s utility and made my Smart TV slightly less dumb.

The first of these was to add a ping sensor to report on the power state of the TV. It seems like the TV has pretty rudimentary (but in my opinion good) power management, since it responds to pings when on and doesn’t when in standby.

Here’s the YAML for that sensor:

Basically this is just pinging once every 15s. I kept the repetitions this low in order to ping more frequently and still keep the network traffic low. If a ping is lost I’m not too worried since the next one happens pretty quickly. Also the TV is on a wired Ethernet connection, so packet loss is very low (as compared to wifi).

I’ve fused this with my existing power switch in order to overcome some reporting weirdness from the CEC switch. It seems to me that the TV doesn’t always report it’s power state, especially when turned off via the remote.

Here is the template switch that integrates the two:

This switch becomes the primary means for controlling and displaying the TV power state in HASS. Now it’s really reliable, with the caveat that it may not update the state immediately, due to the ping interval. This is something which I can live with because it will now show the correct state most of the time. Previously it showed the incorrect state most of the time!

Detecting Netflix

As I was port scanning the TV (what? you mean it’s just me that scans every device that comes into my house?), I noticed an that port 9080 was open. Some investigation proved that this port is opened by the Netflix app on the TV and low and behold, if I exit Netflix the port is closed.

This gives us a nice way to detect if Netflix is running on the TV. This is useful, because despite my protestations people in my household seem to want to use the native app rather than Kodi (instability of the Kodi plugin is one reason for this). This is unfortunate in that I can’t see the state in HASS and therefore have had to disable my automation to turn off the TV when nothing is playing, lest it switch off five minutes into a Netflix stream.

I used the command line binary sensor to detect the open port (thanks to VDRainer on the HASS community forums for helping me with an issue here):

Here we run an nmap command which will detect the open port, grep for the answer and output ON or OFF depending on the state. By default this will be run every minute, which is good enough for me. Unfortunately, I haven’t found a way to use secrets with the command, so you’ll need to insert the IP of the TV manually if you want to use this.

smart tv less dumb
The Netflix Sensor

This doesn’t give us any information on whether or what Netflix is playing, just that the app is open. That information is probably available via this port, since it seems to be running some kind of web service for remote control. Someone would need to do the relevant investigation to work out what the endpoints are though.

Putting It All Together

Now I can update my TV power off automation:

Here I’m triggering the automation if either the local Kodi player or the Netflix sensor are idle/off for 5 minutes. I also check that both of these are in the desired state in the conditions. The extra time condition is to account for the use of the TV YouTube app, which I can’t detect. It only tends to be used before 8pm, so I restrict the time that this automation runs just in case.


That actually turned out to be quite a long post for a ‘quick’ project! I’m pretty happy with this approach and it’s allowed me to bring back an automation which has been disabled for ages. Hopefully this can start saving some power again, since people still leave the TV on. Now if only I could detect that pesky YouTube app! Then I really will have made my smart TV less dumb, but not yet truly smart (at least as far as I’m concerned).

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 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:

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:

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:

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:


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.