Skip to content

Commit 4bc65c0

Browse files
add utility to import complex message and add support for nested array in set_message
Signed-off-by: Mikael Arguedas <[email protected]>
1 parent ed01243 commit 4bc65c0

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2019 Mikael Arguedas.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import importlib
16+
from typing import Any
17+
18+
from rosidl_parser.definition import NamespacedType
19+
20+
21+
def import_message_from_namespaced_type(message_type: NamespacedType) -> Any:
22+
module = importlib.import_module(
23+
'.'.join(message_type.basetype.namespaces))
24+
return getattr(module, message_type.basetype.name)

rosidl_runtime_py/rosidl_runtime_py/set_message.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
from typing import Any
1616
from typing import Dict
1717

18+
from rosidl_parser.definition import NamespacedType
19+
from rosidl_runtime_py.convert import slot_types_dict_from_message
20+
from rosidl_runtime_py.import_message import import_message_from_namespaced_type
21+
1822

1923
def set_message_fields(msg: Any, values: Dict[str, str]) -> None:
2024
"""
@@ -33,4 +37,13 @@ def set_message_fields(msg: Any, values: Dict[str, str]) -> None:
3337
except TypeError:
3438
value = field_type()
3539
set_message_fields(value, field_value)
40+
rosidl_type = slot_types_dict_from_message(msg)[field_name]
41+
# Check if field is an array of ROS messages
42+
if isinstance(field_type(), list):
43+
if isinstance(rosidl_type.basetype, NamespacedType):
44+
field_elem_type = import_message_from_namespaced_type(rosidl_type)
45+
for n in range(len(value)):
46+
submsg = field_elem_type()
47+
set_message_fields(submsg, value[n])
48+
value[n] = submsg
3649
setattr(msg, field_name, value)

0 commit comments

Comments
 (0)