Exemplo n.º 1
0
    def main(self, *, args):  # noqa: D102
        with NodeStrategy(args) as node:
            node_names = get_node_names(
                node=node, include_hidden_nodes=args.include_hidden_nodes)

        node_name = get_absolute_node_name(args.node_name)
        if node_name not in [n.full_name for n in node_names]:
            return 'Node not found'

        with DirectNode(args) as node:
            parameter = Parameter()
            Parameter.name = args.name
            value = ParameterValue()
            value.type = ParameterType.PARAMETER_NOT_SET
            parameter.value = value

            response = call_set_parameters(node=node,
                                           node_name=args.node_name,
                                           parameters=[parameter])

            # output response
            assert len(response.results) == 1
            result = response.results[0]
            if result.successful:
                msg = 'Deleted parameter successfully'
                if result.reason:
                    msg += ': ' + result.reason
                print(msg)
            else:
                msg = 'Deleting parameter failed'
                if result.reason:
                    msg += ': ' + result.reason
                print(msg, file=sys.stderr)
Exemplo n.º 2
0
 def __init__(self, **kwargs):
     assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
         'Invalid arguments passed to constructor: %s' % \
         ', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
     self.name = kwargs.get('name', str())
     from rcl_interfaces.msg import ParameterValue
     self.value = kwargs.get('value', ParameterValue())
Exemplo n.º 3
0
    def __init__(self, robot_name, wandb=False, config_name="optimization"):
        super().__init__(robot_name, wandb=wandb)
        self.current_speed = None
        self.last_time = 0
        self.number_of_iterations = 100
        self.time_limit = 10
        # needs to be specified by subclasses
        self.directions = None
        self.reset_height_offset = None
        self.reset_rpy_offset = [0, 0, 0]
        self.last_yaw = 0
        self.summed_yaw = 0

        # load moveit config values
        moveit_parameters = load_moveit_parameter(self.robot_name)

        # load walk params
        self.walk_parameters = get_parameters_from_ros_yaml(
            "walking", f"{get_package_share_directory('bitbots_quintic_walk')}"
            f"/config/{config_name}.yaml",
            use_wildcard=True)
        # activate IK reset only for wolfgang
        self.walk_parameters.append(
            Parameter(name="node.ik_reset",
                      value=ParameterValue(
                          bool_value=self.robot_name == "wolfgang")))

        # create walk as python class to call it later
        self.walk = PyWalk(self.namespace,
                           self.walk_parameters + moveit_parameters)
    def send_request_to_change_parameters(
        self,  # Arguments are alphabetically sorted
        expect,
        frame_rate: float,
        output_directory: Path,
        real_time_factor: float,
        scenario: Path,
    ):
        """Send request to change scenario interpreter's parameters."""
        request = rcl_interfaces.srv.SetParameters.Request()

        request.parameters = [
            Parameter(
                name="intended_result",
                value=ParameterValue(type=ParameterType.PARAMETER_STRING,
                                     string_value=str(expect.name)),
            ),
            Parameter(
                name="osc_path",
                value=ParameterValue(type=ParameterType.PARAMETER_STRING,
                                     string_value=str(scenario)),
            ),
            Parameter(
                name="output_directory",
                value=ParameterValue(
                    type=ParameterType.PARAMETER_STRING,
                    string_value=str(output_directory),
                ),
            ),
            Parameter(
                name="local_real_time_factor",
                value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                     double_value=real_time_factor),
            ),
            Parameter(
                name="local_frame_rate",
                value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                     double_value=frame_rate),
            ),
        ]

        future = self.client_set_parameters.call_async(request)
        rclpy.spin_until_future_complete(self,
                                         future,
                                         timeout_sec=self.timeout_sec)
        return future
Exemplo n.º 5
0
 def test_integer_array(self):
     int_array = array('i', [1, 2, 3])
     self.assertEqual(Parameter.Type.INTEGER_ARRAY,
                      Parameter.Type.from_parameter_value(int_array))
     # test that it doesn't raise
     Parameter.from_parameter_msg(
         ParameterMsg(name='int_array',
                      value=ParameterValue(type=7,
                                           integer_array_value=[1, 2, 3])))
Exemplo n.º 6
0
 def test_double_array(self):
     double_array = array('d', [1.0, 2.0, 3.0])
     self.assertEqual(Parameter.Type.DOUBLE_ARRAY,
                      Parameter.Type.from_parameter_value(double_array))
     # test that it doesn't raise
     Parameter.from_parameter_msg(
         ParameterMsg(name='double_array',
                      value=ParameterValue(
                          type=8, double_array_value=[1.0, 2.0, 3.0])))
Exemplo n.º 7
0
def get_parameter_value(p_type, value):
    p_value = ParameterValue()
    p_value.type = p_type
    if p_type == ParameterType.PARAMETER_BOOL:
        p_value.bool_value = value
    elif p_type == ParameterType.PARAMETER_INTEGER:
        p_value.integer_value = value
    elif p_type == ParameterType.PARAMETER_DOUBLE:
        p_value.double_value = value
    elif p_type == ParameterType.PARAMETER_STRING:
        p_value.string_value = value
    return p_value
Exemplo n.º 8
0
def get_parameter_value(*, string_value):
    """Guess the desired type of the parameter based on the string value."""
    value = ParameterValue()
    if string_value.lower() in ('true', 'false'):
        value.type = ParameterType.PARAMETER_BOOL
        value.bool_value = string_value.lower() == 'true'
    elif _is_integer(string_value):
        value.type = ParameterType.PARAMETER_INTEGER
        value.integer_value = int(string_value)
    elif _is_float(string_value):
        value.type = ParameterType.PARAMETER_DOUBLE
        value.double_value = float(string_value)
    else:
        value.type = ParameterType.PARAMETER_STRING
        value.string_value = string_value
    return value
Exemplo n.º 9
0
    async def get_parameters_callback(self, req, rsp):
        dtstr = self._get_gap_str_datetime()
        self.logger.info("[{}]Service start! ==========".format(dtstr))

        # 0.5秒待機(重たい処理の代わり)
        length = len(self._df)
        for i, row in self._df.iterrows():
            self.logger.info("<Srv>[{}/{}]{}".format(i, length,
                                                     row.loc[self._NAME_DATA]))
            para = ParameterValue()
            para.string_value = row.loc[self._NAME_DATA]
            time.sleep(0.5)
        rsp.values.append(para)

        dtstr = self._get_gap_str_datetime()
        self.logger.info("[{}]Service end! ==========".format(dtstr))

        return rsp
Exemplo n.º 10
0
    def test_parameter_value_to_python(self):
        """Test the parameter_value_to_python conversion function."""
        test_cases = [
            (ParameterValue(type=int(ParameterType.PARAMETER_NOT_SET)), None),
            (ParameterValue(type=int(ParameterType.PARAMETER_INTEGER),
                            integer_value=42), 42),
            (ParameterValue(type=int(ParameterType.PARAMETER_DOUBLE),
                            double_value=3.5), 3.5),
            (ParameterValue(type=int(ParameterType.PARAMETER_STRING),
                            string_value='foo'), 'foo'),
            (ParameterValue(type=int(ParameterType.PARAMETER_BYTE_ARRAY),
                            byte_array_value=[b'J', b'P']), [b'J', b'P']),
            (ParameterValue(type=int(ParameterType.PARAMETER_INTEGER_ARRAY),
                            integer_array_value=[1, 2, 3]), [1, 2, 3]),
            (ParameterValue(type=int(ParameterType.PARAMETER_DOUBLE_ARRAY),
                            double_array_value=[1.0, 2.0,
                                                3.0]), [1.0, 2.0, 3.0]),
            (ParameterValue(type=int(ParameterType.PARAMETER_STRING_ARRAY),
                            string_array_value=['foo', 'bar']), ['foo',
                                                                 'bar']),
        ]

        for input_value, expected_value in test_cases:
            result_value = parameter_value_to_python(input_value)
            if isinstance(expected_value, list):
                assert len(result_value) == len(expected_value)
                # element-wise comparison for lists
                assert all(x == y
                           for x, y in zip(result_value, expected_value))
            else:
                assert result_value == expected_value

        # Test invalid 'type' member
        parameter_value = ParameterValue(type=42)
        with pytest.raises(RuntimeError):
            parameter_value_to_python(parameter_value)
Exemplo n.º 11
0
def _get_parameter_value(string_value):
    """
    Guess the desired type of the parameter based on the string value

    @param string_value: The string value of a parameter
    """
    value = ParameterValue()
    try:
        yaml_value = yaml.safe_load(string_value)
    except yaml.parser.ParserError:
        value.type = ParameterType.PARAMETER_STRING
        value.string_value = string_value
        return value
    if isinstance(yaml_value, bool):
        value.type = ParameterType.PARAMETER_BOOL
        value.bool_value = yaml_value
    elif isinstance(yaml_value, int):
        value.type = ParameterType.PARAMETER_INTEGER
        value.integer_value = yaml_value
    elif isinstance(yaml_value, float):
        value.type = ParameterType.PARAMETER_DOUBLE
        value.double_value = yaml_value
    elif isinstance(yaml_value, list):
        if all((isinstance(v, bool) for v in yaml_value)):
            value.type = ParameterType.PARAMETER_BOOL_ARRAY
            value.bool_array_value = yaml_value
        elif all((isinstance(v, int) for v in yaml_value)):
            value.type = ParameterType.PARAMETER_INTEGER_ARRAY
            value.integer_array_value = yaml_value
        elif all((isinstance(v, float) for v in yaml_value)):
            value.type = ParameterType.PARAMETER_DOUBLE_ARRAY
            value.double_array_value = yaml_value
        elif all((isinstance(v, str) for v in yaml_value)):
            value.type = ParameterType.PARAMETER_STRING_ARRAY
            value.string_array_value = yaml_value
        else:
            value.type = ParameterType.PARAMETER_STRING
            value.string_value = string_value
    else:
        value.type = ParameterType.PARAMETER_STRING
        value.string_value = string_value
    return value
Exemplo n.º 12
0
 def get_parameter_value(self):
     parameter_value = ParameterValue(type=self.type_.value)
     if Parameter.Type.BOOL == self.type_:
         parameter_value.bool_value = self.value
     elif Parameter.Type.INTEGER == self.type_:
         parameter_value.integer_value = self.value
     elif Parameter.Type.DOUBLE == self.type_:
         parameter_value.double_value = self.value
     elif Parameter.Type.STRING == self.type_:
         parameter_value.string_value = self.value
     elif Parameter.Type.BYTE_ARRAY == self.type_:
         parameter_value.byte_array_value = self.value
     elif Parameter.Type.BOOL_ARRAY == self.type_:
         parameter_value.bool_array_value = self.value
     elif Parameter.Type.INTEGER_ARRAY == self.type_:
         parameter_value.integer_array_value = self.value
     elif Parameter.Type.DOUBLE_ARRAY == self.type_:
         parameter_value.double_array_value = self.value
     elif Parameter.Type.STRING_ARRAY == self.type_:
         parameter_value.string_array_value = self.value
     return parameter_value
Exemplo n.º 13
0
    def declare_parameter(
        self,
        name: str,
        value: ParameterValue = ParameterValue(),
        descriptor: ParameterDescriptor = ParameterDescriptor()
    ) -> Parameter:
        """
        Declare and initialize a parameter.

        This method, if successful, will result in any callback registered with
        :func:`set_parameters_callback` to be called.

        :param name: Fully-qualified name of the parameter, including its namespace.
        :param value: Value of the parameter to declare.
        :param descriptor: Descriptor for the parameter to declare.
        :return: Parameter with the effectively assigned value.
        :raises: ParameterAlreadyDeclaredException if the parameter had already been declared.
        :raises: InvalidParameterException if the parameter name is invalid.
        :raises: InvalidParameterValueException if the registered callback rejects the parameter.
        """
        return self.declare_parameters('', [(name, value, descriptor)])[0]
Exemplo n.º 14
0
def _set_param(node_name, name, value, parameter_type=None):
    """
    Internal helper function for set_param.
    Attempts to set the given parameter in the target node with the desired value,
    deducing the parameter type if it's not specified.
    parameter_type allows forcing a type for the given value; this is useful to delete parameters.
    """
    parameter = Parameter()
    parameter.name = name
    if parameter_type is None:
        parameter.value = get_parameter_value(string_value=value)
    else:
        parameter.value = ParameterValue()
        parameter.value.type = parameter_type
        if parameter_type != ParameterType.PARAMETER_NOT_SET:
            setattr(parameter.value, _parameter_type_mapping[parameter_type])

    try:
        # call_get_parameters will fail if node does not exist.
        call_set_parameters(node=_node,
                            node_name=node_name,
                            parameters=[parameter])
    except:
        pass
