8
8
9
9
# Import standard python modules.
10
10
import sys
11
+ import json
11
12
12
13
# Import Adafruit IO MQTT client.
13
14
from Adafruit_IO import MQTTClient
41
42
# Subscribe to the current forecast
42
43
forecast_today = 'current'
43
44
# Subscribe to tomorrow's forecast
44
- forecast_tomorrow = 'forecast_days_2'
45
+ forecast_two_days = 'forecast_days_2'
45
46
# Subscribe to forecast in 5 days
46
47
forecast_in_5_days = 'forecast_days_5'
47
48
@@ -56,7 +57,7 @@ def connected(client):
56
57
client .subscribe_weather (forecast_id , forecast_today )
57
58
58
59
# Subscribe to changes on tomorrow's forecast.
59
- client .subscribe_weather (forecast_id , forecast_tomorrow )
60
+ client .subscribe_weather (forecast_id , forecast_two_days )
60
61
61
62
# Subscribe to changes on forecast in 5 days.
62
63
client .subscribe_weather (forecast_id , forecast_in_5_days )
@@ -70,19 +71,32 @@ def message(client, topic, payload):
70
71
"""Message function will be called when any subscribed forecast has an update.
71
72
Weather data is updated at most once every 20 minutes.
72
73
"""
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' :
78
76
# 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' ]))
86
100
87
101
# Create an MQTT client instance.
88
102
client = MQTTClient (ADAFRUIT_IO_USERNAME , ADAFRUIT_IO_KEY )
0 commit comments