mysensors greenhouse sensor

Prototyping Battery Powered Sensors with MySensors and Home Assistant

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

Sometimes it’s nice to be able to undertake a spur of the moment project that can be completed in a couple of hours. Of course, this rarely happens if the project is hardware related due to the need to wait for any parts you may not have to hand. This article will relate one such rare occurrence in my decision to try out the MySensors project for an outdoor, battery powered sensor prototype which would be integrated with Home Assistant.

The motivation for this project was the installation of a small greenhouse kit from the local hardware store, so that we had somewhere sheltered to raise seeds for the garden. The positioning of the greenhouse is along the back wall of our house, which gets quite a bit of sun. I realised it would be nice to log the temperature inside the greenhouse and send notifications when it was outside certain thresholds. I could then go out to open the door and otherwise check on the seedlings. As you will see below, I was able to build such a sensor very quickly and get it running using pretty much unmodified example code.

About MySensors

MySensors is an Arduino library for building low power mesh networked sensors based NRF24L01+ and RFM69 radios. It allows you to easily get the networking up and running so you can focus on building and deploying your sensors.

The sensors connect back to a gateway device which forwards traffic on to some controller software. There are several different types of gateway available, ranging from a simple serial gateway to networked options using MQTT and the ESP8266. There are also several different controllers available. However, I’ll be focussing on using Home Assistant.

Since these sensors are based on relatively low powered components, such as low bit-rate radios and 8-bit Arduinos they are much more suited to battery operation than the equivalent ESP8266 or ESP32 based sensor. The trade off for this is that the performance and capabilities are lower. For that reason I’d advise you to use an ESP based system with ESPHome if you have a decent power supply available or where you are actuating devices that already have higher power requirements. This is because MySensors actuation devices are not allowed to sleep in order to receive commands, which negates many of the power savings.

Parts and Assembly

For my initial deployment I wanted to test the power usage of a sensor in the field so as to see if this approach is viable. This sensor would use a DHT11 temperature and humidity sensor along with the radio and would be powered from 2xAA batteries. I also built a simple serial gateway which I connected directly to my main server via USB.

mysensors home assistant
The assembled gateway
mysensors home assistant
The assembled electronics for the sensor

The parts used in my build were as follows:

mysensors case
The sensor case, fresh off the printer
mysensors case
Packing the electronics in the case resulted in quite the birds nest
mysensors case
However, everything looked neat with the lid on!

These were assembled pretty much as per the instructions. First I connected up the radios to both gateway and sensor. I then connected up the DHT sensor and the battery holder on the sensor side. It’s worth noting that I used digital pin 4 rather than pin 3 for the DHT because I connected it without looking at the instructions. However, it makes little difference, just a minor change to the example code.

I didn’t make any hardware optimisations for low power usage at this stage, except for the obvious one of removing the power LED on the pro mini board (LED1 on the schematic). This will save a significant amount of power, since otherwise it would be on all the time.

Software

The software side of things was even more trivial than the hardware. For the gateway I just flashed the provided serial gateway code. For the sensor I just flashed the DHT example code with the small modification to the pin noted above. Both of these just worked without any further tweaking. The DHT example did require me to include a custom DHT sensor library which I copied from the git repo in question.

I used my preferred tool of Platformio for building and flashing. The only things to consider here are to initialise the projects with the correct board names (diecimilaatmega328 and pro8MHzatmega328 in my case) and to install the MySensors library in each project. This can be accomplished with the command:

platformio lib install --save MySensors

If you want to reproduce my exact setup or use it as a basis for your own, you can grab my code from GitLab.

Connecting MySensors to Home Assistant

With the firmware flashed to the devices, the next step is setting up the MySensors controller in Home Assistant. The first step in this process was making the serial adapter of the Arduino available through the layers of virtualisation in my setup. In order to do this I first added the serial adapter as a USB device to the KVM virtual machine via virt-manager. Secondly, I added the device to the Home Assistant container in my docker-compose.yml file with the entry:

devices:
  - /dev/ttyUSB0:/dev/ttyUSB0

