utils.py
Go to the documentation of this file.
1 import os
2 import yaml
3 
4 
5 def create_xacro_file(xacro_target,
6  yaml_file=None,
7  requested_macros=None,
8  boiler_plate_top='',
9  boiler_plate_bot='',
10  num_test=lambda name, num: True,
11  param_test=lambda name, params={}: True,
12  ):
13  """
14  Purpose: Create a .xacro file to create a custom WAM-V .urdf
15 
16  Args:
17  xacro_target (str): Target file for writing the xacro to
18  NOTE: will overwrite an existing file
19  yaml_file (str): .yaml file with requested macros
20  requested_macros (dict): if dict is passed directly => ignore yaml file
21  boiler_plate_top (str): String to start the xacro file
22  boiler_plate_bot (str): String to end the xacro file
23  num_test (function): test if the number of macro types is allowed
24  param_test (function): test if a macro call parameters are sensible
25 
26  Creates a xacro file at 'xacro_target'
27 
28  Returns test_fail (bool): Indicator if the wamv passed compliance tests
29  """
30  test_fail = False
31  # Initialize xacro file
32  xacro_file = open(xacro_target, 'wb')
33  xacro_file.write(boiler_plate_top)
34 
35  # If requested_macros not given, then open yaml_file
36  if requested_macros is None:
37  s = open(yaml_file, 'r')
38  requested_macros = yaml.safe_load(s)
39 
40  # Handle case with empty yaml file
41  if requested_macros is None:
42  xacro_file.write(boiler_plate_bot)
43  xacro_file.close()
44  return
45 
46  # Object must be available
47  for key, objects in requested_macros.items():
48  # Check if number of objects is valid
49  test_fail = num_test(key, len(objects))
50 
51  # Create block for each object
52  xacro_file.write(' <!-- === %s === -->\n' % key)
53  for i in objects:
54  # Check for valid parameters
55  test_fail = param_test(key, i)
56 
57  # Write macro
58  # Strip all astrisks from key value to allow us to call
59  # the same macro multiple times.
60  xacro_file.write(' ' + macro_call_gen(key.strip('*'), i))
61  xacro_file.write('\n')
62 
63  xacro_file.write(boiler_plate_bot)
64  xacro_file.close()
65  return test_fail
66 
67 
68 def add_gazebo_thruster_config(xacro_target,
69  yaml_file=None,
70  requested_macros=None,
71  boiler_plate_top='',
72  boiler_plate_bot='',
73  ):
74  """
75  Purpose: Append gazebo thruster config tags to a .xacro file to
76  create a custom WAM-V .urdf
77 
78  Args:
79  xacro_target (str): Target file for writing the xacro to
80  NOTE: will append an existing file
81  should be used on thruster
82  xacro file created by
83  create_xacro_file()
84  yaml_file (str): .yaml file with requested macros
85  requested_macros (dict): if dict is passed directly => ignore yaml file
86  boiler_plate_top (str): First string to append to the xacro file
87  boiler_plate_bot (str): Last string to append to the xacro file
88 
89  Appends gazebo thruster config tags to 'xacro_target'
90  """
91  # Initialize xacro file for appending
92  xacro_file = open(xacro_target, 'ab')
93  xacro_file.write(boiler_plate_top)
94 
95  # If requested_macros not given, then open yaml_file
96  if requested_macros is None:
97  s = open(yaml_file, 'r')
98  requested_macros = yaml.safe_load(s)
99 
100  # Handle case with empty yaml file
101  if requested_macros is None:
102  xacro_file.write(boiler_plate_bot)
103  xacro_file.close()
104  return
105 
106  # WAM-V Gazebo thrust plugin setup
107  for key, objects in requested_macros.items():
108  for obj in objects:
109  xacro_file.write(' ' +
110  macro_call_gen('wamv_gazebo_thruster_config',
111  {'name': obj['prefix']}))
112 
113  xacro_file.write(boiler_plate_bot)
114  xacro_file.close()
115 
116 
117 def macro_call_gen(name, params={}):
118  macro_call = ' <xacro:%s ' % name
119  endline = '/>\n'
120  insert = []
121  for i in params:
122  if i[:3] == '/**':
123  endline = '>\n'
124  insert.append(i[3:])
125  else:
126  macro_call += '%s="%s" ' % (i, str(params[i]))
127  macro_call += endline
128  if insert == []:
129  return macro_call
130  for i in insert:
131  macro_call += ' <%s>\n' % i
132  macro_call += str(params['/**' + i])
133  macro_call += ' </%s>\n' % i
134  macro_call += ' </xacro:' + name + '>\n'
135  return macro_call
136 
137 
138 # Note: all functions below are not currently used, but they are intended
139 # to be used by compliance tests.
140 def get_macros(directory):
141  xacro_files = get_macro_files(directory)
142  macros = {}
143  for i in xacro_files:
144  name, params = parse_xacro_file(i)
145  macros[name] = params
146  return macros
147 
148 
149 def get_macro_files(directory):
150  xacro_files = [directory+'/'+f for f in os.listdir(directory)
151  if os.path.isfile(os.path.join(directory, f)) and
152  (f[-6:] == '.xacro')]
153  child_directories = [d[0] for d in os.walk(directory)]
154  child_directories = child_directories[1:]
155  for i in child_directories:
156  for j in get_macro_files(i):
157  xacro_files.append(j)
158  return xacro_files
159 
160 
161 def parse_xacro_file(xacro_file_name):
162  xacro_file = open(xacro_file_name, 'r')
163  contents = xacro_file.read()
164  # remove comment blocks
165  while '<!--' in contents:
166  start = contents.find('<!--')
167  end = contents.find('-->')
168  contents = contents.replace(contents[start:end+3], '')
169  # get macro declaration
170  start = contents.find('<xacro:macro')
171  end = contents.find('>', start)
172  declaration = contents[start:end]
173 
174  contents = contents.replace(contents[start:end+1], '')
175  # remove the declaration from the string so we know we processed it
176  name_pose = declaration.find('name')
177  start = declaration.find('"', name_pose)
178  end = declaration.find('"', start+1)
179  name = declaration[start+1:end]
180 
181  params_pose = declaration.find('params')
182  start = declaration.find('"', params_pose)
183  end = declaration.find('"', start+1)
184  params_str = declaration[start+1:end].split(' ')
185  params = {}
186  for i in params_str:
187  i = i.replace('\n', '')
188  if i != '':
189  key = i
190  if ':' in i:
191  key = i[:i.find(':')]
192  if '=' in i:
193  value = i[i.find('=')+1:]
194  else:
195  value = ''
196  value = value.replace('\n', '')
197  params[key] = value
198 
199  if contents.find('<xacro:macro') != -1:
200  raise Exception('multiple macros defined in %s' % xacro_file_name)
201 
202  return name, params
def add_gazebo_thruster_config(xacro_target, yaml_file=None, requested_macros=None, boiler_plate_top='', boiler_plate_bot='')
Definition: utils.py:73
def parse_xacro_file(xacro_file_name)
Definition: utils.py:161
def macro_call_gen(name, params={})
Definition: utils.py:117


vrx_gazebo
Author(s): Brian Bingham , Carlos Aguero
autogenerated on Thu May 7 2020 03:54:56