示例#1
0
文件: genmqtt.py 项目: nsxsoft/genmon
    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 = mylog.SetupLogger("client", "/var/log/mygenpush.log")

        self.console = mylog.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 = myclient.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.MyThread(
                self.MainPollingThread, Name="PollingThread")

        except Exception as e1:
            self.LogErrorLine("Error in mygenpush init: " + str(e1))
示例#2
0
import datetime, time, sys, smtplib, signal, os, threading, socket
from genmonlib import mylog, myclient


#----------  Signal Handler ------------------------------------------
def signal_handler(signal, frame):

    sys.exit(0)


#------------------- Command-line interface for monitor -----------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = 'localhost' if len(sys.argv) < 2 else sys.argv[1]

    # log errors in this module to a file
    log = mylog.SetupLogger("client", "client.log")

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)

    MyClientInterface = myclient.ClientInterface(host=address, log=log)

    try:

        while True:
            try:
                line = raw_input(">")
            except NameError:
                pass
                line = input(">")
示例#3
0
#------------------- StartTransferCallBack -----------------#
def StartTransferCallBack():

    try:
        MyClientInterface.ProcessMonitorCommand(
            "generator: setremote=starttransfer")
    except Exception as e1:
        log.error("Error: " + str(e1))


#------------------- Command-line interface for gengpioin -----------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = '127.0.0.1' if len(sys.argv) < 2 else sys.argv[1]

    try:
        log = mylog.SetupLogger("client", "gengpioin.log")
        # Set the signal handler
        signal.signal(signal.SIGINT, signal_handler)

        MyClientInterface = myclient.ClientInterface(host=address, log=log)

        #setup GPIO using Board numbering
        GPIO.setmode(GPIO.BOARD)

        print GPIO.RPI_INFO

        GPIO.setwarnings(True)

        GPIO.setup(
            INPUT_STOP, GPIO.IN,
            pull_up_down=GPIO.PUD_UP)  # input, set internal pull up resistor#
示例#4
0
文件: genlog.py 项目: nsxsoft/genmon
            LogFile.write("Time,Event\n")

        LogFile.write(excel_date(time) + "," + Event + "\n")
        LogFile.flush()


#------------------- Command-line interface for genlog -------------------------
if __name__ == '__main__':

    address = '127.0.0.1'
    fileName = ""

    HelpStr = '\npython genlog.py -a <IP Address or localhost> -f <outputfile>\n'

    try:
        console = mylog.SetupLogger("genlog_console", log_file="", stream=True)
        opts, args = getopt.getopt(sys.argv[1:], "ha:f:",
                                   ["address=", "filename="])
    except getopt.GetoptError:
        console.error(HelpStr)
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            console.error(HelpStr)
            sys.exit()
        elif opt in ("-a", "--address"):
            address = arg
        elif opt in ("-f", "--filename"):
            fileName = arg
            fileName = fileName.strip()
示例#5
0
    except Exception as e1:
       log.error("Error: " + str(e1))
       console.error("Error: " + str(e1))

#------------------- Command-line interface for gengpio ------------------------
if __name__=='__main__': # usage program.py [server_address]
    address='127.0.0.1' if len(sys.argv)<2 else sys.argv[1]

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)

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

    console = mylog.SetupLogger("pushover_console", log_file = "", stream = True)
    log = mylog.SetupLogger("client", "/var/log/genpushover.log")

    try:

        config = myconfig.MyConfig(filename = '/etc/genpushover.conf', section = 'genpushover', log = log)

        appid = config.ReadValue('appid')
        userid = config.ReadValue('userid')
        pushsound = config.ReadValue('pushsound', default = 'updown')

        if appid == None or not len(appid):
            log.error("Error:  invalid app ID")
            console.error("Error:  invalid app ID")
            sys.exit(2)
示例#6
0
    def __init__(self, ConfigFilePath=None):
        super(Monitor, self).__init__()
        self.ProgramName = "Generator Monitor"
        self.Version = "Unknown"
        self.log = None
        self.IsStopping = False
        self.ProgramComplete = False
        if ConfigFilePath == None:
            self.ConfigFilePath = "/etc/"
        else:
            self.ConfigFilePath = ConfigFilePath

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

        self.FeedbackLogFile = os.path.dirname(
            os.path.realpath(__file__)) + "/feedback.json"
        self.LogLocation = "/var/log/"
        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.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 = mylog.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)

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

        self.config = myconfig.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 = mylog.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

        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.MyThread(
            self.InterfaceServerThread, Name="InterfaceServerThread")

        # init mail, start processing incoming email
        self.mail = mymail.MyMail(monitor=True,
                                  incoming_folder=self.IncomingEmailFolder,
                                  processed_folder=self.ProcessedEmailFolder,
                                  incoming_callback=self.ProcessCommand)
        self.Threads = self.MergeDicts(self.Threads, self.mail.Threads)
        self.MailInit = True

        self.FeedbackPipe = mypipe.MyPipe("Feedback",
                                          self.FeedbackReceiver,
                                          log=self.log)
        self.Threads = self.MergeDicts(self.Threads, self.FeedbackPipe.Threads)
        self.MessagePipe = mypipe.MyPipe("Message",
                                         self.MessageReceiver,
                                         log=self.log,
                                         nullpipe=self.mail.DisableSNMP)
        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 = generac_HPanel.HPanel(
                    self.log,
                    newinstall=self.NewInstall,
                    simulation=self.Simulation,
                    simulationfile=self.SimulationFile,
                    message=self.MessagePipe,
                    feedback=self.FeedbackPipe,
                    config=self.config)
            else:
                self.Controller = generac_evolution.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.FatalError("Error opening controller device: " + str(e1))
            return None

        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)
示例#7
0
    def __init__(self, log=None):
        super(MyMQTT, self).__init__()

        self.LogFileName = "/var/log/genmqtt.log"

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

        # cleanup
        # test
        self.console = mylog.SetupLogger("mymqtt_console",
                                         log_file="",
                                         stream=True)

        self.Username = None
        self.Password = None
        self.Address = None
        self.Topic = None

        self.MQTTAddress = "127.0.0.1"
        self.MonitorAddress = "127.0.0.1"
        self.Port = 1883
        self.Topic = "generator"
        self.TopicRoot = None
        self.BlackList = None
        self.PollTime = 2
        self.FlushInterval = float(
            'inf')  # default to inifite flush interval (e.g., never)
        self.Debug = False

        try:

            # read config file
            config = RawConfigParser()
            # config parser reads from current directory, when running form a cron tab this is
            # not defined so we specify the full path
            config.read('/etc/genmqtt.conf')

            CONFIG_SECTION = "genmqtt"
            if config.has_option(CONFIG_SECTION, 'username'):
                self.Username = config.get(CONFIG_SECTION, 'username')
            if config.has_option(CONFIG_SECTION, 'password'):
                self.Password = config.get(CONFIG_SECTION, 'password')

            self.MQTTAddress = config.get(CONFIG_SECTION, 'mqtt_address')
            if config.has_option(CONFIG_SECTION, 'monitor_address'):
                self.MonitorAddress = config.get(CONFIG_SECTION,
                                                 'monitor_address')
            if config.has_option(CONFIG_SECTION, 'mqtt_port'):
                self.MQTTPort = config.getint(CONFIG_SECTION, 'mqtt_port')

            if config.has_option(CONFIG_SECTION, 'poll_interval'):
                self.PollTime = config.getfloat(CONFIG_SECTION,
                                                'poll_interval')
            if config.has_option(CONFIG_SECTION, 'root_topic'):
                self.TopicRoot = config.get(CONFIG_SECTION, 'root_topic')
            if config.has_option(CONFIG_SECTION, 'blacklist'):
                BlackList = config.get(CONFIG_SECTION, 'blacklist')
                self.BlackList = BlackList.strip().split(",")
            if config.has_option(CONFIG_SECTION, 'debug'):
                self.Debug = config.getboolean(CONFIG_SECTION, 'debug')
            if config.has_option(CONFIG_SECTION, 'flush_interval'):
                self.FlushInterval = config.getfloat(CONFIG_SECTION,
                                                     'flush_interval')
        except Exception as e1:
            log.error("Error reading /etc/genmqtt.conf: " + str(e1))
            console.error("Error reading /etc/genmqtt.conf: " + str(e1))
            sys.exit(1)

        try:
            self.MQTTclient = mqtt.Client(client_id="genmon")
            if self.Username != None and len(
                    self.Username) and self.Password != None:
                self.MQTTclient.username_pw_set(self.Username,
                                                password=self.Password)

            self.MQTTclient.on_connect = self.on_connect
            self.MQTTclient.on_message = self.on_message

            self.MQTTclient.connect(self.MQTTAddress, self.Port, 60)

            self.Push = MyGenPush(host=self.MonitorAddress,
                                  log=self.log,
                                  callback=self.PublishCallback,
                                  polltime=self.PollTime,
                                  blacklist=self.BlackList,
                                  flush_interval=self.FlushInterval)

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

            self.MQTTclient.loop_start()
        except Exception as e1:
            self.LogErrorLine("Error in MyMQTT init: " + str(e1))
            self.console.error("Error in MyMQTT init: " + str(e1))
            sys.exit(1)
示例#8
0
#------------------------------------------------------------
if __name__ == "__main__":
    address = 'localhost' if len(sys.argv) <= 2 else sys.argv[1]

    ConfigFilePath = '/etc/' if len(sys.argv) <= 3 else sys.argv[2]

    MAIL_CONFIG = ConfigFilePath + "mymail.conf"
    GENMON_CONFIG = ConfigFilePath + "genmon.conf"

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

    # log errors in this module to a file
    console = mylog.SetupLogger("genserv_console", log_file="", stream=True)

    if os.geteuid() != 0:
        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(ConfigFilePath + 'genmon.conf'):
        LogConsole("Missing config file : " + ConfigFilePath + 'genmon.conf')
        sys.exit(1)

    AppPath = sys.argv[0]
    if not LoadConfig():
        LogConsole("Error reading configuraiton file.")
        sys.exit(1)
示例#9
0
        if opt == '-h':
            print(HelpStr)
            sys.exit()
        elif opt in ("-a", "--address"):
            address = arg
        elif opt in ("-f", "--filename"):
            fileName = arg

    print 'Address is "', address
    print 'Output file is "', fileName
    if not len(fileName):
        print(HelpStr)
        sys.exit(2)

    try:
        log = mylog.SetupLogger("client", "genlog.log")
        # Set the signal handler
        signal.signal(signal.SIGINT, signal_handler)

        MyClientInterface = myclient.ClientInterface(host=address, log=log)

        LastEvent = ""

        while True:

            data = MyClientInterface.ProcessMonitorCommand(
                "generator: getbase")

            if LastEvent != data:
                LastEvent = data
                LogDataToFile(fileName, datetime.now(), data)
示例#10
0
def LoadConfig():

    global log
    global clientport
    global loglocation
    global bUseSecureHTTP
    global HTTPPort
    global HTTPAuthUser
    global HTTPAuthPass
    global HTTPAuthUser_RO
    global HTTPAuthPass_RO
    global SSLContext
    global favicon

    HTTPAuthPass = None
    HTTPAuthUser = None
    SSLContext = None
    try:

        # heartbeat server port, must match value in check_generator_system.py and any calling client apps
        if genmon_config.HasOption('server_port'):
            clientport = genmon_config.ReadValue('server_port',
                                                 return_type=int,
                                                 default=0)

        if genmon_config.HasOption('loglocation'):
            loglocation = genmon_config.ReadValue('loglocation')

        # log errors in this module to a file
        log = mylog.SetupLogger("genserv", loglocation + "genserv.log")

        if genmon_config.HasOption('usehttps'):
            bUseSecureHTTP = genmon_config.ReadValue('usehttps',
                                                     return_type=bool)

        if genmon_config.HasOption('http_port'):
            HTTPPort = genmon_config.ReadValue('http_port',
                                               return_type=int,
                                               default=8000)

        if genmon_config.HasOption('favicon'):
            favicon = genmon_config.ReadValue('favicon')

        # user name and password require usehttps = True
        if bUseSecureHTTP:
            if genmon_config.HasOption('http_user'):
                HTTPAuthUser = genmon_config.ReadValue('http_user', default="")
                HTTPAuthUser = HTTPAuthUser.strip()
                # No user name or pass specified, disable
                if HTTPAuthUser == "":
                    HTTPAuthUser = None
                    HTTPAuthPass = None
                elif genmon_config.HasOption('http_pass'):
                    HTTPAuthPass = genmon_config.ReadValue('http_pass',
                                                           default="")
                    HTTPAuthPass = HTTPAuthPass.strip()
                if HTTPAuthUser != None and HTTPAuthPass != None:
                    if genmon_config.HasOption('http_user_ro'):
                        HTTPAuthUser_RO = genmon_config.ReadValue(
                            'http_user_ro', default="")
                        HTTPAuthUser_RO = HTTPAuthUser_RO.strip()
                        if HTTPAuthUser_RO == "":
                            HTTPAuthUser_RO = None
                            HTTPAuthPass_RO = None
                        elif genmon_config.HasOption('http_pass_ro'):
                            HTTPAuthPass_RO = genmon_config.ReadValue(
                                'http_pass_ro', default="")
                            HTTPAuthPass_RO = HTTPAuthPass_RO.strip()

            HTTPSPort = genmon_config.ReadValue('https_port',
                                                return_type=int,
                                                default=443)

        if bUseSecureHTTP:
            app.secret_key = os.urandom(12)
            OldHTTPPort = HTTPPort
            HTTPPort = HTTPSPort
            if genmon_config.HasOption('useselfsignedcert'):
                bUseSelfSignedCert = genmon_config.ReadValue(
                    'useselfsignedcert', return_type=bool)

                if bUseSelfSignedCert:
                    SSLContext = 'adhoc'
                else:
                    if genmon_config.HasOption(
                            'certfile') and genmon_config.HasOption('keyfile'):
                        CertFile = genmon_config.ReadValue('certfile')
                        KeyFile = genmon_config.ReadValue('keyfile')
                        if CheckCertFiles(CertFile, KeyFile):
                            SSLContext = (CertFile, KeyFile)  # tuple
                        else:
                            HTTPPort = OldHTTPPort
                            SSLContext = None
            else:
                # if we get here then usehttps is enabled but not option for useselfsignedcert
                # so revert to HTTP
                HTTPPort = OldHTTPPort

        return True
    except Exception as e1:
        LogConsole("Missing config file or config file entries: " + str(e1))
        return False
示例#11
0
        syslog.syslog("%s" % Message)
        syslog.closelog()

    except Exception as e1:
        log.error("Error: " + str(e1))
        print("Error: " + str(e1))


#------------------- Command-line interface for gengpio -----------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = '127.0.0.1' if len(sys.argv) < 2 else sys.argv[1]

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)

    log = mylog.SetupLogger("client", "/var/log/gensyslog.log")
    try:

        GenNotify = mynotify.GenNotify(host=address,
                                       onready=OnReady,
                                       onexercise=OnExercise,
                                       onrun=OnRun,
                                       onrunmanual=OnRunManual,
                                       onalarm=OnAlarm,
                                       onservice=OnService,
                                       onoff=OnOff,
                                       onmanual=OnManual,
                                       onutilitychange=OnUtilityChange,
                                       log=log)

        while True:
示例#12
0
    def __init__(self,
                 start=False,
                 stop=False,
                 hardstop=False,
                 loglocation="/var/log/",
                 log=None,
                 localinit=False,
                 ConfigFilePath=None):

        self.Start = start
        self.Stop = stop
        self.HardStop = hardstop

        if ConfigFilePath == None:
            self.ConfigFilePath = "/etc/"
        else:
            self.ConfigFilePath = ConfigFilePath

        self.ConfigFileName = "genloader.conf"
        # log errors in this module to a file
        if localinit == True:
            self.configfile = self.ConfigFileName
        else:
            self.configfile = self.ConfigFilePath + self.ConfigFileName

        self.ModulePath = os.path.dirname(os.path.realpath(__file__)) + "/"
        self.ConfPath = os.path.dirname(os.path.realpath(__file__)) + "/conf/"

        # log errors in this module to a file
        if log == None:
            self.log = mylog.SetupLogger("genloader",
                                         loglocation + "genloader.log")
        else:
            self.log = log

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

        try:
            if self.Start:
                if not self.CheckSystem():
                    self.LogInfo("Error check system readiness. Exiting")
                    sys.exit(2)

            self.CachedConfig = {}

            # check to see if genloader.conf is present, if not copy it from genmon directory
            if not os.path.isfile(self.configfile):
                self.LogInfo("Warning: unable to find config file: " +
                             self.configfile +
                             " Copying file to /etc/ directory.")
                if os.path.isfile(self.ConfPath + self.ConfigFileName):
                    copyfile(self.ConfPath + self.ConfigFileName,
                             self.configfile)
                else:
                    self.LogInfo("Unable to find config file.")
                    sys.exit(2)

            self.config = myconfig.MyConfig(filename=self.configfile,
                                            section="genmon",
                                            log=self.log)
            if not self.GetConfig():
                self.LogInfo("Error reading config file. Exiting")
                sys.exit(2)

            if not self.ValidateConfig():
                self.LogInfo("Error validating config. Exiting")
                sys.exit(2)

            self.LoadOrder = self.GetLoadOrder()

            if self.Stop:
                self.StopModules()
                time.sleep(2)

            if self.Start:
                self.StartModules()
        except Exception as e1:
            self.LogErrorLine("Error in init: " + str(e1))
示例#13
0
    def __init__(self, log=None):
        super(MyMQTT, self).__init__()

        self.LogFileName = "/var/log/genmqtt.log"

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

        # cleanup
        # test
        self.console = mylog.SetupLogger("mymqtt_console",
                                         log_file="",
                                         stream=True)

        self.Username = None
        self.Password = None
        self.Address = None
        self.Topic = None

        self.MQTTAddress = "127.0.0.1"
        self.MonitorAddress = "127.0.0.1"
        self.Port = 1883
        self.Topic = "generator"
        self.TopicRoot = None
        self.BlackList = None
        self.PollTime = 2
        self.FlushInterval = float(
            'inf')  # default to inifite flush interval (e.g., never)
        self.Debug = False

        try:
            config = myconfig.MyConfig(filename='/etc/genmqtt.conf',
                                       section='genmqtt',
                                       log=log)
            if config.HasOption('username'):
                self.Username = config.ReadValue('username')
            if config.HasOption('password'):
                self.Password = config.ReadValue('password')

            self.MQTTAddress = config.ReadValue('mqtt_address')
            if config.HasOption('monitor_address'):
                self.MonitorAddress = config.ReadValue('monitor_address')
            if config.HasOption('mqtt_port'):
                self.MQTTPort = config.ReadValue('mqtt_port', return_type=int)

            if config.HasOption('poll_interval'):
                self.PollTime = config.ReadValue('poll_interval',
                                                 return_type=float)
            if config.HasOption('root_topic'):
                self.TopicRoot = config.ReadValue('root_topic')
            if config.HasOption('blacklist'):
                BlackList = config.ReadValue('blacklist')
                self.BlackList = BlackList.strip().split(",")
            if config.HasOption('debug'):
                self.Debug = config.ReadValue('debug', return_type=bool)
            if config.HasOption('flush_interval'):
                self.FlushInterval = config.ReadValue('flush_interval',
                                                      return_type=float)
        except Exception as e1:
            log.error("Error reading /etc/genmqtt.conf: " + str(e1))
            console.error("Error reading /etc/genmqtt.conf: " + str(e1))
            sys.exit(1)

        try:
            self.MQTTclient = mqtt.Client(client_id="genmon")
            if self.Username != None and len(
                    self.Username) and self.Password != None:
                self.MQTTclient.username_pw_set(self.Username,
                                                password=self.Password)

            self.MQTTclient.on_connect = self.on_connect
            self.MQTTclient.on_message = self.on_message

            self.MQTTclient.connect(self.MQTTAddress, self.Port, 60)

            self.Push = MyGenPush(host=self.MonitorAddress,
                                  log=self.log,
                                  callback=self.PublishCallback,
                                  polltime=self.PollTime,
                                  blacklist=self.BlackList,
                                  flush_interval=self.FlushInterval)

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

            self.MQTTclient.loop_start()
        except Exception as e1:
            self.LogErrorLine("Error in MyMQTT init: " + str(e1))
            self.console.error("Error in MyMQTT init: " + str(e1))
            sys.exit(1)