Exemplo n.º 15
0
    def test_declare_parameter(self):
        result_initial_foo = self.node.declare_parameter(
            'initial_foo', ParameterValue(), ParameterDescriptor())
        result_foo = self.node.declare_parameter(
            'foo',
            ParameterValue(type=Parameter.Type.INTEGER.value,
                           integer_value=42), ParameterDescriptor())
        result_bar = self.node.declare_parameter(
            'bar',
            ParameterValue(type=Parameter.Type.STRING.value,
                           string_value='hello'), ParameterDescriptor())
        result_baz = self.node.declare_parameter(
            'baz',
            ParameterValue(type=Parameter.Type.DOUBLE.value,
                           double_value=2.41), ParameterDescriptor())

        # OK cases.
        self.assertIsInstance(result_initial_foo, Parameter)
        self.assertIsInstance(result_foo, Parameter)
        self.assertIsInstance(result_bar, Parameter)
        self.assertIsInstance(result_baz, Parameter)
        self.assertEqual(result_initial_foo.value, 4321)
        self.assertEqual(result_foo.value, 42)
        self.assertEqual(result_bar.value, 'hello')
        self.assertEqual(result_baz.value, 2.41)
        self.assertEqual(self.node.get_parameter('initial_foo').value, 4321)
        self.assertEqual(self.node.get_parameter('foo').value, 42)
        self.assertEqual(self.node.get_parameter('bar').value, 'hello')
        self.assertEqual(self.node.get_parameter('baz').value, 2.41)

        # Error cases.
        with self.assertRaises(ParameterAlreadyDeclaredException):
            self.node.declare_parameter(
                'foo',
                ParameterValue(type=Parameter.Type.STRING.value,
                               string_value='raise'), ParameterDescriptor())
        with self.assertRaises(InvalidParameterException):
            self.node.declare_parameter(
                '123foo',
                ParameterValue(type=Parameter.Type.STRING.value,
                               string_value='raise'), ParameterDescriptor())
        with self.assertRaises(InvalidParameterException):
            self.node.declare_parameter(
                'foo??',
                ParameterValue(type=Parameter.Type.STRING.value,
                               string_value='raise'), ParameterDescriptor())

        self.node.set_parameters_callback(self.reject_parameter_callback)
        with self.assertRaises(InvalidParameterValueException):
            self.node.declare_parameter(
                'reject_me',
                ParameterValue(type=Parameter.Type.STRING.value,
                               string_value='raise'), ParameterDescriptor())

        with self.assertRaises(AssertionError):
            self.node.declare_parameter(
                1,
                ParameterValue(type=Parameter.Type.STRING.value,
                               string_value='wrong_name_type'),
                ParameterDescriptor())

        with self.assertRaises(AssertionError):
            self.node.declare_parameter('wrong_parameter_value_type', 1234,
                                        ParameterDescriptor())

        with self.assertRaises(AssertionError):
            self.node.declare_parameter('wrong_parameter_descriptor_type',
                                        ParameterValue(), ParameterValue())
Exemplo n.º 16
0
from rcl_interfaces.msg import Parameter, ParameterType, ParameterValue
import rclpy
import rclpy.logging

# Run velocities
auv_xy_velo = 0.4
auv_z_velo = 0.2  # Run slower to actually hit the run phase
auv_yaw_velo = 0.4

# Use these parameters to force a simple back/forth motion
straight_motion_auv_params = [
    # pose_plan_max_short_plan_xy controls how much distance to cover with an "all DoF" motion,
    # vs. the more typical "long plan" that turns toward the motion, runs, then turns again.
    # Set this to a large value so that we can run backwards and side-to-side without turning.
    Parameter(name='pose_plan_max_short_plan_xy',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                   double_value=99.)),

    # Turn off replanning
    Parameter(name='global_plan_max_xy_err',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                   double_value=99.0)),

    # good_pose_dist controls how close we need to be to a marker to trust the pose.
    # Set this to a large-ish value so that we always build a local plan at each pose.
    Parameter(name='good_pose_dist',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                   double_value=4.)),

    # Specify the run velocities
    Parameter(name='auv_xy_velo',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
Exemplo n.º 17
0

# Get zn_no_overshoot PID parameters
# Not used in ft3
def zn_no_overshoot(Ku, Tu):
    return [0.2 * Ku, 0.4 * Ku / Tu, 0.0667 * Ku * Tu]


def zn_no_overshoot_params(dim: str, Ku, Tu):
    return pid_param_obj(dim, zn_no_overshoot(Ku, Tu))


base_auv_params = [
    # Never replan
    Parameter(name='global_plan_max_xy_err',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=10.0)),

    # Trust markers up to 3m away
    Parameter(name='good_pose_dist',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=3.0)),
]

# Normal motion, with local planning
# Use the planned yaw to rotate body to world frame (this is the default)
normal_motion_params = [
    Parameter(name='pose_plan_pause_duration',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=1.0)),
    Parameter(name='pose_plan_epsilon_xyz',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=0.05)),
    Parameter(name='pose_plan_epsilon_yaw',
              value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=0.05)),
Exemplo n.º 18
0
def dict_to_obj(d: Dict):
    return [Parameter(name=item[0],
                      value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE,
                                           double_value=item[1]))
            for item in d.items()]
Exemplo n.º 19
0
def set_param_double(params: List[Parameter], name: str, value: float):
    for param in params:
        if param.name == name:
            param.value = ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=value)
            return
    print('ERROR parameter', name, 'is not in the list')
Exemplo n.º 20
0
 def __init__(self, **kwargs):
     assert all(['_' + key in self.__slots__ for key in kwargs.keys()]), \
         "Invalid arguments passed to constructor: %r" % kwargs.keys()
     self.name = kwargs.get('name', str())
     from rcl_interfaces.msg import ParameterValue
     self.value = kwargs.get('value', ParameterValue())
Exemplo n.º 21
0
    def declare_parameters(
        self, namespace: str,
        parameters: List[Tuple[str, Optional[ParameterValue],
                               Optional[ParameterDescriptor]]]
    ) -> List[Parameter]:
        """
        Declare a list of parameters.

        This method, if successful, will result in any callback registered with
        :func:`set_parameters_callback` to be called once for each parameter.
        If one of those calls fail, an exception will be raised and the remaining parameters will
        not be declared.
        Parameters declared up to that point will not be undeclared.

        :param namespace: Namespace for parameters.
        :param parameters: Tuple with parameters to declare, with a name, value and descriptor.
        :return: Parameter list with the effectively assigned values for each of them.
        :raises: ParameterAlreadyDeclaredException if the parameter had already been declared.
        :raises: InvalidParameterException if the parameter name is invalid.
        :raises: InvalidParameterValueException if the registered callback rejects any parameter.
        """
        parameter_list = []
        descriptor_list = []
        for parameter_tuple in parameters:
            name = parameter_tuple[0]
            assert isinstance(name, str)
            # Get value from initial parameters, of from tuple if it doesn't exist.
            if name in self._initial_parameters:
                value = self._initial_parameters[name].get_parameter_value()
            elif parameter_tuple[1] is None:
                value = ParameterValue()
            else:
                value = parameter_tuple[1]
            assert isinstance(value, ParameterValue)
            descriptor = parameter_tuple[2]
            if descriptor is None:
                descriptor = ParameterDescriptor()
            assert isinstance(descriptor, ParameterDescriptor)

            # Note(jubeira): declare_parameters verifies the name, but set_parameters doesn't.
            full_name = namespace + name
            validate_parameter_name(full_name)

            parameter_list.append(
                Parameter.from_parameter_msg(
                    ParameterMsg(name=full_name, value=value)))
            descriptor_list.append(descriptor)

        parameters_already_declared = [
            parameter.name for parameter in parameter_list
            if parameter.name in self._parameters
        ]
        if any(parameters_already_declared):
            raise ParameterAlreadyDeclaredException(
                parameters_already_declared)

        # Call the callback once for each of the parameters, using method that doesn't
        # check whether the parameter was declared beforehand or not.
        self._set_parameters(parameter_list,
                             descriptor_list=descriptor_list,
                             raise_on_failure=True)
        return self.get_parameters(
            [parameter.name for parameter in parameter_list])
Exemplo n.º 22
0
    def __init__(self):
        super().__init__('experiments')

        # Set up experiments
        self._experiments = [
            # Experiment(note='simple controller', mode=Control.AUV_SEQUENCE, count=1, base_params=[
            #     Parameter(name='auv_z_target',
            #               value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=-1.5)),
            #     Parameter(name='auv_controller',
            #               value=ParameterValue(type=ParameterType.PARAMETER_INTEGER, integer_value=0)),
            # ], filter_params=[
            #     Parameter(name='four_dof',
            #               value=ParameterValue(type=ParameterType.PARAMETER_BOOL, bool_value=True)),
            # ]),
            Experiment(note='ignore estimate controller',
                       mode=Control.AUV_SEQUENCE,
                       count=1,
                       base_params=[
                           Parameter(name='auv_z_target',
                                     value=ParameterValue(
                                         type=ParameterType.PARAMETER_DOUBLE,
                                         double_value=-1.5)),
                           Parameter(name='auv_controller',
                                     value=ParameterValue(
                                         type=ParameterType.PARAMETER_INTEGER,
                                         integer_value=1)),
                       ],
                       filter_params=[
                           Parameter(name='four_dof',
                                     value=ParameterValue(
                                         type=ParameterType.PARAMETER_BOOL,
                                         bool_value=True)),
                       ]),

            # Experiment(note='six DoF filter', mode=Control.AUV_SEQUENCE, count=10, base_params=[
            #     Parameter(name='auv_z_target',
            #               value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=-1.5))
            # ], filter_params=[
            #     Parameter(name='four_dof',
            #               value=ParameterValue(type=ParameterType.PARAMETER_BOOL, bool_value=False))
            # ]),
            #
            # Experiment(note='four DoF filter', mode=Control.AUV_SEQUENCE, count=10, base_params=[
            #     Parameter(name='auv_z_target',
            #               value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=-1.5))
            # ], filter_params=[
            #     Parameter(name='four_dof',
            #               value=ParameterValue(type=ParameterType.PARAMETER_BOOL, bool_value=True))
            # ]),
        ]

        # self._experiments = []
        # for step in range(1, 20, 1):
        #     self._experiments.append(Experiment(note='', mode=Control.AUV_SEQUENCE, count=1, base_params=[
        #                 Parameter(name='auv_z_target',
        #                           value=ParameterValue(type=ParameterType.PARAMETER_DOUBLE, double_value=-(2. + step/10.)))
        #             ], filter_params=[]))

        # If we're in a mission record odometry and ground truth messages for later processing
        self._odom_msgs: Optional[List[Odometry]] = None
        self._gt_msgs: Optional[List[Odometry]] = None
        self._odom_sub = self.create_subscription(Odometry, '/odom',
                                                  self.odom_cb, 5)
        self._gt_sub = self.create_subscription(Odometry, '/ground_truth',
                                                self.gt_cb, 5)

        # Set parameter service clients
        self._set_param_base_node_client = self.create_client(
            SetParameters, '/base_node/set_parameters')
        self._set_param_filter_node_client = self.create_client(
            SetParameters, '/filter_node/set_parameters')

        # Mission action client
        self._mission_action_client = ActionClient(self, Mission, '/mission')

        # Futures manage the async state changes
        self._set_base_node_params_future = None
        self._set_filter_node_params_future = None
        self._send_goal_future = None
        self._get_result_future = None

        # Start 1st experiment
        self._idx = 0
        self._count = 0
        self.get_logger().info(
            'starting experiment {}, ({}), will run {} time(s)'.format(
                self._idx, self._experiments[self._idx].note,
                self._experiments[self._idx].count))
        self.get_logger().info('starting run {} of {}'.format(
            self._count + 1, self._experiments[self._idx].count))

        # Step 1
        self.set_base_node_params()
Exemplo n.º 23
0
    def test_declare_parameters(self):
        parameters = [
            ('foo',
             ParameterValue(type=Parameter.Type.INTEGER.value,
                            integer_value=42), ParameterDescriptor()),
            ('bar',
             ParameterValue(type=Parameter.Type.STRING.value,
                            string_value='hello'), ParameterDescriptor()),
            ('baz',
             ParameterValue(type=Parameter.Type.DOUBLE.value,
                            double_value=2.41), ParameterDescriptor()),
        ]

        result = self.node.declare_parameters('', parameters)

        # OK cases.
        self.assertIsInstance(result, list)
        self.assertIsInstance(result[0], Parameter)
        self.assertIsInstance(result[1], Parameter)
        self.assertIsInstance(result[2], Parameter)
        self.assertEqual(result[0].value, 42)
        self.assertEqual(result[1].value, 'hello')
        self.assertEqual(result[2].value, 2.41)
        self.assertEqual(self.node.get_parameter('foo').value, 42)
        self.assertEqual(self.node.get_parameter('bar').value, 'hello')
        self.assertEqual(self.node.get_parameter('baz').value, 2.41)

        result = self.node.declare_parameters('/namespace/', parameters)

        # OK cases.
        self.assertIsInstance(result, list)
        self.assertIsInstance(result[0], Parameter)
        self.assertIsInstance(result[1], Parameter)
        self.assertIsInstance(result[2], Parameter)
        self.assertEqual(result[0].value, 42)
        self.assertEqual(result[1].value, 'hello')
        self.assertEqual(result[2].value, 2.41)
        self.assertEqual(self.node.get_parameter('/namespace/foo').value, 42)
        self.assertEqual(
            self.node.get_parameter('/namespace/bar').value, 'hello')
        self.assertEqual(self.node.get_parameter('/namespace/baz').value, 2.41)

        # Error cases.
        with self.assertRaises(ParameterAlreadyDeclaredException):
            self.node.declare_parameters('', parameters)

        # Declare a new set of parameters; the first one is not already declared,
        # but 2nd and 3rd one are.
        parameters = [
            ('foobar',
             ParameterValue(type=Parameter.Type.INTEGER.value,
                            integer_value=43), ParameterDescriptor()),
            ('bar',
             ParameterValue(type=Parameter.Type.STRING.value,
                            string_value='hello'), ParameterDescriptor()),
            ('baz',
             ParameterValue(type=Parameter.Type.DOUBLE.value,
                            double_value=2.41), ParameterDescriptor()),
        ]
        with self.assertRaises(ParameterAlreadyDeclaredException):
            self.node.declare_parameters('', parameters)

        # Declare a new set; the third one shall fail because of its name.
        parameters = [
            ('foobarbar',
             ParameterValue(type=Parameter.Type.INTEGER.value,
                            integer_value=44), ParameterDescriptor()),
            ('barbarbar',
             ParameterValue(type=Parameter.Type.STRING.value,
                            string_value='world'), ParameterDescriptor()),
            ('baz??wrong_name',
             ParameterValue(type=Parameter.Type.DOUBLE.value,
                            double_value=2.41), ParameterDescriptor()),
        ]
        with self.assertRaises(InvalidParameterException):
            self.node.declare_parameters('', parameters)

        # Declare a new set; the third one shall be rejected by the callback.
        parameters = [
            ('im_ok',
             ParameterValue(type=Parameter.Type.INTEGER.value,
                            integer_value=44), ParameterDescriptor()),
            ('im_also_ok',
             ParameterValue(type=Parameter.Type.STRING.value,
                            string_value='world'), ParameterDescriptor()),
            ('reject_me',
             ParameterValue(type=Parameter.Type.DOUBLE.value,
                            double_value=2.41), ParameterDescriptor()),
        ]
        self.node.set_parameters_callback(self.reject_parameter_callback)
        with self.assertRaises(InvalidParameterValueException):
            self.node.declare_parameters('', parameters)

        with self.assertRaises(AssertionError):
            self.node.declare_parameters(
                '', [(1,
                      ParameterValue(type=Parameter.Type.STRING.value,
                                     string_value='wrong_name_type'),
                      ParameterDescriptor())])

        with self.assertRaises(AssertionError):
            self.node.declare_parameters(
                '',
                [('wrong_parameter_value_type', 1234, ParameterDescriptor())])

        with self.assertRaises(AssertionError):
            self.node.declare_parameters(
                '', [('wrong_parameter_descriptor_tpye', ParameterValue(),
                      ParameterValue())])