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