Script takes config file from command line now.
[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 datetime
15
16 baseurl = 'http://api.openweathermap.org/data/2.5/weather'
17 debug = False
18
19 def getweather(apikey, cityid):
20     query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
21     try:
22         response = requests.get(query)
23         if response.status_code != 200:
24             response = 'N/A'
25             return response
26         else:
27             weatherdata = response.json()
28             return weatherdata
29     except requests.exceptions.RequestException as error:
30         print (error)
31         sys.exit(1)
32
33
34 def fromtimestamp(timestamp, format):
35     return datetime.datetime.fromtimestamp(timestamp).strftime(format)
36
37
38 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
39 def degToCompass(num):
40     if num is None:
41         return 'N/A'
42     val=int((num/22.5)+.5)
43     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
44     return arr[(val % 16)]
45
46
47 def extractweatherdata(w):
48     data = dict(
49         datetime = w['dt'],
50         sunrise = w['sys']['sunrise'],
51         sunset = w['sys']['sunset'],
52         temp = w['main']['temp'],
53         pressure = w['main']['pressure'],
54         humidity = w['main']['humidity'],
55         visibility = w['visibility'],
56         weather = w['weather'][0]['description'],
57         sky = w['weather'][0]['main'],
58         windspeed = w['wind']['speed'],
59         winddegrees = w['wind']['deg'],
60         cloudiness = w['clouds']['all'],
61     )
62
63     data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S')
64     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
65     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
66     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
67     data['winddirection'] = degToCompass(data['winddegrees'])
68     data['precipitation'] = w['rain']['3h'] if 'rain' in w else 'N/A'
69
70     return data
71
72
73 def main(configfile):
74     config = configparser.ConfigParser()
75     config.read(configfile)
76     apikey = config.get('openweathermap', 'apikey');
77     cityid = config.get('openweathermap', 'cityid');
78
79     weather_raw = getweather(apikey, cityid)
80     if debug:
81         pprint(weather_raw)
82     weather = extractweatherdata(weather_raw)
83     if debug:
84         pprint(weather)
85     # TODO:
86     # write to db
87     # write to csv
88     
89     # output like wetter.at.pl
90     print(
91         weather['date'] + ';' +
92         weather['time'] + ';' +
93         weather['sunrise_t'] + ';' +
94         weather['sunset_t'] + ';' +
95         str(weather['temp']) + ';' +
96         str(weather['precipitation']) + ' mm/h;' +
97         str(weather['windspeed']) + ' km/h ' + weather['winddirection'] + ';' +
98         weather['weather'] + ';' +
99         str(weather['cloudiness'])
100     )
101
102
103 if __name__ == '__main__':
104     default_config_file = os.path.expanduser('~/seewasser.ini')
105     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
106     parser.add_argument('--config', default=default_config_file, help='configuration file')
107     args = parser.parse_args()
108     main(args.config)