Skip to content

Instantly share code, notes, and snippets.

@junara
Last active December 4, 2019 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save junara/229b2d324cb2928eb8966092db733078 to your computer and use it in GitHub Desktop.
Save junara/229b2d324cb2928eb8966092db733078 to your computer and use it in GitHub Desktop.
IBS-TH1 のログを取得してAmbientとローカルCSVに出力する python script
*/10 * * * * python /あなたの絶対パス/inkbird.py
from bluepy import btle
import binascii
import ambient
import csv
from datetime import datetime
from pytz import timezone
CHANNEL_ID = 'あなたのAmbientチャネルID'
WRITE_KEY = 'あなたのAmbientライトキー'
PERIPHERAL_MAC_ADDRESS = 'あなたのInkibird IBS-TH1 MACアドレス'
HANDLE = 0x002d
CSV_FILE = 'CSVファイルを出力するローカルの絶対パス(/xxx/xxx/hoge.csv とか)'
def main():
peripheral = btle.Peripheral(PERIPHERAL_MAC_ADDRESS)
characteristic = get_characteristic(peripheral, HANDLE)
temperature = characteristic_to_temperature(characteristic)
humidity = characteristic_to_humidity(characteristic)
data = send_data_params(temperature, humidity)
peripheral.disconnect
export_csv(data, CSV_FILE)
return send_ambient(data, CHANNEL_ID, WRITE_KEY)
def send_ambient(data, channel_id, write_key):
am = ambient.Ambient(channel_id, write_key)
am.send(data)
def get_characteristic(peripheral, handle):
return peripheral.readCharacteristic(handle)
def characteristic_to_temperature(characteristic):
temp_hex = binascii.b2a_hex(characteristic[1]) + binascii.b2a_hex(characteristic[0])
return float(int(temp_hex, 16)) / 100
def characteristic_to_humidity(characteristic):
humid_hex = binascii.b2a_hex(characteristic[3]) + binascii.b2a_hex(characteristic[2])
return float(int(humid_hex, 16)) / 100
def send_data_params(temperature, humidity):
return {
'd1': temperature,
'd2': humidity,
}
def export_csv(data, csv_file):
with open(csv_file, 'a') as f:
writer = csv.writer(f)
writer.writerow(
[
datetime_now(),
data['d1'],
data['d2']
]
)
def datetime_now():
return datetime.now(timezone('Asia/Tokyo'))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment