umbau auf profile/database abgeschlossen, lauffähige version
This commit is contained in:
parent
fdd7afd35b
commit
51610ad421
9 changed files with 353 additions and 401 deletions
272
src/API.py
272
src/API.py
|
|
@ -4,12 +4,13 @@ Created on 24.10.2013
|
|||
@author: Philipp Rauch
|
||||
@version: 0.6
|
||||
'''
|
||||
from sys import stderr
|
||||
import datetime
|
||||
from flask import Flask, jsonify, abort, make_response, request
|
||||
from socket import gethostname
|
||||
from config import Config
|
||||
import ems
|
||||
# from sys import stderr
|
||||
from datetime import datetime
|
||||
from flask import Flask, jsonify, make_response, request
|
||||
from socket import gethostname
|
||||
from config import Config
|
||||
from ems import ems
|
||||
from buffer import Buffer
|
||||
|
||||
### LOAD CONFIG ###
|
||||
c = Config()
|
||||
|
|
@ -18,147 +19,14 @@ conf = c.readConf()
|
|||
api_host = gethostname() if conf['flask_server'] == '0.0.0.0' else conf['flask_server']
|
||||
api_url = 'http://%s:%s' % (api_host, conf['flask_port'])
|
||||
|
||||
#### BUFFER ####
|
||||
class Buffer(object):
|
||||
|
||||
error = {
|
||||
'db_error' : {
|
||||
'id' : 1,
|
||||
'content' : None }
|
||||
}
|
||||
|
||||
system = {
|
||||
'00_config' : conf,
|
||||
'0_request' : [],
|
||||
'0_done' : [],
|
||||
'device' : {},
|
||||
'error' : error
|
||||
}
|
||||
|
||||
_instance = None
|
||||
_id = 0
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
# http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
|
||||
if not cls._instance:
|
||||
cls._instance = super(Buffer, cls).__new__(
|
||||
cls, *args, **kwargs)
|
||||
return cls._instance
|
||||
|
||||
def gen_start_url(self, l):
|
||||
'''
|
||||
generate a URL form a list
|
||||
@param l: list of aspacts of the URL
|
||||
@return: URL
|
||||
'''
|
||||
url = api_url
|
||||
for i in l:
|
||||
url = '%s/%s' % (url, i)
|
||||
return url
|
||||
|
||||
def get_level(self, l):
|
||||
'''
|
||||
iterating over a dictionary on a given path
|
||||
@param l: items witch tell the path to the value
|
||||
@return: dictionary with the key and value of the last item in the list
|
||||
'''
|
||||
level = l.pop(0)
|
||||
for i in l:
|
||||
if isinstance(level, dict) and i in level:
|
||||
level = level.get(i)
|
||||
else:
|
||||
abort(404)
|
||||
self.set_href(level, self.gen_start_url(l)) #set all links above
|
||||
return {l[-1] : level}
|
||||
|
||||
def generate_links(self, dic, url, postfix):
|
||||
'''
|
||||
generats a link to dic if dic is a dictionary
|
||||
@param dic: variable that is being tested on a dictionary
|
||||
@param url: previous url
|
||||
@param postfix: appendix to the given url
|
||||
'''
|
||||
if isinstance(dic, dict):
|
||||
if '00_config' in url.split('/'):
|
||||
return
|
||||
url = '%s/%s' % (url, postfix)
|
||||
self.set_href(dic, url)
|
||||
else:
|
||||
return
|
||||
|
||||
def set_href(self, dic, url):
|
||||
'''
|
||||
set the ref link if dic is a dictionary
|
||||
@param dic: variable that is being tested on a dictionary
|
||||
@param url: url to the first dictionary
|
||||
'''
|
||||
if isinstance(dic, dict):
|
||||
for i in dic.keys():
|
||||
self.generate_links(dic.get(i), url, i)
|
||||
dic.update({'000_href': url})
|
||||
dic.update({'000_timestamp' : str(datetime.datetime.now())})
|
||||
|
||||
def foo(self, l, args):
|
||||
'''
|
||||
@param l: list
|
||||
@param args: arguments from the reqest
|
||||
@return: Dictionary
|
||||
'''
|
||||
del l[-1]
|
||||
dic = self.get_level(l).get(l[-1])
|
||||
if isinstance(dic, dict) and 'dyn' in dic:
|
||||
message = 'generating view for %s' % (l[-1])
|
||||
else:
|
||||
abort(404)
|
||||
return { l[-1] : message, 'args' : args.to_dict(flat=False)}
|
||||
|
||||
def update_buffer(self, push):
|
||||
'''
|
||||
Method to update the Buffer on the given path
|
||||
@param push: message to push in the buffer
|
||||
construction: key is the path
|
||||
value is the dict
|
||||
'''
|
||||
|
||||
## Test of valid push message ##
|
||||
if not isinstance(push, dict):
|
||||
stderr.write('error wrong parameter: Type is %s expect dict' %
|
||||
push.__class__.__name__)
|
||||
return
|
||||
if len(push.keys()) not in [1]:
|
||||
stderr.write('error wrong number of arguments: %s expect 1' %
|
||||
len(push.keys()))
|
||||
return
|
||||
if not isinstance(push.get(push.keys()[0]) ,dict):
|
||||
stderr.write('error value is not dict')
|
||||
return
|
||||
|
||||
key = push.keys()[0]
|
||||
value = push[key]
|
||||
path = key.split('/')
|
||||
if path[0] == '':
|
||||
path.remove('')
|
||||
|
||||
sys = self.system
|
||||
for key in path:
|
||||
try:
|
||||
sys = sys[key]
|
||||
except KeyError:
|
||||
stderr.write('error wrong path: %s' % key)
|
||||
return
|
||||
sys.update(value)
|
||||
return key
|
||||
|
||||
def init_buffer(self):
|
||||
self.system['reqest'].append('init')
|
||||
pass
|
||||
#buf = Buffer()
|
||||
|
||||
class Request(object):
|
||||
|
||||
def __init__(self, path, time, id):
|
||||
def __init__(self, path, time, req_id):
|
||||
self.content = path
|
||||
self.time = time
|
||||
self.id = id
|
||||
self.id = req_id
|
||||
|
||||
|
||||
|
||||
|
|
@ -166,88 +34,78 @@ class API(object):
|
|||
|
||||
def __init__(self):
|
||||
self.app = Flask(__name__)
|
||||
self.buf = Buffer()
|
||||
|
||||
### Start EMS thread ###
|
||||
self.EMS = ems.ems(buf)
|
||||
self.EMS = ems(self.buf)
|
||||
self.emsthread = self.EMS.start()
|
||||
|
||||
if conf['config_debug']:
|
||||
print 'EMS-Thread:\t', self.EMS
|
||||
print '\tAPI-BUFFER:\t', buf
|
||||
print '\tAPI-BUFFER:\t', self.buf
|
||||
|
||||
### ADD URL RULES ###
|
||||
self.app.error_handler_spec[None][400] = bad_reqest
|
||||
self.app.error_handler_spec[None][404] = not_found
|
||||
self.app.error_handler_spec[None][405] = not_allowed
|
||||
self.app.error_handler_spec[None][500] = server_error
|
||||
self.app.add_url_rule('/', 'get_root', get_root, methods = ['GET'])
|
||||
self.app.error_handler_spec[None][400] = self.bad_reqest
|
||||
self.app.error_handler_spec[None][404] = self.not_found
|
||||
self.app.error_handler_spec[None][405] = self.not_allowed
|
||||
self.app.error_handler_spec[None][500] = self.server_error
|
||||
self.app.add_url_rule('/', 'get_root', self.get_root, methods = ['GET'])
|
||||
self.app.add_url_rule('/<path:path>', 'get_catch_all',
|
||||
get_catch_all, methods = ['GET'])
|
||||
self.get_catch_all, methods = ['GET'])
|
||||
|
||||
buf = Buffer()
|
||||
########## ERROR Handler ##########
|
||||
def not_allowed(self, error):
|
||||
return make_response(jsonify( { 'error': '405 Not Allowed' } ), 405)
|
||||
|
||||
########## ERROR Handler ##########
|
||||
def not_allowed(error):
|
||||
return make_response(jsonify( { 'error': '405 Not Allowed' } ), 405)
|
||||
def not_found(self, error):
|
||||
return make_response(jsonify( { 'error': '404 Not Found' } ), 404)
|
||||
|
||||
def not_found(error):
|
||||
return make_response(jsonify( { 'error': '404 Not Found' } ), 404)
|
||||
def bad_reqest(self, error):
|
||||
return make_response(jsonify( { 'error': '400 Bad Reqest' } ), 400)
|
||||
|
||||
def bad_reqest(error):
|
||||
return make_response(jsonify( { 'error': '400 Bad Reqest' } ), 400)
|
||||
def server_error(self, error):
|
||||
return make_response(jsonify( { 'error': '500 Internal Server Error' } ), 500)
|
||||
|
||||
def server_error(error):
|
||||
return make_response(jsonify( { 'error': '500 Internal Server Error' } ), 500)
|
||||
########## GET Handler ##########
|
||||
def get_root(self):
|
||||
self.buf.set_href(Buffer.system, api_url)
|
||||
return jsonify( { 'system' : Buffer.system } )
|
||||
|
||||
########## GET Handler ##########
|
||||
def get_root():
|
||||
buf.set_href(Buffer.system, api_url)
|
||||
return jsonify( { 'system' : Buffer.system } )
|
||||
def get_catch_all(self, path):
|
||||
l = path.split('/')
|
||||
l.insert(0, Buffer.system)
|
||||
if '' == l[-1]: # if last element of list is empty
|
||||
del l[-1] # remove it
|
||||
out = self.buf.get_level(l)
|
||||
elif 'dyn' == l[-1]:
|
||||
args = request.args # returns a dictionary with a list of values for each key
|
||||
# each value and each key is represented as a string
|
||||
# to convert it to a dictionary use to_dict(flat=False)
|
||||
# to_dict(flat=True) returns the key and the first item of the value list.
|
||||
out = self.buf.foo(l, args)
|
||||
else:
|
||||
#req = add_reqest(path)
|
||||
|
||||
def get_catch_all(path):
|
||||
l = path.split('/')
|
||||
l.insert(0, Buffer.system)
|
||||
if '' == l[-1]: # if last element of list is empty
|
||||
del l[-1] # remove it
|
||||
out = buf.get_level(l)
|
||||
elif 'dyn' == l[-1]:
|
||||
args = request.args # returns a dictionary with a list of values for each key
|
||||
# each value and each key is represented as a string
|
||||
# to convert it to a dictionary use to_dict(flat=False)
|
||||
# to_dict(flat=True) returns the key and the first item of the value list.
|
||||
out = buf.foo(l, args)
|
||||
else:
|
||||
#req = add_reqest(path)
|
||||
#while req not in Buffer.system['done']:
|
||||
# pass
|
||||
|
||||
#while req not in Buffer.system['done']:
|
||||
# pass
|
||||
#Buffer.system['done'].remove(req)
|
||||
out = self.buf.get_level(l)
|
||||
|
||||
#Buffer.system['done'].remove(req)
|
||||
out = buf.get_level(l)
|
||||
return jsonify( out )
|
||||
|
||||
return jsonify( out )
|
||||
def add_reqest(self, path):
|
||||
notinlist = False
|
||||
time = datetime.now()
|
||||
req_id = Buffer._id
|
||||
tmp = Request(path, time, req_id)
|
||||
try:
|
||||
Buffer.system['request'].index(tmp)
|
||||
except ValueError:
|
||||
notinlist = True
|
||||
|
||||
def add_reqest(path):
|
||||
notinlist = False
|
||||
time = datetime.datetime.now()
|
||||
id = Buffer._id
|
||||
tmp = Request(path, time, id)
|
||||
try:
|
||||
Buffer.system['request'].index(tmp)
|
||||
except ValueError:
|
||||
notinlist = True
|
||||
|
||||
if notinlist:
|
||||
Buffer.system['request'].insert(0, tmp)
|
||||
return id
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def API_start():
|
||||
api = API()
|
||||
api.app.run(host = conf['flask_server'],
|
||||
port = int(conf['flask_port']))
|
||||
#debug = conf['flask_debug']
|
||||
API_start()
|
||||
if notinlist:
|
||||
Buffer.system['request'].insert(0, tmp)
|
||||
return id
|
||||
else:
|
||||
return False
|
||||
|
|
|
|||
101
src/CANFilter.py
101
src/CANFilter.py
|
|
@ -1,50 +1,62 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf8 -*-
|
||||
'''
|
||||
Created on 13.11.2013
|
||||
|
||||
@author: Philipp Rauch
|
||||
@version: 0.1
|
||||
'''
|
||||
from CanMessage import CanMessage
|
||||
from CanSignal import CanSignal
|
||||
from PCan import PcanAdapter
|
||||
from Sym2Lib import Add2Adapter, Sym2Code
|
||||
from datetime import datetime
|
||||
from time import sleep
|
||||
from threading import Thread
|
||||
from Queue import Queue
|
||||
from config import Config
|
||||
import database
|
||||
from PCan import PcanAdapter
|
||||
from Sym2Lib import Add2Adapter, get_DataFrameDict
|
||||
from datetime import datetime
|
||||
from time import sleep
|
||||
from threading import Thread
|
||||
from Queue import Queue
|
||||
from config import Config
|
||||
from pandas import DataFrame
|
||||
from profile.database import Database
|
||||
|
||||
debug = True
|
||||
|
||||
class CANFilter(Thread):
|
||||
|
||||
battery_current, battery_voltage = [], []
|
||||
battery_soc, battery_timestamp = [], [] #create tmp lists
|
||||
|
||||
### LOAD CONFIG ###
|
||||
c = Config()
|
||||
conf = c.readConf()
|
||||
|
||||
cursor = database.setup(conf)
|
||||
### Lookup f<>r CAN --> DB ###
|
||||
lookup = {
|
||||
'dc_battery' : 'battery'
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
Thread.__init__(self)
|
||||
|
||||
self.queue = Queue()
|
||||
|
||||
### init DB ###
|
||||
self.db = Database()
|
||||
self.db.loadDatabase(strHost = self.conf['mySQL_server'],
|
||||
intPort = int(self.conf['mySQL_port']),
|
||||
strUser = self.conf['mySQL_user'],
|
||||
strPasswd = self.conf['mySQL_pass'],
|
||||
strDatabase = self.conf['mySQL_database'],
|
||||
strTable = None)
|
||||
|
||||
self.symList = []
|
||||
|
||||
### init PCAN ###
|
||||
self.pcan = PcanAdapter(PcanAdapter.Baudrate[self.conf['can_baudrate']],
|
||||
debug = self.conf['config_debug'])
|
||||
self.pcan.initialize()
|
||||
|
||||
if isinstance(self.conf["symfile"], str):
|
||||
sym = "%s/%s" % (self.conf["config_dictionary"], self.conf["symfile"])
|
||||
Sym2Code(sym)
|
||||
sym = "%s/%s" % (self.conf["config_dictionary"],
|
||||
self.conf["symfile"])
|
||||
self.symList.append(get_DataFrameDict(sym))
|
||||
Add2Adapter(self.pcan, sym)
|
||||
elif isinstance(self.conf["symfile"], list):
|
||||
for element in self.conf["symfile"]:
|
||||
sym = "%s/%s" % (self.conf["config_dictionary"], element)
|
||||
#Sym2Code(sym)
|
||||
self.symList.append(get_DataFrameDict(sym))
|
||||
Add2Adapter(self.pcan, sym)
|
||||
|
||||
def mean(self, l):
|
||||
|
|
@ -52,45 +64,24 @@ class CANFilter(Thread):
|
|||
|
||||
def run(self):
|
||||
while True:
|
||||
receiveMessageId = self.pcan.receiveMessage()
|
||||
receiveMessageName = self.pcan.receiveMessage()
|
||||
|
||||
if receiveMessageId == self.pcan.Messages['dc_battery'].Id:
|
||||
for sym in self.symList:
|
||||
if receiveMessageName in sym.keys():
|
||||
tmp = {}
|
||||
for sig in list(sym[receiveMessageName].columns):
|
||||
tmp[sig] = self.pcan.Messages[receiveMessageName].Signals[sig].GetData()
|
||||
sym[receiveMessageName] = sym[receiveMessageName].append(tmp, ignore_index=True)
|
||||
|
||||
self.battery_current.append(
|
||||
self.pcan.Messages['dc_battery'].Signals['current'].GetData())
|
||||
self.battery_voltage.append(
|
||||
self.pcan.Messages['dc_battery'].Signals['voltage'].GetData())
|
||||
self.battery_soc.append(
|
||||
self.pcan.Messages['dc_battery'].Signals['soc'].GetData())
|
||||
self.battery_timestamp.append(datetime.now())
|
||||
if len(sym[receiveMessageName].index) == 100:
|
||||
res = DataFrame(sym[receiveMessageName].mean(axis=0)).T
|
||||
|
||||
if len(self.battery_timestamp) == 100:
|
||||
if debug:
|
||||
print 'current: ', self.mean(self.battery_current)
|
||||
print 'voltage: ', self.mean(self.battery_voltage)
|
||||
print 'SoC: ', self.mean(self.battery_soc)
|
||||
print 'time: ', self.battery_timestamp[50]
|
||||
res.drop('isMaster', axis = 1, inplace = True)
|
||||
res.drop('isCharging', axis = 1, inplace = True)
|
||||
res['DateTime'] = datetime.now()
|
||||
|
||||
tabelle = 'battery'
|
||||
self.db.writeDatabase(self.lookup[receiveMessageName], res)
|
||||
sym[receiveMessageName] = sym[receiveMessageName].drop(sym[receiveMessageName].index[:])
|
||||
#print res
|
||||
|
||||
list_daten = [(tabelle, str(self.battery_timestamp[i]),
|
||||
str(self.battery_voltage[i]),
|
||||
str(self.battery_current[i]),
|
||||
str(self.battery_soc[i])) for i in range(100)]
|
||||
|
||||
mean_daten = (tabelle, str(self.battery_timestamp[50]),
|
||||
str(self.mean(self.battery_voltage)),
|
||||
str(self.mean(self.battery_current)),
|
||||
str(self.mean(self.battery_soc)))
|
||||
|
||||
sql = "INSERT INTO %s VALUES (\'%s\',%s,%s,%s)"
|
||||
|
||||
self.queue.put(mean_daten[0])
|
||||
|
||||
self.cursor.execute(sql % mean_daten)
|
||||
#self.cursor.executemany(sql, daten)
|
||||
|
||||
## clear tmp lists ##
|
||||
del self.battery_current[:], self.battery_voltage[:],
|
||||
del self.battery_soc[:], self.battery_timestamp[:]
|
||||
sleep(0.01)
|
||||
|
|
|
|||
170
src/buffer.py
Normal file
170
src/buffer.py
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
'''
|
||||
Created on 29.01.2014
|
||||
|
||||
@author: rauchp
|
||||
'''
|
||||
from sys import stderr
|
||||
from socket import gethostname
|
||||
from config import Config
|
||||
from datetime import datetime
|
||||
from flask import abort
|
||||
|
||||
### jason test ###
|
||||
from numpy import timedelta64, float64, int64
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from math import isnan
|
||||
|
||||
### LOAD CONFIG ###
|
||||
c = Config()
|
||||
conf = c.readConf()
|
||||
|
||||
api_host = gethostname() if conf['flask_server'] == '0.0.0.0' else conf['flask_server']
|
||||
api_url = 'http://%s:%s' % (api_host, conf['flask_port'])
|
||||
|
||||
class Buffer(object):
|
||||
|
||||
error = {
|
||||
'db_error' : {}
|
||||
}
|
||||
|
||||
system = {
|
||||
'00_config' : conf,
|
||||
'0_request' : [],
|
||||
'0_done' : [],
|
||||
'device' : {},
|
||||
'error' : error
|
||||
}
|
||||
|
||||
_instance = None
|
||||
_id = 0
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
# http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
|
||||
if not cls._instance:
|
||||
cls._instance = super(Buffer, cls).__new__(
|
||||
cls, *args, **kwargs)
|
||||
return cls._instance
|
||||
|
||||
def gen_start_url(self, l):
|
||||
'''
|
||||
generate a URL form a list
|
||||
@param l: list of aspacts of the URL
|
||||
@return: URL
|
||||
'''
|
||||
url = api_url
|
||||
for i in l:
|
||||
url = '%s/%s' % (url, i)
|
||||
return url
|
||||
|
||||
def get_level(self, l):
|
||||
'''
|
||||
iterating over a dictionary on a given path
|
||||
@param l: items witch tell the path to the value
|
||||
@return: dictionary with the key and value of the last item in the list
|
||||
'''
|
||||
level = l.pop(0)
|
||||
for i in l:
|
||||
if isinstance(level, dict) and i in level:
|
||||
level = level.get(i)
|
||||
else:
|
||||
abort(404)
|
||||
self.set_href(level, self.gen_start_url(l)) #set all links above
|
||||
return {l[-1] : level}
|
||||
|
||||
def generate_links(self, dic, url, postfix):
|
||||
'''
|
||||
generats a link to dic if dic is a dictionary
|
||||
@param dic: variable that is being tested on a dictionary
|
||||
@param url: previous url
|
||||
@param postfix: appendix to the given url
|
||||
'''
|
||||
if isinstance(dic, dict):
|
||||
if '00_config' in url.split('/'):
|
||||
return
|
||||
url = '%s/%s' % (url, postfix)
|
||||
self.set_href(dic, url)
|
||||
else:
|
||||
return
|
||||
|
||||
def set_href(self, dic, url):
|
||||
'''
|
||||
set the ref link if dic is a dictionary
|
||||
@param dic: variable that is being tested on a dictionary
|
||||
@param url: url to the first dictionary
|
||||
'''
|
||||
if isinstance(dic, dict):
|
||||
for i in dic.keys():
|
||||
self.generate_links(dic.get(i), url, i)
|
||||
dic.update({'000_href': url})
|
||||
dic.update({'000_timestamp' : str(datetime.now())})
|
||||
|
||||
def foo(self, l, args):
|
||||
'''
|
||||
@param l: list
|
||||
@param args: arguments from the reqest
|
||||
@return: Dictionary
|
||||
'''
|
||||
del l[-1]
|
||||
dic = self.get_level(l).get(l[-1])
|
||||
if isinstance(dic, dict) and 'dyn' in dic:
|
||||
message = 'generating view for %s' % (l[-1])
|
||||
else:
|
||||
abort(404)
|
||||
return { l[-1] : message, 'args' : args.to_dict(flat=False)}
|
||||
|
||||
def value_to_json(self, value): #timedelta64, float64, int64
|
||||
if isinstance(value, date) or isinstance(value, timedelta64):
|
||||
return str(value)
|
||||
elif isinstance(value, Decimal) or isinstance(value, float64):
|
||||
return float(value)
|
||||
elif isinstance(value, int64):
|
||||
return int(value)
|
||||
elif isinstance(value, float) and isnan(value):
|
||||
return None
|
||||
else:
|
||||
return value
|
||||
|
||||
def update_buffer(self, push):
|
||||
'''
|
||||
Method to update the Buffer on the given path
|
||||
@param push: message to push in the buffer
|
||||
construction: key is the path
|
||||
value is the dict
|
||||
'''
|
||||
|
||||
## Test of valid push message ##
|
||||
if not isinstance(push, dict):
|
||||
stderr.write('error wrong parameter: Type is %s expect dict' %
|
||||
push.__class__.__name__)
|
||||
return
|
||||
if len(push.keys()) not in [1]:
|
||||
stderr.write('error wrong number of arguments: %s expect 1' %
|
||||
len(push.keys()))
|
||||
return
|
||||
if not isinstance(push.get(push.keys()[0]) ,dict):
|
||||
stderr.write('error value is not dict')
|
||||
return
|
||||
|
||||
key = push.keys()[0]
|
||||
value = push[key]
|
||||
path = key.split('/')
|
||||
if path[0] == '':
|
||||
path.remove('')
|
||||
|
||||
sys = self.system
|
||||
for k in path:
|
||||
try:
|
||||
sys = sys[k]
|
||||
except KeyError:
|
||||
stderr.write('error wrong path: %s' % k)
|
||||
return
|
||||
for k in value:
|
||||
value[k] = self.value_to_json(value[k])
|
||||
|
||||
sys.update(value)
|
||||
return key
|
||||
|
||||
def init_buffer(self):
|
||||
self.system['reqest'].append('init')
|
||||
pass
|
||||
|
|
@ -4,7 +4,7 @@ mySQL_port = 3306 # default 3306
|
|||
mySQL_user = stud_EMS
|
||||
mySQL_pass = sql13
|
||||
mySQL_database = photodb
|
||||
mySQL_speed = 0.1 # time between two query's in sec
|
||||
mySQL_speed = 0.05 # time between two query's in sec
|
||||
|
||||
#### FLASK ####
|
||||
flask_server = 0.0.0.0 # 0.0.0.0 for public access
|
||||
|
|
@ -15,7 +15,6 @@ flask_debug = True
|
|||
config_debug = True
|
||||
|
||||
#### CAN ####
|
||||
#possible Baud Rates: 100k, 125k, 250k, 500k, 1000k
|
||||
can_baudrate = 250k
|
||||
|
||||
symfile = ems-test.sym
|
||||
## possible Baud Rates: 100k, 125k, 250k, 500k, 1000k ##
|
||||
can_baudrate = 250k
|
||||
symfile = ems-test.sym
|
||||
|
|
|
|||
40
src/ems.py
40
src/ems.py
|
|
@ -4,8 +4,7 @@ Created on 15.11.2013
|
|||
@author: Philipp Rauch
|
||||
@version: 0.02
|
||||
'''
|
||||
from threading import Thread, Timer
|
||||
import thread
|
||||
from threading import Thread
|
||||
from switch import Switch, MYSQL
|
||||
from config import Config
|
||||
from time import sleep
|
||||
|
|
@ -28,29 +27,14 @@ def startSwitch():
|
|||
return switch, queue, query
|
||||
|
||||
def update_device(query, queue, buf):
|
||||
#query.put('/device')
|
||||
#buf.update_buffer(queue.get())
|
||||
keys = buf.system['device'].keys()
|
||||
for key in keys:
|
||||
if key.startswith("000"):
|
||||
continue
|
||||
query.put('/device/%s' % key)
|
||||
print 'GET:\t', buf.update_buffer(queue.get())
|
||||
sleep(0.5)
|
||||
|
||||
class Emulator(object):
|
||||
def __init__(self, func):
|
||||
self._func = func()
|
||||
|
||||
def run(self, time):
|
||||
self._func()
|
||||
self.threadTimer = Timer(time, self.run(time))
|
||||
self.threadTimer.start()
|
||||
|
||||
def stop(self):
|
||||
self.threadTimer.cancel()
|
||||
sleep(1)
|
||||
print(self.threadTimer.isAlive())
|
||||
get = buf.update_buffer(queue.get())
|
||||
#print 'GET:\t', get
|
||||
#sleep(0.1)
|
||||
|
||||
class ems(Thread):
|
||||
def __init__(self, buf):
|
||||
|
|
@ -59,11 +43,10 @@ class ems(Thread):
|
|||
self.switch, self.queue, self.query = startSwitch()
|
||||
if conf['config_debug']:
|
||||
print '\tEMS-BUFFER:\t', buf
|
||||
#self.update = Emulator(update_device(self.query, self.queue, self.buffer))
|
||||
#self.update.run(conf['mySQL_speed'])
|
||||
|
||||
self.query.put('/device')
|
||||
self.buffer.update_buffer(self.queue.get())
|
||||
update_device(self.query, self.queue, self.buffer)
|
||||
get = self.buffer.update_buffer(self.queue.get())
|
||||
#print 'GET:\t', get
|
||||
|
||||
def __del__(self):
|
||||
self.update.stop()
|
||||
|
|
@ -71,16 +54,7 @@ class ems(Thread):
|
|||
|
||||
def run(self):
|
||||
while True:
|
||||
# if self.getRequest():
|
||||
update_device(self.query, self.queue, self.buffer)
|
||||
#old = None
|
||||
#while True:
|
||||
# new = self.getNewMsg(old)
|
||||
# if conf['config_debug']:
|
||||
# print 'GET:\t', new
|
||||
# self.buffer.update_buffer(new)
|
||||
# self.queue.task_done()
|
||||
# old = new
|
||||
|
||||
def getNewMsg(self, old):
|
||||
'''
|
||||
|
|
|
|||
|
|
@ -3,67 +3,30 @@ Created on 26.11.2013
|
|||
|
||||
@author: Philipp Rauch
|
||||
'''
|
||||
from MySQLdb import connect
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
from profile.database import Database
|
||||
|
||||
tables = {}
|
||||
|
||||
def get_tables(cur, db):
|
||||
sql_tables = 'SHOW TABLES FROM %s'
|
||||
tables = []
|
||||
cur.execute(sql_tables % db)
|
||||
|
||||
#TODO try - except
|
||||
for i in cur:
|
||||
tables.append(i[0])
|
||||
return tables
|
||||
|
||||
|
||||
def get_prime(cur, tabele):
|
||||
sql_get_prim = "SHOW COLUMNS FROM %s WHERE `Key` = 'PRI'"
|
||||
sql_get_no_prim = "SHOW COLUMNS FROM %s WHERE `Key` != 'PRI'"
|
||||
collum = []
|
||||
cur.execute(sql_get_prim % tabele)
|
||||
|
||||
#TODO try - except
|
||||
for i in cur:
|
||||
collum.append(i[0])
|
||||
|
||||
cur.execute(sql_get_no_prim % tabele)
|
||||
for i in cur:
|
||||
collum.append(i[0])
|
||||
|
||||
return collum
|
||||
_sort_lookup = { 'EA_Last' : 'DateTime' }
|
||||
|
||||
def setup(conf):
|
||||
'''
|
||||
establishes a connection to the database and returns a cursor
|
||||
establishes a connection to the database and returns a Database object
|
||||
|
||||
@return: cursor to the database
|
||||
'''
|
||||
connection = connect(host = conf['mySQL_server'],
|
||||
user = conf['mySQL_user'],
|
||||
passwd = conf['mySQL_pass'],
|
||||
db = conf['mySQL_database'],
|
||||
port = int(conf['mySQL_port']))
|
||||
cursor = connection.cursor()
|
||||
|
||||
tab = get_tables(cursor, conf['mySQL_database'])
|
||||
for i in tab:
|
||||
primes = get_prime(cursor, i)
|
||||
tables[i] = primes
|
||||
print tables
|
||||
|
||||
return cursor
|
||||
|
||||
def loop(cursor, item):
|
||||
@return: Database object
|
||||
'''
|
||||
|
||||
db = Database()
|
||||
db.loadDatabase(strHost = conf['mySQL_server'],
|
||||
intPort = int(conf['mySQL_port']),
|
||||
strUser = conf['mySQL_user'],
|
||||
strPasswd = conf['mySQL_pass'],
|
||||
strDatabase = conf['mySQL_database'],
|
||||
strTable = None)
|
||||
return db
|
||||
|
||||
def loop(db, item):
|
||||
'''
|
||||
sql_values = 'SELECT * FROM %s ORDER BY %s DESC LIMIT 0, 1'
|
||||
'''
|
||||
sql_values = 'SELECT * FROM %s ORDER BY %s DESC LIMIT 1'
|
||||
|
||||
path = item.split('/')
|
||||
if path[0] == '':
|
||||
path.remove('')
|
||||
|
|
@ -71,34 +34,25 @@ def loop(cursor, item):
|
|||
table = path[len(path) -1]
|
||||
if table == 'device':
|
||||
tmp = { table : {} }
|
||||
for i in tables.keys():
|
||||
for i in db.getInformation()['Table'].keys():
|
||||
tmp[table][i] = {}
|
||||
return tmp
|
||||
|
||||
try:
|
||||
sort = db.getInformation()['Table_Prime'][table][0]
|
||||
except:
|
||||
try:
|
||||
sort = _sort_lookup[table]
|
||||
except:
|
||||
return { 'error/db_error' : { table : 'no Prime-Key / Sort defined' } }
|
||||
|
||||
cursor.execute(sql_values % (table, tables[table][0]))
|
||||
values = []
|
||||
for row in cursor:
|
||||
values = row
|
||||
res = db.readDatabase(intRowOffset=0, intRowNumber=1, strTable=table, strSort=sort, invertSort=True)
|
||||
result = res.to_dict()
|
||||
|
||||
result = {}
|
||||
for k in result:
|
||||
result[k] = result[k][0]
|
||||
|
||||
for i in range(0, len(tables[table])):
|
||||
if values == []:
|
||||
result[tables[table][i]] = None
|
||||
else:
|
||||
if isinstance(values[i], date) or isinstance(values[i], timedelta):
|
||||
result[tables[table][i]] = str(values[i])
|
||||
elif isinstance(values[i], Decimal):
|
||||
result[tables[table][i]] = float(values[i])
|
||||
else:
|
||||
result[tables[table][i]] = values[i]
|
||||
|
||||
# for p in range(len(path)):
|
||||
# result = { path.pop() : result }
|
||||
result = {item : result}
|
||||
|
||||
return result
|
||||
return {item : result}
|
||||
|
||||
def close(cursor):
|
||||
pass
|
||||
|
|
|
|||
25
src/run.py
Normal file
25
src/run.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
'''
|
||||
Created on 29.01.2014
|
||||
|
||||
@author: Philipp Rauch
|
||||
'''
|
||||
from config import Config
|
||||
from API import API
|
||||
from CANFilter import CANFilter
|
||||
|
||||
### LOAD CONFIG ###
|
||||
c = Config()
|
||||
conf = c.readConf()
|
||||
|
||||
### start CAN to DB ###
|
||||
print 'starte CAN mit Baud von', conf['can_baudrate']
|
||||
can = CANFilter()
|
||||
can.start()
|
||||
|
||||
### API-Service ###
|
||||
def API_start():
|
||||
api = API()
|
||||
api.app.run(host = conf['flask_server'],
|
||||
port = int(conf['flask_port']))
|
||||
#debug = conf['flask_debug']
|
||||
API_start()
|
||||
|
|
@ -67,7 +67,6 @@ class Switch(Thread):
|
|||
|
||||
item = self.getItem(block = True)
|
||||
|
||||
#item = 'device'
|
||||
if self.source == MYSQL:
|
||||
result = database.loop(self.cursor, item)
|
||||
elif self.source == MODBUS:
|
||||
|
|
|
|||
34
src/test.py
34
src/test.py
|
|
@ -3,37 +3,19 @@ Created on 21.11.2013
|
|||
|
||||
@author: Philipp Rauch
|
||||
'''
|
||||
import CANFilter
|
||||
#import ems
|
||||
#import time
|
||||
#import switch
|
||||
# import CANFilter
|
||||
# import Sym2Lib
|
||||
from config import Config
|
||||
|
||||
### LOAD CONFIG ###
|
||||
c = Config()
|
||||
conf = c.readConf()
|
||||
|
||||
### Sym2Lib test ###
|
||||
# sym = "%s/%s" % (conf["config_dictionary"], conf["symfile"])
|
||||
# print Sym2Lib.get_DataFrameDict(sym)
|
||||
|
||||
### CAN test ###
|
||||
print 'starte CAN mit Baud von', conf['can_baudrate']
|
||||
can = CANFilter.CANFilter()
|
||||
can.start()
|
||||
|
||||
### EMS test ###9
|
||||
|
||||
# buffer = {}
|
||||
# print 'starte EMS'
|
||||
# th = ems.ems(buffer)
|
||||
# th.start()
|
||||
# while True:
|
||||
# print buffer
|
||||
# sleep(0.1)
|
||||
|
||||
### Switch test ###
|
||||
# sw = switch.Switch(switch.MYSQL)
|
||||
# queue = sw.initialisiere()
|
||||
# sw.start()
|
||||
# print '\tTEST:\t', queue
|
||||
#
|
||||
# while True:
|
||||
# print 'GET:\t%s' % queue.get()
|
||||
# print 'starte CAN mit Baud von', conf['can_baudrate']
|
||||
# can = CANFilter.CANFilter()
|
||||
# can.start()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue