def opAnyString(self, inArg, inoutArg):
     tc = CORBA.TypeCode('IDL:omg.org/CORBA/string:1.0')
     assert inArg.typecode() == tc
     assert inArg.value() == constants.STRING_IN
     assert inoutArg.typecode() == tc
     assert inoutArg.value() == constants.STRING_INOUT_IN
     return (CORBA.Any(tc, constants.STRING_RETN),
             CORBA.Any(tc, constants.STRING_INOUT_OUT),
             CORBA.Any(tc, constants.STRING_OUT))
 def opAnyStruct(self, inArg, inoutArg):
     tc = CORBA.TypeCode('IDL:matecorba/test/VariableLengthStruct:1.0')
     assert inArg.typecode() == tc
     assert inArg.value().a == constants.STRING_IN
     assert inoutArg.typecode() == tc
     assert inoutArg.value().a == constants.STRING_INOUT_IN
     return (CORBA.Any(tc, matecorba.test.VariableLengthStruct(constants.STRING_RETN)),
             CORBA.Any(tc, matecorba.test.VariableLengthStruct(constants.STRING_INOUT_OUT)),
             CORBA.Any(tc, matecorba.test.VariableLengthStruct(constants.STRING_OUT)))
Exemplo n.º 3
0
def getRandomStruct(typeCode, compRef):
    '''
    Helper function
    '''
    structDef = getDefinition(typeCode.id())

    try:
        return getKnownBaciType(structDef._get_id())
    except:
        pass

    #determine which namespace the struct is in...
    #changes 'IDL:alma/someMod/.../struct:1.0" to
    # [ 'someMod', ...,'struct' ]
    nameHierarchy = structDef._get_id().split(':')[1].split('/')[1:]
    #Just the 'struct' part...
    structName = nameHierarchy.pop()
    moduleName = nameHierarchy.pop(0)
    LOGGER.logTrace("module=" + moduleName + "; hierarchy=" +
                    str(nameHierarchy) + "; struct=" + structName)
    #import the top module
    tGlobals = {}
    tLocals = {}
    #module object where the struct is contained
    container = __import__(moduleName, tGlobals, tLocals, [])
    if container == None:
        msg = "import of module \'" + moduleName + "\' failed"
        LOGGER.logCritical(msg)
        raise CORBA.NO_IMPLEMENT(msg)

    # Now navigate down the nested hierarchy of objects
    for h in nameHierarchy:
        previousContainer = container
        container = container.__dict__.get(h)
        if container == None:
            msg = "Name \'" + h + "\' not found in " + str(previousContainer)
            LOGGER.logCritical(msg)
            raise CORBA.NO_IMPLEMENT(msg)

    #class object for the struct
    tClass = container.__dict__.get(structName)
    if tClass == None:
        msg =  "Could not get structure \'" + structName + "\' from " \
                    + str(container)
        LOGGER.logCritical(msg)
        raise CORBA.NO_IMPLEMENT(msg)

    #create an instance of the struct using a kooky Python mechanism.
    retVal = instance(tClass)

    #populate the fields of the struct using the IFR
    for member in structDef._get_members():
        LOGGER.logTrace("Adding a member variable for: " + str(member.name))
        retVal.__dict__[member.name] = getRandomValue(
            member.type_def._get_type(), compRef)

    return retVal
Exemplo n.º 4
0
def makeNVP(name, value):
    if (type(value) == type('')):
        return CosLifeCycle.NameValuePair(name,
                                          CORBA.Any(CORBA.TC_string, value))
    elif (type(value) == type(0)):
        return CosLifeCycle.NameValuePair(name,
                                          CORBA.Any(CORBA.TC_ulong, value))
    else:
        sys.stderr.write("Unexpected type.\n")
        sys.exit(1)
    def test28_typecode(self):
        '''TypeCodes'''
        objref = factory.getAnyServer()

        inarg = CORBA.TypeCode('IDL:matecorba/test/ArrayUnion:1.0')
        inoutarg = CORBA.TypeCode('IDL:matecorba/test/AnyServer:1.0')
        retn, inout, out = objref.opTypeCode(inarg, inoutarg)

        assert retn == CORBA.TypeCode(
            'IDL:matecorba/test/VariableLengthStruct:1.0')
        assert inout == CORBA.TypeCode('IDL:matecorba/test/TestException:1.0')
        assert out == CORBA.TypeCode('IDL:matecorba/test/AnEnum:1.0')
Exemplo n.º 6
0
    def __init__(self, desc):
        if type(desc) is not types.IntType: raise CORBA.INTERNAL()
        if desc not in [
                tv_null, tv_void, tv_short, tv_long, tv_ushort, tv_ulong,
                tv_float, tv_double, tv_boolean, tv_char, tv_octet, tv_any,
                tv_TypeCode, tv_Principal, tv_longlong, tv_ulonglong,
                tv_longdouble, tv_wchar
        ]:
            raise CORBA.INTERNAL()

        self._d = desc
        self._k = CORBA.TCKind._item(desc)
Exemplo n.º 7
0
def main(args):
    orb = CORBA.ORB_init(args)
    poa = orb.resolve_initial_references("RootPOA")

    orb.register_value_factory(CORBA.id(ValueTest.Three), Three_i)

    ti = Test_i()
    to = ti._this()

    print orb.object_to_string(to)

    poa._get_the_POAManager().activate()
    orb.run()
    def test27_any_equivalence(self):
        '''anys equivalence'''

        tc = CORBA.TypeCode('IDL:matecorba/test/unionSeq:1.0')
        seq = [
            test.VariableLengthUnion(4, CORBA.TRUE),
            test.VariableLengthUnion(2, 'blah'),
            test.VariableLengthUnion(55, constants.LONG_IN)
        ]
        a = CORBA.Any(tc, seq)
        b = CORBA.Any(tc, seq)

        assert a == b
Exemplo n.º 9
0
def _convertToCorbaAny(value):
    from sys import version_info

    if version_info.major > 2:
        integers = (int, )
    else:
        integers = (
            long,  # noqa: F821
            int,
        )
    import CORBA

    t = type(value)
    if t is float:
        return CORBA.Any(CORBA.TC_double, value)
    elif isinstance(value, bool):
        return CORBA.Any(CORBA.TC_boolean, value)
    elif isinstance(value, integers):
        return CORBA.Any(CORBA.TC_longlong, value)
    elif isinstance(value, str):
        return CORBA.Any(CORBA.TC_string, value)
    elif isinstance(value, (list, tuple)):
        if isinstance(value[0], (list, tuple)):
            return CORBA.Any(CORBA.TypeCode("IDL:hpp/floatSeqSeq:1.0"), value)
        else:
            return CORBA.Any(CORBA.TypeCode("IDL:hpp/floatSeq:1.0"), value)
    else:  # Assume value is already a CORBA.Any
        return value
    def test23_any_string(self):
        '''any with strings'''
        objref = factory.getAnyServer()

        tc = CORBA.TypeCode('IDL:omg.org/CORBA/string:1.0')
        retn, inout, out = objref.opAnyString(
            CORBA.Any(tc, constants.STRING_IN),
            CORBA.Any(tc, constants.STRING_INOUT_IN))

        assert retn.typecode() == tc
        assert retn.value() == constants.STRING_RETN
        assert inout.typecode() == tc
        assert inout.value() == constants.STRING_INOUT_OUT
        assert out.typecode() == tc
        assert out.value() == constants.STRING_OUT
Exemplo n.º 11
0
def getUnsupported(typeCode, compRef):
    '''
    Helper function
    '''
    valType = typeCode.kind()
    LOGGER.logCritical(str(valType) + " not yet supported")
    raise CORBA.NO_IMPLEMENT()
Exemplo n.º 12
0
def test(channel):
    # Prepare
    assert (channel._is_a(CosEventChannelAdmin._tc_EventChannel.id()))
    consumer_i = servant.PullConsumer_i()
    supplier_i = servant.PushSupplier_i()
    supplier_i.connect(channel)
    consumerAdmin = for_consumers(channel)

    test = "PPulS-1"  # ----------------------------------------------------------
    proxyPullSupplier = obtain_pull_supplier(consumerAdmin)
    try:
        connect_pull_consumer(proxyPullSupplier,
                              CosEventComm.PullConsumer._nil)
        push(supplier_i.pushConsumer, CORBA.Any(CORBA.TC_string, test))
        result, hasEvent = try_pull(proxyPullSupplier, time.time() + timeout)
        if (hasEvent):
            if (result.value(CORBA.TC_string) == test):
                passed(test)
            else:
                failed(test + ": wrong value (" +
                       result.value(CORBA.TC_string) + ")")
        else:
            failed(test + ": timed out")
        disconnect_pull_supplier(proxyPullSupplier)  # Tidy up
    except CORBA.Exception, ex:
        failed(test + ": got exception %s" % ex.__class__.__name__)
Exemplo n.º 13
0
def createFixedTC(digits, scale):
    if digits < 1 or digits > 31 or scale > digits:
        raise CORBA.BAD_PARAM(omniORB.BAD_PARAM_InvalidFixedPointLimits,
                              CORBA.COMPLETED_NO)

    d = (tv_fixed, digits, scale)
    return createTypeCode(d)
Exemplo n.º 14
0
 def try_pull(self):
     if (self.event):
         result = self.event
         self.event = None
         return (result, 1)
     else:
         return (CORBA.Any(CORBA.TC_long, 0), 0)
Exemplo n.º 15
0
 def setUp(self):
     self._orb = CORBA.ORB_init([''])
     test = MEDCouplingCorbaSwigTest.MEDCouplingCorbaServBasicsTest()
     f = file(test.buildFileNameForIOR(), "r")
     ior = f.read()
     self._objC = self._orb.string_to_object(ior)
     pass
Exemplo n.º 16
0
 def pull(self):
     if (self.event):
         result = self.event
         self.event = None
         return result
     else:
         raise CORBA.TRANSIENT(0, CORBA.COMPLETED_NO)
Exemplo n.º 17
0
 def equal(self, tc):
     try:
         if self._d == tc._d: return CORBA.TRUE
         else: return CORBA.FALSE
     except AttributeError:
         raise CORBA.BAD_PARAM(omniORB.BAD_PARAM_WrongPythonType,
                               CORBA.COMPLETED_NO)
Exemplo n.º 18
0
def test(channel):
    # Prepare
    assert (channel._is_a(CosEventChannelAdmin._tc_EventChannel.id()))
    consumer_i = servant.PullConsumer_i()
    consumer_i.connect(channel)
    supplier_i = servant.PushSupplier_i()
    supplierAdmin = for_suppliers(channel)

    test = "PPshC-1"  # ----------------------------------------------------------
    proxyPushConsumer = obtain_push_consumer(supplierAdmin)
    connect_push_supplier(proxyPushConsumer, CosEventComm.PushSupplier._nil)
    push(proxyPushConsumer, CORBA.Any(CORBA.TC_string, test))
    result, hasEvent = try_pull(consumer_i.pullSupplier, time.time() + timeout)
    if (hasEvent):
        if (result.value(CORBA.TC_string) == test):
            passed(test)
        else:
            failed(test + ": wrong value (" + result.value(CORBA.TC_string) +
                   ")")
    else:
        failed(test + ": timed out")
    disconnect_push_consumer(proxyPushConsumer)  # Tidy!

    test = "PPshC-3"  # ----------------------------------------------------------
    proxyPushConsumer = obtain_push_consumer(supplierAdmin)
    connect_push_supplier(proxyPushConsumer, supplier_i._this())
    try:
        connect_push_supplier(proxyPushConsumer, supplier_i._this())
        failed(test + ": no exception")
    except CosEventChannelAdmin.AlreadyConnected, ex:
        passed(test)
Exemplo n.º 19
0
    def __init__(self, objref, perm=0):
        if not isinstance(objref, CORBA.Object):
            raise CORBA.BAD_PARAM(BAD_PARAM_WrongPythonType,
                                  CORBA.COMPLETED_NO)

        self._forward = objref
        self._perm = perm
Exemplo n.º 20
0
    def setUp(self):
        self._orb = CORBA.ORB_init()
        self._poa = self._orb.resolve_initial_references("RootPOA")

        prop = OpenRTM_aist.Properties(defaults_str=configsample_spec)
        ca = OpenRTM_aist.ConfigAdmin(prop.getNode("conf"))
        self._sdoconf = Configuration_impl(ca)
Exemplo n.º 21
0
 def __init__(self, desc, parent):
     if type(desc) is not types.TupleType or \
        desc[0] != tv_value_box:
         raise CORBA.INTERNAL()
     self._d = desc
     self._k = CORBA.tk_value_box
     self._p = parent
Exemplo n.º 22
0
def main(argv):

    print "Game Server starting..."

    orb = CORBA.ORB_init(argv, CORBA.ORB_ID)
    poa = orb.resolve_initial_references("RootPOA")

    poa._get_the_POAManager().activate()

    gf_impl = GameFactory_i(poa)
    gf_id = poa.activate_object(gf_impl)
    gf_obj = poa.id_to_reference(gf_id)

    print orb.object_to_string(gf_obj)

    # Bind the GameFactory into the Naming service. This code is
    # paranoid about checking all the things which could go wrong.
    # Normally, you would assume something this fundamental works, and
    # just die with uncaught exceptions if it didn't.
    try:
        nameRoot = orb.resolve_initial_references("NameService")
        nameRoot = nameRoot._narrow(CosNaming.NamingContext)
        if nameRoot is None:
            print "NameService narrow failed!"
            sys.exit(1)

    except CORBA.ORB.InvalidName, ex:
        # This should never happen, since "NameService" is always a
        # valid name, even if it hadn't been configured.

        print "Got an InvalidName exception when resolving NameService!"
        sys.exit(1)
Exemplo n.º 23
0
def createValueTC(id, name, modifier, base, members):
    base_desc = base._d

    if modifier == CORBA.VM_TRUNCATABLE:
        if base_desc == tv_null:
            raise CORBA.BAD_PARAM(omniORB.BAD_PARAM_InvalidTypeCode,
                                  CORBA.COMPLETED_NO)
        base_ids = base_desc[5]
        if base_ids is None:
            base_ids = (id, base_desc[2])
        else:
            base_ids = (id, ) + base_ids
    else:
        base_ids = None

    dlist = [
        tv_value,
        omniORB.createUnknownValue(id, base_desc), id, name, modifier,
        base_ids, base_desc
    ]
    for m in members:
        dlist.append(m.name)
        dlist.append(m.type._d)
        dlist.append(m.access)

    return createTypeCode(tuple(dlist))
Exemplo n.º 24
0
 def __init__(self, desc):
     if type(desc) is not types.TupleType or \
        desc[0] not in [ tv_objref,
                         tv_abstract_interface,
                         tv_local_interface ]:
         raise CORBA.INTERNAL()
     self._d = desc
     self._k = CORBA.TCKind._items[desc[0]]
    def test25_any_struct(self):
        '''any with structs'''
        objref = factory.getAnyServer()

        tc = CORBA.TypeCode('IDL:matecorba/test/VariableLengthStruct:1.0')
        inarg = CORBA.Any(tc, test.VariableLengthStruct(constants.STRING_IN))
        inoutarg = CORBA.Any(
            tc, test.VariableLengthStruct(constants.STRING_INOUT_IN))

        retn, inout, out = objref.opAnyStruct(inarg, inoutarg)

        assert retn.typecode() == tc
        assert retn.value().a == constants.STRING_RETN
        assert inout.typecode() == tc
        assert inout.value().a == constants.STRING_INOUT_OUT
        assert out.typecode() == tc
        assert out.value().a == constants.STRING_OUT
Exemplo n.º 26
0
 def getEvent(self):
     t = time.time()
     x = self.radius * cos(self.omega * t)
     y = self.radius * sin(self.omega * t)
     z = 0.0
     alpha = self.omega * t
     qx, qy, qz, qw = 0.0, 0.0, sin(alpha * 0.5), cos(alpha * 0.5)
     return [
         OT_CORBA.EventAttribute(
             "position",
             CORBA.Any(CORBA.TypeCode("IDL:OT_CORBA/FloatVector:1.0"),
                       [x, y, z])),
         OT_CORBA.EventAttribute(
             "orientation",
             CORBA.Any(CORBA.TypeCode("IDL:OT_CORBA/FloatVector:1.0"),
                       [qx, qy, qz, qw])),
         OT_CORBA.EventAttribute("timestamp", any.to_any(t))
     ]
Exemplo n.º 27
0
def get_mock_enum_prop():
    '''
    Mocks enum ACS properties
    '''
    chars = CORBA.Any(CORBA.TC_string, 'STATE1, STATE2, STATE3')
    attrs = {'get_characteristic_by_name.return_value': chars}
    mock_prop = Mock()
    mock_prop.configure_mock(**attrs)
    return mock_prop
Exemplo n.º 28
0
def equals(a, b, client=None):
    """
    Compare whether the two objects a and b are the same on the server.
    param a, b object to compare.
    param client either an instance of Client or a client to the Tools interface.
    """
    import CORBA

    orb = CORBA.ORB_init()
    return a == b or orb.object_to_string(a) == orb.object_to_string(b)
Exemplo n.º 29
0
 def close(self, evt):
     if self.toplevel:
         self.toplevel = None
         try:
             self.game.unwatchGame(self.cookie)
         except CORBA.SystemException, ex:
             print "System exception trying to unwatch game:"
             print "  ", CORBA.id(ex), ex
             
         id = poa.servant_to_id(self)
         poa.deactivate_object(id)
Exemplo n.º 30
0
def from_any(any, keep_structs=0):
    """from_any(any, keep_structs=0) -- extract the data from an Any.

    If keep_structs is true, CORBA structs are left as Python
    instances; if false, structs are turned into dictionaries with
    string keys.
    """
    if not isinstance(any, CORBA.Any):
        raise CORBA.BAD_PARAM(omniORB.BAD_PARAM_WrongPythonType,
                              CORBA.COMPLETED_NO)
    return _from_desc_value(any._t._d, any._v, keep_structs)
  def setUp(self):
    orb = CORBA.ORB_init(sys.argv)
    poa = orb.resolve_initial_references("RootPOA")
    poa._get_the_POAManager().activate()

    self._mysvc = MyService_impl()
    self._mycon = OpenRTM_aist.CorbaConsumer()
    #self._mysvc._this()

    self._cpSvc = CorbaPort("MyService")
    self._cpCon = CorbaPort("MyService")
Exemplo n.º 32
0
def main(args):
    orb = CORBA.ORB_init(args)
    poa = orb.resolve_initial_references("RootPOA")

    orb.register_value_factory(CORBA.id(ValueTest.Three), Three_i)

    ti = Test_i()
    to = ti._this()

    print orb.object_to_string(to)

    poa._get_the_POAManager().activate()
    orb.run()
Exemplo n.º 33
0
    def killGame(self):
        selection = self.listbox.curselection()
        if selection == (): return
        
        index = int(selection[0])
        info  = self.gameList[index]

        try:
            info.obj.kill()
            msg = "killed"

        except CORBA.SystemException, ex:
            print "System exception trying to kill game:"
            print "  ", CORBA.id(ex), ex
            msg = "error contacting object"
Exemplo n.º 34
0
    def getGameList(self):
        """Get the list of games from the GameFactory, and populate
        the Listbox in the GUI"""

        # To make life interesting, we get the game information
        # structures one at a time from the server. It would be far
        # more sensible to get them many at a time.

        self.gameList = []
        self.listbox.delete(0,END)

        try:
            seq, iterator = self.gameFactory.listGames(0)
        except CORBA.SystemException, ex:
            print "System exception contacting GameFactory:"
            print "  ", CORBA.id(ex), ex
            return
Exemplo n.º 35
0
    def selectGame(self, evt):
        selection = self.listbox.curselection()

        if selection == (): return

        index = int(selection[0])
        info  = self.gameList[index]

        try:
            players = info.obj._get_players()
            if players == 0:
                msg = "no players yet"
            elif players == 1:
                msg = "one player waiting"
            else:
                msg = "game in progress"

        except CORBA.SystemException, ex:
            print "System exception contacting Game:"
            print "  ", CORBA.id(ex), ex
            msg = "error contacting Game object"
Exemplo n.º 36
0
    def newGameEntered(self, evt):
        name = evt.widget.get()
        self.newGameDialogue.destroy()
        self.newGameDialogue = None

        if name == "":
            self.statusMessage("You must give a non-empty name")
            return

        try:
            game = self.gameFactory.newGame(name)

        except TicTacToe.GameFactory.NameInUse:
            self.statusMessage("Game name in use")
            return

        except CORBA.SystemException, ex:
            print "System exception trying to create new game:"
            print "  ", CORBA.id(ex), ex
            self.statusMessage("System exception trying to create new game")
            return
Exemplo n.º 37
0
    def click(self, evt):
        x = evt.x / 100
        y = evt.y / 100
        try:
            self.statusMessage("Waiting for other player...")
            state = self.controller.play(x, y)
            self.drawState(state)

        except TicTacToe.GameController.SquareOccupied:
            self.statusMessage("Square already occupied")

        except TicTacToe.GameController.NotYourGo:
            self.statusMessage("Not your go")

        except TicTacToe.GameController.InvalidCoordinates:
            self.statusMessage("Eek!  Invalid coordinates")

        except CORBA.SystemException:
            print "System exception trying to contact GameController:"
            print "  ", CORBA.id(ex), ex
            self.statusMessage("System exception contacting GameController!")
Exemplo n.º 38
0
    def watchGame(self):
        selection = self.listbox.curselection()
        if selection == (): return
        
        index = int(selection[0])
        info  = self.gameList[index]

        si = Spectator_i(self.master, info.name)
        id = poa.activate_object(si)
        so = poa.id_to_reference(id)
        try:
            cookie, state = info.obj.watchGame(so)
            si.go(info.obj, cookie, state)

            self.statusMessage("Watching %s" % info.name)

        except CORBA.SystemException, ex:
            poa.deactivate_object(id)
            print "System exception trying to watch game:"
            print "  ", CORBA.id(ex), ex
            self.statusMessage("%s: system exception contacting game" % \
                               info.name)
            self.getGameList()
 def testBaseCorbaFetching(self):
     self.assertTrue(not CORBA.is_nil(self._objC))
     pass
Exemplo n.º 40
0
                stype = "noughts"
            else:
                stype = "crosses"

            pi.go(info.obj, controller, stype)

            self.statusMessage("%s: joined game as %s" % (info.name, stype))

        except TicTacToe.Game.CannotJoin, ex:
            poa.deactivate_object(id)
            self.statusMessage("%s: cannot join game" % info.name)

        except CORBA.SystemException, ex:
            poa.deactivate_object(id)
            print "System exception trying to join game:"
            print "  ", CORBA.id(ex), ex
            self.statusMessage("%s: system exception contacting game" % \
                               info.name)
            self.getGameList()

    def watchGame(self):
        selection = self.listbox.curselection()
        if selection == (): return
        
        index = int(selection[0])
        info  = self.gameList[index]

        si = Spectator_i(self.master, info.name)
        id = poa.activate_object(si)
        so = poa.id_to_reference(id)
        try:
Exemplo n.º 41
0
        pass

try:
    BooleanType
except NameError:
    class BooleanType:
        pass

try:
    bool(1)
except:
    def bool(x): return x


# Fixed type
_f = CORBA.fixed(0)
FixedType = type(_f)


def to_any(data):
    """to_any(data) -- try to return data as a CORBA.Any"""
    tc, val = _to_tc_value(data)
    return CORBA.Any(tc, val)


def _to_tc_value(data):
    """_to_tc_value(data) -- return TypeCode and value for Any insertion"""

    if data is None:
        return CORBA.TC_null, None
Exemplo n.º 42
0
#!/usr/bin/python
import CORBA
class mail:
	msg = 0
	def submit(self, msg):
		print "Message Recieved from:", msg.fr
		print "Message for:", msg.to
		for line in msg.body:
			print line
			self.msgs = self.msgs + 1;
		print "Message Served: ", self.msgs

CORBA.load_idl("msg.idl")
CORBA.load_idl("/usr/share/idl/name-service.idl")

orb = CORBA.ORB_init((), CORBA.ORB_ID)
poa = orb.resolve_initial_references("RootPOA")

servant = POA.MESSAGING.mail(mail())
poa.activate_object(servant)
ref = poa.servant_to_reference(servant)
open("./msg-server.ior","w").write(orb.object_to_string(ref))
print "Wrote IOR to file", orb.object_to_string(ref)
poa.the_POAManager.activate()
orb.run()
Exemplo n.º 43
0
        uri = 'file:%s' % directory
        print uri, action
        self.dialogs['add-repos']['local'] = uri


if __name__ == '__main__':
    conn = RepositoryConnection()
    win = RepositoryBrowserWindow(conn)
    win.connect('destroy', mainquit)
    m = win.browser.repos.main
    mainloop()
    

    
