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


openrtm_aist
Author(s): Noriaki Ando
autogenerated on Sat Jun 8 2019 18:49:06