3
1

シェルスクリプトでcurlからSwithBotのAPI v1.1を呼ぶ

Last updated at Posted at 2023-09-18

概要

1年前にリリースされた、新バージョンv1.1のSwitchBot APIに、シェルスクリプトでアクセスしたい。
リクエストに署名を付加する要件が追加されたため、ちょっと手順が増えたのでそのまとめ。

準備

SwitchBotアプリからトークンとシークレットを入手。iOSアプリの場合、「プロフィール」→「⚙️設定」から「アプリバージョン」を10回タップすると「開発者向けオプション」が現れるので、そこから入手可能。

公式情報

手順

switchbot_api_v11.sh
#!/bin/bash

token="<トークン>"
secret="<シークレット>"
t=$(date +%s%3N)
nonce=$(uuidgen -r)
sign=$(echo -n ${token}${t}${nonce} | openssl dgst -sha256 -hmac ${secret} -binary | base64)

result=$(
    curl -s "https://api.switch-bot.com/v1.1/devices" \
      --header "Authorization: ${token}" \
      --header "sign: ${sign}" \
      --header "t: ${t}" \
      --header "nonce: ${nonce}" \
      --header "Content-Type: application/json; charset=utf8")

echo $result
  • date +%s%3N
    • ミリ秒のunixtimeを取得。仕様では13桁のunixtimeを送ることになっています。
  • uuidgen
    • UUIDを生成するコマンド。-rはランダム生成
    • コマンドがない場合は、別途インストール
      • sudo apt install uuid-runtime
      • sudo yum install util-linux

なお、curlで取得したJSONをjqにつないで、必要な情報だけ選び、配列として変数に格納すると、その後の処理に便利です。

例えば温湿度計の状態を取得する場合、

result=($(
    curl -s "https://api.switch-bot.com/v1.1/devices/<device_id>/status" \
      --header "Authorization: ${token}" \
      --header "sign: ${sign}" \
      --header "t: ${t}" \
      --header "nonce: ${nonce}" \
      --header "Content-Type: application/json; charset=utf8" \
    | jq ".body.humidity, .body.temperature"
))

とすると、${result[0]}に湿度が、${result[1]}に温度が入ります。

以上です。

3
1
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
3
1