示例#14
0

#------------------- Command-line interface for gengpio -----------------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = '127.0.0.1' if len(sys.argv) < 2 else sys.argv[1]

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)

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

    console = mylog.SetupLogger("sms_console_modem", log_file="", stream=True)
    log = mylog.SetupLogger("client", "/var/log/gensms_modem.log")

    try:

        SMS = mymodem.LTEPiHat(log=log)
        if not SMS.InitComplete:
            SMS.Close()
            log.error("Modem Init FAILED!")
            console.error("Modem Init FAILED!")
            sys.exit(2)

    except Exception as e1:
        log.error("Error on modem init:" + str(e1))
        console.error("Error modem init: " + str(e1))
        sys.exit(1)
示例#15
0

#----------  Signal Handler ------------------------------------------
def signal_handler(signal, frame):

    GPIO.cleanup()
    MyClientInterface.Close()
    sys.exit(0)


#------------------- Command-line interface for gengpio -----------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = '127.0.0.1' if len(sys.argv) < 2 else sys.argv[1]

    try:
        log = mylog.SetupLogger("client", "gengpio.log")
        console = mylog.SetupLogger("gengpio_console",
                                    log_file="",
                                    stream=True)
        # Set the signal handler
        signal.signal(signal.SIGINT, signal_handler)

        MyClientInterface = myclient.ClientInterface(host=address, log=log)

        #setup GPIO using Board numbering
        GPIO.setmode(GPIO.BOARD)

        console.info(GPIO.RPI_INFO)

        GPIO.setwarnings(False)
示例#16
0
            sys.exit()
        elif opt in ("-a", "--address"):
            address = arg
            print ('Address is : %s' % address)
        elif opt in ("-f", "--filename"):
            fileName = arg
            print ('Output file is : %s' % fileName)

    if not len(address):
        print ("Address is : localhost")
        address = "localhost"

    if not len(fileName):
        print (HelpStr)
        sys.exit(2)

    try:
        log = mylog.SetupLogger("client", "kwlog2csv.log")

        MyClientInterface = myclient.ClientInterface(host = address, log = log)

        data = MyClientInterface.ProcessMonitorCommand("generator: power_log_json")

        data = json.loads(data)

        for Time, Value in reversed(data):
            LogToFile(fileName, Time, Value)

    except Exception as e1:
        print ("Error (1): " + str(e1))
示例#17
0
    print("Please see the project documentation at https://github.com/jgyates/genmon.\n")
    sys.exit(2)



#----------  Signal Handler ------------------------------------------
def signal_handler(signal, frame):

    sys.exit(0)

#------------------- Command-line interface for monitor -----------------#
if __name__=='__main__': # usage program.py [server_address]
    address='localhost' if len(sys.argv)<2 else sys.argv[1]

    # log errors in this module to a file
    console = mylog.SetupLogger("client_console", log_file = "", stream = True)
    log = mylog.SetupLogger("client", "client.log")

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)

    startcount = 0
    while startcount <= 2:
        try:
            MyClientInterface = myclient.ClientInterface(host = address, log = log)
            break
        except Exception as e1:
            startcount += 1
            if startcount >= 2:
                console.error("Error: genmon not loaded.")
                sys.exit(1)
示例#18
0
def LoadConfig():

    global log
    global clientport
    global loglocation
    global bUseSecureHTTP
    global HTTPPort
    global HTTPAuthUser
    global HTTPAuthPass
    global HTTPAuthUser_RO
    global HTTPAuthPass_RO
    global SSLContext
    global favicon

    HTTPAuthPass = None
    HTTPAuthUser = None
    SSLContext = None
    try:
        config = RawConfigParser()
        # config parser reads from current directory, when running form a cron tab this is
        # not defined so we specify the full path
        config.read(GENMON_CONFIG)

        # heartbeat server port, must match value in check_generator_system.py and any calling client apps
        if config.has_option('GenMon', 'server_port'):
            clientport = config.getint('GenMon', 'server_port')

        if config.has_option('GenMon', 'loglocation'):
            loglocation = config.get("GenMon", 'loglocation')

        # log errors in this module to a file
        log = mylog.SetupLogger("genserv", loglocation + "genserv.log")

        if config.has_option('GenMon', 'usehttps'):
            bUseSecureHTTP = config.getboolean('GenMon', 'usehttps')

        if config.has_option('GenMon', 'http_port'):
            HTTPPort = config.getint('GenMon', 'http_port')

        if config.has_option('GenMon', 'favicon'):
            favicon = config.get('GenMon', 'favicon')

        # user name and password require usehttps = True
        if bUseSecureHTTP:
            if config.has_option('GenMon', 'http_user'):
                HTTPAuthUser = config.get('GenMon', 'http_user')
                HTTPAuthUser = HTTPAuthUser.strip()
                # No user name or pass specified, disable
                if HTTPAuthUser == "":
                    HTTPAuthUser = None
                    HTTPAuthPass = None
                elif config.has_option('GenMon', 'http_pass'):
                    HTTPAuthPass = config.get('GenMon', 'http_pass')
                    HTTPAuthPass = HTTPAuthPass.strip()
                if HTTPAuthUser != None and HTTPAuthPass != None:
                    if config.has_option('GenMon', 'http_user_ro'):
                        HTTPAuthUser_RO = config.get('GenMon', 'http_user_ro')
                        HTTPAuthUser_RO = HTTPAuthUser_RO.strip()
                        if HTTPAuthUser_RO == "":
                            HTTPAuthUser_RO = None
                            HTTPAuthPass_RO = None
                        elif config.has_option('GenMon', 'http_pass_ro'):
                            HTTPAuthPass_RO = config.get(
                                'GenMon', 'http_pass_ro')
                            HTTPAuthPass_RO = HTTPAuthPass_RO.strip()

        if bUseSecureHTTP:
            app.secret_key = os.urandom(12)
            OldHTTPPort = HTTPPort
            HTTPPort = 443
            if config.has_option('GenMon', 'useselfsignedcert'):
                bUseSelfSignedCert = config.getboolean('GenMon',
                                                       'useselfsignedcert')

                if bUseSelfSignedCert:
                    SSLContext = 'adhoc'
                else:
                    if config.has_option('GenMon',
                                         'certfile') and config.has_option(
                                             'GenMon', 'keyfile'):
                        CertFile = config.get('GenMon', 'certfile')
                        KeyFile = config.get('GenMon', 'keyfile')
                        if CheckCertFiles(CertFile, KeyFile):
                            SSLContext = (CertFile, KeyFile)  # tuple
                        else:
                            HTTPPort = OldHTTPPort
                            SSLContext = None
            else:
                # if we get here then usehttps is enabled but not option for useselfsignedcert
                # so revert to HTTP
                HTTPPort = OldHTTPPort

        return True
    except Exception as e1:
        LogConsole("Missing config file or config file entries: " + str(e1))
        return False
示例#19
0
        print(message.id)

    except Exception as e1:
        log.error("Error: " + str(e1))
        print("Error: " + str(e1))


#------------------- Command-line interface for gengpio -----------------#
if __name__ == '__main__':  # usage program.py [server_address]
    address = '127.0.0.1' if len(sys.argv) < 2 else sys.argv[1]

    # Set the signal handler
    signal.signal(signal.SIGINT, signal_handler)
    try:
        log = mylog.SetupLogger("client", "/var/log/genpushover.log")

        # read config file
        config = RawConfigParser()
        # config parser reads from current directory, when running form a cron tab this is
        # not defined so we specify the full path
        config.read('/etc/genpushover.conf')

        appid = config.get('genpushover', 'appid')
        userid = config.get('genpushover', 'userid')
        pushsound = config.get('genpushover', 'pushsound')

        GenNotify = mynotify.GenNotify(host=address,
                                       onready=OnReady,
                                       onexercise=OnExercise,
                                       onrun=OnRun,