def _load_state(self, state): self.logger.debug("Loading state: {}".format(state)) s = None try: state_module = load_module('{}.{}.{}'.format( self._states_location.replace("/", "."), self._state_table_name, state)) # Get the `on_enter` method self.logger.debug("Checking {}".format(state_module)) on_enter_method = getattr(state_module, 'on_enter') setattr(self, 'on_enter_{}'.format(state), on_enter_method) self.logger.debug("Added `on_enter` method from {} {}".format( state_module, on_enter_method)) self.logger.debug("Created state") s = State(name=state) s.add_callback('enter', '_update_status') if can_graph: s.add_callback('enter', '_update_graph') s.add_callback('enter', 'on_enter_{}'.format(state)) except Exception as e: raise error.InvalidConfig( "Can't load state modules: {}\t{}".format(state, e)) return s
def _load_state(self, state): self.logger.debug("Loading state: {}".format(state)) s = None try: state_module = load_module('{}.{}.{}'.format( self._states_location.replace("/", "."), self._state_table_name, state )) # Get the `on_enter` method self.logger.debug("Checking {}".format(state_module)) on_enter_method = getattr(state_module, 'on_enter') setattr(self, 'on_enter_{}'.format(state), on_enter_method) self.logger.debug( "Added `on_enter` method from {} {}".format( state_module, on_enter_method)) self.logger.debug("Created state") s = State(name=state) s.add_callback('enter', '_update_status') if can_graph: s.add_callback('enter', '_update_graph') s.add_callback('enter', 'on_enter_{}'.format(state)) except Exception as e: raise error.InvalidConfig("Can't load state modules: {}\t{}".format(state, e)) return s
def _create_scheduler(self): """ Sets up the scheduler that will be used by the observatory """ scheduler_config = self.config.get('scheduler', {}) scheduler_type = scheduler_config.get('type', 'dispatch') # Read the targets from the file fields_file = scheduler_config.get('fields_file', 'simple.yaml') fields_path = os.path.join(self.config['directories']['targets'], fields_file) self.logger.debug('Creating scheduler: {}'.format(fields_path)) if os.path.exists(fields_path): try: # Load the required module module = utils.load_module( 'pocs.scheduler.{}'.format(scheduler_type)) # Simple constraint for now constraints = [ constraint.MoonAvoidance(), constraint.Duration(30 * u.deg) ] # Create the Scheduler instance self.scheduler = module.Scheduler(self.observer, fields_file=fields_path, constraints=constraints) self.logger.debug("Scheduler created") except ImportError as e: raise error.NotFound(msg=e) else: raise error.NotFound( msg="Fields file does not exist: {}".format(fields_file))
def __init__(self, name='Generic Camera', model='simulator', port=None, primary=False, focuser=None, *args, **kwargs): super().__init__(*args, **kwargs) try: self._image_dir = self.config['directories']['images'] except KeyError: self.logger.error("No images directory. Set image_dir in config") self.model = model self.port = port self.name = name self.is_primary = primary self._connected = False self._serial_number = 'XXXXXX' self._readout_time = kwargs.get('readout_time', 5.0) self._file_extension = kwargs.get('file_extension', 'fits') self.filter_type = 'RGGB' self.properties = None self._current_observation = None if focuser: if isinstance(focuser, AbstractFocuser): self.logger.debug("Focuser received: {}".format(focuser)) self.focuser = focuser self.focuser.camera = self elif isinstance(focuser, dict): try: module = load_module('pocs.focuser.{}'.format( focuser['model'])) except AttributeError as err: self.logger.critical( "Couldn't import Focuser module {}!".format(module)) raise err else: self.focuser = module.Focuser(**focuser, camera=self) self.logger.debug("Focuser created: {}".format( self.focuser)) else: # Should have been passed either a Focuser instance or a dict with Focuser # configuration. Got something else... self.logger.error( "Expected either a Focuser instance or dict, got {}". format(focuser)) self.focuser = None else: self.focuser = None self.logger.debug('Camera created: {}'.format(self))
def __init__(self, name='Generic Camera', model='simulator', port=None, primary=False, focuser=None, *args, **kwargs): super().__init__(*args, **kwargs) try: self._image_dir = self.config['directories']['images'] except KeyError: self.logger.error("No images directory. Set image_dir in config") self.model = model self.port = port self.name = name self.is_primary = primary self._connected = False self._serial_number = 'XXXXXX' self._readout_time = kwargs.get('readout_time', 5.0) self._file_extension = kwargs.get('file_extension', 'fits') self.filter_type = 'RGGB' self.properties = None self._current_observation = None if focuser: if isinstance(focuser, AbstractFocuser): self.logger.debug("Focuser received: {}".format(focuser)) self.focuser = focuser self.focuser.camera = self elif isinstance(focuser, dict): try: module = load_module('pocs.focuser.{}'.format(focuser['model'])) except AttributeError as err: self.logger.critical("Couldn't import Focuser module {}!".format(module)) raise err else: self.focuser = module.Focuser(**focuser, camera=self) self.logger.debug("Focuser created: {}".format(self.focuser)) else: # Should have been passed either a Focuser instance or a dict with Focuser # configuration. Got something else... self.logger.error( "Expected either a Focuser instance or dict, got {}".format(focuser)) self.focuser = None else: self.focuser = None self.logger.debug('Camera created: {}'.format(self))
def _create_mount(self, mount_info=None): """Creates a mount object. Details for the creation of the mount object are held in the configuration file or can be passed to the method. This method ensures that the proper mount type is loaded. Args: mount_info (dict): Configuration items for the mount. Returns: pocs.mount: Returns a sub-class of the mount type """ if mount_info is None: mount_info = self.config.get('mount') model = mount_info.get('model') port = mount_info.get('port') if 'mount' in self.config.get('simulator', []): model = 'simulator' driver = 'simulator' mount_info['simulator'] = True else: model = mount_info.get('brand') driver = mount_info.get('driver') # TODO(jamessynge): We should move the driver specific validation into the driver # module (e.g. module.create_mount_from_config). This means we have to adjust the # definition of this method to return a validated but not fully initialized mount # driver. if model != 'bisque': port = mount_info.get('port') if port is None or len(glob(port)) == 0: msg = "Mount port ({}) not available. Use --simulator=mount for simulator. Exiting.".format( port) raise error.PanError(msg=msg, exit=True) self.logger.debug('Creating mount: {}'.format(model)) module = load_module('pocs.mount.{}'.format(driver)) # Make the mount include site information self.mount = module.Mount(location=self.earth_location) self.logger.debug('Mount created')
def test_bad_load_module(): with pytest.raises(NotFound): load_module('FOOBAR')
def _create_cameras(self, **kwargs): """Creates a camera object(s) Loads the cameras via the configuration. Creates a camera for each camera item listed in the config. Ensures the appropriate camera module is loaded. Note: We are currently only operating with one camera and the `take_pic.sh` script automatically discovers the ports. Note: This does not actually make a usb connection to the camera. To do so, call the 'camear.connect()' explicitly. Args: **kwargs (dict): Can pass a camera_config object that overrides the info in the configuration file. Can also pass `auto_detect`(bool) to try and automatically discover the ports. Returns: list: A list of created camera objects. Raises: error.CameraNotFound: Description error.PanError: Description """ if kwargs.get('camera_info') is None: camera_info = self.config.get('cameras') self.logger.debug("Camera config: \n {}".format(camera_info)) a_simulator = 'camera' in self.config.get('simulator', []) if a_simulator: self.logger.debug("Using simulator for camera") ports = list() # Lookup the connected ports if not using a simulator auto_detect = kwargs.get('auto_detect', camera_info.get('auto_detect', False)) if not a_simulator and auto_detect: self.logger.debug("Auto-detecting ports for cameras") try: ports = list_connected_cameras() except Exception as e: self.logger.warning(e) if len(ports) == 0: raise error.PanError( msg= "No cameras detected. Use --simulator=camera for simulator." ) else: self.logger.debug("Detected Ports: {}".format(ports)) for cam_num, camera_config in enumerate(camera_info.get('devices', [])): cam_name = 'Cam{:02d}'.format(cam_num) if not a_simulator: camera_model = camera_config.get('model') # Assign an auto-detected port. If none are left, skip if auto_detect: try: camera_port = ports.pop() except IndexError: self.logger.warning( "No ports left for {}, skipping.".format(cam_name)) continue else: try: camera_port = camera_config['port'] except KeyError: raise error.CameraNotFound( msg="No port specified and auto_detect=False") camera_focuser = camera_config.get('focuser', None) camera_readout = camera_config.get('readout_time', 6.0) else: # Set up a simulated camera with fully configured simulated # focuser camera_model = 'simulator' camera_port = '/dev/camera/simulator' camera_focuser = { 'model': 'simulator', 'focus_port': '/dev/ttyFAKE', 'initial_position': 20000, 'autofocus_range': (40, 80), 'autofocus_step': (10, 20), 'autofocus_seconds': 0.1, 'autofocus_size': 500 } camera_readout = 0.5 camera_set_point = camera_config.get('set_point', None) camera_filter = camera_config.get('filter_type', None) self.logger.debug('Creating camera: {}'.format(camera_model)) try: module = load_module('pocs.camera.{}'.format(camera_model)) self.logger.debug('Camera module: {}'.format(module)) except ImportError: raise error.CameraNotFound(msg=camera_model) else: # Create the camera object cam = module.Camera(name=cam_name, model=camera_model, port=camera_port, set_point=camera_set_point, filter_type=camera_filter, focuser=camera_focuser, readout_time=camera_readout) is_primary = '' if camera_info.get('primary', '') == cam.uid: self.primary_camera = cam is_primary = ' [Primary]' self.logger.debug("Camera created: {} {} {}".format( cam.name, cam.uid, is_primary)) self.cameras[cam_name] = cam # If no camera was specified as primary use the first if self.primary_camera is None: self.primary_camera = self.cameras['Cam00'] if len(self.cameras) == 0: raise error.CameraNotFound(msg="No cameras available. Exiting.", exit=True) self.logger.debug("Cameras created")