No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oko-weather-sync.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import logging
  2. import time
  3. import datetime
  4. import urllib.parse
  5. import http.client
  6. from influxdb import InfluxDBClient
  7. from oko_user_config import *
  8. oko_influxdb_query = "select temperature, humidity, light, windspeed, pressure from weather where device='%STATION%' order by time desc limit 1;"
  9. def read_data_from_influxdb():
  10. # temp, hum, wind, pres, date
  11. ret = [ 0.0, 0.0, 0.0, 0.0, "" ]
  12. client = InfluxDBClient(oko_server, oko_server_port, oko_user, oko_password, oko_dbname)
  13. query = oko_influxdb_query.replace("%STATION%", oko_weatherstation_name)
  14. print(query)
  15. qres = client.query(query)
  16. print(qres)
  17. tdata = qres.raw['series'][0]['values'][0]
  18. print(tdata)
  19. ret[0] = tdata[1] # temp
  20. ret[1] = tdata[2] # hum
  21. ret[2] = tdata[4] * 1000 # wind km/h to m/s
  22. ret[3] = tdata[5] # pres
  23. ret[4] = tdata[0] # date
  24. print(ret)
  25. return ret
  26. def send_data_to_openweather(temp, hum, wind, pres, date):
  27. # http://api.openweathermap.org/data/3.0/stations?appid=
  28. http.client.HTTPSConnection.debuglevel = 1
  29. conn = http.client.HTTPSConnection("api.openweathermap.org")
  30. logging.basicConfig()
  31. logging.getLogger().setLevel(logging.DEBUG)
  32. requests_log = logging.getLogger("requests.packages.urllib3")
  33. requests_log.setLevel(logging.DEBUG)
  34. requests_log.propagate = True
  35. url = "/data/3.0/measurements?appid=" + openweather_api_key
  36. data = '[{"station_id":"' + openweather_station_id + '",' + \
  37. '"dt":' + str(date) + ',' + \
  38. '"temperature":' + str(temp) + ',' + \
  39. '"wind_speed":' + str(wind) + ',' + \
  40. '"pressure":' + str(pres) + ',' + \
  41. '"humidity":' + str(hum) + '' + \
  42. '}]'
  43. header = { "Content-Type" : "application/json" }
  44. print(url)
  45. print(data)
  46. print(header)
  47. #conn.request("POST", url, urllib.parse.urlencode(data), header)
  48. conn.request("POST", url, data, header)
  49. res = conn.getresponse()
  50. print(res.read())
  51. def date_to_str(date):
  52. date = date.replace("T", " ")[0:19]
  53. ret = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").timetuple()))
  54. return ret
  55. if __name__ == "__main__":
  56. data = [ 0.0, 0.0, 0.0, 0.0, 0 ]
  57. data = read_data_from_influxdb()
  58. temp = data[0]
  59. hum = data[1]
  60. wind = data[2]
  61. pres = data[3]
  62. date = data[4]
  63. tdate = date_to_str(date)
  64. send_data_to_openweather(temp, hum, wind, pres, tdate)