rtc_handle10_11.py
Go to the documentation of this file.
00001 #/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 # -*- Python -*-
00004 
00005 import sys
00006 from omniORB import CORBA, URI
00007 # from omniORB import any
00008 from omniORB import any, cdrMarshal, cdrUnmarshal
00009 
00010 import OpenRTM_aist
00011 import RTC
00012 
00013 
00014 from CorbaNaming import *
00015 import SDOPackage
00016 # from EmbryonicRtc import *
00017 
00018 # class RtmEnv :
00019 #       rtm environment manager
00020 #       orb, naming service, rtc proxy list
00021 #
00022 class RtmEnv : 
00023 
00024     def __init__(self, orb_args, nserver_names=["localhost"], 
00025                                      orb=None, naming=None):
00026         if not orb :
00027             orb = CORBA.ORB_init(orb_args)
00028         self.orb = orb
00029         self.name_space = {}
00030         if naming : # naming can specify only one naming service
00031             self.name_space['default']=NameSpace(orb, naming=naming)
00032         else :
00033             for ns in nserver_names :
00034               self.name_space[ns]=NameSpace(orb, server_name=ns)
00035 
00036     def __del__(self):
00037         self.orb.shutdown(wait_for_completion=CORBA.FALSE)
00038         self.orb.destroy()
00039 #
00040 # class NameSpace :
00041 #       rtc_handles and object list in naming service
00042 #
00043 class NameSpace :
00044     def __init__(self, orb, server_name=None, naming=None):
00045         self.orb = orb
00046         self.name = server_name
00047         if naming :
00048           self.naming = naming
00049         else :
00050           self.naming = CorbaNaming(self.orb, server_name) 
00051 
00052         self.b_len = 10 # iteration cut off no.
00053         self.rtc_handles = {}
00054         self.obj_list = {}
00055 
00056     def get_object_by_name(self, name, cl=RTC.RTObject):
00057         ref = self.naming.resolveStr(name)
00058         if ref is None: return None     # return CORBA.nil ?
00059         if cl :
00060             return ref._narrow(cl)
00061         else :
00062             return ref
00063 
00064     def list_obj(self) :
00065         self.rtc_handes = {}
00066         self.obj_list = {}
00067         return self.list_obj1(self.naming._rootContext, "")
00068 
00069     def list_obj1(self, name_context, parent) :
00070         if not name_context :
00071             name_context = self.naming._rootContext 
00072         rslt = []
00073         b_list = name_context.list(self.b_len)
00074         for bd in b_list[0] :
00075             rslt = rslt + self.proc_bd(bd, name_context, parent)
00076         if b_list[1] :  # iterator : there exists remaining.
00077             t_list = b_list[1].next_n(self.b_len)
00078             while t_list[0] :
00079                 for bd in t_list[1] :
00080                     rslt = rslt + self.proc_bd(bd, name_context, parent)
00081                 t_list = b_list[1].next_n(self.b_len)
00082         return rslt
00083 
00084     def proc_bd(self, bd, name_context, parent) :
00085 #        print '-------------------------------------------------------------------'
00086 #        print 'bd= ', bd
00087 #        print 'name_context= ', name_context
00088 #        print 'parent= ', parent
00089         rslt = []
00090         pre = ""
00091         if parent :
00092             pre = parent + "/"
00093         nam = pre + URI.nameToString(bd.binding_name)
00094         if bd.binding_type == CosNaming.nobject :
00095             tmp = name_context.resolve(bd.binding_name)
00096             self.obj_list[nam]=tmp
00097             print 'objcet '+nam+' was listed.'
00098             try :
00099                 tmp = tmp._narrow(RTC.RTObject)
00100             except :
00101                 print nam+' is not RTC.'
00102                 tmp = None
00103             try :
00104                 if tmp :
00105                    rslt = [[nam, tmp]]
00106                    self.rtc_handles[nam]=RtcHandle(nam,self,tmp)
00107                    print 'handle for '+nam+' was created.'
00108                 else :
00109                    pass
00110             except :
00111                 print nam+' is not alive.' , sys.exc_info()[0]
00112                 pass
00113         else :
00114             tmp = name_context.resolve(bd.binding_name)
00115             tmp = tmp._narrow(CosNaming.NamingContext)
00116             rslt = self.list_obj1(tmp, nam)
00117         return rslt
00118 
00119 #
00120 # data conversion
00121 #
00122 def nvlist2dict(nvlist) :
00123     rslt = {}
00124     for tmp in nvlist :
00125         rslt[tmp.name]=tmp.value.value()   # nv.value and any.value()
00126     return rslt
00127 def dict2nvlist(dict) :
00128     rslt = []
00129     for tmp in dict.keys() :
00130         rslt.append(SDOPackage.NameValue(tmp, any.to_any(dict[tmp])))
00131     return rslt
00132 #
00133 #  connector, port, inport, outport, service
00134 #                
00135 
00136 class Connector :
00137     def __init__(self, plist, name = None, id="", prop_dict={}) :
00138        self.connectp=False
00139        self.plist = plist
00140        self.port_reflist = [tmp.port_profile.port_ref for tmp in plist]
00141        if name :
00142            self.name = name
00143        else :
00144            self.name = string.join([tmp.name for tmp in plist],'_')
00145        self.prop_dict_req = prop_dict
00146        self.prop_nvlist_req = dict2nvlist(self.prop_dict_req)
00147        self.profile_req = RTC.ConnectorProfile(self.name, id, self.port_reflist, 
00148                           self.prop_nvlist_req)
00149        self.nego_prop()
00150 
00151     def nego_prop(self) :
00152        self.possible = True
00153        for kk in self.def_prop :
00154            if kk in self.prop_dict_req :
00155                if not self.prop_dict_req[kk] :
00156                    self.prop_dict_req[kk]=self.def_prop[kk]
00157            else :
00158                 self.prop_dict_req[kk]=self.def_prop[kk]
00159            for pp in self.plist :  
00160                if not ((self.prop_dict_req[kk] in pp.prop[kk]) or 
00161                                  ('Any' in    pp.prop[kk])) :
00162                    print kk, self.prop_dict_req[kk]
00163                    self.prop_dict_req[kk] = ""
00164                    self.possible = False
00165        self.prop_nvlist_req = dict2nvlist(self.prop_dict_req)
00166        self.profile_req.properties = self.prop_nvlist_req
00167        return self.possible
00168 
00169     def connect(self) :
00170 #
00171 #   out and inout parameters are retuned as a tuple   
00172 #
00173        if self.connectp == False :
00174           ret, self.profile = self.port_reflist[0].connect(self.profile_req)
00175           self.prop_nvlist = self.profile.properties
00176           self.prop_dict = nvlist2dict(self.prop_nvlist)
00177           if ret == RTC.RTC_OK :
00178               self.connectp=True
00179        else :
00180           ret = "?"
00181        return ret
00182 
00183     def disconnect(self) :
00184        if self.connectp == True :
00185            ret = self.port_reflist[0].disconnect(self.profile.connector_id)
00186        else :
00187            ret = "?"
00188        self.connectp = False
00189        return ret
00190 
00191 class IOConnector(Connector) :
00192     def __init__(self, plist, name = None, id="", prop_dict={}) :
00193 #      self.def_prop = {'dataport.dataflow_type':'Push' ,
00194 #                       'dataport.interface_type':'CORBA_Any' ,
00195 #                       'dataport.subscription_type':'Flush'}
00196        self.def_prop = {'dataport.dataflow_type':'push',
00197                         'dataport.interface_type':'corba_cdr' ,
00198                         'dataport.subscription_type':'flush'}
00199        Connector.__init__(self, plist, name, id, prop_dict)
00200 
00201 class ServiceConnector(Connector) :
00202     def __init__(self, plist, name = None, id="", prop_dict={}) :
00203        self.def_prop = {'port.port_type':'CorbaPort' }
00204        Connector.__init__(self, plist, name, id, prop_dict)
00205 
00206 
00207 class Port :
00208     def __init__(self, profile,nv_dict=None,handle=None) :
00209         self.handle=handle
00210         self.name=profile.name    
00211         self.port_profile = profile
00212         if not nv_dict :
00213             nv_dict = nvlist2dict(profile.properties)
00214         self.prop = nv_dict
00215         self.con = None           # this must be set in each subclasses
00216     def get_info(self) :
00217         self.con.connect()
00218         tmp1 = self.get_connections()
00219         tmp2 = [pp.connector_id for pp in tmp1]
00220         if self.con.profile.connector_id in tmp2 :
00221             print "connecting"
00222             self.con.disconnect()
00223 
00224     def get_connections(self) :
00225         return self.port_profile.port_ref.get_connector_profiles()
00226 
00227 class CorbaServer :
00228     def __init__(self, profile, port) :
00229         self.profile = profile
00230         self.port = port
00231         self.name = profile.instance_name
00232         self.type = profile.type_name
00233         self.ref = None
00234         ref_key = 'port.' + self.type + '.' + self.name
00235         self.ref=self.port.con.prop_dict[ref_key]
00236         if isinstance(self.ref,str) :
00237             self.ref=port.handle.env.orb.string_to_object(self.ref)
00238 #
00239 # if we import stubs before we create instances,
00240 # we rarely need to narrow the object references.
00241 # we need to specify global symbol table to evaluate class symbols.
00242 #
00243     def narrow_ref(self, gls) :
00244         if self.type.find('::') == -1 :
00245             self.narrow_sym = eval('_GlobalIDL.' + self.type, gls)
00246         else :
00247             self.narrow_sym = eval(self.type.replace('::','.'), gls)
00248         self.ref = self.ref._narrow(self.narrow_sym)
00249 
00250 class CorbaClient :
00251     def __init__(self, profile) :
00252         self.profile = profile
00253         self.name = profile.instance_name
00254         self.type = profile.type_name
00255 #
00256 # to connect to an outside corba client,
00257 # we need an implementation of the corresponding corba server.
00258 # but ....
00259 #
00260 
00261 class RtcService(Port) :
00262     def __init__(self, profile,nv_dict=None, handle=None) :
00263         Port.__init__(self, profile, nv_dict, handle)
00264         self.con = ServiceConnector([self])
00265         self.get_info()
00266         self.provided={}
00267         self.required={}
00268         tmp = self.port_profile.interfaces
00269         for itf in tmp :
00270             if itf.polarity == RTC.PROVIDED :
00271                 self.provided[itf.instance_name] = CorbaServer(itf,self)
00272             elif itf.polarity == RTC.REQUIRED :
00273                 self.required[itf.instance_name] = CorbaClient(itf)
00274 
00275 #    def open(self) :
00276 #        self.con.connect()
00277 #        self.provided={}
00278 #        self.required={}
00279 #        tmp = self.port_profile.interfaces
00280 #        for itf in tmp :
00281 #            if itf.polarity == RTC.PROVIDED :
00282 #                self.provided[itf.instance_name] = CorbaServer(itf,self)
00283 #            elif itf.polarity == RTC.REQUIRED :
00284 #                self.required[itf.instance_name] = CorbaClient(itf)
00285 
00286 #    def close(self) :
00287 #        return self.con.disconnect()
00288 def strip_data_class(data_class_str) :
00289     tmp = data_class_str.split(':')
00290     if len(tmp) == 1 :
00291         return data_class_str
00292     else :
00293         tmp = tmp[1].split('/')
00294         return tmp[1]
00295 
00296 class RtcInport(Port) :
00297     def __init__(self, profile, nv_dict=None, handle=None) :
00298         Port.__init__(self, profile, nv_dict, handle)
00299         self.con = IOConnector([self], prop_dict={'dataport.dataflow_type':'push'})
00300         self.get_info() 
00301 #       self.ref = self.con.prop_dict['dataport.corba_any.inport_ref']
00302         self.ref = self.con.prop_dict['dataport.corba_cdr.inport_ref']
00303 #        self.data_class = eval('RTC.' + self.prop['dataport.data_type'])
00304 #        self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type'])
00305         tmp=strip_data_class(self.prop['dataport.data_type'])
00306         print tmp
00307         self.data_class = eval('RTC.' + tmp)
00308         self.data_tc = eval('RTC._tc_' + tmp)
00309     def write(self,data) :
00310 #        self.ref.put(CORBA.Any(self.data_tc,
00311 #                         self.data_class(RTC.Time(0,0),data)))
00312         self.ref.put(cdrMarshal(self.data_tc,
00313                                 self.data_class(RTC.Time(0,0),data), 1))
00314     def open(self) :
00315         self.con.connect()
00316         self.ref = self.con.prop_dict['dataport.corba_cdr.inport_ref']
00317 
00318     def close(self) :
00319         return self.con.disconnect()
00320 
00321 class RtcOutport(Port) :
00322     def __init__(self, profile,nv_dict=None, handle=None) :
00323         Port.__init__(self, profile, nv_dict, handle)
00324         con_prop_dict={'dataport.dataflow_type':'pull',
00325                        'dataport.buffer.type':'ringbuffer',
00326                        'dataport.buffer.read.empty_policy':'last',
00327                        'dataport.buffer.length':'1'}
00328         self.con = IOConnector([self], prop_dict=con_prop_dict)
00329         self.get_info()
00330 #        if 'dataport.corba_any.outport_ref' in self.con.prop_dict :
00331 #          self.ref = self.con.prop_dict['dataport.corba_any.outport_ref']
00332         if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict :
00333            self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref']
00334         else :
00335            self.ref=None
00336 #        self.data_class = eval('RTC.' + self.prop['dataport.data_type'])
00337 #        self.data_tc = eval('RTC._tc_' + self.prop['dataport.data_type'])
00338         tmp=strip_data_class(self.prop['dataport.data_type'])
00339         self.data_class = eval('RTC.' + tmp)
00340         self.data_tc = eval('RTC._tc_' + tmp)
00341 
00342     def read(self) :
00343         if self.ref :
00344            try :
00345                 tmp1=self.ref.get()
00346                 tmp2= cdrUnmarshal(self.data_tc,tmp1[1], 1)
00347 #           return tmp2.data
00348                 return tmp2
00349            except :
00350                 return None
00351         else :
00352            print "not supported"
00353            return None
00354 
00355     def open(self) :
00356         self.con.connect()
00357         if 'dataport.corba_cdr.outport_ref' in self.con.prop_dict :
00358            self.ref = self.con.prop_dict['dataport.corba_cdr.outport_ref']
00359 
00360     def close(self) :
00361         return self.con.disconnect()
00362 
00363 #
00364 # RtcHandle
00365 #
00366 class RtcHandle :
00367   def __init__(self, name, env, ref=None) :
00368     self.name = name
00369     self.env = env
00370     if ref :
00371         self.rtc_ref = ref
00372     else :
00373         self.rtc_ref = env.naming.resolve(name)._narrow(RTC.RTObject)
00374     self.conf_ref = None
00375     self.retrieve_info()
00376 
00377   def retrieve_info(self) :
00378     self.conf_set={}
00379     self.conf_set_data={}
00380     self.port_refs = []
00381     self.execution_contexts =[]
00382     if self.rtc_ref :
00383         self.conf_ref = self.rtc_ref.get_configuration()
00384         conf_set = self.conf_ref.get_configuration_sets()
00385         for cc in conf_set :
00386             self.conf_set[cc.id]=cc
00387             self.conf_set_data[cc.id]=nvlist2dict(cc.configuration_data)
00388         self.profile = self.rtc_ref.get_component_profile()
00389         self.prop = nvlist2dict(self.profile.properties)
00390         #self.execution_contexts = self.rtc_ref.get_contexts()
00391         self.execution_contexts = self.rtc_ref.get_owned_contexts()
00392         self.port_refs = self.rtc_ref.get_ports()  
00393     # this includes inports, outports and service ports
00394     self.ports = {}
00395     self.services = {}
00396     self.inports = {}
00397     self.outports = {}
00398     for pp in self.port_refs :
00399         tmp = pp.get_port_profile()
00400         tmp_prop = nvlist2dict(tmp.properties)
00401         tmp_name = tmp.name.lstrip(self.name.split('.')[0]).lstrip('.')
00402         print 'port_name:', tmp_name
00403 #       self.ports[tmp.name]=Port(tmp, tmp_prop)
00404         if tmp_prop['port.port_type']=='DataInPort' :
00405             self.inports[tmp_name]=RtcInport(tmp,tmp_prop, self)
00406 #            self.inports[tmp.name]=Port(tmp, tmp_prop)
00407         elif tmp_prop['port.port_type']=='DataOutPort' :
00408             self.outports[tmp_name]=RtcOutport(tmp, tmp_prop, self)
00409 #            self.outports[tmp.name]=Port(tmp, tmp_prop)
00410         elif tmp_prop['port.port_type']=='CorbaPort' :
00411             self.services[tmp_name]=RtcService(tmp, tmp_prop, self)
00412 #            self.services[tmp.name]=Port(tmp, tmp_prop)
00413 
00414   def set_conf(self,conf_set_name,param_name,value) :
00415       conf_set=self.conf_set[conf_set_name]
00416       conf_set_data=self.conf_set_data[conf_set_name]
00417       conf_set_data[param_name]=value
00418       conf_set.configuration_data=dict2nvlist(conf_set_data)
00419 #      self.conf_ref.set_configuration_set_values(conf_set_name,conf_set)
00420       self.conf_ref.set_configuration_set_values(conf_set)
00421   def set_conf_activate(self,conf_set_name,param_name,value) :
00422       self.set_conf(conf_set_name,param_name,value)
00423       self.conf_ref.activate_configuration_set(conf_set_name)
00424   def activate(self):
00425       return self.execution_contexts[0].activate_component(self.rtc_ref)
00426   def deactivate(self):
00427       return self.execution_contexts[0].deactivate_component(self.rtc_ref)
00428   def reset(self):
00429       return self.execution_contexts[0].reset_component(self.rtc_ref)
00430   def get_state(self):
00431       return self.execution_contexts[0].get_component_state(self.rtc_ref)
00432 
00433 #
00434 # pipe
00435 #  a pipe is an port (interface & implementation)
00436 #  for a port(an RtcInport or RtcOutport object) of an outside rtc.
00437 #  you need an empty rtc (comp) to create pipes.
00438 #  you can subscribe and communicate to the outside port with the pipe.
00439 #  
00440 #
00441 class InPipe() :
00442   def __init__(self,comp, port) :
00443     self.comp=comp
00444     self.port=port
00445     self.pname=port.name.replace('.','_')
00446     self.pipe=comp.makeOutPort(self.pname,port.data_class(RTC.Time(0,0),[]),OpenRTM_aist.RingBuffer(1))
00447     self.buf=getattr(comp,'_d_'+self.pname)
00448     tmp = self.pipe.getPortProfile()
00449     self.pipe_port = RtcOutport(tmp, nvlist2dict(tmp.properties))
00450     self.con = IOConnector([self.pipe_port,self.port])
00451   def connect(self):
00452     return self.con.connect()
00453   def disconnect(self):
00454     return self.con.disconnect()
00455   def write(self, data) :
00456     self.buf.data=data
00457     self.pipe.write()
00458 class OutPipe() :
00459   def __init__(self,comp, port) :
00460     self.comp=comp
00461     self.port=port
00462     self.pname=port.name.replace('.','_')
00463     self.pipe=comp.makeInPort(self.pname,port.data_class(RTC.Time(0,0),[]),OpenRTM_aist.RingBuffer(1))
00464     self.buf=getattr(comp,'_d_'+self.pname)
00465     tmp = self.pipe.getPortProfile()
00466     self.pipe_port = RtcInport(tmp, nvlist2dict(tmp.properties))
00467     self.con = IOConnector([self.pipe_port,self.port])
00468   def connect(self):
00469     return self.con.connect()
00470   def disconnect(self):
00471     return self.con.disconnect()
00472   def read(self) :
00473     return self.pipe.read().data
00474 #
00475 #
00476 #
00477 def make_pipe(comp, handle) :
00478   handle.in_pipe={}
00479   for i_port in handle.inports :
00480     handle.in_pipe[i_port]=InPipe(comp, handle.inports[i_port])
00481   handle.out_pipe={}
00482   for o_port in handle.outports :
00483     handle.out_pipe[o_port]=OutPipe(comp, handle.outports[o_port])


openrtm_aist_python
Author(s): Shinji Kurihara
autogenerated on Thu Aug 27 2015 14:17:28