Exemplo n.º 1
0
    def send(self, data, addr=None):
        """
        send data to addr
        :param data: response data
        :param addr: to
        """

        if not addr:
            addr = self.addr

        logger.logDebug("To '%s' sending data: '%s'" %
                        (str(addr), str(data).strip()))

        if not self.sock:
            self.initClient()  # conection error? try repair...

        if not self.sock:
            logger.logError(
                "Socket not ready! Cant't send to '%s' data '%s'." %
                (str(addr), str(data).strip()))
            return CONST.RET_IO_ERROR

        try:
            if self.protocol == SOCKET_TCP:
                self.sock.send(data)

            if self.protocol == SOCKET_UDP:
                self.sock.sendto(data, addr)

        except socket.error as err:
            logger.logError("Sending data failed. Error Code: " + str(err[0]) +
                            ' Message: ' + err[1])
            return CONST.RET_IO_ERROR

        return CONST.RET_OK
Exemplo n.º 2
0
    def stop(self):
        """
        stop process
        """

        logger.logInfo("Stoping...")
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if not pid:
            logger.logInfo("Pidfile %s does not exist. Daemon not running." %
                           self.pidfile)
            # no pidfile - no error
            return CONST.RET_OK

        #Try killing the daemon process
        try:
            logger.logDebug("Trying to kill pid %s" % pid)
            while True:
                os.kill(pid, SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    self.delPID()
            else:
                logger.logError(str(err))
                return CONST.RET_ERROR
Exemplo n.º 3
0
    def start(self):
        """
        start main process
        if not debug - daemonize
        """
        
        logger.logInfo("Starting...")

        pid = self.status()

        if pid:
            logger.logError("Daemon already running with pid %s" % self.pidfile)
            return CONST.RET_ERROR

        # Start the daemon
        if not self.debug:
            logger.logDebug("Demonizing...")
            if self.daemonize() > CONST.RET_OK:
                return CONST.RET_ERROR

        logger.logInfo("Running")

        try:
            self.run()        
            logger.logDebug("Main loop finished")
        except Exception as err:
            logger.logError("Main loop error: %s" % str(err))
            
            return CONST.RET_ERROR

        return CONST.RET_OK
Exemplo n.º 4
0
    def stop(self):
        """
        stop process
        """
        
        logger.logInfo("Stoping...")
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if not pid:
            logger.logInfo("Pidfile %s does not exist. Daemon not running." % self.pidfile)
            # no pidfile - no error
            return CONST.RET_OK

        #Try killing the daemon process
        try:
            logger.logDebug("Trying to kill pid %s" % pid)
            while True:
                os.kill(pid, SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    self.delPID()
            else:
                logger.logError(str(err))
                return CONST.RET_ERROR
Exemplo n.º 5
0
    def send(self, data, addr = None):
        """
        send data to addr
        :param data: response data
        :param addr: to
        """
        
        if not addr:
            addr = self.addr
            
        logger.logDebug("To '%s' sending data: '%s'" % (str(addr), str(data).strip()))            
            
        if not self.sock:
            self.initClient() # conection error? try repair...

        if not self.sock:
            logger.logError("Socket not ready! Cant't send to '%s' data '%s'." % (str(addr), str(data).strip()))
            return CONST.RET_IO_ERROR
            
        try:
            if self.protocol == SOCKET_TCP:
                self.sock.send(data)

            if self.protocol == SOCKET_UDP:
                self.sock.sendto(data, addr)

        except socket.error as err:
            logger.logError("Sending data failed. Error Code: " + str(err[0]) + ' Message: ' + err[1])
            return CONST.RET_IO_ERROR

        return CONST.RET_OK
Exemplo n.º 6
0
    def recv(self):
        """
        get incomming data
        """
        (recv_data, addr) = (None, None)

        if not self.sock:
            logger.logError("Cant't receive data. Socket not ready")
            return (None, None)
        
        try:
            if self.protocol == SOCKET_TCP:
                recv_data = self.sock.recv(2048)
                addr = self.addr

            if self.protocol == SOCKET_UDP:
                recv_data, addr = self.sock.recvfrom(2048)
                
        except socket.error as err:
            logger.logError("Receiving data failed. Error Code: " + str(err[0]) + ' Message: ' + err[1])
            return (None, None)
        
        logger.logDebug("From: '%s' received data: '%s'" % (str(addr), str(recv_data).strip()))

        return (recv_data, addr)
Exemplo n.º 7
0
    def responseLoop(self):
        """
        communication, recv - response loop untile exit data received
        """

        logger.logDebug("Waiting for message main loop")

        while True:
            logger.logDebug("Waiting for message...")
            (recv_data, addr) = self.recv()

            if recv_data in EXIT_DATA:
                break

            (recv_data, addr) = self.dataPreHandler(recv_data, addr)

            try:
                reply_data = self.datahandler(recv_data, addr)
            except Exception as err:
                logger.logError("Handling data error: %s" % str(err))
                reply_data = MESSAGE_HANDLER_ERROR

            if not self.replying:
                continue

            if self.send(reply_data, addr) != CONST.RET_OK:
                logger.logError("Sending response data '%s' failed!" %
                                str(reply_data))

            if reply_data in EXIT_DATA:
                break
Exemplo n.º 8
0
    def responseLoop(self):
        """
        communication, recv - response loop untile exit data received
        """
        
        logger.logDebug("Waiting for message main loop")

        while True:
            logger.logDebug("Waiting for message...")
            (recv_data, addr) = self.recv()

            if recv_data in EXIT_DATA:
                break

            (recv_data, addr) = self.dataPreHandler(recv_data, addr)
            
            try:
                reply_data = self.datahandler(recv_data, addr)
            except Exception as err:
                logger.logError("Handling data error: %s" % str(err))
                reply_data = MESSAGE_HANDLER_ERROR

            if not self.replying:
                continue

            if self.send(reply_data, addr) != CONST.RET_OK:
                logger.logError("Sending response data '%s' failed!" % str(reply_data))

            if reply_data in EXIT_DATA:
                break
Exemplo n.º 9
0
 def cecSourceActivatedCallback(self, logicalAddress, activated):
     """
     cec-callback for activated source
     """
     
     logger.logDebug("[SOURCEACTIVATED] %s:%s active source: %s" % (str(logicalAddress), str(activated), self.GetActiveSourceOsdName()))
     self.sendEvents(EVENT.CEC_ACTIVESOURCE_TEMPLATE % str(activated))
Exemplo n.º 10
0
    def cecLogCallback(self, level, timestamp, message):
        """
        cec-callback for log
        """
        
        libCECloglevel_dict = {cec.CEC_LOG_ERROR:   "ERROR",
                               cec.CEC_LOG_WARNING: "WARNING",
                               cec.CEC_LOG_NOTICE:  "NOTICE",
                               cec.CEC_LOG_TRAFFIC: "TRAFFIC",
                               cec.CEC_LOG_DEBUG:   "DEBUG",
                              }

        if hasattr(CFG, 'CEC_LOG_TO_DEFAULT_LOG') and CFG.CEC_LOG_TO_DEFAULT_LOG:
            logger.logDebug("[CEC_LOG_%s] %s %s" % (libCECloglevel_dict[level], str(timestamp), message))

        if level == cec.CEC_LOG_DEBUG:

            pattern_active_source = "^making .* \((.+?)\) the active source$"
            m_active_source = re.search(pattern_active_source, message)

            if m_active_source:
                iAddress = int(m_active_source.group(1), 16)
                osdName = self.getDeviceOSDName(int(iAddress))
                logger.logInfo("Source %s is active" % osdName)

                try:
                    self.sendEvents(EVENT.CECLOG_ACTIVESOURCE_TEMPLATE % osdName)
                except Exception as err:
                    logger.logError("error %s" % str(err))
Exemplo n.º 11
0
    def start(self):
        """
        start main process
        if not debug - daemonize
        """

        logger.logInfo("Starting...")

        pid = self.status()

        if pid:
            logger.logError("Daemon already running with pid %s" %
                            self.pidfile)
            return CONST.RET_ERROR

        # Start the daemon
        if not self.debug:
            logger.logDebug("Demonizing...")
            if self.daemonize() > CONST.RET_OK:
                return CONST.RET_ERROR

        logger.logInfo("Running")

        try:
            self.run()
            logger.logDebug("Main loop finished")
        except Exception as err:
            logger.logError("Main loop error: %s" % str(err))

            return CONST.RET_ERROR

        return CONST.RET_OK
Exemplo n.º 12
0
    def cecLogCallback(self, level, timestamp, message):
        """
        cec-callback for log
        """

        libCECloglevel_dict = {
            cec.CEC_LOG_ERROR: "ERROR",
            cec.CEC_LOG_WARNING: "WARNING",
            cec.CEC_LOG_NOTICE: "NOTICE",
            cec.CEC_LOG_TRAFFIC: "TRAFFIC",
            cec.CEC_LOG_DEBUG: "DEBUG",
        }

        if hasattr(CFG,
                   'CEC_LOG_TO_DEFAULT_LOG') and CFG.CEC_LOG_TO_DEFAULT_LOG:
            logger.logDebug(
                "[CEC_LOG_%s] %s %s" %
                (libCECloglevel_dict[level], str(timestamp), message))

        if level == cec.CEC_LOG_DEBUG:

            pattern_active_source = "^making .* \((.+?)\) the active source$"
            m_active_source = re.search(pattern_active_source, message)

            if m_active_source:
                iAddress = int(m_active_source.group(1), 16)
                osdName = self.getDeviceOSDName(int(iAddress))
                logger.logInfo("Source %s is active" % osdName)

                try:
                    self.sendEvents(EVENT.CECLOG_ACTIVESOURCE_TEMPLATE %
                                    osdName)
                except Exception as err:
                    logger.logError("error %s" % str(err))
Exemplo n.º 13
0
    def recv(self):
        """
        get incomming data
        """
        (recv_data, addr) = (None, None)

        if not self.sock:
            logger.logError("Cant't receive data. Socket not ready")
            return (None, None)

        try:
            if self.protocol == SOCKET_TCP:
                recv_data = self.sock.recv(2048)
                addr = self.addr

            if self.protocol == SOCKET_UDP:
                recv_data, addr = self.sock.recvfrom(2048)

        except socket.error as err:
            logger.logError("Receiving data failed. Error Code: " +
                            str(err[0]) + ' Message: ' + err[1])
            return (None, None)

        logger.logDebug("From: '%s' received data: '%s'" %
                        (str(addr), str(recv_data).strip()))

        return (recv_data, addr)
Exemplo n.º 14
0
 def receiveData(self, data_dict):
     """
     default receiver function
     :param data_dict: received data
     """
     
     logger.logDebug("Input data '%s' not handled" % str(data_dict).strip())
     return CONST.RET_OK
Exemplo n.º 15
0
    def receiveData(self, data_dict):
        """
        default receiver function
        :param data_dict: received data
        """

        logger.logDebug("Input data '%s' not handled" % str(data_dict).strip())
        return CONST.RET_OK
Exemplo n.º 16
0
 def turnOnBottom(self):
     """
     turn on bottom two
     """
           
     if self.daytime.isShining():
         logger.logDebug("Doing nothing due to day time.")
         return
     self.turnOn(CFG.OUTPUT_BOTTOM)  
Exemplo n.º 17
0
 def turnOnTop(self):
     """
     turn on top two
     """
     
     if self.daytime.isShining():
         logger.logDebug("Doing nothing due to day time.")
         return
     self.turnOn(CFG.OUTPUT_TOP)
Exemplo n.º 18
0
 def turnOnAll(self):
     """
     turn on all
     """
     
     if self.daytime.isShining():
         logger.logDebug("Doing nothing due to day time.")
         return
     self.turnOn(CFG.OUTPUT_ALL)    
Exemplo n.º 19
0
    def cecSourceActivatedCallback(self, logicalAddress, activated):
        """
        cec-callback for activated source
        """

        logger.logDebug("[SOURCEACTIVATED] %s:%s active source: %s" %
                        (str(logicalAddress), str(activated),
                         self.GetActiveSourceOsdName()))
        self.sendEvents(EVENT.CEC_ACTIVESOURCE_TEMPLATE % str(activated))
Exemplo n.º 20
0
 def toggle(self, arr):
     """
     piface functions (toggle command)
     :param arr: all items will be handled
     """
     
     logger.logDebug("Toggle %s" % str(arr))
     for i in arr:
         if i in CFG.OUTPUT_CLOCKWISE:
             self.pifacedigital.output_pins[i].toggle()
Exemplo n.º 21
0
 def turnOff(self, arr):
     """
     piface functions (off command)
     :param arr: all items will be handled
     """
     
     logger.logDebug("Turn off %s" % str(arr))
     for i in arr:
         if i in CFG.OUTPUT_CLOCKWISE:
             self.pifacedigital.output_pins[i].turn_off()
Exemplo n.º 22
0
 def menuHandler(self, widget, data = None):   
     """
     send command on item click
     """
     
     target = data.split(CONST.DELIMITER)[0]
     cmdstring = CONST.DELIMITER.join(data.split(CONST.DELIMITER)[1:])
     
     logger.logDebug("Sending cmd for %s: '%s'" % (target, cmdstring) )
     self.sendCommands([cmdstring], target)
Exemplo n.º 23
0
    def menuHandler(self, widget, data=None):
        """
        send command on item click
        """

        target = data.split(CONST.DELIMITER)[0]
        cmdstring = CONST.DELIMITER.join(data.split(CONST.DELIMITER)[1:])

        logger.logDebug("Sending cmd for %s: '%s'" % (target, cmdstring))
        self.sendCommands([cmdstring], target)
Exemplo n.º 24
0
    def initDefaultCB(self):
        """
        initialize default callbacks
        """

        logger.logDebug("Settings CEC default callbacks")
        self.setLogCallback(self.cecLogCallback)
        self.setKeyPressCallback(self.cecKeyPressCallback)
        self.setCommandCallback(self.cecCommandCallback)
        self.setMenuStateCallback(self.cecMenuStateCallback)
        self.setSourceActivatedCallback(self.cecSourceActivatedCallback)
Exemplo n.º 25
0
 def initDefaultCB(self):
     """
     initialize default callbacks
     """
     
     logger.logDebug("Settings CEC default callbacks")
     self.setLogCallback(self.cecLogCallback)
     self.setKeyPressCallback(self.cecKeyPressCallback)
     self.setCommandCallback(self.cecCommandCallback)    
     self.setMenuStateCallback(self.cecMenuStateCallback)
     self.setSourceActivatedCallback(self.cecSourceActivatedCallback)
Exemplo n.º 26
0
Arquivo: gui.py Projeto: vchlum/shnopp
 def menuHandler(self, widget, data = None):   
     """
     handle data when menu item used
     :param widget: 
     :param data: full item string
     """
             
     target = data.split(CONST.DELIMITER)[0]
     cmdstring = CONST.DELIMITER.join(data.split(CONST.DELIMITER)[1:])
     
     logger.logDebug("Sending cmd for %s: '%s'" % (target, cmdstring) )
     self.sendCommands([cmdstring], target)
Exemplo n.º 27
0
 def transmitCode(self, code):
     """
     transmit code using pi_switch
     :param code: code to transmit
     """
     
     try:
         logger.logDebug("Transmitting code: %s" % str(code))
         self.ac_socks.send(code)
         time.sleep(CFG.MIN_TRNASMIT_INTERVAL)
     except Exception as err:
         logger.logError("Transmitting AC socket code error: %s" % str(err))
Exemplo n.º 28
0
 def run(self):
     """
     create gtk systry menu and ask for items
     """
     
     self.askForItems()
             
     try:
         self.systray = gtk.StatusIcon()
         self.systray.set_from_stock(gtk.STOCK_ABOUT)
         self.systray.connect('popup-menu', self.onRightClick)
         gtk.main()
     except Exception as err:
         logger.logDebug("error: %s", err )
Exemplo n.º 29
0
    def run(self):
        """
        create gtk systry menu and ask for items
        """

        self.askForItems()

        try:
            self.systray = gtk.StatusIcon()
            self.systray.set_from_stock(gtk.STOCK_ABOUT)
            self.systray.connect('popup-menu', self.onRightClick)
            gtk.main()
        except Exception as err:
            logger.logDebug("error: %s", err)
Exemplo n.º 30
0
    def lightLighting(self):
        """
        event specific function
        """
        
        if self.daytime.isShining():
            logger.logDebug("Doing nothing due to day time.")
            return

        if not CFG.AC_SOCK_2 in CFG.MY_PLACES:
            return

        code = self.items[CFG.AC_SOCK_2][CFG.AC_SOCK_2_2][CMD.ON]
        self.tasker.putTask(code)
Exemplo n.º 31
0
    def morningLight(self):
        """
        event specific function
        never used yet
        """
        
        if self.daytime.isShining():
            logger.logDebug("Doing nothing due to day time.")
            return

        if not CFG.AC_SOCK_1 in CFG.MY_PLACES:
            return

        code = self.items[CFG.AC_SOCK_1][CFG.AC_SOCK_1_1][CMD.ON]
        self.tasker.putTask(code)

        code = self.items[CFG.AC_SOCK_1][CFG.AC_SOCK_1_2][CMD.ON]
        self.tasker.putTask(code)
Exemplo n.º 32
0
    def goForBeerLighting(self):
        """
        event specific function
        """
        
        if self.daytime.isShining():
            logger.logDebug("Doing nothing due to day time.")
            return
        
        ac_sockets_to_on = [(CFG.AC_SOCK_2, CFG.AC_SOCK_2_2, CMD.ON), 
                            (CFG.AC_SOCK_3, CFG.AC_SOCK_2_4, CMD.ON)]

        for (place, ac_sock, sockcmd) in ac_sockets_to_on:
            if not place in CFG.MY_PLACES:
                continue

            code = self.items[place][ac_sock][sockcmd]
            self.tasker.putTask(code)
Exemplo n.º 33
0
    def listenTCPThread(self):
        """
        TCP listener thread
        """
        
        logger.logInfo("TCP listener started on '%s'" % str(self.addr))

        while True:
            try:
                (client_sock, client_addr) = self.sock.accept()
            except socket.error as err:
                logger.logError("Failed to accept TCP connection. Error Code: " + str(err[0]) + ' Message: ' + err[1])
                break

            logger.logDebug("Connection with '%s' accepted." % str(client_addr))
            threading.Thread(target=self.startComunication, args=(client_addr, client_sock)).start()

        logger.logInfo("TCP listener on '%s' ended" % str(self.addr))
Exemplo n.º 34
0
    def initConfig(self, this_cec_name):
        """
        initialize cec config
        :param this_cec_name: name for this device
        """
        
        logger.logDebug("Initializing libCEC config")

        try:
            self.cecconfig.strDeviceName = self.this_cec_name
            # 0 = do not make the primary device the active source 
            self.cecconfig.bActivateSource = 0
            # https://github.com/Pulse-Eight/libcec/blob/2c675dac48387c48c7f43c5d2547ef0c4ef5c7dd/include/cectypes.h
            #self.cecconfig.bMonitorOnly = 1
            self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE)
            self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT
        except Exception as err:
            logger.logError("Initializing libCEC config error: %s" % str(err) )
Exemplo n.º 35
0
    def initConfig(self, this_cec_name):
        """
        initialize cec config
        :param this_cec_name: name for this device
        """

        logger.logDebug("Initializing libCEC config")

        try:
            self.cecconfig.strDeviceName = self.this_cec_name
            # 0 = do not make the primary device the active source
            self.cecconfig.bActivateSource = 0
            # https://github.com/Pulse-Eight/libcec/blob/2c675dac48387c48c7f43c5d2547ef0c4ef5c7dd/include/cectypes.h
            #self.cecconfig.bMonitorOnly = 1
            self.cecconfig.deviceTypes.Add(
                cec.CEC_DEVICE_TYPE_RECORDING_DEVICE)
            self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT
        except Exception as err:
            logger.logError("Initializing libCEC config error: %s" % str(err))
Exemplo n.º 36
0
    def detectDevices(self):
        """
        detect hdmi-cec devices
        """
        
        logger.logDebug("Detecting CEC devices")

        try:
            self.libCEC.RescanActiveDevices()
            addresses = self.libCEC.GetActiveDevices()
            activeSource = self.libCEC.GetActiveSource()
            logger.logInfo("CEC active device: %s" % self.getDeviceOSDName(activeSource) )
            
            for iAddress in range(0, 15):
                if addresses.IsSet(iAddress):
                    self.devices[self.libCEC.GetDeviceOSDName(iAddress)] = self.Device(iAddress, self.libCEC)
                    logger.logInfo("CEC device %s detected on address: %i" % (self.libCEC.GetDeviceOSDName(iAddress), iAddress) )

        except Exception as err:
            logger.logError("Detecting CEC devices error: %s" % str(err) )
Exemplo n.º 37
0
    def detectAdapter(self):
        """
        detect an adapter and return the com port path
        """
        
        logger.logDebug("Detecting CEC adapters")

        try:
            adapter_found = None
            adapters = self.libCEC.DetectAdapters()

            for adapter in adapters:
                logger.logInfo("CEC adapter found on port: %s vendor: %s product: %s" % (adapter.strComName, hex(adapter.iVendorId), hex(adapter.iProductId)))
                adapter_found = adapter.strComName

            return adapter_found

        except Exception as err:
            logger.logError("Detecting CEC adapter error: %s" % str(err) )
            return None
Exemplo n.º 38
0
        def POST(self, id):
            """
            post
            """
            
            id=id.encode('utf-8')
            if (str(id) == "askForItems"):
                global items
                items.clear()
                askForItems()
                time.sleep(2)
                
            id = id + CONST.DELIMITER + web.data().encode('utf-8').split("=")[1]
            
            target = id.split(CONST.DELIMITER)[0]
            cmdstring = CONST.DELIMITER.join(id.split(CONST.DELIMITER)[1:])
        
            logger.logDebug("Sending cmd for %s: '%s'" % (target, cmdstring) )
            sendCommands([cmdstring], target)

            raise web.seeother('/')
Exemplo n.º 39
0
    def taskThread(self):
        """
        tasker main thread - loop 
        """
        
        logger.logDebug("Task thread started")

        self.tasks = Queue.Queue()
        while True:
            try:
                task = self.tasks.get()

                if self.handler:
                    try:
                        self.handler(task)
                    except Exception as err:
                        logger.logDebug("Task error: %s" % str(err))

                self.tasks.task_done()
            except:
                pass
Exemplo n.º 40
0
    def taskThread(self):
        """
        tasker main thread - loop 
        """

        logger.logDebug("Task thread started")

        self.tasks = Queue.Queue()
        while True:
            try:
                task = self.tasks.get()

                if self.handler:
                    try:
                        self.handler(task)
                    except Exception as err:
                        logger.logDebug("Task error: %s" % str(err))

                self.tasks.task_done()
            except:
                pass
Exemplo n.º 41
0
    def setStatus(self, devid, newstatus, switch=1):
        done = False

        for attempt in ("first", "second", "third"):
            try:
                logger.logDebug("%s try to set status on %s" % (attempt, devid))

                key = CFG.DEVICES[devid]
                tuyadev = pytuya.OutletDevice(devid, key[0], key[1])

                status = tuyadev.status()['dps'][str(switch)]
                if status == newstatus:
                    logger.logDebug("status already set, skipping  %s" % devid)
                    break

                tuyadev.set_status(newstatus, switch)
                time.sleep(CFG.SLEEP_INTERVAL)

                status = tuyadev.status()['dps'][str(switch)]
                if status == newstatus:
                    logger.logDebug("status successfully set %s" % devid)
                    done = True
            except:
                logger.logError("failed to set status of %s" % devid)

            if done:
                break
Exemplo n.º 42
0
    def setTuyaStatus(self, devid, newstatus, switch=1):
        done = False

        for attempt in ("first", "second", "third"):
            try:
                logger.logDebug("%s try to set status on %s" %
                                (attempt, devid))

                key = CFG.DEVICES[devid]
                tuyadev = pytuya.OutletDevice(devid, key[0], key[1])

                status = tuyadev.status()['dps'][str(switch)]
                if status == newstatus:
                    logger.logDebug("status already set, skipping  %s" % devid)
                    break

                tuyadev.set_status(newstatus, switch)
                time.sleep(CFG.SLEEP_INTERVAL)

                status = tuyadev.status()['dps'][str(switch)]
                if status == newstatus:
                    logger.logDebug("status successfully set %s" % devid)
                    done = True
            except:
                logger.logError("failed to set status of %s" % devid)

            if done:
                break
Exemplo n.º 43
0
    def listenTCPThread(self):
        """
        TCP listener thread
        """

        logger.logInfo("TCP listener started on '%s'" % str(self.addr))

        while True:
            try:
                (client_sock, client_addr) = self.sock.accept()
            except socket.error as err:
                logger.logError(
                    "Failed to accept TCP connection. Error Code: " +
                    str(err[0]) + ' Message: ' + err[1])
                break

            logger.logDebug("Connection with '%s' accepted." %
                            str(client_addr))
            threading.Thread(target=self.startComunication,
                             args=(client_addr, client_sock)).start()

        logger.logInfo("TCP listener on '%s' ended" % str(self.addr))
Exemplo n.º 44
0
        def POST(self, id):
            """
            post
            """

            id = id.encode('utf-8')
            if (str(id) == "askForItems"):
                global items
                items.clear()
                askForItems()
                time.sleep(2)

            id = id + CONST.DELIMITER + web.data().encode('utf-8').split(
                "=")[1]

            target = id.split(CONST.DELIMITER)[0]
            cmdstring = CONST.DELIMITER.join(id.split(CONST.DELIMITER)[1:])

            logger.logDebug("Sending cmd for %s: '%s'" % (target, cmdstring))
            sendCommands([cmdstring], target)

            raise web.seeother('/')
Exemplo n.º 45
0
    def listenServer(self):
        """
        server listener
        """

        logger.logDebug("Starting listener on '%s'" % str(self.addr))

        if self.protocol == SOCKET_TCP:
            listenerthread = self.listenTCPThread

        if self.protocol == SOCKET_UDP:
            listenerthread = self.listenUDPThread

        if self.keepalive:
            t_target = self.keepAliveThread
            t_args = (self.startServer, listenerthread)
        else:
            t_target = listenerthread
            t_args = ()

        t = threading.Thread(target=t_target, args=t_args)
        t.setDaemon(True)
        t.start()
Exemplo n.º 46
0
    def detectAdapter(self):
        """
        detect an adapter and return the com port path
        """

        logger.logDebug("Detecting CEC adapters")

        try:
            adapter_found = None
            adapters = self.libCEC.DetectAdapters()

            for adapter in adapters:
                logger.logInfo(
                    "CEC adapter found on port: %s vendor: %s product: %s" %
                    (adapter.strComName, hex(
                        adapter.iVendorId), hex(adapter.iProductId)))
                adapter_found = adapter.strComName

            return adapter_found

        except Exception as err:
            logger.logError("Detecting CEC adapter error: %s" % str(err))
            return None
Exemplo n.º 47
0
    def listenServer(self):
        """
        server listener
        """
        
        logger.logDebug("Starting listener on '%s'" % str(self.addr))
        
        if self.protocol == SOCKET_TCP:
            listenerthread = self.listenTCPThread

        if self.protocol == SOCKET_UDP:
            listenerthread = self.listenUDPThread

        if self.keepalive:
            t_target = self.keepAliveThread
            t_args = (self.startServer, listenerthread)
        else:
            t_target = listenerthread
            t_args = ()

        t = threading.Thread(target = t_target, args = t_args)
        t.setDaemon(True)
        t.start()
Exemplo n.º 48
0
    def run(self):
        """
        plugin main
        """

        self.rfdevice.enable_rx()
        timestamp = None
        lastcode = None

        while True:
            if self.rfdevice.rx_code_timestamp != timestamp:
                try:
                    if lastcode == self.rfdevice.rx_code and self.rfdevice.rx_code_timestamp < timestamp + 1000000:
                        timestamp = self.rfdevice.rx_code_timestamp
                        logger.logDebug("rf433_receive skipping: %s" %
                                        str(timestamp))
                        time.sleep(CFG.SLEEP_INTERVAL)
                        continue
                except:
                    logger.logDebug("rf433_receive passing: %s" %
                                    str(timestamp))
                logger.logDebug("rf433_receive timestamp: %s" % str(timestamp))
                timestamp = self.rfdevice.rx_code_timestamp
                lastcode = self.rfdevice.rx_code
                logger.logDebug(
                    "rf433_receive code: %s length %s protocol: %s" %
                    (str(self.rfdevice.rx_code),
                     str(self.rfdevice.rx_pulselength),
                     str(self.rfdevice.rx_proto)))

                keycode = str(self.rfdevice.rx_code)
                if keycode in CFG.RF433.keys() and CFG.RF433[keycode][0]:
                    if len(CFG.RF433[keycode]) == 2:
                        self.setTuyaStatus(CFG.RF433[keycode][0],
                                           CFG.RF433[keycode][1])
                    if len(CFG.RF433[keycode]) == 3:
                        self.setTuyaStatus(CFG.RF433[keycode][0],
                                           CFG.RF433[keycode][1],
                                           CFG.RF433[keycode][2])
                    time.sleep(CFG.SLEEP_INTERVAL)
                else:
                    self.sendEvents(EVENT.RF433_PRESSED %
                                    self.rfdevice.rx_code)

            time.sleep(CFG.SLEEP_INTERVAL)

        rfdevice.cleanup()
Exemplo n.º 49
0
    def detectDevices(self):
        """
        detect hdmi-cec devices
        """

        logger.logDebug("Detecting CEC devices")

        try:
            self.libCEC.RescanActiveDevices()
            addresses = self.libCEC.GetActiveDevices()
            activeSource = self.libCEC.GetActiveSource()
            logger.logInfo("CEC active device: %s" %
                           self.getDeviceOSDName(activeSource))

            for iAddress in range(0, 15):
                if addresses.IsSet(iAddress):
                    self.devices[self.libCEC.GetDeviceOSDName(
                        iAddress)] = self.Device(iAddress, self.libCEC)
                    logger.logInfo(
                        "CEC device %s detected on address: %i" %
                        (self.libCEC.GetDeviceOSDName(iAddress), iAddress))

        except Exception as err:
            logger.logError("Detecting CEC devices error: %s" % str(err))
Exemplo n.º 50
0
class Daemon(object):
    """
    deamon class - inspired by:
    http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
    """
    def __init__(self, pidfile, debug):
        """
        deamon init function
        :param pidfile: used pidfile
        :param debug: True/False - affects forking
        """
        self.pidfile = pidfile
        self.debug = debug

    def daemonize(self):
        """
        daemonize process
        """

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            logger.logError("fork #1 failed: %d (%s)\n" %
                            (e.errno, e.strerror))
            return CONST.RET_ERROR

        logger.logDebug("fork #1 finished")

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            logger.logError("fork #2 failed: %d (%s)\n" %
                            (e.errno, e.strerror))
            return CONST.RET_ERROR
Exemplo n.º 51
0
    def run(self):
        """
        plugin main
        """
        
        self.rfdevice.enable_rx()
        timestamp = None
        lastcode = None

        while True:
            if self.rfdevice.rx_code_timestamp != timestamp:
                try:
                    if lastcode == self.rfdevice.rx_code and self.rfdevice.rx_code_timestamp < timestamp + 1000000:
                        timestamp = self.rfdevice.rx_code_timestamp
                        logger.logDebug("rf433_receive skipping: %s" % str(timestamp))
                        time.sleep(CFG.SLEEP_INTERVAL)
                        continue
                except:
                    logger.logDebug("rf433_receive passing: %s" % str(timestamp))
                logger.logDebug("rf433_receive timestamp: %s" % str(timestamp))
                timestamp = self.rfdevice.rx_code_timestamp
                lastcode = self.rfdevice.rx_code
                logger.logDebug("rf433_receive code: %s length %s protocol: %s" % (str(self.rfdevice.rx_code), str(self.rfdevice.rx_pulselength), str(self.rfdevice.rx_proto)))

                keycode = str(self.rfdevice.rx_code)
                if keycode in CFG.RF433.keys() and CFG.RF433[keycode][0]:
                    if len(CFG.RF433[keycode]) == 2:
                        self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1])
                    if len(CFG.RF433[keycode]) == 3:
                        self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1], CFG.RF433[keycode][2])
                    time.sleep(CFG.SLEEP_INTERVAL)
                else:
                    self.sendEvents(EVENT.RF433_PRESSED % self.rfdevice.rx_code)

            time.sleep(CFG.SLEEP_INTERVAL)

        rfdevice.cleanup()
