Add API to view sensors.
[chrisu/seepark.git] / owm.py
diff --git a/owm.py b/owm.py
index b21a61495807f9759a461d4d25ce740a45ac6efd..d42ebed28136758fbee389fd5ae73bba603156cf 100755 (executable)
--- a/owm.py
+++ b/owm.py
@@ -11,7 +11,9 @@ import argparse
 import requests
 import configparser
 import os
+import csv
 import datetime
+import math
 
 baseurl = 'http://api.openweathermap.org/data/2.5/weather'
 debug = False
@@ -65,16 +67,33 @@ def extractweatherdata(w):
     data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
     data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
     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
 
 
+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):
     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')
 
     weather_raw = getweather(apikey, cityid)
     if debug:
@@ -82,22 +101,12 @@ def main(configfile):
     weather = extractweatherdata(weather_raw)
     if debug:
         pprint(weather)
+
     # TODO:
     # write to db
+
     # 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(config.get("openweathermap", 'csvfilename'), weather)
 
 
 if __name__ == '__main__':