예제 #1
0
        /// <summary>
        /// Initialize the AllJoyn portions of the application.
        /// </summary>
        private void InitializeAllJoyn()
        {
            Task t1 = new Task(() =>
            {
                try
                {
                    Debug.UseOSLogging(true);
                    //Debug.SetDebugLevel("ALL", 1);
                    //Debug.SetDebugLevel("ALLJOYN", 7);

                    bus = new BusAttachment(ApplicationName, true, 4);
                    bus.Start();

                    const string connectSpec = "null:";
                    bus.ConnectAsync(connectSpec).AsTask().Wait();
                    DisplayStatus("Connected to AllJoyn successfully.");

                    busListeners = new Listeners(bus, this);
                    bus.RegisterBusListener(busListeners);
                    chatService = new ChatSessionObject(bus, ObjectPath, this);
                    bus.RegisterBusObject(chatService);
                    bus.FindAdvertisedName(NamePrefix);
                }
                catch (Exception ex)
                {
                    QStatus stat  = AllJoynException.GetErrorCode(ex.HResult);
                    string errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                    DisplayStatus("InitializeAllJoyn Error : " + errMsg);
                }
            });

            t1.Start();
        }
예제 #2
0
        private void RxLoop()
        {
            Task rxLoopTask = new Task(() =>
            {
                try
                {
                    while (_running)
                    {
                        byte[] buf     = new byte[2048];
                        int[] received = new int[1];
                        // sockstream is blocking
                        _sockStream.Recv(buf, buf.Length, received);
                        if (received[0] >= 0)
                        {
                            _rxCount += received[0];
                            // TODO write to file
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    var m = AllJoynException.GetErrorMessage(e.HResult);
                    var h = AllJoynException.GetErrorCode(e.HResult);
                }
            });

            rxLoopTask.Start();
        }
예제 #3
0
        /// <summary>
        /// Initializes a new instance of the Client class.
        /// </summary>
        /// <param name="name">The name of the client application.</param>
        /// <param name="pinReady">The event to communicate there is a pin waiting.</param>
        public Client(string name, AutoResetEvent pinReady)
        {
            this.PinReady = pinReady;

            // Create the BusAttachment and other prep for accepting input from the client(s).
            this.ConnectBus = new Task(() =>
            {
                try
                {
                    this.InitializeAllJoyn(name);
                    App app = Windows.UI.Xaml.Application.Current as App;
                    app.Bus = this.Bus;
                }
                catch (Exception ex)
                {
                    const string ErrorFormat = "Bus intialization for client produced error(s). QStatus = 0x{0:X}.";
                    QStatus status           = AllJoynException.GetErrorCode(ex.HResult);
                    string error             = string.Format(ErrorFormat, status);

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

            this.ConnectBus.Start();
        }
예제 #4
0
        async void InitializeAllJoyn()
        {
            Debug.UseOSLogging(true);
            Debug.SetDebugLevel("ALLJOYN", 7);

            _bus = new BusAttachment(APPLICATION_NAME, true, 4);
            string connectSpec = "null:";

            _bus.Start();

            try
            {
                _mp3Reader = new MP3Reader();

                if (_streamingSong != null)
                {
                    _streamingSongBasicProperties = await _streamingSong.GetBasicPropertiesAsync();

                    if (_streamingSongBasicProperties != null)
                    {
                        _streamingSongMusicProperties = await _streamingSong.Properties.GetMusicPropertiesAsync();

                        if (_streamingSongMusicProperties != null)
                        {
                            await _mp3Reader.SetFileAsync(_streamingSong);

                            _bus.ConnectAsync(connectSpec).AsTask().Wait();
                            _connected = true;

                            _listeners = new Listeners(_bus, this);
                            _bus.RegisterBusListener(_listeners);
                            _mediaSource = new MediaSource(_bus);
                            _audioStream = new AudioStream(_bus, "mp3", _mp3Reader, 100, 1000);
                            _mediaSource.AddStream(_audioStream);

                            /* Register MediaServer bus object */
                            _bus.RegisterBusObject(_mediaSource.MediaSourceBusObject);
                            /* Request a well known name */
                            _bus.RequestName(MediaServerName, (int)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE));

                            /* Advertise name */
                            _bus.AdvertiseName(MediaServerName, TransportMaskType.TRANSPORT_ANY);

                            /* Bind a session for incoming client connections */
                            SessionOpts opts    = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
                            ushort[]    portOut = new ushort[1];
                            _bus.BindSessionPort(SESSION_PORT, portOut, opts, _listeners);
                        }
                    }
                }
            } catch (Exception ex)
            {
                string  message = ex.Message;
                QStatus status  = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg  = AllJoynException.GetErrorMessage(ex.HResult);
            }
        }
예제 #5
0
        /// <summary>
        /// connects with the bus, creates an interface and advertises a well-known name for
        /// clients to join a session with.
        /// </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 (busObject == null && busAtt == null)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalServiceApp", true, 4);

                        busObject = new SignalServiceBusObject(busAtt);
                        OutputLine("BusObject Created.");

                        busListener = new SignalServiceBusListener(busAtt);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        await busAtt.ConnectAsync(SignalServiceGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalServiceGlobals.ConnectSpec + ".");

                        SessionOpts sessionOpts = new SessionOpts(
                            SignalServiceGlobals.SessionProps.TrType,
                            SignalServiceGlobals.SessionProps.IsMultiPoint,
                            SignalServiceGlobals.SessionProps.PrType,
                            SignalServiceGlobals.SessionProps.TmType);
                        try
                        {
                            ushort[] portOut = new ushort[1];
                            busAtt.BindSessionPort(SignalServiceGlobals.SessionProps.SessionPort, portOut, sessionOpts, busListener);

                            busAtt.RequestName(SignalServiceGlobals.WellKnownServiceName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);

                            busAtt.AdvertiseName(SignalServiceGlobals.WellKnownServiceName, TransportMaskType.TRANSPORT_ANY);
                            OutputLine("Name is Being Advertised as: " + SignalServiceGlobals.WellKnownServiceName);
                        }
                        catch (COMException ce)
                        {
                            QStatus s = AllJoynException.GetErrorCode(ce.HResult);
                            OutputLine("Errors were produced while establishing the service.");
                            TearDown();
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors occurred while setting up the service.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busObject      = null;
                        busAtt         = null;
                    }
                });
                task.Start();
            }
        }
예제 #6
0
 /// <summary>
 /// Sends a 'Chat' signal using the specified parameters
 /// </summary>
 /// <param name="filter">filter to use </param>
 public void AddRule(string filter)
 {
     try
     {
         this.busObject.Bus.AddMatch(filter);
     }
     catch (Exception ex)
     {
         QStatus status = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.sessionOps.Output("adding a rule failed: " + errMsg);
     }
 }
예제 #7
0
 /// <summary>
 /// This method sends the current message to the chat service for delivery to the remote device.
 /// </summary>
 /// <param name="id">The session ID associated with this message.</param>
 /// <param name="message">The actual message being sent.</param>
 private void SendMyMessage(uint id, string message)
 {
     try
     {
         this.OnChat(this.SessionId, "Me : ", message);
         this.chatService.SendChatSignal(this.SessionId, message);
         this.MessageBox.Text = string.Empty;
     }
     catch (Exception ex)
     {
         QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         DisplayStatus("SendMessage Error : " + errMsg);
     }
 }
예제 #8
0
        /// <summary>
        /// Leave the currently active chat session.
        /// </summary>
        private void LeaveChannel()
        {
            try
            {
                this.bus.LeaveSession(this.SessionId);
                this.DisplayStatus("Leave chat session " + this.SessionId + " successfully");
            }
            catch (Exception ex)
            {
                QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                this.DisplayStatus("Leave chat session " + this.SessionId + " failed: " + errMsg);
            }

            this.SessionId = 0;
        }