Exemplo n.º 52
0
    def cecKeyPressCallback(self, keycode, duration):
        """
        cec-callback for key press
        """

        if duration == 0:
            logger.logDebug("[KEY] %s pressed, time: %s" %
                            (str(keycode), str(duration)))
            self.sendEvents(EVENT.CEC_KEYPRESSED_TEMPLATE % keycode)

        if duration > 0:
            logger.logDebug("[KEY] %s released, time: %s" %
                            (str(keycode), str(duration)))
            self.sendEvents(EVENT.CEC_KEYRELEASED_TEMPLATE % keycode)

            if keycode in self.keymap.keys():
                if hasattr(CFG, 'EMIT_REMOTECONTROL_KEYS'
                           ) and CFG.EMIT_REMOTECONTROL_KEYS:
                    self.uidevice.emit_click(self.keymap[keycode])
                    logger.logDebug("[KEY] code %s emitted" %
                                    str(self.keymap[keycode]))
Exemplo n.º 53
0
        def POST(self):
            """
            post
            """
            global items

            try:
                input = web.input()
                if 'pwd' in input.keys(
                ) and input['pwd'] == CFG.WEB_HOOK_PASSWORD:
                    logger.logDebug("password ok")
                    if 'action' in input.keys(
                    ) and input['action'] in items.keys():
                        if len(items[input['action']]) > 0:
                            sendEvents(items[input['action']])
                            return "ok"
                    else:
                        logger.logDebug("wrong action")
                else:
                    logger.logDebug("wrong password")

            except Exception as err:
                logger.logError(str(err))
            return "none"
Exemplo n.º 54
0
        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            logger.logError("fork #2 failed: %d (%s)\n" %
                            (e.errno, e.strerror))
            return CONST.RET_ERROR

        logger.logDebug("fork #2 finished")

        try:  # redirect standard file descriptors if not yet
            logger.closestdIO()
        except:
            pass

        # write pidfile
        atexit.register(self.delPID)
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)

        logger.logInfo("Sucessfully daemonized with pid: %s" % pid)

        return CONST.RET_OK
Exemplo n.º 55
0
    def cecMenuStateCallback(self, state):
        """
        cec-callback for menu state
        """

        logger.logDebug("[MENUSTATE] %s" % str(state))
Exemplo n.º 56
0
    def cecCommandCallback(self, cmd):
        """
        cec-callback for command
        """

        logger.logDebug("[COMMAND] %s" % cmd)