Raspberry PiのセットアップからSwitchBot API実行までやってみる

Raspberry Piをセットアップして遊んでみました。 割と高価な買い物だったので、今後の活躍に期待です。
2024.04.30

はじめに

IoTの世界に興味を持ち、学習を始めるためにRaspberry Piを購入しました。
本記事ではRaspberry Piの初期設定から、SwitchBot APIを使ってデバイスリストを取得するまでの手順を紹介します。
IoT初心者の方にも参考になれば幸いです。

必要なもの

今回用意したものは以下の通りとなります。

  • Raspberry Pi 4 Model B(周辺機器も含む)
  • MacBook Air - macOS Sonoma(OS導入、SSH接続に使用)

Raspberry Piのセットアップ

Raspberry Pi を動かすには、ストレージとなるmicroSDカードにOSをインストールする必要があります。
今回はRaspberry Pi Imager を使って、OSの導入を行います。
以下のコマンドを実行し、Raspberry Pi Imager をダウンロードします。

$ brew install --cask raspberry-pi-imager

Raspberry Pi Imager を起動し、以下の値を選択して次へ進みます。

Raspberry Piデバイス OS ストレージ
Raspberry Pi 4 Raspberry Pi OS (64-bit) <インストール先のmicroSDカード>

OSの設定をするか確認画面が出るので、設定を編集するで進みます。

一般タブではユーザー名/パスワードWi-Fiロケールを設定します。
適宜ご自身の環境に合わせた設定を行なってください。

サービスタブではSSHを有効化するにして、パスワード認証を使うに設定し、保存に進みます。

そのまま進むと書き込みが始まるので、終わるまで待機します。

書き込みが終わり次第、microSDカードを Raspberry Pi に接続すればOSインストールは完了です。

SwitchBot APIを使ってみる

今回はお試しでSwitchBot APIを触ってみます。
まずは、SwitchBot API を使うためのAPIトークンを取得しておきます。
以下手順を参考に取得を行います。
トークンシークレットは後ほど利用しますので、メモ帳等に控えておきます。

Getting Started
Please follow these steps, Download the SwitchBot app on App Store or Google Play Store
Register a SwitchBot account and log in into your account
Generate an Open Token within the app a) Go to Profile > Preference b) Tap App Version 10 times. Developer Options will show up c) Tap Developer Options d) Tap Get Token

以下の手順に従ってください
App StoreまたはGoogle Play StoreでSwitchBotアプリをダウンロードする。
SwitchBotアカウントを登録し、アカウントにログインします。
アプリ内でOpen Tokenを生成する a) Profile > Preferenceに移動 b) App Versionを10回タップ。開発者向けオプションが表示されます c) 開発者向けオプションをタップ d) トークンを取得をタップ
引用: SwitchBot API v1.1

続いて、Raspberry Pi 上で動かすPythonコードを用意します。
今回はサンプルコードをベースにし、認証とデバイスリストの取得のみを行う簡易的な内容としました。
適宜トークンシークレットを入力してください。

sample.py

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

# Declare empty header dictionary
apiHeader = {}
# open token
token = '' # copy and paste from the SwitchBot app V6.14 or later
# secret key
secret = '' # copy and paste from the SwitchBot app V6.14 or later
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())

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

# API endpoint for getting device list
api_url = "https://api.switch-bot.com/v1.1/devices"

# Send GET request to the API
response = requests.get(api_url, headers=apiHeader)

# Check if the request was successful
if response.status_code == 200:
    # Parse the JSON response
    devices = response.json()
    
    # Print the list of devices
    print("Device List:")
    for device in devices["body"]["deviceList"]:
        print("- Device ID: {}, Device Name: {}".format(device["deviceId"], device["deviceName"]))
else:
    print("Failed to retrieve device list. Status Code:", response.status_code)

以下コマンドで Raspberry Pi のディレクトリに上記のコードを配置し、SSH接続を行います。

$ scp sample.py {ユーザー名}@raspberrypi.local:/{任意のディレクトリ}/
$ ssh {ユーザー名}@raspberrypi.local

接続できたら、pythonスクリプトを実行します。

$ python3 sample.py 
Device List:
- Device ID: XXXXXXXXXXXX, Device Name: デバイスA
- Device ID: XXXXXXXXXXXX, Device Name: デバイスB

上記のようにデバイス一覧が取得できればOKです。

まとめ

今回は初歩的な内容にはなりますが、Raspberry PiのセットアップとSwitchBot APIの実行をやってみました。
今後はAWS IoTを活用した学習を行なっていきたい所存です。