funktionsfähige Testimplementierung

*test.py startet den CANFilter, der die Daten vom CAN-BUS in die Datenbank
schreibt. (CAN-msgid = 0x3A4, 2&3 Byte, Multiplikator 0.01)
*API.py startet die API
*Diese kann man unter localhost:5000 erreichen
*der CAN Wert läuft auf "localhost:5000/dc_labor/device/battery/voltage"
auf
This commit is contained in:
Philipp Rauch 2013-11-22 14:25:12 +01:00
parent 59340b5fee
commit cda58b0f2e
7 changed files with 132 additions and 80 deletions

View file

@ -10,10 +10,11 @@ from datetime import datetime
from flask import Flask, jsonify, abort, make_response, request from flask import Flask, jsonify, abort, make_response, request
from socket import gethostname from socket import gethostname
from threading import Thread from threading import Thread
from config import readConf from config import Config
import ems import ems
conf = readConf() c = Config()
conf = c.readConf()
api_host = gethostname() if conf['flask_server'] == '0.0.0.0' else conf['flask_server'] 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']) api_url = 'http://%s:%s' % (api_host, conf['flask_port'])
@ -163,7 +164,7 @@ class API(object):
self.app.add_url_rule('/<path:path>', 'get_catch_all', get_catch_all, methods = ['GET']) self.app.add_url_rule('/<path:path>', 'get_catch_all', get_catch_all, methods = ['GET'])
# def run(self): # def run(self):
self.app.run(host = conf['flask_server'], port = int(conf['flask_port']), debug = True) # self.app.run(host = conf['flask_server'], port = int(conf['flask_port']), debug = True)
buf = Buffer() buf = Buffer()
@ -202,7 +203,8 @@ def start():
api = API() api = API()
api.app.run(host = conf['flask_server'], port = int(conf['flask_port']), debug = conf['flask_debug']) api.app.run(host = conf['flask_server'], port = int(conf['flask_port']), debug = conf['flask_debug'])
emsthread = ems.ems(buf) EMS = ems.ems(buf)
print 'EMS-Thread:\t', emsthread emsthread = EMS.start()
print 'EMS-Thread:\t', EMS
print '\tAPI:\t', buf print '\tAPI:\t', buf
start() start()

View file

@ -13,7 +13,7 @@ from time import sleep
from threading import Thread from threading import Thread
from Queue import Queue from Queue import Queue
from MySQLdb import connect from MySQLdb import connect
from config import readConf from config import Config
debug = False debug = False
@ -21,12 +21,14 @@ class CANFilter(Thread):
battery_current, battery_voltage, battery_capacity, battery_timestamp, test = [], [], [], [], [] #create tmp lists battery_current, battery_voltage, battery_capacity, battery_timestamp, test = [], [], [], [], [] #create tmp lists
conf = readConf() c = Config()
conf = c.readConf()
connection = connect(host = conf['mySQL_server'], connection = connect(host = conf['mySQL_server'],
user = conf['mySQL_user'], user = conf['mySQL_user'],
passwd = conf['mySQL_pass'], passwd = conf['mySQL_pass'],
db = conf['mySQL_database']) db = conf['mySQL_database'],
port = int(conf['mySQL_port']))
cursor = connection.cursor() cursor = connection.cursor()
def __init__(self): def __init__(self):
@ -34,7 +36,7 @@ class CANFilter(Thread):
self.queue = Queue() self.queue = Queue()
self.pcan = PcanAdapter(PcanAdapter.Baudrate['250k']) self.pcan = PcanAdapter(PcanAdapter.Baudrate['250k'], debug = self.conf['config_debug'])
self.pcan.initialize() self.pcan.initialize()
dc_battery = CanMessage(0x3A4, 8, 50, 'dc_battery') dc_battery = CanMessage(0x3A4, 8, 50, 'dc_battery')
@ -74,36 +76,36 @@ class CANFilter(Thread):
self.pcan.Messages['dc_charging'].addSignal( voltage ) self.pcan.Messages['dc_charging'].addSignal( voltage )
def mean(self, l): def mean(self, l):
return float(sum(l))/len(l) if len(l) > 0 else 0 return float(sum(l))/len(l) if len(l) > 0 else 0
def run(self): def run(self):
while True: while True:
receiveMessageId = self.pcan.receiveMessage() receiveMessageId = self.pcan.receiveMessage()
if receiveMessageId == self.pcan.Messages['dc_battery'].Id: if receiveMessageId == self.pcan.Messages['dc_battery'].Id:
self.battery_current.append(self.pcan.Messages['dc_battery'].Signals['current'].GetData()) 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_voltage.append(self.pcan.Messages['dc_battery'].Signals['voltage'].GetData())
self.battery_capacity.append(self.pcan.Messages['dc_battery'].Signals['capacity'].GetData()) self.battery_capacity.append(self.pcan.Messages['dc_battery'].Signals['capacity'].GetData())
self.battery_timestamp.append(datetime.now()) self.battery_timestamp.append(datetime.now())
if len(self.battery_timestamp) == 100: if len(self.battery_timestamp) == 100:
if debug: if debug:
print 'current: ', self.mean(self.battery_current) print 'current: ', self.mean(self.battery_current)
print 'voltage: ', self.mean(self.battery_voltage) print 'voltage: ', self.mean(self.battery_voltage)
print 'SoC: ', self.mean(self.battery_capacity) print 'SoC: ', self.mean(self.battery_capacity)
print 'time: ', self.mean(self.battery_timestamp) print 'time: ', self.mean(self.battery_timestamp)
tabelle = 'battery' tabelle = 'battery'
# daten = [(tabelle, str(self.battery_timestamp[i]), str(self.battery_current[i]), str(self.battery_voltage[i]), str(self.battery_capacity[i])) for i in range(100)] # daten = [(tabelle, str(self.battery_timestamp[i]), str(self.battery_current[i]), str(self.battery_voltage[i]), str(self.battery_capacity[i])) for i in range(100)]
daten = (tabelle, str(self.battery_timestamp[50]), str(self.mean(self.battery_current)), str(self.mean(self.battery_voltage)), str(self.mean(self.battery_capacity))) daten = (tabelle, str(self.battery_timestamp[50]), str(self.mean(self.battery_current)), str(self.mean(self.battery_voltage)), str(self.mean(self.battery_capacity)))
sql = "INSERT INTO %s VALUES (%s,%s,%s,%s)" sql = "INSERT INTO %s VALUES (%s,%s,%s,%s)"
self.queue.put(daten[0]) self.queue.put(daten[0])
# for i in daten: # for i in daten:
# print sql % daten # print sql % daten
self.cursor.execute("INSERT INTO %s VALUES (\'%s\',%s,%s,%s)" % daten) self.cursor.execute("INSERT INTO %s VALUES (\'%s\',%s,%s,%s)" % daten)
#self.cursor.executemany(sql, daten) #self.cursor.executemany(sql, daten)
del self.battery_current[:], self.battery_voltage[:], self.battery_capacity[:], self.battery_timestamp[:] #clear tmp lists del self.battery_current[:], self.battery_voltage[:], self.battery_capacity[:], self.battery_timestamp[:] #clear tmp lists
sleep(0.01) sleep(0.01)

View file

@ -3,43 +3,57 @@ Created on 21.11.2013
@author: rauchp @author: rauchp
''' '''
class Config():
_instance = None
confDic = { _confDic = {
'mySQL_server': 'localhost', 'mySQL_server': 'localhost',
'mySQL_port': '3306', 'mySQL_port': '3306',
'mySQL_user': 'smoke', 'mySQL_user': 'smoke',
'mySQL_pass': 'KiWujcafAlor', 'mySQL_pass': 'KiWujcafAlor',
'mySQL_database': 'smoke_test', 'mySQL_database': 'smoke_test',
'mySQL_table': 'battery', 'mySQL_table': 'battery',
'flask_server': '0.0.0.0', 'flask_server': '0.0.0.0',
'flask_port': '5000', 'flask_port': '5000',
'flask_debug': False, 'flask_debug': False,
} 'config_debug' : False,
'config_read' : False
}
def readConf(): def __new__(cls, *args, **kwargs):
try: # http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
confFile = open("config\ems.conf", "r") if not cls._instance:
error = False cls._instance = super(Config, cls).__new__(
except IOError: cls, *args, **kwargs)
error = True return cls._instance
if error: def readConf(self):
confDic.update({'error' : 'config/ems.conf not found'}) if self._confDic['config_read']:
return confDic return self._confDic
for line in confFile: try:
line = line.strip() confFile = open("config\ems.conf", "r")
if len(line) > 0 and not line[0] == "#": error = False
ident = line.split("=") except IOError:
for i in range(len(ident)): error = True
ident[i] = ident[i].strip()
val = ident[1].split("#") #cut off comments
val[0] = val[0].strip()
val[0] = True if val[0] == 'True' else val[0]
val[0] = False if val[0] == 'False' else val[0]
confDic[ident[0]] = val[0]
confFile.close()
return confDic if error:
self._confDic.update({'error' : 'config/ems.conf not found'})
return self._confDic
print 'config:\t', readConf() for line in confFile:
line = line.strip()
if len(line) > 0 and not line[0] == "#":
ident = line.split("=")
for i in range(len(ident)):
ident[i] = ident[i].strip()
val = ident[1].split("#") #cut off comments
val[0] = val[0].strip()
val[0] = True if val[0] == 'True' else val[0]
val[0] = False if val[0] == 'False' else val[0]
self._confDic[ident[0]] = val[0]
confFile.close()
self._confDic['config_read'] = True
if self._confDic['config_debug']:
print ('config:\t', self._confDic)
return self._confDic

View file

@ -1,14 +1,18 @@
#### DATENBANK #### #### DATENBANK ####
mySQL_server = localhost mySQL_server = localhost
mySQL_port = 3306 # default 3306 mySQL_port = 3306 # default 3306
mySQL_user = smoke mySQL_user = smoke
mySQL_pass = KiWujcafAlor mySQL_pass = KiWujcafAlor
mySQL_database = smoke_test mySQL_database = smoke_test
mySQL_table = battery mySQL_table = battery
#### FLASK #### #### FLASK ####
flask_server = 0.0.0.0 # 0.0.0.0 for public access flask_server = 0.0.0.0 # 0.0.0.0 for public access
flask_port = 5000 flask_port = 5000
flask_debug = False # currently not used flask_debug = True
#### CONFIG ####
config_debug = False

View file

@ -39,7 +39,8 @@ class ems(Thread):
alt = None alt = None
while True: while True:
neu = self.queue.get() neu = self.queue.get()
if not alt == neu: if not alt == neu or True:
self.buffer.device.get['battery'].update({'Voltage' : neu[2]}) # self.buffer.update({'Voltage' : neu[2]})
print neu self.buffer.device.get('battery').update({'voltage' : neu[2]})
# print self.buffer.device.get('battery').get('voltage'), neu[2]
alt = neu alt = neu

View file

@ -9,15 +9,15 @@ from threading import Thread
from Queue import Queue from Queue import Queue
#from CANFilter import CANFilter #from CANFilter import CANFilter
from time import sleep from time import sleep
from config import readConf from config import Config
from MySQLdb import connect from MySQLdb import connect
MYSQL = 0 MYSQL = 0
CSV = 1 CSV = 1
XML = 2 XML = 2
JSON = 3 JSON = 3
c = Config()
conf = readConf() conf = c.readConf()
class Swich(Thread): class Swich(Thread):
@ -29,7 +29,8 @@ class Swich(Thread):
def __del__(self): def __del__(self):
if self.source == MYSQL: if self.source == MYSQL:
self.CAN.join() # self.CAN.join()
pass
def initialisiere(self): def initialisiere(self):
if self.source == MYSQL: if self.source == MYSQL:
@ -44,7 +45,8 @@ class Swich(Thread):
self.connection = connect(host = conf['mySQL_server'], self.connection = connect(host = conf['mySQL_server'],
user = conf['mySQL_user'], user = conf['mySQL_user'],
passwd = conf['mySQL_pass'], passwd = conf['mySQL_pass'],
db = conf['mySQL_database']) db = conf['mySQL_database'],
port = int(conf['mySQL_port']))
self.cursor = self.connection.cursor() self.cursor = self.connection.cursor()
### init Queue ### ### init Queue ###

27
scr/test.py Normal file
View file

@ -0,0 +1,27 @@
'''
Created on 21.11.2013
@author: rauchp
'''
import CANFilter
# import ems
# import time
# from config import Config
#
# c = Config()
# conf = c.readConf()
# buffer={}
# if conf['config_debug']:
# print 'starte CAN'
can = CANFilter.CANFilter()
can.start()
# if conf['config_debug']:
# print 'starte EMS'
# th = ems.ems(buffer)
# th.start()
# if conf['config_debug']:
# print 'alles gestartet'
# while True:
# print buffer
# time.sleep(1)