コード例 #1
0
            public void CatHandler(InterfaceMember member, Message message)
            {
                string ret    = message.GetArg(0).Value.ToString() + message.GetArg(1).Value.ToString();
                MsgArg retArg = new MsgArg("s", new object[] { ret });

                this.busObject.MethodReply(message, new MsgArg[] { retArg });
            }
コード例 #2
0
        /// <summary>
        /// Event handler which is called when a remote object tries to set the property 'name'
        /// in this service's interface.
        /// </summary>
        /// <param name="interfaceName">name of the interface containing property 'name'.</param>
        /// <param name="propertyName">name of the property whos value to set.</param>
        /// <param name="msg">contains the new value for which to set the property value.</param>
        /// <returns>ER_OK if the property value change and signal were executed sucessfully,
        /// else returns ER_BUS_BAD_SEND_PARAMETER.</returns>
        public QStatus SetHandler(string interfaceName, string propertyName, MsgArg msg)
        {
            QStatus status = QStatus.ER_OK;

            if (propertyName == "name")
            {
                string newName = msg.Value.ToString();
                try
                {
                    App.OutputLine("///////////////////////////////////////////////////////////////////////");
                    App.OutputLine("Name Property Changed (newName=" + newName + "\toldName=" + this.name + ").");
                    this.name = newName;
                    object[] obj      = { newName };
                    MsgArg   msgReply = new MsgArg("s", obj);
                    this.BusObject.Signal(string.Empty, 0, this.signalMember, new MsgArg[] { msgReply }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                    status = QStatus.ER_OK;
                }
                catch (Exception ex)
                {
                    App.OutputLine("The Name Change signal was not able to send.");
                    System.Diagnostics.Debug.WriteLine("Exception:");
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    status = QStatus.ER_BUS_BAD_SEND_PARAMETER;
                }
            }

            return(status);
        }
コード例 #3
0
        /// <summary>
        /// Event handler which is called when a remote object tries to set the property 'name'
        /// in this service's interface.
        /// </summary>
        /// <param name="interfaceName">name of the interface containing property 'name'.</param>
        /// <param name="propertyName">name of the property whos value to set.</param>
        /// <param name="msg">contains the new value for which to set the property value.</param>
        /// <returns>ER_OK if the property value change and signal were executed sucessfully,
        /// else returns ER_BUS_BAD_SEND_PARAMETER.</returns>
        public QStatus SetHandler(string interfaceName, string propertyName, MsgArg msg)
        {
            QStatus status = QStatus.ER_OK;
            if (propertyName == "name")
            {
                string newName = msg.Value.ToString();
                try
                {
                    App.OutputLine("///////////////////////////////////////////////////////////////////////");
                    App.OutputLine("Name Property Changed (newName=" + newName + "\toldName=" + this.name + ").");
                    this.name = newName;
                    object[] obj = { newName };
                    MsgArg msgReply = new MsgArg("s", obj);
                    this.BusObject.Signal(string.Empty, 0, this.signalMember, new MsgArg[] { msgReply }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                    status = QStatus.ER_OK;
                }
                catch (Exception ex)
                {
                    App.OutputLine("The Name Change signal was not able to send.");
                    System.Diagnostics.Debug.WriteLine("Exception:");
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    status = QStatus.ER_BUS_BAD_SEND_PARAMETER;
                }
            }

            return status;
        }
コード例 #4
0
        public void SetString()
        {
            MsgArg msg = new MsgArg();

            msg.Value = "ABC";
            Assert.AreEqual("ABC", msg.Value);
            Assert.AreEqual("s", msg.Signature);
        }
コード例 #5
0
        public void SetBool()
        {
            MsgArg msg = new MsgArg();

            msg.Value = true;
            Assert.AreEqual(true, msg.Value);
            Assert.AreEqual("b", msg.Signature);
        }
コード例 #6
0
        public void SetByte()
        {
            MsgArg msg = new MsgArg();

            msg.Value = (byte)9;
            Assert.AreEqual((byte)9, msg.Value);
            Assert.AreEqual("y", msg.Signature);
        }
コード例 #7
0
        public void SetDouble()
        {
            MsgArg msg = new MsgArg();

            msg.Value = 123.456;
            Assert.AreEqual(123.456, msg.Value);
            Assert.AreEqual("d", msg.Signature);
        }
コード例 #8
0
        public void SetInt32()
        {
            MsgArg msg = new MsgArg();

            msg.Value = (Int32)12345;
            Assert.AreEqual(12345, msg.Value);
            Assert.AreEqual("i", msg.Signature);
        }
コード例 #9
0
        public void SetUInt32()
        {
            MsgArg msg = new MsgArg();

            msg.Value = (UInt32)12345;
            Assert.AreEqual((uint)12345, msg.Value);
            Assert.AreEqual("u", msg.Signature);
        }
コード例 #10
0
        public void SetInt64()
        {
            MsgArg msg = new MsgArg();

            msg.Value = (Int64)12345;
            Assert.AreEqual((long)12345, msg.Value);
            Assert.AreEqual("x", msg.Signature);
        }
コード例 #11
0
        public void SetUInt16()
        {
            MsgArg msg = new MsgArg();

            msg.Value = (UInt16)12345;
            Assert.AreEqual((ushort)12345, msg.Value);
            Assert.AreEqual("q", msg.Signature);
        }
コード例 #12
0
        /// <summary>
        /// called when a signal has been sent from the signal service indicated 'name' property has
        /// changed. It prints out new value to UI
        /// </summary>
        /// <param name="member">Interface member for signal received</param>
        /// <param name="path">path to the source of the signal</param>
        /// <param name="msg">new value of the 'name' property</param>
        public void NameChangedSignalHandler(InterfaceMember member, string path, Message msg)
        {
            MsgArg msgArg  = msg.GetArg(0);
            string newName = msgArg.Value as string;

            App.OutputLine(string.Empty);
            App.OutputLine("/////////////////////////////Name Change Signal/////////////////////////////////");
            App.OutputLine("A Name Changed signal was recieved from '" + SignalConsumerGlobals.WellKnownServiceName + path + "' with a new value of '" + newName + "'");
        }
コード例 #13
0
 public MsgArgs(uint numArgs)
 {
     _msgArgs  = alljoyn_msgargs_create((UIntPtr)numArgs);
     _argArray = new MsgArg[numArgs];
     for (uint i = 0; i < numArgs; i++)
     {
         _argArray[i] = new MsgArg(this, i);
     }
 }
コード例 #14
0
ファイル: Message.cs プロジェクト: peterdocter/Coco2dxDemo
            /**
             * Return the arguments for this Message.
             *
             * @return An AllJoyn.MsgArg containing all the arguments for this Message
             */
            public MsgArg GetArgs()
            {
                IntPtr  MsgArgPtr;
                UIntPtr numArgs;

                alljoyn_message_getargs(_message, out numArgs, out MsgArgPtr);
                MsgArg args = new MsgArg(MsgArgPtr, (int)numArgs);

                return(args);
            }
コード例 #15
0
        /// <summary>
        /// Responds to a ping request.
        /// </summary>
        /// <param name="member">The parameter is not used.</param>
        /// <param name="message">arguments sent by the client</param>
        private void PingMethodHandler(InterfaceMember member, Message message)
        {
            string output = message.GetArg(0).Value as string;

            App.OutputLine(string.Format("Ping : {0}", output));
            App.OutputLine(string.Format("Reply : {0}", output));

            object[] args = { output };

            MsgArg msgReply = new MsgArg("s", args);
            this.BusObject.MethodReply(message, new MsgArg[] { msgReply });
        }
コード例 #16
0
        public void SetInt32Array()
        {
            MsgArg msg = new MsgArg();

            msg.Value = new int[] { 1, 2, 3, 4, 5 };
            Assert.AreEqual("ai", msg.Signature);
            var v = msg.Value;

            Assert.IsNotNull(v);
            Assert.IsInstanceOfType(v, typeof(int[]));
            int[] arr = (int[])v;
            Assert.AreEqual(5, arr.Length);
        }
コード例 #17
0
        /// <summary>
        /// Responds to a ping request.
        /// </summary>
        /// <param name="member">The parameter is not used.</param>
        /// <param name="message">arguments sent by the client</param>
        private void PingMethodHandler(InterfaceMember member, Message message)
        {
            string output = message.GetArg(0).Value as string;

            App.OutputLine(string.Format("Ping : {0}", output));
            App.OutputLine(string.Format("Reply : {0}", output));

            object[] args = { output };

            MsgArg msgReply = new MsgArg("s", args);

            this.BusObject.MethodReply(message, new MsgArg[] { msgReply });
        }
コード例 #18
0
 /// <summary>
 /// Sends a 'Chat' signal using the specified parameters
 /// </summary>
 /// <param name="sessionId">A unique SessionId used to contain the signal</param>
 /// <param name="msg">Message that will be sent over the 'Chat' signal</param>
 /// <param name="flags">Flags for the signal</param>
 /// <param name="ttl">Time To Live for the signal</param>
 public void SendChatSignal(uint sessionId, string msg, byte flags, ushort ttl)
 {
     try
     {
         MsgArg msgArg = new MsgArg("s", new object[] { msg });
         this.busObject.Signal(string.Empty, sessionId, this.chatSignal, new MsgArg[] { msgArg }, ttl, flags);
     }
     catch (Exception ex)
     {
         var errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.sessionOps.Output("Sending Chat Signal failed: " + errMsg);
     }
 }
コード例 #19
0
 /// <summary>
 /// This method sends a message to the person on the other end.
 /// </summary>
 /// <param name="id">The destination ID.</param>
 /// <param name="msg">The message to send.</param>
 public void SendChatSignal(uint id, string msg)
 {
     try
     {
         MsgArg msgarg = new MsgArg("s", new object[] { msg });
         this.busObject.Signal(string.Empty, id, this.chatSignalMember, new MsgArg[] { msgarg }, 0, 0);
     }
     catch (System.Exception ex)
     {
         QStatus errCode = AllJoyn.AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg  = AllJoyn.AllJoynException.GetErrorMessage(ex.HResult);
         this.hostPage.DisplayStatus("SendChatSignal Error: " + errMsg);
     }
 }
コード例 #20
0
 /// <summary>
 /// concatenates two strings sent by the client and returns the result
 /// </summary>
 /// <param name="member">Member of the interface which message contains</param>
 /// <param name="message">arguments sent by the client</param>
 public void CatMethodHandler(InterfaceMember member, Message message)
 {
     MsgArg msg = message.GetArg(0);
     MsgArg msg2 = message.GetArg(1);
     string val = msg.Value as string;
     string val2 = msg2.Value as string;
     App.OutputLine("//////////////////////////////////////////////////////////////////");
     App.OutputLine("Cat Method was called by '" + message.Sender + "' given '" + val +
                     "' and '" + val2 + "' as arguments.");
     string ret = val + val2;
     object[] obj = { ret };
     MsgArg msgReply = new MsgArg("s", obj);
     this.BusObject.MethodReply(message, new MsgArg[] { msgReply });
     App.OutputLine("The value '" + ret + "' was returned to '" + message.Sender + "'.");
 }
コード例 #21
0
            public void SayHiHandler(InterfaceMember member, Message message)
            {
                Assert.AreEqual("hello", message.GetArg(0).Value.ToString());
                MsgArg retArg = new MsgArg("s", new object[] { "aloha" });

                try
                {
                    // BUGBUG: Throws exception saying signature of the msgArg is not what was expected, but its correct.
                    this.busObject.MethodReplyWithQStatus(message, QStatus.ER_OK);
                }
                catch (Exception ex)
                {
                    string err = AllJoynException.GetExceptionMessage(ex.HResult);
                    Assert.IsFalse(true);
                }
            }
コード例 #22
0
        public void SetBoolArray()
        {
            MsgArg msg = new MsgArg();

            msg.Value = new bool[] { true, false, true };
            Assert.AreEqual("ab", msg.Signature);
            var v = msg.Value;

            Assert.IsNotNull(v);
            Assert.IsInstanceOfType(v, typeof(bool[]));
            bool[] arr = (bool[])v;
            Assert.AreEqual(3, arr.Length);
            Assert.IsTrue(arr[0]);
            Assert.IsFalse(arr[1]);
            Assert.IsTrue(arr[2]);
        }
コード例 #23
0
 /// <summary>
 /// Concatenate the two string arguments and return the result to the caller
 /// </summary>
 /// <param name="member">Method interface member entry.</param>
 /// <param name="message">The received method call message containing the two strings
 /// to concatenate</param>
 public void Cat(InterfaceMember member, Message message)
 {
     try
     {
         string arg1   = message.GetArg(0).Value as string;
         string arg2   = message.GetArg(1).Value as string;
         MsgArg retArg = new MsgArg("s", new object[] { arg1 + arg2 });
         this.busObject.MethodReply(message, new MsgArg[] { retArg });
         this.DebugPrint("Method Reply successful (ret=" + arg1 + arg2 + ")");
     }
     catch (Exception ex)
     {
         var errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.DebugPrint("Method Reply unsuccessful: " + errMsg);
     }
 }
コード例 #24
0
        /// <summary>
        /// concatenates two strings sent by the client and returns the result
        /// </summary>
        /// <param name="member">Member of the interface which message contains</param>
        /// <param name="message">arguments sent by the client</param>
        public void CatMethodHandler(InterfaceMember member, Message message)
        {
            MsgArg msg  = message.GetArg(0);
            MsgArg msg2 = message.GetArg(1);
            string val  = msg.Value as string;
            string val2 = msg2.Value as string;

            App.OutputLine("//////////////////////////////////////////////////////////////////");
            App.OutputLine("Cat Method was called by '" + message.Sender + "' given '" + val +
                           "' and '" + val2 + "' as arguments.");
            string ret = val + val2;

            object[] obj      = { ret };
            MsgArg   msgReply = new MsgArg("s", obj);

            this.BusObject.MethodReply(message, new MsgArg[] { msgReply });
            App.OutputLine("The value '" + ret + "' was returned to '" + message.Sender + "'.");
        }
コード例 #25
0
        private static string ArgValueToString(MsgArg arg)
        {
            var v = arg.Value;

            if (v is byte[])
            {
                return(string.Join(" ", ((byte[])v).Select(b => b.ToString("x2"))));
            }
            if (v is string[])
            {
                return(string.Join(" ", (string[])v));
            }
            if (v is string)
            {
                return((string)v);
            }
            return($"User defined Value\tValue: '{v?.ToString()}'\tSignature: '{arg.Signature}'");
        }
コード例 #26
0
 public MsgArg this[int i]
 {
     get
     {
         return(_argArray[i]);
     }
     set
     {
         MsgArg arg = value as MsgArg;
         if (arg != null)
         {
             if (arg._setValue != null)
             {
                 _argArray[i].Set(arg._setValue);
             }
         }
     }
 }
コード例 #27
0
ファイル: BusObject.cs プロジェクト: hybridgroup/alljoyn
 /**
  * Handle a bus attempt to write a property value to this object.
  * BusObjects that implement properties should override this method.
  * This default version just replies with QStatus.BUS_NO_SUCH_PROPERTY
  *
  * @param ifcName    Identifies the interface that the property is defined on
  * @param propName  Identifies the the property to set
  * @param val        The property value to set. The type of this value is the actual value
  *                   type.
  */
 protected virtual void OnPropertySet(string ifcName, string propName, MsgArg val)
 {
 }
コード例 #28
0
 /// <summary>
 /// Concatenate the two string arguments and return the result to the caller
 /// </summary>
 /// <param name="member">Method interface member entry.</param>
 /// <param name="message">The received method call message containing the two strings
 /// to concatenate</param>
 public void Cat(InterfaceMember member, Message message)
 {
     try
     {
         string arg1 = message.GetArg(0).Value as string;
         string arg2 = message.GetArg(1).Value as string;
         MsgArg retArg = new MsgArg("s", new object[] { arg1 + arg2 });
         this.busObject.MethodReply(message, new MsgArg[] { retArg });
         this.DebugPrint("Method Reply successful (ret=" + arg1 + arg2 + ")");
     }
     catch (Exception ex)
     {
         var errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.DebugPrint("Method Reply unsuccessful: " + errMsg);
     }
 }
コード例 #29
0
ファイル: BusObject.cs プロジェクト: peterdocter/Coco2dxDemo
 /**
  * Reply to a method call.
  *
  * @param message      The method call message
  * @param args     The reply arguments (can be NULL)
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus MethodReply(Message message, MsgArg args)
 {
     return(alljoyn_busobject_methodreply_args(_busObject, message.UnmanagedPtr, args.UnmanagedPtr,
                                               (UIntPtr)args.Length));
 }
コード例 #30
0
 public void CatHandler(InterfaceMember member, Message message)
 {
     string ret = message.GetArg(0).Value.ToString() + message.GetArg(1).Value.ToString();
     MsgArg retArg = new MsgArg("s", new object[] { ret });
     this.busObject.MethodReply(message, new MsgArg[] { retArg });
 }
コード例 #31
0
        public void AddMatchTest()
        {
            BusAttachment  bus    = new BusAttachment("addmatch", true, 4);
            AddMatchBusObj busObj = new AddMatchBusObj(bus);
            BusListener    bl     = new BusListener(bus);

            bus.RegisterBusListener(bl);
            busObj.MatchValid = true;
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment service = new BusAttachment("service", true, 4);
            BusObject     busObj2 = new BusObject(service, "/serviceTest", false);

            InterfaceDescription[] intf = new InterfaceDescription[1];
            service.CreateInterface("org.alljoyn.addmatchtest", intf, false);
            intf[0].AddSignal("testSig", "s", "str", (byte)0, "");
            intf[0].Activate();
            busObj2.AddInterface(intf[0]);
            service.RegisterBusObject(busObj2);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.addmatch", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(43, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                                                                       ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.addmatch", TransportMaskType.TRANSPORT_ANY);

            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
            {
                if (namePrefix == "org.alljoyn.addmatch")
                {
                    foundService.Set();
                }
            });
            bus.FindAdvertisedName("org.alljoyn.addmatch");

            foundService.WaitOne();
            Task <JoinSessionResult> join = bus.JoinSessionAsync("org.alljoyn.addmatch", 43, new SessionListener(bus),
                                                                 new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY),
                                                                 new SessionOpts[1], null).AsTask <JoinSessionResult>();

            join.Wait();
            Assert.IsTrue(QStatus.ER_OK != join.Result.Status);

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }

            bus.RemoveMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = false;
            for (int i = 0; i < 10; i++)
            {
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
            }

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = true;
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }
        }
コード例 #32
0
ファイル: Client.cs プロジェクト: peterdocter/Coco2dxDemo
        /// <summary>
        /// This method is called when the advertised name is found.
        /// </summary>
        /// <param name="wellKnownName">A well known name that the remote bus is advertising.</param>
        /// <param name="transportMask">Transport that received the advertisement.</param>
        /// <param name="namePrefix">The well-known name prefix used in call to FindAdvertisedName that triggered this callback.</param>
        private async void FoundAdvertisedName(string wellKnownName, TransportMaskType transportMask, string namePrefix)
        {
            if (!string.IsNullOrEmpty(wellKnownName) && wellKnownName.CompareTo(App.ServiceName) == 0)
            {
                string foundIt = string.Format(
                                               "Client found advertised name '{0}' on {1}.",
                                               wellKnownName,
                                               transportMask.ToString());

                App.OutputLine(foundIt);

                // We found a remote bus that is advertising the well-known name so connect to it.
                bool result = await this.JoinSessionAsync();

                if (result)
                {
                    InterfaceDescription secureInterface = this.Bus.GetInterface(App.InterfaceName);

                    this.ProxyObject = new ProxyBusObject(this.Bus, App.ServiceName, App.ServicePath, 0);
                    this.ProxyObject.AddInterface(secureInterface);

                    MsgArg[] inputs = new MsgArg[1];

                    inputs[0] = new MsgArg("s", new object[] { "Client says Hello AllJoyn!" });

                    MethodCallResult callResults = null;

                    try
                    {
                        callResults = await this.ProxyObject.MethodCallAsync(App.InterfaceName, "Ping", inputs, null, 5000, 0);
                    }
                    catch (Exception ex)
                    {
                        const string ErrorFormat =
                            "ProxyObject.MethodCallAsync(\"Ping\") call produced error(s). QStatus = 0x{0:X} ('{1}').";
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        string error = string.Format(ErrorFormat, status, status.ToString());

                        System.Diagnostics.Debug.WriteLine(error);
                        App.OutputLine(error);
                    }

                    if (callResults != null)
                    {
                        Message mess = callResults.Message;
                        AllJoynMessageType messType = mess.Type;

                        if (messType == AllJoynMessageType.MESSAGE_METHOD_RET)
                        {
                            string strRet = mess.GetArg(0).Value as string;

                            if (!string.IsNullOrEmpty(strRet))
                            {
                                string output = string.Format(
                                                              "{0}.Ping (path = {1}) returned \"{2}\"",
                                                              App.InterfaceName,
                                                              App.ServicePath,
                                                              strRet);
                                App.OutputLine(output);
                            }
                            else
                            {
                                const string Error =
                                        "Error: Server returned null or empty string in response to ping.";

                                App.OutputLine(Error);
                                System.Diagnostics.Debug.WriteLine(Error);
                            }
                        }
                        else
                        {
                            string error =
                                    string.Format("Server returned message of type '{0}'.", messType.ToString());

                            App.OutputLine(error);
                            System.Diagnostics.Debug.WriteLine(error);
                        }
                    }
                }
            }
        }
コード例 #33
0
ファイル: MsgArg.cs プロジェクト: peterdocter/Coco2dxDemo
			/** @endcond */

			/**
			 * Access the indexed element in an array of MsgArgs
			 * 
			 */
			public MsgArg this[int index]
			{
				get
				{
					MsgArg ret = new MsgArg();
					ret._msgArg = alljoyn_msgarg_array_element(this._msgArg, (UIntPtr)index);
					//Prevent the code calling alljoyn_msgarg_destroy on this variable
					ret._isDisposed = true;
					return ret;
				}
				set
				{
					alljoyn_msgarg_clone(alljoyn_msgarg_array_element(this._msgArg, (UIntPtr)index), value._msgArg);
				}
			}
コード例 #34
0
        /// <summary>
        /// Connects to the bus, finds the service and sets the 'name' property to the value 
        /// specified by the user.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">Arguments associated with the click event.</param>
        private void Button_RunNameChangeClient(object sender, RoutedEventArgs e)
        {
            if (this.TextBox_Input.Text == string.Empty)
            {
                this.OutputLine("You must provide an argument to run Name Change Client!");
            }

            if (!runningClient && this.TextBox_Input.Text != string.Empty)
            {
                string newName = this.TextBox_Input.Text;
                Task task = new Task(async () =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("NameChangeApp", true, 4);
                        OutputLine("BusAttachment Created.");

                        NameChangeBusListener busListener = new NameChangeBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(NameChangeGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + NameChangeGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(NameChangeGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sOpts = new SessionOpts(
                            NameChangeGlobals.SessionProps.TrType,
                            NameChangeGlobals.SessionProps.IsMultiPoint,
                            NameChangeGlobals.SessionProps.PrType,
                            NameChangeGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            NameChangeGlobals.WellKnownServiceName, 
                            NameChangeGlobals.SessionProps.SessionPort, 
                            busListener, 
                            sOpts, 
                            sOptsOut, 
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK == status) 
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }
                        else 
                        {
                            this.OutputLine("Join Session was unsuccessful.");
                        }

                        ProxyBusObject pbo = new ProxyBusObject(busAtt, NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.ServicePath, sessionId);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await pbo.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK == status)
                            {
                                this.OutputLine("Introspection of the service object was successful.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service object was unsuccessful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            object[] obj = new object[] { newName };
                            MsgArg msg = new MsgArg("s", obj);
                            SetPropertyResult setResult = await pbo.SetPropertyAsync(NameChangeGlobals.InterfaceName, "name", msg, null, 2000);
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                        OutputLine("Error: " + ex.ToString());
                        runningClient = false;
                    }
                });
                task.Start();
            }
        }
コード例 #35
0
ファイル: MsgArgs.cs プロジェクト: hybridgroup/alljoyn
 /**
  * Constructor for MsgArgs.
  */
 public MsgArgs(uint numArgs)
 {
     _msgArg = new MsgArg(numArgs);
 }
コード例 #36
0
ファイル: MsgArg.cs プロジェクト: peterdocter/Coco2dxDemo
			/**
			 * Matches a signature to the MsArg and if the signature matches unpacks the component values of a MsgArg into an object. 
			 * This function resolved through variants, so if the MsgArg is a variant that references a 32 bit integer is can be unpacked
			 * directly into a 32 bit integer pointer.
			 *
			 *  - @c 'a'  An object containing an array 
			 *  - @c 'b'  An object containing a bool
			 *  - @c 'd'  An object containing a double (64 bits)
			 *  - @c 'g'  An object containing a string that represents an AllJoyn signature
			 *  - @c 'h'  An object containing a Socket file desciptor
			 *  - @c 'i'  An object containing an int
			 *  - @c 'n'  An object containing a short
			 *  - @c 'o'  An object containing a string that represents the name of an AllJoyn object
			 *  - @c 'q'  An object containing a ushort
			 *  - @c 's'  An object containing a string
			 *  - @c 't'  An object containing a ulong
			 *  - @c 'u'  An object containing a uint
			 *  - @c 'v'  An object containing a MsgArg
			 *  - @c 'x'  An object containing a long
			 *  - @c 'y'  An object containing a byte
			 *
			 *  - @c '(' and @c ')'  An object containing a struct
			 *  - @c '{' and @c '}'  An object containing the key and value pair of a dictonary
			 *
			 *  - @c '*' This matches any value type. This should not show up in a signature it is used by AllJoyn for matching
			 *
			 * @param      sig    The signature for MsgArg value
			 * @param[out] value  object to hold the values unpacked from the MsgArg
			 * @return
			 *      - QStatus.OK if the signature matched and MsgArg was successfully unpacked.
			 *      - QStatus.BUS_SIGNATURE_MISMATCH if the signature did not match.
			 *      - An error status otherwise
			 */
			//TODO add in examples into the Get documentation
			public QStatus Get(string sig, out object value)
			{
				QStatus status = QStatus.OK;
				value = null;
				// handle multiple signatures in one get command
				if (sig.Length > 1)
				{
					string[] sigs = splitSignature(sig);
					if (sigs.Length > 1)
					{
						//is the signature larger than the passed in MsgArg?
						if (sigs.Length > _length)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						object[] values = new object[sigs.Length];
						for (int j = 0; j < sigs.Length; ++j)
						{
							status = this[j].Get(sigs[j], out values[j]);
							if (AllJoyn.QStatus.OK != status)
							{
								return status;
							}
						}
						value = values;
						return status;
					}
				}
				switch ((AllJoynTypeId)sig[0])
				{
					case AllJoynTypeId.ALLJOYN_BYTE:
						byte y;
						status = alljoyn_msgarg_get_uint8(_msgArg, out y);
						value = y;
						break;
					case AllJoynTypeId.ALLJOYN_BOOLEAN:
						bool b;
						status = alljoyn_msgarg_get_bool(_msgArg, out b);
						value = b;
						break;
					case AllJoynTypeId.ALLJOYN_INT16:
						short n;
						status = alljoyn_msgarg_get_int16(_msgArg, out n);
						value = n;
						break;
					case AllJoynTypeId.ALLJOYN_UINT16:
						ushort q;
						status = alljoyn_msgarg_get_uint16(_msgArg, out q);
						value = q;
						break;
					case AllJoynTypeId.ALLJOYN_INT32:
						int i;
						status = alljoyn_msgarg_get_int32(_msgArg, out i);
						value = i;
						break;
					case AllJoynTypeId.ALLJOYN_UINT32:
						uint u;
						status = alljoyn_msgarg_get_uint32(_msgArg, out u);
						value = u;
						break;
					case AllJoynTypeId.ALLJOYN_INT64:
						long x;
						status = alljoyn_msgarg_get_int64(_msgArg, out x);
						value = x;
						break;
					case AllJoynTypeId.ALLJOYN_UINT64:
						ulong t;
						status = alljoyn_msgarg_get_uint64(_msgArg, out t);
						value = t;
						break;
					case AllJoynTypeId.ALLJOYN_DOUBLE:
						double d;
						status = alljoyn_msgarg_get_double(_msgArg, out d);
						value = d;
						break;
					case AllJoynTypeId.ALLJOYN_STRING:
						IntPtr s;
						status = alljoyn_msgarg_get_string(_msgArg, out s);
						value = Marshal.PtrToStringAnsi(s);
						break;
					case AllJoynTypeId.ALLJOYN_OBJECT_PATH:
						IntPtr o;
						status = alljoyn_msgarg_get_objectpath(_msgArg, out o);
						value = Marshal.PtrToStringAnsi(o);
						break;
					case AllJoynTypeId.ALLJOYN_SIGNATURE:
						IntPtr g;
						status = alljoyn_msgarg_get_signature(_msgArg, out g);
						value = Marshal.PtrToStringAnsi(g);
						break;
					case AllJoynTypeId.ALLJOYN_VARIANT:
						IntPtr v;
						status = alljoyn_msgarg_get_variant(_msgArg, out v);
						if (status)
						{
							value = new MsgArg(v);
						}
						break;
					case AllJoynTypeId.ALLJOYN_ARRAY:
						int length;
						switch ((AllJoynTypeId)sig[1])
						{
							case AllJoynTypeId.ALLJOYN_BYTE:
								IntPtr ay;
								status = alljoyn_msgarg_get_uint8_array(_msgArg, out length, out ay);
								byte[] ay_result = new byte[length];
								Marshal.Copy(ay, ay_result, 0, length);
								value = ay_result;
								break;
							case AllJoynTypeId.ALLJOYN_BOOLEAN:
								IntPtr ab;
								status = alljoyn_msgarg_get_bool_array(_msgArg, out length, out ab);
								int[] ab_result = new int[length];
								Marshal.Copy(ab, ab_result, 0, length);
								bool[] ab_retValue = new bool[length];
								for (int j = 0; j < length; j++)
								{
									if (ab_result[j] == 0)
									{
										ab_retValue[j] = false;
									}
									else
									{
										ab_retValue[j] = true;
									}
								}
								value = ab_retValue;
								break;
							case AllJoynTypeId.ALLJOYN_INT16:
								IntPtr an;
								status = alljoyn_msgarg_get_int16_array(_msgArg, out length, out an);
								short[] an_result = new short[length];
								Marshal.Copy(an, an_result, 0, length);
								value = an_result;
								break;
							case AllJoynTypeId.ALLJOYN_UINT16:
								IntPtr aq;
								status = alljoyn_msgarg_get_uint16_array(_msgArg, out length, out aq);
								short[] aq_result = new short[length];
								Marshal.Copy(aq, aq_result, 0, length);
								ShortConverter shortConverter = new ShortConverter();
								shortConverter.Shorts = aq_result;
								value = shortConverter.UShorts;
								break;
							case AllJoynTypeId.ALLJOYN_INT32:
								IntPtr ai;
								status = alljoyn_msgarg_get_int32_array(_msgArg, out length, out ai);
								int[] ai_result = new int[length];
								Marshal.Copy(ai, ai_result, 0, length);
								value = ai_result;
								break;
							case AllJoynTypeId.ALLJOYN_UINT32:
								IntPtr au;
								status = alljoyn_msgarg_get_uint32_array(_msgArg, out length, out au);
								int[] au_result = new int[length];
								Marshal.Copy(au, au_result, 0, length);

								IntConverter intConverter = new IntConverter();
								intConverter.Ints = au_result;
								value = intConverter.UInts;
								break;
							case AllJoynTypeId.ALLJOYN_INT64:
								IntPtr ax;
								status = alljoyn_msgarg_get_int64_array(_msgArg, out length, out ax);
								long[] ax_result = new long[length];
								Marshal.Copy(ax, ax_result, 0, length);
								value = ax_result;
								break;
							case AllJoynTypeId.ALLJOYN_UINT64:
								IntPtr at;
								status = alljoyn_msgarg_get_uint64_array(_msgArg, out length, out at);
								long[] at_result = new long[length];
								Marshal.Copy(at, at_result, 0, length);

								LongConverter longConverter = new LongConverter();
								longConverter.Longs = at_result;
								value = longConverter.ULongs;
								break;
							case AllJoynTypeId.ALLJOYN_DOUBLE:
								IntPtr ad;
								status = alljoyn_msgarg_get_double_array(_msgArg, out length, out ad);
								double[] ad_result = new double[length];
								Marshal.Copy(ad, ad_result, 0, length);
								value = ad_result;
								break;
							case AllJoynTypeId.ALLJOYN_STRING:
								IntPtr sa;
								status = alljoyn_msgarg_get_variant_array(_msgArg, "as", out length, out sa);
								if (status)
								{
									string[] as_result = new string[length];
									for (int j = 0; j < length; ++j)
									{
										if (status)
										{
											IntPtr inner_s;
											status = alljoyn_msgarg_get_string(alljoyn_msgarg_array_element(sa, (UIntPtr)j), out inner_s);
											as_result[j] = Marshal.PtrToStringAnsi(inner_s);
										}
										else
										{
											break;
										}
									}
									value = as_result;
								}
								break;
							case AllJoynTypeId.ALLJOYN_OBJECT_PATH:
								IntPtr ao;
								status = alljoyn_msgarg_get_variant_array(_msgArg, "ao", out length, out ao);
								if (status)
								{
									string[] ao_result = new string[length];
									for (int j = 0; j < length; ++j)
									{
										if (status)
										{
											IntPtr inner_o;
											status = alljoyn_msgarg_get_objectpath(alljoyn_msgarg_array_element(ao, (UIntPtr)j), out inner_o);
											ao_result[j] = Marshal.PtrToStringAnsi(inner_o);
										}
										else
										{
											break;
										}
									}
									value = ao_result;
								}
								break;
							case AllJoynTypeId.ALLJOYN_SIGNATURE:
								IntPtr ag;
								status = alljoyn_msgarg_get_variant_array(_msgArg, "ag", out length, out ag);
								if (status)
								{
									string[] ag_result = new string[length];
									for (int j = 0; j < length; ++j)
									{
										if (status)
										{
											IntPtr inner_g;
											status = alljoyn_msgarg_get_signature(alljoyn_msgarg_array_element(ag, (UIntPtr)j), out inner_g);
											ag_result[j] = Marshal.PtrToStringAnsi(inner_g);
										}
										else
										{
											break;
										}
									}
									value = ag_result;
								}
								break;
							case AllJoynTypeId.ALLJOYN_VARIANT:
								IntPtr av;
								status = alljoyn_msgarg_get_variant_array(_msgArg, "av", out length, out av);
								if (status)
								{
									MsgArg av_result = new MsgArg(av);
									av_result._length = length;
									value = av_result;
								}
								break;
							case AllJoynTypeId.ALLJOYN_DICT_ENTRY_OPEN:
								int dict_size = alljoyn_msgarg_get_array_numberofelements(_msgArg);
								System.Collections.Generic.Dictionary<object, object> dict = new System.Collections.Generic.Dictionary<object, object>();
								// signature of form a{KV} where key is always one letter value
								// just must be a complete signature lenght - 1 for K  - 2 for 'a{' and '}'
								string key_sig = sig.Substring(2, 1);
								string value_sig = sig.Substring(3, sig.Length - 4);
								if (key_sig == null || value_sig == null)
								{
									status = AllJoyn.QStatus.BUS_SIGNATURE_MISMATCH;
								}
								for (int j = 0; j < dict_size; ++j)
								{
									IntPtr inner_data_ptr;
									alljoyn_msgarg_get_array_element(_msgArg, (UIntPtr)j, out inner_data_ptr);
									Object actualKey;
									Object actualValue;
									MsgArg key_MsgArg = new MsgArg(alljoyn_msgarg_getkey(inner_data_ptr));
									MsgArg value_MsgArg = new MsgArg(alljoyn_msgarg_getvalue(inner_data_ptr));
									key_MsgArg.Get(key_sig, out actualKey);
									value_MsgArg.Get(value_sig, out actualValue);
									dict.Add(actualKey, actualValue);
								}
								value = dict;
								break;
							case AllJoynTypeId.ALLJOYN_STRUCT_OPEN:
								int struct_array_size = alljoyn_msgarg_get_array_numberofelements(_msgArg);
								MsgArg struct_array = new MsgArg(struct_array_size);
								for (int j = 0; j < struct_array_size; ++j)
								{
									IntPtr struct_array_ptr;
									alljoyn_msgarg_get_array_element(_msgArg, (UIntPtr)j, out struct_array_ptr);
									AllJoyn.MsgArg tmp = new MsgArg(struct_array_ptr);
									struct_array[j] = tmp;
								}
								value = struct_array;
								break;
							case AllJoynTypeId.ALLJOYN_ARRAY:
								int outer_array_size = alljoyn_msgarg_get_array_numberofelements(_msgArg);
								object[] outerArray = new object[outer_array_size];
								for (int j = 0; j < outer_array_size; j++)
								{
									if (status)
									{
										IntPtr inner_data_ptr;
										alljoyn_msgarg_get_array_element(_msgArg, (UIntPtr)j, out inner_data_ptr);
										MsgArg tmp = new MsgArg(inner_data_ptr);
										string inner_array_sig = Marshal.PtrToStringAnsi(alljoyn_msgarg_get_array_elementsignature(_msgArg, (UIntPtr)j));
										status = tmp.Get(inner_array_sig, out outerArray[j]);
									}
									else
									{
										break;
									}
								}
								value = outerArray;
								break;
							default:
								status = QStatus.WRITE_ERROR;
								break;
						}
						break;
					case AllJoynTypeId.ALLJOYN_STRUCT_OPEN:
						if ((AllJoynTypeId)sig[sig.Length - 1] != AllJoynTypeId.ALLJOYN_STRUCT_CLOSE)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						string[] struct_sigs = splitSignature(sig.Substring(1, sig.Length - 2));
						if (struct_sigs == null)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						int numMembers = alljoyn_msgarg_getnummembers(_msgArg);
						if (numMembers != struct_sigs.Length)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}

						object[] structObjects = new object[numMembers];
						for (int j = 0; j < struct_sigs.Length; ++j)
						{
							MsgArg arg = new MsgArg(alljoyn_msgarg_getmember(_msgArg, (UIntPtr)j));
							status = arg.Get(struct_sigs[j], out structObjects[j]);
							if (AllJoyn.QStatus.OK != status)
							{
								return status;
							}
						}
						value = structObjects;
						break;
					case AllJoynTypeId.ALLJOYN_DICT_ENTRY_OPEN:
						// A dictionary entry must start with 'a' followed by '{'
						// if it starts with '{' it is an invalid signature.
						status = QStatus.BUS_BAD_SIGNATURE;
						break;
					default:
						status = QStatus.WRITE_ERROR;
						break;
				}
				return status;
			}
コード例 #37
0
        /// <summary>
        /// Connects to the bus, finds the service and calls the 'cat' with the two 
        /// arguments "Hello " and "World!"
        /// </summary>
        /// <param name="sender">UI control which signaled the click event</param>
        /// <param name="e">arguments associated with the click event</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (!runningClient)
            {
                Task task = new Task(async () =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("ClientApp", true, 4);
                        this.OutputLine("BusAttachment Created.");

                        BasicClientBusListener basicClientBusListener = new BasicClientBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(basicClientBusListener);
                        this.OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(BasicClientGlobals.ConnectSpec);
                        this.OutputLine("Bundled Daemon Registered.");
                        this.OutputLine("BusAttachment Connected to " + BasicClientGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(BasicClientGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            BasicClientGlobals.SessionProps.TrType, 
                            BasicClientGlobals.SessionProps.IsMultiPoint, 
                            BasicClientGlobals.SessionProps.PrType, 
                            BasicClientGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            BasicClientGlobals.WellKnownServiceName,
                            BasicClientGlobals.SessionProps.SessionPort,
                            basicClientBusListener,
                            sessionOpts,
                            sOptsOut,
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK != status)
                        {
                            this.OutputLine("Joining a session with the Service was unsuccessful.");
                        }
                        else
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }

                        // Create the proxy for the service interface by introspecting the service bus object
                        ProxyBusObject proxyBusObject = new ProxyBusObject(busAtt, BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.ServicePath, 0);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await proxyBusObject.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK != status)
                            {
                                this.OutputLine("Introspection of the service bus object failed.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service bus object was successful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            // Call 'cat' method with the two string to be concatenated ("Hello" and " World!")
                            MsgArg[] catMe = new MsgArg[2];
                            catMe[0] = new MsgArg("s", new object[] { "Hello" });
                            catMe[1] = new MsgArg("s", new object[] { " World!" });

                            InterfaceDescription interfaceDescription = proxyBusObject.GetInterface(BasicClientGlobals.InterfaceName);
                            InterfaceMember interfaceMember = interfaceDescription.GetMember("cat");

                            this.OutputLine("Calling the 'cat' method of the service with args 'Hello' and ' World!'");
                            MethodCallResult callResults = await proxyBusObject.MethodCallAsync(interfaceMember, catMe, null, 100000, 0);
                            Message msg = callResults.Message;
                            if (msg.Type == AllJoynMessageType.MESSAGE_METHOD_RET)
                            {
                                string strRet = msg.GetArg(0).Value as string;
                                this.OutputLine("Sender '" + msg.Sender + "' returned the value '" + strRet + "'");
                            }
                            else
                            {
                                this.OutputLine("The 'cat' method call produced errors of type: " + msg.Type.ToString());
                            }
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                    }
                });
                task.Start();
            }
        }
コード例 #38
0
 /// <summary>
 /// This method sends a message to the person on the other end.
 /// </summary>
 /// <param name="id">The destination ID.</param>
 /// <param name="msg">The message to send.</param>
 public void SendChatSignal(uint id, string msg)
 {
     try
     {
         MsgArg msgarg = new MsgArg("s", new object[] { msg });
         this.busObject.Signal(string.Empty, id, this.chatSignalMember, new MsgArg[] { msgarg }, 0, 0);
     }
     catch (System.Exception ex)
     {
         QStatus errCode = AllJoyn.AllJoynException.GetErrorCode(ex.HResult);
         string errMsg = AllJoyn.AllJoynException.GetErrorMessage(ex.HResult);
         this.hostPage.DisplayStatus("SendChatSignal Error: " + errMsg);
     }
 }
コード例 #39
0
ファイル: BusObject.cs プロジェクト: hybridgroup/alljoyn
 /**
  * Send a signal.
  *
  * @param destination      The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
  * @param sessionId        A unique SessionId for this AllJoyn session instance
  * @param signal           Interface member of signal being emitted.
  * @param args             The arguments for the signal (can be NULL)
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal, MsgArg args)
 {
     return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, 0, 0, IntPtr.Zero);
 }
コード例 #40
0
ファイル: BusObject.cs プロジェクト: hybridgroup/alljoyn
 /**
  * Send a signal.
  *
  * @param destination      The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
  * @param sessionId        A unique SessionId for this AllJoyn session instance
  * @param signal           Interface member of signal being emitted.
  * @param args             The arguments for the signal (can be NULL)
  * @param timeToLife       If non-zero this specifies in milliseconds the useful lifetime for this
  *                         signal. If delivery of the signal is delayed beyond the timeToLive due to
  *                         network congestion or other factors the signal may be discarded. There is
  *                         no guarantee that expired signals will not still be delivered.
  * @param flags            Logical OR of the message flags for this signals. The following flags apply to signals:
  *                         - If ALLJOYN_FLAG_SESSIONLESS is set the signal will be sent out to any listener without
  *                           requireing a connected session
  *                         - If ALLJOYN_FLAG_GLOBAL_BROADCAST is set broadcast signal (null destination) will be
  *                           forwarded across bus-to-bus connections.
  *                         - If ALLJOYN_FLAG_COMPRESSED is set the header is compressed for destinations that can
  *                           handle header compression.
  *                         - If ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any
  *                           is encrypted.
  * @param msg              The sent signal message is returned to the caller.
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal,
     MsgArg args, ushort timeToLife, byte flags, Message msg)
 {
     return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, timeToLife, flags, msg.UnmanagedPtr);
 }
コード例 #41
0
ファイル: BusObject.cs プロジェクト: peterdocter/Coco2dxDemo
 /**
  * Send a signal.
  *
  * @param destination      The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
  * @param sessionId        A unique SessionId for this AllJoyn session instance
  * @param signal           Interface member of signal being emitted.
  * @param args             The arguments for the signal (can be NULL)
  * @param timeToLife       If non-zero this specifies in milliseconds the useful lifetime for this
  *                         signal. If delivery of the signal is delayed beyond the timeToLive due to
  *                         network congestion or other factors the signal may be discarded. There is
  *                         no guarantee that expired signals will not still be delivered.
  * @param flags            Logical OR of the message flags for this signals. The following flags apply to signals:
  *                         - If ALLJOYN_FLAG_SESSIONLESS is set the signal will be sent out to any listener without
  *                           requireing a connected session
  *                         - If ALLJOYN_FLAG_GLOBAL_BROADCAST is set broadcast signal (null destination) will be
  *                           forwarded across bus-to-bus connections.
  *                         - If ALLJOYN_FLAG_COMPRESSED is set the header is compressed for destinations that can
  *                           handle header compression.
  *                         - If ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any
  *                           is encrypted.
  * @param msg              The sent signal message is returned to the caller.
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal,
                          MsgArg args, ushort timeToLife, byte flags, Message msg)
 {
     return(alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, timeToLife, flags, msg.UnmanagedPtr));
 }
コード例 #42
0
 /// <summary>
 /// Sends a 'Chat' signal using the specified parameters
 /// </summary>
 /// <param name="sessionId">A unique SessionId used to contain the signal</param>
 /// <param name="msg">Message that will be sent over the 'Chat' signal</param>
 /// <param name="flags">Flags for the signal</param>
 /// <param name="ttl">Time To Live for the signal</param>
 public void SendChatSignal(uint sessionId, string msg, byte flags, ushort ttl)
 {
     try
     {
         MsgArg msgArg = new MsgArg("s", new object[] { msg });
         this.busObject.Signal(string.Empty, sessionId, this.chatSignal, new MsgArg[] { msgArg }, ttl, flags);
     }
     catch (Exception ex)
     {
         var errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.sessionOps.Output("Sending Chat Signal failed: " + errMsg);
     }
 }
コード例 #43
0
ファイル: MsgArg.cs プロジェクト: peterdocter/Coco2dxDemo
			/**
			 * Determines Equality
			 *
			 * @param arg  the MsgArg which will be compared with this MsgArg
			 *
			 * @return  Returns true if the MsgArg is has the same signatures and values.
			 */
			public bool Equals(MsgArg arg)
			{
				// If parameter is null return false.
				if ((object)arg == null)
				{
					return false;
				}
				return alljoyn_msgarg_equal(this.UnmanagedPtr, arg.UnmanagedPtr);
			}
