#!/usr/bin/env python | |
import paho.mqtt.client as mqtt | |
import json | |
import requests | |
BROKER = '192.168.0.1' | |
TOPIC = "weather/renton" | |
URL = "http://api.openweathermap.org/data/2.5/weather?id=5808189&APPID=<your api key goes here>" | |
API_DELAY_SEC = 60 * 10 # every 10 minutes | |
# OpenWeatherMap reports temps in Kelvin, apparently ¯\_(ツ)_/¯ | |
k_to_f = lambda k: (k - 273.15)*1.8 + 32 | |
def query_weather(): | |
try: | |
req = requests.get(URL) | |
body = req.text | |
result = json.loads(body) | |
return result | |
except: | |
return None | |
def on_connect(client, userdata, flags, rc): | |
print("Connected with result code " + str(rc)) | |
if __name__ == '__main__': | |
client = mqtt.Client() | |
client.on_connect = on_connect | |
client.connect(BROKER, 1883, 60) | |
weather = query_weather() | |
if weather is not None: | |
temp_k = weather['main']['temp'] | |
temp_f = k_to_f(temp_k) | |
print("Publishing current temp (%f) to topic '%s'" % (temp_f, TOPIC)) | |
client.publish(TOPIC, temp_f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment