python_gen.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- Python -*-
3 #
4 # @file Py_src.py
5 # @brief rtc-template Python soruce code generator class
6 # @date $Date: 2005/08/26 12:02:37 $
7 # @author Noriaki Ando <n-ando@aist.go.jp>
8 #
9 # Copyright (C) 2004-2008
10 # Task-intelligence Research Group,
11 # Intelligent Systems Research Institute,
12 # National Institute of
13 # Advanced Industrial Science and Technology (AIST), Japan
14 # All rights reserved.
15 #
16 # $Id$
17 #
18 
19 import re
20 import os
21 import gen_base
22 import string
23 import sys
24 
26  return "Python component code generator"
27 
28 def usage():
29  """
30  Python generator specific usage
31  """
32  return """
33 ----------------------------------
34  Help for Python code generator
35 ----------------------------------
36 Python code generator generates the following files.
37  [Component name].py............Component class and executable
38  README.[Component name]........Specification template of the component
39 
40 No additional options are available for Python code generator.
41 
42 """
43 
45  return []
46 
47 service_impl = """\
48 [for sidl in service_idl]
49 from [sidl.idl_basename]_idl_example import *
50 [endfor]"""
51 
52 global_idl = """\
53 import _GlobalIDL, _GlobalIDL__POA
54 """
55 no_global_idl = ""
56 
57 module_spec = """\
58 [l_name]_spec = ["implementation_id", "[basicInfo.name]",
59  "type_name", "[basicInfo.name]",
60  "description", "[basicInfo.description]",
61  "version", "[basicInfo.version]",
62  "vendor", "[basicInfo.vendor]",
63  "category", "[basicInfo.category]",
64  "activity_type", "[basicInfo.componentType]",
65  "max_instance", "[basicInfo.maxInstances]",
66  "language", "Python",
67  "lang_type", "SCRIPT",
68 [if-any configurationSet.configuration]
69 [for config in configurationSet.configuration]
70  "conf.default.[config.name]", "[config.defaultValue]",
71 [endfor][endif]
72  ""]
73 """
74 
75 data_ports = """\
76 [for dport in dataPorts]
77  self._d_[dport.name] = RTC.[dport.type]([dport.data_type_args])
78 [if dport.portType is DataInPort]
79  self._[dport.name]In = OpenRTM_aist.InPort("[dport.name]", self._d_[dport.name])
80  self.addInPort("[dport.name]",self._[dport.name]In)
81 
82 [elif dport.portType is DataOutPort]
83  self._[dport.name]Out = OpenRTM_aist.OutPort("[dport.name]", self._d_[dport.name])
84  self.addOutPort("[dport.name]",self._[dport.name]Out)
85 
86 [endif]
87 [endfor]
88 """
89 
90 service_ports = """\
91 [for sport in servicePorts]
92  self._[sport.name]Port = OpenRTM_aist.CorbaPort("[sport.name]")
93 [for sif in sport.serviceInterface]
94 [if sif.direction is Provided]
95  self._[sif.name] = [sif.type]_i()
96  self._[sport.name]Port.registerProvider("[sif.name]", "[sif.type]", self._[sif.name])
97 [elif sif.direction is Required]
98  self._[sif.name] = OpenRTM_aist.CorbaConsumer(interfaceType=_GlobalIDL.[sif.type])
99  self._[sport.name]Port.registerConsumer("[sif.name]", "[sif.type]", self._[sif.name])
100 [endif]
101  self.addPort(self._[sport.name]Port)
102 
103 [endfor]
104 [endfor]
105 """
106 
107 configurations = """\
108 [for config in configurationSet.configuration]
109  self._[config.name] = [config.defaultData]
110 
111 [endfor]
112 """
113 
114 bind_config = """
115 [for conf in configurationSet.configuration]
116  self.bindParameter("[conf.name]", self._[conf.name], "[conf.defaultValue]")
117 [endfor]"""
118 
119 
120 #------------------------------------------------------------
121 # Python component source code template
122 #------------------------------------------------------------
123 py_source = """#!/usr/bin/env python
124 # -*- Python -*-
125 
126 import sys
127 sys.path.append(".")
128 
129 # Import RTM module
130 import RTC
131 import OpenRTM_aist
132 
133 # Import Service implementation class
134 # <rtc-template block="service_impl">
135 # </rtc-template>
136 
137 # Import Service stub modules
138 # <rtc-template block="global_idl">
139 # </rtc-template>
140 
141 
142 # This module's spesification
143 # <rtc-template block="module_spec">
144 # </rtc-template>
145 
146 class [basicInfo.name](OpenRTM_aist.DataFlowComponentBase):
147  def __init__(self, manager):
148  OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
149 
150  # initialize of configuration-data.
151  # <rtc-template block="configurations">
152  # </rtc-template>
153 
154 
155  def onInitialize(self):
156  # DataPorts initialization
157  # <rtc-template block="data_ports">
158  # </rtc-template>
159 
160  # ServicePorts initialization
161  # <rtc-template block="service_ports">
162  # </rtc-template>
163 
164  # Bind variables and configuration variable
165  # <rtc-template block="bind_config">
166  # </rtc-template>
167  return RTC.RTC_OK
168 
169 
170 [for act in activity]
171  #def [act.name](self[if-any act.args], [act.args][else][endif]):
172  # return RTC.RTC_OK
173 
174 [endfor]
175 
176 
177 def [basicInfo.name]Init(manager):
178  profile = OpenRTM_aist.Properties(defaults_str=[l_name]_spec)
179  manager.registerFactory(profile,
180  [basicInfo.name],
181  OpenRTM_aist.Delete)
182 
183 
184 def MyModuleInit(manager):
185  [basicInfo.name]Init(manager)
186 
187  # Create a component
188  comp = manager.createComponent("[basicInfo.name]")
189 
190 
191 
192 def main():
193  mgr = OpenRTM_aist.Manager.init(sys.argv)
194  mgr.setModuleInitProc(MyModuleInit)
195  mgr.activateManager()
196  mgr.runManager()
197 
198 if __name__ == "__main__":
199  main()
200 
201 """
202 
203 
204 
205 
207  """
208  Python component source code generation class
209  """
210  def __init__(self, data, opts):
211  self.data = data
212  self.data['fname'] = self.data['basicInfo']['name']
213  self.data['fname_py'] = self.data['fname'] + ".py"
214  self.data["u_name"] = self.data["fname"].upper()
215  self.data["l_name"] = self.data["fname"].lower()
216 
217  self.CreateActivityFuncs(self.data)
218  self.CreateDataPorts(self.data)
219  self.CreateService(self.data)
220  self.CreateConfiguration(self.data)
221  self.tags = {}
222  self.tags["service_impl"] = service_impl
223  if len(self.data["service_idl"]) > 0 or \
224  len(self.data["consumer_idl"]) > 0:
225  self.tags["global_idl"] = global_idl
226  else:
227  self.tags["global_idl"] = no_global_idl
228  self.tags["module_spec"] = module_spec
229  self.tags["data_ports"] = data_ports
230  self.tags["service_ports"] = service_ports
231  self.tags["configurations"] = configurations
232  self.tags["bind_config"] = bind_config
233  self.gen_tags(self.tags)
234  return
235 
236 
237  def CreateActivityFuncs(self, dict):
238  acts = (("onFinalize", None), \
239  ("onStartup", "ec_id"), \
240  ("onShutdown", "ec_id"), \
241  ("onActivated", "ec_id"), \
242  ("onDeactivated", "ec_id"), \
243  ("onExecute", "ec_id"), \
244  ("onAborting", "ec_id"), \
245  ("onError", "ec_id"), \
246  ("onReset", "ec_id"), \
247  ("onStateUpdate", "ec_id"), \
248  ("onRateChanged", "ec_id"))
249  actlist = []
250  for name, args in acts:
251  a = {}
252  a["name"] = name
253  a["args"] = args
254  actlist.append(a)
255 
256  dict["activity"] = actlist
257  return
258 
259  def CreateService(self, dict):
260  if dict["service_idl"]:
261  for svc in dict["service_idl"]:
262  svc["impl_py"] = svc["idl_basename"] + \
263  "_idl_example.py"
264 
265  if dict["consumer_idl"]:
266  for cons in dict["consumer_idl"]:
267  try:
268  cons["modulename"] = "_GlobalIDL"
269  f = open(cons["idl_fname"], 'a+')
270  while 1:
271  _str = f.readline()
272  if not _str:
273  break
274  mod_idx = _str.find("module", 0)
275  if mod_idx < 0:
276  break;
277  _str = _str[mod_idx + 6:]
278  idx = _str.find("{", 0)
279  if idx < 0:
280  break
281  _str = _str[:idx]
282  cons["modulename"] = \
283  string.strip(_str)
284  break
285  f.close()
286  except IOError:
287  print "Can't find file:", file
288  return
289 
290  def CreateDataPorts(self, dict):
291  if dict["dataPorts"] == None:
292  return
293  for dport in dict["dataPorts"]:
294  if self.check_data_type(dport["type"]) == "sequence":
295  dport["data_type_args"] = "RTC.Time(0,0),[]"
296  else:
297  dport["data_type_args"] = "RTC.Time(0,0),0"
298  return
299 
300  def CreateConfiguration(self, dict):
301  config = dict["configurationSet"]["configuration"]
302  if config:
303  for i, conf in enumerate(config):
304  split_data = conf["defaultValue"].split(",")
305  if len(split_data) > 1:
306  _data = []
307  _type = self.get_type(conf["type"])
308  for d in split_data:
309  _data.append(_type(d))
310  conf["defaultData"] = str([_data])
311  else:
312  _type = self.get_type(conf["type"])
313  conf["defaultData"] = \
314  str([_type(conf["defaultValue"])])
315  return
316 
317  def check_data_type(self, _type):
318  if str(_type) in ["TimedShortSeq", "TimedLongSeq",
319  "TimedUShortSeq", "TimedULongSeq",
320  "TimedFloatSeq", "TimedDoubleSeq",
321  "TimedCharSeq","TimedBooleanSeq",
322  "TimedOctetSeq", "TimedStringSeq"]:
323  return "sequence"
324  else:
325  return None
326  return None
327 
328  def get_type(self, _type):
329  if str(_type) == "int":
330  return int
331  elif str(_type) == "long":
332  return long
333  elif str(_type) == "float":
334  return float
335  elif str(_type) == "double":
336  return float
337  elif str(_type) == "string":
338  return str
339  else:
340  return str
341 
342  return str
343 
344  def print_impl(self):
345  for sidl in self.data["service_idl"]:
346  if not os.access(sidl["idl_fname"], os.F_OK):
347  sys.stderr.write("Error: IDL file \"" \
348  + sidl["idl_fname"] \
349  + "\" not found.\n")
350  sys.exit(1)
351 
352  try:
353  cmd = "omniidl -bpython -Wbexample " + \
354  sidl["idl_fname"]
355  os.system(cmd)
356  except:
357  sys.stderr.write("Generate error: " \
358  + sidl["impl_py"] + "\n")
359 
360  print " File \"" \
361  + sidl["impl_py"] \
362  + "\" was generated."
363 
364  for cons in self.data["consumer_idl"]:
365  dup = False
366  for svc in self.data["service_idl"]:
367  if cons["idl_fname"] == svc["idl_fname"]:
368  dup = True
369 
370  if not dup:
371  if not os.access(cons["idl_fname"], os.F_OK):
372  sys.stderr.write("Error: IDL file \"" \
373  + cons["idl_fname"] \
374  + "\" not found.\n")
375  sys.exit(1)
376 
377  try:
378  cmd = "omniidl -bpython " + \
379  cons["idl_fname"]
380  os.system(cmd)
381  except:
382  sys.stderr.write("Generate error: omniidl -bpython " + cons["idl_fname"])
383  return
384 
385  def print_pysrc(self):
386  """
387  Generate component class script
388  """
389  self.gen(self.data["fname_py"], py_source, self.data, self.tags)
390  return
391 
392 
393  def print_all(self):
394  self.print_impl()
395  self.print_pysrc()
396  return
def CreateConfiguration(self, dict)
Definition: python_gen.py:300
def usage()
Definition: python_gen.py:28
vstring split(const std::string &input, const std::string &delimiter, bool ignore_empty)
Split string by delimiter.
Definition: stringutil.cpp:346
def gen(self, fname, temp_txt, data, tags)
Definition: gen_base.py:86
def check_data_type(self, _type)
Definition: python_gen.py:317
def __init__(self, data, opts)
Definition: python_gen.py:210
def CreateActivityFuncs(self, dict)
Definition: python_gen.py:237
def CreateService(self, dict)
Definition: python_gen.py:259
def get_opt_fmt()
Definition: python_gen.py:44
def gen_tags(self, tags)
Definition: gen_base.py:79
def get_type(self, _type)
Definition: python_gen.py:328
def CreateDataPorts(self, dict)
Definition: python_gen.py:290
def description()
Definition: python_gen.py:25


openrtm_aist
Author(s): Noriaki Ando
autogenerated on Mon Feb 28 2022 23:00:44