home assistant wall mounted tablet

Home Assistant Wall Mounted Tablet Update

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

This is an update to my previous post on my wall mounted Home Assistant tablet. There have been quite a few changes, so I thought it was worth another post on the subject. Let’s get into it…

Power Failure

I’ll start with the big issue which has plagued this project – power. Since the battery in the original tablet was completely exhausted I had built a wired power supply to replace it. Unfortunately, this wasn’t powerful enough and the tablet would power off sometimes under high load. This problem seemed to get worse until the tablet would power off after just a few minutes, thus becoming pretty much useless.

home assistant wall mounted tablet
The new PSU all wired up (difficult to capture in a photo!)

I mentioned previously that I had ordered a 5A power supply to fix this problem, but even that didn’t work. The tablet must pull transient currents of more than 5A, which a battery can supply quite easily. Unfortunately the fixed power supply cannot. This is a real shame because I put a lot of effort into the new power supply – I even printed a case for it based on a modified version of the parametric PCB case I used in my recent MySensors build.

Even with the failure of the new power supply, the exercise in building this has demonstrated the utility of a wall mounted tablet in our household. The decision was therefore taken to replace the old broken tablet with a new one.

The New Tablet

The new tablet is the Lenovo Tab E8 (link is to Amazon, but ours came from a local retailer), chosen solely because it was the cheapest 8 inch tablet available!

home assistant wall mounted tablet
The new tablet mounted on the wall, complete with new brackets

The tablet seems pretty good overall, at least for the price. The build quality is fine, although the case is very plastic-y. It’s a little slow after boot up as it loads up everything, but in normal usage as a wall mounted dashboard it performs perfectly well. The shipped operating system is Android 7.0, which is up to date enough to not present any problems with app support.

The biggest issue with this device is that it charges really slowly, even from the provided charger. I even had cases when setting it up that the battery would still drain when plugged in to the charger. I was a little concerned that the tablet battery would become discharged over time during normal use, due to wake ups from the motion sensing. However, once the tablet was mounted on the wall and left overnight it charged to 100% and has remained there since.

Fixing the Brackets

I printed new brackets for the tablet with a reduced front lip. This removes the issue with the brackets obscuring the screen. The right bracket (left from the point of view of the tablet and in the STL files) also has a cut out in it’s side to allow the USB cable to pass through. I made these edits in OpenSCAD, by first importing the original STL files. I then created an object which represents the material I wanted to remove. Then a difference operation between the two gives the final object. I’m pretty pleased with them. The only thing I wasn’t able to reproduce was the rounded internal edges on the cut out sections.

Wall Panel MQTT Integration

With the power issues solved, I can integrate the tablet fully with Home Assistant (without fear that the extra load will cause it to power off). I’ve integrated in the sensors available on this device (pretty much just the power status). The full YAML code for this is available on GitLab. This pretty much went according to the WallPanel documentation. However, I did find that I needed to specify a value_template in order to extract the battery value:

sensor:
  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/battery"
    name: "Kitchen WallPanel Battery Level"
    unit_of_measurement: "%"
    value_template: '{{value_json.value}}'
    device_class: battery

To extract the boolean status for the charging state sensors, the template gets a little more complex:

binary_sensor:
  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/battery"
    name: "Kitchen WallPanel Charge State"
    value_template: '{% if value_json.charging %}ON{% else %}OFF{% endif %}'
    device_class: power

  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/battery"
    name: "Kitchen WallPanel AC State"
    value_template: '{% if value_json.acPlugged %}ON{% else %}OFF{% endif %}'
    device_class: plug

I also integrated in the motion, face detection and QR code sensors, although I’m not using the face detection or QR code sensors and have since disabled them in WallPanel.

sensor:
  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/qrcode"
    name: "Kitchen QR Code"
    value_template: '{{value_json.value}}'

binary_sensor:
  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/motion"
    name: "Kitchen Motion"
    payload_on: '{"value":true}'
    payload_off: '{"value":false}'
    device_class: motion

  - platform: mqtt
    state_topic: "wallpanel/kitchen/sensor/face"
    name: "Kitchen Face Detected"
    payload_on: '{"value":true}'
    payload_off: '{"value":false}'
    device_class: motion

The final integration I did was to add a switch to turn on and off the camera streaming. However, in general usage this seems a bit flakey, with the camera stream not usually becoming available until after a WallPanel restart. Here’s the YAML used for the switch anyway:

switch:
  - platform: mqtt
    command_topic: "wallpanel/kitchen/command"
    name: "Kitchen Camera State"
    payload_on: '{"camera": true}'
    payload_off: '{"camera": false}'
    optimistic: true
    retain: true

Dashboard Improvements

home assistant wall mounted tablet
My Current Dashboard

I’ve improved my dashboard somewhat since my last post. However, it’s still a long way from some of the awesome dashboards I’ve seen posted. It’s still a work in progress!

The main changes have been to switch to the animated weather custom card for the weather forecast and to add Custom Header to my install to compact the header. I then added more buttons, some media controls and a gauge showing the progress of my 3D prints. The vacuum buttons call some custom scripts to start the vacuum with our preferred settings. This is necessary to work around a bug in HASS with the Botvac D3:

script:
  spot_clean:
    alias: "Spot Clean"
    sequence:
      - alias: "Start spot clean"
        service: vacuum.neato_custom_cleaning
        data:
          entity_id: vacuum.marvin
          mode: 2
          category: 3

  house_clean:
    alias: "House Clean"
    sequence:
      - alias: "Start house clean"
        service: vacuum.neato_custom_cleaning
        data:
          entity_id: vacuum.marvin
          mode: 1
          category: 2

It should be noted that I’m running a slightly older version of HASS at the moment. In newer versions the service name changed to neato.custom_cleaning. Also, using a category value of 3 for spot cleaning appears to be undocumented, but if you look at the library, that’s what it’s doing.

Conclusions

This setup is now working perfectly and all the problems with the previous iteration have been resolved. It’s unfortunate that this was done by throwing money at the problems, but sometimes things just don’t work out as we hope!

Overall, I’m really happy with the finished product. The dashboard will be continually developing as I come up with ideas and work out what’s useful and what isn’t. Feel free to share your ideas again via the feedback channels.

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.

tiny tiny rss docker

Self-Hosted RSS with Tiny Tiny RSS in Docker

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

With the rise of social media, RSS seems to have been largely forgotten. However, there are still those who are dedicated enough to keep curating their own list of feeds and plenty of software to support them. I’ve always been a fan of RSS and believe it’s probably time for a resurgence in use that would free us from our algorithmic overlords. As such I’ve run an instance of Tiny Tiny RSS for several years and the time has come to migrate it to Docker.

It’s relatively unknown that you can still get RSS feeds for most news sources on the Internet. For example, I use TT-RSS to keep up with Youtube and Reddit (just add .rss to the end of any subreddit URL) as well as the usual blogs and news sites.

About Tiny Tiny RSS

Tiny Tiny RSS is a web based RSS application (think Google Reader replacement). It’s PHP based and supports Postgres or MySQL (like) databases. I’ve been using it for may years and although I’ve tried out other web based RSS readers (such as Miniflux), I’ve never found anything as good as TT-RSS.

tiny tiny rss docker
My Tiny Tiny RSS install

A particular favourite feature of mine is the ability to generate feeds from any internal view, which makes it great for integrating with other systems which may consume RSS/Atom.

There is also an Android app which is available via the Play Store or F-Droid.

Finding a Tiny Tiny RSS Docker Image

I had initially planned to use the LinuxServer.io TT-RSS image, but it seems to have been deprecated. With a bit of searching I found this repo, however it’s pretty out of date and doesn’t build any more. After looking through my GitLab repos, it turned out I’d already tried upgrading that image as part of one of my previous attempts with Docker. I’ve finished off this migration and made the repo public so everyone can benefit from my efforts. Thanks to some CI magic and GitLab’s built in container registry you can pull the latest version like so:

docker pull registry.gitlab.com/robconnolly/docker-ttrss

Feel free to read through the project README to familiarise yourself with the options available in the image. It’s pretty much as it was in the original repository, so I’ll go through my setup below.

Setup with docker-compose

I’m integrating this with my existing Docker setup via docker-compose and Traefik. As such I added the following to my docker-compose.yml file:

