python_gen.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
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-2005
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: python_gen.py,v 1.1 2005/08/26 12:02:37 n-ando Exp $
17 #
18 
19 #
20 # $Log: python_gen.py,v $
21 # Revision 1.1 2005/08/26 12:02:37 n-ando
22 # This code generator module uses ezt (Easy Template).
23 #
24 # Revision 1.1.1.1 2005/05/12 09:06:18 n-ando
25 # Public release.
26 #
27 #
28 
29 import re
30 import os
31 import ezt
32 import gen_base
33 
34 import string
35 import sys
36 
38  return "Python component code generator"
39 
40 def usage():
41  """
42  Python generator specific usage
43  """
44  return """
45 ----------------------------------
46  Help for Python code generator
47 ----------------------------------
48 Python code generator generates the following files.
49  [Component name].py............Component class and executable
50  README.[Component name]........Specification template of the component
51 
52 No additional options are available for Python code generator.
53 
54 """
55 
57  return []
58 
59 
60 service_impl = """\
61 [for service_idl]from [service_idl.idl_basename]_idl_example import *
62 [end]"""
63 
64 consumer_import = """\
65 import _GlobalIDL, _GlobalIDL__POA
66 """
67 
68 initialize_configuration_param = """\
69  [for config]self._[config.name] = [config.default_data]
70  [end]"""
71 
72 module_spec = """\
73 [l_name]_spec = ["implementation_id", "[module.name]",
74  "type_name", "[module.name]",
75  "description", "[module.desc]",
76  "version", "[module.version]",
77  "vendor", "[module.vendor]",
78  "category", "[module.category]",
79  "activity_type", "[module.comp_type]",
80  "max_instance", "[module.max_inst]",
81  "language", "Python",
82  "lang_type", "SCRIPT",
83 [for config] "conf.default.[config.name]", "[config.default]",
84 [end] ""]"""
85 
86 #------------------------------------------------------------
87 # Python component source code template
88 #------------------------------------------------------------
89 py_source = """#!/usr/bin/env python
90 # -*- Python -*-
91 
92 import sys
93 import time
94 sys.path.append(".")
95 
96 # Import RTM module
97 import RTC
98 import OpenRTM_aist
99 
100 # Import Service implementation class
101 # <rtc-template block="service_impl">
102 # </rtc-template>
103 
104 # Import Service stub modules
105 # <rtc-template block="consumer_import">
106 # </rtc-template>
107 
108 
109 # This module's spesification
110 # <rtc-template block="module_spec">
111 # </rtc-template>
112 
113 class [module.name](OpenRTM_aist.DataFlowComponentBase):
114  def __init__(self, manager):
115  OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
116 
117  [for inport]self._d_[inport.name] = RTC.[inport.type]([inport.data_type_args])
118  self._[inport.name]In = OpenRTM_aist.InPort("[inport.name]", self._d_[inport.name])
119  [end][for outport]self._d_[outport.name] = RTC.[outport.type]([outport.data_type_args])
120  self._[outport.name]Out = OpenRTM_aist.OutPort("[outport.name]", self._d_[outport.name])
121  [end]
122  [for corbaport]self._[corbaport.name]Port = OpenRTM_aist.CorbaPort("[corbaport.name]")
123  [end]
124  [for service]self._[service.name] = [service.type]_i()
125  [end]
126  [for consumer]self._[consumer.name] = OpenRTM_aist.CorbaConsumer(interfaceType=_GlobalIDL.[consumer.type])
127  [end]
128  # initialize of configuration-data.
129  # <rtc-template block="init_conf_param">
130  # </rtc-template>
131 
132 
133 
134  def onInitialize(self):
135  # Bind variables and configuration variable
136  [for config]self.bindParameter("[config.name]", self._[config.name], "[config.default]")
137  [end]
138 
139  # Set InPort buffers
140  [for inport]self.addInPort("[inport.name]",self._[inport.name]In)
141  [end]
142  # Set OutPort buffers
143  [for outport]self.addOutPort("[outport.name]",self._[outport.name]Out)
144  [end]
145 
146  # Set service provider to Ports
147  [for service]self._[service.port]Port.registerProvider("[service.name]", "[service.type]", self._[service.name])
148  [end]
149  # Set service consumers to Ports
150  [for consumer]self._[consumer.port]Port.registerConsumer("[consumer.name]", "[consumer.type]", self._[consumer.name])
151  [end]
152  # Set CORBA Service Ports
153  [for corbaport]self.addPort(self._[corbaport.name]Port)
154  [end]
155 
156  return RTC.RTC_OK
157 
158 
159  [for activity]
160  #def [activity.name](self, ec_id):
161  #
162  # return RTC.RTC_OK
163  [end]
164 
165 
166 def [module.name]Init(manager):
167  profile = OpenRTM_aist.Properties(defaults_str=[l_name]_spec)
168  manager.registerFactory(profile,
169  [module.name],
170  OpenRTM_aist.Delete)
171 
172 def MyModuleInit(manager):
173  [module.name]Init(manager)
174 
175  # Create a component
176  comp = manager.createComponent("[module.name]")
177 
178 
179 
180 def main():
181  mgr = OpenRTM_aist.Manager.init(sys.argv)
182  mgr.setModuleInitProc(MyModuleInit)
183  mgr.activateManager()
184  mgr.runManager()
185 
186 if __name__ == "__main__":
187  main()
188 
189 """
190 
191 
192 
193 class Struct:
194  def __init__(self):
195  return
196 
197 
199  acts = (("onFinalize", ""), \
200  ("onStartup", "RTC::UniqueId ec_id"), \
201  ("onShutdown", "RTC::UniqueId ec_id"), \
202  ("onActivated", "RTC::UniqueId ec_id"), \
203  ("onDeactivated", "RTC::UniqueId ec_id"), \
204  ("onExecute", "RTC::UniqueId ec_id"), \
205  ("onAborting", "RTC::UniqueId ec_id"), \
206  ("onError", "RTC::UniqueId ec_id"), \
207  ("onReset", "RTC::UniqueId ec_id"), \
208  ("onStateUpdate", "RTC::UniqueId ec_id"), \
209  ("onRateChanged", "RTC::UniqueId ec_id"))
210  actlist = []
211  for name, args in acts:
212  a = Struct()
213  a.name = name
214  a.args = args
215  actlist.append(a)
216 
217  dict["activity"] = actlist
218 
219 
220 def MakeSuffix(opts, dict):
221  impl_suffix = "SVC_impl"
222  skel_suffix = "Skel"
223  stub_suffix = "Stub"
224  for opt, arg in opts:
225  if opt.find("--svc-impl-suffix") == 0:
226  impl_suffix = arg
227  if opt.find("--svc-skel-suffix") == 0:
228  skel_suffix = arg
229  if opt.find("--svc-stub-suffix") == 0:
230  stub_suffix = arg
231  dict["impl_suffix"] = impl_suffix
232  dict["skel_suffix"] = skel_suffix
233  dict["stub_suffix"] = stub_suffix
234 
235 
237  """
238  Python component source code generation class
239  """
240  def __init__(self, data, opts):
241  self.data = data.copy()
242  MakeActivityFuncs(self.data)
243  MakeSuffix(opts, self.data)
244  self.data['fname_py'] = self.data['fname'] + ".py"
245  self.data["begin_brace"] = "["
246  self.data["end_brace"] = "]"
247  self.data["u_name"] = self.data["module"].name.upper()
248  self.data["l_name"] = self.data["module"].name.lower()
249 
250 
251  self.tags = {}
252  if self.data["service_idl"]:
253  for svc in self.data["service_idl"]:
254  svc.impl_py = svc.idl_basename + "_idl_example.py"
255  self.tags["service_impl"] = service_impl
256 
257  if self.data["consumer_idl"]:
258  for cons in self.data["consumer_idl"]:
259  try:
260  cons.modulename = "_GlobalIDL"
261  f = open(cons.idl_fname,'a+')
262  while 1:
263  _str = f.readline()
264  if not _str:
265  break
266  mod_idx = _str.find("module",0)
267  if mod_idx > -1:
268  _str = _str[mod_idx+6:]
269  idx = _str.find("{",0)
270  if idx > -1:
271  _str = _str[:idx]
272  cons.modulename = string.strip(_str)
273  break
274  f.close()
275  except IOError:
276  print "Can't find file:", file
277 
278  self.tags["consumer_import"] = consumer_import
279 
280  if self.data["config"]:
281  for i in range(len(self.data["config"])):
282  split_data = self.data["config"][i].default.split(",")
283  if len(split_data) > 1:
284  _data = []
285  _type = self.get_type(self.data["config"][i].type)
286  for d in split_data:
287  _data.append(_type(d))
288  self.data["config"][i].default_data = [_data]
289  else:
290  _type = self.get_type(self.data["config"][i].type)
291  self.data["config"][i].default_data = [_type(self.data["config"][i].default)]
292 
293  self.tags["init_conf_param"] = initialize_configuration_param
294 
295  if self.data["inport"]:
296  for inp in self.data["inport"]:
297  if self.check_data_type(inp.type) == "sequence":
298  inp.data_type_args = "RTC.Time(0,0),[]"
299  else:
300  inp.data_type_args = "RTC.Time(0,0),0"
301 
302  if self.data["outport"]:
303  for outp in self.data["outport"]:
304  if self.check_data_type(outp.type) == "sequence":
305  outp.data_type_args = "RTC.Time(0,0),[]"
306  else:
307  outp.data_type_args = "RTC.Time(0,0),0"
308 
309 
310 
311  self.tags["module_spec"] = module_spec
312  self.gen_tags(self.tags)
313  return
314 
315 
316  def check_data_type(self, _type):
317  if str(_type) in ["TimedShortSeq", "TimedLongSeq", "TimedUShortSeq",
318  "TimedULongSeq", "TimedFloatSeq", "TimedDoubleSeq",
319  "TimedCharSeq","TimedBooleanSeq", "TimedOctetSeq",
320  "TimedStringSeq"]:
321  return "sequence"
322  else:
323  return None
324 
325 
326  def get_type(self, _type):
327  if str(_type) == "int":
328  return int
329  elif str(_type) == "long":
330  return long
331  elif str(_type) == "float":
332  return float
333  elif str(_type) == "double":
334  return float
335  elif str(_type) == "string":
336  return str
337  else:
338  return str
339 
340 
341  def print_impl(self):
342  for svc_idl in self.data["service_idl"]:
343  if not os.access(svc_idl.idl_fname, os.F_OK):
344  sys.stderr.write("Error: IDL file \"" \
345  + svc_idl.idl_fname \
346  + "\" not found.\n")
347  sys.exit(1)
348 
349  try:
350  cmd = "omniidl -bpython -Wbexample "+svc_idl.idl_fname
351  os.system(cmd)
352  except:
353  sys.stderr.write("Generate error: " \
354  + svc_idl.impl_py + "\n")
355 
356 
357  print " File \"" \
358  + svc_idl.impl_py \
359  + "\" was generated."
360 
361  for cons in self.data["consumer_idl"]:
362  dup = False
363  for svc in self.data["service_idl"]:
364  if cons.idl_fname == svc.idl_fname:
365  dup = True
366 
367  if not dup:
368  if not os.access(cons.idl_fname, os.F_OK):
369  sys.stderr.write("Error: IDL file \"" \
370  + cons.idl_fname \
371  + "\" not found.\n")
372  sys.exit(1)
373 
374  try:
375  cmd = "omniidl -bpython "+cons.idl_fname
376  os.system(cmd)
377  except:
378  sys.stderr.write("Generate error: omniidl -bpython "+cons.idl_fname)
379 
380 
381  def print_pysrc(self):
382  """
383  Generate component class script
384  """
385  self.gen(self.data["fname_py"],py_source,self.data, self.tags)
386  return
387 
388 
389  def print_all(self):
390  self.print_impl()
391  self.print_pysrc()
392  return
def gen(self, fname, temp_txt, data, tags)
Definition: gen_base.py:105


openrtm_aist_python
Author(s): Shinji Kurihara
autogenerated on Thu Jun 6 2019 19:11:34