Exemple #1
0
    def StartThreads(self, reload = False):

        try:
            # start thread to accept incoming sockets for nagios heartbeat
            self.Threads["ComWatchDog"] = MyThread(self.ComWatchDog, Name = "ComWatchDog")

            if self.bSyncDST or self.bSyncTime:     # Sync time thread
                self.Threads["TimeSyncThread"] = MyThread(self.TimeSyncThread, Name = "TimeSyncThread")

            if not self.DisableWeather and not self.WeatherAPIKey == None and len(self.WeatherAPIKey) and not self.WeatherLocation == None and len(self.WeatherLocation):
                Unit = 'metric' if self.UseMetric else 'imperial'
                self.MyWeather = MyWeather(self.WeatherAPIKey, location = self.WeatherLocation, unit = Unit, log = self.log)
                self.Threads = self.MergeDicts(self.Threads, self.MyWeather.Threads)
        except Exception as e1:
            self.LogErrorLine("Error in StartThreads: " + str(e1))
Exemple #2
0
    def __init__(self, config=None, log=None, callback=None):
        super(MyMsgQueue, self).__init__()
        self.log = log
        self.config = config
        self.callback = callback
        self.MessageQueue = []

        self.QueueLock = threading.RLock()

        self.max_retry_time = 600  # 10 min
        self.default_wait = 120  # 2 min
        self.debug = False

        if self.config != None:
            try:
                self.max_retry_time = self.config.ReadValue('max_retry_time',
                                                            return_type=int,
                                                            default=600)
                self.default_wait = self.config.ReadValue('default_wait',
                                                          return_type=int,
                                                          default=120)
                self.debug = self.config.ReadValue('debug',
                                                   return_type=bool,
                                                   default=False)

            except Exception as e1:
                self.LogErrorLine(
                    "Error in MyMsgQueue:init, error reading config: " +
                    str(e1))
        if not self.callback == None:
            self.Threads["QueueWorker"] = MyThread(self.QueueWorker,
                                                   Name="QueueWorker",
                                                   start=False)
            self.Threads["QueueWorker"].Start()
Exemple #3
0
    def StartReadThread(self):

        # start read thread to monitor incoming data commands
        self.Threads["SerialReadThread"] = MyThread(self.ReadThread,
                                                    Name="SerialReadThread")

        return self.Threads["SerialReadThread"]
Exemple #4
0
    def __init__(self, apikey, location, log = None, unit = 'imperial'):
        super(MyWeather, self).__init__()
        self.APIKey = apikey
        self.log = log
        self.Location = location
        self.OWM = None
        self.Observation = None
        self.WeatherUnit = unit
        self.WeatherData = None
        self.ObservationLocation = None
        self.DataAccessLock = threading.Lock()     # lock to synchronize access to WeatherData

        if not pyowm_installed:
            self.LogError("Library pyowm not installed, disabling weather support." )
            return
        try:
            if self.APIKey != None:
                self.APIKey = self.APIKey.strip()
            if self.Location != None:
                self.Location = self.Location.strip()

            if self.APIKey == None or not len(self.APIKey) or self.Location == None or not len(self.Location):
                self.LogError("Weather API key invalid or Weather Location invalid")
                return

            self.InitOWM()
            self.Threads["WeatherThread"] = MyThread(self.WeatherThread, Name = "WeatherThread")
        except Exception as e1:
            self.LogErrorLine("Error on MyWeather:init: " + str(e1))
Exemple #5
0
    def __init__(self,
                 host="127.0.0.1",
                 port=9082,
                 log=None,
                 callback=None,
                 polltime=None,
                 blacklist=None,
                 flush_interval=float('inf'),
                 use_numeric=False,
                 debug=False):

        super(MyGenPush, self).__init__()
        self.Callback = callback

        self.UseNumeric = use_numeric
        self.Debug = debug

        if polltime == None:
            self.PollTime = 3
        else:
            self.PollTime = float(polltime)

        if log != None:
            self.log = log
        else:
            # log errors in this module to a file
            self.log = SetupLogger("client", "/var/log/mygenpush.log")

        self.console = SetupLogger("mygenpush_console",
                                   log_file="",
                                   stream=True)

        self.AccessLock = threading.Lock()
        self.BlackList = blacklist
        self.LastValues = {}
        self.FlushInterval = flush_interval
        self.LastChange = {}

        try:
            startcount = 0
            while startcount <= 10:
                try:
                    self.Generator = ClientInterface(host=host, log=log)
                    break
                except Exception as e1:
                    startcount += 1
                    if startcount >= 10:
                        self.console.info("genmon not loaded.")
                        self.LogError("Unable to connect to genmon.")
                        sys.exit(1)
                    time.sleep(1)
                    continue
            # start thread to accept incoming sockets for nagios heartbeat
            self.Threads["PollingThread"] = MyThread(self.MainPollingThread,
                                                     Name="PollingThread")

        except Exception as e1:
            self.LogErrorLine("Error in mygenpush init: " + str(e1))
Exemple #6
0
    def __init__(self,
                host=ProgramDefaults.LocalHost,
                port=ProgramDefaults.ServerPort,
                log = None,
                loglocation = ProgramDefaults.LogPath,
                onready = None,
                onexercise = None,
                onrun = None,
                onrunmanual = None,
                onalarm = None,
                onservice = None,
                onoff = None,
                onmanual = None,
                onutilitychange = None,
                start = True,
                console = None):

        super(GenNotify, self).__init__()

        self.AccessLock = threading.Lock()
        self.Threads = {}
        self.LastEvent = None
        self.LastOutageStatus = None
        self.Events = {}            # Dict for handling events


        self.log = log
        self.console = console
        
        try:
            # init event callbacks
            if onready != None:
                self.Events["READY"] = onready
            if onexercise != None:
                self.Events["EXERCISING"] = onexercise
            if onrun != None:
                self.Events["RUNNING"] = onrun
            if onrunmanual != None:
                self.Events["RUNNING-MANUAL"] = onrunmanual
            if onalarm != None:
                self.Events["ALARM"] = onalarm
            if onservice != None:
                self.Events["SERVICEDUE"] = onservice
            if onoff != None:
                self.Events["OFF"] = onoff
            if onmanual != None:
                self.Events["MANUAL"] = onmanual
            if onutilitychange != None:
                self.Events["OUTAGE"] = onutilitychange


            self.Generator = ClientInterface(host = host, port = port, log = log, loglocation = loglocation)

            self.Threads["PollingThread"] = MyThread(self.MainPollingThread, Name = "PollingThread", start = start)
            self.Started = start
        except Exception as e1:
            self.LogErrorLine("Error in mynotify init: "  + str(e1))
Exemple #7
0
    def __init__(self,
                 updatecallback,
                 address=0x9d,
                 name="/dev/serial",
                 rate=9600,
                 config=None,
                 inputfile=None):

        super(ModbusFile, self).__init__(updatecallback=updatecallback,
                                         address=address,
                                         name=name,
                                         rate=rate,
                                         config=config)

        self.Address = address
        self.Rate = rate
        self.PortName = name
        self.InputFile = inputfile
        self.InitComplete = False
        self.UpdateRegisterList = updatecallback
        self.RxPacketCount = 0
        self.TxPacketCount = 0
        self.ComTimoutError = 0
        self.TotalElapsedPacketeTime = 0
        self.ComTimoutError = 0
        self.CrcError = 0
        self.SimulateTime = True

        self.ModbusStartTime = datetime.datetime.now()  # used for com metrics
        self.Registers = {}
        self.Strings = {}
        self.FileData = {}

        if self.InputFile == None:
            self.InputFile = os.path.dirname(
                os.path.realpath(__file__)) + "/modbusregs.txt"

        if not os.path.isfile(self.InputFile):
            self.LogError("Error: File not present: " + self.InputFile)
        self.CommAccessLock = threading.RLock(
        )  # lock to synchronize access to the serial port comms
        self.UpdateRegisterList = updatecallback

        if not self.ReadInputFile(self.InputFile):
            self.LogError("ModusFile Init(): Error loading input file: " +
                          self.InputFile)
        else:
            if not self.AdjustInputData():
                self.LogInfo("Error parsing input data")

            self.Threads["ReadInputFileThread"] = MyThread(
                self.ReadInputFileThread,
                Name="ReadInputFileThread",
                start=False)
            self.Threads["ReadInputFileThread"].Start()
        self.InitComplete = False
Exemple #8
0
    def __init__(self,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 log=None,
                 callback=None,
                 polltime=None,
                 blacklist=None,
                 flush_interval=float('inf'),
                 use_numeric=False,
                 debug=False,
                 loglocation=ProgramDefaults.LogPath,
                 console=None):

        super(MyGenPush, self).__init__()
        self.Callback = callback

        self.UseNumeric = use_numeric
        self.debug = debug
        self.Exiting = False

        if polltime == None:
            self.PollTime = 3
        else:
            self.PollTime = float(polltime)

        if log != None:
            self.log = log
        else:
            # log errors in this module to a file
            self.log = SetupLogger("client",
                                   os.path.join(loglocation, "mygenpush.log"))

        self.console = console

        self.AccessLock = threading.Lock()
        self.BlackList = blacklist
        self.LastValues = {}
        self.FlushInterval = flush_interval
        self.LastChange = {}

        try:
            self.Generator = ClientInterface(host=host, port=port, log=log)

            self.GetGeneratorStartInfo()
            # start thread to accept incoming sockets for nagios heartbeat
            self.Threads["MainPollingThread"] = MyThread(
                self.MainPollingThread, Name="MainPollingThread", start=False)
            self.Threads["MainPollingThread"].Start()

        except Exception as e1:
            self.LogErrorLine("Error in mygenpush init: " + str(e1))
Exemple #9
0
    def __init__(self,
                 gpio=None,
                 trigger=GPIO.FALLING,
                 resistorpull=GPIO.PUD_UP,
                 log=None,
                 callback=None,
                 uselibcallbacks=False,
                 bouncetime=None):
        super(MyGPIOInput, self).__init__()
        self.Trigger = trigger
        self.ResistorPull = resistorpull
        self.GPIO = gpio
        self.log = log
        self.TimeoutSeconds = 1
        self.BounceTime = bouncetime
        self.Callback = callback
        self.UseLibCallbacks = uselibcallbacks
        self.Exiting = False

        try:

            GPIO.setmode(GPIO.BOARD)
            GPIO.setwarnings(True)
            GPIO.setup(gpio, GPIO.IN, pull_up_down=resistorpull)

            if callback != None and callable(callback):
                if self.BounceTime > 0:
                    GPIO.add_event_detect(gpio=self.GPIO,
                                          edge=self.Trigger,
                                          bouncetime=self.BounceTime)
                else:
                    GPIO.add_event_detect(gpio=self.GPIO, edge=self.Trigger)
                if self.UseLibCallbacks:
                    GPIO.add_event_callback(gpio=self.GPIO,
                                            callback=self.Callback)
                else:
                    # setup callback
                    self.Threads["GPIOInputMonitor"] = MyThread(
                        self.GPIOInputMonitor,
                        Name="GPIOInputMonitor",
                        start=False)
                    self.Threads["GPIOInputMonitor"].Start()

        except Exception as e1:
            self.LogErrorLine("Error in MyGPIOInput:init: " + str(gpio) +
                              " : " + str(e1))
Exemple #10
0
    def __init__(self,
                 name,
                 callback=None,
                 Reuse=False,
                 log=None,
                 simulation=False,
                 nullpipe=False,
                 ConfigFilePath=ProgramDefaults.ConfPath):
        super(MyPipe, self).__init__(simulation=simulation)
        self.log = log
        self.BasePipeName = name
        self.NullPipe = nullpipe

        if self.Simulation:
            return

        self.ThreadName = "ReadPipeThread" + self.BasePipeName
        self.Callback = callback

        self.FileAccessLock = threading.RLock()

        self.FileName = os.path.join(ConfigFilePath,
                                     self.BasePipeName + "_dat")

        try:
            if not Reuse:
                try:
                    os.remove(self.FileName)
                except:
                    pass
                with open(self.FileName, 'w') as f:  # create empty file
                    f.write("")

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

        if self.NullPipe or not self.Callback == None or not self.Simulation:
            self.Threads[self.ThreadName] = MyThread(self.ReadPipeThread,
                                                     Name=self.ThreadName)
Exemple #11
0
    def __init__(self,
        log = None,
        loglocation = ProgramDefaults.LogPath,
        ConfigFilePath = MyCommon.DefaultConfPath,
        host = ProgramDefaults.LocalHost,
        port = ProgramDefaults.ServerPort,
        console = None):

        super(GenTankData, self).__init__()

        self.LogFileName = os.path.join(loglocation, "gentankutil.log")
        self.AccessLock = threading.Lock()

        self.log = log
        self.console = console

        self.MonitorAddress = host
        self.PollTime =  2
        self.TankID = ""
        self.debug = False
        configfile = os.path.join(ConfigFilePath, 'gentankutil.conf')
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename = configfile, section = 'gentankutil', log = self.log)

            self.PollTime = self.config.ReadValue('poll_frequency', return_type = float, default = 60)
            self.debug = self.config.ReadValue('debug', return_type = bool, default = False)
            self.username = self.config.ReadValue('username', default = "")
            self.password = self.config.ReadValue('password', default = "")
            self.tank_name = self.config.ReadValue('tank_name', default = "")

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        if self.username == "" or self.username == None or self.password == "" or self.password == None:
            self.LogError("Invalid user name or password, exiting")
            sys.exit(1)

        try:
            self.Generator = ClientInterface(host = self.MonitorAddress, port = port, log = self.log)

            #if not self.CheckGeneratorRequirement():
            #    self.LogError("Requirements not met. Exiting.")
            #    sys.exit(1)

            self.tank = tankutility(self.username, self.password, self.log, debug = self.debug)
            # start thread monitor time for exercise
            self.Threads["TankCheckThread"] = MyThread(self.TankCheckThread, Name = "TankCheckThread", start = False)
            self.Threads["TankCheckThread"].Start()

            signal.signal(signal.SIGTERM, self.SignalClose)
            signal.signal(signal.SIGINT, self.SignalClose)

        except Exception as e1:
            self.LogErrorLine("Error in GenTankData init: " + str(e1))
            self.console.error("Error in GenTankData init: " + str(e1))
            sys.exit(1)
Exemple #12
0
    def __init__(self,
                 host="127.0.0.1",
                 port=9082,
                 log=None,
                 onready=None,
                 onexercise=None,
                 onrun=None,
                 onrunmanual=None,
                 onalarm=None,
                 onservice=None,
                 onoff=None,
                 onmanual=None,
                 onutilitychange=None):

        super(GenNotify, self).__init__()

        self.AccessLock = threading.Lock()
        self.Threads = {}
        self.LastEvent = None
        self.LastOutageStatus = None
        self.Events = {}  # Dict for handling events

        if log != None:
            self.log = log
        else:
            # log errors in this module to a file
            self.log = SetupLogger("client", "/var/log/myclient.log")

        self.console = SetupLogger("notify_console", log_file="", stream=True)
        try:
            # init event callbacks
            if onready != None:
                self.Events["READY"] = onready
            if onexercise != None:
                self.Events["EXERCISING"] = onexercise
            if onrun != None:
                self.Events["RUNNING"] = onrun
            if onrunmanual != None:
                self.Events["RUNNING-MANUAL"] = onrunmanual
            if onalarm != None:
                self.Events["ALARM"] = onalarm
            if onservice != None:
                self.Events["SERVICEDUE"] = onservice
            if onoff != None:
                self.Events["OFF"] = onoff
            if onmanual != None:
                self.Events["MANUAL"] = onmanual
            if onutilitychange != None:
                self.Events["OUTAGE"] = onutilitychange

            startcount = 0
            while startcount <= 10:
                try:
                    self.Generator = ClientInterface(host=host, log=log)
                    break
                except Exception as e1:
                    startcount += 1
                    if startcount >= 10:
                        self.console.info("genmon not loaded.")
                        sys.exit(1)
                    time.sleep(1)
                    continue

            # start thread to accept incoming sockets for nagios heartbeat
            self.Threads["PollingThread"] = MyThread(self.MainPollingThread,
                                                     Name="PollingThread")
        except Exception as e1:
            self.LogErrorLine("Error in mynotify init: " + str(e1))
Exemple #13
0
    def __init__(self,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 onready=None,
                 onexercise=None,
                 onrun=None,
                 onrunmanual=None,
                 onalarm=None,
                 onservice=None,
                 onoff=None,
                 onmanual=None,
                 onutilitychange=None,
                 onsoftwareupdate=None,
                 onsystemhealth=None,
                 onfuelstate=None,
                 start=True,
                 console=None,
                 notify_outage=True,
                 notify_error=True,
                 notify_warning=True,
                 notify_info=True,
                 notify_sw_update=True,
                 config=None):

        super(GenNotify, self).__init__()

        self.AccessLock = threading.Lock()
        self.Threads = {}
        self.LastEvent = None
        self.LastOutageStatus = None
        self.LastSoftwareUpdateStatus = None
        self.LastSystemHealth = None
        self.LastFuelWarningStatus = True
        self.Events = {}  # Dict for handling events
        self.notify_outage = notify_outage
        self.notify_error = notify_error
        self.notify_warning = notify_warning
        self.notify_info = notify_info
        self.notify_sw_update = notify_sw_update
        self.config = config

        self.log = log
        self.console = console

        try:

            # get settings from config file if supplied
            if self.config != None:
                self.notify_outage = self.config.ReadValue('notify_outage',
                                                           return_type=bool,
                                                           default=True)
                self.notify_error = self.config.ReadValue('notify_error',
                                                          return_type=bool,
                                                          default=True)
                self.notify_warning = self.config.ReadValue('notify_warning',
                                                            return_type=bool,
                                                            default=True)
                self.notify_info = self.config.ReadValue('notify_info',
                                                         return_type=bool,
                                                         default=True)
                self.notify_sw_update = self.config.ReadValue(
                    'notify_sw_update', return_type=bool, default=True)

            # init event callbacks
            if onready != None and self.notify_info:
                self.Events["READY"] = onready
            if onexercise != None and self.notify_info:
                self.Events["EXERCISING"] = onexercise
            if onrun != None and self.notify_info:
                self.Events["RUNNING"] = onrun
            if onrunmanual != None and self.notify_info:
                self.Events["RUNNING-MANUAL"] = onrunmanual
            if onalarm != None and self.notify_error:
                self.Events["ALARM"] = onalarm
            if onservice != None and self.notify_warning:
                self.Events["SERVICEDUE"] = onservice
            if onoff != None and self.notify_info:
                self.Events["OFF"] = onoff
            if onmanual != None and self.notify_info:
                self.Events["MANUAL"] = onmanual
            if onutilitychange != None and self.notify_outage:
                self.Events["OUTAGE"] = onutilitychange
            if onsoftwareupdate != None and self.notify_sw_update:
                self.Events["SOFTWAREUPDATE"] = onsoftwareupdate
            if onsystemhealth != None:
                self.Events["SYSTEMHEALTH"] = onsystemhealth
            if onfuelstate != None and self.notify_warning:
                self.Events["FUELWARNING"] = onfuelstate

            self.Generator = ClientInterface(host=host,
                                             port=port,
                                             log=log,
                                             loglocation=loglocation)

            self.Threads["PollingThread"] = MyThread(self.MainPollingThread,
                                                     Name="PollingThread",
                                                     start=start)
            self.Started = start
        except Exception as e1:
            self.LogErrorLine("Error in mynotify init: " + str(e1))
Exemple #14
0
    def __init__(self,
                 monitor=False,
                 incoming_folder=None,
                 processed_folder=None,
                 incoming_callback=None,
                 localinit=False,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath="/etc/",
                 log=None,
                 start=True):

        self.Monitor = monitor  # true if we receive IMAP email
        self.IncomingFolder = incoming_folder  # folder to look for incoming email
        self.ProcessedFolder = processed_folder  # folder to move mail to once processed
        self.IncomingCallback = incoming_callback  # called back with mail subject as a parameter
        if ConfigFilePath == None or ConfigFilePath == "":
            self.ConfigFilePath = "/etc/"
        else:
            self.ConfigFilePath = ConfigFilePath
        self.Mailbox = 0
        self.EmailSendQueue = []  # queue for email to send
        self.DisableEmail = False
        self.DisableIMAP = False
        self.DisableSNMP = False
        self.DisableSmtpAuth = False
        self.SSLEnabled = False
        self.TLSDisable = False
        self.UseBCC = False
        self.ExtendWait = 0
        self.Threads = {}  # Dict of mythread objects
        self.debug = False
        self.ModulePath = os.path.dirname(
            os.path.dirname(os.path.realpath(__file__)))
        # log errors in this module to a file
        if localinit == True:
            self.logfile = "mymail.log"
            self.configfile = "mymail.conf"
        else:
            self.logfile = os.path.join(loglocation, "mymail.log")
            self.configfile = os.path.join(self.ConfigFilePath, "mymail.conf")

        if log == None:
            self.log = SetupLogger("mymail", self.logfile)
        else:
            self.log = log

        # if mymail.conf is present attempt to copy it from the
        # main source directory
        if not os.path.isfile(self.configfile):
            if os.path.join(os.path.isfile(self.ModulePath, "mymail.conf")):
                copyfile(os.path.join(self.ModulePath, "mymail.conf"),
                         self.configfile)
            else:
                self.LogError("Missing config file : " + self.configfile)
                sys.exit(1)

        self.config = MyConfig(filename=self.configfile,
                               section="MyMail",
                               log=self.log)

        self.GetConfig()

        if self.DisableEmail:
            self.DisableIMAP = True
            self.DisableSNMP = True
            self.Monitor = False

        if not len(self.SMTPServer):
            self.DisableSNMP = True

        if not len(self.IMAPServer):
            self.DisableIMAP = True
            self.Monitor = False

        atexit.register(self.Close)

        if not self.DisableEmail:
            if not self.DisableSMTP and self.SMTPServer != "":
                self.Threads["SendMailThread"] = MyThread(
                    self.SendMailThread, Name="SendMailThread", start=start)
            else:
                self.LogError("SMTP disabled")

            if not self.DisableIMAP and self.Monitor and self.IMAPServer != "":  # if True then we will have an IMAP monitor thread
                if incoming_callback and incoming_folder and processed_folder:
                    self.Threads["EmailCommandThread"] = MyThread(
                        self.EmailCommandThread,
                        Name="EmailCommandThread",
                        start=start)
                else:
                    self.FatalError(
                        "ERROR: incoming_callback, incoming_folder and processed_folder are required if receive IMAP is used"
                    )
            else:
                self.LogError("IMAP disabled")
Exemple #15
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 console=None):

        super(GenCTHat, self).__init__()

        #https://tutorials-raspberrypi.com/mcp3008-read-out-analog-signals-on-the-raspberry-pi/
        #https://forums.raspberrypi.com/viewtopic.php?t=237182

        self.LogFileName = os.path.join(loglocation, "gencthat.log")
        self.AccessLock = threading.Lock()

        self.log = log
        self.console = console

        self.MonitorAddress = host
        self.PollTime = 2
        self.SampleTimeMS = 34
        self.debug = False
        self.ConfigFileName = 'gencthat.conf'
        configfile = os.path.join(ConfigFilePath, self.ConfigFileName)
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename=configfile,
                                   section='gencthat',
                                   log=self.log)

            self.Multiplier = self.config.ReadValue('multiplier',
                                                    return_type=float,
                                                    default=0.488)
            # this checks to see if an old version of the conf file is in use and replaces it
            if self.Multiplier == 0.218:
                self.ConfPath = os.path.join(
                    os.path.dirname(os.path.realpath(__file__)), "conf")
                if os.path.isfile(
                        os.path.join(self.ConfPath, self.ConfigFileName)):
                    copyfile(os.path.join(self.ConfPath, self.ConfigFileName),
                             configfile)
                    self.LogError(
                        "Copied " +
                        os.path.join(self.ConfPath, self.ConfigFileName) +
                        " to " + configfile)
                    self.config = MyConfig(filename=configfile,
                                           section='gencthat',
                                           log=self.log)
                else:
                    self.LogError(
                        "Error: unable to find config file: " +
                        os.path.join(self.ConfPath, self.ConfigFileName))

            self.SampleTimeMS = self.config.ReadValue('sample_time_ms',
                                                      return_type=int,
                                                      default=34)
            self.Multiplier = self.config.ReadValue('multiplier',
                                                    return_type=float,
                                                    default=0.488)
            self.PollTime = self.config.ReadValue('poll_frequency',
                                                  return_type=float,
                                                  default=60)
            self.powerfactor = self.config.ReadValue('powerfactor',
                                                     return_type=float,
                                                     default=1.0)
            self.bus = self.config.ReadValue('bus', return_type=int, default=1)
            self.device = self.config.ReadValue('device',
                                                return_type=int,
                                                default=0)
            self.strict = self.config.ReadValue('strict',
                                                return_type=bool,
                                                default=False)
            self.singlelegthreshold = self.config.ReadValue(
                'singlelegthreshold', return_type=float, default=0.6)
            self.debug = self.config.ReadValue('debug',
                                               return_type=bool,
                                               default=False)

            self.LogDebug("Multiplier: " + str(self.Multiplier))
            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        try:

            self.adc = MCP3008(bus=self.bus, device=self.device, log=self.log)
            self.adc.open()

            self.Generator = ClientInterface(host=self.MonitorAddress,
                                             port=port,
                                             log=self.log)

            #if not self.CheckGeneratorRequirement():
            #    self.LogError("Requirements not met. Exiting.")
            #    sys.exit(1)

            # start thread monitor time for exercise
            self.Threads["SensorCheckThread"] = MyThread(
                self.SensorCheckThread, Name="SensorCheckThread", start=False)
            self.Threads["SensorCheckThread"].Start()

            signal.signal(signal.SIGTERM, self.SignalClose)
            signal.signal(signal.SIGINT, self.SignalClose)

        except Exception as e1:
            self.LogErrorLine("Error in GenCTHat init: " + str(e1))
            self.console.error("Error in GenCTHat init: " + str(e1))
            sys.exit(1)
Exemple #16
0
    def StartTimeThread(self):

        # This is done is a separate thread as not to block any return email processing
        # since we attempt to sync with generator time
        MyThread(self.Controller.SetGeneratorTimeDate, Name = "SetTimeThread")
        return "Time Set: Command Sent\n"
Exemple #17
0
    def __init__(self, ConfigFilePath = ProgramDefaults.ConfPath):
        super(Monitor, self).__init__()

        self.ProgramName = "Generator Monitor"
        self.Version = "Unknown"
        self.log = None
        self.IsStopping = False
        self.ProgramComplete = False
        if ConfigFilePath == None or ConfigFilePath == "":
            self.ConfigFilePath = ProgramDefaults.ConfPath
        else:
            self.ConfigFilePath = ConfigFilePath

        self.ConnectionList = []    # list of incoming connections for heartbeat
        # defautl values
        self.SiteName = "Home"
        self.ServerSocket = None
        self.ServerSocketPort = ProgramDefaults.ServerPort    # server socket for nagios heartbeat and command/status
        self.IncomingEmailFolder = "Generator"
        self.ProcessedEmailFolder = "Generator/Processed"

        self.FeedbackLogFile = self.ConfigFilePath + "feedback.json"
        self.LogLocation = ProgramDefaults.LogPath
        self.LastLogFileSize = 0
        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
        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
        self.Controller = None
        self.ControllerSelected = None
        self.bDisablePlatformStats = False
        self.ReadOnlyEmailCommands = False
        self.SlowCPUOptimization = False
        # weather parameters
        self.WeatherAPIKey = None
        self.WeatherLocation = None
        self.UseMetric = False
        self.WeatherMinimum = True
        self.DisableWeather = False
        self.MyWeather = None

        # Time Sync Related Data
        self.bSyncTime = False          # Sync gen to system time
        self.bSyncDST = False           # sync time at DST change
        self.bDST = False               # Daylight Savings Time active if True
        # simulation
        self.Simulation = False
        self.SimulationFile = None

        self.console = SetupLogger("genmon_console", log_file = "", stream = True)

        if os.geteuid() != 0:
            self.LogConsole("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'.")
            sys.exit(1)

        if not os.path.isfile(self.ConfigFilePath + 'genmon.conf'):
            self.LogConsole("Missing config file : " + self.ConfigFilePath + 'genmon.conf')
            sys.exit(1)
        if not os.path.isfile(self.ConfigFilePath + 'mymail.conf'):
            self.LogConsole("Missing config file : " + self.ConfigFilePath + 'mymail.conf')
            sys.exit(1)

        self.config = MyConfig(filename = self.ConfigFilePath + 'genmon.conf', section = "GenMon", log = self.console)
        # read config file
        if not self.GetConfig():
            self.LogConsole("Failure in Monitor GetConfig")
            sys.exit(1)

        # log errors in this module to a file
        self.log = SetupLogger("genmon", self.LogLocation + "genmon.log")

        self.config.log = self.log

        if self.IsLoaded():
            self.LogConsole("ERROR: genmon.py is already loaded.")
            self.LogError("ERROR: genmon.py is already loaded.")
            sys.exit(1)


        if self.NewInstall:
            self.LogError("New version detected: Old = %s, New = %s" % (self.Version, GENMON_VERSION))
            self.Version = GENMON_VERSION

        self.ProgramStartTime = datetime.datetime.now()     # used for com metrics
        self.LastSofwareUpdateCheck = datetime.datetime.now()

        atexit.register(self.Close)
        signal.signal(signal.SIGTERM, self.Close)
        signal.signal(signal.SIGINT, self.Close)

        # start thread to accept incoming sockets for nagios heartbeat and command / status clients
        self.Threads["InterfaceServerThread"] = MyThread(self.InterfaceServerThread, Name = "InterfaceServerThread")

        # init mail, start processing incoming email
        self.mail = MyMail(monitor=True, incoming_folder = self.IncomingEmailFolder,
            processed_folder =self.ProcessedEmailFolder,incoming_callback = self.ProcessCommand,
            loglocation = self.LogLocation, ConfigFilePath = ConfigFilePath)

        self.Threads = self.MergeDicts(self.Threads, self.mail.Threads)
        self.MailInit = True

        self.FeedbackPipe = MyPipe("Feedback", self.FeedbackReceiver,
            log = self.log, ConfigFilePath = self.ConfigFilePath)
        self.Threads = self.MergeDicts(self.Threads, self.FeedbackPipe.Threads)
        self.MessagePipe = MyPipe("Message", self.MessageReceiver, log = self.log,
            nullpipe = self.mail.DisableSNMP, ConfigFilePath = self.ConfigFilePath)
        self.Threads = self.MergeDicts(self.Threads, self.MessagePipe.Threads)

        try:
            #Starting device connection
            if self.Simulation:
                self.LogError("Simulation Running")
            if not self.ControllerSelected == None and len(self.ControllerSelected):
                self.LogError("Selected Controller: " + str(self.ControllerSelected))
            else:
                self.ControllerSelected = "generac_evo_nexus"

            if self.ControllerSelected.lower() == "h_100" :
                self.Controller = HPanel(self.log, newinstall = self.NewInstall, simulation = self.Simulation, simulationfile = self.SimulationFile, message = self.MessagePipe, feedback = self.FeedbackPipe, config = self.config)
            else:
                self.Controller = Evolution(self.log, self.NewInstall, simulation = self.Simulation, simulationfile = self.SimulationFile, message = self.MessagePipe, feedback = self.FeedbackPipe, config = self.config)
            self.Threads = self.MergeDicts(self.Threads, self.Controller.Threads)

        except Exception as e1:
            self.LogErrorLine("Error opening controller device: " + str(e1))
            sys.exit(1)


        self.StartThreads()

        self.ProcessFeedbackInfo()

        # send mail to tell we are starting
        self.MessagePipe.SendMessage("Generator Monitor Starting at " + self.SiteName, "Generator Monitor Starting at " + self.SiteName , msgtype = "info")

        self.LogError("GenMon Loaded for site: " + self.SiteName)
Exemple #18
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort):

        super(GenTankData, self).__init__()

        self.LogFileName = os.path.join(loglocation, "gentankdiy.log")
        self.AccessLock = threading.Lock()
        # log errors in this module to a file
        self.log = SetupLogger("gentankdiy", self.LogFileName)

        self.console = SetupLogger("gentankdiy_console",
                                   log_file="",
                                   stream=True)

        self.MonitorAddress = host
        self.PollTime = 2
        self.debug = False

        configfile = os.path.join(ConfigFilePath, 'gentankdiy.conf')
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename=configfile,
                                   section='gentankdiy',
                                   log=self.log)

            self.PollTime = self.config.ReadValue('poll_frequency',
                                                  return_type=float,
                                                  default=60)
            self.debug = self.config.ReadValue('debug',
                                               return_type=bool,
                                               default=False)
            self.i2c_address = self.config.ReadValue('i2c_address',
                                                     return_type=int,
                                                     default=72)
            self.mv_per_step = self.config.ReadValue('mv_per_step',
                                                     return_type=int,
                                                     default=125)
            self.Multiplier = self.config.ReadValue(
                'volts_to_percent_multiplier', return_type=float, default=20.0)
            # I2C channel 1 is connected to the GPIO pins
            self.i2c_channel = self.config.ReadValue('i2c_channel',
                                                     return_type=int,
                                                     default=1)

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        try:

            try:
                startcount = 0
                while startcount <= 10:
                    try:
                        self.Generator = ClientInterface(
                            host=self.MonitorAddress, port=port, log=self.log)
                        break
                    except Exception as e1:
                        startcount += 1
                        if startcount >= 10:
                            self.console.info("genmon not loaded.")
                            self.LogError("Unable to connect to genmon.")
                            sys.exit(1)
                        time.sleep(1)
                        continue

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

            # start thread monitor time for exercise
            self.Threads["TankCheckThread"] = MyThread(self.TankCheckThread,
                                                       Name="TankCheckThread",
                                                       start=False)

            if not self.InitADC():
                self.LogError("InitADC failed, exiting")
                sys.exit(1)

            self.Threads["TankCheckThread"].Start()

            atexit.register(self.Close)
            signal.signal(signal.SIGTERM, self.Close)
            signal.signal(signal.SIGINT, self.Close)

        except Exception as e1:
            self.LogErrorLine("Error in GenTankData init: " + str(e1))
            self.console.error("Error in GenTankData init: " + str(e1))
            sys.exit(1)
Exemple #19
0
    def __init__(self,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 onready=None,
                 onexercise=None,
                 onrun=None,
                 onrunmanual=None,
                 onalarm=None,
                 onservice=None,
                 onoff=None,
                 onmanual=None,
                 onutilitychange=None,
                 start=True):

        super(GenNotify, self).__init__()

        self.AccessLock = threading.Lock()
        self.Threads = {}
        self.LastEvent = None
        self.LastOutageStatus = None
        self.Events = {}  # Dict for handling events

        if log != None:
            self.log = log
        else:
            # log errors in this module to a file
            self.log = SetupLogger("client",
                                   os.path.join(loglocation, "myclient.log"))

        self.console = SetupLogger("notify_console", log_file="", stream=True)
        try:
            # init event callbacks
            if onready != None:
                self.Events["READY"] = onready
            if onexercise != None:
                self.Events["EXERCISING"] = onexercise
            if onrun != None:
                self.Events["RUNNING"] = onrun
            if onrunmanual != None:
                self.Events["RUNNING-MANUAL"] = onrunmanual
            if onalarm != None:
                self.Events["ALARM"] = onalarm
            if onservice != None:
                self.Events["SERVICEDUE"] = onservice
            if onoff != None:
                self.Events["OFF"] = onoff
            if onmanual != None:
                self.Events["MANUAL"] = onmanual
            if onutilitychange != None:
                self.Events["OUTAGE"] = onutilitychange

            startcount = 0
            while startcount <= 10:
                try:
                    self.Generator = ClientInterface(host=host,
                                                     port=port,
                                                     log=log,
                                                     loglocation=loglocation)
                    break
                except Exception as e1:
                    startcount += 1
                    if startcount >= 10:
                        self.console.info("genmon not loaded.")
                        sys.exit(1)
                    time.sleep(1)
                    continue

            self.Threads["PollingThread"] = MyThread(self.MainPollingThread,
                                                     Name="PollingThread",
                                                     start=start)
            self.Started = start
        except Exception as e1:
            self.LogErrorLine("Error in mynotify init: " + str(e1))
Exemple #20
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 console=None):

        super(GenTankData, self).__init__()

        self.LogFileName = os.path.join(loglocation, "gentankdiy.log")
        self.AccessLock = threading.Lock()

        self.log = log
        self.console = console
        self.MonitorAddress = host

        configfile = os.path.join(ConfigFilePath, 'gentankdiy.conf')
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename=configfile,
                                   section='gentankdiy',
                                   log=self.log)

            self.gauge_type = self.config.ReadValue('gauge_type',
                                                    return_type=int,
                                                    default=1)

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        try:
            if self.gauge_type == 1:
                self.gauge = GaugeDIY1(self.config,
                                       log=self.log,
                                       console=self.console)
            elif self.gauge_type == 2:
                self.gauge = GaugeDIY2(self.config,
                                       log=self.log,
                                       console=self.console)
            else:
                self.LogError("Invalid guage type: " + str(self.gauge_type))
                sys.exit(1)

            self.debug = self.gauge.debug
            self.Generator = ClientInterface(host=self.MonitorAddress,
                                             port=port,
                                             log=self.log)

            # start thread monitor time for exercise
            self.Threads["TankCheckThread"] = MyThread(self.TankCheckThread,
                                                       Name="TankCheckThread",
                                                       start=False)

            if not self.gauge.InitADC():
                self.LogError("InitADC failed, exiting")
                sys.exit(1)

            self.Threads["TankCheckThread"].Start()

            signal.signal(signal.SIGTERM, self.SignalClose)
            signal.signal(signal.SIGINT, self.SignalClose)

        except Exception as e1:
            self.LogErrorLine("Error in GenTankData init: " + str(e1))
            self.console.error("Error in GenTankData init: " + str(e1))
            sys.exit(1)
Exemple #21
0
    def __init__(self,
            port = "/dev/ttyAMA0" ,
            rate = 115200,
            loglocation = ProgramDefaults.LogPath,
            log = None,
            localinit = False,
            ConfigFilePath = ProgramDefaults.ConfPath,
            recipient = None):
        super(MyModem, self).__init__()

        self.MessagesSent = 0
        self.Errors = 0
        self.SendActive = False
        self.ModemLock = threading.RLock()
        self.Sending = False
        self.SendQueue = []

        if ConfigFilePath == None:
            self.ConfigFilePath = ProgramDefaults.ConfPath
        else:
            self.ConfigFilePath = ConfigFilePath

        # log errors in this module to a file
        if localinit == True:
            self.configfile = "mymodem.conf"
        else:
            self.configfile = os.path.join(self.ConfigFilePath, "mymodem.conf")

        # log errors in this module to a file
        if log == None:
            self.log = SetupLogger("mymodem", os.path.join(loglocation, "mymodem.log"))
        else:
            self.log = log

        self.console = SetupLogger("mymodem_console", log_file = "", stream = True)

        try:
            self.config = MyConfig(filename = self.configfile, section = "MyModem", log = self.log)

            self.LogAtCommands = self.config.ReadValue('log_at_commands', return_type = bool, default = False)

            self.MessageLevel = self.config.ReadValue('message_level', default = 'error')

            self.Rate = self.config.ReadValue('rate', return_type = int, default = 115200)

            self.Port = self.config.ReadValue('port', default = "/dev/ttyAMA0")

            self.Recipient = self.config.ReadValue('recipient', default = recipient)

            self.ModemType = self.config.ReadValue('modem_type', default = "LTEPiHat")

        except Exception as e1:
            self.LogErrorLine("Error reading config file: " + str(e1))
            self.LogConsole("Error reading config file: " + str(e1))
            return

        if self.Recipient == None or not len(self.Recipient):
            self.LogErrorLine("Error invalid recipient")
            self.LogConsole("Error invalid recipient")

        if self.Port == None or not len(self.Port):
            self.LogErrorLine("Error invalid port")
            self.LogConsole("Error invalid port")
            return

        if self.Rate == None or self.Rate <= 0:
            self.LogErrorLine("Error invalid rate")
            self.LogConsole("Error invalid rate")
            return

        # rate * 10 bits then convert to MS
        self.CharacterTimeMS = (((1/ self.Rate) * 10)  *1000)

        self.InitComplete = False

        try:
            self.SerialDevice = SerialDevice(port, rate = rate, log = self.log, loglocation = loglocation)
            self.Threads = self.MergeDicts(self.Threads, self.SerialDevice.Threads)

            self.Threads["SendMessageThread"] = MyThread(self.SendMessageThread, Name = "SendMessageThread")

        except Exception as e1:
            self.LogErrorLine("Error opening serial device in MyModem: " + str(e1))
Exemple #22
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort,
                 console=None):

        super(GenExercise, self).__init__()

        self.AccessLock = threading.Lock()

        self.log = log
        self.console = console

        self.MonitorAddress = host
        self.PollTime = 2
        self.ExerciseActive = False
        self.Debug = False

        try:
            self.config = MyConfig(filename=os.path.join(
                ConfigFilePath, 'genexercise.conf'),
                                   section='genexercise',
                                   log=self.log)

            self.ExerciseType = self.config.ReadValue('exercise_type',
                                                      default="Normal")
            self.ExerciseHour = self.config.ReadValue('exercise_hour',
                                                      return_type=int,
                                                      default=12)
            self.ExerciseMinute = self.config.ReadValue('exercise_minute',
                                                        return_type=int,
                                                        default=0)
            self.ExerciseDayOfMonth = self.config.ReadValue(
                'exercise_day_of_month', return_type=int, default=1)
            self.ExerciseDayOfWeek = self.config.ReadValue(
                'exercise_day_of_week', default="Monday")
            self.ExerciseDuration = self.config.ReadValue('exercise_duration',
                                                          return_type=float,
                                                          default=12)
            self.ExerciseWarmup = self.config.ReadValue('exercise_warmup',
                                                        return_type=float,
                                                        default=0)
            self.ExerciseFrequency = self.config.ReadValue(
                'exercise_frequency', default="Monthly")
            self.MonitorAddress = self.config.ReadValue(
                'monitor_address', default=ProgramDefaults.LocalHost)
            self.LastExerciseTime = self.config.ReadValue('last_exercise',
                                                          default=None)
            self.UseGeneratorTime = self.config.ReadValue('use_gen_time',
                                                          return_type=bool,
                                                          default=False)
            self.Debug = self.config.ReadValue('debug',
                                               return_type=bool,
                                               default=False)

            # Validate settings
            if not self.ExerciseType.lower() in [
                    "normal", "quiet", "transfer"
            ]:
                self.ExerciseType = "normal"
            if self.ExerciseHour > 23 or self.ExerciseHour < 0:
                self.ExerciseHour = 12
            if self.ExerciseMinute > 59 or self.ExerciseMinute < 0:
                self.ExerciseMinute = 0
            if not self.ExerciseDayOfWeek.lower() in [
                    "monday", "tuesday", "wednesday", "thursday", "friday",
                    "saturday", "sunday"
            ]:
                self.ExerciseDayOfWeek = "Monday"
            if self.ExerciseDayOfMonth > 28 or self.ExerciseDayOfMonth < 1:
                self.ExerciseDayOfMonth = 1
            if self.ExerciseDuration > 60:
                self.ExerciseDuration = 60
            if self.ExerciseDuration < 5:
                self.ExerciseDuration = 5
            if self.ExerciseWarmup > 30:
                self.ExerciseWarmup = 30
            if self.ExerciseWarmup < 0:
                self.ExerciseWarmup = 0
            if not self.ExerciseFrequency.lower() in [
                    "weekly", "biweekly", "monthly"
            ]:
                self.ExerciseFrequency = "Monthly"

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine(
                "Error reading " +
                os.path.join(ConfigFilePath, "genexercise.conf") + ": " +
                str(e1))
            self.console.error(
                "Error reading " +
                os.path.join(ConfigFilePath, "genexercise.conf") + ": " +
                str(e1))
            sys.exit(1)

        try:

            self.Generator = ClientInterface(host=self.MonitorAddress,
                                             port=port,
                                             log=self.log)

            if not self.CheckGeneratorRequirement():
                self.LogError("Requirements not met. Exiting.")
                sys.exit(1)

            # start thread monitor time for exercise
            self.Threads["ExerciseThread"] = MyThread(self.ExerciseThread,
                                                      Name="ExerciseThread",
                                                      start=False)
            self.Threads["ExerciseThread"].Start()

            try:
                if self.ExerciseFrequency.lower() == "monthly":
                    DayStr = "Day " + str(self.ExerciseDayOfMonth)
                else:
                    DayStr = str(self.ExerciseDayOfWeek)

                self.LogError("Execise: " + self.ExerciseType + ", " +
                              self.ExerciseFrequency + " at " +
                              str(self.ExerciseHour) + ":" +
                              str(self.ExerciseMinute) + " on " + DayStr +
                              " for " + str(self.ExerciseDuration) +
                              " min. Warmup: " + str(self.ExerciseWarmup))
                self.DebugOutput("Debug Enabled")
            except Exception as e1:
                self.LogErrorLine(str(e1))

            signal.signal(signal.SIGTERM, self.SignalClose)
            signal.signal(signal.SIGINT, self.SignalClose)

        except Exception as e1:
            self.LogErrorLine("Error in GenExercise init: " + str(e1))
            self.console.error("Error in GenExercise init: " + str(e1))
            sys.exit(1)
Exemple #23
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort):

        super(GenTemp, self).__init__()

        self.LogFileName = os.path.join(loglocation, "gentemp.log")
        self.AccessLock = threading.Lock()
        # log errors in this module to a file
        self.log = SetupLogger("gentemp", self.LogFileName)

        self.console = SetupLogger("gentemp_console", log_file="", stream=True)

        self.LastValues = {}

        self.MonitorAddress = host
        self.debug = False
        self.PollTime = 1
        self.BlackList = None

        configfile = os.path.join(ConfigFilePath, 'gentemp.conf')
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename=configfile,
                                   section='gentemp',
                                   log=self.log)

            self.UseMetric = self.config.ReadValue('use_metric',
                                                   return_type=bool,
                                                   default=False)
            self.PollTime = self.config.ReadValue('poll_frequency',
                                                  return_type=float,
                                                  default=1)
            self.debug = self.config.ReadValue('debug',
                                               return_type=bool,
                                               default=False)
            self.DeviceLabels = self.GetParamList(
                self.config.ReadValue('device_labels', default=None))
            self.BlackList = self.GetParamList(
                self.config.ReadValue('blacklist', default=None))

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        try:

            try:
                startcount = 0
                while startcount <= 10:
                    try:
                        self.Generator = ClientInterface(
                            host=self.MonitorAddress, port=port, log=self.log)
                        break
                    except Exception as e1:
                        startcount += 1
                        if startcount >= 10:
                            self.LogConsole("genmon not loaded.")
                            self.LogError("Unable to connect to genmon.")
                            sys.exit(1)
                        time.sleep(1)
                        continue

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

            self.DeviceList = self.EnumDevices()

            if not len(self.DeviceList):
                self.LogConsole("No sensors found.")
                self.LogError("No sensors found.")
                sys.exit(1)

            # start thread monitor time for exercise
            self.Threads["GenTempThread"] = MyThread(self.GenTempThread,
                                                     Name="GenTempThread",
                                                     start=False)
            self.Threads["GenTempThread"].Start()

            atexit.register(self.Close)

        except Exception as e1:
            self.LogErrorLine("Error in GenTemp init: " + str(e1))
            self.LogConsole("Error in GenTemp init: " + str(e1))
            sys.exit(1)
Exemple #24
0
    def __init__(self,
                 log=None,
                 loglocation=ProgramDefaults.LogPath,
                 ConfigFilePath=MyCommon.DefaultConfPath,
                 host=ProgramDefaults.LocalHost,
                 port=ProgramDefaults.ServerPort):

        super(GenTankData, self).__init__()

        self.LogFileName = loglocation + "gentankutil.log"
        self.AccessLock = threading.Lock()
        # log errors in this module to a file
        self.log = SetupLogger("gentankutil", self.LogFileName)

        self.console = SetupLogger("gentankutil_console",
                                   log_file="",
                                   stream=True)

        self.MonitorAddress = host
        self.PollTime = 2
        self.TankID = ""
        self.debug = False
        configfile = ConfigFilePath + 'gentankutil.conf'
        try:
            if not os.path.isfile(configfile):
                self.LogConsole("Missing config file : " + configfile)
                self.LogError("Missing config file : " + configfile)
                sys.exit(1)

            self.config = MyConfig(filename=configfile,
                                   section='gentankutil',
                                   log=self.log)

            self.PollTime = self.config.ReadValue('poll_frequency',
                                                  return_type=float,
                                                  default=60)
            self.debug = self.config.ReadValue('debug',
                                               return_type=bool,
                                               default=False)
            self.username = self.config.ReadValue('username', default="")
            self.password = self.config.ReadValue('password', default="")
            self.tank_name = self.config.ReadValue('tank_name', default="")

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = ProgramDefaults.LocalHost

        except Exception as e1:
            self.LogErrorLine("Error reading " + configfile + ": " + str(e1))
            self.LogConsole("Error reading " + configfile + ": " + str(e1))
            sys.exit(1)

        if self.username == "" or self.username == None or self.password == "" or self.password == None:
            self.LogError("Invalid user name or password, exiting")
            sys.exit(1)

        try:

            try:
                startcount = 0
                while startcount <= 10:
                    try:
                        self.Generator = ClientInterface(
                            host=self.MonitorAddress, port=port, log=self.log)
                        break
                    except Exception as e1:
                        startcount += 1
                        if startcount >= 10:
                            self.console.info("genmon not loaded.")
                            self.LogError("Unable to connect to genmon.")
                            sys.exit(1)
                        time.sleep(1)
                        continue

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

            #if not self.CheckGeneratorRequirement():
            #    self.LogError("Requirements not met. Exiting.")
            #    sys.exit(1)

            self.tank = tankutility(self.username,
                                    self.password,
                                    self.log,
                                    debug=self.debug)
            # start thread monitor time for exercise
            self.Threads["TankCheckThread"] = MyThread(self.TankCheckThread,
                                                       Name="TankCheckThread",
                                                       start=False)
            self.Threads["TankCheckThread"].Start()

            atexit.register(self.Close)
            signal.signal(signal.SIGTERM, self.Close)
            signal.signal(signal.SIGINT, self.Close)

        except Exception as e1:
            self.LogErrorLine("Error in GenTankData init: " + str(e1))
            self.console.error("Error in GenTankData init: " + str(e1))
            sys.exit(1)
Exemple #25
0
    def __init__(self):
        super(GenExercise, self).__init__()

        self.LogFileName = "/var/log/genexercise.log"
        self.AccessLock = threading.Lock()
        # log errors in this module to a file
        self.log = SetupLogger("genexercise", self.LogFileName)

        self.console = SetupLogger("genexercise_console", log_file = "", stream = True)

        self.MonitorAddress = "127.0.0.1"
        self.PollTime =  2
        self.ExerciseActive = False
        self.Debug = False

        try:
            self.config = MyConfig(filename = '/etc/genexercise.conf', section = 'genexercise', log = self.log)

            self.ExerciseType = self.config.ReadValue('exercise_type', default = "Normal")
            self.ExerciseHour = self.config.ReadValue('exercise_hour', return_type = int, default = 12)
            self.ExerciseMinute = self.config.ReadValue('exercise_minute', return_type = int, default = 0)
            self.ExerciseDayOfMonth = self.config.ReadValue('exercise_day_of_month', return_type = int, default = 1)
            self.ExerciseDayOfWeek = self.config.ReadValue('exercise_day_of_week',  default = "Monday")
            self.ExerciseDuration = self.config.ReadValue('exercise_duration', return_type = float, default = 12)
            self.ExerciseWarmup = self.config.ReadValue('exercise_warmup', return_type = float, default = 0)
            self.ExerciseFrequency = self.config.ReadValue('exercise_frequency',  default = "Monthly")
            self.MonitorAddress = self.config.ReadValue('monitor_address', default = "127.0.0.1")
            self.LastExerciseTime = self.config.ReadValue('last_exercise',  default = None)
            self.UseGeneratorTime = self.config.ReadValue('use_gen_time',  return_type = bool, default = False)
            self.Debug = self.config.ReadValue('debug', return_type = bool, default = False)

            # Validate settings
            if not self.ExerciseType.lower() in ["normal","quiet", "transfer"]:
                self.ExerciseType = "normal"
            if self.ExerciseHour  > 23 or self.ExerciseHour < 0:
                self.ExerciseHour = 12
            if self.ExerciseMinute  > 59 or self.ExerciseMinute < 0:
                self.ExerciseMinute = 0
            if not self.ExerciseDayOfWeek.lower() in ["monday", "tuesday", "wednesday","thursday","friday","saturday","sunday"]:
                self.ExerciseDayOfWeek = "Monday"
            if self.ExerciseDayOfMonth  > 28 or self.ExerciseDayOfMonth < 1:
                self.ExerciseDayOfMonth = 1
            if self.ExerciseDuration  > 60:
                self.ExerciseDuration = 60
            if self.ExerciseDuration  < 5:
                self.ExerciseDuration = 5
            if self.ExerciseWarmup  > 30:
                self.ExerciseWarmup = 30
            if self.ExerciseWarmup  < 0:
                self.ExerciseWarmup = 0
            if not self.ExerciseFrequency.lower() in ["weekly","biweekly", "monthly"]:
                self.ExerciseFrequency = "Monthly"

            if self.MonitorAddress == None or not len(self.MonitorAddress):
                self.MonitorAddress = "127.0.0.1"

        except Exception as e1:
            self.LogErrorLine("Error reading /etc/genexercise.conf: " + str(e1))
            self.console.error("Error reading /etc/genexercise.conf: " + str(e1))
            sys.exit(1)

        try:

            try:
                startcount = 0
                while startcount <= 10:
                    try:
                        self.Generator = ClientInterface(host = self.MonitorAddress, log = self.log)
                        break
                    except Exception as e1:
                        startcount += 1
                        if startcount >= 10:
                            self.console.info("genmon not loaded.")
                            self.LogError("Unable to connect to genmon.")
                            sys.exit(1)
                        time.sleep(1)
                        continue

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

            if not self.CheckGeneratorRequirement():
                self.LogError("Requirements not met. Exiting.")
                sys.exit(1)

            # start thread monitor time for exercise
            self.Threads["ExerciseThread"] = MyThread(self.ExerciseThread, Name = "ExerciseThread", start = False)
            self.Threads["ExerciseThread"].Start()

            try:
                if self.ExerciseFrequency.lower() == "monthly":
                    DayStr = "Day " + str(self.ExerciseDayOfMonth)
                else:
                    DayStr = str(self.ExerciseDayOfWeek)

                self.LogError("Execise: " + self.ExerciseType + ", " + self.ExerciseFrequency + " at "
                    + str(self.ExerciseHour) + ":" + str(self.ExerciseMinute) + " on " + DayStr + " for "
                    + str(self.ExerciseDuration) + " min. Warmup: " + str(self.ExerciseWarmup))
                if self.Debug:
                    self.LogError("Debug Enabled")
            except Exception as e1:
                self.LogErrorLine(str(e1))
            atexit.register(self.Close)
            signal.signal(signal.SIGTERM, self.Close)
            signal.signal(signal.SIGINT, self.Close)

        except Exception as e1:
            self.LogErrorLine("Error in GenExercise init: " + str(e1))
            self.console.error("Error in GenExercise init: " + str(e1))
            sys.exit(1)