This article describes how to send information about available disk space and the number of pending updates to Home Assistant using MQTT.
Requirements
- A running MQTT broker (e.g., Mosquitto).
- Installed MQTT client (e.g.,
mosquitto-clients
). - A Linux system with the
apt
package manager. - Home Assistant configured to support MQTT.
Script Configuration
The Bash script performs two key operations:
- Checks the number of pending updates.
- Calculates the amount of free disk space.
Example script:
#!/bin/bash
set -e
# Update package list and get the number of pending updates
apt-get update | logger -t 'auto_apt'
updates_count=$(apt-get -s -o Debug::NoLocking=true upgrade | grep ^Inst | wc -l)
/usr/bin/mosquitto_pub -r -t 'system/updates' -m $updates_count
# Calculate free disk space in MB
free_space=$(df --total | grep /media | awk '{printf "%.0f", $4/1024}')
/usr/bin/mosquitto_pub -r -t 'home-srv/system/free_space' -m $free_space
Explanation:
apt-get update
: Updates the list of available packages.apt-get -s -o Debug::NoLocking=true upgrade
: Simulates the upgrade process and lists packages to be updated.grep ^Inst | wc -l
: Counts the packages that need updating.df --total
: Displays information about available disk space.grep /media
: Search line for/media
disk indf
response to send data for it.awk '{printf "%.0f", $4/1024}'
: Converts bytes to megabytes (MB).mosquitto_pub -r
: Publishes an MQTT message with the “retained flag.”
Configuring Cron Job
To run the script regularly as root user (to check updates), use the cron job scheduler:
- Edit the root user’s cron table:
sudo crontab -e
- Add an entry to execute the script every hour:
0 */6 * * * /path/to/your/script.sh
- Save the changes.
Running apt-get update frequently can generate significant load on the system and network. It is recommended to limit the frequency of this operation to avoid unnecessary strain, especially on resource-constrained devices.
Home Assistant Configuration
- In the
configuration.yaml
file, add MQTT sensors:
mqtt:
- sensor:
name: "System updates"
state_topic: "system/updates"
state_class: measurement
unique_id: "system.updates.hassio"
value_template: "{{ value | int }}"
- sensor:
name: "System media space"
unique_id: 'mqtt.host.media.free.space.hdd'
device_class: "data_size"
state_topic: "home-srv/system/free_space"
suggested_display_precision: 1
value_template: "{{ value | int }}"
state_class: measurement
unit_of_measurement: MB
- Restart Home Assistant to load the new settings.
Summary
With the above script and configuration, you can easily monitor the state of your operating system in Home Assistant. MQTT enables seamless integration, while cron ensures regular data updates. This automation helps quickly respond to potential issues like low disk space or pending updates.