コード例 #1
0
    def get_menu_path_read(self, name):
        """
        Get the read menu path parameter value from the dictionary.
        @param name Name of the value to be retrieved.
        @raises KeyError if the name is invalid.
        @raises InstrumentParameterException if the description is missing
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        return self._param_dict[name].description.menu_path_read
コード例 #2
0
ファイル: driver.py プロジェクト: r-swilderd/mi-instrument
    def hex2value(hex_value, divisor=None):
        """
        Convert a SBE hex value to a value.  Some hex values are converted
        from raw counts to volts using a divisor.  If passed the value
        will be calculated, otherwise return an int.
        @param hex_value: string to convert
        @param divisor: conversion value
        @return: int or float of the converted value
        """
        if not isinstance(hex_value, str):
            raise InstrumentParameterException("hex value not a string")

        if divisor is not None and divisor == 0:
            raise InstrumentParameterException("divisor can not be 0")

        value = int(hex_value, 16)
        if divisor is not None:
            return float(value) / divisor
        else:
            return value
コード例 #3
0
    def hex2value(self, hex_value):
        """
        Convert a ADC hex value to an int value.
        @param hex_value: string to convert
        @return: int of the converted value
        """
        if not isinstance(hex_value, str):
            raise InstrumentParameterException("hex value not a string")

        value = int(hex_value, 16)
        return value
コード例 #4
0
    def get_submenu_write(self, name):
        """
        Get the write final destination parameter value from the dictionary.
        @param name Name of the value to be retrieved.
        @raises KeyError if the name is invalid.
        @raises InstrumentParameterException if the description is missing
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        return self._param_dict[name].description.submenu_write
コード例 #5
0
 def _int_to_hexstring(val, slen):
     """
     Write an integer value to an ASCIIHEX string formatted for SAMI
     configuration set operations.
     @param val the integer value to convert.
     @param slen the required length of the returned string.
     @retval an integer string formatted in ASCIIHEX for SAMI configuration
     set operations.
     @throws InstrumentParameterException if the integer and string length
     values are not an integers.
     """
     if not isinstance(val, int):
         raise InstrumentParameterException('Value %s is not an integer.' %
                                            str(val))
     elif not isinstance(slen, int):
         raise InstrumentParameterException('Value %s is not an integer.' %
                                            str(slen))
     else:
         hexstr = format(val, 'X')
         return hexstr.zfill(slen)
コード例 #6
0
ファイル: driver.py プロジェクト: r-swilderd/mi-instrument
    def _build_connection(self, config):
        """
        Constructs and returns a Connection object according to the given
        configuration. The connection object is a LoggerClient instance in
        this base class. Subclasses can overwrite this operation as needed.
        The value returned by this operation is assigned to self._connections
        and also to self._protocol._connection upon entering in the
        DriverConnectionState.CONNECTED state.

        @param all_configs configuration dict
        @returns a dictionary of Connection instances, which will be assigned to self._connection
        @throws InstrumentParameterException Invalid configuration.
        """
        all_configs = config
        connections = {}
        for name, config in all_configs.items():
            if not isinstance(config, dict):
                continue
            if 'mock_port_agent' in config:
                mock_port_agent = config['mock_port_agent']
                # check for validity here...
                if mock_port_agent is not None:
                    connections[name] = mock_port_agent
            else:
                try:
                    addr = config['addr']
                    port = config['port']
                    cmd_port = config.get('cmd_port')

                    if isinstance(addr, str) and isinstance(
                            port, int) and len(addr) > 0:
                        connections[name] = PortAgentClient(
                            addr, port, cmd_port)
                    else:
                        raise InstrumentParameterException(
                            'Invalid comms config dict.')

                except (TypeError, KeyError):
                    raise InstrumentParameterException(
                        'Invalid comms config dict.')
        return connections