예제 #9
0
        /// <summary>
        /// Do the work of joining a session.
        /// </summary>
        /// <param name="folder">The folder to put the received file in.</param>
        /// <returns>true if all the input variables look good.</returns>
        public bool StartJoinSessionTask(StorageFolder folder)
        {
            bool returnValue = false;

            this.Folder = folder;

            if (null != this.Bus && null != this.Folder)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        if (0 != this.SessionId)
                        {
                            this.Bus.LeaveSession(this.SessionId);
                        }

                        this.lastIndex = 0;
                        this.CreateInterfaceAndBusObject();
                        this.AddSignalHandler();

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

                        if (result)
                        {
                            App.OutputLine("Successfully joined session.");
                        }
                    }
                    catch (Exception ex)
                    {
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        string message = string.Format(
                            "Errors were produced while establishing the application '{0}' (0x{0:X}).",
                            status.ToString(),
                            status);
                        App.OutputLine(message);
                    }
                });

                task.Start();

                returnValue = true;
            }

            return(returnValue);
        }
예제 #10
0
        /// <summary>
        /// Shut down the hosted channel.
        /// </summary>
        private void StopChannel()
        {
            try
            {
                var wellKnownName = this.MakeWellKnownName(this.channelHosted);
                this.bus.CancelAdvertiseName(wellKnownName, alljoynTransports);
                this.bus.UnbindSessionPort(ContactPort);
                this.bus.ReleaseName(wellKnownName);
                this.Channels.Remove(this.channelHosted);

                this.channelHosted = null;
            }
            catch (Exception ex)
            {
                QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                DisplayStatus("StopChannel Error : " + errMsg);
            }
        }
예제 #11
0
 /// <summary>
 /// Start up the channel we are hosting.
 /// </summary>
 /// <param name="name">The name, minus the name prefix, for the channel we are hosting.</param>
 private void StartChannel(string name)
 {
     try
     {
         this.channelHosted = name;
         string wellKnownName = this.MakeWellKnownName(name);
         this.bus.RequestName(wellKnownName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
         this.bus.AdvertiseName(wellKnownName, alljoynTransports);
         ushort[]    portOut = new ushort[1];
         SessionOpts opts    = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, alljoynTransports);
         this.bus.BindSessionPort(ContactPort, portOut, opts, this.busListeners);
         DisplayStatus("Start Chat channel " + name + " successfully");
     }
     catch (Exception ex)
     {
         QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         DisplayStatus("StartChannel Error : " + errMsg);
     }
 }
예제 #12
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.GetErrorCode(ex.HResult);
#endif
                    Assert.IsFalse(true);
                }
            }
예제 #13
0
        /// <summary>
        /// Join an existing channel with the given name.
        /// </summary>
        /// <param name="name">The name of the channel to join.</param>
        private async void JoinChannel(string name)
        {
            try
            {
                this.DisplayStatus("Joining chat session: " + name);
                string        wellKnownName = this.MakeWellKnownName(name);
                SessionOpts   opts          = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, alljoynTransports);
                SessionOpts[] opts_out      = new SessionOpts[1];
                this.channelJoined = name;
                JoinSessionResult result = await this.bus.JoinSessionAsync(
                    wellKnownName,
                    ContactPort,
                    this.busListeners,
                    opts,
                    opts_out,
                    null);

                if (result.Status == QStatus.ER_OK)
                {
                    this.SessionId = result.SessionId;
                    this.DisplayStatus("Join chat session " + this.SessionId + " successfully");
                    await this.coreDispatcher.RunAsync(
                        CoreDispatcherPriority.Normal,
                        () => { this.JoinChannelButton.Content = "Leave Channel"; });
                }
                else
                {
                    this.DisplayStatus("Join chat session " + result.SessionId + " failed. Error: " + result.Status);
                }
            }
            catch (Exception ex)
            {
                QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                DisplayStatus("JoinChannel Error : " + errMsg);
            }
        }
