Beispiel #1
0
 def setAsClosed(self, client, exception="None"):
     """Set client as closed"""
     # print "Client: ", client.getClient(), "closing."
     client.setClosed()
     try:
         client.connection.write(struct.pack('<L', 0))
         client.connection.close()
         client.serverSocket.close()
     except Exception:
         pass
     if exception is not None:
         utils.format_exception(exception)
Beispiel #2
0
 def newPort(self):
     """Check if a port is available, and if it is, assign it, otherwise continue testing the next one."""
     result = 0
     while result is 0:
         try:
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             result = sock.connect_ex(('127.0.0.1', self.port))
             if result is 0:
                 self.port += 1
             else:
                 self.serverSocket.bind(('0.0.0.0', self.port))
                 self.serverSocket.listen(0)
                 time.sleep(1)
         except Exception as e:
             utils.format_exception(e)
Beispiel #3
0
    def start_pyro4bot_object(self, d, proc_pipe):
        """Start PYRO4BOT component."""
        (name_ob, ip, ports) = utils.uri_split(d["pyro4id"])
        try:
            # Daemon proxy for sensor
            daemon = Pyro4.Daemon(host=ip,
                                  port=utils.get_free_port(ports, ip=ip))
            daemon._pyroHmacKey = self.node["password"].encode()

            proc_pipe.send("CONTINUE")
            deps = utils.prepare_proxys(d, self.node["password"])

            # assinging tty out and err for object
            default_tty = utils.get_tty()
            utils.set_tty_err(d["tty_err"])

            # Preparing class for pyro4
            pyro4bot_class = control.Pyro4bot_Loader(globals()[d["cls"]],
                                                     **deps)
            new_object = pyro4bot_class()

            # Associate object to the daemon
            uri = daemon.register(new_object, objectId=name_ob)

            # Get and save exposed methods
            exposed = Pyro4.core.DaemonObject(daemon).get_metadata(
                name_ob, True)

            # Hide methods from Control
            safe_exposed = {}
            for k in exposed.keys():
                safe_exposed[k] = list(
                    set(exposed[k]) - set(dir(control.Control)))
            safe_exposed["methods"].extend(["__docstring__", "__exposed__"])
            new_object.exposed.update(safe_exposed)

            setproctitle.setproctitle("PYRO4BOT." + name_ob)
            # Save dosctring documentation inside sensor object
            new_object.docstring.update(
                self.get_docstring(new_object, safe_exposed))

            daemon.requestLoop()
            # getting tty default to exit
            utils.set_tty_out(default_tty)
            utils.set_tty_err(default_tty)

            print("[%s] Shutting %s" %
                  (colored("Down", 'green'), d["pyro4id"]))
        except Exception as e:
            proc_pipe.send("FAIL")
            print("ERROR: creating sensor robot object: " + d["pyro4id"])
            print(utils.format_exception(e))
Beispiel #4
0
 def worker_read(self):
     """Main worker."""
     while self.worker_run:
         for foo in self.camera.capture_continuous(self.buffer,
                                                   'jpeg',
                                                   use_video_port=True):
             # Si hay clientes a la espera...
             while len(self.clients) is 0:
                 time.sleep(2)
             try:
                 self.acceptConnections()
                 streamPosition = self.buffer.tell()
                 for c in self.clients:
                     if c.closed is False:
                         try:
                             if c.connection is not 0:
                                 c.connection.write(
                                     struct.pack('<L', streamPosition))
                                 c.connection.flush()
                         except Exception as e:
                             closer = threading.Thread(
                                 target=self.setAsClosed, args=(c, ))
                             closer.start()
                 self.buffer.seek(0)
                 readBuffer = self.buffer.read()
                 for c in self.clients:
                     if c.closed is False:
                         try:
                             if c.connection is not 0:
                                 c.connection.write(readBuffer)
                         except Exception as e:
                             closer = threading.Thread(
                                 target=self.setAsClosed, args=(c, ))
                             closer.start()
                 self.buffer.seek(0)
                 self.buffer.truncate()
             except Exception as e:
                 utils.format_exception(e)
Beispiel #5
0
    def thread_publisher(self, publication, frec):
        """Publish the publication in the subscriber list."""
        self.__check_start__()
        self.L_info("[FG][LOCAL] Starting Publisher")
        if not hasattr(self, 'subscriptors'):
            self.subscriptors = {}
        while self.threadpublisher:
            value = publication.get()
            try:
                subscriptors = self.subscriptors.copy()
                for key in subscriptors.keys(
                ):  # Key has an attribute to publish
                    subscriptors = self.subscriptors[key]
                    try:
                        if key in value:
                            for s in subscriptors:
                                # print("publicando", key, value[key], "-> ", s.subscripter_uri)
                                try:
                                    s.subscripter.publication(
                                        s.subscripter_attr, value[key])
                                except (Pyro4.errors.ConnectionClosedError,
                                        Pyro4.errors.CommunicationError):
                                    # print(
                                    #     "Can not connect to the subscriber: {}".format(s))
                                    self.subscriptors[key] = [
                                        sub for sub in self.subscriptors[key]
                                        if sub.id != s.id
                                    ]
                                except Exception as ex:
                                    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                                    print(
                                        template.format(
                                            type(ex).__name__, ex.args))
                                    # del self.subscriptors[key]

                    except TypeError:
                        print("Invalid argument.")
                        raise
                        exit()
            except Exception as e:
                print(utils.format_exception(e))
                raise
            time.sleep(frec)