weatherstation/oko-weather/oko-weather-sync.py

97 lines
2.4 KiB
Python
Raw Normal View History

import logging
import time
import datetime
import urllib.parse
import http.client
from influxdb import InfluxDBClient
from oko_user_config import *
2020-03-27 19:06:11 +01:00
oko_influxdb_query = "select temperature, humidity, light, windspeed, pressure from weather where device='%STATION%' order by time desc limit 1;"
def read_data_from_influxdb():
# temp, hum, wind, pres, date
ret = [ 0.0, 0.0, 0.0, 0.0, "" ]
client = InfluxDBClient(oko_server, oko_server_port, oko_user, oko_password, oko_dbname)
2020-03-27 19:06:11 +01:00
query = oko_influxdb_query.replace("%STATION%", oko_weatherstation_name)
print(query)
qres = client.query(query)
print(qres)
tdata = qres.raw['series'][0]['values'][0]
print(tdata)
ret[0] = tdata[1] # temp
ret[1] = tdata[2] # hum
ret[2] = tdata[4] * 1000 # wind km/h to m/s
ret[3] = tdata[5] # pres
ret[4] = tdata[0] # date
print(ret)
return ret
def send_data_to_openweather(temp, hum, wind, pres, date):
# http://api.openweathermap.org/data/3.0/stations?appid=
http.client.HTTPSConnection.debuglevel = 1
2020-03-24 22:29:18 +01:00
conn = http.client.HTTPSConnection("api.openweathermap.org")
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
2020-03-25 11:09:00 +01:00
url = "/data/3.0/measurements?appid=" + openweather_api_key
data = '[{"station_id":"' + openweather_station_id + '",' + \
'"dt":' + str(date) + ',' + \
'"temperature":' + str(temp) + ',' + \
'"wind_speed":' + str(wind) + ',' + \
'"pressure":' + str(pres) + ',' + \
'"humidity":' + str(hum) + '' + \
'}]'
header = { "Content-Type" : "application/json" }
print(url)
print(data)
print(header)
conn.request("POST", url, data, header)
res = conn.getresponse()
print(res.read())
def date_to_str(date):
date = date.replace("T", " ")[0:19]
ret = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").timetuple()))
return ret
if __name__ == "__main__":
data = [ 0.0, 0.0, 0.0, 0.0, 0 ]
data = read_data_from_influxdb()
temp = data[0]
hum = data[1]
wind = data[2]
pres = data[3]
date = data[4]
tdate = date_to_str(date)
send_data_to_openweather(temp, hum, wind, pres, tdate)