MySQL working, need to retro SQLite

This commit is contained in:
Patrick McDonagh
2016-04-12 18:31:14 -05:00
parent c568c2dfdb
commit c8baa20927
17 changed files with 408 additions and 608 deletions

View File

@@ -11,4 +11,8 @@ sS'user'
p5
S'website'
p6
s.
sS'database'
p7
S'poconsole'
p8
s.

View File

@@ -3,7 +3,8 @@ import pickle
mysql_cfg = {
'host':'127.0.0.1',
'user':'website',
'password':'henrypump'
'password':'henrypump',
'database':'poconsole'
}
with open('mysql_cfg.pickle', 'wb') as pickleconfig:

View File

@@ -14,9 +14,6 @@ with open('mysql_cfg.pickle', 'rb') as cfgFile:
PLC_IP_ADDRESS = "10.10.10.3"
def readTag(addr, tag):
time.sleep(0.01)
c = ClxDriver()
@@ -36,7 +33,7 @@ def readTag(addr, tag):
class Tag():
global readTag, con, PLC_IP_ADDRESS
def __init__(self, name, tag, data_type, change_threshold, guarantee_sec, mapFn=None, plc_type='CLX'):
def __init__(self, name, tag, db_id, data_type, change_threshold, guarantee_sec, mapFn=None, plc_type='CLX', plc_ip_address='192.168.1.10'):
self.name = str(name)
self.tag = str(tag)
self.data_type = str(data_type)
@@ -48,13 +45,15 @@ class Tag():
self.mapFn = mapFn
self.plc_type = plc_type
self.readFn = readTag
self.db_id = db_id
if self.plc_type == "u800":
self.readFn = u800.readTag
self.plc_ip_address = plc_ip_address
def read(self, forceSend):
writeToDB = False
if self.tag:
v = self.readFn(PLC_IP_ADDRESS, self.tag)
v = self.readFn(self.plc_ip_address, self.tag)
if v:
if self.data_type == 'BOOL' or self.data_type == 'STRING':
val = v[0]
@@ -78,7 +77,7 @@ class Tag():
def sendToDB(self):
# TODO: Datetime
query = "INSERT INTO poconsole.tag_vals (dtime, name, val) VALUES ('{}', '{}', {})".format(time.strftime('%Y-%m-%d %H:%M:%S'), self.name, self.value)
query = "INSERT INTO poconsole.tag_vals (dtime, tagID, val) VALUES ('{}', '{}', {})".format(time.strftime('%Y-%m-%d %H:%M:%S'), self.db_id, self.value)
self.last_send_time = time.time()
print query
# TODO: CHECK ON THIS LOGIC -- with con:

View File

@@ -29,7 +29,7 @@ def readTag(addr, tag):
class Tag():
global readTag, con
def __init__(self, name, tag, data_type, change_threshold, guarantee_sec, mapFn=None, plc_type='CLK'):
def __init__(self, name, tag, db_id, data_type, change_threshold, guarantee_sec, mapFn=None, plc_type='CLK', plc_ip_address='192.168.1.10'):
self.name = name
self.tag = tag
self.data_type = data_type
@@ -41,13 +41,15 @@ class Tag():
self.mapFn = mapFn
self.plc_type = plc_type
self.readFn = readTag
self.db_id = db_id
if self.plc_type == "u800":
self.readFn = u800.readTag
self.plc_ip_address = plc_ip_address
def read(self, forceSend):
writeToDB = False
if self.tag:
v = readFn(PLC_IP_ADDRESS, self.tag)
v = readFn(self.plc_ip_address, self.tag)
if v:
if self.data_type == 'BOOL' or self.data_type == 'STRING':
val = v[0]
@@ -70,7 +72,7 @@ class Tag():
self.sendToDB()
def sendToDB(self):
query = "INSERT INTO tag_vals (dtime, name, val) VALUES ({}, '{}', {})".format(time.time(), self.name, self.value)
query = "INSERT INTO tag_vals (dtime, tagID, val) VALUES ({}, '{}', {})".format(time.time(), self.db_id, self.value)
print query
# TODO: CHECK ON THIS LOGIC -- with con:
cur = con.cursor()

View File

@@ -19,32 +19,76 @@ if mysql_cfg:
db = mysqlcon.connect(**mysql_cfg)
tag_store = {}
configProperties = {}
def main():
db.connect()
cur = db.cursor()
query = "SELECT * FROM poconsole.tags WHERE class = 5 AND deleted = 0"
query = "SELECT * FROM tags WHERE class = 5 AND deleted = 0"
cur.execute(query)
tags = cur.fetchall()
print tags
# [(1, u'Century Counter Up', 5, u'Century_Counter_Up', u'REAL', 10.0, 3600, None, 0)]
db.disconnect()
configObj = {}
db.connect()
cur = db.cursor()
query = "SELECT parameter, val FROM config GROUP BY parameter;"
cur.execute(query)
config = cur.fetchall()
db.disconnect()
for x in config:
configObj[x[0]] = x[1]
try:
configProperties['PLC_IP_ADDRESS'] = str(configObj['ip_address'])
print("FYI, using PLC IP Address from the database {0}".format(configProperties['PLC_IP_ADDRESS']))
except KeyError:
print("FYI, there is no PLC IP Address stored in the database, defaulting to 192.168.1.10")
configProperties['PLC_IP_ADDRESS'] = "192.168.1.10"
try:
configProperties['plc_type'] = str(configObj['plc_type'])
print("FYI, using PLC Type from the database {0}".format(configProperties['plc_type']))
except KeyError:
print("FYI, there is no PLC Type stored in the database, defaulting to CLX")
configProperties['plc_type'] = "CLX"
try:
configProperties['scan_rate'] = int(configObj['scan_rate'])
print("FYI, using Scan Rate from the database {0}".format(configProperties['scan_rate']))
except KeyError:
print("FYI, there is no Scan Rate stored in the database, defaulting to 10 seconds")
configProperties['scan_rate'] = 10
try:
sa_test = str(configObj['save_all'])
if sa_test == "true":
configProperties['save_all'] = True
else:
configProperties['save_all'] = False
print("FYI, value for save_all is {0}".format(configProperties['save_all']))
except KeyError:
print("FYI, there is no save_all value stored in the database, using False")
configProperties['save_all'] = False
for t in tags:
tag_store[t[1]] = Tag(t[1], t[3], t[4], t[5], t[6], mapFn=t[7])
tag_store[t[1]] = Tag(t[1], t[3], t[0], t[5], t[6], t[7], mapFn=t[8], plc_type=configProperties['plc_type'], plc_ip_address=configProperties['PLC_IP_ADDRESS'])
PLC_IP_ADDRESS = "10.10.10.3" # MAKE THIS A db VALUE
scan_rate = 10
while True:
for tag in tag_store:
try:
tag_store[tag].read(False)
tag_store[tag].read(configProperties['save_all'])
except:
print("ERROR EVALUATING {}".format(tag))
traceback.print_exc()
time.sleep(scan_rate)
time.sleep(configProperties['scan_rate'])
if __name__ == '__main__':
main()

View File

@@ -1,276 +0,0 @@
#! /usr/bin/env python
# Copyright (C) 2014 Gayner Technical Services Pty Ltd
from ctypes import *
# PLC TYPES
Unknow=0
PLC=1
SLC500=2
LGX=3
# EIP DATA TYPES
PLC_BIT=1
PLC_BIT_STRING=2
PLC_BYTE_STRING=3
PLC_INTEGER=4
PLC_TIMER=5
PLC_COUNTER=6
PLC_CONTROL=7
PLC_FLOATING=8
PLC_ARRAY=9
PLC_ADRESS=15
PLC_BCD=16
# LOGIX DATA TYPES
LGX_BOOL=0xC1
LGX_BITARRAY=0xD3
LGX_SINT=0xC2
LGX_INT=0xC3
LGX_DINT=0xC4
LGX_REAL=0xCA
class Eip_Session(Structure):
_fields_ = [
('sock',c_int),
('Session_Handle', c_uint),
('Sender_ContextL',c_int),
('Sender_ContextH',c_int),
('timeout', c_int),
('references', c_int),
('Data', c_void_p),
]
class Eip_Connection(Structure):
_fields_ = [
('Eip_Session', Eip_Session),
('references', c_int),
('Data', c_void_p),
('ConnectionSerialNumber', c_uint),
('OriginatorVendorID', c_uint),
('OriginatorSerialNumber', c_int),
('OT_ConnID', c_int),
('TO_ConnID', c_int),
('packet', c_short),
('Path_size', c_byte)
]
class Eip_PLC_Read(Structure):
_fields_ = [
('type', c_int),
('Varcount', c_int),
('totalise', c_int),
('elementsize', c_int),
('mask', c_uint),
]
class TuxEIPException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class TuxEIP:
def __init__(self, **kwargs):
self.__libpath = kwargs.get("libpath", "libtuxeip.dylib")
self.__tuxeip = CDLL(self.__libpath)
self.__tuxeip._cip_err_msg.restype = c_char_p
def __del__(self):
del self.__tuxeip
def OpenSession(self, slaveip_, slaveport_=44818, slavetimeout_=1000):
self.__tuxeip._OpenSession.restype = POINTER(Eip_Session)
# Convert params to C types
slaveip = c_char_p(slaveip_)
slaveport = c_int(slaveport_)
slavetimeout = c_int(slavetimeout_)
session = self.__tuxeip._OpenSession(slaveip, slaveport, slavetimeout)
#print self.__tuxeip._cip_err_msg, self.__tuxeip._cip_errno, self.__tuxeip._cip_ext_errno
if bool(session) == False:
raise TuxEIPException("Could not open session to " + str(slaveip) + ":" + str(slaveport))
return session
def RegisterSession(self, sess_):
self.__tuxeip._RegisterSession.restype = c_int
reg = self.__tuxeip._RegisterSession(sess_)
if reg != False:
raise TuxEIPException("Could not register session")
return reg
def ConnectPLCOverCNET(self, sess_, plctype_, priority_, timeoutticks_, connid_, conserial_,
vendorid_, serialnum_, timeoutmult_, rpi_, transport_, slavepath_):
# Convert params to C types
priority = c_byte(priority_)
timeoutticks = c_byte(timeoutticks_)
connid = c_uint(connid_)
conserial = c_ushort(conserial_)
vendorid = c_ushort(vendorid_)
serialnum = c_uint(serialnum_)
timeutmult = c_byte(timeoutmult_)
rpi = c_uint(rpi_)
transport = c_byte(transport_)
slavepath = c_char_p(slavepath_)
pathlength = len(slavepath_)
self.__tuxeip._ConnectPLCOverCNET.restype = POINTER(Eip_Connection)
connection = self.__tuxeip._ConnectPLCOverCNET(
sess_,
plctype_,
priority,
timeoutticks,
connid,
conserial,
vendorid,
serialnum,
timeutmult,
rpi,
transport,
slavepath,
pathlength
)
if bool(connection) == False:
raise TuxEIPException("Could not connect to CPU")
return connection
def ReadLgxData(self, sess_, conn_, var_, num_):
self.__tuxeip._ReadLgxData.restype = POINTER(Eip_PLC_Read)
readdata = self.__tuxeip._ReadLgxData(sess_, conn_, var_, num_)
if bool(readdata) == False:
raise TuxEIPException("Read data failed")
return readdata
def WriteLGXData(self, sess_, conn_, address_, datatype_, data_, num_ ):
if datatype_ == LGX_INT or datatype_ == LGX_BOOL or datatype_ == LGX_DINT or datatype_ == LGX_SINT:
data = c_int(data_)
elif datatype_ == LGX_REAL:
data = c_float(data_)
else:
raise TuxEIPException("Write data failed")
data = self.__tuxeip._WriteLgxData(sess_, conn_, address_, datatype_, byref(data), num_)
return data
def ReadLGXDataAsFloat(self, sess_, conn_, var_, num_):
data = self.ReadLgxData(sess_, conn_, var_, num_)
d = self.GetLGXValueAsFloat(data)
self.FreePLCRead(data)
return d
def ReadLGXDataAsInteger(self, sess_, conn_, var_, num_):
data = self.ReadLgxData(sess_, conn_, var_, num_)
d = self.GetLGXValueAsInteger(data)
self.FreePLCRead(data)
return d
def ReadPLCDataAsFloat(self, sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, number_):
data = self.ReadPLCData(sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, number_)
d = self.PCCC_GetValueAsFloat(data)
self.FreePLCRead(data)
return d
def ReadPLCDataAsInteger(self, sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, number_):
data = self.ReadPLCData(sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, number_)
d = self.PCCC_GetValueAsInteger(data)
self.FreePLCRead(data)
return d
def ReadPLCData(self, sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, number_):
self.__tuxeip._ReadPLCData.restype = POINTER(Eip_PLC_Read)
readdata = self.__tuxeip._ReadPLCData(sess_, conn_, dhp_, routepath_, routesize_, plctype_,
tns_, address_, number_)
if bool(readdata) == False:
raise TuxEIPException("Read data failed")
return readdata
def GetLGXValueAsFloat(self, readdata_):
if bool(readdata_) == False:
return None
self.__tuxeip._GetLGXValueAsFloat.restype = c_float
values = []
for i in range(0, readdata_.contents.Varcount):
v = self.__tuxeip._GetLGXValueAsFloat(readdata_, i)
values.append(v)
return values
def GetLGXValueAsInteger(self, readdata_):
if bool(readdata_) == False:
return None
self.__tuxeip._GetLGXValueAsInteger.restype = c_int
values = []
for i in range(0, readdata_.contents.Varcount):
v = self.__tuxeip._GetLGXValueAsInteger(readdata_, i)
values.append(v)
return values
def PCCC_GetValueAsFloat(self, readdata_):
if bool(readdata_) == False:
return None
self.__tuxeip._PCCC_GetValueAsFloat.restype = c_float
values = []
for i in range(0, readdata_.contents.Varcount):
v = self.__tuxeip._PCCC_GetValueAsFloat(readdata_, i)
values.append(v)
return values
def PCCC_GetValueAsInteger(self, readdata_):
if bool(readdata_) == False:
return None
self.__tuxeip._PCCC_GetValueAsInteger.restype = c_int
values = []
for i in range(0, readdata_.contents.Varcount):
v = self.__tuxeip._PCCC_GetValueAsInteger(readdata_, i)
values.append(v)
return values
def WritePLCData(self, sess_, conn_, dhp_, routepath_, routesize_, plctype_, tns_, address_, datatype_, data_, number_):
if datatype_ == PLC_INTEGER:
data = c_int(data_)
elif datatype_ == PLC_FLOATING:
data = c_float(data_)
else:
raise TuxEIPException("Variable type not supported" + str(datatype_))
result = self.__tuxeip._WritePLCData(sess_, conn_, dhp_, routepath_, routesize_, plctype_,
tns_, address_, datatype_, byref(data), number_)
return result
def Forward_Close(self, conn_):
self.__tuxeip._Forward_Close(conn_)
def UnRegisterSession(self, sess_):
self.__tuxeip._UnRegisterSession(sess_)
def CloseSession(self, sess_):
self.__tuxeip.CloseSession(sess_)
def FreePLCRead(self, data_):
self.__tuxeip._FreePLCRead(data_)

Binary file not shown.