Use seeparklib.openweathermap.
[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 configparser
12 import os
13 import csv
14 import datetime
15 import math
16 from seeparklib.openweathermap import openweathermap_json
17
18 debug = False
19
20
21 def fromtimestamp(timestamp, format):
22     return datetime.datetime.fromtimestamp(timestamp).strftime(format)
23
24
25 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
26 def degToCompass(num):
27     if num is None or num is math.nan:
28         return 'N/A'
29     val=int((num/22.5)+.5)
30     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
31     return arr[(val % 16)]
32
33
34 def extractweatherdata(w):
35     data = dict(
36         datetime = w['dt'],
37         sunrise = w['sys']['sunrise'],
38         sunset = w['sys']['sunset'],
39         temp = w['main']['temp'],
40         pressure = w['main']['pressure'],
41         humidity = w['main']['humidity'],
42         visibility = w['visibility'],
43         weather = w['weather'][0]['description'],
44         sky = w['weather'][0]['main'],
45         windspeed = w['wind']['speed'],
46         cloudiness = w['clouds']['all'],
47     )
48
49     data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S')
50     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
51     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
52     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
53     data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
54     data['winddirection'] = degToCompass(data['winddegrees'])
55     data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
56
57     return data
58
59
60 def write_csv(csv_file, weather_data):
61     """output like wetter.at.pl"""
62     with open(csv_file, "a", newline="") as file:
63         writer = csv.writer(file, dialect="excel", delimiter=';')
64         writer.writerow([
65             weather_data['date'],
66             weather_data['time'],
67             weather_data['sunrise_t'],
68             weather_data['sunset_t'],
69             "{:.2f}".format(weather_data['temp']),
70             "{:.2f} mm/h".format(weather_data['precipitation']),
71             "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
72             weather_data['weather'],
73             "{}".format(weather_data['cloudiness'])
74         ])
75
76
77 def main(configfile):
78     config = configparser.ConfigParser()
79     config.read(configfile)
80     apikey = config.get('openweathermap', 'apikey')
81     cityid = config.get('openweathermap', 'cityid')
82     csvfile = config.get("openweathermap", 'csvfilename')
83
84     weather_raw = openweathermap_json(apikey, cityid)
85     if debug:
86         pprint(weather_raw)
87     weather = extractweatherdata(weather_raw)
88     if debug:
89         pprint(weather)
90
91     # TODO:
92     # write to db
93
94     # write to csv
95     write_csv(os.path.expanduser(csvfile), weather)
96
97
98 if __name__ == '__main__':
99     default_config_file = os.path.expanduser('~/seewasser.ini')
100     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
101     parser.add_argument('--config', default=default_config_file, help='configuration file')
102     args = parser.parse_args()
103     main(args.config)