SwitchBot API

IFTTT不発事故に起因する2021年版AirconShutdownの善後策。

SwitchBotハブミニ

SwitchBotハブミニ

これまではTwitter経由のIFTTTで家電リモコンSwitchBotを制御していたところ、2022年版IRKitでは直接APIを叩くようにできたので、SwitchBotSwitchBot Open APIを叩くことに。

SwitchBot Open API

https://api.switch-bot.com/v1.0/devices/**<deviceId>**/commands

というRESTエンドポイントに制御データをPOSTする枠組み。****で指定する対象装置は

curl --request GET 'https://api.switch-bot.com/v1.0/devices' \
  --header 'Authorization: 認証トークン' \
  --header 'Content-Type: application/json; charset=utf8'

で一覧を取得できる。なお、認証トークンはSwitchBotをHub経由でAPIから操作するに倣い、SwitchBotアプリの「開発者向けオプション」から取得できる。

ちなみに、エアコンの制御データのパラメータは

deviceType
commandType
Command
command parameter
Description
…となっているので、、エアコン停止用の
{  "command": "setAll", "parameter": "25,1,1,off", "commandType": "command"}

というデータを"switchbot_aircon_off.json"というファイルにして

#!/bin/bash
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

というスクリプトを回せばエアコン3台が順次停止になる運びだ。

ローカルAPIな2022年版IRKitとは違って https://api.switch-bot.com/ に繋がらなかったらアウトだが、それは2021年版AirconShutdownと同じ。TwitterやIFTTTのサービスを経由しない分だけ障害点に起因するリスクは減った、という理解でOKだ。

参照

しずかなかずし https://shizuka-na-kazushi.style/

kTech123|note https://note.com/klayer123/

Qiita https://qiita.com/

GitHub https://github.com/

SwitchBot https://www.switchbot.jp/

Wikipedia https://ja.wikipedia.org/wiki/