😎

n8nでSwitchBot APIを利用する

に公開

APIの準備

APIを使うためにSwitchBotアプリを操作する必要があります。
https://blog.switchbot.jp/announcement/api-v1-1/
プロフィールページ→設定→基本データ→アプリバージョンを10回タップ→開発者向けオプションが表示→トークンを取得
トークン(API_TOKEN)とクライアントシークレット(CLIENT_SECRET)を控えておきます

デバイスIDの取得

https://qiita.com/katta1024/items/6a5af91c986fe3c47f4d
こちらを参考にGoogleAppsScriptから一覧を取得して控えておくと良いと思います
(SwitchBotアプリのデバイス情報BLE MACの「:」を省いて繋げたものがデバイスIDっぽいのでそれでもいいかもしれません)

APIヘッダーをn8nのコードノードで作る

言語をPythonにして

import json
import time
import hashlib
import hmac
import base64
import uuid

# Declare empty header dictionary
header = {}

# token
token = `API_TOKEN`
# secret
secret = `CLIENT_SECRET`

nonce = uuid.uuid4()
t = int(round(time.time() * 1000))
string_to_sign = '{}{}{}'.format(token, t, nonce)

string_to_sign = bytes(string_to_sign, 'utf-8')
secret = bytes(secret, 'utf-8')

sign = base64.b64encode(hmac.new(secret, msg=string_to_sign, digestmod=hashlib.sha256).digest())

header['Authorization'] = token
header['Content-Type'] = 'application/json'
header['charset'] = 'utf8'
header['t'] = str(t)
header['sign'] = str(sign, 'utf-8')
header['nonce'] = str(nonce)

return header

SwitchBot APIを使用するワークフローで使い回せます

SwitchBotデバイスの操作ノードを作る

n8nのHTTP Requestノードで作っていきます
https://github.com/OpenWonderLabs/SwitchBotAPI
各種コマンドやパラメータは上記参照

Curtain3を操作する場合は
Method: POST
URL: https://api.switch-bot.com/v1.1/devices/デバイスID/commands
Authentication: none
SendHeader: ON
Header Parameters(↑で作ったheaderの値を取る)
 Content-Type: {{ $json['Content-Type'] }} 
 Authorization: {{ $json.Authorization }}
 charset: {{ $json.charset }}
 t: {{ $json.t }}
 sign: {{ $json.sign }}
 nonce: {{ $json.nonce }}
Send Body
 Body Content Type: JSON
 command: setPosition
 parameter: 0,1,0 (サイレントモードで全開)
 commandType: command

のような感じ。左右連携はないので左右それぞれのデバイスIDでノードを作ります。


毎朝7:30にカーテンを自動で開ける例

ハブから情報取得して部屋が暗かったら〜〜とか
室温が◯℃なら〜〜とかもできます

Discussion