owm.py: import sys
[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:
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     data = dict(
52         datetime = w['dt'],
53         sunrise = w['sys']['sunrise'],
54         sunset = w['sys']['sunset'],
55         temp = w['main']['temp'],
56         pressure = w['main']['pressure'],
57         humidity = w['main']['humidity'],
58         visibility = w['visibility'],
59         weather = w['weather'][0]['description'],
60         sky = w['weather'][0]['main'],
61         windspeed = w['wind']['speed'],
62         winddegrees = w['wind']['deg'],
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['winddirection'] = degToCompass(data['winddegrees'])
71     data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
72
73     return data
74
75
76 def write_csv(csv_file, weather_data):
77     """output like wetter.at.pl"""
78     with open(csv_file, "a", newline="") as file:
79         writer = csv.writer(file, dialect="excel", delimiter=';')
80         writer.writerow([
81             weather_data['date'],
82             weather_data['time'],
83             weather_data['sunrise_t'],
84             weather_data['sunset_t'],
85             "{:.2f}".format(weather_data['temp']),
86             "{:.2f} mm/h".format(weather_data['precipitation']),
87             "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
88             weather_data['weather'],
89             "{}".format(weather_data['cloudiness'])
90         ])
91
92
93 def main(configfile):
94     config = configparser.ConfigParser()
95     config.read(configfile)
96     apikey = config.get('openweathermap', 'apikey')
97     cityid = config.get('openweathermap', 'cityid')
98     csvfile = config.get("openweathermap", 'csvfilename')
99
100     weather_raw = getweather(apikey, cityid)
101     if debug:
102         pprint(weather_raw)
103     weather = extractweatherdata(weather_raw)
104     if debug:
105         pprint(weather)
106
107     # TODO:
108     # write to db
109
110     # write to csv
111     write_csv(os.path.expanduser(csvfile), weather)
112
113
114 if __name__ == '__main__':
115     default_config_file = os.path.expanduser('~/seewasser.ini')
116     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
117     parser.add_argument('--config', default=default_config_file, help='configuration file')
118     args = parser.parse_args()
119     main(args.config)