Once the deployment had finished, I was able to add the MySensors integration to my Home Assistant configuration, which I did in a new package file:

mysensors:
   gateways:
     - device: /dev/ttyUSB0
       persistence_file: '/config/mysensors.json'
   debug: true
   persistence: true
   version: '2.3'
   optimistic: false

This sets up the integration with a single serial gateway on the port in question. With HASS restarted after this change, I was able to see my sensors. However, the entity IDs and resulting friendly names are based on the MySensors internal identifiers. I don’t really mind the cryptic entity IDs, but I updated the friendly names by adding the following to my customize section:

sensor.temperatureandhumidity_3_0:
friendly_name: "Greenhouse Humidity"

sensor.temperatureandhumidity_3_1:
friendly_name: "Greenhouse Temperature"

Notifications

The final step in the HASS setup for this achieves the goal of being notified when I need to check on the seedlings. This was accomplished via a couple of simple automations:

automation:
  - alias: "Greenhouse High Temperature Notification"
    trigger:
      platform: numeric_state
      entity_id: sensor.temperatureandhumidity_3_1
      above: 27
      for:
        minutes: 30
    condition:
      condition: state
      entity_id: input_boolean.greenhouse_active
      state: 'on'
    action:
      service: notify.family
      data_template:
        title: "Greenhouse Temperature High!"
        message: "The greenhouse temperature is {{ states.sensor.temperatureandhumidity_3_1.state }}{{ states.sensor.temperatureandhumidity_3_1.attributes.unit_of_measurement }}. You may wish to open the door and check if the plants need watering."
  - alias: "Greenhouse Low Temperature Notification"
    trigger:
      platform: numeric_state
      entity_id: sensor.temperatureandhumidity_3_1
      below: 11
      for:
        minutes: 30
    condition:
      condition: state
      entity_id: input_boolean.greenhouse_active
      state: 'on'
    action:
      service: notify.family
      data_template:
        title: "Greenhouse Temperature Low!"
        message: "The greenhouse temperature is {{ states.sensor.temperatureandhumidity_3_1.state }}{{ states.sensor.temperatureandhumidity_3_1.attributes.unit_of_measurement }}. You may wish to close the door."

These are pretty simple and send the notifications via my Gotify server. The only minor bit of complexity was that I added an input boolean to allow the notifications to be controlled together. I could just as easily turn off both automation rules when the greenhouse is not in use, but it’s nice to have a single switch for that purpose:

input_boolean:
  greenhouse_active:
    name: "Greenhouse In Use"
    icon: mdi:sprout

Range Issues

With all that in place, I tested the sensor overnight inside the house and then deployed it the following morning. I had placed it inside as close to the back wall where the greenhouse is located as possible and it worked fine. It even worked fine after deploying it in the greenhouse for around 12 hours.

mysensors greenhouse sensor
The sensor deployed inside the greenhouse (from inside)
mysensors home assistant
From outside the plastic of the greenhouse protects the electronics from the elements

Then it stopped sending data.

I brought the sensor in and examined it. The battery voltage was fine and after a reset it came back up, so I deployed it again. The same thing happened within a few minutes. I then brought the sensor back inside and put it in the garage, just a few meters from the gateway. It’s been operating there successfully for several days.

I can only conclude from this that the radio range is pretty poor. I have a couple of mitigations in mind for this, the first of these will be to move the gateway closer to the garden. For this I may need a networked gateway, or I may plug it into a nearby Raspberry Pi. I’ll try the Raspberry Pi idea first and see if I can get it working with the Node-RED MySensors nodes. Ideally, I’d like these just to operate as a proxy so that the MySensors controller will still be Home Assistant.

The other potential mitigation is to use a radio with a higher gain antenna and amplifier on the gateway. I may do this anyway in time in order to get better range into the garden for other sensors.

Conclusion

Overall I’m pretty pleased with the MySensors setup I’ve been able to create here. It’s very much a prototype and there are still a few issues to work out, but it’s promising. The best thing is that it only took me a couple of hours, though this was aided massively by having the parts already to hand.

MySensors itself seems quite nice and there is certainly a large community around it. As compared to other offerings such as ESPHome, it feels a bit basic to actually have to write (or copy) Arduino code and upload it to the device. I much prefer the YAML approach for describing simple sensors. That said, I still had to write no code in order to get this working! I’d love to see a similar YAML based code generator for this platform though.

I’ll definitely be building and deploying a few more MySensors nodes, primarily in the garden where ability to run off batteries for a decent length of time is a great advantage. However, I need to fix the range issue first, which I’ll be sure to post an update on.

As always please get in contact to share your own experiences!

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.

rasperry pi usb power switching

Switching Raspberry Pi USB Power via Home Assistant and Octoprint

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

Over the last week, I’ve been continuing my 3D printing journey by getting my Octoprint system up and running. I’ve also been integrating Octoprint with Home Assistant. One of the annoyances I encountered along the way is that the Ender 3 will accept power over the USB connection. This is useful for programming, but annoying in normal use. This means that the control board to the printer and the display will always be powered when the Raspberry Pi running Octoprint is powered up, even if the printer power supply is powered down. In order to solve this, I began looking into ways of switching the power of the USB ports on the Pi 4. The solution I found is more generally useful in home automation.

rasperry pi usb power switching
Without this trick the annoyingly bright LCD display is always on when the Octoprint system has power

If you’ve followed my approach to home automation, you’ll know I make heavy use of the Raspberry Pi in my media systems and elsewhere. The latest addition of the Octoprint systems brings the number of Pis in the house to five. Most of these have some kind of USB peripheral plugged into them. Being able to power cycle a misbehaving peripheral without interrupting other operations on the device or trying to reach into whatever crevice hosts the Pi is very useful. This approach also opens up more avenues when integrated with Home Assistant. Dumb USB devices can now be powered off and on easily.

Some of this post it relevant to a stand-alone Home Assistant based setup and the rest is more relevant to Octoprint. I’ve tried to separate the two parts so you can skip the sections you’re not interested in.

Getting Started

The key to this is a utility called hub-ctrl.c, which as it sounds is a utility for controlling USB hubs, in a single C file. There is also a package in the raspbian repositories called uhubctl, but in my testing this didn’t work with the Raspberry Pi 4. hub-ctrl.c must be compiled from source, but since it’s a single C file this is trivial. The following commands will download, compile and install it along with it’s dependencies:

$ sudo apt install libusb-dev build-essential git
$ git clone https://github.com/codazoda/hub-ctrl.c.git
$ cd hub-ctrl.c
$ gcc -o hub-ctrl hub-ctrl.c -lusb
$ sudo mv hub-ctrl /usr/local/bin/

Once this process is complete you can start playing around with your USB ports (use the -h flag to see the arguments). Passing the -v flag will show a detailed listing of the current port status.

In my experiments I found that the power to my ports would not shut off unless I individually powered down all the ports on hub’s 1 and 2. It’s possible that this would interfere with the Ethernet if it were in use, but it’s perfectly fine over wifi. Basically it seems that the USB implementation on the Pi 4 is somewhat buggy. The upshot of this is that I must also power down the attached USB webcam. This adds some complications to my scripts later. It’s worth trying this on some of the other Pi models to see what the experience there is like.

I implemented the following script to power down the USB ports (in /usr/local/bin/psu_off.sh):

#!/bin/bash

systemctl stop webcamd
sleep 2

hub-ctrl -h 2 -P 1 -p 0
hub-ctrl -h 2 -P 2 -p 0
hub-ctrl -h 2 -P 3 -p 0
hub-ctrl -h 2 -P 4 -p 0
hub-ctrl -h 1 -P 1 -p 0

There is also a corresponding power up script (/usr/local/bin/psu_on.sh):

#!/bin/bash

hub-ctrl -h 2 -P 1 -p 1
hub-ctrl -h 2 -P 2 -p 1
hub-ctrl -h 2 -P 3 -p 1
hub-ctrl -h 2 -P 4 -p 1
hub-ctrl -h 1 -P 1 -p 1

sleep 2
systemctl start webcamd

