Migrating Home Assistant from a Raspberry Pi 3B+ to VirtualBox on OS X
Shell scripts to get keyboard and battery values. Run it on a schedule somehow. I like a GUI so I use ‘Run Shell Script’ in Automator and schedule them with a daily ‘custom script’ event in iCal.
Keyboard (i5 Mac, Sonoma)
#!/bin/sh rawMouse=$(ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '| sed 's/ | "Bluetooth Product Name" = "Magic Mouse 2"/ \| Mouse:/' | sed 's/ | "Bluetooth Product Name" = "Magic Keyboard with Numeric Keypad"/ \| Keyboard:/'| sed 's/ | "Bluetooth Product Name" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | | "BatteryPercent" = / /'); echo $rawMouse > /Applications/MAMP/htdocs/mac-kb-mouse/mac-kb-mouse-raw.txt; echo $rawMouse | tail -c 4 > /Applications/MAMP/htdocs/mac-kb-mouse/keyboard-battery.txt
Mouse (i5 Mac, Sonoma)
#!/bin/sh rawMouse=$(ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '| sed 's/ | "Bluetooth Product Name" = "Magic Mouse 2"/ \| Mouse:/' | sed 's/ | "Bluetooth Product Name" = "Magic Keyboard with Numeric Keypad"/ \| Keyboard:/'| sed 's/ | "Bluetooth Product Name" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | | "BatteryPercent" = / /'); echo $rawMouse > /Applications/MAMP/htdocs/mac-kb-mouse/mac-kb-mouse-raw.txt; tr '\n' ' ' < /Applications/MAMP/htdocs/mac-kb-mouse/mac-kb-mouse-raw.txt | cut -c10-12 > /Applications/MAMP/htdocs/mac-kb-mouse/mouse-battery.txt
Keyboard (M4 Mac, Sequoia)
#!/bin/shrawMouse=$(ioreg -r -l -n IOHIDInterface | egrep '"BatteryPercent" = |^ \| "Product" = '| sed 's/ | "Product" = "Magic Mouse"/ \| Mouse:/' | sed 's/ | "Product" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | "Product" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | | "BatteryPercent" = / /'); echo "$rawMouse" | grep 'BatteryPercent' | awk 'NR==2 { gsub(/[^0-9]/, "", $0); print $0 }' > /Applications/MAMP/htdocs/mac-kb-mouse/keyboard-battery.txt
Mouse (M4 Mac, Sequoia)
#!/bin/shrawMouse=$(ioreg -r -l -n IOHIDInterface | egrep '"BatteryPercent" = |^ \| "Product" = '| sed 's/ | "Product" = "Magic Mouse"/ \| Mouse:/' | sed 's/ | "Product" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | "Product" = "Magic Keyboard"/ \| Keyboard:/'| sed 's/ | | "BatteryPercent" = / /'); echo "$rawMouse" | grep 'BatteryPercent' | awk 'NR==1 { gsub(/[^0-9]/, "", $0); print $0 }' > /Applications/MAMP/htdocs/mac-kb-mouse/mouse-battery.txt
These create keyboard-battery.txt and mouse-battery.txt files which contain the battery percentage.
I save mine in my MAMP htdocs folder and read it with a Home Assistant command line sensor like this:
- sensor: command: "curl -sS 'http://192.168.0.2:8888/mac-kb-mouse/keyboard-battery.txt'" scan_interval: 300 command_timeout: 2 name: i5 iMac keyboard battery unit_of_measurement: '%'
This creates sensor.i5_imac_keyboard_battery with the battery value as a percentage.
Possibly related