def connectPorts(outP, inPs, subscription="flush", dataflow="Push", bufferlength=1, rate=1000): if not isinstance(inPs, list): inPs = [inPs] for inP in inPs: if isConnected(outP, inP) == True: print outP.get_port_profile().name,'and',inP.get_port_profile().name,'are already connected' continue if dataTypeOfPort(outP) != dataTypeOfPort(inP): print outP.get_port_profile().name,'and',inP.get_port_profile().name,'have different data types' continue nv1 = SDOPackage.NameValue("dataport.interface_type", any.to_any("corba_cdr")) nv2 = SDOPackage.NameValue("dataport.dataflow_type", any.to_any(dataflow)) nv3 = SDOPackage.NameValue("dataport.subscription_type", any.to_any(subscription)) nv4 = SDOPackage.NameValue("dataport.buffer.length", any.to_any(str(bufferlength))) nv5 = SDOPackage.NameValue("dataport.publisher.push_rate", any.to_any(str(rate))) con_prof = RTC.ConnectorProfile("connector0", "", [outP, inP], [nv1, nv2, nv3, nv4, nv5]) ret,prof = inP.connect(con_prof) if ret != RTC.RTC_OK: print "failed to connect" continue # confirm connection if isConnected(outP, inP) == False: print "connet() returned RTC_OK, but not connected"
def test_TerminateFailUnexpectedException (self): self.preconditions() # Make the device throw a generic Python exception on terminate, which will become # a CORBA::UNKNOWN to the DomainManager props = [CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any("terminate"))] self._device.configure(props) # Test that the exception occurs as expected self.assertRaises(CORBA.UNKNOWN, self._device.terminate, 0) # Create an application. self._domMgr.installApplication("/waveforms/CapacityUsage/CapacityUsage.sad.xml") self.assertEqual(len(self._domMgr._get_applicationFactories()), 1) appFact = self._domMgr._get_applicationFactories()[0] app = appFact.create(appFact._get_identifier(), [], []) # Get the component pid, then release the app; the component will be orphaned # but the release should succeed, restoring the device's capacity. pid = app._get_componentProcessIds()[0].processId app.releaseObject() # Restore the normal operation of terminate to kill the orphan. props = [CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any(""))] self._device.configure(props) self._device.terminate(pid) # Verify that the capacity has been returned to the device. prop = CF.DataType(id="DCE:5636c210-0346-4df7-a5a3-8fd34c5540a8", value=any.to_any(None)) props = self._device.query([prop]) self.assertEqual(props[0].value._v, 100000000)
def test_pythonPropertyTypes (self): self.assertNotEqual(self._domMgr, None, "DomainManager not available") self.assertNotEqual(self._devMgr, None, "DeviceManager not available") self._app = self._launchApp("TestPythonPropsWithOverride") self.assertNotEqual(self._app, None, "Failed to launch app") # The TestPyProps component is also the assembly controller, so we can # query it via the application. props = self._app.query([CF.DataType("DCE:ffe634c9-096d-425b-86cc-df1cce50612f", any.to_any(None)), CF.DataType("test_float", any.to_any(None)), CF.DataType("test_double", any.to_any(None))]) for prop in props: if prop.id == "DCE:ffe634c9-096d-425b-86cc-df1cce50612f": prop_struct = prop if prop.id == "test_float": prop_float = prop if prop.id == "test_double": prop_double = prop self.assertEqual(prop_float.value.typecode(), CORBA.TC_float) self.assertEqual(prop_double.value.typecode(), CORBA.TC_double) for sub in prop_struct.value._v: if sub.id == 'item4': sub_type_float = sub.value.typecode() if sub.id == 'item3': sub_type_double = sub.value.typecode() self.assertEqual(sub_type_float, CORBA.TC_float) self.assertEqual(sub_type_double, CORBA.TC_double)
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})
def test_StructExternal(self): appFact = self.createAppFact("ExternalStruct") self._app = appFact.create(appFact._get_name(), [], []) self.assertNotEqual(self._app, None) # Make sure that the allocation was made to the device prop = CF.DataType(id="DCE:001fad60-b4b3-4ed2-94cb-40e1d956bf4f", value=any.to_any(None)) for dev in self._devMgr._get_registeredDevices(): if dev._get_label() == 'BasicTestDevice1': allocRes = dev.query([prop]) self.assertEquals(allocRes[0].value.value()[0].value.value(), 90) self.assertAlmostEquals(allocRes[0].value.value()[1].value.value(), 0.9) self.assertEquals(allocRes[0].value.value()[2].value.value()[0], 45) self.assertEquals(allocRes[0].value.value()[2].value.value()[1], 450) # Make sure values are deallocated on release self._app.releaseObject() self._app = None prop = CF.DataType(id="DCE:001fad60-b4b3-4ed2-94cb-40e1d956bf4f", value=any.to_any(None)) for dev in self._devMgr._get_registeredDevices(): if dev._get_label() == 'BasicTestDevice1': allocRes = dev.query([prop]) self.assertEquals(allocRes[0].value.value()[0].value.value(), 100) self.assertAlmostEquals(allocRes[0].value.value()[1].value.value(), 1.0) self.assertEquals(allocRes[0].value.value()[2].value.value()[0], 50) self.assertEquals(allocRes[0].value.value()[2].value.value()[1], 500)
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 test_DevicePlacementPropertyOverride_cpp(self): devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_ExecParamOverride_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:68dc0d3b-deb2-4fae-b898-62273b74614b" 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, "new execparam value") propId = "DCE:07350439-e917-45ef-b71f-e387a737fd9c" 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, "new configured value") try: propId = "DCE:07350439-e917-45ef-b71f-a-bad-id" prop = CF.DataType(id=propId, value=any.to_any(None)) result = self._app.query([prop]) self.assertTrue(False) except: self.assertTrue(True)
def _testLoggingConfigURI(self, domLoggingConfigArg, devLoggingConfigArg): """A common function used to test various forms of the log4cxx URI.""" if not domLoggingConfigArg: domLoggingConfigArg = "" domNB, domMgr = self.launchDomainManager(loggingURI=domLoggingConfigArg) self.assertNotEqual(domMgr, None) 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") domLoggingConfigURI = result[0].value._v # Launch a device manager if not devLoggingConfigArg: devLoggingConfigArg = "" devNB, devMgr = self.launchDeviceManager("/nodes/test_EmptyNode/DeviceManager.dcd.xml", loggingURI=devLoggingConfigArg) self.assertNotEqual(devMgr, None) prop = CF.DataType(id="LOGGING_CONFIG_URI", value=any.to_any(None)) result = devMgr.query([prop]) self.assertEqual(len(result), 1) self.assertEqual(result[0].id, "LOGGING_CONFIG_URI") devLoggingConfigURI = result[0].value._v return domLoggingConfigURI, devLoggingConfigURI
def test_DeviceExecParamOverride(self): devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml") self.assertNotEqual(devMgr, None) props = devMgr.query([]) # 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 execparam get's sent to Device device = devMgr._get_registeredDevices()[0] propId = "DCE:c03e148f-e9f9-4d70-aa00-6e23d33fa648" prop = CF.DataType(id=propId, value=any.to_any(None)) try: result = device.query([prop]) except: pass 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, "path/to/some/config/file") # Test that the DCD file execparam that are readonly get sent the default value in the PRF file device = devMgr._get_registeredDevices()[0] propId = "DCE:6f5881b3-433e-434b-8204-d39c89ff4be2" prop = CF.DataType(id=propId, value=any.to_any(None)) try: result = device.query([prop]) except: pass self.assertEqual(len(result), 1) self.assertEqual(result[0].id, propId) # This should not have been overrided by the dcd self.assertEqual(result[0].value._v, "DefaultValueGood") # Test whether the execparam "ImplementationSpecificProperty" was overloaded properly from the implementation-specific PRF file propId = "DCE:dc4289a8-bb98-435b-b914-305ffaa7594f" prop = CF.DataType(id=propId, value=any.to_any(None)) try: result = device.query([prop]) except: pass self.assertEqual(len(result), 1) self.assertEqual(result[0].id, propId) # This should have been overrided by the implementation-specific PRF file self.assertEqual(result[0].value._v, "NewLinuxx86Value") # Test whether the implementation-specific execparam property get's overloaded by the DCD propId = "DCE:716ea1c4-059a-4b18-8b66-74804bd8d435" prop = CF.DataType(id=propId, value=any.to_any(None)) try: result = device.query([prop]) except: pass self.assertEqual(len(result), 1) self.assertEqual(result[0].id, propId) # This should have been overrided by the implementation-specific PRF file self.assertEqual(result[0].value._v, "OverloadedTheImplementationSpecific") self.assertNotEqual(result[0].value._v, "NewLinuxx86Value2")
def test_NilProperty(self): self.preconditions() # Use the prop_str property for this test. prop = CF.DataType("DCE:4e7c1977-5f53-4061-bae7-cb8c1072f4b7", any.to_any(None)) # Check that the default value is not 'None'. propVal = self._app.query([prop])[0] self.assertNotEqual(propVal.value.value(), None) # Enable nil values for the property. prop.value = any.to_any(True) self._app.runTest(2, [prop]) # Explicitly configure the value to None and verify that it reports back # as 'None'. prop.value = any.to_any(None) self._app.configure([prop]) propVal = self._app.query([prop])[0] self.assertEqual(propVal.value.value(), None) # Clear the property's nil status and check that it no longer returns # 'None'. prop.value = any.to_any(False) self._app.runTest(3, [prop]) propVal = self._app.query([prop])[0] self.assertNotEqual(propVal.value.value(), None)
def create(stream_id, frontend_status, identifier = 'my_id', collector_frequency = -1.0 ): _sri = BULKIO.StreamSRI(hversion=1, xstart=0.0, xdelta=1.0, xunits=BULKIO.UNITS_TIME, subsize=0, ystart=0.0, ydelta=0.0, yunits=BULKIO.UNITS_NONE, mode=0, streamID=stream_id, blocking=False, keywords=[]) if frontend_status.sample_rate <= 0.0: _sri.xdelta = 1.0 else: _sri.xdelta = 1/frontend_status.sample_rate if collector_frequency < 0: colFreq = frontend_status.center_frequency else: colFreq = float(collector_frequency) _col_rf = CF.DataType(id='COL_RF', value=_any.to_any(colFreq)) _col_rf.value._t = CORBA.TC_double _sri.keywords.append(_col_rf) _chan_rf = CF.DataType(id='CHAN_RF', value=_any.to_any(frontend_status.center_frequency)) _chan_rf.value._t = CORBA.TC_double _sri.keywords.append(_chan_rf) _rf_flow_id = CF.DataType(id='FRONTEND::RF_FLOW_ID', value=_any.to_any(frontend_status.rf_flow_id)) _sri.keywords.append(_rf_flow_id) _bw_rf = CF.DataType(id='FRONTEND::BANDWIDTH', value=_any.to_any(frontend_status.bandwidth)) _bw_rf.value._t = CORBA.TC_double _sri.keywords.append(_bw_rf) _dev_id = CF.DataType(id='FRONTEND::DEVICE_ID', value=_any.to_any(identifier)) _sri.keywords.append(_dev_id) return _sri
def createVideoAllocation(video_type='CAPTURE',allocation_id=None,channels=0,frame_height=0,frame_width=0, fps=0.0,fps_tolerance=10.0,device_control=True,returnDict=True): if returnDict: retval = {'FRONTEND::video_allocation':{'FRONTEND::video_allocation::video_type':video_type,'FRONTEND::video_allocation::allocation_id':allocation_id, 'FRONTEND::video_allocation::channels':channels,'FRONTEND::video_allocation::frame_height':frame_height, 'FRONTEND::video_allocation::frame_width':frame_width,'FRONTEND::video_allocation::fps':fps, 'FRONTEND::video_allocation::fps_tolerance':fps_tolerance,'FRONTEND::video_allocation::device_control':device_control}} if allocation_id == None: retval['FRONTEND::video_allocation']['FRONTEND::video_allocation::allocation_id']=model._uuidgen() else: alloc=[] alloc.append(CF.DataType(id='FRONTEND::video_allocation::video_type',value=any.to_any(video_type))) if allocation_id == None: alloc.append(CF.DataType(id='FRONTEND::video_allocation::allocation_id',value=any.to_any(model._uuidgen()))) else: alloc.append(CF.DataType(id='FRONTEND::video_allocation::allocation_id',value=any.to_any(allocation_id))) alloc.append(CF.DataType(id='FRONTEND::video_allocation::channels',value=any.to_any(channels))) alloc[-1].value._t = CORBA.TC_long alloc.append(CF.DataType(id='FRONTEND::video_allocation::frame_height',value=any.to_any(frame_height))) alloc[-1].value._t = CORBA.TC_long alloc.append(CF.DataType(id='FRONTEND::video_allocation::frame_width',value=any.to_any(frame_width))) alloc[-1].value._t = CORBA.TC_long alloc.append(CF.DataType(id='FRONTEND::video_allocation::fps',value=any.to_any(fps))) alloc[-1].value._t = CORBA.TC_double alloc.append(CF.DataType(id='FRONTEND::video_allocation::fps_tolerance',value=any.to_any(fps_tolerance))) alloc[-1].value._t = CORBA.TC_double alloc.append(CF.DataType(id='FRONTEND::video_allocation::device_control',value=any.to_any(device_control))) retval = CF.DataType(id='FRONTEND::video_allocation',value=CORBA.Any(CF._tc_Properties,alloc)) return retval
def test_javaPropsRangeStruct(self): self.assertNotEqual(self._domMgr, None, "DomainManager not available") self.assertNotEqual(self._devMgr, None, "DeviceManager not available") self.assertNotEqual(self._app, None, "Failed to launch app") # Test upper bounds my_struct = CF.DataType(id='my_struct', value=any.to_any([ CF.DataType(id='struct_octet', value=CORBA.Any(CORBA.TC_octet, 255)), CF.DataType(id='struct_short', value=CORBA.Any(CORBA.TC_short, 32767)), CF.DataType(id='struct_ushort', value=CORBA.Any(CORBA.TC_ushort, 65535)), CF.DataType(id='struct_long', value=CORBA.Any(CORBA.TC_long, 2147483647)), CF.DataType(id='struct_ulong', value=CORBA.Any(CORBA.TC_ulong, 4294967295)), CF.DataType(id='struct_longlong', value=CORBA.Any(CORBA.TC_longlong, 9223372036854775807L)) ])) self._app.configure([my_struct]) res = self._app.query([]) for r in res: if r.id == 'my_struct': val = r.value.value() for v in val: if v.id == 'struct_octet': self.assertEquals(v.value.value(), 255) elif v.id == 'struct_short': self.assertEquals(v.value.value(), 32767) elif v.id == 'struct_ushort': self.assertEquals(v.value.value(), 65535) elif v.id == 'struct_long': self.assertEquals(v.value.value(), 2147483647) elif v.id == 'struct_ulong': self.assertEquals(v.value.value(), 4294967295) elif v.id == 'struct_longlong': self.assertEquals(v.value.value(), 9223372036854775807L) # Test lower bounds my_struct = CF.DataType(id='my_struct', value=any.to_any([ CF.DataType(id='struct_octet', value=CORBA.Any(CORBA.TC_octet, 0)), CF.DataType(id='struct_short', value=CORBA.Any(CORBA.TC_short, -32768)), CF.DataType(id='struct_ushort', value=CORBA.Any(CORBA.TC_ushort, 0)), CF.DataType(id='struct_long', value=CORBA.Any(CORBA.TC_long, -2147483648)), CF.DataType(id='struct_ulong', value=CORBA.Any(CORBA.TC_ulong, 0)), CF.DataType(id='struct_longlong', value=CORBA.Any(CORBA.TC_longlong, -9223372036854775808L)) ])) self._app.configure([my_struct]) res = self._app.query([]) for r in res: if r.id == 'my_struct': val = r.value.value() for v in val: if v.id == 'struct_octet': self.assertEquals(v.value.value(), 0) elif v.id == 'struct_short': self.assertEquals(v.value.value(), -32768) elif v.id == 'struct_ushort': self.assertEquals(v.value.value(), 0) elif v.id == 'struct_long': self.assertEquals(v.value.value(), -2147483648) elif v.id == 'struct_ulong': self.assertEquals(v.value.value(), 0) elif v.id == 'struct_longlong': self.assertEquals(v.value.value(), -9223372036854775808L)
def test_QueryBadValue(self): """ Tests that invalid values in Python components do not break query() """ 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") pre_props = self._app.query([]) # Set the internal variable to an invalid value # NB: In the future, we may disallow the ability to set properties from # invalid values; this test will need to be updated self._app.configure([CF.DataType('test_float', any.to_any('bad string'))]) # Try querying the broken property to check that the query doesn't # throw an unexpected exception self._app.query([CF.DataType('test_float', any.to_any(None))]) # Try querying all properties to ensure that the invalid value does not # derail the entire query post_props = self._app.query([]) self.assertEqual(len(pre_props), len(post_props))
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])
def query(self, obj, operator=None): # Get the complete current value via the base class interface. value = self._query(obj) if value is None: return any.to_any(value) # Don't apply an operator if the value is already a CORBA Any, which # should only occur in the case of a (legacy) user callback. if isinstance(value, CORBA.Any): return value # Attempt to apply the operator to the returned value. try: if operator in ("[]", "[*]"): value = self._getDefaultOperator(value, operator) elif operator == "[?]": value = self._getKeysOperator(value, operator) return any.to_any(check_type_for_long(value)) elif operator == "[@]": value = self._getKeyValuePairsOperator(value, operator) return any.to_any(check_type_for_long(value)) elif operator == "[#]": value = len(self._getDefaultOperator(value, operator)) return any.to_any(check_type_for_long(value)) elif operator != None: value = self._getSliceOperator(value, operator) except Exception, e: raise AttributeError, "error processing operator '%s': '%s' %s" % (operator, e, "\n".join(traceback.format_tb(sys.exc_traceback)))
def test_LoadFailUnexpectedException (self): self.preconditions() # Make the device throw a generic Python exception on allocate, which will become # a CORBA::UNKNOWN to the DomainManager props = [CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any("load"))] self._device.configure(props) # Test that the exception occurs as expected self.assertRaises(CORBA.UNKNOWN, self._device.load, self._domMgr._get_fileMgr(), "/waveforms/CapacityUsage/CapacityUsage.sad.xml", CF.LoadableDevice.EXECUTABLE) # Try to create an application that uses capacity; it should fail, # but the failure should be handled gracefully and the device's # capacity should be restored. self._domMgr.installApplication("/waveforms/CapacityUsage/CapacityUsage.sad.xml") self.assertEqual(len(self._domMgr._get_applicationFactories()), 1) appFact = self._domMgr._get_applicationFactories()[0] try: app = appFact.create(appFact._get_identifier(), [], []) self.fail("Application should have failed due to exception") except CF.ApplicationFactory.CreateApplicationError: pass # Verify that the capacity has been returned to the device. prop = CF.DataType(id="DCE:5636c210-0346-4df7-a5a3-8fd34c5540a8", value=any.to_any(None)) props = self._device.query([prop]) self.assertEqual(props[0].value._v, 100000000)
def addModifyKeyword(self, sri, id, myValue, addOnly=False): if not addOnly: for keyword in sri.keywords: if keyword.id == id: keyword.value = any.to_any(myValue) return True sri.keywords.append(CF.DataType(id=id, value=any.to_any(myValue))) return True
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)
def test_EventAppPortConnectionSIGQUIT(self): self.localEvent = threading.Event() self.eventFlag = False self._nb_domMgr, domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile) self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_EventPortTestDevice_node/DeviceManager.dcd.xml") domainName = scatest.getTestDomainName() domMgr.installApplication("/waveforms/PortConnectFindByDomainFinderEvent/PortConnectFindByDomainFinderEvent.sad.xml") appFact = domMgr._get_applicationFactories()[0] app = appFact.create(appFact._get_name(), [], []) app.start() # Kill the domainMgr os.kill(self._nb_domMgr.pid, signal.SIGQUIT) if not self.waitTermination(self._nb_domMgr, 5.0): self.fail("Domain Manager Failed to Die") # Restart the Domain Manager (which should restore the old channel) self._nb_domMgr, domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile) newappFact = domMgr._get_applicationFactories()[0] app2 = newappFact.create(appFact._get_name(), [], []) app2.start() channelName = URI.stringToName("%s/%s" % (domainName, 'anotherChannel')) try: appChannel = self._root.resolve(channelName)._narrow(CosEventChannelAdmin.EventChannel) except: self.assertEqual(False, True) else: self.assertEqual(True, True) # resolve the producer for the event supplier_admin = appChannel.for_suppliers() _proxy_consumer = supplier_admin.obtain_push_consumer() _supplier = Supplier_i() _proxy_consumer.connect_push_supplier(_supplier._this()) # resolve the consumer for the event consumer_admin = appChannel.for_consumers() _proxy_supplier = consumer_admin.obtain_push_supplier() _consumer = Consumer_i(self) _proxy_supplier.connect_push_consumer(_consumer._this()) # a flag is raised only when two responses come back (one for each running app) _proxy_consumer.push(any.to_any("message")) self.localEvent.wait(5.0) self.assertEqual(self.eventFlag, True) self.eventFlag = False # this step tests whether the number of subscribers to the channel is restored app2.releaseObject() self.localEvent.clear() _proxy_consumer.push(any.to_any("message")) self.localEvent.wait(5.0) self.assertEqual(self.eventFlag, True) app.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 query(self, configProperties): # If the list is empty, get all props if configProperties == []: return [CF.DataType(id=i, value=any.to_any(v)) for i,v in self.params.items()] else: result = [] for p in configProperties: result.append(CF.DataType(id=p.id, value=any.to_any(self.parms[p.id]))) return result
def struct_from_dict(id, dt): '''Creates a Struct Property from a dictionary. input: - 'id': id of returned Struct Property - 'dt': dictionary containing Struct contents returns: - Struct Property is id of 'id' ''' a = [CF.DataType(id=k, value=any.to_any(check_type_for_long(v))) for k, v in dt.items()] return CF.DataType(id=id, value=any.to_any(a))
def getIdentifiers(self): props = [] for id in self.outPorts: try: value = any.to_any(self.outPorts[id]._get_identifier()) except CORBA.TRANSIENT: # If the other end is unreachable, just report the identifier # as "None" so it is clear that the connection still exists. value = any.to_any(None) props.append(CF.DataType(id=id, value=value)) return props
def _createResource(self, profile, name, execparams={}, impl=None): log.debug("Creating resource '%s' with profile '%s'", name, profile) # Pack the execparams into an array of string-valued properties properties = [CF.DataType(k, to_any(str(v))) for k, v in execparams.iteritems()] # Tell the IDE to launch a specific implementation, if given if impl is not None: properties.append(CF.DataType("__implementationID", to_any(impl))) rescFactory = self.__ide.getResourceFactoryByProfile(profile) return rescFactory.createResource(name, properties)
def test_AllocateRaiseUnexpectedException (self): devBooter_2, self._devMgr_2 = self.launchDeviceManager("/nodes/test_UnusableAllocateCapacity_node/DeviceManager.dcd.xml", debug=9) local_device = self._devMgr_2._get_registeredDevices()[0] # Cause a failure during the allocation process props = [CF.DataType(id="invalidCapacity", value=any.to_any(1000))] retval = local_device.allocateCapacity(props) self.assertEqual(retval, False) # Cause a failure during the allocation process props = [CF.DataType(id="configurationProperty", value=any.to_any(1000))] self.assertRaises(CF.Device.InvalidCapacity, local_device.allocateCapacity, props)
def testMemoryCapacityAllocation(self): ####################################################################### # Launch the device self.runGPP() ####################################################################### # Simulate regular component startup # Verify that initialize nor configure throw errors self.comp_obj.initialize() configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False) self.comp_obj.configure(configureProps) ####################################################################### # Test memory capacity qr = [CF.DataType(id="DCE:329d9304-839e-4fec-a36f-989e3b4d311d", value=any.to_any(None)), # memTotal CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(None)), # memCapacity CF.DataType(id="DCE:fc24e19d-eda9-4200-ae96-8ba2ed953128", value=any.to_any(None)), # memThreshold CF.DataType(id="DCE:6565bffd-cb09-4927-9385-2ecac68035c7", value=any.to_any(None)), # memFree ] qr = self.comp_obj.query(qr) memTotal = qr[0].value.value() memCapacity = qr[1].value.value() memThreshold = qr[2].value.value() memFree = qr[3].value.value() self.assertEqual(int(memCapacity), int(memTotal*(memThreshold/100.0))) self.assert_(memFree > 0) self.assert_(memFree < memTotal) allocateMemCapacity = memCapacity / 4 for i in xrange(1,5): # All four should succeed allocated = self.comp_obj.allocateCapacity([CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(allocateMemCapacity))]) self.assertEqual(allocated, True) qr = [CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(None))] qr = self.comp_obj.query(qr) self.assertEqual(qr[0].value.value(), memCapacity - (i*allocateMemCapacity)) # The next allocation should fail allocated = self.comp_obj.allocateCapacity([CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(allocateMemCapacity))]) self.assertEqual(allocated, False) # Deallocate and try again self.comp_obj.deallocateCapacity([CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(allocateMemCapacity))]) qr = [CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(None))] qr = self.comp_obj.query(qr) self.assertEqual(qr[0].value.value(), memCapacity - (3*allocateMemCapacity)) allocated = self.comp_obj.allocateCapacity([CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(allocateMemCapacity))]) self.assertEqual(allocated, True) r = [CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(None))] qr = self.comp_obj.query(qr) self.assertEqual(qr[0].value.value(), memCapacity - (4*allocateMemCapacity)) # Deallocate all for i in xrange(3,-1,-1): # All four should succeed self.comp_obj.deallocateCapacity([CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(allocateMemCapacity))]) qr = [CF.DataType(id="DCE:8dcef419-b440-4bcf-b893-cab79b6024fb", value=any.to_any(None))] qr = self.comp_obj.query(qr) self.assertEqual(qr[0].value.value(), memCapacity - (i*allocateMemCapacity))
def writeDataPort(port, data, tm=1.0, disconnect=True): global connector_list, orb connector_name = "writeDataPort" prof = None for p in connector_list: if p["port"]._is_equivalent(port): if port.get_connector_profile(p["prof"].connector_id).name == connector_name: prof = p["prof"] else: connector_list.remove(p) if prof is None: 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(connector_name, "", [port], [nv1, nv2, nv3]) ret, prof = port.connect(con_prof) if ret != RTC.RTC_OK: print("failed to connect") return None connector_list.append({"port":port,"prof":prof}) 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) for p in connector_list: if prof.connector_id == p["prof"].connector_id: connector_list.remove(p) else: return prof.connector_id return None
def test_InvalidConfigureProperty(self): self.preconditions() # Use the prop_str property for this test. props = [CF.DataType("not valide property id", any.to_any(None))] props.append(CF.DataType("DCE:4e7c1977-5f53-4061-bae7-cb8c1072f4b7", any.to_any(None))) # Make sure that the appropriate exception is raised self.assertRaises(CF.PropertySet.PartialConfiguration, self._app.configure, props) # Make sure that the app is still good prop = CF.DataType("DCE:4e7c1977-5f53-4061-bae7-cb8c1072f4b7", any.to_any(None)) # Check that the default value is not 'None'. propVal = self._app.query([prop])[0] self.assertNotEqual(propVal.value.value(), None)
def test_externalFail(self): appFact = self.createAppFact("ExternalFail") self.assertRaises(CF.ApplicationFactory.CreateApplicationError, appFact.create, appFact._get_name(), [], []) # Make sure that none of the allocations were made prop = CF.DataType(id="DCE:001fad60-b4b3-4ed2-94cb-40e1d956bf4f", value=any.to_any(None)) prop2 = CF.DataType(id="simple_alloc", value=any.to_any(None)) for dev in self._devMgr._get_registeredDevices(): if dev._get_label() == "BasicTestDevice1": allocRes = dev.query([prop]) elif dev._get_label() == "SADUsesDevice_1": allocRes2 = dev.query([prop2]) self.assertEquals(allocRes[0].value.value()[0].value.value(), 100) self.assertAlmostEquals(allocRes[0].value.value()[1].value.value(), 1.0) self.assertEquals(allocRes2[0].value.value(), 10)
def test_InvalidConfigureProperty(self): self.preconditions() # Use the prop_str property for this test. props = [CF.DataType("not valide property id", any.to_any(None))] props.append( CF.DataType("DCE:4e7c1977-5f53-4061-bae7-cb8c1072f4b7", any.to_any(None))) # Make sure that the appropriate exception is raised self.assertRaises(CF.PropertySet.PartialConfiguration, self._app.configure, props) # Make sure that the app is still good prop = CF.DataType("DCE:4e7c1977-5f53-4061-bae7-cb8c1072f4b7", any.to_any(None)) # Check that the default value is not 'None'. propVal = self._app.query([prop])[0] self.assertNotEqual(propVal.value.value(), None)
def _process_results( self, app, comp_name='ECM', delay=1, wait_int=1.5, enablecb=False): components = app._get_registeredComponents() comp = None for component in components: if comp_name in component.componentObject._get_identifier(): comp = component.componentObject if enablecb : component.componentObject.configure([CF.DataType( id='enablecb', value=any.to_any(True)) ]) break app.start() time.sleep(delay) mlimit=None mxmit = None mrecv=None self.assertNotEqual(comp,None) stuff = comp.query([]) self.assertNotEqual(stuff,None) pdict = props_to_dict(stuff) mlimit = pdict['msg_limit'] gotmrecv=False pcnt=0 while gotmrecv == False : stuff = comp.query([] ) stuff = comp.query([ CF.DataType( id='msg_xmit', value=any.to_any(None)) ] ) self.assertNotEqual(stuff,None) pdict = props_to_dict(stuff) mxmit = pdict['msg_xmit'] stuff = comp.query([ CF.DataType(id='msg_recv', value=any.to_any(None)) ] ) self.assertNotEqual(stuff,None) pdict = props_to_dict(stuff) mrecv = pdict['msg_recv'] if ( mlimit == mrecv and mlimit == mxmit) or pcnt == 5: gotmrecv=True continue pcnt+=1 time.sleep(wait_int) return (mlimit, mxmit, mrecv)
def test_DeallocateFailUnexpectedException (self): self.preconditions() # Make the device throw a generic Python exception on deallocate, which will become # a CORBA::UNKNOWN to the DomainManager props = [CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any("deallocateCapacity"))] self._device.configure(props) # Test that the exception occurs as expected capacity = [CF.DataType(id="DCE:5636c210-0346-4df7-a5a3-8fd34c5540a8", value=any.to_any(0))] self.assertRaises(CORBA.UNKNOWN, self._device.deallocateCapacity, capacity) # Create and release an application; the DomainManager should handle the exception # in stride. self._domMgr.installApplication("/waveforms/CapacityUsage/CapacityUsage.sad.xml") self.assertEqual(len(self._domMgr._get_applicationFactories()), 1) appFact = self._domMgr._get_applicationFactories()[0] app = appFact.create(appFact._get_identifier(), [], []) app.releaseObject()
def test_DeviceManagerURIOverride(self): # Test that the device manager DCD can override the log4cxx URI domNB, domMgr = self.launchDomainManager(loggingURI="") self.assertNotEqual(domMgr, None) # Launch a device manager devNB, devMgr = self.launchDeviceManager( "/nodes/test_LoggingBasicTestDevice_node/DeviceManager.dcd.xml", loggingURI="dev/mgr/logging.properties") self.assertNotEqual(devMgr, None) # Double check the DeviceManager LOGGING_CONFIG_URI prop = CF.DataType(id="LOGGING_CONFIG_URI", value=any.to_any(None)) result = devMgr.query([prop]) self.assertEqual(len(result), 1) self.assertEqual(result[0].id, "LOGGING_CONFIG_URI") devLoggingConfigURI = result[0].value._v expectedDevLoggingConfigUri = "file://" + os.path.join( scatest.getSdrPath(), "dev/mgr/logging.properties") self.assertEqual(devLoggingConfigURI, expectedDevLoggingConfigUri) # Check the devices exec params self.assertEqual(len(devMgr._get_registeredDevices()), 1) device = devMgr._get_registeredDevices()[0] execparams = device.query([ CF.DataType(id="DCE:85d133fd-1658-4e4d-b3ff-1443cd44c0e2", value=any.to_any(None)) ])[0] args = execparams.value._v.split() execparams = {} while len(args) > 0: name = args.pop(0) value = args.pop(0) execparams[name] = value self.assert_(execparams.has_key("LOGGING_CONFIG_URI")) devMgrFileSysIOR = self._orb.object_to_string(devMgr._get_fileSys()) 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_(devMgr._get_fileSys()._is_equivalent(execparamObj))
def deserialize(self, cdr, data_type): if self._endian is not None: try: data = cdrUnmarshal( any.to_any(data_type).typecode(), cdr, self._endian) return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_OK, data except BaseException: return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_ERROR, data_type else: return OpenRTM_aist.ByteDataStreamBase.SERIALIZE_NOT_SUPPORT_ENDIAN, data_type
def newNV(name, value): try: any_val = any.to_any(value) except: print("ERROR NVUtil.newNV : Can't convert to any. ", type(value)) raise nv = SDOPackage.NameValue(name, any_val) return nv
def test_UTCTimeJava(self): prop = self._app.query( [CF.DataType('simple_utctime', any.to_any(None))]) datetime = time.localtime(prop[0].value.value().twsec) self.assertEquals(datetime.tm_year, 2017) self.assertEquals(datetime.tm_mon, 2) self.assertEquals(datetime.tm_mday, 1) self.assertEquals(datetime.tm_hour, 10) self.assertEquals(datetime.tm_min, 1) self.assertEquals(datetime.tm_sec, 0) self.assertEquals(prop[0].value.value().tfsec, 0.123) self._app.configure([CF.DataType('reset_utctime', any.to_any(True))]) prop = self._app.query( [CF.DataType('simple_utctime', any.to_any(None))]) now = time.time() self.assertEquals( abs(now - (prop[0].value.value().twsec + prop[0].value.value().tfsec)) < 0.1, True)
def test_ExternalPropOverride(self): self.assertNotEqual(self._domMgr, None) self.assertNotEqual(self._devMgr, None) self._domMgr.installApplication( '/waveforms/ExternalProperties/ExternalProperties.sad.xml') self.assertEqual(len(self._domMgr._get_applicationFactories()), 1) appFact = self._domMgr._get_applicationFactories()[0] props = [] props.append(CF.DataType(id='ext_prop_ulong', value=any.to_any(123456))) props.append( CF.DataType(id='DCE:b8f43ac8-26b5-40b3-9102-d127b84f9e4b', value=any.to_any("Override_value"))) props.append( CF.DataType(id='DCE:0a3663dd-7747-4b7f-b9cb-20f1e52e7089', value=any.to_any(98765))) props.append(CF.DataType(id='test_float', value=any.to_any(99.9))) app = appFact.create(appFact._get_name(), props, []) res = app.query([]) for r in res: if r.id == 'ext_prop_ulong': self.assertEquals(123456, r.value.value()) elif r.id == 'DCE:b8f43ac8-26b5-40b3-9102-d127b84f9e4b': self.assertEquals('Override_value', r.value.value()) elif r.id == 'DCE:0a3663dd-7747-4b7f-b9cb-20f1e52e7089': self.assertEquals(98765, r.value.value()) elif r.id == 'test_float': self.fail( 'The property "test_float" was not marked as external') # Props that are not external should not be configured comps = app._get_registeredComponents() for c in comps: if c.identifier == 'TestPythonProps_1:ExternalProperties_1': comp = c res = comp.componentObject.query([]) for r in res: if r.id == 'test_float': self.assertAlmostEquals(1.234, r.value.value()) self.assertNotAlmostEquals(99.9, r.value.value())
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))
def test_eventChannelCB(self): queue = Queue.Queue() sub = Subscriber(self._domMgr, self.channelName, dataArrivedCB=queue.put) pub = Publisher(self._domMgr, self.channelName) payload = 'hello' data = _any.to_any(payload) pub.push(data) rec_data = queue.get(timeout=1.0) self.assertEquals(rec_data._v, payload) pub.terminate() sub.terminate()
def test_externalFail(self): appFact = self.createAppFact("ExternalFail") self.assertRaises(CF.ApplicationFactory.CreateApplicationError, appFact.create, appFact._get_name(), [], []) # Make sure that none of the allocations were made prop = CF.DataType(id="DCE:001fad60-b4b3-4ed2-94cb-40e1d956bf4f", value=any.to_any(None)) prop2 = CF.DataType(id="simple_alloc", value=any.to_any(None)) for dev in self._devMgr._get_registeredDevices(): if dev._get_label() == 'BasicTestDevice1': allocRes = dev.query([prop]) elif dev._get_label() == "SADUsesDevice_1": allocRes2 = dev.query([prop2]) self.assertEquals(allocRes[0].value.value()[0].value.value(), 100) self.assertAlmostEquals(allocRes[0].value.value()[1].value.value(), 1.0) self.assertEquals(allocRes[0].value.value()[2].value.value()[0], 50) self.assertEquals(allocRes[0].value.value()[2].value.value()[1], 500) self.assertEquals(allocRes2[0].value.value(), 10)
def write(self, data): # data -> (conversion) -> CDR stream cdr_data = None if self._endian is not None: cdr_data = cdrMarshal(any.to_any(data).typecode(), data, self._endian) else: self._rtcout.RTC_ERROR("write(): endian %s is not support.",self._endian) return self.UNKNOWN_ERROR self._buffer.write(cdr_data) return self.PORT_OK
def test_pythonNamingContextOnly(self): self.setupStandalone('sdr/dom/components/py_comp/py_comp.spd.xml', 'py_comp', 'python') process, ref = execute(self, self.spd, self.impl, {}) pid = process.pid() comp_id = ref._get_identifier() self.assertEquals(comp_id, 'some_id') ref.start() time.sleep(0.5) app_id = ref.query([CF.DataType(id='app_id', value=any.to_any(None))])[0].value._v number_components = ref.query( [CF.DataType(id='number_components', value=any.to_any(None))])[0].value._v dom_id = ref.query([CF.DataType(id='dom_id', value=any.to_any(None))])[0].value._v self.assertEqual(app_id, "") self.assertEqual(number_components, -2) self.assertEqual(dom_id, "") os.kill(pid, 2)
def test_InvalidStateException(self): test_prop = CF.DataType('test_cap', value=any.to_any('foo')) self._device._set_adminState(CF.Device.LOCKED) self.assertRaises(CF.Device.InvalidState, self._device.allocateCapacity, [test_prop]) self.assertRaises(CF.Device.InvalidState, self._device.deallocateCapacity, [test_prop]) self._device._set_adminState(CF.Device.SHUTTING_DOWN) self.assertRaises(CF.Device.InvalidState, self._device.allocateCapacity, [test_prop]) self._device._set_adminState(CF.Device.UNLOCKED)
def test_ApplicationFactoryURIPassDown(self): domNB, domMgr = self.launchDomainManager(loggingURI="sca:///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 self.assertEqual(devLoggingConfigURI, "sca:///mgr/logging.properties") # 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] app = appFact.create(appFact._get_name(), [], []) # 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(), [], []) break self.assertEqual(len(domMgr._get_applications()), 2)
def test_ApplicationUsesDevice(self): self._nb_domMgr, self._domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile) self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_SADUsesDevice/DeviceManager.dcd.xml") self._domMgr.installApplication("/waveforms/SADUsesDeviceWave/SADUsesDeviceWaveExternalSimple.sad.xml") appFact = self._domMgr._get_applicationFactories()[0] app = appFact.create(appFact._get_name(), [], []) # Make sure that the allocation was made to the device prop = CF.DataType(id='simple_alloc', value=any.to_any(None)) for dev in devMgr._get_registeredDevices(): if dev._get_label() == 'SADUsesDevice_1': allocRes = dev.query([prop]) self.assertEquals(allocRes[0].value.value(), 8) # Kill the domainMgr os.kill(self._nb_domMgr.pid, signal.SIGTERM) # TODO if SIGKILL is used (simulating a nodeBooter unexpected abort, # the IOR and the newly spawned domain manager do not work if not self.waitTermination(self._nb_domMgr): self.fail("Domain Manager Failed to Die") # Start the domainMgr again self._nb_domMgr, newDomMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile) # Capacity still allocated to device prop = CF.DataType(id='simple_alloc', value=any.to_any(None)) for dev in devMgr._get_registeredDevices(): if dev._get_label() == 'SADUsesDevice_1': allocRes = dev.query([prop]) self.assertEquals(allocRes[0].value.value(), 8) # Release app to free up device capacity to make sure usesdevicecapacties was properly restored newApp = newDomMgr._get_applications()[0] newApp.releaseObject() prop = CF.DataType(id='simple_alloc', value=any.to_any(None)) for dev in devMgr._get_registeredDevices(): if dev._get_label() == 'SADUsesDevice_1': allocRes = dev.query([prop]) self.assertEquals(allocRes[0].value.value(), 10)
def test_AddAndRemoveEvents(self): app = self._rhDom.createApplication( '/waveforms/DomainEventReaderWaveform/DomainEventReaderWaveform.sad.xml' ) comp = app.comps[0] # Count Add and Remove events before starting 2nd device manager and device. def _waitFirstAddEvent(): if comp.query( [CF.DataType(id='num_add_events', value=any.to_any(None))])[0].value._v: return True else: print 'got num_add_events: 0' self.waitPredicate(_waitFirstAddEvent, 1) num_add_events = comp.query( [CF.DataType(id='num_add_events', value=any.to_any(None))])[0].value._v num_remove_events = comp.query( [CF.DataType(id='num_remove_events', value=any.to_any(None))])[0].value._v self.assertEquals(num_add_events, 1) # the waveform self.assertEquals(num_remove_events, 0) _, self._devMgr_2 = self.launchDeviceManager( "/nodes/DomainEventReader/DeviceManager.dcd.xml") self._devMgr_2.shutdown() # Count Add and Remove events after starting and stopping 2nd device manager and device. num_add_events = comp.query( [CF.DataType(id='num_add_events', value=any.to_any(None))])[0].value._v num_remove_events = comp.query( [CF.DataType(id='num_remove_events', value=any.to_any(None))])[0].value._v self.assertEquals( num_add_events, 3) # the waveform, the 2nd device manager, the 2nd device self.assertEquals(num_remove_events, 2) # the 2nd device manager, the 2nd device
def callback_file_io_message(self, msg_id, new_value): if "CLOSE" in new_value.file_operation: filename = str(new_value.filename) filename = filename.split('/')[-1] if self.requests.has_key(filename): msg_out = control_writes_i.CutResponse() msg_out.request_id = self.requests[filename] msg_out.file_location = new_value.filename self.port_response.sendMessage(msg_out) enabled_false = CF.DataType(id='recording_enabled', value=any.to_any(False)) self.FileWriter_3.componentObject.configure([enabled_false])
def test_StructProps(self): # Check expected default self.assertEqual(self.comp.struct_prop, { 'item_string': 'default', 'item_long': 0 }) # Change the value and check that it is updated newvalue = {'item_string': 'changed', 'item_long': 1000} self.comp.struct_prop = newvalue self.assertEqual(self.comp.struct_prop, newvalue) # Working directly with the CORBA values, add an invalid field to the # current value and check that it does not throw an exception. anyval = self.comp.query( [CF.DataType('struct_prop', any.to_any(None))])[0] anyval.value._v.append(CF.DataType('invalid_field', any.to_any(None))) try: self.comp.configure([anyval]) except CF.PropertySet.InvalidConfiuration: self.fail('Extra struct fields were not silently ignored')
def query(self, configProperties): self.propertySetAccess.acquire() # If the list is empty, get all props if configProperties == []: self._log.trace("query all properties") try: rv = [] for propid in self._props.keys(): if self._props.has_id(propid) and self._props.isQueryable( propid): try: value = self._props.query(propid) except Exception, e: self._log.error('Failed to query %s: %s', propid, e) value = any.to_any(None) rv.append(CF.DataType(propid, value)) except: self.propertySetAccess.release() raise # otherwise get only the requested ones else: self._log.trace("query %s properties", len(configProperties)) try: unknownProperties = [] for prop in configProperties: if self._props.has_id(prop.id) and self._props.isQueryable( prop.id): try: prop.value = self._props.query(prop.id) except Exception, e: self._log.error('Failed to query %s: %s', prop.id, e) else: self._log.warning( "property %s cannot be queried. valid Id: %s", prop.id, self._props.has_id(prop.id)) unknownProperties.append(prop) except: self.propertySetAccess.release() raise if len(unknownProperties) > 0: self._log.warning("query called with invalid properties %s", unknownProperties) self.propertySetAccess.release() raise CF.UnknownProperties(unknownProperties) rv = configProperties self.propertySetAccess.release() self._log.trace("query -> %s properties", len(rv)) return rv
def basetest_Now(self, comp_name): comp = sb.launch(comp_name) self.assertNotEqual(comp, None) cur_time = rhtime.now() comp_time = comp.rightnow.queryValue() _cur_time = cur_time.twsec + cur_time.tfsec _comp_time = comp_time.twsec + comp_time.tfsec self.assertTrue(abs(_cur_time - _comp_time) < 1, True) prop = CF.DataType(id='simple1970', value=any.to_any(None)) retval = comp.ref.query([prop]) self.assertEqual(retval[0].value._v.twsec, 0) self.assertEqual(retval[0].value._v.tfsec, 0)
def test_SimpleSequenceFromNil(self): self.preconditions() # Make sure that seq_long has at least 1 value to start seq_long = CF.DataType(id='seq_long', value=any.to_any(None)) props = self._app.query([seq_long]) self.assertNotEqual(len(props[0].value.value()), 0) # Set the sequence to 'nil' and check that it now has no values self._app.configure([seq_long]) props = self._app.query([seq_long]) self.assertEqual(len(props[0].value.value()), 0)
def basetest_Now(self, app_name): self.basetest_Overload(app_name) prop = CF.DataType(id='simple1970', value=any.to_any(None)) retval = self._app.comps[0].ref.query([prop]) self.assertEqual(retval[0].value._v.twsec, 0) self.assertEqual(retval[0].value._v.tfsec, 0) prop = CF.DataType(id='simpleSeqDefNow', value=any.to_any(None)) retval = self._app.comps[0].ref.query([prop]) self.assertEquals(len(retval[0].value._v), 1) self.assertEquals(retval[0].value._v[0].tcstatus, 1) self.assertNotEquals(retval[0].value._v[0].twsec, 0) self.assertNotEquals(retval[0].value._v[0].tfsec, 0) prop = CF.DataType(id='simpleSeqNoDef', value=any.to_any(None)) retval = self._app.comps[0].ref.query([prop]) self.assertEquals(len(retval[0].value._v), 0) prop = CF.DataType(id='simpleSeq1970', value=any.to_any(None)) retval = self._app.comps[0].ref.query([prop]) self.assertEquals(len(retval[0].value._v), 1) self.assertEquals(retval[0].value._v[0].tcstatus, 1) self.assertEquals(retval[0].value._v[0].twsec, 0) self.assertEquals(retval[0].value._v[0].tfsec, 0)
def test_ComponentPlacementPropertyOverride(self): devmgr_nb, devMgr = self.launchDeviceManager( "/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml", debug=self.debuglevel) 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 })
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
def initialize(self): """ This is called by the framework immediately after your component registers with the NameService. In general, you should add customization here and not in the __init__ constructor. If you have a custom port implementation you can override the specific implementation here with a statement similar to the following: self.some_port = MyPortImplementation() """ SigGen_base.initialize(self) self.last_xfer_len = self.xfer_len keywords = [] if self.chan_rf != -1: keywords.append(CF.DataType('CHAN_RF', any.to_any(self.chan_rf))) if self.col_rf != -1: keywords.append(CF.DataType('COL_RF', any.to_any(self.col_rf))) if self.sri_blocking == None: self.sri_blocking = False self.sri = BULKIO.StreamSRI(1, 0.0, 0.0, BULKIO.UNITS_TIME, 0, 0.0, 0.0, BULKIO.UNITS_NONE, 0, self.stream_id, self.sri_blocking, keywords) self.sriUpdate = True self.phase = 0 self.chirp = 0 self.sample_time_delta = 0.0 self.delta_phase = 0.0 self.delta_phase_offset = 0.0 self.cached_stream_id = self.stream_id self.stream_created = False self.next_time = None self._waveform = Waveform.Waveform() # Separate listeners required. Bug fixed in CF 1.10.1 self.addPropertyChangeListener("stream_id", self.prop_update_sri) self.addPropertyChangeListener("chan_rf", self.prop_update_sri2) self.addPropertyChangeListener("col_rf", self.prop_update_sri3) self.addPropertyChangeListener("sri_blocking", self.prop_update_sri_blocking)
def handle(self, logRecord): if self._enable: if self._ecm and self._pub : #print "RH_LogEventAppender::handle .... connection to ECM::Publisher rec: " + str(logRecord) eventLogLevel = ossie.logger.ConvertLog4ToCFLevel(self.level) logEvent = any.to_any(CF.LogEvent(self.prodId,self.prodName,self.prodFQN,long(logRecord.created),eventLogLevel,logRecord.getMessage())) try: self._pub.push(logEvent) except Exception, e: print "RH_LogEventAppender::handle EVENT CHANNEL, PUSH OPERATION FAILED WITH EXCEPTION " + str(e) else: print "RH_LogEventAppender::handle No EVENT CHANNEL to publish on."
def updateandPushSRI(self): self.sri.xdelta = 1.0 / self.sr self.sri.streamID = self.stream_id keywords = [] for keyword in self.keyword_dict.keys(): keywords.append( CF.DataType(keyword, any.to_any(self.keyword_dict[keyword]))) self.sri.keywords = keywords self.sri.mode = 1 try: self.outputPort.pushSRI(self.sri) except Exception, e: print "Exception on pushSRI", str(e)
def test_removeSdoServiceConsumer(self): any_val = any.to_any("3.14159") nv = SDOPackage.NameValue("PROPERTIES NAME 0", any_val) sprof = SDOPackage.ServiceProfile("test id", "INTERFACE_TYPE", [nv], SDOServiceMock()) sdoadmin = SdoServiceAdmin(MockRTC()) self.assertEqual(sdoadmin.addSdoServiceConsumer(sprof), False) sdoadmin._consumers.append(MockSdoServiceConsumer()) self.assertEqual(sdoadmin.removeSdoServiceConsumer("test id"), True) self.assertEqual(sdoadmin.addSdoServiceConsumer(sprof), False) sdoadmin._consumers.append(MockSdoServiceConsumer()) self.assertEqual(sdoadmin.removeSdoServiceConsumer("test id2"), False) return
def test_TerminateFailUnexpectedException(self): self.preconditions() # Make the device throw a generic Python exception on terminate, which will become # a CORBA::UNKNOWN to the DomainManager props = [ CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any("terminate")) ] self._device.configure(props) # Test that the exception occurs as expected self.assertRaises(CORBA.UNKNOWN, self._device.terminate, 0) # Create an application. self._domMgr.installApplication( "/waveforms/CapacityUsage/CapacityUsage.sad.xml") self.assertEqual(len(self._domMgr._get_applicationFactories()), 1) appFact = self._domMgr._get_applicationFactories()[0] app = appFact.create(appFact._get_identifier(), [], []) # Get the component pid, then release the app; the component will be orphaned # but the release should succeed, restoring the device's capacity. pid = app._get_componentProcessIds()[0].processId app.releaseObject() # Restore the normal operation of terminate to kill the orphan. props = [ CF.DataType(id="DCE:58f5720f-3a33-4056-8359-6b560613815d", value=any.to_any("")) ] self._device.configure(props) self._device.terminate(pid) # Verify that the capacity has been returned to the device. prop = CF.DataType(id="DCE:5636c210-0346-4df7-a5a3-8fd34c5540a8", value=any.to_any(None)) props = self._device.query([prop]) self.assertEqual(props[0].value._v, 100000000)