コード例 #44
0
ファイル: JetStreamMsg.cs プロジェクト: bojanskr/nats.net
 // Take the reply and parse it into the metadata.
 internal JetStreamMsg(IConnection conn, MsgArg arg, Subscription s, byte[] payload, long totalLen) :
     base(arg, s, payload, totalLen)
 {
     Connection = conn;
     MetaData   = new MetaData(_reply);
 }
コード例 #45
0
ファイル: ProxyBusObject.cs プロジェクト: hybridgroup/alljoyn
            public QStatus MethodCallSynch(string ifaceName, string methodName, MsgArg args, Message replyMsg,
				uint timeout, byte flags)
            {
                return alljoyn_proxybusobject_methodcall(_proxyBusObject, ifaceName, methodName, args.UnmanagedPtr,
                    (UIntPtr)args.Length, replyMsg.UnmanagedPtr, timeout, flags);
            }
コード例 #46
0
        public void AddMethodHandlerTest()
        {
            BusAttachment service = new BusAttachment("methodhandler", true, 4);
            MethodHandlerBusObject busObj = new MethodHandlerBusObject(service, "/handlertest");
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            SessionPortListener spl = new SessionPortListener(service);
            spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) =>
            {
                Assert.AreEqual(33, sessionPort);
                return true;
            });
            service.RequestName("org.alljoyn.methodhandlertest", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(33, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl);
            service.AdvertiseName("org.alljoyn.methodhandlertest", TransportMaskType.TRANSPORT_ANY);

            BusAttachment client = new BusAttachment("methodcaller", true, 4);
            BusListener bl = new BusListener(client);
            client.RegisterBusListener(bl);
            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    foundMethodObjectName.Set();
                });
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.methodhandlertest");
            foundMethodObjectName.WaitOne();
            Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.methodhandlertest", 33, new SessionListener(client),
                new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask<JoinSessionResult>();
            joinTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status);
            ProxyBusObject proxy = new ProxyBusObject(client, "org.alljoyn.methodhandlertest", "/handlertest", joinTask.Result.SessionId);
            Task<IntrospectRemoteObjectResult> introTask = proxy.IntrospectRemoteObjectAsync(null).AsTask<IntrospectRemoteObjectResult>();
            introTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == introTask.Result.Status);

            MsgArg[] args1 = new MsgArg[2];
            args1[0] = new MsgArg("s", new object[] { "one" });
            args1[1] = new MsgArg("s", new object[] { "two" });
            Task<MethodCallResult> catTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("cat"),
                args1, null, 60000, (byte)0).AsTask<MethodCallResult>();
            catTask.Wait();
            Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == catTask.Result.Message.Type);
            Assert.AreEqual("onetwo", catTask.Result.Message.GetArg(0).Value.ToString());

            // Check BUGBUG above
            //MsgArg[] args2 = new MsgArg[1];
            //args2[0] = new MsgArg("s", new object[] { "hello" });
            //Task<MethodCallResult> sayHiTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("sayhi"),
            //    args2, null, 60000, (byte)0).AsTask<MethodCallResult>();
            //sayHiTask.Wait();
            //Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == sayHiTask.Result.Message.Type);
            //Assert.AreEqual("aloha", sayHiTask.Result.Message.GetArg(0).Value.ToString());

            // TODO: add another method call that test function with signature MethodReply(AllJoyn.Message msg, string error, string errorMessage)
        }