コード例 #7
0
    def set_init_value(self, name, value):
        """
        Set the value to the default value stored in the param dict
        @param The parameter name to add to
        @param The value to set for the initialization variable
        @raise KeyError if the name is invalid
        @raises InstrumentParameterException if the description is missing        
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        self._param_dict[name].description.init_value = value
コード例 #8
0
    def is_settable_param(self, name):
        """
        Return true if a parameter is not read only
        @param name name of a parameter
        @retval True if the parameter is flagged as not read only
        @raises KeyError if parameter doesn't exist
        @raises InstrumentParameterException if the description is missing
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        return not (self._param_dict[name].description.visibility == ParameterDictVisibility.READ_ONLY)
コード例 #9
0
    def is_startup_param(self, name):
        """
        Return true if a parameter name references a startup parameter
        @param name name of a parameter
        @retval True if the parameter is flagged as a startup param
        @raises KeyError if parameter doesn't exist
        @raises InstrumentParameterException if the description is missing                
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        return self._param_dict[name].description.startup_param == True
コード例 #10
0
    def _set_is_data_only(self, data_only, timeout):
        if not isinstance(data_only, bool):
            #            return InstErrorCode.INVALID_PARAM_VALUE
            raise InstrumentParameterException(
                msg='data_only object is not a bool: %s' % data_only)

        try:
            self.trhph_client.set_is_data_only(data_only, timeout)
            #            return InstErrorCode.OK
            return
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
コード例 #11
0
    def _handler_command_get(self, *args, **kwargs):
        """
        Get parameters while in the command state.
        @param params List of the parameters to pass to the state
        @retval returns (next_state, result) where result is a dict {}. No
            agent state changes happening with Get, so no next_agent_state
        @throw InstrumentParameterException for invalid parameter
        """
        result_vals = {}

        # Retrieve required parameter.
        # Raise if no parameter provided, or not a dict.
        try:
            params = args[0]

        except IndexError:
            raise InstrumentParameterException(
                '_handler_command_get requires a parameter dict.')

        if Parameter.ALL in params:
            log.debug("Parameter ALL in params")
            params = Parameter.list()
            params.remove(Parameter.ALL)

        log.debug("_handler_command_get: params = %s", params)

        if params is None or not isinstance(params, list):
            raise InstrumentParameterException(
                "GET parameter list not a list!")

        # fill the return values from the update
        for param in params:
            if not Parameter.has(param):
                raise InstrumentParameterException("Invalid parameter!")
            result_vals[param] = self._param_dict.get(param)
            self._param_dict.get_config_value(param)
        result = result_vals

        log.debug("Get finished, next_state: %s, result: %s", None, result)
        return None, result
コード例 #12
0
    def set_resource(self, *args, **kwargs):
        """
        Set the driver parameter
        """
        log.trace("start set_resource")
        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException(
                'Set command requires a parameter dict.')

        log.trace("set_resource: iterate through params: %s", params)
        for (key, val) in params.iteritems():
            if key in [
                    DriverParameter.BATCHED_PARTICLE_COUNT,
                    DriverParameter.RECORDS_PER_SECOND
            ]:
                if not isinstance(val, int):
                    raise InstrumentParameterException(
                        "%s must be an integer" % key)
            if key in [DriverParameter.PUBLISHER_POLLING_INTERVAL]:
                if not isinstance(val, (int, float)):
                    raise InstrumentParameterException("%s must be an float" %
                                                       key)

            if val <= 0:
                raise InstrumentParameterException("%s must be > 0" % key)

            self._param_dict.set_value(key, val)

        # Set the driver parameters
        self._generate_particle_count = self._param_dict.get(
            DriverParameter.BATCHED_PARTICLE_COUNT)
        self._particle_count_per_second = self._param_dict.get(
            DriverParameter.RECORDS_PER_SECOND)
        self._polling_interval = self._param_dict.get(
            DriverParameter.PUBLISHER_POLLING_INTERVAL)
        log.trace("Driver Parameters: %s, %s, %s", self._polling_interval,
                  self._particle_count_per_second,
                  self._generate_particle_count)
コード例 #13
0
ファイル: driver.py プロジェクト: vipullakhani/mi-instrument
    def set_init_params(self, config):
        if not isinstance(config, dict):
            raise InstrumentParameterException("Invalid init config format")

        self._startup_config = config

        param_config = config.get(DriverConfigKey.PARAMETERS)
        if param_config:
            for name in param_config.keys():
                self._param_dict.add(name, '', None, None)
                log.debug("Setting init value for %s to %s", name,
                          param_config[name])
                self._param_dict.set_init_value(name, param_config[name])
コード例 #14
0
ファイル: driver.py プロジェクト: petercable/mi-instrument
    def _set_params(self, *args, **kwargs):
        """
        Issue commands to the instrument to set various parameters
        """
        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException('Set command requires a parameter dict.')

        self._verify_not_readonly(*args, **kwargs)
        update_params = False

        # check values that the instrument doesn't validate
        # handle special cases for driver specific parameters
        for (key, val) in params.iteritems():
            if key == Parameter.PUMP_DELAY and (val < MIN_PUMP_DELAY or val > MAX_PUMP_DELAY):
                raise InstrumentParameterException("pump delay out of range")
            elif key == Parameter.NUM_AVG_SAMPLES and (val < MIN_AVG_SAMPLES or val > MAX_AVG_SAMPLES):
                raise InstrumentParameterException("num average samples out of range")

        for (key, val) in params.iteritems():

            old_val = self._param_dict.format(key)
            new_val = self._param_dict.format(key, val)
            log.debug("KEY = %r OLD VALUE = %r NEW VALUE = %r", key, old_val, new_val)

            if old_val != new_val:
                update_params = True
                if ConfirmedParameter.has(key):
                    # We add a write delay here because this command has to be sent
                    # twice, the write delay allows it to process the first command
                    # before it receives the beginning of the second.
                    self._do_cmd_resp(Command.SET, key, val, write_delay=0.2)
                else:
                    self._do_cmd_resp(Command.SET, key, val, **kwargs)

        log.debug("set complete, update params")
        if update_params:
            self._update_params()
コード例 #15
0
ファイル: driver.py プロジェクト: petercable/mi-instrument
    def _boolean_to_off_on(v):
        """
        Write a boolean value to string formatted for sbe16 set operations.
        @param v a boolean value.
        @retval A yes/no string formatted for sbe16 set operations.
        @throws InstrumentParameterException if value not a bool.
        """

        if not isinstance(v, bool):
            raise InstrumentParameterException('Value %s is not a bool.' % str(v))
        if v:
            return 'on'
        return 'off'
コード例 #16
0
 def add_parameter(self, parameter):
     """
     Add a Parameter object to the dictionary or replace an existing one.
     The value can be any object that is an instance of the Parameter class
     or subclasses. This is the preferred method for adding these entries as
     they allow the user to choose the type of parameter to be used
     and make testing more straightforward.
     @param parameter The Parameter object to use
     """
     if not (isinstance(parameter, Parameter)):
         raise InstrumentParameterException(
             "Invalid Parameter added! Attempting to add: %s" % parameter)
     self._param_dict[parameter.name] = parameter
コード例 #17
0
    def _handler_command_set(self, *args, **kwargs):
        """
        Perform a set command.
        @param args[0] parameter : value dict.
        @retval (next_state, result) tuple, (None, None).
        @throws InstrumentParameterException if missing set parameters, if set parameters not ALL and
        not a dict, or if parameter can't be properly formatted.

        """
        next_state = None
        result = None
        startup = False

        log.debug("_handler_command_set enter ")
        # Retrieve required parameter.
        # Raise if no parameter provided, or not a dict.
        try:
            params = args[0]

        except IndexError:
            raise InstrumentParameterException('Set command requires a parameter dict.')

        if not isinstance(params, dict):
            raise InstrumentParameterException('Set parameters not a dict.')

        try:
            startup = args[1]
        except IndexError:
            pass

        old_config = self._param_dict.get_config()
        self._set_params(params, startup)

        new_config = self._param_dict.get_config()
        if old_config != new_config:
            self._driver_event(DriverAsyncEvent.CONFIG_CHANGE)

        return next_state, result
コード例 #18
0
ファイル: driver.py プロジェクト: n1ywb/mi-instrument
    def _verify_set_values(self, params):
        """
        Verify supplied values are in range, if applicable
        @param params: Dictionary of Parameter:value pairs to be verified
        @throws InstrumentParameterException
        """
        constraints = ParameterConstraint.dict()
        parameters = Parameter.reverse_dict()

        # step through the list of parameters
        for key, val in params.iteritems():
            # verify this parameter exists
            if not Parameter.has(key):
                raise InstrumentParameterException(
                    'Received invalid parameter in SET: %s' % key)
            # if constraint exists, verify we have not violated it
            constraint_key = parameters.get(key)
            if constraint_key in constraints:
                var_type, minimum, maximum = constraints[constraint_key]
                constraint_string = 'Parameter: %s Value: %s Type: %s Minimum: %s Maximum: %s' % \
                                    (key, val, var_type, minimum, maximum)
                log.debug('SET CONSTRAINT: %s', constraint_string)
                # check bool values are actual booleans
                if var_type == bool:
                    if val not in [True, False]:
                        raise InstrumentParameterException(
                            'Non-boolean value!: %s' % constraint_string)
                # else, check if we can cast to the correct type
                else:
                    try:
                        var_type(val)
                    except ValueError:
                        raise InstrumentParameterException(
                            'Type mismatch: %s' % constraint_string)
                    # now, verify we are within min/max
                    if val < minimum or val > maximum:
                        raise InstrumentParameterException('Out of range: %s' %
                                                           constraint_string)
コード例 #19
0
ファイル: driver.py プロジェクト: n1ywb/mi-instrument
    def _set_params(self, *args, **kwargs):
        """
        Set various parameters internally to the driver. No issuing commands to the
        instrument needed for this driver.
        """

        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException(
                'Set command requires a parameter dict.')

        #list can be null, like in the case of direct access params, in this case do nothing
        if not params:
            return

        # Do a range check before we start all sets
        for (key, val) in params.iteritems():

            if key == Parameter.INTERVAL and not (0 < val < 601):
                log.debug("Auto Sample Interval not in 1 to 600 range ")
                raise InstrumentParameterException(
                    "sample interval out of range [1, 600]")

            if key == Parameter.INSTRUMENT_SERIES:
                if val not in 'ABC':
                    log.debug("Instrument Series is not A, B or C ")
                    raise InstrumentParameterException(
                        "Instrument Series is not invalid ")
                else:
                    self._get_sample_cmd = self.THSPH_COMMANDS[val][
                        Command.GET_SAMPLE]
                    self._comm_test_cmd = self.THSPH_COMMANDS[val][
                        Command.COMM_TEST]

            log.debug('key = (%s), value = (%s)' % (key, val))

            self._param_dict.set_value(key, val)
コード例 #20
0
    def set_default(self, name):
        """
        Set the value to the default value stored in the param dict
        @raise KeyError if the name is invalid
        @raise ValueError if the default_value is missing
        @raises InstrumentParameterException if the description is missing
        """
        if not self._param_dict[name].description:
            raise InstrumentParameterException("No description present!")

        if self._param_dict[name].description.default_value is not None:
            self._param_dict[name].value.set_value(self._param_dict[name].description.default_value)
        else:
            raise ValueError("Missing default value")
コード例 #21
0
    def _handler_command_get(self, params=None, *args, **kwargs):
        """
        Get parameters while in the command state.
        @param params List of the parameters to pass to the state
        @retval returns (next_state, result) where result is a dict {}. No
            agent state changes happening with Get, so no next_agent_state
        @throw InstrumentParameterException for invalid parameter
        """
        next_state = None
        result = None
        result_vals = {}
        
        if (params == None):
            raise InstrumentParameterException("GET parameter list empty!")
            
        if (params == Parameter.ALL):
            params = [Parameter.CYCLE_TIME, Parameter.EH_ISOLATION_AMP_POWER,
                      Parameter.HYDROGEN_POWER, Parameter.INST_AMP_POWER,
                      Parameter.METADATA_POWERUP, Parameter.METADATA_RESTART,
                      Parameter.REFERENCE_TEMP_POWER, Parameter.RES_SENSOR_POWER,
                      Parameter.VERBOSE]
            
        if not isinstance(params, list):
            raise InstrumentParameterException("GET parameter list not a list!")

        # Do a bulk update from the instrument since they are all on one page
        self._update_params()
        
        # fill the return values from the update
        for param in params:
            if not Parameter.has(param):
                raise InstrumentParameterException("Invalid parameter!")
            result_vals[param] = self._param_dict.get(param) 
        result = result_vals

        log.debug("Get finished, next: %s, result: %s", next_state, result) 
        return (next_state, result)
コード例 #22
0
    def _set_params(self, *args, **kwargs):
        """
        Set various parameters internally to the driver. No issuing commands to the
        instrument needed for this driver.
        """
        log.debug("_set_params ")
        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException('Set command requires a parameter dict.')

        #list can be null, like in the case of direct access params, in this case do nothing
        if not params:
            return

        # Sampling interval is the only parameter that is set by the driver.
        # Do a range check before we start all sets
        for (key, val) in params.iteritems():
            if key == Parameter.INTERVAL and not (0 < val < 601):
                log.debug("Auto Sample Interval not in 1 to 600 range ")
                raise InstrumentParameterException("sample interval out of range [1, 600]")
            log.debug('key = (%s), value = (%s)' % (key, val))

        self._param_dict.set_value(Parameter.INTERVAL, params[Parameter.INTERVAL])
コード例 #23
0
ファイル: driver.py プロジェクト: vipullakhani/mi-instrument
    def _handler_autosample_set(self, *args, **kwargs):
        """
        Perform a set command.
        @param args[0] parameter : value dict.
        @return next_state, (next_state, result)
        @throws InstrumentParameterException
        """
        next_state = None
        result = []
        startup = False

        if len(args) < 1:
            raise InstrumentParameterException('Set command requires a parameter dict.')
        params = args[0]
        if len(args) > 1:
            startup = args[1]

        if not isinstance(params, dict):
            raise InstrumentParameterException('Set parameters not a dict.')
        if not isinstance(startup, bool):
            raise InstrumentParameterException('Startup not a bool.')

        self._set_params(params, startup)
        return next_state, result
コード例 #24
0
ファイル: driver.py プロジェクト: vipullakhani/mi-instrument
    def _handler_command_set(self, *args, **kwargs):
        """
        Set instrument parameters
        """
        next_state = None
        result = []
        startup = False

        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException('set command requires a parameter dictionary.')

        try:
            startup = args[1]
        except IndexError:
            pass

        if not isinstance(params, dict):
            raise InstrumentParameterException('set parameters is not a dictionary')

        self._set_params(params, startup)

        return next_state, (next_state, result)
コード例 #25
0
    def set_internal_timestamp(self, timestamp=None, unix_time=None):
        """
        Set the internal timestamp
        @param timestamp: NTP timestamp to set
        @param unix_time: Unix time as returned from time.time()
        @raise InstrumentParameterException if timestamp or unix_time not supplied
        """
        if timestamp is None and unix_time is None:
            raise InstrumentParameterException(
                "timestamp or unix_time required")

        if unix_time is not None:
            timestamp = ntplib.system_to_ntp_time(unix_time)

        self.contents[DataParticleKey.INTERNAL_TIMESTAMP] = float(timestamp)
コード例 #26
0
ファイル: driver.py プロジェクト: r-swilderd/mi-instrument
 def _float_or_int_to_string(v):
     """
     Write a float or int value to string formatted for "generic" set operations.
     Overloaded to print ints and floats without trailing zeros after the decimal point.
     Also supports passing through a "None" value for the empty param dictionary in startup.
     @param v A float or int val.
     @retval a numerical string formatted for "generic" set operations.
     @throws InstrumentParameterException if value is not a float or an int.
     """
     if isinstance(v, float):
         return ('%0.3f' % v).rstrip('0').rstrip('.')
     elif isinstance(v, int):
         return '%d' % v
     elif v is None:
         return None
     else:
         raise InstrumentParameterException('Value %s is not a float or an int.' % v)
コード例 #27
0
    def set_internal_timestamp(self, timestamp=None, unix_time=None):
        """
        Set the internal timestamp
        @param timestamp: NTP timestamp to set
        @param unit_time: Unix time as returned from time.time()
        @raise InstrumentParameterException if timestamp or unix_time not supplied
        """
        if timestamp is None and unix_time is None:
            raise InstrumentParameterException("timestamp or unix_time required")

        if unix_time is not None:
            timestamp = ntplib.system_to_ntp_time(unix_time)

        # Do we want this to happen here or in down stream processes?
        # if(not self._check_timestamp(timestamp)):
        #    raise InstrumentParameterException("invalid timestamp")

        self.contents[DataParticleKey.INTERNAL_TIMESTAMP] = float(timestamp)
コード例 #28
0
 def _from_seconds(value):
     """
     Converts a number of seconds into a (unit, value) tuple.
     
     @param value The number of seconds to convert
     @retval A tuple of unit and value where the unit is 1 for seconds and 2
         for minutes. If the value is 15-59, units should be returned in
         seconds. If the value is over 59, the units will be returned in
         a number of minutes where the seconds are rounded down to the
         nearest minute.
     """
     if (value < 15) or (value > 3600):
         raise InstrumentParameterException("Invalid seconds value: %s" % value)
     
     if (value < 60):
         return (1, value)
     else:
         return (2, value // 60)
コード例 #29
0
ファイル: driver.py プロジェクト: vipullakhani/mi-instrument
    def _handler_command_get(self, *args, **kwargs):
        """
        Get parameter.  Query this protocol plus all slave protocols.
        @param args: arglist which should contain a list of parameters to get
        @return None, results
        """
        params = args[0]

        if not isinstance(params, list):
            params = [params]

        temp_dict = {}
        result_dict = {}

        # request is for all parameters, send get(ALL) to each protocol then combine the results.
        if Parameter.ALL in params:
            params = [Parameter.ALL]
            _, result = self._handler_get(params, **kwargs)
            result_dict.update(result)
            for protocol in self._slave_protocols.values():
                _, result = protocol._handler_get(params, **kwargs)
                result_dict.update(result)

        # request is for specific parameters.  Determine which protocol should service each,
        # call the appropriate _handler_get and combine the results
        else:
            for key in params:
                log.debug('about to split: %s', key)
                target, _ = key.split('_', 1)
                temp_dict.setdefault(target, []).append(key)
            for key in temp_dict:
                if key == MASTER:
                    _, result = self._handler_get(params, **kwargs)
                else:
                    if key in self._slave_protocols:
                        _, result = self._slave_protocols[key]._handler_get(
                            params, **kwargs)
                    else:
                        raise InstrumentParameterException(
                            'Invalid key(s) in GET action: %r' %
                            temp_dict[key])
                result_dict.update(result)

        return None, result_dict
コード例 #30
0
    def get_direct_access_list(self):
        """
        Return a list of parameter names that are tagged as direct access
        parameters
        
        @retval A list of parameter names, possibly empty
        @raises InstrumentParameterException if the description is missing                
        """

        return_val = []
        for key in self._param_dict.keys():

            if not self._param_dict[key].description:
                raise InstrumentParameterException("No description present!")

            if self._param_dict[key].description.direct_access == True:
                return_val.append(key)

        return return_val