00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 import re
00030 import os
00031 import ezt
00032 import gen_base
00033
00034 import string
00035 import sys
00036
00037 def description():
00038 return "Python component code generator"
00039
00040 def usage():
00041 """
00042 Python generator specific usage
00043 """
00044 return """
00045 ----------------------------------
00046 Help for Python code generator
00047 ----------------------------------
00048 Python code generator generates the following files.
00049 [Component name].py............Component class and executable
00050 README.[Component name]........Specification template of the component
00051
00052 No additional options are available for Python code generator.
00053
00054 """
00055
00056 def get_opt_fmt():
00057 return []
00058
00059
00060 service_impl = """\
00061 [for service_idl]from [service_idl.idl_basename]_idl_example import *
00062 [end]"""
00063
00064 consumer_import = """\
00065 import _GlobalIDL, _GlobalIDL__POA
00066 """
00067
00068 initialize_configuration_param = """\
00069 [for config]self._[config.name] = [config.default_data]
00070 [end]"""
00071
00072 module_spec = """\
00073 [l_name]_spec = ["implementation_id", "[module.name]",
00074 "type_name", "[module.name]",
00075 "description", "[module.desc]",
00076 "version", "[module.version]",
00077 "vendor", "[module.vendor]",
00078 "category", "[module.category]",
00079 "activity_type", "[module.comp_type]",
00080 "max_instance", "[module.max_inst]",
00081 "language", "Python",
00082 "lang_type", "SCRIPT",
00083 [for config] "conf.default.[config.name]", "[config.default]",
00084 [end] ""]"""
00085
00086
00087
00088
00089 py_source = """#!/usr/bin/env python
00090 # -*- Python -*-
00091
00092 import sys
00093 import time
00094 sys.path.append(".")
00095
00096 # Import RTM module
00097 import RTC
00098 import OpenRTM_aist
00099
00100 # Import Service implementation class
00101 # <rtc-template block="service_impl">
00102 # </rtc-template>
00103
00104 # Import Service stub modules
00105 # <rtc-template block="consumer_import">
00106 # </rtc-template>
00107
00108
00109 # This module's spesification
00110 # <rtc-template block="module_spec">
00111 # </rtc-template>
00112
00113 class [module.name](OpenRTM_aist.DataFlowComponentBase):
00114 def __init__(self, manager):
00115 OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
00116
00117 [for inport]self._d_[inport.name] = RTC.[inport.type]([inport.data_type_args])
00118 self._[inport.name]In = OpenRTM_aist.InPort("[inport.name]", self._d_[inport.name])
00119 [end][for outport]self._d_[outport.name] = RTC.[outport.type]([outport.data_type_args])
00120 self._[outport.name]Out = OpenRTM_aist.OutPort("[outport.name]", self._d_[outport.name])
00121 [end]
00122 [for corbaport]self._[corbaport.name]Port = OpenRTM_aist.CorbaPort("[corbaport.name]")
00123 [end]
00124 [for service]self._[service.name] = [service.type]_i()
00125 [end]
00126 [for consumer]self._[consumer.name] = OpenRTM_aist.CorbaConsumer(interfaceType=_GlobalIDL.[consumer.type])
00127 [end]
00128 # initialize of configuration-data.
00129 # <rtc-template block="init_conf_param">
00130 # </rtc-template>
00131
00132
00133
00134 def onInitialize(self):
00135 # Bind variables and configuration variable
00136 [for config]self.bindParameter("[config.name]", self._[config.name], "[config.default]")
00137 [end]
00138
00139 # Set InPort buffers
00140 [for inport]self.addInPort("[inport.name]",self._[inport.name]In)
00141 [end]
00142 # Set OutPort buffers
00143 [for outport]self.addOutPort("[outport.name]",self._[outport.name]Out)
00144 [end]
00145
00146 # Set service provider to Ports
00147 [for service]self._[service.port]Port.registerProvider("[service.name]", "[service.type]", self._[service.name])
00148 [end]
00149 # Set service consumers to Ports
00150 [for consumer]self._[consumer.port]Port.registerConsumer("[consumer.name]", "[consumer.type]", self._[consumer.name])
00151 [end]
00152 # Set CORBA Service Ports
00153 [for corbaport]self.addPort(self._[corbaport.name]Port)
00154 [end]
00155
00156 return RTC.RTC_OK
00157
00158
00159 [for activity]
00160 #def [activity.name](self, ec_id):
00161 #
00162 # return RTC.RTC_OK
00163 [end]
00164
00165
00166 def [module.name]Init(manager):
00167 profile = OpenRTM_aist.Properties(defaults_str=[l_name]_spec)
00168 manager.registerFactory(profile,
00169 [module.name],
00170 OpenRTM_aist.Delete)
00171
00172 def MyModuleInit(manager):
00173 [module.name]Init(manager)
00174
00175 # Create a component
00176 comp = manager.createComponent("[module.name]")
00177
00178
00179
00180 def main():
00181 mgr = OpenRTM_aist.Manager.init(sys.argv)
00182 mgr.setModuleInitProc(MyModuleInit)
00183 mgr.activateManager()
00184 mgr.runManager()
00185
00186 if __name__ == "__main__":
00187 main()
00188
00189 """
00190
00191
00192
00193 class Struct:
00194 def __init__(self):
00195 return
00196
00197
00198 def MakeActivityFuncs(dict):
00199 acts = (("onFinalize", ""), \
00200 ("onStartup", "RTC::UniqueId ec_id"), \
00201 ("onShutdown", "RTC::UniqueId ec_id"), \
00202 ("onActivated", "RTC::UniqueId ec_id"), \
00203 ("onDeactivated", "RTC::UniqueId ec_id"), \
00204 ("onExecute", "RTC::UniqueId ec_id"), \
00205 ("onAborting", "RTC::UniqueId ec_id"), \
00206 ("onError", "RTC::UniqueId ec_id"), \
00207 ("onReset", "RTC::UniqueId ec_id"), \
00208 ("onStateUpdate", "RTC::UniqueId ec_id"), \
00209 ("onRateChanged", "RTC::UniqueId ec_id"))
00210 actlist = []
00211 for name, args in acts:
00212 a = Struct()
00213 a.name = name
00214 a.args = args
00215 actlist.append(a)
00216
00217 dict["activity"] = actlist
00218
00219
00220 def MakeSuffix(opts, dict):
00221 impl_suffix = "SVC_impl"
00222 skel_suffix = "Skel"
00223 stub_suffix = "Stub"
00224 for opt, arg in opts:
00225 if opt.find("--svc-impl-suffix") == 0:
00226 impl_suffix = arg
00227 if opt.find("--svc-skel-suffix") == 0:
00228 skel_suffix = arg
00229 if opt.find("--svc-stub-suffix") == 0:
00230 stub_suffix = arg
00231 dict["impl_suffix"] = impl_suffix
00232 dict["skel_suffix"] = skel_suffix
00233 dict["stub_suffix"] = stub_suffix
00234
00235
00236 class python_gen(gen_base.gen_base):
00237 """
00238 Python component source code generation class
00239 """
00240 def __init__(self, data, opts):
00241 self.data = data.copy()
00242 MakeActivityFuncs(self.data)
00243 MakeSuffix(opts, self.data)
00244 self.data['fname_py'] = self.data['fname'] + ".py"
00245 self.data["begin_brace"] = "["
00246 self.data["end_brace"] = "]"
00247 self.data["u_name"] = self.data["module"].name.upper()
00248 self.data["l_name"] = self.data["module"].name.lower()
00249
00250
00251 self.tags = {}
00252 if self.data["service_idl"]:
00253 for svc in self.data["service_idl"]:
00254 svc.impl_py = svc.idl_basename + "_idl_example.py"
00255 self.tags["service_impl"] = service_impl
00256
00257 if self.data["consumer_idl"]:
00258 for cons in self.data["consumer_idl"]:
00259 try:
00260 cons.modulename = "_GlobalIDL"
00261 f = open(cons.idl_fname,'a+')
00262 while 1:
00263 _str = f.readline()
00264 if not _str:
00265 break
00266 mod_idx = _str.find("module",0)
00267 if mod_idx > -1:
00268 _str = _str[mod_idx+6:]
00269 idx = _str.find("{",0)
00270 if idx > -1:
00271 _str = _str[:idx]
00272 cons.modulename = string.strip(_str)
00273 break
00274 f.close()
00275 except IOError:
00276 print "Can't find file:", file
00277
00278 self.tags["consumer_import"] = consumer_import
00279
00280 if self.data["config"]:
00281 for i in range(len(self.data["config"])):
00282 split_data = self.data["config"][i].default.split(",")
00283 if len(split_data) > 1:
00284 _data = []
00285 _type = self.get_type(self.data["config"][i].type)
00286 for d in split_data:
00287 _data.append(_type(d))
00288 self.data["config"][i].default_data = [_data]
00289 else:
00290 _type = self.get_type(self.data["config"][i].type)
00291 self.data["config"][i].default_data = [_type(self.data["config"][i].default)]
00292
00293 self.tags["init_conf_param"] = initialize_configuration_param
00294
00295 if self.data["inport"]:
00296 for inp in self.data["inport"]:
00297 if self.check_data_type(inp.type) == "sequence":
00298 inp.data_type_args = "RTC.Time(0,0),[]"
00299 else:
00300 inp.data_type_args = "RTC.Time(0,0),0"
00301
00302 if self.data["outport"]:
00303 for outp in self.data["outport"]:
00304 if self.check_data_type(outp.type) == "sequence":
00305 outp.data_type_args = "RTC.Time(0,0),[]"
00306 else:
00307 outp.data_type_args = "RTC.Time(0,0),0"
00308
00309
00310
00311 self.tags["module_spec"] = module_spec
00312 self.gen_tags(self.tags)
00313 return
00314
00315
00316 def check_data_type(self, _type):
00317 if str(_type) in ["TimedShortSeq", "TimedLongSeq", "TimedUShortSeq",
00318 "TimedULongSeq", "TimedFloatSeq", "TimedDoubleSeq",
00319 "TimedCharSeq","TimedBooleanSeq", "TimedOctetSeq",
00320 "TimedStringSeq"]:
00321 return "sequence"
00322 else:
00323 return None
00324
00325
00326 def get_type(self, _type):
00327 if str(_type) == "int":
00328 return int
00329 elif str(_type) == "long":
00330 return long
00331 elif str(_type) == "float":
00332 return float
00333 elif str(_type) == "double":
00334 return float
00335 elif str(_type) == "string":
00336 return str
00337 else:
00338 return str
00339
00340
00341 def print_impl(self):
00342 for svc_idl in self.data["service_idl"]:
00343 if not os.access(svc_idl.idl_fname, os.F_OK):
00344 sys.stderr.write("Error: IDL file \"" \
00345 + svc_idl.idl_fname \
00346 + "\" not found.\n")
00347 sys.exit(1)
00348
00349 try:
00350 cmd = "omniidl -bpython -Wbexample "+svc_idl.idl_fname
00351 os.system(cmd)
00352 except:
00353 sys.stderr.write("Generate error: " \
00354 + svc_idl.impl_py + "\n")
00355
00356
00357 print " File \"" \
00358 + svc_idl.impl_py \
00359 + "\" was generated."
00360
00361 for cons in self.data["consumer_idl"]:
00362 dup = False
00363 for svc in self.data["service_idl"]:
00364 if cons.idl_fname == svc.idl_fname:
00365 dup = True
00366
00367 if not dup:
00368 if not os.access(cons.idl_fname, os.F_OK):
00369 sys.stderr.write("Error: IDL file \"" \
00370 + cons.idl_fname \
00371 + "\" not found.\n")
00372 sys.exit(1)
00373
00374 try:
00375 cmd = "omniidl -bpython "+cons.idl_fname
00376 os.system(cmd)
00377 except:
00378 sys.stderr.write("Generate error: omniidl -bpython "+cons.idl_fname)
00379
00380
00381 def print_pysrc(self):
00382 """
00383 Generate component class script
00384 """
00385 self.gen(self.data["fname_py"],py_source,self.data, self.tags)
00386 return
00387
00388
00389 def print_all(self):
00390 self.print_impl()
00391 self.print_pysrc()
00392 return