Last active
February 7, 2026 20:14
-
-
Save ryrun/5db8d28ad9ce7e7a3e36688c116db42a to your computer and use it in GitHub Desktop.
Simple Bash script that reads macOS accessory battery levels via pmset and publishes them to Home Assistant using MQTT discovery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -euo pipefail | |
| broker_host="${BROKER_HOST:-192.168.0.123}"; broker_port="${BROKER_PORT:-1883}" | |
| mqtt_user="${MQTT_USER:-mqtt-user}"; mqtt_pass="${MQTT_PASS:-$(cat "$HOME/.mqtt_pass")}" | |
| discovery_prefix="${DISC_PREFIX:-homeassistant}"; state_base="${STATE_BASE:-macos/accps}" | |
| publish_args=(-h "$broker_host" -p "$broker_port"); [[ -n "$mqtt_user" ]] && publish_args+=(-u "$mqtt_user" -P "$mqtt_pass") | |
| slug(){ echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/_/g;s/_+/_/g;s/^_//;s/_$//'; } | |
| pmset -g accps 2>/dev/null | sed -nE 's/^[[:space:]]*-//p' | while IFS= read -r line; do | |
| device_name="$(echo "$line" | sed -E 's/[[:space:]]*\(id=.*$//')" | |
| # Only used to provide a unique device identifier in Home Assistant. | |
| device_id="uniqueid1234" | |
| battery_percent="$(echo "$line" | sed -nE 's/.*[^0-9]([0-9]{1,3})%.*/\1/p')" | |
| [[ -z "${device_id:-}" || -z "${battery_percent:-}" ]] && continue | |
| device_key="$(slug "${device_name}_${device_id}")" | |
| config_topic="$discovery_prefix/sensor/$device_key/battery/config" | |
| state_topic="$state_base/$device_key/battery" | |
| payload="{\"name\":\"Battery\",\"state_topic\":\"$state_topic\",\"unit_of_measurement\":\"%\",\"device_class\":\"battery\",\"unique_id\":\"${device_key}_battery\",\"device\":{\"identifiers\":[\"$device_key\"],\"name\":\"$device_name\"}}" | |
| /opt/homebrew/bin/mosquitto_pub "${publish_args[@]}" -t "$config_topic" -r -m "$payload" | |
| /opt/homebrew/bin/mosquitto_pub "${publish_args[@]}" -t "$state_topic" -r -m "$battery_percent" | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment