Esempio n. 1
0
    def __init__(self,
                 updatecallback,
                 address=0x9d,
                 name="/dev/serial",
                 rate=9600,
                 loglocation="/var/log/"):

        self.Address = address
        self.Threads = {}  # Dict of mythread objects
        self.DeviceInit = False
        self.CommAccessLock = threading.RLock(
        )  # lock to synchronize access to the serial port comms
        self.UpdateRegisterList = updatecallback
        # log errors in this module to a file
        self.log = mylog.SetupLogger("mymodbus", loglocation + "mymodbus.log")

        try:
            #Starting serial connection
            self.Slave = myserial.SerialDevice(name, rate, loglocation)
            self.DeviceInit = True

        except Exception as e1:
            self.FatalError("Error opening serial device: " + str(e1))
            return None

        try:
            # CRCMOD library, used for CRC calculations
            self.ModbusCrc = crcmod.predefined.mkCrcFun('modbus')
        except Exception as e1:
            self.FatalError("Unable to find crcmod package: " + str(e1))
Esempio n. 2
0
    def __init__(self,
                 updatecallback,
                 address=0x9d,
                 name="/dev/serial",
                 rate=9600,
                 loglocation="/var/log/"):
        super(ModbusBase, self).__init__()
        self.Address = address
        self.Rate = rate
        self.PortName = name
        self.InitComplete = False
        self.IsStopping = False
        self.UpdateRegisterList = updatecallback
        self.RxPacketCount = 0
        self.TxPacketCount = 0
        self.ComTimoutError = 0
        self.TotalElapsedPacketeTime = 0
        self.ComTimoutError = 0
        self.CrcError = 0
        self.CommAccessLock = threading.RLock(
        )  # lock to synchronize access to the serial port comms
        self.ModbusStartTime = datetime.datetime.now()  # used for com metrics

        # log errors in this module to a file
        self.log = mylog.SetupLogger("mymodbus", loglocation + "mymodbus.log")
Esempio n. 3
0
    def __init__(self, updatecallback, address = 0x9d, name = "/dev/serial", rate=9600, loglocation = "/var/log/", inputfile = None):
        super(ModbusFile, self).__init__(updatecallback = updatecallback, address = address, name = name, rate = rate, loglocation = loglocation)
        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 = {}

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

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

        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

        self.ReadInputFile(self.InputFile)
        self.Threads["ReadInputFileThread"] = mythread.MyThread(self.ReadInputFileThread, Name = "ReadInputFileThread")
Esempio n. 4
0
    def __init__(self, monitor = False, incoming_folder = None, processed_folder = None, incoming_callback = None, localinit = False, loglocation = "/var/log/", ConfigFilePath = 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:
            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.SSLEnabled = False
        self.Threads = {}                               # Dict of mythread objects

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

        self.log = mylog.SetupLogger("mymail", self.logfile)

        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.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.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")
Esempio n. 5
0
    def __init__(self, host="127.0.0.1", port=9082, log=None):
        super(ClientInterface, self).__init__()
        if log != None:
            self.log = log
        else:
            # log errors in this module to a file
            self.log = mylog.SetupLogger("client", "/var/log/myclient.log")

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

        self.AccessLock = threading.RLock()
        self.EndOfMessage = "EndOfMessage"
        self.rxdatasize = 2000
        self.host = host
        self.port = port

        self.Connect()
Esempio n. 6
0
    def __init__(self, name, rate=9600, loglocation = "/var/log/", Parity = None, OnePointFiveStopBits = None):
        super(SerialDevice, self).__init__()
        self.DeviceName = name
        self.BaudRate = rate
        self.Buffer = []
        self.BufferLock = threading.Lock()
        self.DiscardedBytes = 0
        self.Restarts = 0
        self.SerialStartTime = datetime.datetime.now()     # used for com metrics

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

        #Starting serial connection
        self.SerialDevice = serial.Serial()
        self.SerialDevice.port = name
        self.SerialDevice.baudrate = rate
        self.SerialDevice.bytesize = serial.EIGHTBITS     #number of bits per bytes
        if Parity == None:
            self.SerialDevice.parity = serial.PARITY_NONE    #set parity check: no parity
        elif Parity == 1:
            self.SerialDevice.parity = serial.PARITY_ODD     #set parity check: use odd parity
        else:
            self.SerialDevice.parity = serial.PARITY_EVEN    #set parity check: use even parity

        if OnePointFiveStopBits == None:
            self.SerialDevice.stopbits = serial.STOPBITS_ONE  #number of stop bits
        elif OnePointFiveStopBits:
            self.SerialDevice.stopbits = serial.STOPBITS_ONE_POINT_FIVE  #number of stop bits
        else:
            self.SerialDevice.stopbits = serial.STOPBITS_ONE  #number of stop bits

        self.SerialDevice.timeout =  0.05                 # small timeout so we can check if the thread should exit
        self.SerialDevice.xonxoff = False                 #disable software flow control
        self.SerialDevice.rtscts = False                  #disable hardware (RTS/CTS) flow control
        self.SerialDevice.dsrdtr = False                  #disable hardware (DSR/DTR) flow control
        self.SerialDevice.writeTimeout = None             #timeout for write, return when packet sent

        #Check if port failed to open
        if (self.SerialDevice.isOpen() == False):
            try:
                self.SerialDevice.open()
            except Exception as e:
                self.FatalError( "Error on open serial port %s: " % self.DeviceName + str(e))
                return None
        else:
            self.FatalError( "Serial port already open: %s" % self.DeviceName)
            return None

        self.Flush()
        self.StartReadThread()
Esempio n. 7
0
    def __init__(self, host="127.0.0.1", port=9082, log = None):

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

        self.EndOfMessage = "EndOfMessage"
        self.rxdatasize = 2000
        self.host = host
        self.port = port

        self.Connect()
Esempio n. 8
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):

        self.AccessLock = threading.Lock()
        self.ThreadList = []
        self.LastEvent = None
        self.Events = {}  # Dict for handling events

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

        # 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

        self.Generator = myclient.ClientInterface(host=host, log=log)

        # start thread to accept incoming sockets for nagios heartbeat
        self.StartThread(self.MainPollingThread, Name="PollingThread")
Esempio n. 9
0
    def __init__(self,
        updatecallback,
        address = 0x9d,
        name = "/dev/serial",
        rate=9600,
        config = None):

        super(ModbusBase, self).__init__()
        self.Address = address
        self.Rate = rate
        self.PortName = name
        self.config = config
        self.InitComplete = False
        self.IsStopping = False
        self.UpdateRegisterList = updatecallback
        self.RxPacketCount = 0
        self.TxPacketCount = 0
        self.ComTimoutError = 0
        self.TotalElapsedPacketeTime = 0
        self.SlaveException = 0
        self.CrcError = 0
        self.ComValidationError = 0
        self.UnexpectedData = 0
        self.SlowCPUOptimization = False
        self.UseTCP = False

        if self.config != None:
            self.loglocation = self.config.ReadValue('loglocation', default = '/var/log/')
            self.SlowCPUOptimization = self.config.ReadValue('optimizeforslowercpu', return_type = bool, default = False)
            self.UseTCP = self.config.ReadValue('use_serial_tcp', return_type = bool, default = False)
            self.Address = int(self.config.ReadValue('address', default = '9d'),16)         # modbus address
            self.AdditionalModbusTimeout = self.config.ReadValue('additional_modbus_timeout', return_type = float, default = 0.0)
        else:
            self.loglocation = default = './'


        self.CommAccessLock = threading.RLock()     # lock to synchronize access to the serial port comms
        self.ModbusStartTime = datetime.datetime.now()     # used for com metrics

        # log errors in this module to a file
        self.log = mylog.SetupLogger("mymodbus", self.loglocation + "mymodbus.log")
Esempio n. 10
0
    def __init__(self,
                 monitor=False,
                 incoming_folder=None,
                 processed_folder=None,
                 incoming_callback=None,
                 localinit=False):

        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
        self.Mailbox = 0
        self.EmailSendQueue = []  # queue for email to send

        # log errors in this module to a file
        if localinit == True:
            logfile = "mymail.log"
            configfile = "mymail.conf"
        else:
            logfile = "/var/log/mymail.log"
            configfile = "/etc/mymail.conf"

        self.log = mylog.SetupLogger("mymail", logfile)

        atexit.register(self.Cleanup)
        try:
            config = ConfigParser.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(configfile)

            self.EmailPassword = config.get('MyMail', 'email_pw')
            self.EmailAccount = config.get('MyMail', 'email_account')
            self.EmailRecipient = config.get('MyMail', 'email_recipient')
            self.SMTPServer = config.get('MyMail', 'smtp_server')
            self.IMAPServer = config.get('MyMail', 'imap_server')
            self.SMTPPort = config.getint('MyMail', 'smtp_port')
        except Exception, e1:
            self.FatalError("ERROR: Unable to read config file" + str(e1))
Esempio n. 11
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 = mylog.SetupLogger("client", "/var/log/myclient.log")

        self.console = mylog.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 = myclient.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.MyThread(
                self.MainPollingThread, Name="PollingThread")
        except Exception as e1:
            self.LogErrorLine("Error in mynotify init: " + str(e1))
Esempio n. 12
0
    def __init__(self,
                 port="/dev/ttyAMA0",
                 rate=115200,
                 loglocation="/var/log/",
                 log=None,
                 localinit=False,
                 ConfigFilePath=None,
                 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 = "/etc/"
        else:
            self.ConfigFilePath = ConfigFilePath

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

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

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

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

            if self.config.HasOption('log_at_commands'):
                self.LogAtCommands = self.config.ReadValue('log_at_commands',
                                                           return_type=bool)
            else:
                self.LogAtCommands = False

            if self.config.HasOption('message_level'):
                self.MessageLevel = self.config.ReadValue('message_level')
            else:
                self.MessageLevel = "error"

            if self.config.HasOption('rate'):
                self.Rate = self.config.ReadValue('rate', return_type=int)
            else:
                self.Rate = rate

            if self.config.HasOption('port'):
                self.Port = self.config.ReadValue('port')
            else:
                self.Port = port

            if self.config.HasOption('recipient'):
                self.Recipient = self.config.ReadValue('recipient')
            else:
                self.Recipient = recipient

            if self.config.HasOption('modem_type'):
                self.ModemType = self.config.ReadValue('modem_type')
            else:
                self.ModemType = modem_type

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

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

        self.InitComplete = False

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

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

        except Exception as e1:
            self.LogErrorLine("Error opening serial device in MyModem: " +
                              str(e1))
Esempio n. 13
0
            body = Message)

        print(message.sid)

    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/gensms.log")

        # read config file
        config = configparser.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/gensms.conf')

        account_sid = config.get('gensms', 'accountsid')
        auth_token = config.get('gensms', 'authtoken')
        to_number = config.get('gensms', 'to_number')
        from_number = config.get('gensms', 'from_number')

        GenNotify = mynotify.GenNotify(
                                        host = address,
                                        onready = OnReady,
Esempio n. 14
0
    #---------------------ClientInterface::FatalError------------------------
    def LogError(self, Message):
        log.error(Message)

    #----------  ClientInterface::FatalError ---------------------------------
    def FatalError(self, Message):

        log.error(Message)
        raise Exception(Message)


#------------------------------------------------------------
app = Flask(__name__, static_url_path='')

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


#------------------------------------------------------------
@app.route('/')
def root():
    return app.send_static_file('index.html')


#------------------------------------------------------------
@app.route("/cmd/<command>")
def command(command):

    if command in [
            "status", "outage", "maint", "logs", "monitor", "getbase",
            "getsitename", "setexercise", "setquiet", "getexercise"
Esempio n. 15
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#
Esempio n. 16
0
def LoadConfig():

    global log
    global clientport
    global loglocation
    global bUseSecureHTTP
    global HTTPPort
    global HTTPAuthUser
    global HTTPAuthPass
    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 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

    except Exception as e1:
        log.error("Missing config file or config file entries: " + str(e1))
Esempio n. 17
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,
Esempio n. 18
0
    def __init__(self,
                 monitor=False,
                 incoming_folder=None,
                 processed_folder=None,
                 incoming_callback=None,
                 localinit=False):

        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
        self.Mailbox = 0
        self.EmailSendQueue = []  # queue for email to send
        self.DisableEmail = False
        self.SSLEnabled = False

        # log errors in this module to a file
        if localinit == True:
            logfile = "mymail.log"
            configfile = "mymail.conf"
        else:
            logfile = "/var/log/mymail.log"
            configfile = "/etc/mymail.conf"

        self.log = mylog.SetupLogger("mymail", logfile)

        atexit.register(self.Cleanup)
        try:
            config = configparser.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(configfile)

            self.EmailPassword = config.get('MyMail', 'email_pw')
            self.EmailAccount = config.get('MyMail', 'email_account')
            if config.has_option('MyMail', 'sender_account'):
                self.SenderAccount = config.get('MyMail', 'sender_account')
            else:
                self.SenderAccount = self.EmailAccount
            self.EmailRecipient = config.get('MyMail', 'email_recipient')
            # SMTP Server
            if config.has_option('MyMail', 'smtp_server'):
                self.SMTPServer = config.get('MyMail', 'smtp_server')
                self.SMTPServer = self.SMTPServer.strip()
            else:
                self.SMTPServer = ""
            # IMAP Server
            if config.has_option('MyMail', 'imap_server'):
                self.IMAPServer = config.get('MyMail', 'imap_server')
                self.IMAPServer = self.IMAPServer.strip()
            else:
                self.IMAPServer = ""
            self.SMTPPort = config.getint('MyMail', 'smtp_port')
            if config.has_option('MyMail', 'disableemail'):
                self.DisableEmail = config.getboolean('MyMail', 'disableemail')
            if config.has_option('MyMail', 'ssl_enabled'):
                self.SSLEnabled = config.getboolean('MyMail', 'ssl_enabled')
        except Exception as e1:
            self.FatalError("ERROR: Unable to read config file" + str(e1))

        atexit.register(self.Cleanup)

        if not self.DisableEmail:
            if self.SMTPServer != "":
                self.threadSendEmail = threading.Thread(
                    target=self.SendMailThread, name="SendMailThread")
                self.threadSendEmail.daemon = True
                self.threadSendEmail.start()  # start SMTP thread
            else:
                self.LogError("SMTP disabled")

            if monitor and self.IMAPServer != "":  # if True then we will have an IMAP monitor thread
                if incoming_callback and incoming_folder and processed_folder:
                    self.threadEmail = threading.Thread(
                        target=self.EmailCommandThread,
                        name="EmailCommandThread")
                    self.threadEmail.daemon = True
                    self.threadEmail.start()  # start IMAP thread
                else:
                    self.FatalError(
                        "ERROR: incoming_callback, incoming_folder and processed_folder are required if receive IMAP is used"
                    )
            else:
                self.LogError("IMAP disabled")
Esempio n. 19
0
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datetime, time, sys, smtplib, signal, os, threading, socket
import mylog

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


#----------  ClientInterface::init--- ------------------------------------------
class ClientInterface:
    def __init__(self, host="127.0.0.1", port=9082):

        self.EndOfMessage = "EndOfMessage"
        self.rxdatasize = 2000
        self.host = host
        self.port = port

        self.Connect()

    #----------  ClientInterface::Connect ---------------------------------
    def Connect(self):
Esempio n. 20
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)