Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import json
import requests
TOPIC = "weather/renton"
URL = "<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():
req = requests.get(URL)
body = req.text
result = json.loads(body)
return result
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