3 # needs ~/seepark.ini with
7 # 3319578 for Obsteig, AT
9 from pprint import pprint
17 from sqlalchemy import create_engine
18 from seeparklib.openweathermap import openweathermap_json
21 def fromtimestamp(timestamp):
22 return datetime.datetime.fromtimestamp(timestamp)
25 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
26 def degToCompass(num):
27 if num is None or num is math.nan:
29 val=int((num/22.5)+.5)
30 arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
31 return arr[(val % 16)]
34 def extractweatherdata(w):
36 datetime = fromtimestamp(w['dt']),
37 sunrise = fromtimestamp(w['sys']['sunrise']),
38 sunset = fromtimestamp(w['sys']['sunset']),
39 temp = w['main']['temp'],
40 pressure = w['main']['pressure'],
41 humidity = w['main']['humidity'],
42 weather = w['weather'][0]['description'],
43 sky = w['weather'][0]['main'],
44 windspeed = w['wind']['speed'],
45 cloudiness = w['clouds']['all'],
48 data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
49 data['winddirection'] = degToCompass(data['winddegrees'])
50 data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
51 data['visibility'] = w.get('visibility', math.nan)
56 def write_csv(csv_file, weather_data):
57 """output like wetter.at.pl"""
58 with open(csv_file, "a", newline="") as file:
59 writer = csv.writer(file, dialect="excel", delimiter=';')
61 weather_data['datetime'].date(),
62 weather_data['datetime'].time(),
63 weather_data['sunrise'].time(),
64 weather_data['sunset'].time(),
65 "{:.2f}".format(weather_data['temp']),
66 "{:.2f} mm/h".format(weather_data['precipitation']),
67 "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
68 weather_data['weather'],
69 "{}".format(weather_data['cloudiness'])
73 def write_db(config, url, weather_json, weather_data):
74 user = config.get('database', 'user')
75 pwd = config.get('database','password')
76 host = config.get('database','hostname')
77 db = config.get('database','database')
79 engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
80 conn = engine.connect()
81 row = dict(cityid=config.get('openweathermap', 'cityid'), url=url, result=json.dumps(weather_json))
82 row.update(weather_data)
83 for key, value in row.items():
84 if isinstance(value, float) and math.isnan(value):
86 sql_columns = list(row.keys())
87 sql_values = list(row.values())
88 sql = 'insert into openweathermap ({}) values ({})'.format(', '.join(sql_columns), ','.join(['%s'] * len(sql_columns)))
89 conn.execute(sql, *sql_values)
93 def main(configfile, debug):
94 config = configparser.ConfigParser()
95 config.read(configfile)
96 apikey = config.get('openweathermap', 'apikey')
97 cityid = config.get('openweathermap', 'cityid')
98 csvfile = config.get("openweathermap", 'csvfilename')
100 url, weather_json = openweathermap_json(apikey, cityid)
103 weather_data = extractweatherdata(weather_json)
108 write_db(config, url, weather_json, weather_data)
111 write_csv(os.path.expanduser(csvfile), weather_data)
114 if __name__ == '__main__':
115 default_config_file = os.path.expanduser('~/seewasser.ini')
116 parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
117 parser.add_argument('--config', default=default_config_file, help='configuration file')
118 parser.add_argument('--debug', action='store_true', default=False, help='print debug information')
119 args = parser.parse_args()
120 main(args.config, args.debug)