コード例 #47
0
        public void AddMatchTest()
        {
            BusAttachment bus = new BusAttachment("addmatch", true, 4);
            AddMatchBusObj busObj = new AddMatchBusObj(bus);
            BusListener bl = new BusListener(bus);
            bus.RegisterBusListener(bl);
            busObj.MatchValid = true;
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment service = new BusAttachment("service", true, 4);
            BusObject busObj2 = new BusObject(service, "/serviceTest", false);
            InterfaceDescription[] intf = new InterfaceDescription[1];
            service.CreateInterface("org.alljoyn.addmatchtest", intf, false);
            intf[0].AddSignal("testSig", "s", "str", (byte)0, "");
            intf[0].Activate();
            busObj2.AddInterface(intf[0]);
            service.RegisterBusObject(busObj2);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.addmatch", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(43, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, 
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.addmatch", TransportMaskType.TRANSPORT_ANY);

            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    if (namePrefix == "org.alljoyn.addmatch")
                    {
                        foundService.Set();
                    }
                });
            bus.FindAdvertisedName("org.alljoyn.addmatch");

            foundService.WaitOne();
            Task<JoinSessionResult> join = bus.JoinSessionAsync("org.alljoyn.addmatch", 43, new SessionListener(bus),
                            new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY),
                            new SessionOpts[1], null).AsTask<JoinSessionResult>();
            join.Wait();
            Assert.IsTrue(QStatus.ER_OK != join.Result.Status);

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }

            bus.RemoveMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = false;
            for (int i = 0; i < 10; i++)
            {
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
            }

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = true;
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }
        }