if False:
    import CORBA
    
    
    CORBA._load_idl(join(cfg['local_idl_path'], 'repos.idl'))
    from _GlobalIDL import Repos
    
    orb = CORBA.ORB_init()
    
    ior = file('ior').readline()
    
    o = orb.string_to_object(ior)
    #o.init('deb file:/mirrors/debian sid main contrib non-free')
    #o.update()
    #o.parse()

	def on_update(self):
		addr = VREP_RTC_PATH
		selfAddr = SELF_RTC_PATH

		clientNS = selfAddr.split('/')[0]
		clientAddr = selfAddr[:selfAddr.rfind(':')][len(clientNS)+1:]
		if clientNS.find(':') < 0: clientNS = clientNS+':2809'
		clientPortName = selfAddr.split(':')[1]
		hostNS = addr.split('/')[0]
		hostAddr   = addr[:addr.rfind(':')][len(hostNS)+1:]
		if hostNS.find(':') < 0: hostNS = hostNS+':2809'
		hostPortName   = addr.split(':')[1]

		robotRTCs  = {}
		rangeRTCs  = {}
		cameraRTCs = {}
		objectRTCs = {}
		otherRTCs = {}
		try:
			clientCorbaNaming = OpenRTM_aist.CorbaNaming(OpenRTM_aist.Manager.instance().getORB(), clientNS)
			root_cxt = clientCorbaNaming.getRootContext()

			def parseContext(cxt_str, cxt):
				objs = []
				bindingList, bindingIterator = cxt.list(30)
				for b in bindingList:
					if b.binding_type == CosNaming.ncontext:
						child_cxt_str = b.binding_name[0].id + '.' + b.binding_name[0].kind + '/'
						objs = objs + [cxt_str + o for o in parseContext(child_cxt_str, cxt.resolve(b.binding_name))]
					elif b.binding_type == CosNaming.nobject:
						objs.append(cxt_str + b.binding_name[0].id + '.' + b.binding_name[0].kind)
				return objs
			
			rtobjectNames = parseContext("", root_cxt)
			for rtobjectName in rtobjectNames:
				obj = clientCorbaNaming.resolve(rtobjectName)
				if CORBA.is_nil(obj):
					sys.stdout.write(' - RTObject(%s) not found' % rtobjectName)
					continue
				corbaConsumer = OpenRTM_aist.CorbaConsumer()
				corbaConsumer.setObject(obj)
				try:
					prof = corbaConsumer._ptr().get_component_profile()
					if prof.type_name == 'RobotRTC' and prof.category == 'Simulator':
						robotRTCs[rtobjectName] = corbaConsumer
					elif prof.type_name == 'RangeRTC' and prof.category == 'Simulator':
						rangeRTCs[rtobjectName] = corbaConsumer
					elif prof.type_name == 'CameraRTC' and prof.category == 'Simulator':
						cameraRTCs[rtobjectName] = corbaConsumer
					else:
						if prof.type_name == 'SimulationManager' and prof.category == 'Simulator':

							pass
						else:

							ns, path, port = self.get_host_rtc_paths()
							print clientNS + '/' + rtobjectName
							print ns+'/'+path
							if ns+'/'+path == clientNS+'/'+rtobjectName:
								pass
							else:
								otherRTCs[clientNS+'/'+rtobjectName] = corbaConsumer
				except:
					traceback.print_exc()
					pass

			print robotRTCs
			print otherRTCs
		
			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

			self._confRobotsBuffer.set(yaml.dump(get_object_profile(robotRTCs)))
			self._confRangesBuffer.set(yaml.dump(get_object_profile(rangeRTCs)))
			self._confCamerasBuffer.set(yaml.dump(get_object_profile(cameraRTCs)))

			self.rtcMenu['menu'].delete("0", "end")
			for r in otherRTCs.keys():
				self.rtcMenu['menu'].add_command(label=str(r), command= lambda x=str(r): self.synchRTCEntryBuffer.set(x))

			if len(otherRTCs.keys()) > 0:
				self.synchRTCEntryBuffer.set(otherRTCs.keys()[0])
			else:
				self.synchRTCEntryBuffer.set("")
		
		
			if self._simulator._ptr():
				retval, rtcs = self._simulator._ptr().getSynchronizingRTCs()
				if self._fullpath_to_self[0] in rtcs:
					rtcs.remove(self._fullpath_to_self[0])
				ss = yaml.dump(rtcs)
				if len(rtcs) == 1:
					ss = '[' + ss + ']'
				elif len(rtcs) == 0:
					ss = '[]'
				self._confSyncRTCsBuffer.set(ss)
			else:
				self._confSyncRTCsBuffer.set("[]")
			
		except CORBA.TRANSIENT, e:		
			print 'CORBA.TRANSIENT Exception'
	def on_connect(self):
		addr = self.connectEntryBuffer.get()
		selfAddr = self.selfEntryBuffer.get()
		
		print ' - Connecting ', selfAddr, ' ServicePort to ', addr 

		clientNS = selfAddr.split('/')[0]
		clientAddr = selfAddr[:selfAddr.rfind(':')][len(clientNS)+1:]
		if clientNS.find(':') < 0: clientNS = clientNS+':2809'
		clientPortName = selfAddr.split(':')[1]
		hostNS = addr.split('/')[0]
		hostAddr   = addr[:addr.rfind(':')][len(hostNS)+1:]
		if hostNS.find(':') < 0: hostNS = hostNS+':2809'
		hostPortName   = addr.split(':')[1]
		
		clientCorbaNaming = OpenRTM_aist.CorbaNaming(OpenRTM_aist.Manager.instance().getORB(), clientNS)

 		clientObj = clientCorbaNaming.resolve(clientAddr)
		if CORBA.is_nil(clientObj):
			sys.stdout.write(' -- Failed to connect %s' % clientAddr)
			return

		client = OpenRTM_aist.CorbaConsumer()
		client.setObject(clientObj)
		clientPorts = client._ptr().get_ports()
		clientPort = None
		for p in clientPorts:
			if p.get_port_profile().name.split('.')[1] == clientPortName:
				clientPort = p

		if not clientPort:
			sys.stdout.write(' -- Failed to find port %s' % clientPort)

		hostCorbaNaming = OpenRTM_aist.CorbaNaming(OpenRTM_aist.Manager.instance().getORB(), clientNS)

		hostObj = hostCorbaNaming.resolve(hostAddr)
		if CORBA.is_nil(hostObj):
			sys.stdout.write(' -- Failed to connect %s' % clientAddr)
			return

		host = OpenRTM_aist.CorbaConsumer()
		host.setObject(hostObj)
		hostPorts = host._ptr().get_ports()
		hostPort = None
		for p in hostPorts:
			if p.get_port_profile().name.split('.')[1] == hostPortName:
				hostPort = p

		if not hostPort:
			sys.stdout.write(' -- Failed to find port %s' % hostPort)
			return

		name = clientPortName + '_to_' + hostPortName
		connector_id = name
		ports = [hostPort, clientPort]
		properties = []
		prof = RTC.ConnectorProfile(name, connector_id, ports, properties)

		ret = hostPort.connect(prof)

		hostECList = host._ptr().get_owned_contexts();
		hostECList[0].activate_component(host._ptr());
		clientECList = client._ptr().get_owned_contexts();
		clientECList[0].activate_component(client._ptr());

		for b in self._enableAfterConnectButton:
			b.config(state=tk.NORMAL)
			pass
		
		
		pass
Exemplo n.º 46
0
def main(args):
    orb = CORBA.ORB_init(args)
    poa = orb.resolve_initial_references("RootPOA")
    poa._get_the_POAManager().activate()

    orb.register_value_factory(CORBA.id(ValueTest.Three), Three_i)

    obj = orb.string_to_object(args[1])
    obj = obj._narrow(ValueTest.Test)

    v1 = ValueTest.One("hello", 123)
    v2 = ValueTest.One("test", 42)
    v3 = ValueTest.Two(None, None)
    v4 = ValueTest.Two(v1, None)
    v5 = ValueTest.Two(v1, v2)
    v6 = ValueTest.Two(v1, v1)
    v7 = Derived.Five("abc", 456, "more")

    obj.show("Simple values")
    r1 = obj.op1(v1)
    r2 = obj.op1(v2)
    r3 = obj.op1(None)

    obj.show("Two different values")
    obj.op2(v1, v2)

    obj.show("Nil, value")
    obj.op2(None, v1)

    obj.show("Value, nil")
    obj.op2(v1, None)

    obj.show("Two nils")
    obj.op2(None, None)

    obj.show("Two references to the same value")
    obj.op2(v1, v1)

    obj.show("Value containing two nils")
    r4 = obj.op3(v3)

    obj.show("Value containing value, nil")
    r5 = obj.op3(v4)

    obj.show("Value containing val1, val2")
    r6 = obj.op3(v5)

    obj.show("Value containing two references to same value")
    r7 = obj.op3(v6)

    obj.show("Derived value (should be truncated)")
    r8 = obj.op1(v7)

    obj.show("Same derived value twice")
    obj.op2(v7, v7)

    obj.show("Base value, derived value")
    obj.op2(v1, v7)

    obj.show("Derived value, base value")
    obj.op2(v7, v1)

    obj.show("String in valuebox")
    r9  = obj.op4("Hello")

    obj.show("Empty value box")
    r10 = obj.op4(None)

    obj.show("Nil abstract interface")
    obj.op5(None)

    fi = Four_i()
    fo = fi._this()

    obj.show("Abstract interface set to object reference")
    obj.op5(fo)

    t = Three_i("experiment")
    obj.show("Abstract interface set to value")
    obj.op5(t)

    # Any tests
    a1 = CORBA.Any(ValueTest._tc_One, v1)
    a2 = CORBA.Any(Derived._tc_Five, v7)
    v8 = Derived.Six(1.234, "test")
    a3 = CORBA.Any(Derived._tc_Six, v8)
    a4 = CORBA.Any(ValueTest._tc_One, None)
    a5 = CORBA.Any(ValueTest._tc_One, v2)
    a6 = CORBA.Any(ValueTest._tc_One, v2)

    obj.show("Value in Any")
    obj.op6(a1)

    obj.show("Derived value in Any")
    obj.op6(a2)

    obj.show("Completely unknown value in any")
    obj.op6(a3)

    obj.show("Nil value in any")
    obj.op6(a4)


    obj.show("Two anys")
    obj.op7(a1, a5)

    obj.show("Same any twice")
    obj.op7(a1, a1)

    obj.show("Different anys containing same value")
    obj.op7(a5, a6)

    obj.show("Same derived value twice")
    obj.op7(a2, a2)


    obj.show("Any and value")
    obj.op8(a1, v2)

    obj.show("Any and same value")
    obj.op8(a1, v1)

    obj.show("Any and derived")
    obj.op8(a1, v7)

    obj.show("Same derived value in any and value")
    obj.op8(a2, v7)


    obj.show("Value and any")
    obj.op9(v2, a1)

    obj.show("Value and same value in any")
    obj.op9(v1, a1)

    obj.show("Derived value and any")
    obj.op9(v7, a1)

    obj.show("Same derived value as value and in any")
    obj.op9(v7, a2)

    obj.show("Empty value")
    e1 = ValueTest.Empty()
    e2 = ValueTest.Empty()
    obj.op10(e1)

    obj.show("Different empty values")
    obj.op11(e1, e2)

    obj.show("Same empty values")
    obj.op11(e1, e1)

    obj.show("Empty value, None")
    obj.op11(e1, None)

    obj.show("None, empty value")
    obj.op11(None, e1)

    obj.show("None, None")
    obj.op11(None, None)

    obj.show("Container of empty values")
    c1 = ValueTest.Container(e1, e2)
    obj.op12(c1)

    orb.destroy()