Fixes for common logger object

This commit is contained in:
Patrick McDonagh
2018-07-03 15:19:08 -05:00
parent 21cc94c919
commit 7c690affb5
5 changed files with 44 additions and 37 deletions

View File

@@ -2,6 +2,9 @@
import time import time
from pycomm.ab_comm.clx import Driver as ClxDriver from pycomm.ab_comm.clx import Driver as ClxDriver
from pycomm.cip.cip_base import CommError, DataError from pycomm.cip.cip_base import CommError, DataError
from file_logger import filelogger as log
TAG_DATAERROR_SLEEPTIME = 5 TAG_DATAERROR_SLEEPTIME = 5
@@ -25,15 +28,14 @@ def read_tag(addr, tag, plc_type="CLX"):
except DataError as err: except DataError as err:
clx.close() clx.close()
time.sleep(TAG_DATAERROR_SLEEPTIME) time.sleep(TAG_DATAERROR_SLEEPTIME)
print("Data Error during readTag({}, {}): {}".format(addr, tag, err)) log.error("Data Error during readTag({}, {}): {}".format(addr, tag, err))
except CommError: except CommError:
# err = c.get_status() # err = c.get_status()
clx.close() clx.close()
print("Could not connect during readTag({}, {})".format(addr, tag)) log.error("Could not connect during readTag({}, {})".format(addr, tag))
# print err
except AttributeError as err: except AttributeError as err:
clx.close() clx.close()
print("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err)) log.error("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
clx.close() clx.close()
return False return False
@@ -48,19 +50,17 @@ def read_array(addr, tag, start, end, plc_type="CLX"):
for i in range(start, end): for i in range(start, end):
tag_w_index = tag + "[{}]".format(i) tag_w_index = tag + "[{}]".format(i)
val = clx.read_tag(tag_w_index) val = clx.read_tag(tag_w_index)
# print('{} - {}'.format(tag_w_index, v))
arr_vals.append(round(val[0], 4)) arr_vals.append(round(val[0], 4))
# print(v)
if arr_vals: if arr_vals:
return arr_vals return arr_vals
else: else:
print("No length for {}".format(addr)) log.error("No length for {}".format(addr))
return False return False
except Exception: except Exception:
print("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end)) log.error("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
err = clx.get_status() err = clx.get_status()
clx.close() clx.close()
print(err) log.error(err)
clx.close() clx.close()
@@ -68,18 +68,22 @@ def write_tag(addr, tag, val, plc_type="CLX"):
"""Write a tag value to the PLC.""" """Write a tag value to the PLC."""
direct = plc_type == "Micro800" direct = plc_type == "Micro800"
clx = ClxDriver() clx = ClxDriver()
if clx.open(addr, direct_connection=direct): try:
try: if clx.open(addr, direct_connection=direct):
initial_val = clx.read_tag(tag) try:
print(initial_val) initial_val = clx.read_tag(tag)
write_status = clx.write_tag(tag, val, initial_val[1]) write_status = clx.write_tag(tag, val, initial_val[1])
return write_status return write_status
except Exception: except DataError as err:
print("Error during writeTag({}, {}, {})".format(addr, tag, val)) clx_err = clx.get_status()
err = clx.get_status() clx.close()
clx.close() log.error("--\nDataError during writeTag({}, {}, {}, plc_type={}) -- {}\n{}\n".format(addr, tag, val, plc_type, err, clx_err))
print err
except CommError as err:
clx_err = clx.get_status()
log.error("--\nCommError during write_tag({}, {}, {}, plc_type={})\n{}\n--".format(addr, tag, val, plc_type, err))
clx.close() clx.close()
return False
class Channel(object): class Channel(object):
@@ -148,12 +152,12 @@ class Channel(object):
try: try:
self.value = self.map_[new_value] self.value = self.map_[new_value]
except KeyError: except KeyError:
print("Cannot find a map value for {} in {} for {}".format(new_value, self.map_, self.mesh_name)) log.error("Cannot find a map value for {} in {} for {}".format(new_value, self.map_, self.mesh_name))
self.value = new_value self.value = new_value
else: else:
self.value = new_value self.value = new_value
self.last_send_time = time.time() self.last_send_time = time.time()
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason)) log.info("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed return send_needed
def read(self): def read(self):
@@ -246,7 +250,7 @@ class BoolArrayChannels(Channel):
if new_val_dict[idx] != self.last_value[idx]: if new_val_dict[idx] != self.last_value[idx]:
send = True send = True
except KeyError: except KeyError:
print("Key Error in self.compare_values for index {}".format(idx)) log.error("Key Error in self.compare_values for index {}".format(idx))
send = True send = True
return send return send
@@ -263,7 +267,7 @@ class BoolArrayChannels(Channel):
try: try:
new_val[self.map_[idx]] = bool_arr[idx] new_val[self.map_[idx]] = bool_arr[idx]
except KeyError: except KeyError:
print("Not able to get value for index {}".format(idx)) log.error("Not able to get value for index {}".format(idx))
if self.last_send_time == 0: if self.last_send_time == 0:
send_needed = True send_needed = True
@@ -285,5 +289,5 @@ class BoolArrayChannels(Channel):
self.value = new_val self.value = new_val
self.last_value = self.value self.last_value = self.value
self.last_send_time = time.time() self.last_send_time = time.time()
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason)) log.info("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed return send_needed

View File

@@ -6,6 +6,7 @@
"files": { "files": {
"file1": "multisensor.py", "file1": "multisensor.py",
"file2": "utilities.py", "file2": "utilities.py",
"file3": "Channel.py" "file3": "channel.py",
"file4": "file_logger.py"
} }
} }

View File

@@ -1,11 +1,11 @@
{ {
"name": "multisensor", "name": "multisensor",
"driverFilename": "multisensor.py", "driverFilename": "multisensor.py",
"driverId": "0000", "driverId": "0240",
"additionalDriverFiles": [ "additionalDriverFiles": [
"utilities.py", "utilities.py",
"channel.py", "channel.py",
"logger.py" "file_logger.py"
], ],
"version": 1, "version": 1,
"s3BucketName": "multisensor" "s3BucketName": "multisensor"

View File

@@ -1,11 +1,11 @@
# LOGGING SETUP """Logging setup for multisensor"""
import logging import logging
import sys
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
import sys
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s') log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logFile = './multisensor.log' log_file = './multisensor.log'
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=500*1024, my_handler = RotatingFileHandler(log_file, mode='a', maxBytes=500*1024,
backupCount=2, encoding=None, delay=0) backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter) my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO) my_handler.setLevel(logging.INFO)

View File

@@ -8,11 +8,13 @@ from random import randint
from device_base import deviceBase from device_base import deviceBase
from channel import PLCChannel, read_tag, write_tag from channel import PLCChannel, read_tag, write_tag
from utilities import get_public_ip_address from utilities import get_public_ip_address
from logger import filelogger
from file_logger import filelogger as log
_ = None _ = None
filelogger.info("multisensor startup") # log = file_logger.setup()
log.info("multisensor startup")
# GLOBAL VARIABLES # GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 60 WAIT_FOR_CONNECTION_SECONDS = 60
@@ -84,7 +86,7 @@ class start(threading.Thread, deviceBase):
for i in range(0, WAIT_FOR_CONNECTION_SECONDS): for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
print("multisensor driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i)) print("multisensor driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
time.sleep(1) time.sleep(1)
filelogger.info("BOOM! Starting multisensor driver...") log.info("BOOM! Starting multisensor driver...")
self._check_watchdog() self._check_watchdog()
self._check_ip_address() self._check_ip_address()
@@ -98,7 +100,7 @@ class start(threading.Thread, deviceBase):
while True: while True:
now = time.time() now = time.time()
if self.force_send: if self.force_send:
filelogger.warning("FORCE SEND: TRUE") log.warning("FORCE SEND: TRUE")
for chan in CHANNELS: for chan in CHANNELS:
val = chan.read() val = chan.read()
@@ -109,7 +111,7 @@ class start(threading.Thread, deviceBase):
# print("multisensor driver still alive...") # print("multisensor driver still alive...")
if self.force_send: if self.force_send:
if send_loops > 2: if send_loops > 2:
filelogger.warning("Turning off force_send") log.warning("Turning off force_send")
self.force_send = False self.force_send = False
send_loops = 0 send_loops = 0
else: else: