Merge branch 'master' of pogo:ems

This commit is contained in:
Philipp Rauch 2013-12-09 11:10:13 +01:00
commit 6c9a84c2cd
9 changed files with 145 additions and 97 deletions

View file

@ -4,7 +4,7 @@ Created on 24.10.2013
@author: Philipp Rauch @author: Philipp Rauch
@version: 0.6 @version: 0.6
''' '''
from sys import stderr
from datetime import datetime 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
@ -65,7 +65,7 @@ class Buffer(object):
'dc_labor' : dc_labor, 'dc_labor' : dc_labor,
'dc_grid' : dc_grid, 'dc_grid' : dc_grid,
'ac_grid' : ac_grid, 'ac_grid' : ac_grid,
'request' : None 'request' : {}
} }
_instance = None _instance = None
@ -111,6 +111,8 @@ class Buffer(object):
@param postfix: appendix to the given url @param postfix: appendix to the given url
''' '''
if isinstance(dic, dict): if isinstance(dic, dict):
if '00_config' in url.split('/'):
return
url = '%s/%s' % (url, postfix) url = '%s/%s' % (url, postfix)
self.set_href(dic, url) self.set_href(dic, url)
else: else:
@ -142,9 +144,41 @@ class Buffer(object):
abort(404) abort(404)
return { l[-1] : message, 'args' : args.to_dict(flat=False)} return { l[-1] : message, 'args' : args.to_dict(flat=False)}
def update_buffer(self): def update_buffer(self, push):
#ToDo '''
pass 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)
def init_buffer(self): def init_buffer(self):
#ToDo #ToDo
@ -155,6 +189,14 @@ class API(object):
def __init__(self): def __init__(self):
self.app = Flask(__name__) self.app = Flask(__name__)
### Start EMS thread ###
self.EMS = ems.ems(buf)
self.emsthread = self.EMS.start()
if conf['config_debug']:
print 'EMS-Thread:\t', self.EMS
print '\tAPI-BUFFER:\t', buf
### ADD URL RULES ### ### ADD URL RULES ###
self.app.error_handler_spec[None][400] = bad_reqest self.app.error_handler_spec[None][400] = bad_reqest
self.app.error_handler_spec[None][404] = not_found self.app.error_handler_spec[None][404] = not_found
@ -196,15 +238,10 @@ def get_catch_all(path):
out = buf.get_level(l) out = buf.get_level(l)
return jsonify( out ) return jsonify( out )
def start(): def API_start():
api = API() api = API()
api.app.run(host = conf['flask_server'], api.app.run(host = conf['flask_server'],
port = int(conf['flask_port']), port = int(conf['flask_port']),
debug = conf['flask_debug']) debug = conf['flask_debug'])
EMS = ems.ems(buf) API_start()
emsthread = EMS.start()
if conf['config_debug']:
print 'EMS-Thread:\t', EMS
print '\tAPI-BUFFER:\t', buf
start()

View file

@ -37,41 +37,21 @@ class CANFilter(Thread):
debug = self.conf['config_debug']) debug = self.conf['config_debug'])
self.pcan.initialize() self.pcan.initialize()
dc_battery = CanMessage(0x3A4, 8, 50, 'dc_battery') for message in self.conf['can_messages']:
dc_grid = CanMessage(0x3A5, 8, 50, 'dc_grid') self.pcan.addMessage(CanMessage(int(self.conf[message]['id'], 0), #hex-string to int
dc_pv = CanMessage(0x3A6, 8, 50, 'dc_pv') int(self.conf[message]['length']),
dc_charging = CanMessage(0x3A7, 8, 50, 'dc_charger') int(self.conf[message]['time']),
message))
print "Message: %s" % message
for signal in self.conf["sig_%s" % message]:
self.pcan.Messages[message].addSignal(CanSignal(int(self.conf[signal]['begin']),
int(self.conf[signal]['length']),
int(self.conf[signal]['offset']),
float(self.conf[signal]['scaling']),
int(self.conf[signal]['data']),
signal))
print " - %s" % signal
self.pcan.addMessage(dc_battery)
self.pcan.addMessage(dc_grid)
self.pcan.addMessage(dc_pv)
self.pcan.addMessage(dc_charging)
current = CanSignal(0, 16, 0, 0.001, 0, 'current')
voltage = CanSignal(16, 16, 0, 0.01, 0, 'voltage')
soc = CanSignal(32, 11, 0, 0.05, 0, 'soc')
isMaster = CanSignal(56, 1, 0, 1, 0, 'isMaster')
isFeed = CanSignal(57, 1, 0, 1, 0, 'isFeed')
isCharging = CanSignal(57, 1, 0, 1, 0, 'isCharging')
isOn = CanSignal(58, 1, 0, 1, 0, 'isOn')
self.pcan.Messages['dc_battery'].addSignal( current )
self.pcan.Messages['dc_battery'].addSignal( voltage )
self.pcan.Messages['dc_battery'].addSignal( soc )
self.pcan.Messages['dc_battery'].addSignal( isMaster )
self.pcan.Messages['dc_battery'].addSignal( isCharging )
self.pcan.Messages['dc_grid'].addSignal( current )
self.pcan.Messages['dc_grid'].addSignal( voltage )
self.pcan.Messages['dc_grid'].addSignal( isMaster )
self.pcan.Messages['dc_grid'].addSignal( isFeed )
self.pcan.Messages['dc_grid'].addSignal( isOn )
self.pcan.Messages['dc_pv'].addSignal( current )
self.pcan.Messages['dc_pv'].addSignal( voltage )
self.pcan.Messages['dc_charger'].addSignal( current )
self.pcan.Messages['dc_charger'].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

View file

@ -1,7 +1,7 @@
''' '''
Created on 21.11.2013 Created on 21.11.2013
@author: rauchp @author: Philipp Rauch
''' '''
from sys import stderr from sys import stderr
config = "config\ems.conf" config = "config\ems.conf"

View file

@ -25,10 +25,15 @@ can_messages = dc_battery, dc_grid, dc_pv, dc_charger
'dc_pv = id:0x3A6, length:8, time:50 'dc_pv = id:0x3A6, length:8, time:50
'dc_charger = id:0x3A7, length:8, time:50 'dc_charger = id:0x3A7, length:8, time:50
can_signales = current, voltage, capacity, isMaster, isFeed, isCharging, isOn sig_dc_battery = current, voltage, soc, isMaster, isCharging
sig_dc_grid = current, voltage, isMaster, isFeed, isOn
sig_dc_pv = current, voltage
sig_dc_charger = current, voltage
#can_signales = current, voltage, soc, isMaster, isFeed, isCharging, isOn
'current = begin:0, length:16, offset:0, scaling:0.001, data:0 'current = begin:0, length:16, offset:0, scaling:0.001, data:0
'voltage = begin:16, length:16, offset:0, scaling:0.01, data:0 'voltage = begin:16, length:16, offset:0, scaling:0.01, data:0
'capacity = begin:32, length:11, offset:0, scaling:0.05, data:0 'soc = begin:32, length:11, offset:0, scaling:0.05, data:0
'isMaster = begin:56, length:1, offset:0, scaling:1, data:0 'isMaster = begin:56, length:1, offset:0, scaling:1, data:0
'isFeed = begin:57, length:1, offset:0, scaling:1, data:0 'isFeed = begin:57, length:1, offset:0, scaling:1, data:0
'isCharging = begin:57, length:1, offset:0, scaling:1, data:0 'isCharging = begin:57, length:1, offset:0, scaling:1, data:0

View file

