Created
October 9, 2018 15:11
-
-
Save drewmoseley/47c46a6cad294b3336b17f150dd08570 to your computer and use it in GitHub Desktop.
Sample mqtt weather app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import paho.mqtt.client as mqtt | |
def onConnect(client, obj, flags, rc): | |
print("Connected. rc = %s " % rc) | |
client.subscribe("iot-bbb-example/weather/temperature") | |
client.subscribe("iot-bbb-example/weather/precipitation") | |
# Dummy function to act on temperature data | |
def temperatureActuator(temperature): | |
print("Temperature = %s\n" % temperature) | |
# Dummy function to act on precipitation data | |
def precipitationActuator(precipitation): | |
action = { | |
"rain" : "Grab an umbrella", | |
"sun" : "Don't forget the sunscreen", | |
"hurricane" : "Buy bread, water and peanut butter." | |
} | |
print("Precipitation = %s" % precipitation) | |
print("\t%s\n" % action[precipitation]) | |
def onMessage(mqttc, obj, msg): | |
callbacks = { | |
"iot-bbb-example/weather/temperature" : temperatureActuator, | |
"iot-bbb-example/weather/precipitation" : precipitationActuator | |
} | |
callbacks[msg.topic](msg.payload) | |
client = mqtt.Client() | |
client.on_connect = onConnect | |
client.on_message = onMessage | |
client.connect("test.mosquitto.org", 1883, 60) | |
client.loop_forever() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import paho.mqtt.publish as mqtt | |
import time | |
import random | |
# Dummy function to read from a temperature sensor. | |
def readTemp(): | |
return random.randint(80,100) | |
# Deumm function to read from a rain sensor. | |
def readPrecipitation(): | |
r = random.randint(0,10) | |
if r < 4: | |
return 'rain' | |
elif r < 8: | |
return 'sun' | |
else: | |
return 'hurricane' | |
while True: | |
mqtt.single("iot-bbb-example/weather/temperature", readTemp(), hostname="test.mosquitto.org") | |
mqtt.single("iot-bbb-example/weather/precipitation", readPrecipitation(), hostname="test.mosquitto.org") | |
time.sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment