YANO's digital garage

Copyright ©YANO All rights reserved. https://www.bravotouring.com/~yano/

Last-modified: 2024-03-09 (土)


[一語一絵/IT系]

SwitchBot API / 2022-06-25 (土)

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

SwitchBotハブミニ
[External]SwitchBotハブミニ

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

[External]SwitchBot Open API

https://api.switch-bot.com/v1.0/devices/<deviceId>/commands
というRESTエンドポイントに制御データをPOSTする枠組み。<deviceId>で指定する対象装置は
curl --request GET 'https://api.switch-bot.com/v1.0/devices' \
  --header 'Authorization: 認証トークン' \
  --header 'Content-Type: application/json; charset=utf8'
で一覧を取得できる。なお、認証トークン[External]SwitchBotをHub経由でAPIから操作するに倣い、SwitchBotアプリの「開発者向けオプション」から取得できる。

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

deviceTypeAir Conditioner
commandTypecommand
CommandsetAll
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

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と同じ。TwitterIFTTTのサービスを経由しない分だけ障害点に起因するリスクは減った、という理解でOKだ。

【参照】
●しずかなかずし https://shizuka-na-kazushi.style/
SwitchBot APIの使い方。エアコンをコントロールするプログラムをJavaScriptで書いた! 2021年8月9日
●kTech123|note https://note.com/klayer123/
SwitchBotまとめ
【SwitchBot】API を使って Python でエアコンの操作してみた
●Qiita https://qiita.com/
SwitchBot
SwitchBotAPI
curl で SwitchBotAPI を叩いて SwitchBotを動かす 2021年1月9日
SwitchBotをHub経由でAPIから操作する 2021年7月12日
●GitHub https://github.com/
OpenWonderLabs/SwitchBotAPI: SwitchBot Open API Documents
●SwitchBot https://www.switchbot.jp/
SwitchBotハブミニ
SwitchBotプラグミニ
●Wikipedia https://ja.wikipedia.org/wiki/
Representational State Transfer
スマートホーム
ECHONET Lite