@ -4,7 +4,7 @@ Created on 15.11.2013
@author: Philipp Rauch @author: Philipp Rauch
@version: 0.02 @version: 0.02
''' '''
from sys import stderr # from sys import stderr
from threading import Thread from threading import Thread
from switch import Switch, MYSQL from switch import Switch, MYSQL
from config import Config from config import Config
@ -14,32 +14,35 @@ c = Config()
conf = c.readConf() conf = c.readConf()
def startSwitch(): def startSwitch():
swich = Switch(MYSQL) switch = Switch(MYSQL)
queue, query = swich.initialisiere() queue, query = switch.initialisiere()
if conf['config_debug']: if conf['config_debug']:
print 'SWITCH-Thread:\t', swich print 'SWITCH-Thread:\t', switch
print '\tEMS-QUERY:\t', query print '\tEMS-QUERY:\t', query
print '\tEMS-QUEUE:\t', queue print '\tEMS-QUEUE:\t', queue
swich.start() switch.start()
return queue, query return switch, queue, query
class ems(Thread): class ems(Thread):
def __init__(self, buf): def __init__(self, buf):
Thread.__init__(self) Thread.__init__(self)
self.buffer = buf self.buffer = buf
self.queue, self.query = startSwitch() self.switch, self.queue, self.query = startSwitch()
if conf['config_debug']: if conf['config_debug']:
print '\tEMS-BUFFER:\t', buf print '\tEMS-BUFFER:\t', buf
def __del__(self):
self.switch.stop = True
def run(self): def run(self):
old = None old = None
while True: while True:
new = self.getNewMsg(old) new = self.getNewMsg(old)
if conf['config_debug']: if conf['config_debug']:
print 'GET:\t', new print 'GET:\t', new
self.updateBuffer(new) self.buffer.update_buffer(new)
old = new old = new
def getNewMsg(self, old): def getNewMsg(self, old):
@ -52,40 +55,40 @@ class ems(Thread):
tmp = self.queue.get() tmp = self.queue.get()
return tmp return tmp
def updateBuffer(self, push): # def update_buffer(self, push):
''' # '''
Method to update the Buffer on the given path # Method to update the Buffer on the given path
@param push: message to push in the buffer # @param push: message to push in the buffer
construction: key is the path # construction: key is the path
value is the dict # value is the dict
''' # '''
#
## Test of valid push message ## # ## Test of valid push message ##
if not isinstance(push, dict): # if not isinstance(push, dict):
stderr.write('error wrong parameter: Type is %s expect dict' % push.__class__.__name__) # stderr.write('error wrong parameter: Type is %s expect dict' % push.__class__.__name__)
return # return
if len(push.keys()) not in [1]: # if len(push.keys()) not in [1]:
stderr.write('error wrong number of arguments: %s expect 1' % len(push.keys())) # stderr.write('error wrong number of arguments: %s expect 1' % len(push.keys()))
return # return
if not isinstance(push.get(push.keys()[0]) ,dict): # if not isinstance(push.get(push.keys()[0]) ,dict):
stderr.write('error value is not dict') # stderr.write('error value is not dict')
return # return
#
key = push.keys()[0] # key = push.keys()[0]
value = push[key] # value = push[key]
path = key.split('/') # path = key.split('/')
if path[0] == '': # if path[0] == '':
path.remove('') # path.remove('')
#
sys = self.buffer.system # sys = self.buffer.system
for key in path: # for key in path:
try: # try:
sys = sys[key] # sys = sys[key]
except KeyError: # except KeyError:
stderr.write('error wrong path: %s' % key) # stderr.write('error wrong path: %s' % key)
return # return
#
sys.update(value) # sys.update(value)
def getRequest(self): def getRequest(self):
#TODO: get Request from buffer #TODO: get Request from buffer

View file

@ -1,7 +1,7 @@
''' '''
Created on 26.11.2013 Created on 26.11.2013
@author: rauchp @author: Philipp Rauch
''' '''
from MySQLdb import connect from MySQLdb import connect

26
src/modules/modbus.py Normal file
View file

@ -0,0 +1,26 @@
'''
Created on 05.12.2013
@author: Philipp Rauch
'''
from pymodbus.client.sync import ModbusTcpClient
PAC01 = ModbusTcpClient('10.2.6.5')
PAC02 = ModbusTcpClient('10.2.6.6')
PAC03 = ModbusTcpClient('10.2.6.7')
PAC04 = ModbusTcpClient('10.2.6.8')
PAC01.connect()
# PAC01.write_coil(213, 100,2)
# result = PAC01.read_coils(213,1,unit=2)
a = PAC01.write_registers(213,(1,0),unit=2)
print "Antwort: %s" % a
res = PAC01.read_holding_registers(213,4,unit=2)
print "Werte: %s" % res.registers
# print result.bits[0]
PAC01.close()

View file

@ -59,11 +59,8 @@ class Switch(Thread):
#print 'PUT:\t%s' % result #print 'PUT:\t%s' % result
self.setQueue(result) self.queue.put(result)
sleep(float(conf['mySQL_speed'])) sleep(float(conf['mySQL_speed']))
def setQueue(self, item):
self.queue.put(item)
def getItem(self, block = False): def getItem(self, block = False):
return self.queue.get(block) return self.queue.get(block)

View file

@ -1,7 +1,7 @@
''' '''
Created on 21.11.2013 Created on 21.11.2013
@author: rauchp @author: Philipp Rauch
''' '''
import CANFilter import CANFilter
#import ems #import ems