forked from CentraleNantesRobotics/ros2_convert_msg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.py
executable file
·224 lines (173 loc) · 7.53 KB
/
convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python3
import os
import sys
import shutil
import yaml
import rospkg
types_convert = {}
types_convert['time'] = 'builtin_interfaces/Time'
types_convert['Header'] = 'std_msgs/Header'
types_convert['rosgraph_msgs/Log'] = 'rcl_interfaces/Log'
class Interface:
def __init__(self, filename, package_name):
self.filename = os.path.basename(filename)
self.depends = set()
self.types = set()
self.interface = 'message' if filename[-3:] == 'msg' else 'service'
self.name = self.filename[:-4]
print('\nParsing ' + self.filename)
with open(filename) as f:
content = [line.strip() for line in f.read().splitlines()]
# changes to ROS 2 field names
is_srv = '---' in content
if is_srv:
self.fields_1_to_2 = {'request_': {}, 'response_': {}}
fields = {'request_': [], 'response_': []}
field_prefix = 'request_'
else:
self.fields_1_to_2 = {'': {}}
fields = {'': []}
field_prefix = ''
self.content = []
for line in content:
if line == '---':
field_prefix = 'response_'
if line.startswith('#') or ' ' not in line:
self.content.append(line)
continue
line_spt = line.split()
type_1 = line_spt[0]
field_1 = line_spt[1]
if '=' in field_1:
field_1, info = field_1.split('=')
if len(line_spt) == 2:
line_spt.append('=' + info)
else:
line_spt[2] = '=' + info + line_spt[2]
# adapt field name
field_2 = field_1
if len(line_spt) > 2 and line_spt[2].startswith('='):
# constant should be upper case
if not field_1.isupper():
field_2 = field_1.upper()
else:
# non-constant should be snake_case
if not field_1.islower():
field_2 = ''.join(s.islower() and s or '_'+s.lower() for s in field_1).strip('_')
# adapt field type
type_2 = type_1
if type_2 in types_convert:
type_2 = types_convert[type_2]
if field_2.islower():
if field_2 != field_1:
self.fields_1_to_2[field_prefix][field_1] = field_2
else:
fields[field_prefix].append(field_1)
if package_name in type_2:
type_2 = type_2.split('/')[1]
self.types.add(type_2.strip('[]'))
info = field_2.islower() and 'variable' or 'constant'
if type_2 != type_1 or field_2 != field_1:
print(' {} field {} {} -> changed to {} {}'.format(info, type_1, field_1, type_2, field_2))
#else:
# print(' {} field {} {} -> ok'.format(info, type_1, field_1))
if '/' in type_2:
self.depends.add(type_2.split('/')[0])
self.content.append('{} {} {}'.format(type_2, field_2, ' '.join(line_spt[2:])))
self.content = '\n'.join(self.content)
if any(f for f in self.fields_1_to_2.values()):
for key in fields:
for field in fields[key]:
self.fields_1_to_2[key][field] = field
def save(self, dst):
dst = os.path.join(dst, self.filename[-3:])
if not os.path.exists(dst):
os.makedirs(dst)
with open(os.path.join(dst, self.filename), 'w') as f:
f.write(self.content)
def rep(self):
return '"{}/{}"'.format(self.filename[-3:], self.filename)
def usage(s = ''):
if s:
print(s)
print('Run this script by giving the ROS 1 message package path and the ROS 2 workspace')
sys.exit(0)
if __name__ == '__main__':
if len(sys.argv) != 3:
usage()
src = sys.argv[1]
dst = sys.argv[2]
if not os.path.exists(src):
# try by package name
rospack = rospkg.RosPack()
try:
src = rospack.get_path(src)
except:
pass
if not os.path.exists(src):
usage('ROS 1 package does not exist')
if not os.path.exists(dst):
usage('ROS 2 destination does not exist')
if 'src' in os.listdir(dst):
dst = os.path.join(dst, 'src')
package_name = os.path.basename(src.rstrip(os.path.sep))
dst = os.path.join(dst, package_name)
msgs = []
depends = set()
if os.path.exists(dst):
shutil.rmtree(dst)
for msg_type in ('msg','srv'):
src_dir = os.path.join(src, msg_type)
if os.path.exists(src_dir):
msgs += [Interface(os.path.join(src_dir, f), package_name) for f in os.listdir(src_dir)]
if not msgs:
usage('No interfaces defined in {}'.format(src))
# Create message files
for msg in msgs:
msg.save(dst)
for d in msg.depends:
depends.add(d)
# Create CMakeLists and package.xml
template_path = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(template_path, 'CMakeLists.txt.template')) as f:
cmake = f.read()
with open(os.path.join(template_path, 'package.xml.template')) as f:
pkg_xml = f.read()
cmake = cmake.replace('<package>', package_name)
pkg_xml = pkg_xml.replace('<package>', package_name)
find_depends = []
xml_depends = []
for depend in depends:
find_depends.append('find_package({} REQUIRED)'.format(depend))
for key in ('build', 'exec'):
xml_depends.append('<{key}_depend>{depend}</{key}_depend>'.format(key = key, depend = depend))
cmake = cmake.replace('<find_depends>', '\n'.join(find_depends))
pkg_xml = pkg_xml.replace('<build_exec_depends>', '\n '.join(sorted(xml_depends)))
if depends:
cmake = cmake.replace('<msgs_depends>', 'DEPENDENCIES ' + ' '.join(depends))
else:
cmake = cmake.replace('<msgs_depends>', '')
cmake = cmake.replace('<msgs>', ' \n'.join(msg.rep() for msg in msgs))
mapping_rules = []
for msg in msgs:
if msg.fields_1_to_2:
interface = msg.interface + '_name'
mapping_rules.append({'ros1_package_name': package_name,
'ros2_package_name': package_name,
'ros1_'+interface: msg.name,
'ros2_'+interface: msg.name})
for key in msg.fields_1_to_2:
if msg.fields_1_to_2[key]:
mapping_rules[-1][key+'fields_1_to_2'] = msg.fields_1_to_2[key]
if mapping_rules:
with open(os.path.join(dst, 'mapping_rules.yaml'), 'w') as f:
yaml.safe_dump(mapping_rules, f)
cmake = cmake.replace('<custom_map>', 'install(FILES mapping_rules.yaml DESTINATION share/${PROJECT_NAME})')
pkg_xml = pkg_xml.replace('<custom_map>', '\n <ros1_bridge mapping_rules="mapping_rules.yaml"/>')
else:
cmake = cmake.replace('<custom_map>', '')
pkg_xml = pkg_xml.replace('<custom_map>', '')
with open(os.path.join(dst, 'CMakeLists.txt'), 'w') as f:
f.write(cmake)
with open(os.path.join(dst, 'package.xml'), 'w') as f:
f.write(pkg_xml)