59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
import logging
|
|
import time
|
|
|
|
from os import getenv
|
|
|
|
import requests
|
|
|
|
from tinkerforge.ip_connection import IPConnection
|
|
from tinkerforge.bricklet_outdoor_weather import BrickletOutdoorWeather
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
HOST = getenv("TF_HOST", "192.168.2.160")
|
|
PORT = int(getenv("TF_PORT", 4223))
|
|
UID = getenv("TF_ID", "DYC")
|
|
URL = getenv("INFLUX_URL", "http://influxdb:8086)
|
|
DB = getenv("INFLUXDB_DB", "mydb")
|
|
|
|
|
|
|
|
def influx(type, identifier, **kwargs):
|
|
log.info(f"{type}, {identifier}, {kwargs}")
|
|
time_ns = time.time_ns()
|
|
data = []
|
|
for unit in kwargs:
|
|
data.append(f"{unit},type={type},identifier={identifier} value={kwargs[unit]} {time_ns}")
|
|
try:
|
|
url = f"{URL}/write?db={DB}"
|
|
r = requests.post(url, data="\n".join(data))
|
|
log.info(f"{r}, {r.text}")
|
|
except Exception as e:
|
|
log.exception(e)
|
|
|
|
def cb_station(identifier, temperature, humidity, wind_speed, gust_speed, rain, wind_direction, battery_low):
|
|
influx(type="station", identifier=identifier, temperature=temperature, humidity=humidity, wind_speed=wind_speed, gust_speed=gust_speed, rain=rain, wind_direction=wind_direction, battery_low=battery_low)
|
|
def cb_sensor(identifier, temperature, humidity):
|
|
influx(type="sensor", identifier=identifier, temperature=temperature, humidity=humidity)
|
|
|
|
if __name__ == "__main__":
|
|
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
|
log.info("starting…")
|
|
ipcon = IPConnection()
|
|
ow = BrickletOutdoorWeather(UID, ipcon)
|
|
ipcon.connect(HOST, PORT)
|
|
ow.set_station_callback_configuration(True)
|
|
ow.set_sensor_callback_configuration(True)
|
|
ow.register_callback(ow.CALLBACK_STATION_DATA, cb_station)
|
|
ow.register_callback(ow.CALLBACK_SENSOR_DATA, cb_sensor)
|
|
log.info("try to create influx db…")
|
|
requests.post(f"{URL}/query?q=CREATE DATABASE {DB}")
|
|
log.info("now we play the waiting game…")
|
|
while True:
|
|
try:
|
|
time.sleep(60*60)
|
|
except Exception:
|
|
log.warning("…")
|
|
ipcon.disconnect()
|