Magic Mouse battery level monitoring with unix standard tools and the Home Assistant app

Edit: I just realised, the reported value of battery charge state is plain wrong. I have to look into this and will update the post on success. Don’t implement this now. :wink:

As I always end with an empty Magic Mouse battery (which is really annoying), as the first warning always only arrives some 20 minutes before empty (Apple WHY?!?), I did some googling and tinkering…

Home Assistant App on your Mac

Install the Home Assistant App on your Mac. This allows you to receive Notifications which are displayed as the Mac system messages.

Define a Sensor in HA

configuration.yaml:

# mqtt sensors
mqtt:
  sensor:
    - name: "Mac Mini-01 Magic Mouse Battery"
      device_class: battery
      expire_after: 180 # 30 mins: 60 * 30
      icon: mdi:battery-warning-bluetooth
      state_topic: "hamqtt/sensors/mac-mini-01/magic-mouse-battery"

### read out mouse battery state and mqtt send

First, install the mosquitto server on your mac: `brew install mosquitto`
We only need the client, but sadly that's not available standalone. As long we do not start the server, like described after the installation, it's just a bit of wasted HD space.

This gives the current battery status in percent ~/opt/bin/home_assistant_magic_mouse_battery_upate.sh:
```shell
#!/bin/bash

set -e

HA_MQTT_USER=hamqtt
HA_MQTT_PWD=$(cat ~/.hamqtt_pwd) # store the password in a "safe" place
HA_MQTT_HOST=ha.example.com
HA_MQTT_PORT=1883

MQTT_TOPIC=hamqtt/sensors/mac-mini-01/magic-mouse-battery

MAGIC_MOUSE_BATTERY_LEVEL=$(/usr/sbin/ioreg | egrep '\bAppleSmartBattery\b' | sed -E 's/.*retain ([0-9]+).*/\1/')
/opt/homebrew/bin/mosquitto_pub -h ha.example.com \
  -p 1883 \
  -u ${HA_MQTT_USER} \
  -P ${HA_MQTT_PWD} \
  -t ${MQTT_TOPIC} \
  -m "${MAGIC_MOUSE_BATTERY_LEVEL}"

enter into crontab: */5 * * * * /Users/YOUR_USER/opt/bin/home_assistant_magic_mouse_battery_upate.sh

Monitor the sent messages

Use the MQTTX MQTT Desktop client, to see the first test messages.

Install a nice MQTT GUI client: brew install --cask mqttx
Open it: open open /Applications/MQTTX.app

Configure the connection and set up the topic to monitor: hamqtt/sensors/mac-mini-01/magic-mouse-battery

AppDaemon App to monitor and send notification on low charge

import appdaemon.plugins.hass.hassapi as hass

def logging_setup(self, log_name: str):
    self.log(f"logging into '{log_name}'", level="INFO")
    self._lggr = self.get_user_log(log_name)    
    hostname = platform.node()
    self._lggr.info(f"Initializing {log_name} on {hostname}")

class MacMiniMagicMouseBatteryMonitor(hass.Hass):
    
    def initialize(self):
        logging_setup(self, "mac_mini_magic_mouse_battery_monitor")
        self.listen_state(
            self.send_battery_level_warning, "sensor.mac_mini_01_magic_mouse_battery"
        )

    def send_battery_level_warning(self, entity, attribute, old, new, kwargs):
        self._lggr.info(f"send_battery_level_warning - new battery level: {new}%")

        battery_percent = int(new)
        if battery_percent < 20:            
          title="Charge your Magic Mouse soon."
          service_name = "notify/mobile_app_mini_01"
          msg=f"Battery Level low at {battery_percent}%"
          self.call_service(service_name, message=msg, title=title)

apps.yaml:

mac_mini_magic_mouse_battery_monitor:
  module: mac_mini_magic_mouse_battery_monitor 
  class: MacMiniMagicMouseBatteryMonitor

for logging in appdaemon.yaml:

...
logs:
  mac_mini_magic_mouse_battery_monitor:
    name: mac_mini_magic_mouse_battery_monitor
    filename: /config/logs/mac_mini_magic_mouse_battery_monitor.log
    log_generations: 2
    format:  "{asctime} {levelname:<8}: {message}"

Recap

Now the battery status is read out every 5 minutes started by cron and sent by MQTT to home assistant. The AppDaemon mini automation is monitoring for changes in the battery value and notifies when it becomes below 20% to give you enough time to recharge the battery, before it’s to late.

Have fun with it. :slight_smile:

1 Like