Display Mac Battery Status on Home Assistant
This tutorial will show you how to display the battery status of your MacBook in Home Assistant using MQTT
Install MQTT Mosquitto Broker
Let’s enable the Mosquitto MQTT broker in the Home Assistant. Go to Supervisor and search for “mqtt” and select Mosquitto broker.
Install the broker and start it. Don’t forget to enable the Watchdog and check the log if there are any errors.
Once you have installed, reboot the server and go to Configuration > Integration and check if you see the MQTT broker tile.
If you can’t find it, click Add Integration and search for MQTT.
Create User for MQTT
Select Configuration > Users and add a user. For example “mqtt”, set the password and click Create.
Select the MQTT broker tile and click Configure.
Enter the user you have created and set the password. Leave other parameters as default.
On this page, no action is required, just click Submit.
We are done with configuration and now we need to test it. Download the MQTT Explorer from http://mqtt-explorer.com
Connect to MQTT broker with the IP is your Home Assistant IP address. Enter the username and password you have set and the port is 1883. Click Connect.
If successful, you will get this page.
Go back to MQTT setting and enter the topic home/macbook/temperature on the Publish and Listen topic. Click Start Listening.
Now in MQTT Explorer, set the topic under Publish to home/macbook/temperature and select raw. Enter the number (e.g. 3) and click Publish.
If there is no error, you will see this message in Home Assistant. The connection is established and we are able to send the message from the MQTT client.
Now we need to write a Python code to read the battery status and send it to MQTT server. We will be using the xbar library from https://github.com/matryer/xbar to display the informaton on the status bar.
We will use this command to get the battery percentage value and send this value to MQTT server with publish function.
/usr/bin/pmset -g batt
Put this Python code in the xbar plugins folder.
Display Gauge in Home Assistant
We need to display the battery status information in Home Assistant. Select File Editor and add this line in the /config/configuration.yaml.
— platform: mqtt
Restart Home Assistant.
Go to Configuration > Entities and search for mqtt and find the MQTT Sensor.
In Configuration, select Lovelace Dashboard and Add Dashboard.
On the dashboard that you have added, click Add Card.
Select By Card and search for Gauge.
Select entity sensor.mqtt_sensor and set the other paramterers as per screenshot below and click Save.
And that’s all what we need to do.