Пример #1
0
    def open(self, src, fps=DEFAULT_FPS, only_validate=False):
        logging.info("Opening video source: {}".format(src))
        if self._reader.isOpened():
            logging.error("Source is already opened")
            raise RuntimeError("Stream is already opened")

        error_message = "Can't open video stream {}".format(src)
        if not self._reader.open(src):
            raise ConnectionBrokenError(error_message)

        if only_validate:
            return

        success, image = self._reader.read()
        if not success:
            raise ConnectionBrokenError(error_message)
        height, width, _ = image.shape
        self._video_info["frame_size"] = (width, height)

        self._stop_event.clear()
        capture_interval = 1000.0 / fps

        logging.info("Starting reader thread")
        self._thread = StreamReaderThread(self._reader,
                                          self._queue,
                                          self._stop_event,
                                          capture_interval,
                                          _is_livestream(src))
        self._thread.daemon = True
        self._thread.start()
Пример #2
0
 def end(self):
     try:
         self._stop_event.set()
         if hasattr(self, "_thread") and self._thread.is_alive():
             if not self._queue.empty():
                 self._queue.join()
             self._thread.join()
         self._writer.release()
     except Exception as e:
         logging.error(str(e))
Пример #3
0
 def run(self):
     try:
         while not self._stop_event.is_set():
             success, image = self._reader.read()
             if not success:
                 if self._is_livestream:
                     raise ConnectionBrokenError()
                 else:
                     raise EndOfVideoError()
             timestamp = time.time()
             self._queue.appendleft(VideoFrame(image, timestamp))
             time.sleep(self._cap_interval)
         logging.info("Reader thread is terminated")
     except Exception as e:
         logging.error(str(e))
         self._exception = e
Пример #4
0
 def run(self):
     try:
         while True:
             if self._queue.empty():
                 if self._stop_event.is_set():
                     break
                 else:
                     time.sleep(0.01)
                     continue
             frame = self._queue.get()
             self._writer.write(frame.image)
             self._queue.task_done()
         logging.info("Writer thread is terminated")
     except Exception as e:
         logging.error(str(e))
         self._exception = e
Пример #5
0
 async def _setup(self, ch_name, nats_hosts):
     options = {
         "servers": nats_hosts,
         "io_loop": self._io_loop,
         "max_reconnect_attempts": 60,
         "reconnect_time_wait": 2,
         "disconnected_cb": self._disconnected_cb,
         "reconnected_cb": self._reconnected_cb,
         "error_cb": self._error_cb,
         "closed_cb": self._closed_cb
     }
     try:
         await self._nats.connect(**options)
         logging.info("NATS connection for APIConnector '{}' is "
                      "established.".format(self.__class__.__name__))
     except ErrNoServers as e:
         logging.error(e)
         raise
     else:
         await self._nats.subscribe("api.{}".format(ch_name),
                                    cb=self._api_handler)
Пример #6
0
    async def _api_handler(self, recv):
        subject = recv.subject
        reply = recv.reply
        try:
            msg = json.loads(recv.data.decode())
        except JSONDecodeError:
            raise

        response = {}
        try:
            if msg["command"] == "CREATE":
                self.on_create(msg["params"])
                response["result"] = "success"
            elif msg["command"] == "READ":
                result = self.on_read(msg["params"])
                response["result"] = result
            elif msg["command"] == "UPDATE":
                result = self.on_update(msg["params"])
                response["result"] = result
            elif msg["command"] == "DELETE":
                self.on_delete(msg["params"])
            elif msg["command"] == "START":
                self.on_start(msg["params"])
            elif msg["command"] == "STOP":
                self.on_stop(msg["params"])
        except RuntimeError as e:
            response["error"] = {"message": str(e)}
        except Exception as e:
            logging.error(e)

        try:
            await self._nats_cli.publish(reply, json.dumps(response).encode())
            # await self._nats_cli.flush(1)
        except ErrConnectionClosed as e:
            logging.error("Error ocurred when publishing response: {}, "
                          "ERROR: {}".format(response, e))
        except ErrTimeout as e:
            logging.error("Timeout ocurred when publishing response: {} "
                          "ERROR:: {}".format(response, e))
Пример #7
0
 async def _error_cb(self, e):
     logging.error("[NATS] {}".format(e))