예제 #14
0
        private void InitializeAllJoyn()
        {
            Task _t1 = new Task(() =>
            {
                Debug.UseOSLogging(true);
                //Debug.SetDebugLevel("ALLJOYN", 7);

                string connectSpec = "null:";

                try
                {
                    _bus = new BusAttachment(APPLICATION_NAME, true, 4);
                }
                catch (Exception ex)
                {
                    QStatus stat = AllJoynException.GetErrorCode(ex.HResult);
                }
                _bus.Start();

                _bus.ConnectAsync(connectSpec).AsTask().Wait();

                _listeners = new Listeners(_bus, this);
                _bus.RegisterBusListener(_listeners);

                _mediaSink            = new MediaSink(_bus);
                _mediaRender          = new MediaRenderer();
                _mediaRender.OnOpen  += OnOpen;
                _mediaRender.OnPlay  += OnPlay;
                _mediaRender.OnPause += OnPause;
                _mediaRender.OnClose += OnClose;

                _bus.FindAdvertisedName(MEDIA_SERVER_NAME);
            });

            _t1.Start();
        }
예제 #15
0
        /// <summary>
        /// Connects to the bus and registers a signal handler for when the 'name' property changes.
        /// </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 (busAtt == null)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalConsumerApp", true, 4);

                        // create and activate the interface
                        InterfaceDescription[] interfaceDescription = new InterfaceDescription[1];
                        busAtt.CreateInterface(SignalConsumerGlobals.InterfaceName, interfaceDescription, false);
                        interfaceDescription[0].AddSignal("nameChanged", "s", "newName", (byte)0, string.Empty);
                        interfaceDescription[0].AddProperty("name", "s", (byte)PropAccessType.PROP_ACCESS_RW);
                        interfaceDescription[0].Activate();

                        busListener = new SignalConsumerBusListener(busAtt, foundNameEvent);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        busAtt.ConnectAsync(SignalConsumerGlobals.ConnectSpec).AsTask().Wait();
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalConsumerGlobals.ConnectSpec + ".");

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

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            SignalConsumerGlobals.SessionProps.TrType,
                            SignalConsumerGlobals.SessionProps.IsMultiPoint,
                            SignalConsumerGlobals.SessionProps.PrType,
                            SignalConsumerGlobals.SessionProps.TmType);
                        SessionOpts[] sessionOptsOut = new SessionOpts[1];
                        OutputLine("Requesting a session with the well known service name.");
                        JoinSessionResult joinResult = await busAtt.JoinSessionAsync(
                            SignalConsumerGlobals.WellKnownServiceName,
                            SignalConsumerGlobals.SessionProps.SessionPort,
                            busListener,
                            sessionOpts,
                            sessionOptsOut,
                            null);

                        if (QStatus.ER_OK == joinResult.Status)
                        {
                            OutputLine("Join Session was successful (sessionId=" + joinResult.SessionId + ").");
                            busAtt.AddMatch("type='signal',interface='org.alljoyn.Bus.signal_sample',member='nameChanged'");
                            OutputLine("Subscribed to the 'nameChanged' signal.");
                        }
                        else
                        {
                            OutputLine("Join Session was unsuccessful.");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors were produced while establishing the application.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busAtt         = null;
                    }
                });
                task.Start();
            }
        }
