LoginSignup
3
2

More than 1 year has passed since last update.

Switchbot APIの使い方~デバイスIDの取得~

Last updated at Posted at 2023-02-01

GoogleAppsScriptでSwitchbot機器のデバイスIDを取得する方法を解説します。

トークンとシークレットの入手

まずはAPI認証に用いるトークンとシークレットを入手します。
SwitchBotアプリの[設定] > [開発者向けオプション]から入手可能です。手順は以下の通り。

  1. [プロフィール]タブから[設定]を開きます。
    S__5054472.jpg

  2. [アプリバージョン]を連打すると出てくる[開発者向けオプション]を開きます。
    S__5054470.jpg

  3. トークンとシークレットをメモしておきましょう。
    S__5054471.jpg

これが漏洩すると他社が自分の家の家電の情報を入手したり操作できたりしてしまうので注意しましょう。

デバイス情報一覧の取得

当記事では Switchbot API v1.1を利用していきます。GoogleAppsScriptで以下のコードを実行しましょう。

getDeviceInfo.gs
// // SwichBotAPIのサービスURL、認証情報
const url = 'https://api.switch-bot.com'
const token = "xxxxxxxxxxxxxxx"//Swichbotのトークン(アプリの開発者オプションから取得)
const secret = "xxxxxxxxxxxxxxx"//Swichbotのクライアントシークレット(アプリの開発者オプションから取得)

//SwitchBotに登録されているデバイスの一覧を表示する。
function getDeviceInfo() {
  const path = '/v1.1/devices'
  const nonce = Utilities.getUuid() // 任意の文字列で可 

  let timestamp = new Date()
  timestamp = timestamp.getTime().toString()

  let sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, token + timestamp + nonce, secret)
  sign = Utilities.base64Encode(sign).toUpperCase()

  headers = {
    'Authorization': token,
    'sign': sign,
    't': timestamp,
    'nonce': nonce
  }
  const options = {
    'method': 'GET',
    'headers': headers,
  }
  Logger.log(UrlFetchApp.fetch(url + path, options).getContentText())
}

すると以下のようなレスポンスがあると思います。(内容は登録されている機器により異なります。)

{
	"statusCode": 100,
	"body": {
		"deviceList": [
			{
				"deviceId": "XXXXXXXXXXXXXXX",
				"deviceName": "ロック",
				"deviceType": "Smart Lock",
				"enableCloudService": true,
				"hubDeviceId": "F47E42F891A4",
				"master": true
			},
			{
				"deviceId": "XXXXXXXXXXXXXXX",
				"deviceName": "Hub Mini A4",
				"deviceType": "Hub Mini",
				"enableCloudService": false,
				"hubDeviceId": "000000000000"
			}
		],
		"infraredRemoteList": [
			{
				"deviceId": "XX-XXXXXXXXXXXXXXX-XXXXXXXX",
				"deviceName": "エアコン",
				"remoteType": "Air Conditioner",
				"hubDeviceId": "XXXXXXXXXXXX"
			},
			{
				"deviceId": "XX-XXXXXXXXXXXXXXX-XXXXXXXX",
				"deviceName": "照明",
				"remoteType": "Light",
				"hubDeviceId": "XXXXXXXXXXXX"
			}
		]
	},
	"message": "success"
}

デバイスID等のデバイス情報を取得することができました。デバイスIDは個々の機器の操作をするAPIを呼ぶときに用います。

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