summaryrefslogtreecommitdiff
path: root/ebus/web/controller.py
blob: edf174d38a4a45bc04a39f85a355e65091f1c076 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time
import itty
from werkzeug.contrib.cache import SimpleCache
from simplejson import dumps as dump_json

from ebus.web import model


def data(name):
    return {"name":name}
"""
def data(name):
    if name in (
            "solarDaten.tempKollektor", 
            "solarDaten.tempWarmwasserSolar",
            "betriebsdatenRegler1.boilerTemperatur",
            "betriebsdatenRegler1.kesselTemperatur",
            "betriebsdatenRegler1.aussenTemperatur",
            "betriebsdatenFeuerungsautomat.brauchwasserSollwert", 
            "betriebsdatenFeuerungsautomat.kesselSollwertTemperatur"):
        m = Code('''
            function () {
                emit(parseInt(this.time/900)*900000, {sum: this.values[field], count:1});
            }''')
        r = Code('''
            function (key, values) {
                var n = { sum:0, count:0 };
                for (var i = 0; i<values.length; i++) {
                    n.sum += values[i].sum;
                    n.count += values[i].count;
                };
                return n;
            }''')
        f = Code('''
            function (who,r) {
                r.avg = r.sum/r.count;
                return r;
            }''')
        q={
            "name":name.split(".")[0],
            "time":{"$gt": ( time.time() - (72*3600))},
        }
        fs=["name", "values.%s"%name.split(".")[1]]
        s={
            "field":name.split(".")[1],
            }
        print "query q=%s fs=%s s=%s" % (q,fs,s)
        collection.ensure_index([('time',pymongo.ASCENDING),('name',pymongo.ASCENDING)])
        data = collection.map_reduce(m,r,query=q,finalize=f,fields=fs,scope=s).find().sort('time',pymongo.ASCENDING)
        return map(lambda it: [it['_id'], it['value']['avg']], data)
    elif name in (
            "betriebsdatenFeuerungsautomat.betriebszustand.reduced",
            "solarDaten.solarPumpe.reduced"):
        pName = name.split(".")[0]
        pField = name.split(".")[1]
        q={
            "name":pName,
            "time":{"$gt":(time.time()-(72*3600))}
        }
        fs=["values.%s"%pField, "time"]
        collection.ensure_index([('time',pymongo.ASCENDING),('name',pymongo.ASCENDING)])
        data=collection.find(q,fields=fs).sort('time', pymongo.ASCENDING)
        #TODO.map(Code('''function(it) { return [it.time, it.values.betriebszustand]; }'''))
        data=map(lambda it: [it['time']*1000, it['values'][pField]], data)

        #Fast die ände auf einen Eintrag pro Änderung zusammen
        def reduce(data):
            prev = None
            for item in data:
                if item[1] != prev:
                    prev = item[1]
                    yield item

        return list(reduce(data))
    else:
        return []
"""

class CacheDecorator(object):
    def __init__(self,key,timeout=20): 
        self.cache = SimpleCache(default_timeout=timeout)
        self.func = None
        self.key = key

    def cachedFunc(self, *args, **kwargs):
        key = self.key(args, kwargs)
        ret = self.cache.get(key)
        if ret is None:
            ret = self.func(*args, **kwargs)
            self.cache.set(key, ret)
        return ret

    def __call__(self, func): 
        self.func = func 
        return self.cachedFunc

@itty.get("/")
def index(req):
    filename=os.path.join(os.path.dirname(__file__), "static", "index.html")
    return open(filename,"r").read()

@itty.get('/json/(?P<name>[^/]+)')
@itty.get('/json/(?P<name>[^/]+)/from_date/(?P<from_date>.+)')
@CacheDecorator(key=lambda args,kwargs: tuple(kwargs.keys()) + tuple(kwargs.values()), 
                timeout=20)
def json(req,name=None,from_date=None):
    print "name=%s from_date=%s" % (name,from_date)
    return itty.Response(dump_json( {"label":name, "data":data(name)} ),
                         content_type="application/json")


@itty.get("/static/(?P<filename>.+)")
def static(request,filename):
    file = itty.static_file(filename, root=os.path.join(os.path.dirname(__file__), 'static'))
    return itty.Response(file, content_type=itty.content_type(file))


def run():
    return itty.run_itty(host="0.0.0.0",port=5000)