In this training, you will learn the basics of the Internet of Things. In this part, you will learn the principle of web services.

Get weather data from a web service 
import requests
import json

api_key = "your_openweathermap_api_key"
city = "Paris"

url = "https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric"%(city, api_key)
response = requests.get(url)
data = json.loads(response.text)
temp = data["main"]["temp"]
print(temp)

Current weather class :

import requests
import json

class CurrentWeather():
    api_key = "your_openweathermap_apu_key"
    url = ''
    temp = ''
    humidity = ''
    windspeed = ''
    
    def __init__(self, city):
        self.city = city
        self.url = "https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric"%(self.city, self.api_key)
        response = requests.get(self.url)
        data = json.loads(response.text)
        self.temp = data["main"]["temp"]
        self.humidity = data["main"]["humidity"]
        self.windspeed = data["wind"]["speed"]
        
    def get_temp(self):
        return self.temp
    def get_humidity(self):
        return self.humidity
    def get_windspeed(self):
        return self.windspeed
    def get_city(self):
        return self.city
    
    
if __name__=="__main__":
    city = input('Your city : ')
    current_weather = CurrentWeather(city)
    print("%s Temperature : %sC, Humidity : %s, wind speed : %s km/h"% (current_weather.get_city(),
                                                                        current_weather.get_temp(),
                                                                        current_weather.get_humidity(),
                                                                        current_weather.get_windspeed()))
    
    

Visualize weather data on sense hat emulator:

from sense_emu import SenseHat
from current_weather import CurrentWeather

city = input('Your city : ')

current_weather = CurrentWeather(city)

sense_hat = SenseHat()

message = ("%s Temperature : %sC, Humidity : %s, wind speed : %s km/h"% 
                           (current_weather.get_city(),                                                                      
                            current_weather.get_temp(),                                                                    
                            current_weather.get_humidity(),                                                                
                            current_weather.get_windspeed()))

sense_hat.show_message(message)

 

0 comment

There are no comments yet.

Log in to leave a reply

Related posts

An Internet of Things Training Part 1: Getting Started

13/2/2022

Internet of Things Training Part 2: Programming of Raspberry PI GPIO

13/2/2022

Internet of Things Training Part 3: ThingsBoard IoT platform

14/2/2022