88
99# Import standard python modules.
1010import sys
11+ import json
1112
1213# Import Adafruit IO MQTT client.
1314from Adafruit_IO import MQTTClient
4142# Subscribe to the current forecast
4243forecast_today = 'current'
4344# Subscribe to tomorrow's forecast
44- forecast_tomorrow = 'forecast_days_2'
45+ forecast_two_days = 'forecast_days_2'
4546# Subscribe to forecast in 5 days
4647forecast_in_5_days = 'forecast_days_5'
4748
@@ -56,7 +57,7 @@ def connected(client):
5657 client .subscribe_weather (forecast_id , forecast_today )
5758
5859 # Subscribe to changes on tomorrow's forecast.
59- client .subscribe_weather (forecast_id , forecast_tomorrow )
60+ client .subscribe_weather (forecast_id , forecast_two_days )
6061
6162 # Subscribe to changes on forecast in 5 days.
6263 client .subscribe_weather (forecast_id , forecast_in_5_days )
@@ -70,19 +71,32 @@ def message(client, topic, payload):
7071 """Message function will be called when any subscribed forecast has an update.
7172 Weather data is updated at most once every 20 minutes.
7273 """
73- # Raw data from feed
74- print (topic )
75- print (payload )
76- # parse based on topic
77- if topic is 'current' :
74+ # forecast based on mqtt topic
75+ if topic == 'current' :
7876 # Print out today's forecast
79- print ('Current Forecast: {0}' .format (payload ))
80- elif topic is 'forecast_days_2' :
81- # print out tomorrow's forecast
82- print ('Forecast Tomorrow: {0}' .format (payload ))
83- elif topic is 'forecast_days_5' :
84- # print out forecast in 5 days
85- print ('Forecast in 5 Days: {0}' .format (payload ))
77+ today_forecast = payload
78+ print ('\n Current Forecast' )
79+ parseForecast (today_forecast )
80+ elif topic == 'forecast_days_2' :
81+ # Print out tomorrow's forecast
82+ two_day_forecast = payload
83+ print ('\n Weather in Two Days' )
84+ parseForecast (two_day_forecast )
85+ elif topic == 'forecast_days_5' :
86+ # Print out forecast in 5 days
87+ five_day_forecast = payload
88+ print ('\n Weather in 5 Days' )
89+ parseForecast (five_day_forecast )
90+
91+ def parseForecast (forecast_data ):
92+ """Parses incoming forecast data
93+ """
94+ # incoming data is a utf-8 string, encode it as a json object
95+ forecast = json .loads (forecast_data )
96+ print (forecast )
97+ print ('It is {0} and {1} F.' .format (forecast ['summary' ], forecast ['temperature' ]))
98+ print ('with a humidity of {0}% and a wind speed of {1}mph.' .format (forecast ['humidity' ], forecast ['windSpeed' ]))
99+ print ('There is a {0}% chance of precipitation. It feels like {1} F' .format (forecast ['precipProbability' ], forecast ['apparentTemperature' ]))
86100
87101# Create an MQTT client instance.
88102client = MQTTClient (ADAFRUIT_IO_USERNAME , ADAFRUIT_IO_KEY )
0 commit comments