The systemctl lines in there are for stopping and starting the webcam service, due to the aforementioned issue. You’ll either want to substitute in any services that may be dependent on the USB devices (and won’t detect the disconnect/reconnect) or just remove these lines.

Permissions

The hub-ctrl tool typically needs running via sudo. Since we’re going to want to run this tool from another system we should allow our normal user permission to do this without a password. You may even want to create a new user just for this purpose if you really want to lock down this ability.

To allow the use of our scripts without a password run the command sudo visudo /etc/sudoers.d/usb-power and add the following contents:

pi ALL=NOPASSWD: /usr/local/bin/psu_on.sh
pi ALL=NOPASSWD: /usr/local/bin/psu_off.sh

Of course you can update the username here if you opted to use another user. For my later use case with Octoprint, I need to use the Pi user.

Integrating with Home Assistant

We can integrate this with Home Assistant via a command line switch:

switch:
  - platform: command_line
    switches:
      pi4_usb_power:
        command_on: /usr/bin/ssh -i /config/id_rsa -o StrictHostKeyChecking=no pi@IP_ADDR sudo psu_on.sh
        command_off: /usr/bin/ssh -i /config/id_rsa -o StrictHostKeyChecking=no pi@IP_ADDR sudo psu_off.sh

You’ll obviously need to substitute in the address of your Pi as well as set the path to your SSH key. This key should be installed on the Pi. Right now I’ve left this open so this key can execute any command within the permissions of the Pi user. If you want to lock this down you need the ability to execute multiple remote commands. Follow this ServerFault thread to implement this.

Integrating with Octoprint

If you just came for the USB power switching with Home Assistant, you can skip the next couple of sections and go to the conclusion. However, if you are interested in Octoprint and getting it better integrated with HASS read on!

This approach can easily be integrated into Octoprint via the PSU Control plugin. This allows us to control the status of the USB power directly within Octoprint. To make this work nicely, we need to give Octoprint some idea of the status of the power supply. It would be nice to do this by checking the USB power state and reporting it back. However, I decided to cheat and use the status of the webcam service! Here’s the resulting script (/usr/local/bin/psu_status.sh):

#!/bin/bash

status=$(systemctl is-active webcamd)

if [[ $status = "active" ]]
then
    exit 0
else
    exit 1
fi

We then simply set up the plugin to use our three scripts:

octoprint raspberry pi usb power settings
Note that the status script doesn’t need sudo!

With that in place, you should be able to switch your USB power on and off via the little lightning bolt icon at the top of your Octoprint screen. It’s worth noting that the status script can also be integrated into the HASS switch above by adding the command_state item to it’s configuration.

I’m eventually going to add relay control to my printer to control the main power supply. At this point I’ll update my scripts to also control the relay. I’ll probably query the state of the relay for the status script as well. When I do this, I’ll update this post with the details. In the meantime the following video describes the hardware side of it (as well as a more basic software setup):

Because being on fire is the least desirable state for your printer to be in!

Switching the Octoprint PSU from Home Assistant

Now that we have our scripts integrated with Octoprint we can one-up our integration with HASS by using the Octoprint API to switch the USB power on and off:

switch:
  - platform: command_line
    switches:
      octoprint_psu:
        command_on: '/usr/bin/curl -s -H "Content-Type: application/json" -H "X-Api-Key: OCTOPRINT_API_KEY" -X POST -d ''{ "command":"turnPSUOn" }'' http://IP_ADDR/api/plugin/psucontrol'
        command_off: '/usr/bin/curl -s -H "Content-Type: application/json" -H "X-Api-Key: OCTOPRINT_API_KEY" -X POST -d ''{ "command":"turnPSUOff" }'' http://IP_ADDR/api/plugin/psucontrol'
        command_state: '/usr/bin/curl -s -H "Content-Type: application/json" -H "X-Api-Key: OCTOPRINT_API_KEY" -X POST -d ''{ "command":"getPSUState" }'' http://IP_ADDR/api/plugin/psucontrol'
        value_template: '{{ value.isPSUOn }}'

I decided to continue using the command line switch here, rather than a REST switch. This was because the REST switch requires state feedback via a GET call, which the Octoprint API doesn’t support. Instead we are calling the API via curl, which works fine. Don’t forget to update the code to include your IP address/hostname and also your Octoprint API key. You probably even want to have the whole command in the secrets.yaml file in order to protect these when sharing your config (since HASS doesn’t support templating in secrets).

Bonus: Shutting Down Octoprint from HASS

Now that we have a feel for the Octoprint API, we can use it in HASS to do other things. For example, it’s useful to be able to shutdown the server when we are done with it:

shell_command:
  octoprint_shutdown: '/usr/bin/curl -s -H "Content-Type: application/json" -H "X-Api-Key: OCTOPRINT_API_KEY" -X POST http://IP_ADDR/api/system/commands/core/shutdown'

This is basically the same as above and you can call any API method you like with this approach. To actually make use of this, it needs to be added to a script or automation. For example:

script:
  octoprint_shutdown:
    sequence:
      - service: shell_command.octoprint_shutdown

This can then be added to the HASS UI to get a nice button to shut down the system. You probably want to add a condition on this for real world use, in order to prevent the server being shutdown while a print is in progress. I’m going to leave this as an exercise for the reader!

Conclusion

With this in place I’ve made the use of my 3D printer via Octoprint a little more streamlined. It’s also nice that the USB power switching is more generally useful. I’m sure I’ll find other applications for it in future, since I didn’t know that it was possible until now.

As you can see from the above, I’m aiming for a deeper integration between HASS and my 3D printer than is provided via just the native Octoprint integration. This is just step one. I’m hoping to eventually automate some of the safety procedures and best practices around running the printer, such as ensuring that it is turned off when not in use and possibly even an emergency shutdown. I’ll be sure to update you on the progress of these in future articles.

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.

power supply connected

Salvaging a Broken Tablet for a Smarthome Dashboard

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

I’ve never been massively convinced in the utility of a wall mounted smarthome dashboard. It’s always seemed like there are easier ways of controlling the smart home, for example Zigbee buttons. I guess one advantage could be their use as an information radiator for your home. However, I tend to have a good eye on what’s going on around the home and have notifications set up for all the important non-obvious stuff.

Basically, I was never convinced enough to go out and buy a tablet for this purpose. Especially as the decent tablets in NZ are pretty expensive, we don’t seem to get the cheap Amazon Fire ones which are popular for this application. However, the opportunity arose to use a defunct tablet for this purpose. So I thought I would give it a try – if I could get it to work.

Powering The Tablet

The tablet in question is a Samsung Galaxy Tab Pro 8.4, which is several years old and would not power on due to a completely exhausted battery. After doing a bit of research on YouTube, I was able to determine that it should be possible to disconnect the old battery and use the connector to power the tablet from the wall, with the cable running out through the back of the device.

Once I had the correct tools to pry apart the case without damaging the screen I was able to remove the battery without any problems. I then snipped off the connector on the battery, leaving enough cable to solder some new cables to the positive and negative terminals.

Then I built up a power supply to provide the required 3.8-4.2V via the battery connector. I used a small adjustable voltage regulator to provide power. As it turned out this wasn’t enough to power the tablet by itself. However it did power up when the USB cable was additionally attached.

power supply during testing
The power supply during testing
power supply finished
Power supply once finished off with tape and heatshrink
power supply connected
The power supply sitting in the battery cavity
cutting a hole in the back of the tablet
Since the power supply wouldn’t fit flush, I needed a larger hole than I originally intended in the back of the tablet!
taped up hole
There I fixed it!

Unfortunately, it’s still a bit flakey and will sometimes power off due to a brown out. It’s OK in normal (very light) use as a dashboard, but can’t cope with much more. I’ve ordered a power supply which can supply more current (up to 5A). Hopefully once I have that installed I can drop the USB cable and only need a single connection.

Mounting

I 3D printed the mounting brackets for the tablet from a ready made model. These brackets are nice and easy to print, however I found on installing the tablet that they obscure the bottom corners of the screen quite a bit. I also can’t rotate them so the short sides are along the bottom due to the USB connection. I’m hoping I’ll be able to modify the design in order to reduce the size of the bottom tabs, but I haven’t got around to this yet.

mounting brackets
The mounting brackets once mounted to the wall (they are level, I just can’t hold the camera straight!)

Updating the OS

Aside from the power issue, the main issue with this tablet being so old is the version of Android it was running – 4.4.2! This is pretty ancient and means a lot of apps aren’t available any more. Also the browser app which I wanted to use (WallPanel) uses Android WebView and the version available won’t render Home Assistant’s Lovelace UI. Unfortunately WebView isn’t upgradable in this version of Android either.

With all this in mind I set out to upgrade the tablet. I knew that it was supported by Lineage OS at some point in the past. With a bit of fiddling (and compiling Heimdall from source), I was able to get TWRP running on it. I then installed an old version of Lineage OS (13), OpenGApps Nano and Magisk on it. This gave me Android 6.0 and full root access. Not great, but not awful. I wouldn’t recommend this setup on a device your going to use as a daily driver, since it hasn’t had any security updates in a while.

Smarthome Dashboard and Other Apps

tablet smarthome dashboard
The tablet showing my smarthome dashboard so far

On that base, WallPanel (with an upgraded WebView) works great with HASS. I’ve also installed the prime version of Nova Launcher to give me a nice home screen for launching other apps from (I needed to prime version to scale up the icons for easier casual use). A secondary purpose of this tablet will be for firing things off to the Chromecast quickly without having to use one of our phones, so launching of Netflix and other streaming apps are required.

tablet launcher
The launcher with quick access to other apps

I really like WallPanel, especially the MQTT and camera integrations. However, I’ve currently got most of the advanced features turned off to save power and prevent brown outs! I really need to fix that power supply! I am making use of the motion detection to wake the tablet up though. Tasker and Termux are also installed, but I’m so far not doing much with them.

As you can see from the photos, I’ve begun work on a smarthome dashboard view in Lovelace for this, but I haven’t got too far. Part of the reason for this post is to get others to share their dashboards and give me some inspiration.

Conclusion

It seems like this project has had more than it’s fair share of issues and road blocks. I definitely wouldn’t call it finished, but the proof of concept is there and there is a clear path for what needs to be improved.

So far the tablet has been on the wall for a couple of days and I’m already finding it useful. Since the tablet will wake up as you walk past it will generally catch your eye and convey some useful information (such as when it’s going to stop raining!). I think I’ll focus on the informational/status aspect in my dashboard design going forward.

Next Steps

I’ve documented most of the next steps above, but as a recap:

  1. Replace the power supply with one that can provide more current;
  2. Modify the mounting bracket design to not obscure the tablet screen;
  3. Turn on the advanced features of WallPanel and integrate into HASS;
  4. Finish the Lovelace dashboard.

I’ll also probably do some more integration/automation using Tasker. One feature I would like would be to re-launch the dashboard when the tablet becomes idle, in case someone left it on a different screen.

I hope you’ve enjoyed following this journey of me giving new life to some old hardware. It’s always nice to do that rather than making yet more e-waste! Please feel free to share your own smarthome dashboard projects in the comments and feedback channels, I definitely need more inspiration.

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.

3d print switch cover

Solving Smart Bulb Problems with 3D Printing

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

If you ask the question “should I go for smart bulbs or smart switches?” on pretty much any home automation forum and you’ll undoubtedly get a mixture of answers. Most likely many of these will come down on the side of smart switches as the superior technical solution. This is generally because they replace the existing switch and so can be actuated manually. Also, you don’t have pesky switches that aren’t supposed to be touched, lest the smarts go out of your smart bulbs.

For a variety of reasons (pretty colours among them!), I only have smart bulbs in my house. I’ve written before about how I’ve added manual control back to some of these where required. Of course this still leaves me with certain switches in the house which “shall not be pressed”. I’ve had a nice non-invasive solution in mind for this for a while, but I’ve only been able to realise it since getting a 3D printer.

People Problems

