Merge branch 'web' into owm
authorgregor herrmann <gregor@toastfreeware.priv.at>
Sun, 10 Jun 2018 00:10:23 +0000 (02:10 +0200)
committergregor herrmann <gregor@toastfreeware.priv.at>
Sun, 10 Jun 2018 00:10:23 +0000 (02:10 +0200)
owm.py [new file with mode: 0755]
web/README
web/seepark_web.py
web/static/seepark_web.css
web/templates/seepark_web.html

diff --git a/owm.py b/owm.py
new file mode 100755 (executable)
index 0000000..71f3677
--- /dev/null
+++ b/owm.py
@@ -0,0 +1,107 @@
+#!/usr/bin/python3
+
+# needs ~/seepark.ini with
+# [openweathermap]
+# apikey=...
+# cityid=..
+# 3319578 for Obsteig, AT
+
+from pprint import pprint
+import requests
+import configparser
+import os
+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)
+
+
+def fromtimestamp(timestamp, format):
+    return datetime.datetime.fromtimestamp(timestamp).strftime(format)
+
+
+# https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
+def degToCompass(num):
+    if num is None:
+        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 arr[(val % 16)]
+
+
+def extractweatherdata(w):
+    data = dict(
+        datetime = w.get('dt'),
+        sunrise = w.get('sys').get('sunrise'),
+        sunset = w.get('sys').get('sunset'),
+        temp = w.get('main').get('temp'),
+        pressure = w.get('main').get('pressure'),
+        humidity = w.get('main').get('humidity'),
+        visibility = w.get('visibility'),
+        weather=w['weather'][0]['description'],
+        sky=w['weather'][0]['main'],
+        windspeed=w.get('wind').get('speed'),
+        winddegrees=w.get('wind').get('deg'),
+        cloudiness=w.get('clouds').get('all'),
+        rain=w.get('rain'),
+    )
+
+    data['sunrise_t'] = fromtimestamp(data['sunrise'], '%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['winddirection'] = degToCompass(data['winddegrees'])
+    if not data['rain'] is None:
+        data['precipitation']=data['rain'].get('3h')
+    else:
+        data['precipitation']='N/A'
+
+    return data
+        
+
+def main():
+    config = configparser.ConfigParser()
+    config.read(os.path.expanduser('~/seewasser.ini'))
+    apikey = config.get('openweathermap', 'apikey');
+    cityid = config.get('openweathermap', 'cityid');
+
+    weather_raw = getweather(apikey, cityid)
+    if debug:
+        pprint(weather_raw)
+    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'])
+    )
+
+    
+if __name__ == '__main__':
+    main()
index 7458e9fc52e47cc3f5e367ad3c18390001c84f8d..19ec5859a3f059dfa5c6c2ffeb22386751a9d6d1 100644 (file)
@@ -1,7 +1,7 @@
 Needed package: python3-flask
 
 Start with:
-FLASK_APP=seepark_web.py FLASK_DEBUG=1 flask run
+FLASK_APP=seepark_web.py FLASK_DEBUG=1 SEEPARKINI=~/seewasser.ini flask run
 
 Go to:
 http://127.0.0.1:5000/
index fa08f12480bf96d5a6ace7283fdf1b579efd1b7c..526317407ed5382524d7c8198f62803b5aa12a70 100644 (file)
@@ -1,8 +1,14 @@
 from flask import Flask, render_template, jsonify
 from random import uniform
 import time
+import configparser
+import os
 app = Flask(__name__)
 
+config = configparser.ConfigParser()
+config.read(os.environ['SEEPARKINI'])
+apikey = config.get('openweathermap', 'apikey');
+
 @app.route('/data/', defaults={'timespan': 1})
 @app.route("/data/<int:timespan>", methods=['GET'])
 def data(timespan):
@@ -36,5 +42,5 @@ def data(timespan):
 
 @app.route("/")
 def index():
-    return render_template('seepark_web.html')
+    return render_template('seepark_web.html', apikey=apikey)
 
index 5cf1aadaffaf060caa37fd38d87cf631e95d13bf..6ddd30ab5198fb3eace372412793cb7a78632921 100644 (file)
@@ -21,8 +21,12 @@ button {
     border: 1px solid;
 }
 
-#buttonbar {
+#buttonbar, #openweathermap-widget-15 {
     margin: 0 auto;
     text-align: center;
     padding-top: 1em;
 }
+
+#openweathermap-widget-15 {
+    width: 300px;
+}
index 746e9a5ce5cd8e134e4233d1a78b5537bd827fb3..4d136e3e6dc2bcf538c61ead8c59f8454b7ea328 100644 (file)
                        <button onclick="loaddays(365)">Jahr</button>
                </div>
 
+               <!-- openweathermap widget -->
+               <div id="openweathermap-widget-15"></div>
+               <script>
+               window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = [];
+               window.myWidgetParam.push({
+                       id: 15,
+                       cityid: '3319578',
+                       appid: '{{ apikey }}',
+                       units: 'metric',
+                       containerid: 'openweathermap-widget-15',
+                       lang: 'de',
+               });
+               (function() {
+                       var script = document.createElement('script');
+                       script.async = true;
+                       script.charset = "utf-8";
+                       script.src = "//openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js";
+                       var s = document.getElementsByTagName('script')[0];
+                       s.parentNode.insertBefore(script, s);
+               })();
+               </script>
+
                <!-- Load own javascript code -->
                <script src="{{url_for('static', filename='seepark_web.js')}}"></script>