Beispiel #1
0
    def __init__(
        self, filename=None, sep=default_sep, port=default_port, rpc_export=True, start_server=True, *args, **kwargs
    ):
        self.filename = filename
        self.sep = sep
        self.port = port
        self.serverStarted = False

        self.initTime = time.time()
        self.logger = logging.getLogger(self.__class__.__name__)
        if self.filename is None:
            self.filename = "logs/events_{}.log".format(
                time.strftime(self.timestamp_format, time.localtime(self.initTime))
            )
        try:
            self.out = open(self.filename, "w")
            if rpc_export:
                rpc.export(self)  # NOTE prepends class name to all RPC-enabled method names
                if start_server:
                    rpc.start_server_thread(port=self.port, *args, **kwargs)
                    self.serverStarted = True
        except Exception as e:
            self.logger.error("Error opening log file or starting RPC server: %s", str(e))
        self.logger.info("Logger successfully initialized; filename: %s", self.filename)
Beispiel #2
0
    def __init__(self,
                 argv=None,
                 description=default_description,
                 parent_argparsers=[]):
        """Create a singleton, global application context, parse command-line args (with possible parent parsers passed in), and try to initialize input source parameters."""

        # * Ensure singleton
        if hasattr(self.__class__, 'instance'):
            raise Exception(
                "Context.__init__(): Singleton instance already exists!")

        # * Setup and parse common command-line arguments
        self.argParser = argparse.ArgumentParser(description=description,
                                                 parents=parent_argparsers)
        self.argParser.add_argument('--config',
                                    dest='config_file',
                                    default=self.default_config_filename,
                                    help='configuration filename')
        self.argParser.add_argument('--res',
                                    dest='res_path',
                                    default=self.default_res_path,
                                    help='path to resource directory')
        self.argParser.add_argument(
            '--log',
            dest='log_file',
            default='auto',
            help="where to log messages ('none' to turn off logging)")
        self.argParser.add_argument('--debug',
                                    action="store_true",
                                    help="show debug output?")
        self.argParser.add_argument(
            '--rpc',
            dest='rpc_port',
            type=int,
            nargs='?',
            default=-1,
            help="run RPC server at specified (or default) port")
        #self.argParser.add_argument('--gui', action="store_true", help="display GUI interface/windows?")  # use mutually exclusive [--gui | --no_gui] group instead
        guiGroup = self.argParser.add_mutually_exclusive_group()
        guiGroup.add_argument('--gui',
                              dest='gui',
                              action='store_true',
                              default=True,
                              help="display GUI interface/windows?")
        guiGroup.add_argument('--no_gui',
                              dest='gui',
                              action='store_false',
                              default=False,
                              help="suppress GUI interface/windows?")
        self.argParser.add_argument(
            '--delay',
            dest='delay',
            type=int,
            default=None,
            help=
            "delay between subsequent update iterations, in ms (default: 10ms for GUI mode, none otherwise)"
        )
        self.argParser.add_argument('--loop_video',
                                    action="store_true",
                                    help="keep replaying video?")
        self.argParser.add_argument(
            '--sync_video',
            action="store_true",
            help="synchronize video playback to real-time?")
        self.argParser.add_argument('--video_fps',
                                    default='auto',
                                    help="desired video frame rate (for sync)")
        self.argParser.add_argument('--camera_width',
                                    default='auto',
                                    help="desired camera frame width")
        self.argParser.add_argument('--camera_height',
                                    default='auto',
                                    help="desired camera frame height")
        self.argParser.add_argument('input_source',
                                    nargs='?',
                                    default='0',
                                    help="input image/video/camera device no.")
        self.options = self.argParser.parse_args(argv)  # parse_known_args()?
        if self.options.debug:
            print "Context.__init__(): Options: {}".format(
                pformat(self.options))

        # * Read config file
        self.config = {}
        try:
            with open(self.options.config_file, 'r') as f:
                self.config = yaml.load(f)
        except IOError:
            print "Context.__init__(): Error reading config file: {}".format(
                self.options.config_file)
            raise
        else:
            if self.options.debug:
                print "Context.__init__(): Loaded configuration: {}".format(
                    pformat(self.config))

        # * Obtain resource path and other parameters
        # TODO Provide unified configuration capability with config file and command-line overrides
        self.resPath = os.path.abspath(
            self.options.res_path
        )  # NOTE only absolute path seems to work properly
        if self.options.debug:
            print "Context.__init__(): Resource path: {}".format(self.resPath)

        # * Setup logging (before any other object is initialized that obtains a logger)
        self.setupLogging()

        # * Get a logger instance
        self.logger = logging.getLogger(self.__class__.__name__)

        # * Perform any option-dependent initialization
        if self.options.delay is None and self.options.gui:
            self.options.delay = self.default_delay

        # * Initialize input source parameters (TODO move this logic into InputDevice?)
        self.isDir = False
        self.isImage = False
        self.isVideo = False
        self.isRemote = False
        self.remoteEndpoint = None
        if self.options.input_source is not None:  # TODO include a way to specify None; currently defaults to device #0
            # ** Obtain camera device no. or input video/image filename
            try:
                self.options.input_source = int(
                    self.options.input_source
                )  # works if input_source is an int (a device no.)
            except ValueError:
                self.isRemote, self.remoteEndpoint = isRemote(
                    self.options.input_source, parts=True
                )  # check if this is a network address (endpoint)
                if not self.isRemote:
                    self.options.input_source = os.path.abspath(
                        self.options.input_source
                    )  # fallback: treat input_source as string (filename)
                    if os.path.exists(self.options.input_source):
                        if os.path.isdir(self.options.input_source):
                            self.isDir = True
                        elif isImageFile(self.options.input_source):
                            self.isImage = True
                        elif isVideoFile(self.options.input_source):
                            self.isVideo = True
                        else:
                            self.logger.warn(
                                "Input source type could not be determined: {}"
                                .format(self.options.input_source))
                    else:
                        self.logger.warn(
                            "Input source doesn't exist: {}".format(
                                self.options.input_source))

        # * Start RPC server if requested
        self.isRPCEnabled = False
        if self.options.rpc_port != -1:
            import rpc  # import locally to avoid depending on ZMQ and other RPC-related stuff when not needed
            if self.options.rpc_port is None:
                self.options.rpc_port = rpc.default_port
            rpc.start_server_thread(port=self.options.rpc_port)
            self.isRPCEnabled = True

        # * Timing
        self.resetTime()
Beispiel #3
0
 def __init__(self, port=default_port, start_server=True, *args, **kwargs):
     OutputDevice.__init__(self)
     self.isFresh = True  # used to prevent clients from getting a None as the first image
     rpc.export(self)  # NOTE prepends class name to all RPC-enabled method names
     if start_server:
         rpc.start_server_thread(port=port, *args, **kwargs)
Beispiel #4
0
 def __init__(self, argv=None, description=default_description, parent_argparsers=[]):
   """Create a singleton, global application context, parse command-line args (with possible parent parsers passed in), and try to initialize input source parameters."""
   
   # * Ensure singleton
   if hasattr(self.__class__, 'instance'):
     raise Exception("Context.__init__(): Singleton instance already exists!")
   
   # * Setup and parse common command-line arguments
   self.argParser = argparse.ArgumentParser(description=description, parents=parent_argparsers)
   self.argParser.add_argument('--config', dest='config_file', default=self.default_config_filename, help='configuration filename')
   self.argParser.add_argument('--res', dest='res_path', default=self.default_res_path, help='path to resource directory')
   self.argParser.add_argument('--log', dest='log_file', default='auto', help="where to log messages ('none' to turn off logging)")
   self.argParser.add_argument('--debug', action="store_true", help="show debug output?")
   self.argParser.add_argument('--rpc', dest='rpc_port', type=int, nargs='?', default=-1, help="run RPC server at specified (or default) port")
   #self.argParser.add_argument('--gui', action="store_true", help="display GUI interface/windows?")  # use mutually exclusive [--gui | --no_gui] group instead
   guiGroup = self.argParser.add_mutually_exclusive_group()
   guiGroup.add_argument('--gui', dest='gui', action='store_true', default=True, help="display GUI interface/windows?")
   guiGroup.add_argument('--no_gui', dest='gui', action='store_false', default=False, help="suppress GUI interface/windows?")
   self.argParser.add_argument('--delay', dest='delay', type=int, default=None, help="delay between subsequent update iterations, in ms (default: 10ms for GUI mode, none otherwise)")
   self.argParser.add_argument('--loop_video', action="store_true", help="keep replaying video?")
   self.argParser.add_argument('--sync_video', action="store_true", help="synchronize video playback to real-time?")
   self.argParser.add_argument('--video_fps', default='auto', help="desired video frame rate (for sync)")
   self.argParser.add_argument('--camera_width', default='auto', help="desired camera frame width")
   self.argParser.add_argument('--camera_height', default='auto', help="desired camera frame height")
   self.argParser.add_argument('input_source', nargs='?', default='0', help="input image/video/camera device no.")
   self.options = self.argParser.parse_args(argv)  # parse_known_args()?
   if self.options.debug:
     print "Context.__init__(): Options: {}".format(pformat(self.options))
   
   # * Read config file
   self.config = {}
   try:
     with open(self.options.config_file, 'r') as f:
       self.config = yaml.load(f)
   except IOError:
     print "Context.__init__(): Error reading config file: {}".format(self.options.config_file)
     raise
   else:
     if self.options.debug:
       print "Context.__init__(): Loaded configuration: {}".format(pformat(self.config))
   
   # * Obtain resource path and other parameters
   # TODO Provide unified configuration capability with config file and command-line overrides
   self.resPath = os.path.abspath(self.options.res_path)  # NOTE only absolute path seems to work properly
   if self.options.debug:
     print "Context.__init__(): Resource path: {}".format(self.resPath)
   
   # * Setup logging (before any other object is initialized that obtains a logger)
   self.setupLogging()
   
   # * Get a logger instance
   self.logger = logging.getLogger(self.__class__.__name__)
   
   # * Perform any option-dependent initialization
   if self.options.delay is None and self.options.gui:
     self.options.delay = self.default_delay
   
   # * Initialize input source parameters (TODO move this logic into InputDevice?)
   self.isDir = False
   self.isImage = False
   self.isVideo = False
   self.isRemote = False
   self.remoteEndpoint = None
   if self.options.input_source is not None:  # TODO include a way to specify None; currently defaults to device #0
     # ** Obtain camera device no. or input video/image filename
     try:
       self.options.input_source = int(self.options.input_source)  # works if input_source is an int (a device no.)
     except ValueError:
       self.isRemote, self.remoteEndpoint = isRemote(self.options.input_source, parts=True)  # check if this is a network address (endpoint)
       if not self.isRemote:
         self.options.input_source = os.path.abspath(self.options.input_source)  # fallback: treat input_source as string (filename)
         if os.path.exists(self.options.input_source):
           if os.path.isdir(self.options.input_source):
             self.isDir = True
           elif isImageFile(self.options.input_source):
             self.isImage = True
           elif isVideoFile(self.options.input_source):
             self.isVideo = True
           else:
             self.logger.warn("Input source type could not be determined: {}".format(self.options.input_source))
         else:
           self.logger.warn("Input source doesn't exist: {}".format(self.options.input_source))
   
   # * Start RPC server if requested
   self.isRPCEnabled = False
   if self.options.rpc_port != -1:
     import rpc  # import locally to avoid depending on ZMQ and other RPC-related stuff when not needed
     if self.options.rpc_port is None:
       self.options.rpc_port = rpc.default_port
     rpc.start_server_thread(port=self.options.rpc_port)
     self.isRPCEnabled = True
   
   # * Timing
   self.resetTime()