Skip to content

Commit

Permalink
V1.19.01
Browse files Browse the repository at this point in the history
  • Loading branch information
jgyates committed Jan 27, 2024
1 parent 19c11fe commit 669a8b5
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 28 deletions.
4 changes: 2 additions & 2 deletions addon/genmopeka.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,12 +419,12 @@ def SendCommand(self, Command):
return data

# ----------GenMopekaData::SendMessage----------------------------------------
def SendMessage(self, title, body, type, onlyonce=False):
def SendMessage(self, title, body, type, onlyonce=False, oncedaily=False):

try:
if not self.send_notices:
return "disabled"
message = {"title": title, "body": body, "type": type, "onlyonce": onlyonce}
message = {"title": title, "body": body, "type": type, "onlyonce": onlyonce, "oncedaily": oncedaily}
command = "generator: notify_message=" + json.dumps(message)

data = self.SendCommand(command)
Expand Down
80 changes: 74 additions & 6 deletions addon/gentankutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ def __init__(
self.password = self.config.ReadValue("password", default="")
self.tank_name = self.config.ReadValue("tank_name", default="")
self.tank_name_2 = self.config.ReadValue("tank_name_2", default="")
self.check_battery = self.config.ReadValue("check_battery", return_type=bool, default=False)
self.check_reading = self.config.ReadValue("check_reading", return_type=bool, default=False)
self.reading_timeout = self.config.ReadValue("reading_timeout", return_type=int, default=50)

if self.MonitorAddress == None or not len(self.MonitorAddress):
self.MonitorAddress = ProgramDefaults.LocalHost
Expand Down Expand Up @@ -137,6 +140,21 @@ def __init__(
self.console.error("Error in GenTankData init: " + str(e1))
sys.exit(1)

# ----------GenMopekaData::SendMessage----------------------------------------
def SendMessage(self, title, body, type, onlyonce=False, oncedaily=False):

try:
if not self.check_battery and not self.check_reading:
return "disabled"
message = {"title": title, "body": body, "type": type, "onlyonce": onlyonce, "oncedaily": oncedaily}
command = "generator: notify_message=" + json.dumps(message)

data = self.SendCommand(command)
return data
except Exception as e1:
self.LogErrorLine("Error in SendMessage: " + str(e1))
return ""

# ---------- GenTankData::SendCommand --------------------------------------
def SendCommand(self, Command):

Expand Down Expand Up @@ -220,23 +238,73 @@ def TankCheckThread(self):
dataforgenmon["Tank Name"] = tankdata["name"]
dataforgenmon["Capacity"] = self.tank.GetCapacity()
dataforgenmon["Percentage"] = self.tank.GetPercentage()
self.LogDebug("Tank1 = " + json.dumps(tankdata))
dataforgenmon["Battery"] = self.tank.GetBattery()
dataforgenmon["Temperature"] = self.tank.GetReadingTemperature()
try:
epoch_time = self.tank.GetReadingEpochTime()
datetime_time = datetime.datetime.fromtimestamp(epoch_time / 1000)
dataforgenmon["Reading Time"] = str(datetime_time)
self.CheckTankResponse(tankdata["name"], datetime_time, self.tank.GetBattery())
except Exception as e1:
self.LogErrorLine("Error reading tank 1 reading time: " + str(e1))

#self.LogDebug("Tank1 = " + json.dumps(tankdata))
if len(self.TankID_2) != 0:
tankdata = self.tank.GetData(self.TankID_2)
self.LogDebug("Tank2 = " + json.dumps(tankdata))
dataforgenmon["Percentage2"] = self.tank.GetPercentage()

retVal = self.SendCommand(
"generator: set_tank_data=" + json.dumps(dataforgenmon)
)
self.LogDebug(retVal)
try:
epoch_time = self.tank.GetReadingEpochTime()
datetime_time = datetime.datetime.fromtimestamp(epoch_time / 1000)
dataforgenmon["Battery2"] = self.tank.GetBattery()
dataforgenmon["Reading Time2"] = str(datetime_time)
self.CheckTankResponse(tankdata["name"], datetime_time, self.tank.GetBattery())
except Exception as e1:
self.LogErrorLine("Error reading tank 2 reading time: " + str(e1))

retVal = self.SendCommand("generator: set_tank_data=" + json.dumps(dataforgenmon))
#self.LogDebug(retVal)
if self.WaitForExit("TankCheckThread", float(self.PollTime * 60)):
return
except Exception as e1:
self.LogErrorLine("Error in TankCheckThread: " + str(e1))
if self.WaitForExit("TankCheckThread", float(self.PollTime * 60)):
return

# ----------GenTankData::CheckTankResponse----------------------------------
def CheckTankResponse(self, tank_name, datetime_time, battery_string):
try:
if self.check_reading and self.CheckTimeDiffExpired(datetime_time, (60 * int(self.reading_timeout))): # default is 50 hours
msgbody = "Genmon Tankutil Warning: Tank Monitor Missed Update. Last update was " + str(datetime_time) + " for tank '" + tank_name + "'"
msgsubject = "Genmon Tankutil Tank Monitor Message: Reporting: " + tank_name
self.SendMessage(msgsubject, msgbody, "error", onlyonce=False, oncedaily=True)
self.LogDebug(msgsubject)
self.LogDebug(msgbody)

if self.check_battery and battery_string.lower() == "critical":
msgbody = "Warning: Tank Monitor Battery is : " + str(battery_string)
msgsubject = "Genmon Tankutil Tank Monitor Message: Battery: " + tank_name
self.SendMessage(msgsubject, msgbody, "error", onlyonce=False, oncedaily=True)
self.LogDebug(msgsubject)
self.LogDebug(msgbody)

except Exception as e1:
self.LogErrorLine("Error in CheckTanksReponse: " + str(e1))

#---------------------CheckTimeDiffExpired----------------------------------
# check that numner of minutes has expired since a given time
def CheckTimeDiffExpired(self, time, min):

try:
time_reference_seconds = min * 60.0
if (datetime.datetime.now() - time).total_seconds() > time_reference_seconds:
return True
else:
return False
except Exception as e1:
self.LogErrorLine("Error in CheckTimeDiffExpired: " + str(e1))
return True

# ----------GenTankData::SignalClose----------------------------------------
def SignalClose(self, signum, frame):

Expand Down
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ All notable changes to this project will be documented in this file.
- Add the ability to have minimum delay between short messages (e.g. callmebot signal)
- Minor update for Deepsea controller switch state
- More updates for ComAp controller
- Update to gentankutil to add option to check battery and missed readings. See Add On page to enable this functionality.

## V1.19.00 -2023-11-09
- Updates to genmonmain.sh, startgenmon.sh and genloader.sh for Debian bookworm.
Expand Down
39 changes: 19 additions & 20 deletions genmon.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,8 @@ def __init__(self, ConfigFilePath=ProgramDefaults.ConfPath):
self.SiteName = "Home"
self.ServerSocket = None
self.ServerIPAddress = ""
self.ServerSocketPort = (
ProgramDefaults.ServerPort
) # server socket for nagios heartbeat and command/status
# server socket for nagios heartbeat and command/status
self.ServerSocketPort = ProgramDefaults.ServerPort
self.IncomingEmailFolder = "Generator"
self.ProcessedEmailFolder = "Generator/Processed"

Expand All @@ -81,15 +80,14 @@ def __init__(self, ConfigFilePath=ProgramDefaults.ConfPath):
self.NumberOfLogSizeErrors = 0
# set defaults for optional parameters
self.NewInstall = False # True if newly installed or newly upgraded version
self.FeedbackEnabled = (
False # True if sending autoated feedback on missing information
)
# True if sending autoated feedback on missing information
self.FeedbackEnabled = False
self.FeedbackMessages = {}
self.OneTimeMessages = {}

self.MailInit = False # set to true once mail is init
self.CommunicationsActive = (
False # Flag to let the heartbeat thread know we are communicating
)
# Flag to let the heartbeat thread know we are communicating
self.CommunicationsActive = False

self.Controller = None
self.ControllerSelected = None
self.bDisablePlatformStats = False
Expand Down Expand Up @@ -210,13 +208,15 @@ def __init__(self, ConfigFilePath=ProgramDefaults.ConfPath):
"Feedback",
self.FeedbackReceiver,
log=self.log,
debug = self.debug,
ConfigFilePath=self.ConfigFilePath,
)
self.Threads = self.MergeDicts(self.Threads, self.FeedbackPipe.Threads)
self.MessagePipe = MyPipe(
"Message",
self.MessageReceiver,
log=self.log,
debug = self.debug,
nullpipe=self.mail.DisableSNMP,
ConfigFilePath=self.ConfigFilePath,
)
Expand Down Expand Up @@ -340,6 +340,8 @@ def GetConfig(self):
if self.config.HasOption("sitename"):
self.SiteName = self.config.ReadValue("sitename")

self.debug = self.config.ReadValue("debug", return_type=bool, default=False)

self.multi_instance = self.config.ReadValue(
"multi_instance", return_type=bool, default=False
)
Expand Down Expand Up @@ -518,15 +520,6 @@ def MessageReceiver(self, Message):
MessageDict = {}
MessageDict = json.loads(Message)

if MessageDict["onlyonce"]:
Subject = self.OneTimeMessages.get(MessageDict["subjectstr"], None)
if Subject == None:
self.OneTimeMessages[MessageDict["subjectstr"]] = MessageDict[
"msgstr"
]
else:
return

self.mail.sendEmail(
MessageDict["subjectstr"],
MessageDict["msgstr"],
Expand Down Expand Up @@ -738,6 +731,7 @@ def SendSupportInfo(self, SendLogs=True):
# ---------- Send message ---------------------------------------------------
def SendMessage(self, CmdString):
try:
self.LogDebug("ENTER SendMessage")
if CmdString == None or CmdString == "":
return "Error: invalid command in SendMessage"

Expand All @@ -755,8 +749,13 @@ def SendMessage(self, CmdString):
onlyonce = False
else:
onlyonce = data["onlyonce"]
if not "oncedaily" in data:
oncedaily = False
else:
oncedaily = data["oncedaily"]
self.LogDebug("SENDMSG:" + str(data))
self.MessagePipe.SendMessage(
msgtitle, data["body"], msgtype=data["type"], onlyonce=onlyonce
msgtitle, data["body"], msgtype=data["type"], onlyonce=onlyonce, oncedaily=oncedaily
)
return "OK"
except Exception as e1:
Expand Down
33 changes: 33 additions & 0 deletions genmonlib/mypipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import os
import threading
import time
import datetime

from genmonlib.mysupport import MySupport
from genmonlib.mythread import MyThread
Expand All @@ -28,18 +29,26 @@ def __init__(
callback=None,
Reuse=False,
log=None,
debug=False,
simulation=False,
nullpipe=False,
ConfigFilePath=ProgramDefaults.ConfPath,
):
super(MyPipe, self).__init__(simulation=simulation)
self.log = log
self.debug = debug
self.BasePipeName = name
self.NullPipe = nullpipe

if self.Simulation:
return

# refernce time for resetting daily messages
self.DailyTime = datetime.datetime.now()
# dict for holding one time messages
self.OneTimeMessages = {}
# list for subject of daily
self.DailyMessages = []
self.ThreadName = "ReadPipeThread" + self.BasePipeName
self.Callback = callback

Expand Down Expand Up @@ -139,6 +148,7 @@ def SendMessage(
deletefile=False,
msgtype="error",
onlyonce=False,
oncedaily=False
):

if self.Simulation:
Expand All @@ -152,6 +162,24 @@ def SendMessage(
MessageDict["deletefile"] = deletefile
MessageDict["msgtype"] = msgtype
MessageDict["onlyonce"] = onlyonce
MessageDict["oncedaily"] = oncedaily

if MessageDict["onlyonce"]:
Subject = self.OneTimeMessages.get(MessageDict["subjectstr"], None)
if Subject == None:
# have not sent it so add it to the list
self.OneTimeMessages[MessageDict["subjectstr"]] = MessageDict["msgstr"]
else:
return # already sent this once

#NUMBER_OF_SECONDS = 86400
NUMBER_OF_SECONDS = 60 * 60 * 24 # every 24 hours
if (datetime.datetime.now() - self.DailyTime).total_seconds() > NUMBER_OF_SECONDS:
self.ResetDailyFilter()
if oncedaily and subjectstr in self.DailyMessages:
return
if oncedaily:
self.DailyMessages.append(subjectstr)

data = json.dumps(MessageDict, sort_keys=False)
self.WriteFile(data)
Expand All @@ -160,6 +188,11 @@ def SendMessage(
"Error in SendMessage: <" + (str(subjectstr)) + "> : " + str(e1)
)

#---------------------ResetEmailFilter--------------------------------------
def ResetDailyFilter(self):
self.DailyTime = datetime.datetime.now()
self.DailyMessages = []
return
# ------------ MyPipe::Close-------------------------------------------------
def Close(self):

Expand Down
20 changes: 20 additions & 0 deletions genserv.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ def CheckLockOutDuration():
"title": "Security Warning",
"body": "Genmon login is locked due to exceeding the maximum login attempts.",
"type": "error",
"oncedaily": False,
"onlyonce": False,
}
command = "generator: notify_message=" + json.dumps(message)

Expand Down Expand Up @@ -1660,6 +1662,24 @@ def GetAddOns():
bounds="number",
display_name="Poll Frequency",
)
AddOnCfg["gentankutil"]["parameters"]["check_battery"] = CreateAddOnParam(
ConfigFiles[GENTANKUTIL_CONFIG].ReadValue(
"check_battery", return_type=bool, default=False
),
"boolean",
"If enabled, and email will be sent if the battery level on the sensor is critical. Outbound email must be enabled for this to function.",
bounds="",
display_name="Check Sensor Battery",
)
AddOnCfg["gentankutil"]["parameters"]["check_reading"] = CreateAddOnParam(
ConfigFiles[GENTANKUTIL_CONFIG].ReadValue(
"check_reading", return_type=bool, default=False
),
"boolean",
"If enabled, and email will be sent if the sensor has not performed a reading within 50 hours. Outbound email must be enabled for this to function.",
bounds="",
display_name="Check Sensor Battery",
)

# GENTANKDIY
AddOnCfg["gentankdiy"] = collections.OrderedDict()
Expand Down

0 comments on commit 669a8b5

Please sign in to comment.