]> ToastFreeware Gitweb - chrisu/seepark.git/blob - owm.py
we can have wind without degrees (only speed)
[chrisu/seepark.git] / owm.py
1 #!/usr/bin/python3
2
3 # needs ~/seepark.ini with
4 # [openweathermap]
5 # apikey=...
6 # cityid=..
7 # 3319578 for Obsteig, AT
8
9 from pprint import pprint
10 import argparse
11 import requests
12 import configparser
13 import os
14 import csv
15 import datetime
16 import math
17 import sys
18
19 baseurl = 'http://api.openweathermap.org/data/2.5/weather'
20 debug = False
21
22 def getweather(apikey, cityid):
23     query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
24     try:
25         response = requests.get(query)
26         if response.status_code != 200:
27             response = 'N/A'
28             return response
29         else:
30             weatherdata = response.json()
31             return weatherdata
32     except requests.exceptions.RequestException as error:
33         print (error)
34         sys.exit(1)
35
36
37 def fromtimestamp(timestamp, format):
38     return datetime.datetime.fromtimestamp(timestamp).strftime(format)
39
40
41 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
42 def degToCompass(num):
43     if num is None or num is math.nan:
44         return 'N/A'
45     val=int((num/22.5)+.5)
46     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
47     return arr[(val % 16)]
48
49
50 def extractweatherdata(w):
51     w['wind']['deg'] = math.nan
52     data = dict(
53         datetime = w['dt'],
54         sunrise = w['sys']['sunrise'],
55         sunset = w['sys']['sunset'],
56         temp = w['main']['temp'],
57         pressure = w['main']['pressure'],
58         humidity = w['main']['humidity'],
59         visibility = w['visibility'],
60         weather = w['weather'][0]['description'],
61         sky = w['weather'][0]['main'],
62         windspeed = w['wind']['speed'],
63         cloudiness = w['clouds']['all'],
64     )
65
66     data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S')
67     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
68     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
69     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
70     data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
71     data['winddirection'] = degToCompass(data['winddegrees'])
72     data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
73
74     return data
75
76
77 def write_csv(csv_file, weather_data):
78     """output like wetter.at.pl"""
79     with open(csv_file, "a", newline="") as file:
80         writer = csv.writer(file, dialect="excel", delimiter=';')
81         writer.writerow([
82             weather_data['date'],
83             weather_data['time'],
84             weather_data['sunrise_t'],
85             weather_data['sunset_t'],
86             "{:.2f}".format(weather_data['temp']),
87             "{:.2f} mm/h".format(weather_data['precipitation']),
88             "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
89             weather_data['weather'],
90             "{}".format(weather_data['cloudiness'])
91         ])
92
93
94 def main(configfile):
95     config = configparser.ConfigParser()
96     config.read(configfile)
97     apikey = config.get('openweathermap', 'apikey')
98     cityid = config.get('openweathermap', 'cityid')
99     csvfile = config.get("openweathermap", 'csvfilename')
100
101     weather_raw = getweather(apikey, cityid)
102     if debug:
103         pprint(weather_raw)
104     weather = extractweatherdata(weather_raw)
105     if debug:
106         pprint(weather)
107
108     # TODO:
109     # write to db
110
111     # write to csv
112     write_csv(os.path.expanduser(csvfile), weather)
113
114
115 if __name__ == '__main__':
116     default_config_file = os.path.expanduser('~/seewasser.ini')
117     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
118     parser.add_argument('--config', default=default_config_file, help='configuration file')
119     args = parser.parse_args()
120     main(args.config)