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