Skip to content

Instantly share code, notes, and snippets.

@takamii
Created June 23, 2024 12:09
Show Gist options
  • Save takamii/ad6f0d829d44736e5eb5c72801afb83c to your computer and use it in GitHub Desktop.
Save takamii/ad6f0d829d44736e5eb5c72801afb83c to your computer and use it in GitHub Desktop.
ChatGPTにお願いして Switchbotの温湿度計の値をCSVに追記していくPythonプログラムを作ってもらいました。 実行時にはswitchbot_devices.jsonを用意しておく必要あります(device_id,device_nameをJSONで定義)。 CSVのファイル名はdevice_name.csvとなります。
import requests
import json
import time
import hmac
import hashlib
import base64
from datetime import datetime
import os
# SwitchBot APIトークンとシークレットキー
API_TOKEN = 'YOUR_SWITCHBOT_API_TOKEN'
SECRET_KEY = 'YOUR_SWITCHBOT_SECRET_KEY'
# APIのエンドポイント
BASE_URL = 'https://api.switch-bot.com/v1.1'
# 出力ディレクトリ
OUTPUT_DIR = '/path/to/your/output_directory'
# デバイス情報を保持するファイル
DEVICE_FILE = 'switchbot_devices.json'
def generate_signature(token, secret_key):
nonce = ''
t = int(round(time.time() * 1000))
string_to_sign = '{}{}{}'.format(token, t, nonce)
secret = secret_key.encode('utf-8')
sign = base64.b64encode(hmac.new(secret, msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest())
return sign, t, nonce
def get_temperature_and_humidity(device_id):
# 署名の生成
sign, t, nonce = generate_signature(API_TOKEN, SECRET_KEY)
# HTTPリクエストヘッダー
headers = {
'Authorization': API_TOKEN,
'sign': sign,
't': str(t),
'nonce': nonce,
'Content-Type': 'application/json; charset=utf8'
}
# デバイスのステータスを取得するエンドポイント
url = BASE_URL + '/devices/' + device_id + '/status'
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
if data['statusCode'] == 100:
temperature = data['body']['temperature']
humidity = data['body']['humidity']
return temperature, humidity
else:
print('Error: ', data['message'])
else:
print('Error: Failed to get device status, HTTP status code: ', response.status_code)
return None, None
def calculate_absolute_humidity(temperature, humidity):
# 絶対湿度を計算する
abs_humidity = (6.112 * (2.71828 ** ((17.67 * temperature) / (temperature + 243.5))) * humidity * 2.1674) / (273.15 + temperature)
return abs_humidity
def write_to_csv(current_time, temperature, humidity, abs_humidity, device_id, device_name):
# 出力ディレクトリが存在しない場合は作成する
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
filename = os.path.join(OUTPUT_DIR, '{}.csv'.format(device_name))
file_exists = os.path.isfile(filename)
with open(filename, 'a') as file:
if not file_exists:
# ファイルが存在しない場合、ヘッダーを書き込む
file.write('現在日時,気温,湿度,絶対湿度,デバイスID,デバイス名\n')
file.write('{},{:.1f},{},{:.2f},{},{}\n'.format(current_time, temperature, humidity, abs_humidity, device_id, device_name))
def main():
# デバイス情報をJSONファイルから読み込む
with open(DEVICE_FILE, 'r') as f:
devices = json.load(f)
for device in devices:
device_id = device['device_id']
device_name = device['device_name']
temperature, humidity = get_temperature_and_humidity(device_id)
if temperature is not None and humidity is not None:
abs_humidity = calculate_absolute_humidity(temperature, humidity)
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
write_to_csv(now, temperature, humidity, abs_humidity, device_id, device_name)
print('Data for {} written to CSV file.'.format(device_name))
else:
print('Failed to retrieve data for device: {}'.format(device_name))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment