LoginSignup
3
2

More than 3 years have passed since last update.

PythonでSesami APIをたたく

Last updated at Posted at 2020-05-10

やったこと

ラズパイから自宅のスマートロック(Sesami)を制御します。

参考

Sesame API Version 3 のチュートリアル

作成部分

tokenは固有のものを使用してください。

[STEP1] device_idの取得

# keyを指定してデバイス情報をstrで取得する
# args: device_id, serial, nickname
def get_device_info(key):

    url = "https://api.candyhouse.co/public/sesames"
    headers = {"Authorization": token}

    r = requests.get(url, headers=headers)
    json_data = r.json()

    return json_data[0][key]

[STEP2] 鍵をunlock or lockする

URLがSTEP1と微妙に違うので注意。
STEP1:https://api.candyhouse.co/public/sesames
STEP2:https://api.candyhouse.co/public/sesame

# 鍵の状態がlockならunlock, unlockならlockする
def toggle_device_key(device_id):
    url = "https://api.candyhouse.co/public/sesame/" + device_id
    headers = {"Authorization": token}

    if key_is_locked(device_id) is True:  # locked
        r = requests.post(url, headers=headers, data='{"command":"unlock"}')
    elif key_is_locked(device_id) is False:  # unlocked
        r = requests.post(url, headers=headers, data='{"command":"lock"}')
    else:
        print("error! toggle_device_key")
        return

    json_data = r.json()

    return json_data["task_id"]

[STEP3] 正常にコマンドが実行されたか確認

# task_idを指定して実行結果をbooleanで返す
def check_task_state(task_id):
    url = "https://api.candyhouse.co/public/action-result?"
    headers = {"Authorization": token}

    # task_idが空なら何もしない
    if task_id is None:
        return

    r = requests.get(url + "task_id=" + task_id, headers=headers)
    json_data = r.json()

    # statusが完了(terminated)になるまで待つ
    while json_data["status"] != "terminated":
        # wait
        time.sleep(3)
        # retry
        r = requests.get(url + "task_id=" + task_id, headers=headers)
        json_data = r.json()
    else:
        # 実行結果のステータスをbooleanで返す
        return json_data["successful"]
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