public async Task <bool> StartServer()
            {
                // Initialize the provider for the hosted RFCOMM service.
                provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.ObexObjectPush);

                if (provider != null)
                {
                    // Create a listener for this service and start listening.
                    socketListener = new StreamSocketListener();
                    socketListener.ConnectionReceived += OnConnectionReceived;


                    await socketListener.BindServiceNameAsync(provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                    // Set the SDP attributes and start advertising.
                    InitializeServiceSdpAttributes(provider);
                    provider.StartAdvertising(socketListener);
                    isAdvertising = true;
                    return(true);
                }
                else
                {
                    await new MessageDialog("No").ShowAsync();
                    return(false);
                }
                return(false);
            }
Exemple #2
0
        private async System.Threading.Tasks.Task MakeDiscoverable()
        {
            // Make the system discoverable. Don'd repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists"
            if (!App.IsBluetoothDiscoverable)
            {
                Guid BluetoothServiceUuid = new Guid("17890000-0068-0069-1532-1992D79BE4D8");
                try
                {
                    provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid));

                    Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener();
                    listener.ConnectionReceived += OnConnectionReceived;
                    await listener.BindServiceNameAsync(provider.ServiceId.AsString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket);

                    //     SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
                    // Don't bother setting SPD attributes
                    provider.StartAdvertising(listener, true);
                    App.IsBluetoothDiscoverable = true;
                }
                catch (Exception e)
                {
                    string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothNoDeviceAvailableFormat");
                    string confirmationMessage = string.Format(formatString, e.Message);
                    DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);
                }
            }
        }
        /// <summary>
        /// Cleanup Bluetooth resources
        /// </summary>
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            ServiceName.Visibility     = Visibility.Collapsed;
            ServerButton.IsEnabled     = true;
            ClientButton.IsEnabled     = true;
            DisconnectButton.IsEnabled = false;
            ConversationListBox.Items.Clear();
        }
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                Button_server_start.IsEnabled      = true;
                Button_server_disconnect.IsEnabled = false;
            });
        }
Exemple #5
0
        private async void Disconnect()
        {
            if (_rfcommProvider != null)
            {
                _rfcommProvider.StopAdvertising();
                _rfcommProvider = null;
            }

            if (_controllerSocketListener != null)
            {
                _controllerSocketListener.Dispose();
                _controllerSocketListener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
                ControConnButton.IsEnabled = true;
                //回归正方向
            });
        }
 public void Disconnect()
 {
     Listening = false;
     if (provider != null)
     {
         if (isAdvertising)
         {
             provider.StopAdvertising();
         }
         provider = null;
     }                                                                                                      // StopAdvertising relentlessly causes a crash if not advertising.
     if (socketListener != null)
     {
         socketListener.Dispose(); socketListener = null;
     }
     if (writer != null)
     {
         writer.DetachStream(); writer.Dispose(); writer = null;
     }
     if (reader != null)
     {
         reader.DetachStream(); reader.Dispose(); reader = null;
     }
     if (socket != null)
     {
         socket.Dispose(); socket = null;
     }
     if (listeningTask != null)
     {
         listeningTask = null;
     }
 }
Exemple #7
0
        /// <summary>
        /// Cleanup Bluetooth resources
        /// </summary>
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            ListenButton.IsEnabled     = true;
            DisconnectButton.IsEnabled = false;
            ConversationListBox.Items.Clear();
        }
        async void InitializeBluetooth()
        {
            try
            {
                var service_id = RfcommServiceId.FromUuid(Guid.Parse("ff1477c2-7265-4d55-bb08-c3c32c6d635c"));
                provider = await RfcommServiceProvider.CreateAsync(service_id);

                StreamSocketListener listener = new StreamSocketListener();
                listener.ConnectionReceived += OnConnectionReceived;
                await listener.BindServiceNameAsync(
                    provider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // InitializeServiceSdpAttributes
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
                writer.WriteUInt32(SERVICE_VERSION);
                var data = writer.DetachBuffer();
                provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);

                provider.StartAdvertising(listener, true);
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.ToString());
            }
        }
Exemple #9
0
        /// <summary>
        /// RfcommServerの初期化
        /// </summary>
        private async void InitializeRfcommServer()
        {
            //UUIDを定義
            Guid RfcommChatServiceUuid = Guid.Parse("17fcf242-f86d-4e35-805e-546ee3040b84");

            //UUIDからRfcommProviderをイニシャライズ
            rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommChatServiceUuid));

            // SocketListenerを生成,OnConnectionReceivedをコールバックとして登録
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;

            // Listeningをスタート
            //
            //awaitはasyncキーワードによって変更された非同期メソッドでのみ使用でる.
            //中断ポイントを挿入することで,メソッドの実行を,待機中のタスクが完了するまで中断する
            //async修飾子を使用して定義され,通常1つ以上のawait式を含むメソッドが,"非同期メソッド"と呼る
            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                                                      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            //SDP属性を設定し,そのSDPレコードを他のデバイスが検索できるようにアドバタイズする
            //
            //SDP(Session Description Protcol):
            //セッションの告知・招待などを必要とするマルチメディアセッションを開始するため
            //必要な情報を記述するためのプレゼンテーション層に属するプロトコル
            InitializeServiceSdpAttributes(rfcommProvider);
            rfcommProvider.StartAdvertising(socketListener, true);
        }
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                // restart server;
                Debug.WriteLine("Restarting Server");
                await InitRfcommServer();
            });
        }
        public void Disconnect()
        {
            if (_rfcommProvider != null)
            {
                _rfcommProvider.StopAdvertising();
                _rfcommProvider = null;
            }

            if (_socketListener != null)
            {
                _socketListener.Dispose();
                _socketListener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            _isInitialized = false;

            NotifyClientDisconnected();
        }
Exemple #12
0
        public async Task init()
        {
            using (var con = new SQLiteConnection(dbName)) {
                con.Open();

                using (var cmd = con.CreateCommand()) {
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS text(ID INTEGER PRIMARY KEY AUTOINCREMENT, datetime INT, line TEXT) ";
                    cmd.ExecuteNonQuery();
                }
            }

            _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.ObexObjectPush);

            StreamSocketListener listener = new StreamSocketListener();

            listener.ConnectionReceived += OnConnectionReceived;

            await listener.BindServiceNameAsync(
                _provider.ServiceId.AsString(),
                SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            _provider.StartAdvertising(listener);
            Console.WriteLine("Server start");
            while (true)
            {
            }
            ;
        }
        private async void Disconnect()
        {
            if (_rfcommProvider != null)
            {
                _rfcommProvider.StopAdvertising();
                _rfcommProvider = null;
            }

            if (_socketListener != null)
            {
                _socketListener.Dispose();
                _socketListener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ListenButton.IsEnabled     = true;
                DisconnectButton.IsEnabled = false;
                ConversationListBox.Items.Clear();
            });
        }
        /// <summary>
        /// Make this device discoverable to other Bluetooth devices within range
        /// </summary>
        /// <returns></returns>
        private async Task <bool> MakeDiscoverable()
        {
            // Make the system discoverable. Don't repeatedly do this or the StartAdvertising will throw "cannot create a file when that file already exists."
            if (!_isBluetoothDiscoverable)
            {
                try
                {
                    Guid BluetoothServiceUuid = new Guid(Constants.BluetoothServiceUuid);
                    _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(BluetoothServiceUuid));

                    StreamSocketListener listener = new StreamSocketListener();
                    listener.ConnectionReceived += OnConnectionReceived;
                    await listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.PlainSocket);

                    // No need to set SPD attributes
                    _provider.StartAdvertising(listener, true);
                    _isBluetoothDiscoverable = true;
                }
                catch (Exception ex)
                {
                    string confirmationMessage = string.Format(BluetoothNoDeviceAvailableFormat, ex.Message);
                    await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
                }
            }

            return(_isBluetoothDiscoverable);
        }
        /// <summary>
        /// Initialize a server socket listening for incoming Bluetooth Rfcomm connections
        /// </summary>
        async void InitializeRfcommServer()
        {
            try
            {
                ListenButton.IsEnabled = false;
                DisconnectButton.IsEnabled = true;

                rfcommProvider = await RfcommServiceProvider.CreateAsync(
                    RfcommServiceId.FromUuid(RfcommChatServiceUuid));

                // Create a listener for this service and start listening
                socketListener = new StreamSocketListener();
                socketListener.ConnectionReceived += OnConnectionReceived;

                await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // Set the SDP attributes and start Bluetooth advertising
                InitializeServiceSdpAttributes(rfcommProvider);
                rfcommProvider.StartAdvertising(socketListener);

                NotifyStatus("Listening for incoming connections");
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
Exemple #16
0
        //-------------------------------------------------------------------------uruchamianie serwera
        async private void startServer()
        {
            try
            {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(
                    RfcommServiceId.FromUuid(serviceUuid));
            }
            catch (Exception e)
            {
                if ((uint)e.HResult == 0x9000000F)
                {
                    disconnect();
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                    showPopupDialog("Bluetooth jest wyłączone!\nPowrót");
                    return;
                }
            }

            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;
            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString());

            var sdpWriter = new DataWriter();

            sdpWriter.WriteByte(SdpServiceNameAttributeType);
            sdpWriter.WriteByte((byte)SdpServiceName.Length);
            sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sdpWriter.WriteString(SdpServiceName);
            rfcommProvider.SdpRawAttributes.Add(SdpServiceNameAttributeId, sdpWriter.DetachBuffer());
            rfcommProvider.StartAdvertising(socketListener);
        }
Exemple #17
0
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            state = "None";
        }
Exemple #18
0
        private async void Disconnect()
        {
            if (_provider != null)
            {
                _provider.StopAdvertising();
                _provider = null;
            }

            if (_listener != null)
            {
                _listener.Dispose();
                _listener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
        }
Exemple #19
0
        public async void StartBroadcast(NetworkController netctl)
        {
            this.netctl = netctl;

            try
            {
                commServiceProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.Constants.broadcastGuid));

                listener = new StreamSocketListener();
                listener.ConnectionReceived += RecieveConnection;
                var rfcomm = commServiceProvider.ServiceId.AsString();

                await listener.BindServiceNameAsync(commServiceProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                Logging.Log.Trace("Initializing Session Description Protocal (SDP) Attributes");
                SetupBroadcastAttributes(commServiceProvider);
                Logging.Log.Trace("SDP Attributes Initialized");

                commServiceProvider.StartAdvertising(listener, true);
            }
            catch (Exception ex)
            {
                Logging.Log.Error("An error occured advertising the bluetooth connection");
                Logging.Log.Error(ex.Message);
                return;
            }

            Console.WriteLine("Broadcasting Connections.");
        }
Exemple #20
0
        /// <summary>
        /// 切断
        /// </summary>
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            await Dispatcher.BeginInvoke(
                new Action(() => {
                ConnectButton.IsEnabled = true;
            })
                );
        }
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            //{
            //    ListenButton.IsEnabled = true;
            //    DisconnectButton.IsEnabled = false;
            //    ConversationListBox.Items.Clear();
            //});
        }
Exemple #22
0
        private void Stop(bool stopListener)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate
                {
                    Stop(stopListener);
                }));
                return;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            if (stopListener && socketListener != null)
            {
                if (rfcommProvider != null)
                {
                    rfcommProvider.StopAdvertising();
                    rfcommProvider = null;
                }

                socketListener.Dispose();
                socketListener = null;

                startButton.Enabled = true;
                stopButton.Enabled  = false;
                status.Text         = "Stopped.";
            }
            sendButton.Enabled = false;
        }
Exemple #23
0
        /// <summary>
        /// Initializes the server using RfcommServiceProvider to advertise the Chat Service UUID and start listening
        /// for incoming connections.
        /// </summary>
        private async void InitializeServer()
        {
            try
            {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommChatServiceUuid));
            }
            // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE).
            catch (Exception ex) when((uint)ex.HResult == 0x800710DF)
            {
                // The Bluetooth radio may be off.
                throw new InvalidOperationException("Make sure your Bluetooth Radio is on: " + ex.Message, ex);
            }


            // Create a listener for this service and start listening
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;
            var rfcomm = rfcommProvider.ServiceId.AsString();

            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                                                      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start Bluetooth advertising
            InitializeServiceSdpAttributes(rfcommProvider);

            try
            {
                rfcommProvider.StartAdvertising(socketListener, true);
            }
            catch (Exception e)
            {
                // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why.  Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices.
                throw new Exception(e.Message);
            }
        }
Exemple #24
0
        /// <summary> Clientとの接続を切断 </summary>
        public void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (socket != null)
            {
                if (socket.InputStream != null)
                {
                    socket.InputStream.Dispose();
                }

                if (socket.OutputStream != null)
                {
                    socket.OutputStream.Dispose();
                }
                socket.Dispose();
                socket = null;
            }
        }
Exemple #25
0
        public override async void Initialize()
        {
            System.Diagnostics.Debug.WriteLine("Initializing the Server.");

            try {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid));
            } // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE).
            catch (Exception ex) when((uint)ex.HResult == 0x800710DF)    // The Bluetooth radio may be off.
            {
                System.Diagnostics.Debug.WriteLine("Could not initialize RfcommServiceProvider");
                return;
            }

            // Create a listener for this service and start listening
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;

            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                                                      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start Bluetooth advertising
            InitializeServiceSdpAttributes(rfcommProvider);

            try {
                rfcommProvider.StartAdvertising(socketListener, true);
            } catch (Exception e) {
                // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why.  Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices.
                System.Diagnostics.Debug.WriteLine("Could not start advertising");
                return;
            }

            System.Diagnostics.Debug.WriteLine("Server Succesfully Initialized.");
        }
Exemple #26
0
        /// <summary>
        /// Initialize a server socket listening for incoming Bluetooth Rfcomm connections
        /// </summary>
        async void InitializeRfcommServer()
        {
            try
            {
                ListenButton.IsEnabled     = false;
                DisconnectButton.IsEnabled = true;

                rfcommProvider = await RfcommServiceProvider.CreateAsync(
                    RfcommServiceId.FromUuid(RfcommChatServiceUuid));

                // Create a listener for this service and start listening
                socketListener = new StreamSocketListener();
                socketListener.ConnectionReceived += OnConnectionReceived;

                await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                                                          SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // Set the SDP attributes and start Bluetooth advertising
                InitializeServiceSdpAttributes(rfcommProvider);
                rfcommProvider.StartAdvertising(socketListener);

                NotifyStatus("Listening for incoming connections");
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
        public async void InitializeRfCommServer()
        {
            try
            {
                Console.WriteLine("Starting Serwer..");
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommServiceUuid));

                // Create a listener for this service and start listening
                socketListener = new StreamSocketListener();
                socketListener.ConnectionReceived += OnConnectionReceived;
                await socketListener.BindServiceNameAsync(
                    rfcommProvider.ServiceId.AsString(),
                    SocketProtectionLevel.PlainSocket
                    );

                // Set the SDP attributes and start Bluetooth advertising
                InitializeServiceSdpAttributes(rfcommProvider);
                rfcommProvider.StartAdvertising(socketListener);
                ServerInitiated = true;
                Console.WriteLine("Server initialized..");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                ServerInitiated = false;
            }
        }
Exemple #28
0
        /// <summary>
        /// Clean up for disconnection.
        /// </summary>
        public void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            isListening = false;
        }
Exemple #29
0
 private void StopInitBrowseWpToWin()
 {
     if (provider != null)
     {
         provider.StopAdvertising();
         provider = null;
     }
 }
 public Task <IRfcommServiceProvider> CreateRfcommServiceProviderAsync(Guid serviceId)
 {
     return(Task.Run(() =>
     {
         var serviceProvider = new RfcommServiceProvider(this, serviceId);
         ServiceProviderList.Add(serviceProvider);
         return serviceProvider as IRfcommServiceProvider;
     }));
 }
Exemple #31
0
        private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider)
        {
            var sdpWriter = new DataWriter();

            sdpWriter.WriteByte(Constants.SdpServiceNameAttributeType);
            sdpWriter.WriteByte((byte)Constants.SdpServiceName.Length);
            sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sdpWriter.WriteString(Constants.SdpServiceName);
            rfcommProvider.SdpRawAttributes.Add(Constants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer());
        }
        public async void InitializeReceiver()
        {
            // Initialize the provider for the hosted RFCOMM service // RfcommServiceId FromUuid(Guid uuid);
            _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(btUuid));

            // Create a listener for this service and start listening
            _listener = new StreamSocketListener();
            _listener.ConnectionReceived += Listener_ConnectionReceived;

            await _listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start advertising
            InitializeServiceSdpAttributes(_provider);
            _provider.StartAdvertising(_listener);
        }
        /// <summary>
        /// Creates the SDP record that will be revealed to the Client device when pairing occurs.  
        /// </summary>
        /// <param name="rfcommProvider">The RfcommServiceProvider that is being used to initialize the server</param>
        private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider)
        {
            var sdpWriter = new DataWriter();

            // Write the Service Name Attribute.
            sdpWriter.WriteByte(Constants.SdpServiceNameAttributeType);

            // The length of the UTF-8 encoded Service Name SDP Attribute.
            sdpWriter.WriteByte((byte)Constants.SdpServiceName.Length);

            // The UTF-8 encoded Service Name value.
            sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sdpWriter.WriteString(Constants.SdpServiceName);

            // Set the SDP Attribute on the RFCOMM Service Provider.
            rfcommProvider.SdpRawAttributes.Add(Constants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer());
        }
        /// <summary>
        /// Initializes the server using RfcommServiceProvider to advertise the Chat Service UUID and start listening
        /// for incoming connections.
        /// </summary>
        private async void InitializeRfcommServer()
        {
            ListenButton.IsEnabled = false;
            DisconnectButton.IsEnabled = true;

            try
            {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid));
            }
            // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE).
            catch (Exception ex) when ((uint)ex.HResult == 0x800710DF)
            {
                // The Bluetooth radio may be off.
                rootPage.NotifyUser("Make sure your Bluetooth Radio is on: " + ex.Message, NotifyType.ErrorMessage);
                ListenButton.IsEnabled = true;
                DisconnectButton.IsEnabled = false;
                return;
            }
            

            // Create a listener for this service and start listening
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;
            var rfcomm = rfcommProvider.ServiceId.AsString(); 

            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start Bluetooth advertising
            InitializeServiceSdpAttributes(rfcommProvider);

            try
            {
                rfcommProvider.StartAdvertising(socketListener, true);
            }
            catch (Exception e)
            {
                // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why.  Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices.  
                rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
                ListenButton.IsEnabled = true;
                DisconnectButton.IsEnabled = false;
                return;
            }
            
            rootPage.NotifyUser("Listening for incoming connections", NotifyType.StatusMessage);
        }
        private void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            DataWriter writer = new DataWriter();
                                                                                                                                                                                                                                                                                                     
            // First write the attribute type
            writer.WriteByte(SERVICE_NAME_ATTRIBUTE_TYPE);
            // Then write the data

            // The length of the UTF-8 encoded string.
            writer.WriteByte((byte)SERVICE_NAME.Length);
            // The UTF-8 encoded string.
            writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            writer.WriteString(SERVICE_NAME);

            provider.SdpRawAttributes.Add(SERVICE_NAME_ATTRIBUTE_ID, writer.DetachBuffer());
        }
        /// <summary>
        /// Cleanup Bluetooth resources
        /// </summary>
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            ListenButton.IsEnabled = true;
            DisconnectButton.IsEnabled = false;
            ConversationListBox.Items.Clear();
        }
        public void DeInitialize()
        {
            if (cancellationTokenSource != null)
            {
                cancellationTokenSource.Cancel();
            }
            cancelReceiving = true;

            _provider.StopAdvertising();
            _provider = null;

            _listener.Dispose();
            _listener = null;

            _streamSocket.Dispose();
            _streamSocket = null;
        }
        public override async void receive_file(String devicename, String bluid, int not)
        {
            try {
                _stopwatch.Start();

                _rfcomm_provider = await RfcommServiceProvider.CreateAsync(
                    RfcommServiceId.FromUuid(new Guid(bluid)));

                _bluetooth_listener = new StreamSocketListener();
                _bluetooth_listener.ConnectionReceived += _bluetooth_connection_received;

                await _bluetooth_listener.BindServiceNameAsync(_rfcomm_provider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                _rfcomm_provider.StartAdvertising(_bluetooth_listener);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }
        }
Exemple #39
0
        /// <summary>
        /// Starts the server advertising its service over bluetooth.
        /// </summary>
        /// <returns>The asynchronous request.</returns>
        /// <exception cref="BluetoothDisabledException">
        /// Thrown when bluetooth is disabled or otherwise not available on the device.
        /// </exception>
        /// <exception cref="SecurityException">
        /// Thrown when the application is missing the required capabilities in its manifest.
        /// </exception>
        public async Task Start()
        {
            try
            {
                if (_serviceProvider == null)
                    _serviceProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(ServiceID));

                var listener = new StreamSocketListener();
                listener.ConnectionReceived += ListenerOnConnectionReceived;

                await listener.BindServiceNameAsync(_serviceProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
                
                _serviceProvider.StartAdvertising(listener);
            } 
            catch (Exception ex)
            {
                var errorCode = (uint) ex.HResult;
                
                ServerState = BluetoothServerState.Stopped;

                if (errorCode == ERROR_BLUETOOTH_DISABLED)
                    throw new BluetoothDisabledException();
               
                if (errorCode == ERROR_MISSING_CAPABILITIES)
                    throw new SecurityException("This application is missing the required capabilities in its manifest");

                throw;
            }

            ServerState = BluetoothServerState.Advertising;
        }
    private async Task InitBrowseWpToWin()
    {
      provider = await RfcommServiceProvider.CreateAsync(
                       RfcommServiceId.FromUuid(rfcommServiceUuid));

      var listener = new StreamSocketListener();
      listener.ConnectionReceived += HandleConnectionReceived;

      await listener.BindServiceNameAsync(
        provider.ServiceId.AsString(),
        SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

      using (var writer = new DataWriter())
      {
        writer.WriteByte(ServiceVersionAttributeType);
        writer.WriteUInt32(ServiceVersion);

        var data = writer.DetachBuffer();
        provider.SdpRawAttributes.Add(ServiceVersionAttributeId, data);
        provider.StartAdvertising(listener);
      }
    }
 private void StopInitBrowseWpToWin()
 {
   if (provider != null)
   {
     try
     {
       provider.StopAdvertising();
       provider = null;
     }
     catch (Exception)
     {
       // Yes, this is bad, but for some reason StopAdvertising crashes the app sometimes.
     }
   }
 }
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

        
        }
        void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(SERVICE_VERSION);

            var data = writer.DetachBuffer();
            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
        /// <summary>
        /// Cleanup Bluetooth resources
        /// </summary>
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            ServiceName.Visibility = Visibility.Collapsed;
            ServerButton.IsEnabled = true;
            ClientButton.IsEnabled = true;
            DisconnectButton.IsEnabled = false;
            ConversationListBox.Items.Clear();
        }
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ListenButton.IsEnabled = true;
                DisconnectButton.IsEnabled = false;
                ConversationListBox.Items.Clear();
            });
        }