I actually see this problem as less of a technical one and more of a people one. In the normal operation of our house, it rarely occurs that a smart bulb is turned off at the switch. This is because we are used to the way the house works and trust that the automation system will do the right thing.

Of course, when we have guests this all falls apart. People just can’t help flicking a switch if one is presented to them. Even if they just entered a room where the light came on automatically, they will switch it off on exiting. The only solution is to remove the temptation by removing or covering the switch.

The low tech/ugly solution to this would have been a piece of tape with “do not switch off” scrawled on it in marker pen. However we can do better than that. There are little plastic widgets available which can be stuck over the top of a switch and will restrict its use. I haven’t seen any that will fit the switches here in NZ, which are more square in comparison with British or US switches. So I decided to make my own.

OpenSCAD to the Rescue

As a programmer, it’s probably not a surprise that my 3D modelling software of choice is OpenSCAD. I’ve dabbled in using is before and managed to learn the basics before getting my 3D printer. However, this is the first physical object I’ve actually attempted to produce with it. I’m actually really happy with the result.

Note: the first version of these had the logo flipped for some reason. I’ve since updated the files in GitLab and Thingiverse (links below). The photos below show the original versions with the reversed logo. Thanks to @templarian on Twitter for pointing this out.

3d print switch cover
Yes, these are Home Assistant themed! My way of saying “don’t touch, HASS will take care of it”!
3d print switch cover
Mount the cover by sticking double sided tape or blu-tack to the tabs
The covers look pretty good once mounted. Note the Zigbee switch above for automation override (if needed).

This has been made for my PDL-600 series switches, but the design is parametric, so should be trivially adaptable to other NZ/Australian switches, since most of these seem to maintain the squarish form factor. I’ve also made a double switch cover for two switches arranged horizontally. This was done by elongating one side and centring the logo.

3d print switch cover
Parametric modelling FTW!
3d print switch cover
I made the tabs slightly narrower here so that the cover would fit onto the switch plate
Just fits!

Model Parameters

The model parameters are available at the top of the OpenSCAD source and have comments, which allows the software to present you will a nice dialog for editing the parameters. You can even set presets and switch between them. I’ve already included the presets for my single and double switches.

The available parameters are as follows:

  • wall_thickness – The thickness of the main wall around the switch. Defaults to 1mm and you probably won’t need to change it;
  • button_length – The length of the cover (from top to bottom as you look at it mounted, since the reference is to the flat surface as it’s printed). Adjust depending on the size of your buttons;
  • button_width – The horizontal width of the cover, to allow for non-square buttons and also multi-button arrangements. I doubled this to produce the double cover;
  • button_height – The height of the button from the switch plate. Used to create the internal cavity to cover the switch;
  • logo_x_offset – X coordinate offset of the logo. Use this to move it around if you change the cover dimensions above;
  • logo_y_offset – Y coordinate offset of the logo. Use this to move it around if you change the cover dimensions above;
  • tab_width – the width of the mounting tabs on either side;
  • tab_height – the thickness of the mounting tabs.

Wait, I want some of these…

If you have a 3D printer you can download the OpenSCAD file and STLs (for the variations I’ve printed) on GitLab or Thingiverse. I’ve also included GCode files for the Ender-3 in the Git repo, but I recommend you slice the models yourself with your own settings. You’ll need to print with supports enabled for the internal cavity, but these pop out quite nicely.

If you don’t have a printer, you are welcome to use any of the available 3D printing services online, but I’m afraid I can’t recommend one. I also found them rather expensive when I looked into it.

If there is sufficient demand I might put up a Tindie or Etsy store for these and charge a couple of dollars (plus shipping of course!). Let me know in the comments if you’d be interested in this.

Conclusion

I’m really happy with these, especially considering they are my first custom 3D printed object. They’ve actually solved a real world problem for me, since we recently had guests again and nobody switched off any of the smart lights!

I’m interested to hear if anyone else has used 3D printing to solve smart home annoyances like this. There seems to be a lack of HA related designs on Thingiverse. Let me know if you’ve come up with anything useful!

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