Module laufen als Thread
*Thread für swich implementiert *Thread für API implementiert (noch nicht lauffähig) *Swich startet CANFilter
This commit is contained in:
parent
704e02385f
commit
f0686090ec
5 changed files with 120 additions and 107 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -28,6 +28,7 @@ cache.dat
|
|||
*.out
|
||||
*.synctex.gz
|
||||
*.toc
|
||||
*.pyc
|
||||
.project
|
||||
.pydevproject
|
||||
tmp?.dat
|
||||
|
|
|
|||
105
scr/API.py
105
scr/API.py
|
|
@ -2,17 +2,17 @@
|
|||
Created on 24.10.2013
|
||||
|
||||
@author: Philipp Rauch
|
||||
@version: 0.5
|
||||
@version: 0.6
|
||||
'''
|
||||
|
||||
from flask import Flask, jsonify, abort, make_response, request
|
||||
from time import time
|
||||
import socket
|
||||
from time import time
|
||||
from flask import Flask, jsonify, abort, make_response, request
|
||||
from socket import gethostname
|
||||
from threading import Thread
|
||||
|
||||
app = Flask(__name__)
|
||||
app_host = '0.0.0.0' #api_host='0.0.0.0' for public access
|
||||
app_port = '5000'
|
||||
api_host = socket.gethostname() if app_host == '0.0.0.0' else app_host
|
||||
api_host = gethostname() if app_host == '0.0.0.0' else app_host
|
||||
api_url = 'http://%s:%s' % (api_host, app_port)
|
||||
|
||||
#### BUFFER ####
|
||||
|
|
@ -58,22 +58,19 @@ class Buffer(object):
|
|||
}
|
||||
|
||||
system = {
|
||||
'dc_labor' : dc_labor,
|
||||
'dc_grid' : dc_grid,
|
||||
'dc_labor' : dc_labor,
|
||||
'dc_grid' : dc_grid,
|
||||
'ac_grid' : ac_grid
|
||||
}
|
||||
|
||||
isInitialised = False
|
||||
|
||||
def __init__(self):
|
||||
self.isInitialised = True
|
||||
|
||||
def get_instance(self):
|
||||
if self.isInitialised:
|
||||
return self
|
||||
else:
|
||||
return Buffer().__init__()
|
||||
_instance = None
|
||||
|
||||
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):
|
||||
'''
|
||||
|
|
@ -90,7 +87,7 @@ class Buffer(object):
|
|||
'''
|
||||
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
|
||||
@return: dictionary with the key and value of the last item in the list
|
||||
'''
|
||||
level = l.pop(0)
|
||||
for i in l:
|
||||
|
|
@ -148,28 +145,40 @@ class Buffer(object):
|
|||
#ToDo
|
||||
None
|
||||
|
||||
buf = Buffer().get_instance()
|
||||
class API(Thread):
|
||||
|
||||
def __init__(self):
|
||||
Thread.__init__(self)
|
||||
self.app = Flask(__name__)
|
||||
|
||||
### 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.add_url_rule('/', 'get_root', get_root, methods = ['GET'])
|
||||
self.app.add_url_rule('/<path:path>', 'get_catch_all', get_catch_all, methods = ['GET'])
|
||||
|
||||
def run(self):
|
||||
self.app.run(host = app_host, port = int(app_port), debug = True)
|
||||
|
||||
buf = Buffer()
|
||||
print 'API:\t', buf
|
||||
|
||||
########## ERROR Handler ##########
|
||||
@app.errorhandler(405)
|
||||
def not_allowed(error):
|
||||
return make_response(jsonify( { 'error': '405 Not Allowed' } ), 405)
|
||||
|
||||
@app.errorhandler(404)
|
||||
def not_found(error):
|
||||
return make_response(jsonify( { 'error': '404 Not Found' } ), 404)
|
||||
|
||||
@app.errorhandler(400)
|
||||
def bad_reqest(error):
|
||||
return make_response(jsonify( { 'error': '400 Bad Reqest' } ), 400)
|
||||
|
||||
########## GET Handler ##########
|
||||
@app.route('/', methods = ['GET'])
|
||||
def get_root():
|
||||
buf.set_href(Buffer.system, api_url)
|
||||
return jsonify( { 'system' : Buffer.system } )
|
||||
|
||||
@app.route('/<path:path>', methods = ['GET'])
|
||||
def get_catch_all(path):
|
||||
l = path.split('/')
|
||||
l.insert(0, Buffer.system)
|
||||
|
|
@ -185,49 +194,3 @@ def get_catch_all(path):
|
|||
else:
|
||||
out = buf.get_level(l)
|
||||
return jsonify( out )
|
||||
|
||||
######### POST Handler ##########
|
||||
#@app.route('/db', methods = ['POST'])
|
||||
#def create_item():
|
||||
# if not request.json or not 'title' in request.json:
|
||||
# abort(400)
|
||||
# item = {
|
||||
# 'id': db[-1]['id'] + 1,
|
||||
# 'title': request.json['title'],
|
||||
# 'description': request.json.get('description', ""),
|
||||
# 'done': False
|
||||
# }
|
||||
# db.append(item)
|
||||
# return jsonify( { 'item': item } ), 201
|
||||
|
||||
########## PUT Handler ##########
|
||||
#@app.route('/db/<int:item_id>', methods = ['PUT'])
|
||||
#def update_item(item_id):
|
||||
# item = filter(lambda t: t['id'] == item_id, db)
|
||||
# if len(item) == 0:
|
||||
# abort(404)
|
||||
# if not request.json:
|
||||
# abort(400)
|
||||
# if 'title' in request.json and type(request.json['title']) != unicode:
|
||||
# abort(400)
|
||||
# if 'description' in request.json and type(request.json['description']) is not unicode:
|
||||
# abort(400)
|
||||
# if 'done' in request.json and type(request.json['done']) is not bool:
|
||||
# abort(400)
|
||||
# item[0]['title'] = request.json.get('title', item[0]['title'])
|
||||
# item[0]['description'] = request.json.get('description', item[0]['description'])
|
||||
# item[0]['done'] = request.json.get('done', item[0]['done'])
|
||||
# return jsonify( { 'item': item[0] } ), 201
|
||||
|
||||
########## DELET Handler ##########
|
||||
#@app.route('/db/<int:item_id>', methods = ['DELETE'])
|
||||
#def delete_item(item_id):
|
||||
# item = filter(lambda t: t['id'] == item_id, db)
|
||||
# if len(item) == 0:
|
||||
# abort(404)
|
||||
# db.remove(item[0])
|
||||
# return jsonify( { 'result': True } )
|
||||
|
||||
########## RUN ##########
|
||||
if __name__ == '__main__':
|
||||
app.run(host = app_host, port = int(app_port), debug = True)
|
||||
|
|
@ -2,26 +2,28 @@
|
|||
Created on 13.11.2013
|
||||
|
||||
@author: Philipp Rauch
|
||||
@version: 0.02
|
||||
@version: 0.1
|
||||
'''
|
||||
|
||||
from CanMessage import CanMessage
|
||||
from CanSignal import CanSignal
|
||||
from PCan import PcanAdapter
|
||||
import datetime
|
||||
import time
|
||||
import threading
|
||||
#import MySQLdb
|
||||
from CanSignal import CanSignal
|
||||
from PCan import PcanAdapter
|
||||
from datetime import datetime
|
||||
from time import sleep
|
||||
from threading import Thread
|
||||
from Queue import Queue
|
||||
#from MySQLdb import connect
|
||||
|
||||
debug = False
|
||||
|
||||
class CANFilter(threading.Thread):
|
||||
class CANFilter(Thread):
|
||||
|
||||
battery_current, battery_voltage, battery_capacity, battery_timestamp, test = [], [], [], [], []
|
||||
battery_current, battery_voltage, battery_capacity, battery_timestamp, test = [], [], [], [], [] #create tmp lists
|
||||
|
||||
def __init__(self):
|
||||
print "INIT"
|
||||
threading.Thread.__init__(self)
|
||||
Thread.__init__(self)
|
||||
|
||||
self.queue = Queue()
|
||||
|
||||
self.pcan = PcanAdapter(PcanAdapter.Baudrate['250k'])
|
||||
self.pcan.initialize()
|
||||
|
|
@ -62,6 +64,8 @@ class CANFilter(threading.Thread):
|
|||
self.pcan.Messages['dc_charging'].addSignal( current )
|
||||
self.pcan.Messages['dc_charging'].addSignal( voltage )
|
||||
|
||||
return self.queue
|
||||
|
||||
#connection = MySQLdb.connect("url", "user", "passwort", "datenbankname")
|
||||
#cursor = connection.cursor()
|
||||
|
||||
|
|
@ -76,7 +80,7 @@ class CANFilter(threading.Thread):
|
|||
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_capacity.append(self.pcan.Messages['dc_battery'].Signals['capacity'].GetData())
|
||||
self.battery_timestamp.append(datetime.datetime.now())
|
||||
self.battery_timestamp.append(datetime.now())
|
||||
|
||||
if len(self.battery_timestamp) == 100:
|
||||
if debug:
|
||||
|
|
@ -89,9 +93,11 @@ class CANFilter(threading.Thread):
|
|||
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)]
|
||||
sql = 'INSERT INTO %s VALUES(%s, %s, %s, %s)'
|
||||
|
||||
for i in daten:
|
||||
print sql % i
|
||||
self.queue.put(daten[0])
|
||||
|
||||
# for i in daten:
|
||||
# print sql % i
|
||||
# cursor.executemany(sql, daten)
|
||||
|
||||
del self.battery_current[:], self.battery_voltage[:], self.battery_capacity[:], self.battery_timestamp[:]
|
||||
time.sleep(0.01)
|
||||
del self.battery_current[:], self.battery_voltage[:], self.battery_capacity[:], self.battery_timestamp[:] #clear tmp lists
|
||||
sleep(0.01)
|
||||
39
scr/ems.py
39
scr/ems.py
|
|
@ -2,11 +2,38 @@
|
|||
Created on 15.11.2013
|
||||
|
||||
@author: Philipp Rauch
|
||||
@version: 0.01
|
||||
@version: 0.02
|
||||
'''
|
||||
import threading
|
||||
import Queue
|
||||
import swich
|
||||
from API import Buffer as buf
|
||||
|
||||
foo = swich.Swich(swich.MYSQL)
|
||||
#from threading import Thread
|
||||
#from Queue import Queue
|
||||
from swich import Swich, MYSQL
|
||||
from API import Buffer, API
|
||||
from CANFilter import CANFilter
|
||||
|
||||
def startAPI(): #does not work currently
|
||||
app = API()
|
||||
app.start()
|
||||
pass
|
||||
|
||||
def startCANFilter():
|
||||
can = CANFilter()
|
||||
can.start()
|
||||
pass
|
||||
|
||||
def startSwich():
|
||||
swich = Swich(MYSQL)
|
||||
queue, can = swich.initialisiere()
|
||||
print 'EMS:\t', queue
|
||||
swich.start()
|
||||
pass
|
||||
|
||||
def writeToBuffer():
|
||||
#TODO
|
||||
pass
|
||||
|
||||
startSwich()
|
||||
|
||||
#buf = Buffer()
|
||||
#print 'ems ', buf
|
||||
#startAPI()
|
||||
44
scr/swich.py
44
scr/swich.py
|
|
@ -2,23 +2,26 @@
|
|||
Created on 15.11.2013
|
||||
|
||||
@author: Philipp Rauch
|
||||
@version: 0.01
|
||||
@version: 0.1
|
||||
'''
|
||||
|
||||
import MySQLdb
|
||||
import threading
|
||||
import Queue
|
||||
from CANFilter import CANFilter
|
||||
from threading import Thread
|
||||
from Queue import Queue
|
||||
from CANFilter import CANFilter
|
||||
from time import sleep
|
||||
#from MySQLdb import connect
|
||||
|
||||
MYSQL = 0
|
||||
CSV = 1
|
||||
XML = 2
|
||||
JSON = 3
|
||||
|
||||
class Swich(threading.Thread):
|
||||
class Swich(Thread):
|
||||
|
||||
_isInit = False
|
||||
|
||||
def __init__(self, source = MYSQL):
|
||||
threading.Thread.__init__(self)
|
||||
Thread.__init__(self)
|
||||
self.source = source
|
||||
|
||||
def __del__(self):
|
||||
|
|
@ -27,12 +30,19 @@ class Swich(threading.Thread):
|
|||
|
||||
def initialisiere(self):
|
||||
if self.source == MYSQL:
|
||||
_isInit = True
|
||||
|
||||
### start CAN ###
|
||||
self.CAN = CANFilter()
|
||||
self.CAN.start()
|
||||
|
||||
self.connection = MySQLdb.connect("url", "user", "password", "database_name")
|
||||
self.cursor = self.connection.cursor()
|
||||
self.queue = Queue.Queue()
|
||||
### connect to DB ###
|
||||
# self.connection = MySQLdb.connect("url", "user", "password", "database_name")
|
||||
# self.cursor = self.connection.cursor()
|
||||
|
||||
### init Queue ###
|
||||
self.queue = Queue()
|
||||
print 'SWICH:\t', self.queue
|
||||
return self.queue, self.CAN
|
||||
|
||||
elif self.source == CSV:
|
||||
|
|
@ -46,13 +56,19 @@ class Swich(threading.Thread):
|
|||
|
||||
else:
|
||||
return
|
||||
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
sql = 'SELECT * FROM %s ORDER BY timestamp DESC LIMIT 1'
|
||||
item = Swich.queue.get(block = True) #item is a string which names the table that will be returned (newest values)
|
||||
# item = Swich.queue.get(block = True)
|
||||
item = 'EMS-TEST'
|
||||
|
||||
print self.cursor.execute(sql % item)
|
||||
# data = self.cursor.execute(sql % item)
|
||||
self.setQueue(item)
|
||||
sleep(0.5)
|
||||
|
||||
def setQueue(self, item):
|
||||
self.queue.put(item)
|
||||
self.queue.put(item)
|
||||
|
||||
def getItem(self, block = False):
|
||||
return self.queue.get(block)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue