]> ToastFreeware Gitweb - chrisu/seepark.git/blobdiff - owm.py
Prepare consolidation of data.
[chrisu/seepark.git] / owm.py
diff --git a/owm.py b/owm.py
index b21a61495807f9759a461d4d25ce740a45ac6efd..c57b2422b24550b012bd415458048e99357f2a6a 100755 (executable)
--- a/owm.py
+++ b/owm.py
@@ -8,27 +8,12 @@
 
 from pprint import pprint
 import argparse
 
 from pprint import pprint
 import argparse
-import requests
 import configparser
 import os
 import configparser
 import os
+import csv
 import datetime
 import datetime
-
-baseurl = 'http://api.openweathermap.org/data/2.5/weather'
-debug = False
-
-def getweather(apikey, cityid):
-    query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
-    try:
-        response = requests.get(query)
-        if response.status_code != 200:
-            response = 'N/A'
-            return response
-        else:
-            weatherdata = response.json()
-            return weatherdata
-    except requests.exceptions.RequestException as error:
-        print (error)
-        sys.exit(1)
+import math
+from seeparklib.openweathermap import openweathermap_json
 
 
 def fromtimestamp(timestamp, format):
 
 
 def fromtimestamp(timestamp, format):
@@ -37,7 +22,7 @@ def fromtimestamp(timestamp, format):
 
 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
 def degToCompass(num):
 
 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
 def degToCompass(num):
-    if num is None:
+    if num is None or num is math.nan:
         return 'N/A'
     val=int((num/22.5)+.5)
     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
         return 'N/A'
     val=int((num/22.5)+.5)
     arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
@@ -56,7 +41,6 @@ def extractweatherdata(w):
         weather = w['weather'][0]['description'],
         sky = w['weather'][0]['main'],
         windspeed = w['wind']['speed'],
         weather = w['weather'][0]['description'],
         sky = w['weather'][0]['main'],
         windspeed = w['wind']['speed'],
-        winddegrees = w['wind']['deg'],
         cloudiness = w['clouds']['all'],
     )
 
         cloudiness = w['clouds']['all'],
     )
 
@@ -64,45 +48,55 @@ def extractweatherdata(w):
     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
     data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
+    data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
     data['winddirection'] = degToCompass(data['winddegrees'])
     data['winddirection'] = degToCompass(data['winddegrees'])
-    data['precipitation'] = w['rain']['3h'] if 'rain' in w else 'N/A'
+    data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
 
     return data
 
 
 
     return data
 
 
-def main(configfile):
+def write_csv(csv_file, weather_data):
+    """output like wetter.at.pl"""
+    with open(csv_file, "a", newline="") as file:
+        writer = csv.writer(file, dialect="excel", delimiter=';')
+        writer.writerow([
+            weather_data['date'],
+            weather_data['time'],
+            weather_data['sunrise_t'],
+            weather_data['sunset_t'],
+            "{:.2f}".format(weather_data['temp']),
+            "{:.2f} mm/h".format(weather_data['precipitation']),
+            "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
+            weather_data['weather'],
+            "{}".format(weather_data['cloudiness'])
+        ])
+
+
+def main(configfile, debug):
     config = configparser.ConfigParser()
     config.read(configfile)
     config = configparser.ConfigParser()
     config.read(configfile)
-    apikey = config.get('openweathermap', 'apikey');
-    cityid = config.get('openweathermap', 'cityid');
+    apikey = config.get('openweathermap', 'apikey')
+    cityid = config.get('openweathermap', 'cityid')
+    csvfile = config.get("openweathermap", 'csvfilename')
 
 
-    weather_raw = getweather(apikey, cityid)
+    weather_raw = openweathermap_json(apikey, cityid)
     if debug:
         pprint(weather_raw)
     weather = extractweatherdata(weather_raw)
     if debug:
         pprint(weather)
     if debug:
         pprint(weather_raw)
     weather = extractweatherdata(weather_raw)
     if debug:
         pprint(weather)
+
     # TODO:
     # write to db
     # TODO:
     # write to db
+
     # write to csv
     # write to csv
-    
-    # output like wetter.at.pl
-    print(
-        weather['date'] + ';' +
-        weather['time'] + ';' +
-        weather['sunrise_t'] + ';' +
-        weather['sunset_t'] + ';' +
-        str(weather['temp']) + ';' +
-        str(weather['precipitation']) + ' mm/h;' +
-        str(weather['windspeed']) + ' km/h ' + weather['winddirection'] + ';' +
-        weather['weather'] + ';' +
-        str(weather['cloudiness'])
-    )
+    write_csv(os.path.expanduser(csvfile), weather)
 
 
 if __name__ == '__main__':
     default_config_file = os.path.expanduser('~/seewasser.ini')
     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
     parser.add_argument('--config', default=default_config_file, help='configuration file')
 
 
 if __name__ == '__main__':
     default_config_file = os.path.expanduser('~/seewasser.ini')
     parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
     parser.add_argument('--config', default=default_config_file, help='configuration file')
+    parser.add_argument('--debug', action='store_true', default=False, help='print debug information')
     args = parser.parse_args()
     args = parser.parse_args()
-    main(args.config)
+    main(args.config, args.debug)