LoginSignup
11
10

More than 5 years have passed since last update.

Macのバッテリー状況をSlackに通知する

Last updated at Posted at 2015-12-18

古いMacBookなんかをサーバ用途で使ってたりするときに,なにかの拍子で電源ケーブルが外れてしまいバッテリー切れとかなるとテンションだだ下がりなので死活監視がしたいです,安西先生.

やること

SlackのIncoming Webhookを作成しておきます.

あとは↓なシェルを用意して適当な場所におき

battery_check.sh
#!/bin/bash

# /usr/bin/pmset -g ps
#
# Now drawing from 'AC Power'
#  -InternalBattery-0   26%; charging; 2:22 remaining
#
# Now drawing from 'Battery Power'
#  -InternalBattery-0     100%; discharging; (no estimate) present: true

if `pmset -g ps | grep 'AC Power' &>/dev/null`; then
  rm -f /tmp/low_battery
  exit 0
fi

if [ -e /tmp/low_battery ]; then
  exit 0
fi

REMAINING=`pmset -g ps | tail -1 | cut -f2 | cut -d';' -f1 | tr -d '%'`
if [ $REMAINING -lt 20 ]; then
  touch /tmp/low_battery
  curl  -X POST \
    --data-urlencode 'payload={"channel": "#general", "username": "怒りのバッテリー", "text": "バッテリーキレチャウヨ", "icon_emoji": ":ghost:"}' \
    https://hooks.slack.com/services/xxxxxxxx
fi

LaunchDaemonで60秒おきにチェック.周期は適当です.ほんとはLaunchAgentsでやれば良いと思う...

/Library/LaunchDaemons/local.battery_check.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>local.battery_check</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Library/LaunchDaemons/battery_check.sh</string>
    </array>
    <key>LowPriorityIO</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/local.battery_check/stdout</string>
    <key>StandardErrorPath</key>
    <string>/tmp/local.battery_check/stderr</string>
    <key>RunAtLoad</key>
    <true/>
    <key>StartInterval</key>
    <integer>60</integer>
</dict>
</plist>

これでバッテリーで20%切ると通知されるようになります.

pmsetコマンドはいろいろ取れそうなのでもっと何かできるかも.

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10