コード例 #48
0
 public void SayHiHandler(InterfaceMember member, Message message)
 {
     Assert.AreEqual("hello", message.GetArg(0).Value.ToString());
     MsgArg retArg = new MsgArg("s", new object[] { "aloha" });
     try
     {
         // BUGBUG: Throws exception saying signature of the msgArg is not what was expected, but its correct.
         this.busObject.MethodReplyWithQStatus(message, QStatus.ER_OK);
     }
     catch (Exception ex)
     {
     #if DEBUG
         string err = AllJoynException.GetErrorMessage(ex.HResult);
     #else
         QStatus err = AllJoynException.FromCOMException(ex.HResult);
     #endif
         Assert.IsFalse(true);
     }
 }
コード例 #49
0
ファイル: BusObject.cs プロジェクト: hybridgroup/alljoyn
 /**
  * Reply to a method call.
  *
  * @param message      The method call message
  * @param args     The reply arguments (can be NULL)
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus MethodReply(Message message, MsgArg args)
 {
     return alljoyn_busobject_methodreply_args(_busObject, message.UnmanagedPtr, args.UnmanagedPtr,
         (UIntPtr)args.Length);
 }
コード例 #50
0
ファイル: BusObject.cs プロジェクト: peterdocter/Coco2dxDemo
 /**
  * Send a signal.
  *
  * @param destination      The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
  * @param sessionId        A unique SessionId for this AllJoyn session instance
  * @param signal           Interface member of signal being emitted.
  * @param args             The arguments for the signal (can be NULL)
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal, MsgArg args)
 {
     return(alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, 0, 0, IntPtr.Zero));
 }
コード例 #51
0
 /**
  * Return the arguments for this Message.
  *
  * @return An AllJoyn.MsgArg containing all the arguments for this Message
  */
 public MsgArg GetArgs()
 {
     IntPtr MsgArgPtr;
     UIntPtr numArgs;
     alljoyn_message_getargs(_message, out numArgs, out MsgArgPtr);
     MsgArg args = new MsgArg(MsgArgPtr, (int)numArgs);
     return args;
 }
