private void DoStartAdvertising() { Task.Run(async() => { try { while (_socket != null) { var socket = await _socket.AcceptAsync(); ConnectionReceived?.Invoke(this, new RfcommConnectionReceivedEventArgs(new NetworkStream(socket))); } } catch { //TODO: only trap thread cancellation here } }); }
private async void ReceiveLoop() { await Task.Yield(); while (IsActive) { try { BluetoothSocket socket = await ServerSocket.AcceptAsync(1000); if (socket != null) { BluetoothRFCOMMAccessPoint accessPoint = new BluetoothRFCOMMAccessPoint(new BluetoothDevice(socket.RemoteDevice), new BluetoothPort()); BluetoothConnection connection = new BluetoothConnection(ConnectionProvider, socket, Port, accessPoint); OnConnectionReceive(connection); } } catch (Exception ex) { throw ex; } } }
public async Task <bool> StartServer(e_BtMode mode) { try { if (!Init()) { return(false); } if (mode == e_BtMode.LowEnergy) { var uuid_ser = Java.Util.UUID.FromString(BleConstants.BLE_SERVER_SERVICE_UUID); var uuid_ch = Java.Util.UUID.FromString(BleConstants.BLE_SERVER_CH_UUID); /// Set advertising AdvertiseSettings settings = new AdvertiseSettings.Builder() .SetConnectable(true) .SetAdvertiseMode(AdvertiseMode.LowLatency) .SetTxPowerLevel(AdvertiseTx.PowerMedium) .Build(); AdvertiseData advertiseData = new AdvertiseData.Builder() .SetIncludeDeviceName(true) .SetIncludeTxPowerLevel(true) .Build(); AdvertiseData scanResponseData = new AdvertiseData.Builder() //.AddServiceUuid(new ParcelUuid(uuid_ser)) //otherwise AdvertiseFailure for DataTooLarge //.AddServiceData(new ParcelUuid(uuid_ser), new byte[] { 0x01, 0x02 }) .SetIncludeDeviceName(true) .SetIncludeTxPowerLevel(true) .Build(); _CentralManager.Adapter.BluetoothLeAdvertiser.StartAdvertising(settings, advertiseData, scanResponseData, _AdvertiseCallback); /// Set ble server _GattServer = _CentralManager.OpenGattServer(Android.App.Application.Context, _GattServerCallback); _Mode = mode; var write_ch = new BluetoothGattCharacteristic(uuid_ch, GattProperty.WriteNoResponse, GattPermission.Write); var service = new BluetoothGattService(uuid_ser, GattServiceType.Primary); service.AddCharacteristic(write_ch); _GattServer.AddService(service); } else if (mode == e_BtMode.Socket) { _Mode = mode; _ServerSocket = _CentralManager.Adapter.ListenUsingRfcommWithServiceRecord("server_socket", Java.Util.UUID.FromString(BleConstants.BLE_SERVER_SOCKET_UUID)); _BluetoothSocket = await _ServerSocket.AcceptAsync(); await Task.Run(ServerSocketManager); } else { SERVER_ERR("start server failed"); return(false); } return(true); } catch (Exception ex) { SERVER_ERR("start server error", ex); return(false); } }
//private void BtnStatus_Clicked(object sender, EventArgs e) //{ // var state = ble.State; // this.DisplayAlert("Notice", state.ToString(), "OK !"); // if (state == BluetoothState.Off) // { // btnStatus.TextColor = Color.Red; // } // else // { // btnStatus.TextColor = Color.Green; // } //} #region HETWound Connection private async void BtnConnect_Clicked(object sender, EventArgs e) { if (device != null) { switch (device.Name) { case "HET Wound v2.1-001": //LOGIC await adapter.StopScanningForDevicesAsync(); string notif = ("You've connected to " + device.Name); await adapter.ConnectToDeviceAsync(device); Service = await device.GetServiceAsync(het); var char4 = await Service.GetCharacteristicAsync(char4_uuid); if (MainPage.SetDeviceName != null) { MainPage.SetDeviceName(device.Name, "Connected"); } char1 = await Service.GetCharacteristicAsync(char1_uuid); try { await char1.WriteAsync(cmd_string); } catch { } char4.ValueUpdated += CharacteristicsChanged; btnConnect.TextColor = Color.Green; await char4.StartUpdatesAsync(); await DisplayAlert("Notice", notif, "OK"); break; case "Ticwatch E C36B": //LOGIC await adapter.StopScanningForDevicesAsync(); string notif_w = ("You've connected to " + device.Name); //await adapter.ConnectToDeviceAsync(device); try { // set up the server, start and stop listening for new connections BluetoothServerSocket serverSocket = null; // start listening for a new connection if (!isClosed) { try { bluetooth = BluetoothAdapter.DefaultAdapter; if (bluetooth == null) { Console.WriteLine("NO ADAPTER"); } // MY_UUID is the app's UUID string, also used by the client code Console.WriteLine("Starting the server listener"); serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid)); // keep trying to find a client serverClientSocket = await serverSocket.AcceptAsync(); } catch (IOException ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); await DisplayAlert("Notice", "Cannot connect to device. Please try again.", "OK"); return; } // If a connection was accepted if (serverClientSocket != null) { var device = serverClientSocket.RemoteDevice; bluetooth = null; serverSocket.Close(); // Do work to manage the connection (in a separate thread) try { await DisplayAlert("Notice", notif_w, "OK"); btnConnect.TextColor = Color.Green; await StartListening(serverClientSocket); } catch (Exception ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK"); } } } } catch (Exception ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); } break; default: await DisplayAlert("Notice", "Device not supported !", "OK"); btnConnect.TextColor = Color.Red; break; } } else { await DisplayAlert("Notice", "No Device Selected!", "OK"); btnConnect.TextColor = Color.Red; } //try //{ // if (Xamarin.Forms.Device.RuntimePlatform == Xamarin.Forms.Device.Android) // { // await adapter.StopScanningForDevicesAsync(); // } // if (device != null && device.Name == "HET Wound v2.1-001") // { // string notif = ("You've connected to " + device.Name); // await adapter.ConnectToDeviceAsync(device); // Service = await device.GetServiceAsync(het); // var char4 = await Service.GetCharacteristicAsync(char4_uuid); // if (MainPage.SetDeviceName != null) // { // MainPage.SetDeviceName(device.Name, "Connected"); // } // char1 = await Service.GetCharacteristicAsync(char1_uuid); // try // { // await char1.WriteAsync(cmd_string); // } // catch // { // } // char4.ValueUpdated += CharacteristicsChanged; // btnConnect.TextColor = Color.Green; // await char4.StartUpdatesAsync(); // await DisplayAlert("Notice", notif, "OK"); // } // else // { // await DisplayAlert("Notice", "Device not supported !", "OK"); // btnConnect.TextColor = Color.Red; // } //} //catch(DeviceConnectionException ex) //{ // await DisplayAlert("Notice", ex.Message.ToString(), "OK"); // btnConnect.TextColor = Color.Red; //} }
public async void ConnectToWatchAsync() { isClosed = false; system_ids = new Guid[] { watch_uuid }; foreach (IDevice dev in adapter.GetSystemConnectedOrPairedDevices(system_ids)) { if (dev.Name == "Ticwatch E C36B") { try { // set up the server, start and stop listening for new connections serverSocket = null; // start listening for a new connection if (!isClosed) { try { bluetooth = BluetoothAdapter.DefaultAdapter; if (bluetooth == null) { var message = new NotifyMessage { Message = "Bluetooth turned off or not available" }; Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(message, "NotifyMessage")); } // MY_UUID is the app's UUID string, also used by the client code Console.WriteLine("Starting the server listener"); serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid)); // keep trying to find a client while (serverClientSocket == null) { serverClientSocket = await serverSocket.AcceptAsync(); } } catch (IOException ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); //await DisplayAlert("Notice", "Cannot connect to device. Please try again.", "OK"); return; } // If a connection was accepted if (serverClientSocket != null) { var device = serverClientSocket.RemoteDevice; bluetooth = null; serverSocket.Close(); // Do work to manage the connection (in a separate thread) try { //await DisplayAlert("Notice", notif_w, "OK"); isClosed = true; StartListeningAsync(serverClientSocket, cancellationToken); } catch (Exception ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); //await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK"); } } } else { if (serverClientSocket != null) { serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid)); var device = serverClientSocket.RemoteDevice; bluetooth = null; serverSocket.Close(); // Do work to manage the connection (in a separate thread) try { //await DisplayAlert("Notice", notif_w, "OK"); StartListeningAsync(serverClientSocket, cancellationToken); } catch (Exception ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); //await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK"); } } } } catch (Exception ex) { ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString()); } } } }