Last active
July 30, 2023 13:19
-
-
Save narikakun/4b0cca8e6af4a00b1264634e2fae2f79 to your computer and use it in GitHub Desktop.
micropythonとswitchbot api v1.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import hmac | |
import base64 | |
import cmath | |
import urequests | |
base_url = 'https://api.switch-bot.com/v1.1/' | |
token = "SwitchBot API Token" | |
secret = "SwitchBot API Secret" | |
device_id = "" | |
devices_url = base_url + "devices/{}/status" | |
# サインを作成する | |
nonce = 'raspberryPiPicoWH' | |
t = int(round(utime.time() * 1000)) | |
string_to_sign = bytes(f'{token}{t}{nonce}', 'utf-8') | |
secret = bytes(secret, 'utf-8') | |
sign = base64.b64encode(hmac.new(secret, msg=string_to_sign, digestmod=hashlib.sha256).digest()) | |
# リクエストヘッダを生成 | |
headers = { | |
"Authorization": token, | |
"sign": sign, | |
"t": str(t), | |
"nonce": nonce | |
} | |
# リクエストを作成 | |
url = devices_url.format(device_id) | |
response = urequests.get(url, headers=headers) | |
if response.status_code == 200: | |
data = response.json() | |
temperature = data["body"]["temperature"] | |
humidity = data["body"]["humidity"] | |
print(temperature, humidity) | |
else: | |
print(response.status_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment