added Tag classes for MySQL and SQLite
This commit is contained in:
79
python/tag_sqlite.py
Normal file
79
python/tag_sqlite.py
Normal file
@@ -0,0 +1,79 @@
|
||||
#! /usr/bin/python
|
||||
from datetime import datetime
|
||||
import time
|
||||
import sqlite3 as lite
|
||||
from pycomm.ab_comm.clx import Driver as ClxDriver
|
||||
import micro800 as u800
|
||||
import traceback
|
||||
import pickle
|
||||
|
||||
con = lite.connect("/mnt/usb/data.db")
|
||||
# con = lite.connect("/Users/patrickjmcd/Desktop/data.db")
|
||||
|
||||
|
||||
def readTag(addr, tag):
|
||||
time.sleep(0.01)
|
||||
c = ClxDriver()
|
||||
if c.open(addr):
|
||||
try:
|
||||
v = c.read_tag(tag)
|
||||
return v
|
||||
except Exception:
|
||||
print("ERROR RETRIEVING TAG: {}".format(tag))
|
||||
err = c.get_status()
|
||||
c.close()
|
||||
print err
|
||||
pass
|
||||
c.close()
|
||||
|
||||
class Tag():
|
||||
global readTag, con
|
||||
|
||||
def __init__(self, name, tag, data_type, change_threshold, guarantee_sec, mapFn=None, plc_type='CLK'):
|
||||
self.name = name
|
||||
self.tag = tag
|
||||
self.data_type = data_type
|
||||
self.value = None
|
||||
self.last_value = None
|
||||
self.guarantee_sec = guarantee_sec
|
||||
self.chg_threshold = change_threshold
|
||||
self.last_send_time = 0
|
||||
self.mapFn = mapFn
|
||||
self.plc_type = plc_type
|
||||
self.readFn = readTag
|
||||
if self.plc_type == "u800":
|
||||
self.readFn = u800.readTag
|
||||
|
||||
def read(self, forceSend):
|
||||
writeToDB = False
|
||||
if self.tag:
|
||||
v = readFn(PLC_IP_ADDRESS, self.tag)
|
||||
if v:
|
||||
if self.data_type == 'BOOL' or self.data_type == 'STRING':
|
||||
val = v[0]
|
||||
if self.mapFn:
|
||||
val = self.mapFn[val]
|
||||
if (self.last_send_time == 0) or (self.value is None) or not (self.value == val) or ((time.time() - self.last_send_time) > self.guarantee_sec) or (forceSend):
|
||||
self.last_value = self.value
|
||||
self.value = val
|
||||
writeToDB = True
|
||||
else:
|
||||
writeToDB = False
|
||||
else:
|
||||
if (self.last_send_time == 0) or (self.value is None) or (abs(self.value - v[0]) > self.chg_threshold) or ((time.time() - self.last_send_time) > self.guarantee_sec) or (forceSend):
|
||||
self.last_value = self.value
|
||||
self.value = v[0]
|
||||
writeToDB = True
|
||||
else:
|
||||
writeToDB = False
|
||||
if writeToDB:
|
||||
self.sendToDB()
|
||||
|
||||
def sendToDB(self):
|
||||
query = "INSERT INTO tag_vals (dtime, name, val) VALUES ({}, '{}', {})".format(time.time(), self.name, self.value)
|
||||
print query
|
||||
# TODO: CHECK ON THIS LOGIC -- with con:
|
||||
cur = con.cursor()
|
||||
cur.execute(query)
|
||||
con.commit()
|
||||
cur.close()
|
||||
Reference in New Issue
Block a user