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