Files
HenryPump-Drivers/email_reports/email_reports.py

235 lines
9.4 KiB
Python

"""Driver for email_reports"""
import threading
import json
import time
from random import randint
from datetime import datetime as dt
from device_base import deviceBase
from Channel import PLCChannel, ModbusChannel,read_tag, read_array, write_tag, TAG_DATAERROR_SLEEPTIME
import persistence
from utilities import get_public_ip_address, generate_report, send_email
from file_logger import filelogger as log
PLC_IP_ADDRESS = "192.168.1.10"
from Tags import tags
_ = None
log.info("email_reports startup")
# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 60
IP_CHECK_PERIOD = 60
WATCHDOG_ENABLE = False
WATCHDOG_CHECK_PERIOD = 60
WATCHDOG_SEND_PERIOD = 3600 # Seconds, the longest amount of time before sending the watchdog status
CHANNELS = tags
class start(threading.Thread, deviceBase):
"""Start class required by Meshify."""
def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None,
companyId=None, offset=None, mqtt=None, Nodes=None):
"""Initialize the driver."""
threading.Thread.__init__(self)
deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q,
mcu=mcu, companyId=companyId, offset=offset,
mqtt=mqtt, Nodes=Nodes)
self.daemon = True
self.version = "6"
self.finished = threading.Event()
self.force_send = False
self.public_ip_address = ""
self.public_ip_address_last_checked = 0
self.watchdog = False
self.watchdog_last_checked = 0
self.watchdog_last_sent = 0
self.PERSIST = persistence.load()
threading.Thread.start(self)
# this is a required function for all drivers, its goal is to upload some piece of data
# about your device so it can be seen on the web
def register(self):
"""Register the driver."""
# self.sendtodb("log", "BOOM! Booted.", 0)
pass
def run(self):
"""Actually run the driver."""
for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
print("email_reports driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
time.sleep(1)
log.info("BOOM! Starting email_reports driver...")
if not self.PERSIST:
self.PERSIST = {'yesterday': dt.today().day - 1,
'start': 0,
'end': 10000,
'recipients': ['nmelone@henry-pump.com']}
persistence.store(self.PERSIST)
#self._check_watchdog()
self._check_ip_address()
self.nodes["email_reports_0199"] = self
send_loops = 0
while True:
now = time.time()
if self.force_send:
log.warning("FORCE SEND: TRUE")
if self.isReportTime():
self.run_report()
# print("email_reports driver still alive...")
if self.force_send:
if send_loops > 2:
log.warning("Turning off force_send")
self.force_send = False
send_loops = 0
else:
send_loops += 1
if WATCHDOG_ENABLE:
if (now - self.watchdog_last_checked) > WATCHDOG_CHECK_PERIOD:
self._check_watchdog()
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
self._check_ip_address()
def _check_watchdog(self):
"""Check the watchdog and send to Meshify if changed or stale."""
test_watchdog = self.email_reports_watchdog()
now = time.time()
self.watchdog_last_checked = now
if test_watchdog != self.watchdog or (now - self.watchdog_last_sent) > WATCHDOG_SEND_PERIOD:
self.sendtodbDev(1, 'watchdog', test_watchdog, 0, 'email_reports')
self.watchdog = test_watchdog
self.watchdog_last_sent = now
def _check_ip_address(self):
"""Check the public IP address and send to Meshify if changed."""
self.public_ip_address_last_checked = time.time()
test_public_ip = get_public_ip_address()
if not test_public_ip == self.public_ip_address:
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'email_reports')
self.public_ip_address = test_public_ip
def email_reports_watchdog(self):
"""Write a random integer to the PLC and then 1 seconds later check that it has been decremented by 1."""
randval = randint(0, 32767)
write_tag(str(PLC_IP_ADDRESS), 'watchdog_INT', randval, plc_type="CLX")
time.sleep(1)
watchdog_val = read_tag(str(PLC_IP_ADDRESS), 'watchdog_INT', plc_type="CLX")
try:
return (randval - 1) == watchdog_val[0]
except (KeyError, TypeError):
return False
def email_reports_sync(self, name, value):
"""Sync all data from the driver."""
self.force_send = True
# self.sendtodb("log", "synced", 0)
return True
def email_reports_writeplctag(self, name, value):
"""Write a value to the PLC."""
new_val = json.loads(str(value).replace("'", '"'))
tag_n = str(new_val['tag']) # "cmd_Start"
val_n = new_val['val']
write_res = write_tag(str(PLC_IP_ADDRESS), tag_n, val_n, plc_type="CLX")
print("Result of email_reports_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
if write_res is None:
write_res = "Error writing to PLC..."
return write_res
def isReportTime(self):
right_now = dt.today()
if right_now.hour == 23 and right_now.minute == 0 and not(right_now.day == self.PERSIST['yesterday']):
if right_now.day == 1:
self.PERSIST['start'] = 0
self.PERSIST['end'] = 10000
persistence.store(self.PERSIST)
return True
return False
def run_report(self):
#read a full array from PLC
log.info("Gathering Timestamp between {} and {}".format(self.PERSIST['start'], self.PERSIST['end']))
trans_day, self.PERSIST['end'] = read_array(CHANNELS[1].plc_ip,CHANNELS[1].plc_tag,self.PERSIST['start'],10000,CHANNELS[1].plc_type)
trans_hour, self.PERSIST['end'] = read_array(CHANNELS[2].plc_ip,CHANNELS[1].plc_tag,self.PERSIST['start'],self.PERSIST['end'],CHANNELS[2].plc_type)
trans_min, self.PERSIST['end'] = read_array(CHANNELS[3].plc_ip,CHANNELS[3].plc_tag,self.PERSIST['start'],self.PERSIST['end'],CHANNELS[3].plc_type)
log.info("Gathering Driver IDs between {} and {}".format(self.PERSIST['start'], self.PERSIST['end']))
driver_id, self.PERSIST['end'] = read_array(CHANNELS[0].plc_ip, CHANNELS[0].plc_tag, self.PERSIST['start'], self.PERSIST['end'], CHANNELS[0].plc_type) #addr, tag, start, end, plc_type="CLX"
log.info("Gather Transaction Data between {} and {}".format(self.PERSIST['start'], self.PERSIST['end']))
trans_total, self.PERSIST['end'] = read_array(CHANNELS[4].plc_ip,CHANNELS[4].plc_tag,self.PERSIST['start'],self.PERSIST['end'],CHANNELS[4].plc_type)
self.PERSIST['start'] = self.PERSIST['end']
overall = {
'today_total': CHANNELS[5].read(),
'yesterday_total': CHANNELS[6].read(),
'monthly_total': CHANNELS[7].read(),
'prevmonthly_total': CHANNELS[8].read(),
'current_year_total': CHANNELS[9].read(),
'prev_year_total': CHANNELS[10].read()
}
company_1 = {
'today_total': CHANNELS[11].read(),
'yesterday_total': CHANNELS[12].read(),
'monthly_total': CHANNELS[13].read(),
'prevmonthly_total': CHANNELS[14].read(),
'current_year_total': CHANNELS[15].read(),
'prev_year_total': CHANNELS[16].read()
}
company_2 = {
'today_total': CHANNELS[17].read(),
'yesterday_total': CHANNELS[18].read(),
'monthly_total': CHANNELS[19].read(),
'prevmonthly_total': CHANNELS[20].read(),
'current_year_total': CHANNELS[21].read(),
'prev_year_total': CHANNELS[22].read()
}
company_3 = {
'today_total': CHANNELS[23].read(),
'yesterday_total': CHANNELS[24].read(),
'monthly_total': CHANNELS[25].read(),
'prevmonthly_total': CHANNELS[26].read(),
'current_year_total': CHANNELS[27].read(),
'prev_year_total': CHANNELS[28].read()
}
company_4 = {
'today_total': CHANNELS[29].read(),
'yesterday_total': CHANNELS[30].read(),
'monthly_total': CHANNELS[31].read(),
'prevmonthly_total': CHANNELS[32].read(),
'current_year_total': CHANNELS[33].read(),
'prev_year_total': CHANNELS[34].read()
}
company_5 = {
'today_total': CHANNELS[35].read(),
'yesterday_total': CHANNELS[36].read(),
'monthly_total': CHANNELS[37].read(),
'prevmonthly_total': CHANNELS[38].read(),
'current_year_total': CHANNELS[39].read(),
'prev_year_total': CHANNELS[40].read()
}
log.info("Generating Spreadsheet")
generate_report(driver_id,trans_day,trans_hour,trans_min, trans_total, overall, company_1, company_2, company_3, company_4, company_5)
log.info("Sending Emails")
send_email(self.PERSIST['recipients'])
self.PERSIST['yesterday'] = dt.today().day
persistence.store(self.PERSIST)