SwitchBot API
IFTTT不発事故に起因する2021年版AirconShutdownの善後策。
![]() |
| SwitchBotハブミニ |
これまではTwitter経由のIFTTTで家電リモコンとSwitchBotを制御していたところ、2022年版IRKitでは直接APIを叩くようにできたので、SwitchBotもSwitchBot Open APIを叩くことに。
https://api.switch-bot.com/v1.0/devices/というRESTエンドポイントに制御データをPOSTする枠組み。/commands
curl --request GET 'https://api.switch-bot.com/v1.0/devices' \で一覧を取得できる。なお、認証トークンはSwitchBotをHub経由でAPIから操作するに倣い、SwitchBotアプリの「開発者向けオプション」から取得できる。
--header 'Authorization: 認証トークン' \
--header 'Content-Type: application/json; charset=utf8'
ちなみに、エアコンの制御データのパラメータは
| deviceType | Air Conditioner |
|---|---|
| commandType | command |
| Command | setAll |
| command parameter | {temperature},{mode},{fan speed},{power state} e.g. 26,1,3,on |
| Description | the unit of temperature is in celsius; modes include 1 (auto), 2 (cool), 3 (dry), 4 (fan), 5 (heat); fan speed includes 1 (auto), 2 (low), 3 (medium), 4 (high); power state includes on and off |
{ "command": "setAll", "parameter": "25,1,1,off", "commandType": "command"}というデータを"switchbot_aircon_off.json"というファイルにして
#!/bin/bashというスクリプトを回せばエアコン3台が順次停止になる運びだ。
BASEPATH=$(dirname $0);
SWITCHBOT_API="https://api.switch-bot.com/v1.0"
SWITCHBOT_TOKEN="90edf....3431"
hdr_auth="Authorization:${SWITCHBOT_TOKEN}"
hdr_type="Content-Type: application/json"
# BODY="@${BASEPATH}/switchbot_aircon_off.json"
BODY='{"commandType": "command", "command": "setAll", "parameter": "25,1,1,off"}'
AIRCON_1F="01-2020XXXXXXXX-32" # 1F
AIRCON_2F="01-2020YYYYYYYY-52" # 2F
AIRCON_3F="01-2020ZZZZZZZZ-82" # 3F
for DEVICE_ID in $AIRCON_1F $AIRCON_2F $AIRCON_3F;
do
URL="${SWITCHBOT_API}/devices/${DEVICE_ID}/commands"
curl "${URL}" \
--silent -O /dev/null \
-H "${hdr_auth}" -H "${hdr_type}" \
-X POST -d "${BODY}"
done