コード例 #52
0
ファイル: BusObject.cs プロジェクト: peterdocter/Coco2dxDemo
 /**
  * Handle a bus attempt to write a property value to this object.
  * BusObjects that implement properties should override this method.
  * This default version just replies with QStatus.BUS_NO_SUCH_PROPERTY
  *
  * @param ifcName    Identifies the interface that the property is defined on
  * @param propName  Identifies the the property to set
  * @param val        The property value to set. The type of this value is the actual value
  *                   type.
  */
 protected virtual void OnPropertySet(string ifcName, string propName, MsgArg val)
 {
 }
コード例 #53
0
        public static async Task Maindo(SocketMessage arg)
        {
            try
            {
                if (arg.Content.ToLower().Contains("disable"))
                {
                    GuildStuff.NewGuildSetting(GuildStuff.GuildSettings.CanUseQuarantine, ((SocketTextChannel)arg.Channel).Guild.Id, false);
                    await arg.Channel.SendMessageAsync("No more quarantining in this server!");
                }
                else if (GuildStuff.ReadSetting(GuildStuff.GuildSettings.CanUseQuarantine, ((SocketTextChannel)arg.Channel).Guild.Id))
                {
                    var   Guild   = ((SocketGuildChannel)arg.Channel).Guild;
                    Emoji VoteYes = new Emoji("☣");
                    Emoji VoteNo  = new Emoji("👎");
                    var   User    = arg.MentionedUsers.Count() >= 1 ? arg.MentionedUsers.First() : arg.Author;
                    if (!AUsers.ContainsKey(arg.Author.Id))
                    {
                        if (AUsers.ContainsKey(User.Id))
                        {
                            AUsers.TryRemove(User.Id, out ulong Value);
                            await arg.Channel.SendMessageAsync($"User {User.Mention} removed from quarantine.");
                        }
                        else
                        {
                            var Embed = new EmbedBuilder()
                            {
                                Footer = new EmbedFooterBuilder()
                                {
                                    Text = $"If you want this command disabled, type '{Program.Prefix}quarantine disable'"
                                },
                                Timestamp   = DateTime.UtcNow,
                                Color       = Color.Orange,
                                Description = $"Should {User.Mention} Be Quarantined?",
                                Fields      = new List <EmbedFieldBuilder>()
                                {
                                    {
                                        new EmbedFieldBuilder()
                                        {
                                            Name  = "Vote",
                                            Value = $"{VoteYes} - Yes\n{VoteNo} - No",
                                        }
                                    }
                                },
                                ThumbnailUrl = User.GetAvatarUrl() != null?User.GetAvatarUrl() : Program.Client.CurrentUser.GetAvatarUrl(),
                            };
                            var Msg = await arg.Channel.SendMessageAsync("", false, Embed.Build());

                            new Thread(async x =>
                            {
                                await Msg.AddReactionsAsync(new[] { VoteYes, VoteNo });
                                int VotesInFavor = 0;
                                ulong Target     = User.Id;
                                Func <Cacheable <IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> Ev = (arg1, arg2, arg3) =>
                                {
                                    if (arg3.Emote.Name == "☣")
                                    {
                                        VotesInFavor++;
                                    }
                                    else if (arg3.Emote.Name == "👎")
                                    {
                                        VotesInFavor--;
                                    }
                                    return(Task.CompletedTask);
                                };
                                Program.Client.ReactionAdded += Ev;
                                Thread.Sleep(10000);

                                if (VotesInFavor >= 0)
                                {
                                    AUsers.TryAdd(User.Id, Guild.Id);
                                    var MsgOfMGX  = await arg.Channel.SendMessageAsync($"<@{Target}> is being quarantined..");
                                    long MsgCount = 0;
                                    Task MessageEv(SocketMessage MsgArg)
                                    {
                                        var ThisGuild = ((SocketGuildChannel)MsgArg.Channel).Guild;
                                        if (!MsgArg.Author.IsBot && MsgArg.Author.Id == Target && MsgArg.Channel.Id == arg.Channel.Id && AUsers.ContainsKey(Target) && AUsers[Target] == ThisGuild.Id)
                                        {
                                            MsgCount++;
                                            MsgArg.DeleteAsync();
                                            MsgOfMGX.ModifyAsync(xxx =>
                                            {
                                                xxx.Content = $"Blocked {MsgCount} messages from quarantine - No infected messages here!";
                                            });
                                        }
                                        if (!AUsers.ContainsKey(Target))
                                        {
                                            Program.Client.MessageReceived -= MessageEv;
                                            Thread.CurrentThread.Abort();
                                        }
                                        else if (!MsgArg.Author.IsBot && MsgArg.Author.Id == Target && MsgArg.Channel.Id == arg.Channel.Id && !AUsers.ContainsKey(Target))
                                        {
                                            Program.Client.MessageReceived -= MessageEv;
                                            Thread.CurrentThread.Abort();
                                        }
                                        return(Task.CompletedTask);
                                    }
                                    Program.Client.MessageReceived += MessageEv;
                                }
                                else
                                {
                                    await arg.Channel.SendMessageAsync($"<@{Target}> is not going to be quarantined. Congrats!\n~~you will die soon~~");
                                    Thread.CurrentThread.Abort();
                                }
                            }).Start();
                        }
                    }
                }
                else if (GuildStuff.ReadRank(((SocketTextChannel)arg.Channel).Guild.Id, arg.Author.Id) >= 19)
                {
                    await arg.Channel.SendMessageAsync("Would you like to enable this command for this server?");

                    var WFR = await new WaitForResponse()
                    {
                        TimeLimitS = 30, ChannelId = arg.Channel.Id, UserId = arg.Author.Id
                    }.Start();
                    if (WFR != null && WFR.Content.ToLower().Contains("yes"))
                    {
                        await arg.Channel.SendMessageAsync($"Enabled {Program.Prefix}quarantine as a command!");

                        GuildStuff.NewGuildSetting(GuildStuff.GuildSettings.CanUseQuarantine, ((SocketTextChannel)arg.Channel).Guild.Id, true);
                    }
                    else
                    {
                        await arg.Channel.SendMessageAsync($"👌");
                    }
                }
                else
                {
                    await arg.Channel.SendMessageAsync("Quarantine can't be used in this server!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #54
0
        /// <summary>
        /// Run the client stress op which stresses the bus attachment in a client type
        /// configuration which find the well-known service name and calls the 'cat'
        /// method
        /// </summary>
        /// <param name="isMultipoint">True if operation uses multipoint sessions</param>
        private void RunClient(bool isMultipoint)
        {
            try
            {
                ClientBusListener clientBusListener = new ClientBusListener(this.busAtt, this, this.foundName);
                this.busAtt.FindAdvertisedName(ServiceName);
                this.DebugPrint("Looking for WKN : " + ServiceName);

                this.foundName.WaitOne(12000);

                SessionOpts optsIn = new SessionOpts(
                            TrafficType.TRAFFIC_MESSAGES,
                            isMultipoint,
                            ProximityType.PROXIMITY_ANY,
                            TransportMaskType.TRANSPORT_ANY);
                SessionOpts[] optsOut = new SessionOpts[1];
                Task<JoinSessionResult> joinTask = this.busAtt.JoinSessionAsync(
                            this.DiscoveredName,
                            ServicePort,
                            (SessionListener)clientBusListener,
                            optsIn,
                            optsOut,
                            null).AsTask<JoinSessionResult>();
                joinTask.Wait();
                JoinSessionResult joinResult = joinTask.Result;
                QStatus status = joinResult.Status;

                ProxyBusObject proxyBusObj = null;
                if (QStatus.ER_OK == status)
                {
                    this.DebugPrint("JoinSession with " + this.DiscoveredName + " was successful (sessionId=" + joinResult.SessionId + ")");
                    proxyBusObj = new ProxyBusObject(this.busAtt, this.DiscoveredName, ServicePath, joinResult.SessionId);
                    Task<IntrospectRemoteObjectResult> introTask = proxyBusObj.IntrospectRemoteObjectAsync(null).AsTask<IntrospectRemoteObjectResult>();
                    introTask.Wait();
                    IntrospectRemoteObjectResult introResult = introTask.Result;
                    status = introResult.Status;

                    if (QStatus.ER_OK == status)
                    {
                        this.DebugPrint("Introspection of the service was successfull");
                        MsgArg hello = new MsgArg("s", new object[] { "Hello " });
                        MsgArg world = new MsgArg("s", new object[] { "World!" });
                        InterfaceMember catMethod = proxyBusObj.GetInterface(InterfaceName).GetMethod("cat");
                        byte flags = (byte)0;
                        Task<MethodCallResult> catTask = proxyBusObj.MethodCallAsync(catMethod, new MsgArg[] { hello, world }, null, 5000, flags).AsTask<MethodCallResult>();
                        catTask.Wait();
                        MethodCallResult catResult = catTask.Result;
                        if (catResult.Message.Type == AllJoynMessageType.MESSAGE_METHOD_RET)
                        {
                            this.DebugPrint(this.DiscoveredName + ".cat ( path=" + ServicePath + ") returned \"" + catResult.Message.GetArg(0).Value.ToString() + "\"");
                        }
                        else
                        {
                            this.DebugPrint("Method call on " + this.DiscoveredName + ".cat failed (ReturnType=" + catResult.Message.Type.ToString() + ")");
                        }
                    }
                    else
                    {
                        this.DebugPrint("Introspection was unsuccessful: " + status.ToString());
                    }
                }
                else
                {
                    this.DebugPrint("Join Session was unsuccessful: " + status.ToString());
                }

                this.busAtt.CancelFindAdvertisedName(ServiceName);
                this.busAtt.UnregisterBusListener(clientBusListener);
                this.DebugPrint("Successfully unraveled the client operation");
            }
            catch (ArgumentNullException ex)
            {
                this.DebugPrint(">>>> TIMEOUT, Client could not find WKN >>>>");
            }
            catch (Exception ex)
            {
                var errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                this.DebugPrint(">>>> Client Execution Error >>>> " + errMsg);
            }
        }
コード例 #55
0
ファイル: MsgArg.cs プロジェクト: peterdocter/Coco2dxDemo
			/**
			 * Set value of a message arg from a signature and a list of values. Note that any values or
			 * MsgArg pointers passed in must remain valid until this MsgArg is freed.
			 *
			 *  - @c 'a'  The array length followed by:
			 *            - If the element type is a basic type an array of values of that type.
			 *            - If the element type is an "ARRAY", "STRUCT", "DICT_ENTRY" or "VARIANT" an
			 *              array of MsgArgs where each MsgArg has the signature specified by the element type.
			 *            - If the element type is specified using the wildcard character '*', a pointer to
			 *              an  array of MsgArgs. The array element type is determined from the type of the
			 *              first MsgArg in the array, all the elements must have the same type.
			 *  - @c 'b'  A bool value
			 *  - @c 'd'  A double (64 bits)
			 *  - @c 'g'  A string representing an AllJoyn signature
			 *  - @c 'h'  A SocketFd
			 *  - @c 'i'  An int (32 bits)
			 *  - @c 'n'  A short (16 bits)
			 *  - @c 'o'  A string representing an AllJoyn object
			 *  - @c 'q'  A ushort (16 bits)
			 *  - @c 's'  A pointer to a NUL terminated string (pointer must remain valid for lifetime of the MsgArg)
			 *  - @c 't'  A ulong (64 bits)
			 *  - @c 'u'  A uint (32 bits)
			 *  - @c 'v'  A MsgArg.
			 *  - @c 'x'  An long (64 bits)
			 *  - @c 'y'  A byte (8 bits)
			 *
			 *  - @c '(' and @c ')'  The list of values that appear between the parentheses using the notation above
			 *  - @c '{' and @c '}'  A pair values using the notation above.
			 *
			 *  - @c '*'  A pointer to a MsgArg
			 *
			 * @param sig    The signature for MsgArg value
			 * @param value  object containing values to initialize the MsgArg.
			 *
			 * @return
			 *      - QStatus.OK if the MsgArg was successfully set
			 *      - An error status otherwise
			 */
			//TODO add in examples into the Set documentation
			public QStatus Set(string sig, object value)
			{
				QStatus status = QStatus.OK;
				// handle multiple signatures in one set command
				if (sig.Length > 1)
				{
					string[] sigs = splitSignature(sig);
					if (sigs.Length > 1)
					{
						if (sigs.Length > _length)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						object[] values = (object[])value;
						if (values.Length > _length)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						if (sigs.Length != values.Length)
						{
							return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
						}
						for (int j = 0; j < values.Length; ++j)
						{
							status = this[j].Set(sigs[j], values[j]);
							if (AllJoyn.QStatus.OK != status)
							{
								return status;
							}
						}
						return status;
					}
				}
				try
				{
					switch ((AllJoynTypeId)sig[0])
					{
						case AllJoynTypeId.ALLJOYN_BYTE:
							status = alljoyn_msgarg_set_uint8(_msgArg, (byte)value);
							break;
						case AllJoynTypeId.ALLJOYN_BOOLEAN:
							status = alljoyn_msgarg_set_bool(_msgArg, (bool)value);
							break;
						case AllJoynTypeId.ALLJOYN_INT16:
							status = alljoyn_msgarg_set_int16(_msgArg, (short)value);
							break;
						case AllJoynTypeId.ALLJOYN_UINT16:
							status = alljoyn_msgarg_set_uint16(_msgArg, (ushort)value);
							break;
						case AllJoynTypeId.ALLJOYN_INT32:
							status = alljoyn_msgarg_set_int32(_msgArg, (int)value);
							break;
						case AllJoynTypeId.ALLJOYN_UINT32:
							status = alljoyn_msgarg_set_uint32(_msgArg, (uint)value);
							break;
						case AllJoynTypeId.ALLJOYN_INT64:
							status = alljoyn_msgarg_set_int64(_msgArg, (long)value);
							break;
						case AllJoynTypeId.ALLJOYN_UINT64:
							status = alljoyn_msgarg_set_uint64(_msgArg, (ulong)value);
							break;
						case AllJoynTypeId.ALLJOYN_DOUBLE:
							status = alljoyn_msgarg_set_double(_msgArg, (double)value);
							break;
						case AllJoynTypeId.ALLJOYN_STRING:
							status = alljoyn_msgarg_set_and_stabilize(_msgArg, sig, (string)value);
							break;
						case AllJoynTypeId.ALLJOYN_OBJECT_PATH:
							goto case AllJoynTypeId.ALLJOYN_STRING;
						case AllJoynTypeId.ALLJOYN_SIGNATURE:
							goto case AllJoynTypeId.ALLJOYN_STRING;
						case AllJoynTypeId.ALLJOYN_ARRAY:
							switch ((AllJoynTypeId)sig[1])
							{
								case AllJoynTypeId.ALLJOYN_BYTE:
									status = alljoyn_msgarg_set_uint8_array(_msgArg, (UIntPtr)((byte[])value).Length, (byte[])value);
									break;
								case AllJoynTypeId.ALLJOYN_BOOLEAN:
									Int32[] ab = new Int32[((bool[])value).Length];
									for (int i = 0; i < ab.Length; i++)
									{
										if (((bool[])value)[i])
										{
											ab[i] = 1;
										}
										else
										{
											ab[i] = 0;
										}
									}
									status = alljoyn_msgarg_set_bool_array(_msgArg, (UIntPtr)ab.Length, ab);
									break;
								case AllJoynTypeId.ALLJOYN_INT16:
									status = alljoyn_msgarg_set_int16_array(_msgArg, (UIntPtr)((short[])value).Length, (short[])value);
									break;
								case AllJoynTypeId.ALLJOYN_UINT16:
									status = alljoyn_msgarg_set_uint16_array(_msgArg, (UIntPtr)((ushort[])value).Length, (ushort[])value);
									break;
								case AllJoynTypeId.ALLJOYN_INT32:
									status = alljoyn_msgarg_set_int32_array(_msgArg, (UIntPtr)((int[])value).Length, (int[])value);
									break;
								case AllJoynTypeId.ALLJOYN_UINT32:
									status = alljoyn_msgarg_set_uint32_array(_msgArg, (UIntPtr)((uint[])value).Length, (uint[])value);
									break;
								case AllJoynTypeId.ALLJOYN_INT64:
									status = alljoyn_msgarg_set_int64_array(_msgArg, (UIntPtr)((long[])value).Length, (long[])value);
									break;
								case AllJoynTypeId.ALLJOYN_UINT64:
									status = alljoyn_msgarg_set_uint64_array(_msgArg, (UIntPtr)((ulong[])value).Length, (ulong[])value);
									break;
								case AllJoynTypeId.ALLJOYN_DOUBLE:
									status = alljoyn_msgarg_set_double_array(_msgArg, (UIntPtr)((double[])value).Length, (double[])value);
									break;
								case AllJoynTypeId.ALLJOYN_STRING:
									status = alljoyn_msgarg_set_and_stabilize(_msgArg, sig, (UIntPtr)((string[])value).Length, (string[])value);
									break;
								case AllJoynTypeId.ALLJOYN_SIGNATURE:
									goto case AllJoynTypeId.ALLJOYN_STRING;
								case AllJoynTypeId.ALLJOYN_OBJECT_PATH:
									goto case AllJoynTypeId.ALLJOYN_STRING;
								case AllJoynTypeId.ALLJOYN_STRUCT_OPEN:
									MsgArg array_struct = (MsgArg)value;
									status = alljoyn_msgarg_set(_msgArg, sig, (UIntPtr)array_struct.Length, array_struct.UnmanagedPtr);
									break;
								case AllJoynTypeId.ALLJOYN_DICT_ENTRY_OPEN:
									string inner_dict_sig = sig.Substring(1);
									System.Collections.Generic.Dictionary<object, object> dict_value = ((System.Collections.Generic.Dictionary<object, object>)value);
									int dict_size = dict_value.Count;
									MsgArg dict_args = new MsgArg(dict_size);
									int dict_element_count = 0;
									foreach (System.Collections.Generic.KeyValuePair<object, object> pair in dict_value)
									{
										status = dict_args[dict_element_count].Set(inner_dict_sig, pair);
										dict_element_count++;
										if (status != AllJoyn.QStatus.OK)
										{
											break;
										}
									}
									status = alljoyn_msgarg_set(_msgArg, sig, (UIntPtr)dict_element_count, dict_args.UnmanagedPtr);
									break;
								// when working with arrays of arrays the user must pass in a jagged array
								// i.e.  int[2,4] will not work but int[2][] will work.
								case AllJoynTypeId.ALLJOYN_ARRAY:
									string inner_sig = sig.Substring(1);
									int array_size = ((System.Array)value).GetLength(0);
									MsgArg args = new MsgArg(array_size);
									for (int j = 0; j < array_size; ++j)
									{
										if (status != QStatus.OK)
										{
											break;
										}
										object inner_array = ((System.Array)value).GetValue(j);
										status = args[j].Set(inner_sig, inner_array);
									}
									if (status = QStatus.OK)
									{
										status = alljoyn_msgarg_set(_msgArg, sig, (UIntPtr)array_size, args.UnmanagedPtr);
									}
									break;
								case AllJoynTypeId.ALLJOYN_VARIANT:
									status = alljoyn_msgarg_set(_msgArg, sig, (UIntPtr)((AllJoyn.MsgArg)value).Length, ((AllJoyn.MsgArg)value).UnmanagedPtr);
									break;
								default:
									status = QStatus.WRITE_ERROR;
									break;
							}
							break;
						case AllJoynTypeId.ALLJOYN_STRUCT_OPEN:
							if ((AllJoynTypeId)sig[sig.Length - 1] != AllJoynTypeId.ALLJOYN_STRUCT_CLOSE)
							{
								return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
							}
							string[] struct_sigs = splitSignature(sig.Substring(1, sig.Length - 2));
							if (struct_sigs == null)
							{
								return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
							}
							object[] structObjects = (object[])value;
							// The number of values specified in the signature do not match the
							// number of objects passed in.
							if (struct_sigs.Length != structObjects.Length)
							{
								return AllJoyn.QStatus.BUS_BAD_SIGNATURE;
							}
							MsgArg struct_args = new MsgArg(struct_sigs.Length);
							for (int j = 0; j < struct_sigs.Length; ++j)
							{
								status = struct_args[j].Set(struct_sigs[j], structObjects[j]);
								if (AllJoyn.QStatus.OK != status)
								{
									return status;
								}
							}
							//now struct_args can be used to set the struct
							status = alljoyn_msgarg_setstruct(_msgArg, struct_args._msgArg, (UIntPtr)struct_sigs.Length);
							break;
						case AllJoynTypeId.ALLJOYN_DICT_ENTRY_OPEN:
							string key_sig = sig.Substring(1, 1);
							// signature of form {KV} where key is always one letter value
							// just must be a complete signature lenght - 1 for K  - 2 for '{' and '}'
							string value_sig = sig.Substring(2, sig.Length - 3);
							Object sub_key = ((System.Collections.Generic.KeyValuePair<Object, Object>)value).Key;
							Object sub_value = ((System.Collections.Generic.KeyValuePair<Object, Object>)value).Value;
							MsgArg dict_key_arg = new MsgArg();
							status = dict_key_arg.Set(key_sig, sub_key);
							if (status != AllJoyn.QStatus.OK)
							{
								break;
							}
							MsgArg dict_value_arg = new MsgArg();
							status = dict_value_arg.Set(value_sig, sub_value);
							status = dict_key_arg.Set(key_sig, sub_key);
							if (status != AllJoyn.QStatus.OK)
							{
								break;
							}

							status = alljoyn_msgarg_setdictentry(_msgArg, dict_key_arg._msgArg, dict_value_arg._msgArg);
							break;
						case AllJoynTypeId.ALLJOYN_VARIANT:
							status = alljoyn_msgarg_set(_msgArg, sig, ((MsgArg)value)._msgArg);
							break;
						default:
							status = QStatus.WRITE_ERROR;
							break;
					}
				}
				catch (System.InvalidCastException)
				{
					status = AllJoyn.QStatus.BUS_BAD_SIGNATURE;
				}
				return status;
			}