Esempio n. 1
0
    def start_listener(self):
        '''
        Creates a new thread listening for an upstream 
        connection from the ground station.
        '''
        listenerThread = Listener(self.recievedQueue)
        listenerThread.setName('ISRU Listener')
        listenerThread.start()

        return listenerThread
Esempio n. 2
0
 def __init__(self, op, caption, post_id, file_format, addr):
     self.likes = 0
     self.op = op
     self.caption = caption
     self.id = post_id
     self.liked_by = []
     self.file_format = file_format
     self.link = 'users/' + str(int(post_id / lpn)) + '/' + str(
         post_id % lpn) + '.' + self.file_format
     self.list_sock = None
     listener = Listener(self.link, addr, self)
     listener.start()
Esempio n. 3
0
 def __init__(self, controller):
     self.controller = controller
     listener = Listener(controller)
     listener.start()
Esempio n. 4
0
class RemoteMsg(object):
    """ 
    _RemoteMsg_ 
 
    Main interface of the RemoteMsg module. Clients wishing to use the 
    RemoteMsg should instantiate an object of this class and interface 
    it using the public methods declared by it.
    
    """

    def __init__(self, config, addresses=[], queue=True):
        """
        Constructor.
        
        Requires a WMCore.Configuration object with configuration 
        information. The addresses of recipients and the flag for 
        queue/handling mode can be set with setAdress or setQueue methods 
        also (have a look at their docstring for further help). The 
        listener for messages needs to be started with the startListener 
        method, meanwhile only publication capabilities are available.
        """
        self.myconfig = config

        sections = self.myconfig.listSections_()
        if not "RemoteMsg" in sections:
            msg = "Cannot create RemoteMsg object without "
            msg += "RemoteMsg section in config file"
            raise Exception(msg)

        self.mylogger = None
        self.logMsg = None
        self.__setLogging__()
        self.mylogger.info("\n\n>>>>>RemoteMsg object being created <<<<<<\n")

        self.myComp = None
        if hasattr(self.myconfig.RemoteMsg, "inComponent"):
            self.myComp = self.myconfig.RemoteMsg.inComponent

        self.queueMode = queue
        self.addresses = addresses
        self.user = None
        self.passwd = None

        self.msgLock = threading.Lock()
        self.handlerLock = threading.Lock()
        self.factory = WMFactory("RemoteMsg")

        # If this is instantiated by a WMCore component, get its DB interface
        if self.myComp:
            # Get a reference to our invoking component's DB factory
            myThread = threading.currentThread()
            self.dbFactory = myThread.dbFactory
            self.dialect = myThread.dialect

        # TODO: Our msg queue is just in memo for now, but it might be in a DB
        # We already have the DB interface, but we would need our own Create
        # and Queries modules (in principle, different from those of the comp)
        #         self.factory = WMFactory("threadPool", "WMCore.ThreadPool."+ \
        #                              myThread.dialect)
        #         self.queries = factory.loadObject(self.myComp+"Database"+ \
        #                                        myThread.dialect+"Queries")

        self.msgQueue = []
        self.handlerMap = {}

        # Formatter for responses (change only if in synchronous mode)
        formatter = "RemoteMsgComp.DefaultFormatter"
        if hasattr(self.myconfig.RemoteMsg, "formatter"):
            formatter = self.myconfig.RemoteMsg.formatter
        formatterObj = self.factory.loadObject(formatter)

        params = {
            "msgQueue": self.msgQueue,
            "handlerMap": self.handlerMap,
            "msgLock": self.msgLock,
            "formatter": formatterObj,
            "queueMode": self.queueMode,
        }

        if self.myComp:
            params["component"] = self.myComp
            params["dbFactory"] = self.dbFactory
            params["dialect"] = self.dialect

        self.httpTree = HttpTree(params)

        self.sender = None
        self.__createSender__()
        self.listener = None

    def __del__(self):
        # Tell cherrypy to die
        self.mylogger.info("Asking listener to die")
        if self.listener:
            self.listener.terminate()
            self.listener.join()

    def __setLogging__(self):
        """
        Initializes logging. Use by the constructor.
        """
        compSect = self.myconfig.RemoteMsg

        # Logging
        if not hasattr(compSect, "logFile"):
            compSect.logFile = os.path.join(compSect.RemoteMsgDir, "remoteMsg.log")
        print("Log file is: " + compSect.logFile)

        if not hasattr(compSect, "listenerLogFile"):
            compSect.listenerLogFile = os.path.join(compSect.RemoteMsgDir, "listener.log")
        print("Listener log file is: " + compSect.listenerLogFile)

        logHandler = RotatingFileHandler(compSect.logFile, "a", 1000000, 3)
        logFormatter = logging.Formatter("%(asctime)s:%(levelname)s:%(filename)s:%(message)s")
        logHandler.setFormatter(logFormatter)
        self.mylogger = logging.getLogger("RemoteMsg")
        self.mylogger.addHandler(logHandler)
        self.mylogger.setLevel(logging.INFO)
        # map log strings to integer levels:
        self.logMsg = {
            "DEBUG": logging.DEBUG,
            "ERROR": logging.ERROR,
            "NOTSET": logging.NOTSET,
            "CRITICAL": logging.CRITICAL,
            "WARNING": logging.WARNING,
            "INFO": logging.INFO,
        }
        ##                    'SQLDEBUG' : logging.SQLDEBUG  }
        if hasattr(compSect, "logLevel") and compSect.logLevel in self.logMsg.keys():
            self.mylogger.setLevel(self.logMsg[compSect.logLevel])

    def __createSender__(self):
        """
        Initializes the sender object. Used by the constructor.
        """

        # Sender is not a new thread, so it does not need a lock
        params = {}
        params["addresses"] = self.addresses
        params["port"] = "8030"
        if hasattr(self.myconfig.RemoteMsg, "senderPort"):
            params["port"] = self.myconfig.RemoteMsg.senderPort
        params["service"] = "msg"
        if hasattr(self.myconfig.RemoteMsg, "senderService"):
            params["service"] = self.myconfig.RemoteMsg.senderService
        params["user"] = None
        if hasattr(self.myconfig.RemoteMsg, "senderUser"):
            params["user"] = self.myconfig.RemoteMsg.senderUser
        params["pwd"] = None
        if hasattr(self.myconfig.RemoteMsg, "senderPwd"):
            params["pwd"] = self.myconfig.RemoteMsg.senderPwd
        params["realm"] = "RemoteMsg"
        if hasattr(self.myconfig.RemoteMsg, "realm"):
            params["realm"] = self.myconfig.RemoteMsg.senderRealm

        self.sender = Sender(self.msgQueue, params)

    def startListener(self):
        """
        Starts a listener for incoming remote messages. The method will refuse
        to create a listener if there is already one
        """
        if not self.listener:
            self.mylogger.info("Starting listener")
            self.listener = Listener(self.httpTree, self.myconfig)
            self.listener.start()
        else:
            msg = "Refusing to start listener (there is already one)."
            self.mylogger.info(msg)

    def setAddress(self, addresses):
        """
        Sets the addresses of the remote ends. Argument should be a list of 
        IPs or hostnames. The publish method will send messages to all members
        of this list.
        """
        self.addresses = addresses
        self.sender.setAddress(self.addresses)

    def setAuthentication(self, user, passwd):
        """
        Sets the user/password for authentication
        with the remote application. Has to be done
        before sending a message.
        """
        self.mylogger.debug("Setting user and passwd")
        self.user = user
        self.passwd = passwd

    def setQueue(self, value):
        """
        This is an option that either allows messages that are being received
        to be put in a local queue (so a get method can retrieve them), or if
        set to False  messages are handled directly through the handler framework.
        """
        self.queueMode = value
        self.httpTree.setQueue(self.queueMode)

    def get(self):
        """
        Gets messages from the local buffer (those not handled as explained 
        in the setQueue method).
        The first message of the queue is retrieved and returned. This method
        is only used when the queue is set to True. If queue is set to False
        or there are no stored messages, None is returned.
        """
        if self.queueMode:
            self.msgLock.acquire()
            if self.msgQueue:
                result = self.msgQueue.pop(0)
            else:
                result = None
            self.msgLock.release()
            return result
        else:
            return None

    def publish(self, msgType, payload, sync=False):
        """
        Sends a message to the remote end. 
     
        If sync is set to True, the remote server will complete the message
        handling before replying with some generated data. Otherwise, the 
        remote end will immediately reply with some "Message received"
        indication and execute the handler asynchronously (if the remote end
        is in queue mode, there is no handler execution, so this flag is 
        meaningless).
        
        In any case, the response of the message (e.g. a json string product 
        of the handling of the HTTP request) is returned. 
     
        Can throw an HTTP exception in case of error connecting with the remote
        end.
        """
        return self.sender.send(msgType, payload, sync)

    def setHandler(self, msgType, handler):
        """
        Maps the specified handler to the indicated message type.
        The handler must be the name of a class which can be called (e.g.
        RemoteMsg.SimpleHandler). The handler will only be called if
        queue mode is set to False.
        """
        msg = "Setting new handler %s for msgType %s" % (handler, msgType)
        self.mylogger.debug(msg)
        #  Factory to dynamically load handlers
        params = {}
        if self.myComp:
            params["component"] = self.myComp
        newHandler = self.factory.loadObject(handler, params)
        self.handlerLock.acquire()
        self.handlerMap[msgType] = newHandler
        self.handlerLock.release()
Esempio n. 5
0
from Listener import Listener
from dotenv import load_dotenv
import logging
from time import sleep
import os

logging.basicConfig(level=logging.INFO)

current_dir = os.path.dirname(os.path.abspath(__file__))
load_dotenv(dotenv_path="{}/.env".format(current_dir))

l = Listener()
l.start()


def main():
    while True:
        logging.info("*")
        sleep(1)
        if l.stop():
            break


if __name__ == '__main__':
    main()
Esempio n. 6
0
from Server import server
import time
import logging
import os.path

if __name__ == '__main__':
    
    currdir = os.path.abspath(os.getcwd()+'/../')
    
    try:
        logging.basicConfig(filename=os.path.normpath(currdir+'/logs/runlog.log'), level=logging.DEBUG)
           
        db = Database()
        
        listener = Listener(6969,256,db)
        listener.start()
        
        logging.info("Waiting 15 seconds for sensor data to populate the database...")
        time.sleep(15)
        
        serverdoc = Pagenator(db)
        #print serverdoc
        
        webpage = server(serverdoc,db)
        webpage.run()
        
    except SystemExit:
        print "Shutting Down..."
        logging.info("Shutting Down Main Thread...")
        webpage.stop()
        listener.stop()
Esempio n. 7
0
from Listener import Listener
from pynput.keyboard import Key, Controller
import serial

listener = Listener(
    serial.Serial(port="COM5",
                  baudrate=115200,
                  bytesize=8,
                  timeout=2,
                  stopbits=serial.STOPBITS_ONE))
keyboard = Controller()

commands = listener.start()

for command in commands:

    if (command == 'buttonA'):
        keyboard.press(Key.space)
    elif (command == 'buttonB'):
        keyboard.press(Key.down)
    else:
        keyboard.release(Key.down)
        keyboard.release(Key.space)
Esempio n. 8
0
class NetworkManager(LogImplementer, Thread):
    isRunning = True
    incomingMessages = Queue(MAX_PENDING_MESSAGES)
    outgoingMessages = Queue(MAX_PENDING_MESSAGES)
    listener = None
    initiaterFactory = None
    receiverFactory = None
    receiverList = []
    initiaterList = []
    threadList = []

    def __init__(self):
        LogImplementer.__init__(self)
        Thread.__init__(self)
        self.listener = Listener(self.incomingMessages)

        self.createReceiverCallbacks()
        assert (self.callbackDict is not None
                ), f'Failed to create dictionary for callback functions!'

        self.initiaterFactory = InitiatorFactory()
        self.receiverFactory = ReceiverFactory(self.callbackDict)
        self.setName('Net-Man Thread')

    def createReceiverCallbacks(self):
        callbacks = dict()
        self.callbackDict = callbacks

    def run(self):
        while self.isRunning:
            if (not self.incomingMessages.empty()):
                message = self.incomingMessages.get_nowait()
                self.processIncomingMessage(message)

            if (not self.outgoingMessages.empty()):
                message = self.outgoingMessages.get_nowait()
                self.createInitiater(message)

        self.cleanup()
        self.logger.info('All cleaned up, terminating...')

    def processIncomingMessage(self, message):
        if message:
            receiver = self.receiverFactory.createReceiver(message)

            receiver.start()
            self.receiverList.append(receiver)
        else:
            self.logger.debug('Empty message received, moving on...')

    def createInitiater(self, message):
        if message:
            self.logger.debug(
                f'New message to deliver [{message.type}], creating handler')

            initiator = self.initiaterFactory.createInitiator(
                message, message.sender)
            initiator.start()
            self.initiaterList.append(initiator)
        else:
            self.logger.debug('Empty message received, moving on...')

    def cleanup(self):
        self.logger.info('All finished, joining threads now...')
        self.listener.off()
        self.listener.join()

        self.logger.info('Listener thread joined. Continuing')

        for initiater in self.initiaterList:
            initiater.join()

        for receiver in self.receiverList:
            receiver.join()

    def turnOff(self):
        self.isRunning = False

    def getConnectedDevices(self):
        return InsTable().getNames()

    def initListener(self):
        self.listener.start()
        self.listener.setTimeout(0.05)

    def initialise(self):
        self.initListener()

        handshakeMessage = MessageFactory.createHandshakeMessage()
        self.outgoingMessages.put(handshakeMessage)

        self.start()
Esempio n. 9
0
reporterlogger = logging.getLogger("reporter")
reporterlogger.setLevel(logging.DEBUG)
reporterfh = logging.handlers.RotatingFileHandler('logs/Reporter.log', maxBytes = 10*1024*1024, backupCount=2)
reporterfh.setFormatter(formatter)
reporterlogger.addHandler(reporterfh)

########initialize Listeners
#first create server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('192.168.1.222', 1060))
overseerlogger.info("(+) Listening socket created.")
#create 5 Listeners and start them
for i in range(5):
	t = Listener(sock, i+1)
	t.start()
	overseerlogger.info("(+) Listener "+str(i+1)+" started.")

########Initialize Alert Queue
alertQueue = Queue()

########initialize Reporter
reporter = Reporter(alertQueue, 0)
reporter.start()
overseerlogger.info("(+) Reporter started.")
	
########Initialize dict to hold phrases of active sessions and their states
sessionsDict = dict()
#Initialize list to hold SessionHanlder objects
sessionHandlers = list()
Esempio n. 10
0
from Listener import Listener
from Client import Client


listener = Listener()
client = Client()
listener.start()
client.start()
input()
listener.stop()

class Manager:
    #método construtor
    def __init__(self):
        #lista de conectados
        self.connected = []

        #lista de nomes conectados
        self.names_connected = []

        #instancia um cliente
        self.client = Client()

        #threads
        #envio
        self.ts = None
        #recebimento multicast
        self.tr = None
        #recebimento privado
        self.trp = None
        #listener para entrada do teclado
        self.tl = None

        #flag de controle para que não seja enviado mais que uma mensagem (type 3)
        self.is_first_message = True

    #função que inicializa a threads
    def set_threads(self, manager):
        self.ts = Sender(self.client.multicast_addr, self.client.port,
                         self.client.pvt_port)
        self.ts.start()
        self.tr = Receiver(self.client.multicast_addr, self.client.port,
                           manager)
        self.tr.start()
        self.trp = Receiver_pvt(manager)
        self.trp.start()
        self.tl = Listener(manager)
        self.tl.start()

    #fecha a conexão com os sockets
    def stop_threads(self):
        self.ts.close()
        self.tr.close()
        self.trp.close()

    #adiciona um usuário na lista de conectados
    def add_user(self, client):
        self.connected.append(client)
        self.names_connected.append(client.nick)

    #remove um usuário da lista de conectados
    def pop_user(self, client):
        if (client in self.connected):
            self.connected.remove(client)
        self.names_connected.remove(client.nick)
        print("------------------------------")
        print(client.nick, "saiu do chat")
        print("------------------------------")

    #imprime a lista de conectados
    def show_connected(self):
        print("------------------------------")
        print("Lista de Conectados:")
        for person in self.connected:
            print(person.nick)
        print("------------------------------")

    #Filtra a mensagem de entrada em usuário e mensagem a ser enviada
    def filter_msg(self, data, ch=" "):
        cli = None
        index = [i for i, ltr in enumerate(data) if ltr == ch]
        name = data[index[0] + 1:index[1]]
        for person in self.connected:
            if person.nick == name:
                cli = person
        msg = data[index[1] + 1:]
        return cli, msg

    #define um objeto de mensagem para fazer o envio
    def set_msg(self, data):
        msg = None
        if (len(data) == 1):
            if "TO" in data[0]:
                dst_cli, text = self.filter_msg(data[0])
                msg = Message(4, self.client, len(text), text,
                              dst_cli.pvt_addr)
                if (dst_cli == self.client):
                    print(msg.message)
            elif "COMMANDS" in data[0]:
                self.show_commands()
            elif "SHOW_ALL" in data[0]:
                self.show_connected()
            elif "LEAVE" in data[0]:
                msg = Message(5, self.client, len(""), "")
            else:
                text = data[0]
                msg = Message(3, self.client, len(text), text)
        else:
            msg = Message(data[0], data[1], data[2], data[3])
        return msg

    #imprime mensagem privada
    def print_pvt(self, msg):
        print("------------------------------")
        print("Mensagem privada de " + msg.source.nick + ": " + msg.message)
        print("------------------------------")

    #gerencia a mensagem
    def manage_msg(self, msg):

        #verifica se a mensagem é do tipo join
        if (msg.type == 1):

            #caso o join recebido seja do cliente
            if (msg.source.nick == self.client.nick):

                #se o cliente não está na lista de conectados
                if (self.client.nick not in self.names_connected):
                    #cria o pacote a partir da mensagem
                    pckg = msg.get_package()

                    #dá o join no cliente
                    self.join(pckg)

            #caso o join recebido não seja do cliente
            else:
                #adiciona a fonte da mensagem na lista de conectados
                self.add_user(msg.source)
                print("------------------------------")
                print(msg.source.nick, "entrou no chat.")
                print("------------------------------")
                #envia um join_ack
                self.join_ack()

        #se o join_ack não for do cliente
        elif (msg.type == 2 and msg.source.nick != self.client.nick):

            #se a fonte do join_ack não está na lista de conectados
            if (msg.source.nick not in self.names_connected):
                self.add_user(msg.source)

        #se a mensagem nao foi enviada por esse cliente
        elif (msg.type == 3 and msg.source.nick != self.client.nick):
            self.receive_message(msg)

        #se a mensagem foi enviada por esse cliente
        elif (msg.type == 3 and msg.source.nick == self.client.nick):
            if (self.is_first_message):
                self.is_first_message = False
                pckg = msg.get_package()
                self.ts.send(pckg)
            else:
                self.is_first_message = True

        #caso a mensagem for privada mas é de outra fonte
        elif (msg.type == 4 and msg.source.nick != self.client.nick):
            self.print_pvt(msg)

        #caso a mensagem seja privada e seja do mesmo cliente
        elif (msg.type == 4 and msg.source.nick == self.client.nick):
            pckg = msg.get_package()
            self.ts.send_pvt(pckg, msg.dest)

        #remove o cliente que saiu da lista
        elif (msg.type == 5 and msg.source.nick != self.client.nick):
            self.pop_user(msg.source)

        #finaliza a conexão do cliente
        elif (msg.type == 5 and msg.source.nick == self.client.nick):
            pckg = msg.get_package()
            self.ts.send(pckg)
            self.ts.stop = True
            print("------------------------------")
            print("Conexão encerrada.")
            print("------------------------------")
            self.stop_threads()
            os._exit(0)

    #imprime os comandos do chat na tela
    def show_commands(self):
        print("------------------------------")
        print("Lista de comandos:")
        print(
            "TO nomedousuario mensagem : Comando para enviar mensagens privadas."
        )
        print("SHOW_ALL : Mostra o nome de todos usuários conectados.")
        print("LEAVE : Sai do chat")
        print("------------------------------")

    #realiza o join
    def join(self, pckg):
        #envia o pacote para todos os clientes
        self.ts.send(pckg)
        #adiciona o cliente na lista de conectados
        self.add_user(self.client)
        print("Olá " + self.client.nick + " você foi conectado")
        print("Digite COMMANDS para ver os comandos")
        print("------------------------------")

    #realiza o join_ack
    def join_ack(self):
        #cria a mensagem a partir de uma lista
        msg = self.set_msg([2, self.client, 0, ""])

        #recebe o valor da mensagem em um pacote de bytes
        pckg = msg.get_package()

        #envia o pacote
        self.ts.send(pckg)

    def receive_message(self, msg):
        print(msg.source.nick + " disse a todos: " + msg.message)

    #conecta o cliente
    def connect(self):
        #cria a mensagem a partir de uma lista
        msg = self.set_msg([1, self.client, 0, ""])

        #define o que fazer com a mensagem
        self.manage_msg(msg)