add an openweathermap widget to the webpage
[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     val=int((num/22.5)+.5)
40     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
41     return arr[(val % 16)]
42
43
44 def extractweatherdata(w):
45     data = dict(
46         datetime = w.get('dt'),
47         sunrise = w.get('sys').get('sunrise'),
48         sunset = w.get('sys').get('sunset'),
49         temp = w.get('main').get('temp'),
50         pressure = w.get('main').get('pressure'),
51         humidity = w.get('main').get('humidity'),
52         visibility = w.get('visibility'),
53         weather=w['weather'][0]['description'],
54         sky=w['weather'][0]['main'],
55         windspeed=w.get('wind').get('speed'),
56         winddegrees=w.get('wind').get('deg'),
57         cloudiness=w.get('clouds').get('all'),
58     )
59
60     data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S')
61     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
62     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
63     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
64     data['winddirection'] = degToCompass(data['winddegrees'])
65
66     return data
67         
68
69 def main():
70     config = configparser.ConfigParser()
71     config.read(os.path.expanduser('~/seewasser.ini'))
72     apikey = config.get('openweathermap', 'apikey');
73     cityid = config.get('openweathermap', 'cityid');
74
75     weather_raw = getweather(apikey, cityid)
76     if debug:
77         pprint(weather_raw)
78     weather = extractweatherdata(weather_raw)
79     if debug:
80         pprint(weather)
81     # TODO:
82     # write to db
83     # write to csv
84     
85     # output like wetter.at.pl
86     print(
87         weather['date'] + ';' +
88         weather['time'] + ';' +
89         weather['sunrise_t'] + ';' +
90         weather['sunset_t'] + ';' +
91         str(weather['temp']) + ';' +
92         ';' + # precipitation missing? or only in XML: https://openweathermap.org/current ?
93         str(weather['windspeed']) + 'km/h ' + weather['winddirection'] + ';' +
94         weather['weather'] + ';' +
95         str(weather['cloudiness'])
96     )
97
98     
99 if __name__ == '__main__':
100     main()