Note: This article was published more than a year ago.
- SwitchBot API endpoints, token methods, rate limits, and app screens can change. Consult the latest developer documentation.
- Firmware can change response intervals and available fields. Check both the app and API documentation.
- The Python code reflects the environment at the time. Check compatibility with its dependencies.
Here I use Python and the SwitchBot API to read temperature and humidity from a SwitchBot meter. MQTT, or Message Queuing Telemetry Transport, can also exchange this data efficiently between Internet of Things devices. The same approach should retrieve data from the SwitchBot Meter, Meter Plus, and Indoor/Outdoor Meter. I have confirmed operation with the ordinary Meter and the Indoor/Outdoor Meter.
View the SwitchBot Meter on Amazon (Ad)
View the SwitchBot Indoor/Outdoor Meter on Amazon (Ad)
View the SwitchBot Meter Plus on Amazon (not tested in this article) (Ad)
Once you know the meter's device ID, you can retrieve its data over the network through the SwitchBot API. Combining temperature and humidity readings with Python and other IoT devices offers plenty of possibilities. See the earlier article for obtaining the device ID.
https://riragon.com/blog/en/switchbot-api-python/
SwitchBot API v1.1
https://github.com/OpenWonderLabs/SwitchBotAPI
You need Python 3.6 or later and the requests package. Install Python and prepare a virtual environment as appropriate. Here is an example of installing requests; adapt the Python environment to your setup.
pip install requests pandas
In the following Python program, replace the token, secret token, and device ID with your own values.
The get_device_list() function retrieves the device list and locates the details of the specified device.
The get_device_status() function retrieves and displays its temperature, humidity, and battery level.
switchbot_meter_data_retriever.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 get_device_list(api_token, secret_token):
url = "https://api.switch-bot.com/v1.1/devices"
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
# トークンとシークレットキーを設定
api_token = 'XXXXXXXXXXXXXXXXXXXXXX'
secret_token = 'XXXXXXXXXXXXXXXXXXXXXXXX'
device_id = 'XXXXXXXXXXXXXXXXXXXXX'
device_list_data = get_device_list(api_token, secret_token)
if isinstance(device_list_data, dict) and device_list_data.get('statusCode') == 100:
device_list = device_list_data['body']['deviceList']
for device in device_list:
if device['deviceId'] == device_id:
device_info = {
"Device ID": device.get('deviceId', 'N/A'),
"Device Name": device.get('deviceName', 'N/A'),
"Device Type": device.get('deviceType', 'N/A'),
"Cloud Service Enabled": device.get('enableCloudService', 'N/A'),
"Hub Device ID": device.get('hubDeviceId', 'N/A')
}
for key, value in device_info.items():
print(f"{key}: {value}")
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']
if 'temperature' in body:
print(f"Temperature: {body['temperature']}°C")
if 'humidity' in body:
print(f"Humidity: {body['humidity']}%")
if 'battery' in body:
print(f"Battery Level: {body['battery']}%")
else:
print("デバイスリストの取得に失敗しました。")
The program retrieves and displays device status data through the SwitchBot API.
First, import the required libraries.
requests sends HTTP requests; time handles time-related operations; uuid generates unique identifiers; hmac creates HMAC signatures; hashlib supplies hash functions; and base64 performs Base64 encoding and decoding.
The get_device_status function retrieves the specified device's status.
It first sets the API endpoint URL, then obtains the current timestamp in milliseconds.
It generates a UUID as a unique identifier and constructs the string to sign.
That string is signed with HMAC-SHA256, and the signature is Base64-encoded.
It then sets the headers and sends an HTTP GET request.
If the response succeeds, it returns the JSON data.
Otherwise, it returns the status code and response text.
The get_device_list function retrieves the device list.
Like get_device_status, it sets the API endpoint and generates a timestamp, unique identifier, and signature.
It sets the headers and sends an HTTP GET request.
A successful response returns JSON data.
An unsuccessful response returns the status code and response text.
The program searches the returned list for a device matching the specified ID.
It obtains and displays that device's details.
It then calls get_device_status and displays the temperature, humidity, and battery level.
If retrieving the list fails, it displays the Japanese message meaning 'Failed to retrieve the device list.'
Running the program produces data as shown. I believe these are all the available fields.
python hoguhogu.py
Device ID: ABCDABCDABCD
Device Name: 温湿度計 FA
Device Type: Meter
Cloud Service Enabled: True
Hub Device ID: ABCDABCDABCD
Temperature: 25.2°C
Humidity: 65%
Battery Level: 100%
SwitchBot MeterView details on Amazon Ad · Amazon Associate link
SwitchBot Indoor/Outdoor MeterView details on Amazon Ad · Amazon Associate link





