-
Notifications
You must be signed in to change notification settings - Fork 3
Monitor printer ink levels
To monitor the printer ink levels I needed to install CUPS and HPLIP.
Once the printer is configured you can read the ink levels using the hp-info
utility.
To monitor the ink levels in Home Assistant I use one MQTT sensor per each color.
I've created a script to publish each color ink level to a different MQTT topic (home/printer/<color>
). This script only publishes to MQTT if something is returned from hp-info
utility.
The script looks like:
#!/bin/sh
ink_levels=$(hp-info 2>&1 | grep -oP "(?<=agent[1-4]-level\s{18})(.*\S)" | tr "\n" ",")
colors=(
'magenta'
'cyan'
'yellow'
'black'
)
if [ -n "${ink_levels}" ]; then
IFS=',' read -r -a ink_levels_array <<< "$ink_levels"
for index in "${!ink_levels_array[@]}"
do
if [ -n "${ink_levels_array[index]}" ]; then
mosquitto_pub --cafile /etc/ssl/certs/ca-certificates.crt -h <mqtt_host> -p <mqtt_port> -u <mqtt_user> -P <mqtt_password> -t "home/printer/${colors[index]}" -r -m "${ink_levels_array[index]}"
fi
done
fi
Note hp-info
takes more than 20 seconds to execute. If you try to execute direcly from Home Assistant you will get a timeout error.
I've added the script to crontab to check every 5 minutes the ink levels (keep in mind that it only publishes when the hp-info
utility returns data and this only occurs when the printer is on):
*/5 * * * * bash /home/pi/ink_levels.sh