# -*- coding: utf-8 -*- import os import json import datetime import time import itertools import numpy import bottle import ebus.datastore datastore = ebus.datastore.Datastore("testhdffiles") app = bottle.Bottle("ebus") def maketime(dt): """Rechnet CET DateTime in CET timestamp""" return time.mktime(dt.timetuple())*1000 # - time.altzone)*1000 def parsetime(timestamp): """Macht aus CET timestamp Local DateTime""" return datetime.datetime.fromtimestamp((timestamp/1000)) # + time.altzone) def now(conn): return conn.execute(text("SELECT CURRENT_TIMESTAMP t")).first().t @app.route('/') def index_file(): return static_files("index.html") @app.route('/static/:filename#.+#') def static_files(filename): return bottle.static_file(filename, root=os.path.join(os.path.dirname(__file__),"static")) @app.get('/sensor/:name') def sensor_data_get(name): try: table = datastore.getTable(name) with datastore: data = table.readSorted(sortby="timestamp", checkCSI=True, start=0, stop=1,step=-1).tolist()[0] return {'sensor':name,'error':None,'data':data} except Exception,e: return {'sensor':name,'data':None, 'error':str(e)} @app.put('/sensor/:name') def sensor_data_put(name): try: value = bottle.request.POST.value type = bottle.request.POST.type timestamp = int(time.time()) if type == "int": klass = ebus.datastore.ValueInt elif type == "float": klass = ebus.datastore.ValueFloat elif type == "string": klass = ebus.datastore.ValueString else: return {'error':'INVALID_TYPE', msg:'Type {0} is invalid'.format(type)} datastore.addValue(name, timestamp, value, klass, flush=True) return {'error':None,'msg':"Stored {0} of type {1} with timestamp {2} to {3}".format(value,type,timestamp,name)} except Exception,e: return {'error':e,'msg':e} @app.route('/sensor/:name/:startdate/:enddate') def sensor_name_start_end(name,startdate,enddate): try: startdate, enddate = int(startdate), int(enddate) table=datastore.getTable(name) with datastore: data = [(x['timestamp']*1000, x['value']) for x in table.where("(timestamp >= startdate) & (timestamp <= enddate)")] return {'sensor':name, 'error':None,'data':data} except Exception,e: return {'sensor':name,'data':None, 'error':str(e)} @app.route('/avg/:name/:startdate') def sensor_avg_start(name, startdate): period = 60*15 # 15min try: startdate, enddate = int(startdate), int(time.time()) table=datastore.getTable(name) with datastore: sel_rows = table.where("(timestamp >= startdate) & (timestamp <=enddate)") f_group = range(startdate, enddate, period) data = map(lambda (group_id, grouped_rows): (group_id, numpy.average([row['value'] for row in grouped_rows])), itertools.groupby(sel_rows, lambda t: (t['timestamp']/period)*period)) data = map(lambda (timestamp,value): (timestamp*1000, value), data) return {'sensor':name, 'error':None,'data':data} except Exception,e: return {'sensor':name, 'error':str(e), 'data':None} # vim: autoindent tabstop=4 shiftwidth=4 expandtab softtabstop=4 filetype=python