def test_sequenceOperators (self):
        self.assertNotEqual(self._domMgr, None, "DomainManager not available")
        self.assertNotEqual(self._devMgr, None, "DeviceManager not available")

        self._app = self._launchApp('TestPythonProps')
        self.assertNotEqual(self._app, None, "Application not created")

        # Get the value for the structsequence property. The TestPyProps component
        # is also the assembly controller, so we can query it via the application.
        id = "DCE:897a5489-f680-46a8-a698-e36fd8bbae80"
        prop = self._app.query([CF.DataType(id + '[]', any.to_any(None))])[0]
        value = any.from_any(prop.value)

        # Test the length operator.
        length = self._app.query([CF.DataType(id + '[#]', any.to_any(None))])[0]
        length = any.from_any(length.value)
        self.assertEqual(len(value), length)

        # Test key list.
        keys = self._app.query([CF.DataType(id + '[?]', any.to_any(None))])[0]
        keys = any.from_any(keys.value)
        self.assertEqual(keys, range(length))

        # Test key-value pairs.
        kvpairs = self._app.query([CF.DataType(id + '[@]', any.to_any(None))])[0]
        kvpairs = any.from_any(kvpairs.value)
        for pair in kvpairs:
            index = int(pair['id'])
            self.assertEqual(value[index], pair['value'])

        # Test indexing.
        v1 = self._app.query([CF.DataType(id + '[1]', any.to_any(None))])[0]
        v1 = any.from_any(v1.value)
        self.assertEqual(len(v1), 1)
        self.assertEqual(v1[0], value[1])
示例#2
0
  def findProvider(self, nv, cons, iorstr):
    # new consumer interface descriptor
    newdesc = self._profile.name[:len(self._ownerInstanceName)] + \
        ".port" +  self._profile.name[len(self._ownerInstanceName):]
    newdesc += ".required." + cons.descriptor()

    # find a NameValue of the consumer
    cons_index = OpenRTM_aist.NVUtil.find_index(nv, newdesc)
    if cons_index < 0:
      return False

    provider = str(any.from_any(nv[cons_index].value, keep_structs=True))
    if not provider:
      self._rtcout.RTC_WARN("Cannot extract Provider interface descriptor")
      return False

    # find a NameValue of the provider
    prov_index = OpenRTM_aist.NVUtil.find_index(nv, provider)
    if prov_index < 0:
      return False

    ior_ = str(any.from_any(nv[prov_index].value, keep_structs=True))
    if not ior_:
      self._rtcout.RTC_WARN("Cannot extract Provider IOR string")
      return False
 
    if isinstance(iorstr, list):
      iorstr.append(ior_)

    self._rtcout.RTC_ERROR("interface matched with new descriptor: %s", newdesc)

    return True
示例#3
0
def props_to_dict(pl):
    """Creates a dictionary from a Properties list"""
    result = {}
    for p in pl:
        # struct property
        if p.value.typecode().equivalent(CF._tc_Properties):
            result[p.id] = dict([(x.id, any.from_any(x.value)) for x in p.value.value()])
        # structsequence property
        elif p.value.typecode().equivalent(CORBA._tc_AnySeq):
            result[p.id] = [dict([(x.id, any.from_any(x.value)) for x in y.value()]) for y in p.value.value()]
        # simplesequence property
        elif p.value.typecode().kind() == CORBA.tk_sequence:
            # char and octet are special cases in Python, they should not be returned
            # as explicit lists because that is not how they are configured
            if (
                p.value.typecode().content_type() == CORBA.TC_octet
                or p.value.typecode().content_type() == CORBA.TC_char
            ):
                result[p.id] = any.from_any(p.value)
            else:
                result[p.id] = [x for x in any.from_any(p.value)]
        # simple property
        else:
            result[p.id] = any.from_any(p.value)

    return result
  def test_init(self):
    self.assertEqual(self._inport.getThebuffer(),None)
    profile = self._inport.getPortProfile()
    prop    = OpenRTM_aist.NVUtil.toProperties(profile.properties)

    self.assertEqual(prop.getProperty("dataport.dataflow_type"),"")
    self.assertEqual(prop.getProperty("dataport.interface_type"),"")
    
    pstr = self._inport.getProviderTypes()
    self.assertEqual(len(pstr),0)
    cstr = self._inport.getConsumerTypes()
    self.assertEqual(len(cstr),0)

    self._inport.init(prop)
    
    # self._singlebufferがTrueの場合self._thebufferが取得される
    self.assertNotEqual(self._inport.getThebuffer(),None)
    profile = self._inport.getPortProfile()
    prop    = OpenRTM_aist.NVUtil.toProperties(profile.properties)

    # getPortProfileのpropertiesに以下が追加される
    val = any.from_any(prop.getProperty("dataport.dataflow_type"),keep_structs=True)
    self.assertEqual(val,"push, pull")
    val = any.from_any(prop.getProperty("dataport.interface_type"),keep_structs=True)
    self.assertEqual(val,"corba_cdr")
    
    # ProviderTypes,ConsumerTypesが取得される
    pstr = self._inport.getProviderTypes()
    self.assertEqual(pstr[0],"corba_cdr")
    cstr = self._inport.getConsumerTypes()
    self.assertEqual(cstr[0],"corba_cdr")

    return
    def testScaBasicBehavior(self):
        #######################################################################
        # Launch the component with the default execparams
        execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
        execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
        self.launch(execparams)

        #######################################################################
        # Verify the basic state of the component
        self.assertNotEqual(self.comp, None)
        self.assertEqual(self.comp.ref._non_existent(), False)
        self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
        self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())

        #######################################################################
        # Simulate regular component startup
        # Verify that initialize nor configure throw errors
        self.comp.initialize()
        configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
        self.comp.configure(configureProps)

        #######################################################################
        # Validate that query returns all expected parameters
        # Query of '[]' should return the following set of properties
        expectedProps = []
        expectedProps.extend(
            self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)
        )
        expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
        props = self.comp.query([])
        props = dict((x.id, any.from_any(x.value)) for x in props)
        # Query may return more than expected, but not less
        for expectedProp in expectedProps:
            self.assertEquals(props.has_key(expectedProp.id), True)

        #######################################################################
        # Verify that all expected ports are available
        for port in self.scd.get_componentfeatures().get_ports().get_uses():
            port_obj = self.comp.getPort(str(port.get_usesname()))
            self.assertNotEqual(port_obj, None)
            self.assertEqual(port_obj._non_existent(), False)
            self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)

        for port in self.scd.get_componentfeatures().get_ports().get_provides():
            port_obj = self.comp.getPort(str(port.get_providesname()))
            self.assertNotEqual(port_obj, None)
            self.assertEqual(port_obj._non_existent(), False)
            self.assertEqual(port_obj._is_a(port.get_repid()), True)

        #######################################################################
        # Make sure start and stop can be called without throwing exceptions
        self.comp.start()
        self.comp.stop()

        #######################################################################
        # Simulate regular component shutdown
        self.comp.releaseObject()
 def test_hexProperty(self):
     dev = self._devMgr._get_registeredDevices()[0]
     prop = CF.DataType(id='hex_props',value=any.to_any(None))
     results = dev.query([prop])
     self.assertEqual(any.from_any(results[0].value)[0], 2)
     self.assertEqual(any.from_any(results[0].value)[1], 3)
     prop = CF.DataType(id='hex_prop',value=any.to_any(None))
     results = dev.query([prop])
     self.assertEqual(any.from_any(results[0].value), 2)
    def test_GetPropertySet(self):
        testing.setSoftPkg(os.path.join(scatest.getSdrPath(), "dom", "components", "CommandWrapper", "CommandWrapper.spd.xml"))
        testing.setImplId("DCE:535a68a7-64e4-424b-9045-5ffc7659bf9d")
        testing.RHComponentTestCase.runTest = lambda : None
        tc = testing.RHComponentTestCase()
        tc.setUp()

        execparams = tc.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"))
        execparams = dict([(p.id, any.from_any(p.value)) for p in execparams])
        self.assertEqual(execparams.has_key("EXEC_PARAM_1"), True)
        self.assertEqual(execparams.has_key("EXEC_PARAM_2"), True)
        self.assertEqual(execparams.has_key("EXEC_PARAM_4"), True)
        self.assertEqual(execparams.has_key("SOMEOBJREF"), True)

        self.assertEqual(execparams["EXEC_PARAM_1"], "Test1")
        self.assertEqual(execparams["EXEC_PARAM_2"], 2)
        self.assertEqual(execparams["EXEC_PARAM_4"], True)
        self.assertEqual(execparams["SOMEOBJREF"], None)

        execparams = tc.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
        execparams = dict([(p.id, any.from_any(p.value)) for p in execparams])
        self.assertEqual(execparams.has_key("EXEC_PARAM_1"), True)
        self.assertEqual(execparams.has_key("EXEC_PARAM_2"), True)
        self.assertEqual(execparams.has_key("EXEC_PARAM_4"), True)
        self.assertEqual(execparams.has_key("SOMEOBJREF"), False)

        self.assertEqual(execparams["EXEC_PARAM_1"], "Test1")
        self.assertEqual(execparams["EXEC_PARAM_2"], 2)
        self.assertEqual(execparams["EXEC_PARAM_4"], True)

        cfgparams = tc.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"))
        cfgparams = dict([(p.id, any.from_any(p.value)) for p in cfgparams])
        self.assertEqual(cfgparams.has_key("DCE:a4e7b230-1d17-4a86-aeff-ddc6ea3df26e"), True)
        self.assertEqual(cfgparams.has_key("DCE:5d8bfe8d-bc25-4f26-8144-248bc343aa53"), True)
        self.assertEqual(cfgparams.has_key("DCE:ffe634c9-096d-425b-86cc-df1cce50612f"), True)
        self.assertEqual(cfgparams.has_key("DCE:fa8c5924-845c-484a-81df-7941f2c5baa9"), True)
        self.assertEqual(cfgparams.has_key("DCE:a7de97ee-1e78-45e9-8e2b-204c141656fc"), True)
        self.assertEqual(cfgparams.has_key("DCE:9ec6e2ff-6a4f-4452-8f38-4df47d6eebc1"), True)
        self.assertEqual(cfgparams.has_key("DCE:cf623573-a09d-4fb1-a2ae-24b0b507115d"), True)
        self.assertEqual(cfgparams.has_key("DCE:6ad84383-49cf-4017-b7ca-0ec4c4917952"), True)

        propparams = tc.getPropertySet(kinds=("property",), modes=("readwrite", "writeonly"))
        propparams = dict([(p.id, any.from_any(p.value)) for p in propparams])
        self.assertEqual(propparams.has_key("configure_prop_notset"), True)

        self.assertEqual(cfgparams["DCE:a4e7b230-1d17-4a86-aeff-ddc6ea3df26e"], "/bin/echo")
        self.assertEqual(cfgparams["DCE:5d8bfe8d-bc25-4f26-8144-248bc343aa53"], ["Hello World"])
        self.assertEqual(cfgparams["DCE:ffe634c9-096d-425b-86cc-df1cce50612f"], [{"id": 'item1', 'value': 'value1'},
                                                                                 {"id": 'item2', 'value': 100},
                                                                                 {"id": 'item3', 'value': 3.14156}
                                                                                ])
        self.assertEqual(cfgparams["DCE:fa8c5924-845c-484a-81df-7941f2c5baa9"], 10000)
        self.assertEqual(cfgparams["DCE:a7de97ee-1e78-45e9-8e2b-204c141656fc"], 12345678901)
        self.assertEqual(cfgparams["DCE:9ec6e2ff-6a4f-4452-8f38-4df47d6eebc1"], 11111111111)
        self.assertEqual(cfgparams["DCE:cf623573-a09d-4fb1-a2ae-24b0b507115d"], 500.0)
        self.assertEqual(cfgparams["DCE:6ad84383-49cf-4017-b7ca-0ec4c4917952"], None)
示例#8
0
文件: dfields.py 项目: LANJr4D/FRED
    def merge_histories(self, hist1, hist2):
        """ Merge histories of field and his dislose flag, If time is the same, 
            then histories are sorted/merged according to requestId 
            (if requestId is the same, then they are merged, otherwise sorted):
        """
        all_dates = {} # key is (date, request_id), value is couple list of couple [hist_number, history record]

        for hist_num, hist in enumerate([hist1, hist2]):
            for rec in hist:
                from_date = rec._from
                if from_date: # from/to date can be empty, in that case we ignore it
                    key = (from_date, rec.requestId)
                    val = [hist_num, rec]
                    if all_dates.has_key(key):
                        all_dates[key].append(val)
                    else:
                        all_dates[key] = [val]

        new_hist = []
        last_hist_vals = {0: from_any(hist1[0].value, True),
                          1: from_any(hist2[0].value, True)}
        last_hist_tos = {0: None,
                         1: None}

        for key, rec_list in sorted(all_dates.items()):
            for hist_num, rec in rec_list:
                last_hist_vals[hist_num] = from_any(rec.value, True)
                last_hist_tos[hist_num] = rec.to
            value = to_any([last_hist_vals[0], last_hist_vals[1]])
            request_id = rec_list[0][1].requestId
            _from = rec_list[0][1]._from

            # Do not add subclasses of Null (they represent empty fields).
            to_dict = dict(
                [(hist_num, rec.to) for
                    hist_num, rec in rec_list if
                        rec.to and not isinstance(rec.to, fredtypes.Null)])
            for hist_num in (0, 1):
                if not to_dict.has_key(hist_num):
                    to_dict[hist_num] = last_hist_tos[hist_num]
                if to_dict[hist_num] is None or \
                    isinstance(to_dict[hist_num], fredtypes.Null): # remove None
                    to_dict.pop(hist_num)
            all_are_null = all(isinstance(i, fredtypes.Null) for i in to_dict)
            if to_dict and not all_are_null:
                to = min(to_dict.values())
            else: # all are NULL dates, take one of them
                to = rec_list[0][1].to
            new_rec = Registry.HistoryRecord(_from=_from, to=to, value=value, requestId=request_id)
            new_hist.append(new_rec)

        return list(reversed(new_hist))
    def test_MultipleService(self):
        svcBooter, svcMgr = self.launchDeviceManager("/nodes/test_BasicService_node/DeviceManager.dcd.xml")
        self.assertNotEqual(svcMgr, None)
        svcBooterSecond, svcMgrSecond = self.launchDeviceManager("/nodes/test_SecondBasicService_node/DeviceManager.dcd.xml")
        self.assertNotEqual(svcMgrSecond, None)
        svcBooterSecond, svcMgrThird = self.launchDeviceManager("/nodes/test_PortTestDeviceService_node/DeviceManager.dcd.xml")
        self.assertNotEqual(svcMgrSecond, None)

        #confirm connection is there
        device = svcMgrThird._get_registeredDevices()[0]
        service_1 = svcMgr._get_registeredServices()[0]

        props = service_1.serviceObject.query([])
        testOut = device.runTest(2, [])
        for ii in range(len(props)):
            self.assertEqual(props[ii].id, testOut[ii].id)
            self.assertEqual(any.from_any(props[ii].value), any.from_any(testOut[ii].value))

        svcMgrSecond.shutdown()
        devmgrs = []
        begin_time = time.time()
        while len(devmgrs) != 2:
            devmgrs = self._domMgr._get_deviceManagers()
            time.sleep(0.1)
            if (time.time() - begin_time) > 5.0:
                self.fail('Device manager test_SecondBasicService_node did not unregister')

        props = service_1.serviceObject.query([])
        testOut = device.runTest(2, [])
        for ii in range(len(props)):
            self.assertEqual(props[ii].id, testOut[ii].id)
            self.assertEqual(any.from_any(props[ii].value), any.from_any(testOut[ii].value))

        svcMgrThird.shutdown()
        devmgrs = []
        begin_time = time.time()
        while len(devmgrs) != 1:
            devmgrs = self._domMgr._get_deviceManagers()
            time.sleep(0.1)
            if (time.time() - begin_time) > 5.0:
                self.fail('Device manager test_PortTestDeviceService_node did not unregister')
        svcMgr.shutdown()
        devmgrs = []
        begin_time = time.time()
        while len(devmgrs) != 0:
            devmgrs = self._domMgr._get_deviceManagers()
            time.sleep(0.1)
            if (time.time() - begin_time) > 5.0:
                self.fail('Device manager test_BasicService_node did not unregister')
			def get_object_profile(rtcs):
				profile_dic = {}
				for n, r in rtcs.items():
					objName = ""
					arg = ""
					try:
						for nv in r._ptr().get_component_profile().properties:
							if nv.name == 'conf.__innerparam.objectName':
								objName = any.from_any(nv.value, keep_structs=True)
							elif nv.name == 'conf.__innerparam.argument':
								arg = any.from_any(nv.value, keep_structs=True)
						profile_dic[objName] = arg
					except:
						pass
				return profile_dic
示例#11
0
def writeDataPort(port, data, tm=1.0, disconnect=True):
	nv1 = SDOPackage.NameValue("dataport.interface_type", 
				   any.to_any("corba_cdr"))
	nv2 = SDOPackage.NameValue("dataport.dataflow_type", 
				   any.to_any("Push"))
	nv3 = SDOPackage.NameValue("dataport.subscription_type", 
				   any.to_any("flush"))
	con_prof = RTC.ConnectorProfile("connector0", "", [port], 
					[nv1, nv2, nv3])
	ret,prof = port.connect(con_prof)
	if ret != RTC.RTC_OK:
		print "failed to connect"
		return None
	for p in prof.properties:
		if p.name == 'dataport.corba_cdr.inport_ior':
			ior = any.from_any(p.value)
			obj = orb.string_to_object(ior)
			inport = obj._narrow(InPortCdr)
			cdr = data2cdr(data)
			if inport.put(cdr) != OpenRTM.PORT_OK:
				print "failed to put"
			if disconnect:
				time.sleep(tm)
				port.disconnect(prof.connector_id)
			else:
				return prof.connector_id
	return None		
  def unsubscribeFromIor(self, properties):
    self._rtcout.RTC_TRACE("unsubscribeFromIor()")
    index = OpenRTM_aist.NVUtil.find_index(properties,
                                           "dataport.corba_cdr.inport_ior")
    if index < 0:
      self._rtcout.RTC_ERROR("inport_ior not found")
      return False
    
    ior = ""
    try:
      ior = any.from_any(properties[index].value, keep_structs=True)
    except:
      self._rtcout.RTC_ERROR(sys.exc_info()[0])

    if not ior:
      self._rtcout.RTC_ERROR("prop[inport_ior] is not string")
      return False
    
    orb = OpenRTM_aist.Manager.instance().getORB()
    var = orb.string_to_object(ior)
    if not self._ptr()._is_equivalent(var):
      self._rtcout.RTC_ERROR("connector property inconsistency")
      return False
    
    self.releaseObject()
    return True
  def subscribeFromRef(self, properties):
    self._rtcout.RTC_TRACE("subscribeFromRef()")
    index = OpenRTM_aist.NVUtil.find_index(properties,
                                           "dataport.corba_cdr.inport_ref")
    if index < 0:
      self._rtcout.RTC_ERROR("inport_ref not found")
      return False
    
    obj = None
    try:
      obj = any.from_any(properties[index].value, keep_structs=True)
    except:
      self._rtcout.RTC_ERROR(sys.exc_info()[0])
    
    if not obj:
      self._rtcout.RTC_ERROR("prop[inport_ref] is not objref")
      return False
    
    if CORBA.is_nil(obj):
      self._rtcout.RTC_ERROR("prop[inport_ref] is not objref")
      return False
    
    if not self.setObject(obj):
      self._rtcout.RTC_ERROR("Setting object to consumer failed.")
      return False

    return True
  def subscribeFromIor(self, properties):
    self._rtcout.RTC_TRACE("subscribeFromIor()")
    
    index = OpenRTM_aist.NVUtil.find_index(properties,
                                           "dataport.corba_cdr.inport_ior")
    if index < 0:
      self._rtcout.RTC_ERROR("inport_ior not found")
      return False
    
    ior = ""
    try:
      ior = any.from_any(properties[index].value, keep_structs=True)
    except:
      self._rtcout.RTC_ERROR(sys.exc_info()[0])

    if not ior:
      self._rtcout.RTC_ERROR("inport_ior has no string")
      return False
    
    orb = OpenRTM_aist.Manager.instance().getORB()
    obj = orb.string_to_object(ior)
    
    if CORBA.is_nil(obj):
      self._rtcout.RTC_ERROR("invalid IOR string has been passed")
      return False
    
    if not self.setObject(obj):
      self._rtcout.RTC_WARN("Setting object to consumer failed.")
      return False

    return True
示例#15
0
 def startComponent(self):
     """Standard start-up for testing the component
     """
     #######################################################################
     # Launch the component with the default execparams
     execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
     execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
     self.launch(execparams, initialize=True)
     
     #######################################################################
     # Verify the basic state of the component
     self.assertNotEqual(self.comp, None)
     self.assertEqual(self.comp.ref._non_existent(), False)
     self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
     #self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
     
     #######################################################################
     # Simulate regular component startup
     # Verify that initialize nor configure throw errors
     #self.comp.initialize()
     configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
     self.comp.configure(configureProps)
     
         
     self.comp.start()
示例#16
0
 def checkSRI(self,sri):
     self.assertEqual(sri.streamID,"myStreamID")
     self.assertEqual(sri.mode,0)
     self.assertAlmostEqual(sri.xdelta,1.0/200)
     self.assertEqual(sri.keywords[0].id, "testkw")
     self.assertEqual(len(sri.keywords), 1)
     self.assertAlmostEqual(any.from_any(sri.keywords[0].value), 10.0)
示例#17
0
  def subscribeInterfaces(self, connector_profile):
    self._rtcout.RTC_TRACE("subscribeInterfaces()")
    nv = connector_profile.properties

    strict = False # default is "best_effort"
    index = OpenRTM_aist.NVUtil.find_index(nv, "port.connection.strictness")
    if index >=  0:
      strictness = str(any.from_any(nv[index].value, keep_structs=True))
      if "best_effort" == strictness:
        strict = False
      elif "strict" == strictness:
        strict = True

      self._rtcout.RTC_DEBUG("Connetion strictness is: %s",strictness)

    for consumer in self._consumers:
      ior = []
      if self.findProvider(nv, consumer, ior) and len(ior) > 0:
        self.setObject(ior[0], consumer)
        continue

      ior = []
      if self.findProviderOld(nv, consumer, ior) and len(ior) > 0:
        self.setObject(ior[0], consumer)
        continue

      # never come here without error
      # if strict connection option is set, error is returned.
      if strict:
        self._rtcout.RTC_ERROR("subscribeInterfaces() failed.")
        return RTC.RTC_ERROR

    self._rtcout.RTC_TRACE("subscribeInterfaces() successfully finished.")

    return RTC.RTC_OK
def isString(nv, name):
  try:
    value = find(nv, name)
    val = any.from_any(value, keep_structs=True)
    return type(val) == str
  except:
    return False
    def eventReceived(self, data):
        dataEvent = any.from_any(data, keep_structs=True)
        if dataEvent.sourceId != self.sourceId:
            self.successfullPropChange = False
            return
        if len(dataEvent.properties) == 0:
            self.successfullPropChange = False
            return

        props = properties.props_to_dict(dataEvent.properties)
        if props.has_key('myprop'):
            self.received_myprop = True
            if self.successfullPropChange == None:
                self.successfullPropChange = True
        if props.has_key('anotherprop'):
            self.received_anotherprop = True
            if self.successfullPropChange == None:
                self.successfullPropChange = True
        if props.has_key('seqprop'):
            if props['seqprop'] == [1.0, 2.0, 3.0]:
                self.received_seqprop = True
                if self.successfullPropChange == None:
                    self.successfullPropChange = True
        if props.has_key('some_struct') and props['some_struct'] != None:
            if props['some_struct'] == {"some_number": 3.0, "some_string": "hello"}:
                self.received_some_struct = True
                if self.successfullPropChange == None:
                    self.successfullPropChange = True
        if props.has_key('structseq_prop'):
            if len(props['structseq_prop']) == 1:
                if props['structseq_prop'][0] == {"some_number": 7.0, "some_string": "second message"}:
                    self.received_structseq_prop = True
                    if self.successfullPropChange == None:
                        self.successfullPropChange = True
示例#20
0
 def testScaBasicBehavior(self):
     #######################################################################
     # Validate that query returns all expected parameters
     # Query of '[]' should return the following set of properties
     expectedProps = []
     expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
     expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
     props = self.comp.query([])
     props = dict((x.id, any.from_any(x.value)) for x in props)
     # Query may return more than expected, but not less
     for expectedProp in expectedProps:
         self.assertEquals(props.has_key(expectedProp.id), True)
     
     #######################################################################
     # Verify that all expected ports are available
     for port in self.scd.get_componentfeatures().get_ports().get_uses():
         port_obj = self.comp.getPort(str(port.get_usesname()))
         self.assertNotEqual(port_obj, None)
         self.assertEqual(port_obj._non_existent(), False)
         self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"),  True)
         
     for port in self.scd.get_componentfeatures().get_ports().get_provides():
         port_obj = self.comp.getPort(str(port.get_providesname()))
         self.assertNotEqual(port_obj, None)
         self.assertEqual(port_obj._non_existent(), False)
         self.assertEqual(port_obj._is_a(port.get_repid()),  True)
         
     #######################################################################
     # Make sure start and stop can be called without throwing exceptions
     self.comp.start()
     self.comp.stop()
  def subscribeInterface(self, properties):
    self._rtcout.RTC_TRACE("subscribeInterface()")
    index = OpenRTM_aist.NVUtil.find_index(properties,"dataport.corba_cdr.outport_ior")
        
    if index < 0:
      self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.")
      return False

    if OpenRTM_aist.NVUtil.isString(properties,"dataport.corba_cdr.outport_ior"):
      self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.")
      ior = ""
      try:
        ior = any.from_any(properties[index].value, keep_structs=True)
      except:
        self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())
            
      orb = OpenRTM_aist.Manager.instance().getORB()
      obj = orb.string_to_object(ior)
      ret = self.setObject(obj)
      if ret:
        self._rtcout.RTC_DEBUG("CorbaConsumer was set successfully.")
      else:
        self._rtcout.RTC_ERROR("Invalid object reference.")
        
      return ret

    return False
  def unsubscribeInterface(self, properties):
    self._rtcout.RTC_TRACE("unsubscribeInterface()")
    index = OpenRTM_aist.NVUtil.find_index(properties,
                                           "dataport.corba_cdr.outport_ref")
    if index < 0:
      self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior not found.")
      return
    
    ior = ""
    try:
      ior = any.from_any(properties[index].value, keep_structs=True)
                
      if ior:
        self._rtcout.RTC_DEBUG("dataport.corba_cdr.outport_ior found.")
        orb = OpenRTM_aist.Manager.instance().getORB()
        obj = orb.string_to_object(ior)
        if self._ptr()._is_equivalent(obj):
          self.releaseObject()
          self._rtcout.RTC_DEBUG("CorbaConsumer's reference was released.")
          return

        self._rtcout.RTC_ERROR("hmm. Inconsistent object reference.")

    except:
      self._rtcout.RTC_ERROR(OpenRTM_aist.Logger.print_exception())

    return
    def test_ComponentPlacementPropertyOverride(self):
        devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml")
        self.assertNotEqual(devMgr, None)

        # NOTE These assert check must be kept in-line with the DeviceManager.dcd.xml
        self.assertEqual(len(devMgr._get_registeredDevices()), 1)

        # Test that the DCD file componentproperties get pushed to configure()
        # as per DeviceManager requirement SR:482
        device = devMgr._get_registeredDevices()[0]
        propId = "DCE:6b298d70-6735-43f2-944d-06f754cd4eb9"
        prop = CF.DataType(id=propId, value=any.to_any(None))
        result = device.query([prop])
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].id, propId)
        # This should have been overrided by the dcd
        self.assertEqual(result[0].value._v, "BasicTestDevice1_no_default_prop")

        propId = "DCE:456310b2-7d2f-40f5-bfef-9fdf4f3560ea"
        prop = CF.DataType(id=propId, value=any.to_any(None))
        result = device.query([prop])
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].id, propId)
        # This should have been overrided by the dcd
        self.assertEqual(result[0].value._v, "BasicTestDevice1_default_prop")

        structprop = device.query([CF.DataType(id="DCE:ffe634c9-096d-425b-86cc-df1cce50612f", value=any.to_any(None))])[0]
        struct_propseq = any.from_any(structprop.value)
        d = dict([(d["id"], d["value"]) for d in struct_propseq])
        self.assertEqual(d, {"item1": "the new value", "item2": 400, "item3": 1.414})
示例#24
0
    def setUp(self):
        ossie.utils.testing.ScaComponentTestCase.setUp(self)

        #######################################################################
        # Launch the component with the default execparams
        execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
        execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
        execparams['DEBUG_LEVEL'] = DEBUG_LEVEL
        self.launch(execparams)
        
        #######################################################################
        # Verify the basic state of the component
        self.assertNotEqual(self.comp, None)
        self.assertEqual(self.comp.ref._non_existent(), False)
        self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)

        # Load resources for majority of tests
        self.src = sb.DataSource()
        self.sink = sb.DataSink()
        self.sinkSocket = self.comp
        self.sourceSocket = NetworkSource()

        self.client = None
        self.clients = None
        self.server = None
        self.servers = None
        self.sink2 = None
        self.sourceSocket2 = None
示例#25
0
 def buildPropertiesListView_old (self, parent, properties, propertyDefs):
     for prop in properties:
         id = prop.id
         value = any.from_any(prop.value)
         if id not in propertyDefs:
             valueItem = QListViewItem(parent, id, str(value), '', id)
             continue
         property = propertyDefs[id]
         name = property.get('name', id)
         if property['elementType'] in ('simple', 'simplesequence'):
             # NB: As a temporary hack for mapping back to property id, store the id in
             #     the hidden fourth field.
             valueItem = self.addTreeWidgetItem(self.domMgrPropsItem, name, str(value))
             #if property['mode'] in ('readwrite', 'writeonly'):
             #    valueItem.setRenameEnabled(1, True)
         elif property['elementType'] == 'struct':
             valueItem = QListViewItem(parent, name, '', '', id)
             for field in value:
                 QListViewItem(valueItem, field['id'], str(field['value']))
         elif property['elementType'] == 'structsequence':
             valueItem = QListViewItem(parent, name, '', '', id)
             if value == None:
                 continue
             for index, structval in enumerate(value):
                 subitem = QListViewItem(valueItem, str(index))
                 for field in structval:
                     QListViewItem(subitem, field['id'], str(field['value']))
示例#26
0
文件: dfields.py 项目: LANJr4D/FRED
    def make_content(self):
        self.content = []

        self.inner_field.owner_detail = self.owner_detail
        if self.value:
            for i, history_rec in enumerate(self.value):
                val = from_any(history_rec.value, True)
                inner_field_copy = copy(self.inner_field)
                inner_field_copy.value = val
                date_from = history_rec._from #recoder.corba_to_datetime(history_rec._from)
                date_to = history_rec.to #recoder.corba_to_datetime(history_rec.to)
                logger_url = f_urls['logger'] + 'detail/?id=%s' % history_rec.requestId

                history_tr = tr()
                if i > 0:
                    history_tr.cssc = 'history_row'
                log_req_link = a(attr(href=logger_url), img(attr(src='/img/icons/open.png'))) if history_rec.requestId else ''
                history_tr.add(
                    td(inner_field_copy),
                    td(attr(cssc='history_dates_field'), _('from'), date_from),
                    td(attr(cssc='history_dates_field'), date_to and _('to') or '', date_to),
                    td(attr(cssc='history_dates_field'), log_req_link)
                )
                self.add(history_tr)
        else:
            self.add(div(attr(cssc='field_empty')))
    def test_ComponentPlacementNoPropOverride(self):
        devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_DCDSimpleSeq_node/DeviceManager.dcd.xml")
        self.assertNotEqual(devMgr, None)

        # NOTE These assert check must be kept in-line with the DeviceManager.dcd.xml
        self.assertEqual(len(devMgr._get_registeredDevices()), 1)

        device = devMgr._get_registeredDevices()[0]
        # this device implementation will put a non-nil value on the property (even if a nil has been passed in a configure call)
        propId = "nil_property"
        prop = CF.DataType(id=propId, value=any.to_any(None))
        result = device.query([prop])
        self.assertEqual(any.from_any(result[0].value), None)
        device.configure([prop])
        result = device.query([prop])
        self.assertEqual(any.from_any(result[0].value), -1.0)
示例#28
0
 def push(self, data):
     try:
         if self.__filter == None or data.typecode() in self.__filter:
             event = any.from_any(data, keep_structs=self.__keep_structs)
             self.__on_push(event, data.typecode())
     except:
         traceback.print_exc()
示例#29
0
def dataTypeOfPort(port):
    prof = port.get_port_profile()
    prop = prof.properties
    for p in prop:
        if p.name == "dataport.data_type":
            return any.from_any(p.value)
    return None
示例#30
0
def findService(rtc, port_name, type_name, instance_name):
    if port_name == "":
        prof = rtc.ref.get_component_profile()
        # print("RTC name:",prof.instance_name)
        port_prof = prof.port_profiles
    else:
        p = rtc.port(port_name)
        if p == None:
            print("can't find a port named" + port_name)
            return None
        else:
            port_prof = [p.get_port_profile()]
    port = None
    for pp in port_prof:
        # print("name:", pp.name)
        ifs = pp.interfaces
        for aif in ifs:
            #print("IF name:", aif.instance_name)
            #print("IF type:", aif.type_name)
            if aif.instance_name == instance_name and \
               (type_name == "" or aif.type_name == type_name) and \
               aif.polarity == PROVIDED:
                port = pp.port_ref
    if port == None:
        print("can't find a service named", instance_name)
        return None
    con_prof = RTC.ConnectorProfile("noname", "", [port], [])
    ret, con_prof = port.connect(con_prof)
    ior = any.from_any(con_prof.properties[0].value)
    return orb.string_to_object(ior)
 def testScaBasicBehavior(self):
     #######################################################################
     # Launch the component with the default execparams
     execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
     execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
     self.launch(execparams)
     
     #######################################################################
     # Verify the basic state of the component
     self.assertNotEqual(self.comp, None)
     self.assertEqual(self.comp.ref._non_existent(), False)
     self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
     
     #######################################################################
     # Validate that query returns all expected parameters
     # Query of '[]' should return the following set of properties
     expectedProps = []
     expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
     expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
     props = self.comp.query([])
     props = dict((x.id, any.from_any(x.value)) for x in props)
     # Query may return more than expected, but not less
     for expectedProp in expectedProps:
         self.assertEquals(props.has_key(expectedProp.id), True)
     
     #######################################################################
     # Verify that all expected ports are available
     for port in self.scd.get_componentfeatures().get_ports().get_uses():
         port_obj = self.comp.getPort(str(port.get_usesname()))
         self.assertNotEqual(port_obj, None)
         self.assertEqual(port_obj._non_existent(), False)
         self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"),  True)
         
     for port in self.scd.get_componentfeatures().get_ports().get_provides():
         port_obj = self.comp.getPort(str(port.get_providesname()))
         self.assertNotEqual(port_obj, None)
         self.assertEqual(port_obj._non_existent(), False)
         self.assertEqual(port_obj._is_a(port.get_repid()),  True)
         
     #######################################################################
     # Make sure start and stop can be called without throwing exceptions
     self.comp.start()
     self.comp.stop()
     
     #######################################################################
     # Simulate regular component shutdown
     self.comp.releaseObject()
示例#32
0
    def test_ComponentPlacementNoPropOverride(self):
        devmgr_nb, devMgr = self.launchDeviceManager(
            "/nodes/test_DCDSimpleSeq_node/DeviceManager.dcd.xml", debug=9)
        self.assertNotEqual(devMgr, None)

        # NOTE These assert check must be kept in-line with the DeviceManager.dcd.xml
        self.assertEqual(len(devMgr._get_registeredDevices()), 1)

        device = devMgr._get_registeredDevices()[0]
        # this device implementation will put a non-nil value on the property (even if a nil has been passed in a configure call)
        propId = "nil_property"
        prop = CF.DataType(id=propId, value=any.to_any(None))
        result = device.query([prop])
        self.assertEqual(any.from_any(result[0].value), None)
        device.configure([prop])
        result = device.query([prop])
        self.assertEqual(any.from_any(result[0].value), -1.0)
    def testPush(self):
        receiver = MessageReceiver()
        self._consumer.registerMessage(None, None, receiver.messageReceived)

        # Pack the messages ourselves
        messages = []
        messages.append(CF.DataType('first', to_any(100)))
        messages.append(CF.DataType('second', to_any('some text')))
        messages.append(CF.DataType('third', to_any(0.25)))

        self._supplier.push(props_to_any(messages))

        self.failUnless(receiver.waitMessages(3, 1.0))
        self.assertEqual(3, len(receiver.messages))
        self.assertEqual(100, from_any(receiver.messages[0].value))
        self.assertEqual('some text', from_any(receiver.messages[1].value))
        self.assertEqual(0.25, from_any(receiver.messages[2].value))
示例#34
0
def copyToProperties(prop, nvlist):
  for nv in nvlist:
    try:
      val = str(any.from_any(nv.value, keep_structs=True))
      prop.setProperty(str(nv.name),val)
    except:
      print OpenRTM_aist.Logger.print_exception()
      pass
示例#35
0
 def get_factory_names(self):
     fs = []
     fps = self.ref.get_factory_profiles()
     for afp in fps:
         for p in afp.properties:
             if p.name == "implementation_id":
                 fs.append(any.from_any(p.value))
     return fs
    def test1_configureQuery(self):
        # Launch the resource with the default execparams
        execparams = self.getPropertySet(kinds=("execparam", ),
                                         modes=("readwrite", "writeonly"),
                                         includeNil=False)
        execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
        self.launch(execparams)

        # test string props
        self.comp.stringPropIO1 = "foo"
        # need to push some data so that feval gets called
        self.pushDataAndCheck()
        self.assertEquals(self.comp.stringPropIO1, "foo")
        self.assertEquals(self.comp.stringPropOutput1, "output")

        # complex props
        self.comp.complexPropIO1 = complex(1.5, 2.5)
        # need to push some data so that feval gets called
        self.pushDataAndCheck()
        self.assertEquals(self.comp.complexPropIO1, complex(1.5, 2.5))
        self.assertEquals(self.comp.complexPropOutput1, complex(1, 2))

        # test vector props
        self.comp.vectorPropIO1 = range(10)
        complexVect = [complex(-1, -1), complex(0, 2), complex(5.0, 6)]
        self.comp.complexVectorPropIO1 = complexVect
        # need to push some data so that feval gets called
        self.pushDataAndCheck()
        self.assertEquals(self.comp.vectorPropIO1, range(10))
        self.assertEquals(self.comp.vectorPropOutput1, [-1, 0, 1, 2.5])
        self.assertEquals(self.comp.complexVectorPropIO1, complexVect)
        self.assertEquals(
            self.comp.complexVectorOutput1,
            [complex(-1, -1),
             complex(0, 0),
             complex(1, 0),
             complex(2, 2)])

        # test SRI keywords
        inputData = xrange(100)
        expectedOutput = []
        i = 0
        while i < len(inputData) - 1:
            cplx = complex(inputData[i], inputData[i + 1])
            expectedOutput.append(cplx)
            i += 2
        SRIKeywords = [
            sb.io_helpers.SRIKeyword('val1', 1, 'long'),
            sb.io_helpers.SRIKeyword('val2', 'foo', 'string')
        ]
        self.pushDataAndCheck(streamID="testSRI",
                              expectedOutput=expectedOutput,
                              sampleRate=50,
                              complexData=True,
                              SRIKeywords=SRIKeywords)

        # Simulate regular resource shutdown
        self.comp.releaseObject()
示例#37
0
    def test_DeviceManagerPort(self):
        self._createApp('DeviceManager')
        component = self._getComponents()['PortTest1']

        expectedId = self._devMgr._get_identifier()
        actualId = component.runTest(3, [])
        self.assertEqual(len(actualId), 1)
        actualId = any.from_any(actualId[0].value)
        self.assertEqual(expectedId, actualId)
示例#38
0
 def __call__(self, nv):
     for con in self._cons:
         name_ = nv.name
         if con.descriptor() == name_:
             try:
                 obj = any.from_any(nv.value, keep_structs=True)
                 con.setObject(obj)
             except BaseException:
                 print(OpenRTM_aist.Logger.print_exception())
示例#39
0
 def __call__(self, nv):
   for i in range(self._len):
     name_ = nv.name
     if self._cons[i].descriptor() == name_:
       try:
         obj = any.from_any(nv.value, keep_structs=True)
         self._cons[i].setObject(obj)
       except:
         print(OpenRTM_aist.Logger.print_exception())
示例#40
0
def dump_to_stream(out, nv):
    for n in nv:
        val = any.from_any(n.value, keep_structs=True)
        if isinstance(val, str):
            out += (n.name + ": " + str(n.value) + "\n")
        else:
            out += (n.name + ": not a string value \n")

    return out
示例#41
0
    def _test_Service(self, connection):
        svcBooter, svcMgr = self.launchDeviceManager("/nodes/test_BasicService_node/DeviceManager.dcd.xml")
        self.assertNotEqual(svcMgr, None)

        self._createApp('Service' + connection)
        components = self._getComponents()

        self.assertEqual(len(svcMgr._get_registeredServices()), 1)
        service = svcMgr._get_registeredServices()[0]

        # Compare all of the properties returned directly from the service, and
        # via the runTest interface. They should all be the same, assuming that
        # the port was connected correctly.
        props = service.serviceObject.query([])
        testOut = components['PortTest1'].runTest(1, [])
        for ii in range(1):
            self.assertEqual(props[ii].id, testOut[ii].id)
            self.assertEqual(any.from_any(props[ii].value), any.from_any(testOut[ii].value))
示例#42
0
 def setUp(self):
     nodebooter, self.domMgr = self.launchDomainManager()
     self.assertNotEqual(self.domMgr, None)
     nodebooter, self.devMgr = self.launchDeviceManager(
         "/nodes/test_NicAllocation_node/DeviceManager.dcd.xml")
     self.assertNotEqual(self.devMgr, None)
     self.dev = self.devMgr._get_registeredDevices()[0]
     props = self.dev.query([CF.DataType('nic_list', any.to_any(None))])
     self.nicNames = any.from_any(props[0].value)
示例#43
0
 def __call__(self, nv):
   for i in range(self._len):
     name_ = nv.name
     if self._cons[i].descriptor() == name_:
       try:
         obj = any.from_any(nv.value, keep_structs=True)
         self._cons[i].setObject(obj)
       except:
         traceback.print_exception(*sys.exc_info())
    def test_CollocBasicShared(self):
        self.assertNotEqual(self._domainManager, None)

        app = self._domainManager.createApplication('/waveforms/BasicSharedCollocWave/BasicSharedCollocWave.sad.xml',
                                                    'BasicSharedCollocWave', [], [])

        comps = app._get_registeredComponents()
        self.assertEqual(len(comps), 2)

        request = [CF.DataType('pid', to_any(None))]
        props1 = comps[0].componentObject.query(request)
        props2 = comps[1].componentObject.query(request)

        self.assertEqual(len(props1), 1)
        self.assertEqual(props1[0].id, 'pid')
        self.assertEqual(len(props2), 1)
        self.assertEqual(props2[0].id, 'pid')
        self.assertEqual(from_any(props1[0].value), from_any(props2[0].value))
示例#45
0
def dump_to_stream(out, nv):
  for i in range(len(nv)):
    val = any.from_any(nv[i].value, keep_structs=True)
    if type(val) == str:
	    out[0] += (nv[i].name + ": " + str(nv[i].value) + "\n")
    else:
	    out[0] += (nv[i].name + ": not a string value \n")

  return out[0]
示例#46
0
    def test_ApplicationFactoryCreateURIOverride(self):
        domNB, domMgr = self.launchDomainManager(loggingURI="dom/mgr/logging.properties")
        self.assertNotEqual(domMgr, None)

        # Launch a device manager
        devNB, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml", loggingURI="dev/mgr/logging.properties")
        self.assertNotEqual(domMgr, None)

        # Double check the DomainManager LOGGING_CONFIG_URI
        prop = CF.DataType(id="LOGGING_CONFIG_URI", value=any.to_any(None))
        result = domMgr.query([prop])
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].id, "LOGGING_CONFIG_URI")
        devLoggingConfigURI = result[0].value._v
        expectedDomLoggingConfigUri = "file://" + os.path.join(scatest.getSdrPath(), "dom/mgr/logging.properties")
        self.assertEqual(devLoggingConfigURI, expectedDomLoggingConfigUri)

        # Launch an application
        domMgr.installApplication("/waveforms/CommandWrapper/CommandWrapper.sad.xml")
        self.assertEqual(len(domMgr._get_applicationFactories()), 1)
        self.assertEqual(len(domMgr._get_applications()), 0)

        appFact = domMgr._get_applicationFactories()[0]
        uriOverride = CF.DataType(id="LOGGING_CONFIG_URI", value=any.to_any("sca:///mgr/logging.properties"))
        app = appFact.create(appFact._get_name(), [uriOverride], [])

        # Get the desired component
        self.assertEqual(len(app._get_componentNamingContexts()), 1)
        compName = app._get_componentNamingContexts()[0]
        comp = self._root.resolve(URI.stringToName(compName.elementId))._narrow(CF.Resource)
        self.assertNotEqual(comp, None)

        # Check the components exec params
        execparams = comp.query([CF.DataType(id="DCE:85d133fd-1658-4e4d-b3ff-1443cd44c0e2", value=any.to_any(None))])[0]
        args = any.from_any(execparams.value)
        execparams = {}
        for b in args:
            a = eval(b)
            name = a[0]
            value = a[1]
            execparams[name] = value

        self.assert_(execparams.has_key("LOGGING_CONFIG_URI"))
        self.assertEqual(execparams["LOGGING_CONFIG_URI"].split("?fs=")[0], "sca:///mgr/logging.properties")
        execparamObj = self._orb.string_to_object(execparams["LOGGING_CONFIG_URI"].split("?fs=")[1])
        # Need to compare actual objects since the IOR strings could potentially differ for the same object
        self.assert_(domMgr._get_fileMgr()._is_equivalent(execparamObj))

        # Launch an application with a C++ component to exercise Resource_impl logging configure
        domMgr.installApplication("/waveforms/TestCppProps/TestCppProps.sad.xml")
        self.assertEqual(len(domMgr._get_applicationFactories()), 2)
        for appFact in domMgr._get_applicationFactories():
            if appFact._get_name() == "TestCppProps":
                app = appFact.create(appFact._get_name(), [uriOverride], [])
                break
        self.assertEqual(len(domMgr._get_applications()), 2)
示例#47
0
def getConfiguration(rtc):
    cfg = rtc.get_configuration()
    cfgsets = cfg.get_configuration_sets()
    if len(cfgsets) == 0:
        print("configuration set is not found")
        return None
    ret = {}
    for nv in cfgsets[0].configuration_data:
        ret[nv.name] = any.from_any(nv.value)
    return ret
示例#48
0
 def dataArrived(self, inany ):
     if inany != None:
         try:
             msgin = any.from_any(inany)
             if msgin == self.p_msgid:
                 self.msg_recv += 1
             self.p_msgid += 1
             self._log.info(" Received (CB) msgid :" + str(msgin) + " msg_recv: "  + str(self.msg_recv) )
         except:
             self._log.error(" Error for dataArrived CB")
 def runTest(self, test, props):
     if test == 0:
         # Inject values directly into property storage to allow testing of
         # bad conditions (invalid values)
         for dt in props:
             try:
                 self._props[dt.id] = from_any(dt.value)
             except KeyError:
                 pass
     return []
 def testEventPortSendFunction(self):
     #######################################################################
     # Launch the component with the default execparams
     execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
     execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
     self.launch(execparams)
     
     #######################################################################
     # Simulate regular component startup
     # Verify that initialize nor configure throw errors
     self.comp_obj.initialize()
     
     consumerPort = MessageConsumerPort()
     self.eventPort = self.comp_obj.getPort('propEvent')
     self.eventPort.connectPort(consumerPort._this(), 'some_id')
     
     propIDs = ['eventShortSimple',
             'eventStringSimple',
             'eventBoolSimple',
             'eventUlongSimple',
             'eventFloatSimple',
             'eventOctetSimple',
             'eventCharSimple',
             'eventUshortSimple',
             'eventDoubleSimple',
             'eventLongSimple',
             'eventLonglongSimple',
             'eventUlonglongSimple',
             'eventStringSeq',
             'eventBoolSeq',
             'eventUlongSeq',
             'eventFloatSeq',
             'eventOctetSeq',
             'eventCharSeq',
             'eventUshortSeq',
             'eventDoubleSeq',
             'eventLongSeq',
             'eventLonglongSeq',
             'eventUlonglongSeq',
             'eventShortSeq',
             'eventStruct',
             'eventStructSeq']
     
     for propID in propIDs:
         #test that the internal code sends out an event for each of these properties
         self.comp_obj.configure([ossie.cf.CF.DataType(id='propToSend', value=CORBA.Any(CORBA.TC_string, propID))])
         eventSent = False
         while not eventSent:
             ret = self.comp_obj.query([ossie.cf.CF.DataType(id='eventSent',value=any.to_any(None))])[0]
             if ret.value.value():
                 eventSent = True
         time.sleep(.003) #allow the event send to complete in the other thread
         event = consumerPort.getEvent()
         if not event:
             self.fail("No event was generated for " + str(propID))
示例#51
0
    def value_from_data(self, data):
        value = data.get(self.name)

        if value:
            if self.owner_detail.history and len(
                    value) > 1 and not self.owner_detail.is_nested:
                self.displaying_history = True
                self.history_field.owner_detail = self.owner_detail
                self._assign_current_field(self.history_field)
                for history_record in value:
                    recoder.c2u(from_any(history_record.value, True))
                return value
            else:
                self.normal_field.owner_detail = self.owner_detail
                self._assign_current_field(self.normal_field)
                return recoder.c2u(from_any(value[0].value, True))
        else:
            self.normal_field.owner_detail = self.owner_detail
            self._assign_current_field(self.normal_field)
            return fredtypes.Null()
示例#52
0
 def getProperty(self, name):
     cfg = self.ref.get_configuration()
     cfgsets = cfg.get_configuration_sets()
     if len(cfgsets) == 0:
         print("configuration set is not found")
         return None
     cfgset = cfgsets[0]
     for d in cfgset.configuration_data:
         if d.name == name:
             return any.from_any(d.value)
     return None
    def test_PropertyChangeEvents_Py(self):
        self.received_myprop = False
        self.received_anotherprop = False
        self.received_seqprop = False
        self.received_some_struct = False
        self.received_structseq_prop = False
        self.sourceId = 'prop_change_instance:PropertyChangeEvents_1'
        self.successfullPropChange = None
        self.set = 1
        # Test DeviceManager related events

        # launch DomainManager
        nodebooter, self._domMgr = self.launchDomainManager()
        devBooter, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml")
        self.assertNotEqual(devMgr, None)

        self._domMgr.installApplication("/waveforms/PropertyChangeEvents/PropertyChangeEvents.sad.xml")
        self.assertEqual(len(self._domMgr._get_applicationFactories()), 1)
        self.assertEqual(len(self._domMgr._get_applications()), 0)
        appFact = self._domMgr._get_applicationFactories()[0]
        app = appFact.create(appFact._get_name(), [], [])

        # set up consumer
        _consumer = Consumer_i(self)
        self._domMgr.registerWithEventChannel(_consumer._this(), 'some_id', 'propertyChanges')

        app.configure([CF.DataType(id='myprop',value=any.to_any(2))])
        app.configure([CF.DataType(id='anotherprop',value=any.to_any(2))])
        sequence = CF.DataType(id='seqprop',value=any.to_any([1.0, 2.0, 3.0]))
        sequence.value._t._d = (19,6,0) # change the type from double to float
        some_struct = CF.DataType(id='some_struct',value=any.to_any([CF.DataType(id='some_number',value=any.to_any(3.0)),CF.DataType(id='some_string',value=any.to_any('hello'))]))
        app.configure([sequence])
        app.configure([some_struct])
        structseq_prop = CF.DataType(id='structseq_prop',value=any.to_any([any.to_any([CF.DataType(id='some_number',value=any.to_any(7.0)),CF.DataType(id='some_string',value=any.to_any('second message'))])]))
        app.configure([structseq_prop])
        app.configure([structseq_prop])

        # Ticket #1061: Ensure that eventable structs and struct sequences with
        # 'None' values don't cause exceptions inside the port code.
        results = app.runTest(1061, [])

        # Convert test results into a dictionary
        results = dict((r.id, any.from_any(r.value)) for r in results)

        time.sleep(1)
        self.assertEqual(self.received_myprop, True)
        self.assertEqual(self.received_anotherprop, False)
        self.assertEqual(self.received_seqprop, True)
        self.assertEqual(self.received_some_struct, True)
        self.assertEqual(self.received_structseq_prop, True)
        self.assertEqual(self.successfullPropChange, True)
        self.assertEqual(results['1061'], True)
        self._domMgr.unregisterFromEventChannel('some_id', 'propertyChanges')