ttrss:
    image: registry.gitlab.com/robconnolly/docker-ttrss:latest
    depends_on:
      - mariadb-ttrss
    environment:
      DB_NAME: ${TTRSS_DB_NAME}
      DB_USER: ${TTRSS_DB_USER}
      DB_PASS: ${TTRSS_DB_USER_PASSWD}
      DB_HOST: mariadb-ttrss
      DB_PORT: 3306
      DB_TYPE: mysql
      SELF_URL_PATH: https://ttrss.example.com
    volumes:
      - /mnt/docker-data/ttrss/plugins:/var/www/plugins.local
    labels:
      - 'traefik.enable=true'
      - "traefik.http.middlewares.ttrss_redirect.redirectscheme.scheme=https"
      - "traefik.http.routers.ttrss_insecure.rule=Host(`ttrss.example.com`)"
      - "traefik.http.routers.ttrss_insecure.entrypoints=web"
      - "traefik.http.routers.ttrss_insecure.middlewares=ttrss_redirect@docker"
      - "traefik.http.routers.ttrss.rule=Host(`ttrss.example.com`)"
      - "traefik.http.routers.ttrss.entrypoints=websecure"
      - "traefik.http.routers.ttrss.tls.certresolver=mydnschallenge"
      - "traefik.http.services.ttrss.loadbalancer.server.port=80"
    networks:
      - external
      - internal
    restart: always

Breaking this down, we first create a new service using my TT-RSS image. We then define a dependency on the database container, which we will create later. The environment configuration uses another file env.sh in which we store our secrets. This is of the form:

export TTRSS_DB_ROOT_PASSWD=supersecret
export TTRSS_DB_USER=ttrss
export TTRSS_DB_USER_PASSWD=justalittlebitsecret
export TTRSS_DB_NAME=ttrss

In order to use this the file must be sourced before running docker-compose:

$ source env.sh
$ docker-compose .... # whatever you're doing

We can see that the database is configured entirely via environment variables as shown in the project README. We also set the SELF_URL_PATH variable so that TT-RSS knows where it is located (the URL should be updated for your configuration). I also chose to mount the plugins.local directory on the host machine to allow me to install plugins easily. The remainder of the configuration is for Traefik and is covered in my earlier post (you’ll need to update the hostnames used here too).

Database Setup

As mentioned earlier, we need a database container for TT-RSS to talk to. I’m using MariaDB for this because it’s what I’m familiar with. Also my original TT-RSS installation was in mysql and I wanted to migrate the data. The setup for this is pretty simple using the official MariaDB image:

mariadb-ttrss:
    image: mariadb
    environment:
      MYSQL_ROOT_PASSWORD: ${TTRSS_DB_ROOT_PASSWD}
      MYSQL_USER: ${TTRSS_DB_USER}
      MYSQL_PASSWORD: ${TTRSS_DB_USER_PASSWD}
      MYSQL_DATABASE: ${TTRSS_DB_NAME}
    volumes:
      - /mnt/docker-data/mariadb-ttrss/init/ttrss.sql.gz:/docker-entrypoint-initdb.d/backup.sql.gz
      - /mnt/docker-data/mariadb-ttrss/data:/var/lib/mysql
    networks:
      - internal
    restart: always

As you can see, I re-use the previous environment variables to create the database and user. I also mount the mysql data directory locally and mount a compressed backup of my previous database. This backup will only be loaded the first time the database comes up. You can remove this line if you are doing a clean install.

If you are following my install you’ll also see that I use a couple of Docker networks:

networks:
  external:
  internal:

The external network connects the local service containers to Traefik, whilst the internal network is used between TT-RSS and the database container.

With all this in place you should be able to launch your TT-RSS server with:

docker-compose up -d

At this point, it’s usually a good idea to check the container logs for problems and adjust your configuration accordingly.

Conclusion

Aside from having to update the Docker image for TT-RSS (which took quite a while) this migration was relatively painless. I’m quite happy with my newly Dockerised TT-RSS server. In addition to migrating it into Docker this step has also moved it off my ageing mailserver in preparation for it’s upcoming migration to something newer and moved it from the cloud onto my home server. All positive steps!

Next Steps

I’m pretty keen to keep maintaining my new Docker image for Tiny Tiny RSS, since it seems to be a gap in the community that can be filled. I’m currently building this in CI, but the configuration is pretty basic. In the coming weeks, I’m intending to expand upon this a little and set up a scheduled build which will automatically keep the container up to date. This will hopefully be the topic of a follow up article, so stay tuned!

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.

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.