예제 #16
0
        async void ConnectToServer()
        {
            try
            {
                _mediaSink.ConnectSourceAsync(MEDIA_SERVER_NAME, _sessionId).AsTask().Wait();
                ListStreamResult result = await _mediaSink.ListStreamsAsync();

                MediaDescription[] streams = result.Streams;
                for (int i = 0; i < streams.Length; i++)
                {
                    switch (streams[i].MType)
                    {
                    case MediaType.AUDIO:
                        break;

                    case MediaType.VIDEO:
                        break;

                    case MediaType.IMAGE:
                        break;

                    case MediaType.APPLICATION:
                    case MediaType.TEXT:
                    case MediaType.OTHER:
                        break;
                    }

                    if (mimeType == streams[i].MimeType)
                    {
                        _selectedStream = i;
                        break;
                    }
                }

                // Found a valid stream
                if (_selectedStream != -1)
                {
                    string streamName = streams[_selectedStream].StreamName;
                    _mediaSink.OpenStreamAsync(streamName, _mediaRender).AsTask().Wait();

                    if (_stress)
                    {
                        StressLoop();
                    }
                    else
                    {
                        _mediaSink.PlayAsync().AsTask().Wait();
                        Task.Delay(1000000).AsAsyncAction().AsTask().Wait();
                        _mediaSink.PauseAsync(_drain).AsTask().Wait();
                        Task.Delay(4).AsAsyncAction().AsTask().Wait();;
                        _mediaSink.PlayAsync().AsTask().Wait();
                        Task.Delay(1000000).AsAsyncAction().AsTask().Wait();
                    }

                    _mediaSink.CloseStreamAsync(streamName).AsTask().Wait();
                }
            }
            catch (Exception e)
            {
                var m = AllJoynException.GetErrorMessage(e.HResult);
                var h = AllJoynException.GetErrorCode(e.HResult);
            }
        }
예제 #17
0
        /// <summary>
        /// Initializes the global bus attachment
        /// </summary>
        private void InitializeAllJoyn()
        {
            InterfaceDescription[] iface = new InterfaceDescription[1];

            this.Bus = new BusAttachment("SRPSecurityServiceA", true, 4);

            this.Bus.CreateInterface(App.InterfaceName, iface, true);
            iface[0].AddMethod("Ping", "s", "s", "inStr,outStr", 0, string.Empty);
            iface[0].Activate();

            this.BusObject = new SecureBusObject(this.Bus, iface);

            this.Listeners = new Listeners(this.Bus);
            this.Listeners.NameOwnerChange     += this.NameOwnerChanged;
            this.Listeners.AcceptSessionJoiner += this.AcceptSessionJoiner;

            this.Bus.RegisterBusListener(this.Listeners);
            this.Bus.Start();

            // Enable security.
            // Note the location of the keystore file has been specified and the
            // isShared parameter is being set to true. So this keystore file can
            // be used by multiple applications.
            this.AuthenticationListener = new AuthListener(this.Bus);

            this.AuthenticationListener.RequestCredentials += this.AuthRequestCredentals;
            this.Bus.EnablePeerSecurity(
                App.SecurityType,
                this.AuthenticationListener,
                "/.alljoyn_keystore/s_central.ks",
                true);

            this.Bus.ConnectAsync(App.ConnectSpec).AsTask().Wait();

            SessionOpts sessionOpts = new SessionOpts(
                TrafficType.TRAFFIC_MESSAGES,
                false,
                ProximityType.PROXIMITY_ANY,
                TransportMaskType.TRANSPORT_ANY);

            ushort[] portOut = new ushort[1];

            this.Bus.BindSessionPort(App.ServicePort, portOut, sessionOpts, this.Listeners);

            try
            {
                uint flags = (uint)RequestNameType.DBUS_NAME_REPLACE_EXISTING + (uint)RequestNameType.DBUS_NAME_DO_NOT_QUEUE;
                this.Bus.RequestName(App.ServiceName, flags);
            }
            catch (COMException ce)
            {
                QStatus exceptionStatus = AllJoynException.GetErrorCode(ce.HResult);
                string  error           = string.Format(
                    "Well known name '{0}' was not accepted. QStatus = 0x{1:X}",
                    App.ServiceName,
                    exceptionStatus);

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

            this.Bus.AdvertiseName(App.ServiceName, sessionOpts.TransportMask);
            App.OutputLine(string.Format("Name is being advertised as: '{0}'.", App.ServiceName));
        }
예제 #18
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();
            }
        }
예제 #19
0
        /// <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);
                        }
                    }
                }
            }
        }
예제 #20
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();
            }
        }