示例#54
0
def readDataPort(port, timeout=1.0):
    pprof = port.get_port_profile()
    for prop in pprof.properties:
        if prop.name == "dataport.data_type":
            classname = any.from_any(prop.value)
            break
    nv1 = SDOPackage.NameValue("dataport.interface_type",
                               any.to_any("corba_cdr"))
    nv2 = SDOPackage.NameValue("dataport.dataflow_type", any.to_any("Pull"))
    nv3 = SDOPackage.NameValue("dataport.subscription_type",
                               any.to_any("flush"))
    con_prof = RTC.ConnectorProfile("connector0", "", [port], [nv1, nv2, nv3])
    ret, prof = port.connect(con_prof)
    #
    if ret != RTC.RTC_OK:
        print "failed to connect"
        return None
    for p in prof.properties:
        #print p.name
        if p.name == 'dataport.corba_cdr.outport_ior':
            ior = any.from_any(p.value)
            obj = orb.string_to_object(ior)
            outport = obj._narrow(OutPortCdr)
            tm = 0
            while tm < timeout:
                try:
                    ret, data = outport.get()
                    if ret == OpenRTM.PORT_OK:
                        port.disconnect(prof.connector_id)
                        tokens = classname.split(':')
                        if len(tokens) == 3:  # for 1.1?
                            classname = tokens[1].replace('/', '.')
                        return cdr2data(data, classname)
                except:
                    pass
                time.sleep(0.1)
                tm = tm + 0.1

    port.disconnect(prof.connector_id)
    return None
示例#55
0
    def test_DeviceUsedByThisComponent(self):
        self._createApp('DeviceUsedByComponent')
        components = self._getComponents()

        # Use the TestableObject interface to check that 'PortTest1' has
        # exactly one connection
        # NB: The `usesdevice` can be satisfied by either of the devices, so
        #     just test that it's connected to one of them.
        ids = components['PortTest1'].runTest(0, [])
        self.assertEqual(len(ids), 1)
        usedDevId = any.from_any(ids[0].value).split('/')[0]
        devIds = [dev._get_identifier() for dev in self._devMgr._get_registeredDevices()]
        self.assert_(usedDevId in devIds)
示例#56
0
 def startSourceSocket(self):
     #######################################################################
     # Launch the component with the default execparams
     execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
     execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
     execparams['DEBUG_LEVEL'] = DEBUG_LEVEL
     self.launch(execparams)
     
     #######################################################################
     # Verify the basic state of the component
     self.assertNotEqual(self.comp, None)
     self.assertEqual(self.comp.ref._non_existent(), False)
     self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
示例#57
0
    def test_FindByFileManager(self):
        self._createApp('FindByFileManager')
        components = self._getComponents()

        listing = components['FileManagerPortTest1'].runTest(0, [])
        value = any.from_any(listing[0].value)
        foundMgrDir = False
        for entry in value:
            if entry['kind'] == CF.FileSystem.DIRECTORY:
                if entry['name'] == 'mgr':
                    foundMgrDir = True
                    break
        self.assertEqual(foundMgrDir, True)
    def _test_BasicService(self, node, expected_name):
        devmgr_nb, devMgr = self.launchDeviceManager("/nodes/" + node +
                                                     "/DeviceManager.dcd.xml",
                                                     debug=1)
        self.assertEqual(len(devMgr._get_registeredServices()), 1)
        svc = devMgr._get_registeredServices()[0]
        self.assertNotEqual(svc, None)
        self.assertEqual(svc.serviceName, expected_name)
        self.assertNotEqual(svc.serviceObject, None)
        obj = svc.serviceObject
        obj = obj._narrow(CF.PropertySet)
        self.assertNotEqual(obj, None)

        # Check the name service to ensure the service is properly bound
        svcName = URI.stringToName(scatest.getTestDomainName() + "/" +
                                   expected_name)
        svcobj = self._root.resolve(svcName)._narrow(CF.PropertySet)
        self.assertNotEqual(svcobj, None)
        self.assert_(obj._is_equivalent(svcobj))

        # Check that all the parameters got set correctly
        props = obj.query([])
        d = dict([(p.id, any.from_any(p.value)) for p in props])
        self.assertEqual(d["SERVICE_NAME"], expected_name)
        self.assertEqual(d["DEVICE_MGR_IOR"],
                         self._orb.object_to_string(devMgr))
        self.assertEqual(d["PARAM1"], "ABCD")
        self.assertEqual(d["PARAM2"], 42)
        self.assertAlmostEqual(d["PARAM3"], 3.1459)
        self.assertEqual(d["PARAM4"], False)
        self.assertEqual(d["PARAM5"], "Hello World")
        self.assertEqual(d.has_key("PARAM6"), False)

        # Check that we unregister correctly
        os.kill(devmgr_nb.pid, signal.SIGTERM)

        svcName = URI.stringToName(scatest.getTestDomainName() + "/" +
                                   expected_name)
        time_begin = time.time()
        time_end = time.time()
        name_found = True
        while ((time_end - time_begin) < 2) and name_found:
            time_end = time.time()
            # Don't use assertRaises, so we can simplify things
            try:
                self._root.resolve(svcName)._narrow(CF.PropertySet)
                time.sleep(0.1)
            except CosNaming.NamingContext.NotFound:
                name_found = False
        if name_found:
            self.fail("Expected service to not exist in the naming service")
示例#59
0
 def resolve_value(self, value):
     if value:
         for history_row in value:
             if isinstance(history_row.value, CORBA.Any):
                 object_list = from_any(history_row.value, True)
             else:  # this HistoryRecordList was transformed before (we got here after cache hit), so skip tranformation
                 break
             new_obj_list = []
             for obj in object_list:
                 new_obj_list.append(resolve_object(obj))
             history_row.value = new_obj_list
     if value is None:
         return fredtypes.Null()
     return value
示例#60
0
    def getData(self):
        retval = None
        if self.dataArrivedCB != None:
            return retval

        try:
            tmp = self.events.get(False, .01)
            self.logger.debug('getData: ' + str(tmp))
            retval = any.from_any(tmp)
        except:
            print traceback.print_exc()
            retval = None

        return retval