Note: This article was first published more than a year ago.
- SwitchBot API endpoints, token methods, rate limits, and app screens change frequently. Refer to the latest developer documentation.
- Availability of power-consumption and switch-state data depends on the plug model and firmware. Check the official feature specifications.
- The Python code reflects the environment at the time. Check dependency compatibility.
I will use Python and the SwitchBot API to read device status and turn a SwitchBot Plug or SwitchBot Plug Mini on and off.
Search Amazon for the older SwitchBot Plug (Ad)
Search Amazon for the older SwitchBot Plug Mini (Ad)
See the earlier article for how to obtain the device ID.
https://riragon.com/blog/en/switchbot-api-python/
SwitchBot API v1.1
https://github.com/OpenWonderLabs/SwitchBotAPI
In the Python program below, enter the token, secret token, and device ID from your own environment. The script checks the device's current state through the SwitchBot API, then sends a command to turn it off if it is on, or on if it is off. You need Python 3.6 or later and the requests package. Set up Python and a virtual environment as appropriate. Here is an example of installing requests.
pip install requests
switchbot_plug_control.py
import requests
import time
import uuid
import hmac
import hashlib
import base64
def get_device_status(api_token, secret_token, device_id):
url = f"https://api.switch-bot.com/v1.1/devices/{device_id}/status"
t = int(time.time() * 1000)
nonce = str(uuid.uuid4())
string_to_sign = f"{api_token}{t}{nonce}".encode('utf-8')
secret_key = secret_token.encode('utf-8')
signature = hmac.new(secret_key, string_to_sign, hashlib.sha256).digest()
sign = base64.b64encode(signature).decode('utf-8').upper()
headers = {
"Authorization": api_token,
"Content-Type": "application/json",
"t": str(t),
"nonce": nonce,
"sign": sign
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return response.status_code, response.text
def send_command(api_token, secret_token, device_id, command):
url = f"https://api.switch-bot.com/v1.1/devices/{device_id}/commands"
t = int(time.time() * 1000)
nonce = str(uuid.uuid4())
string_to_sign = f"{api_token}{t}{nonce}".encode('utf-8')
secret_key = secret_token.encode('utf-8')
signature = hmac.new(secret_key, string_to_sign, hashlib.sha256).digest()
sign = base64.b64encode(signature).decode('utf-8').upper()
headers = {
"Authorization": api_token,
"Content-Type": "application/json",
"t": str(t),
"nonce": nonce,
"sign": sign
}
body = {
"command": command,
"parameter": "default",
"commandType": "command"
}
response = requests.post(url, headers=headers, json=body)
print(f"Sending {command} command: {response.text}")
time.sleep(5)
return get_device_status(api_token, secret_token, device_id)
# トークンとシークレットキーを設定
api_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
secret_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
device_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
device_status = get_device_status(api_token, secret_token, device_id)
if isinstance(device_status, dict) and device_status.get('statusCode') == 100:
body = device_status['body']
print(f"Device ID: {body.get('deviceId')}")
print(f"Device Type: {body.get('deviceType')}")
print(f"Hub Device ID: {body.get('hubDeviceId')}")
print(f"Power Status: {body.get('power')}")
print(f"Version: {body.get('version')}")
if body.get('power') == 'on':
updated_status = send_command(api_token, secret_token, device_id, "turnOff")
print("Power Status: off - Turned off the device successfully.")
elif body.get('power') == 'off':
updated_status = send_command(api_token, secret_token, device_id, "turnOn")
print("Power Status: on - Turned on the device successfully.")
else:
print("Failed to retrieve device status. Error:", device_status)
The script sends an HTTP GET request. If it succeeds, it returns device information as JSON; otherwise, it returns the status code and an error message. It sends an on or off operation command to the specified device with an HTTP POST request and displays the result. It then waits ten seconds for the state to change before fetching the status again. From the returned device status, it displays the device ID, type, hub device ID, power state, and version. It sends the appropriate command based on the current on/off state, checks whether the device changed state, and prints a success message if it did. Here is what running it looks like.
Device ID: XXXXXXXXX
Device Type: Plug
Hub Device ID: XXXXXXXXX
Power Status: off
Version: V1.7
Sending turnOn command: {"statusCode":100,"body":{"items":[{"deviceID":"XXXXXXXXX","code":100,"status":{"timeStamp":"XXXXXXXXX","wattage":"0","current":"0","consume":"35","state":"0","power":"on","ipAddr":"XXXXXXXXX","mac":"XXXXXXXXX","voltage":"995"},"message":"success"}]},"message":"success"}
Power Status: on - Turned on the device successfully.
SwitchBot Plug Mini (older model)View listings on Amazon Ad / Amazon Associates link





