private void BtComm() { BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter; string address = adapter.BondedDevices.FirstOrDefault(device => device.Name.Contains("Rover1"))?.Address; try { BluetoothDevice device = adapter.GetRemoteDevice(address); adapter.CancelDiscovery(); BluetoothSocket socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB")); socket.Connect(); Stream output = socket.OutputStream; _readerThread = new Thread(() => ReaderLoop(socket.InputStream)); _readerThread.Start(); foreach (string message in _messageBuffer.GetConsumingEnumerable()) { byte[] data = Encoding.ASCII.GetBytes(message); output.Write(data, 0, data.Length); output.Flush(); } _readerThread.Abort(); Thread.Sleep(2000); output.Close(); socket.Close(); socket.Dispose(); device.Dispose(); } catch (Exception e) { Log.Error("RoverController", $"Exception {e}"); } }
public static async Task DisconnectAsync(bool removeLastDeviceInfo) { var batteryCharacteristic = await BluetoothDevice.GetGattCharacteristicAsync(GattCharacteristicUuids.BatteryLevel); if (batteryCharacteristic != null) { await batteryCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); } var screenshotsCharacteristic = await BluetoothDevice.GetGattCharacteristicAsync(Asteroid.ScreenshotContentCharacteristicUuid); if (screenshotsCharacteristic != null) { await screenshotsCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); } if (BluetoothDevice != null) { BluetoothDevice.ConnectionStatusChanged -= OnBluetoothDeviceConnectionStatusChanged; BluetoothDevice.Dispose(); BluetoothDevice = null; Current = null; if (removeLastDeviceInfo) { UpdateLastSavedDeviceInfo(string.Empty, string.Empty); } } }
public void Dispose() { #if WINDOWS_UWP if (m_btDevice != null) { m_btDevice.Dispose(); m_btDevice = null; } #endif }
public async Task <IEnumerable <IGattService> > ConnectAndDiscoverServicesAsync(bool autoConnect, CancellationToken token) { CancellationTokenRegistration tokenRegistration; lock (_lock) { if (State != BluetoothLEDeviceState.Disconnected) { return(null); } State = BluetoothLEDeviceState.Connecting; _bluetoothDevice = _bluetoothAdapter.GetRemoteDevice(Address); if (_bluetoothDevice == null) { State = BluetoothLEDeviceState.Disconnected; return(null); } if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { _bluetoothGatt = _bluetoothDevice.ConnectGatt(_context, autoConnect, this, BluetoothTransports.Le); } else { _bluetoothGatt = _bluetoothDevice.ConnectGatt(_context, autoConnect, this); } if (_bluetoothGatt == null) { _bluetoothDevice.Dispose(); _bluetoothDevice = null; State = BluetoothLEDeviceState.Disconnected; return(null); } _connectCompletionSource = new TaskCompletionSource <IEnumerable <IGattService> >(TaskCreationOptions.RunContinuationsAsynchronously); tokenRegistration = token.Register(() => { lock (_lock) { Disconnect(); _connectCompletionSource?.SetResult(null); } }); } var result = await _connectCompletionSource.Task; _connectCompletionSource = null; tokenRegistration.Dispose(); return(result); }
private async Task DisconnectDevice() { if (ChosenDevice != null) { DeviceInformation delDev = ChosenDevice; if (IsMiBand2 && miBand != null) { string bandName = ChosenDevice.Name; AddLog($"Disconnecting from {bandName}...", AppLog.LogCategory.Debug); if (miBand.IsConnected()) { try { await miBand.HeartRate.UnsubscribeFromHeartRateNotificationsAsync(MiBandHRValueChanged); await miBand.HeartRate.SetRealtimeHeartRateMeasurement(MiBand2SDK.Enums.RealtimeHeartRateMeasurements.DISABLE); } catch { AddLog($"Device not connected.", AppLog.LogCategory.Debug); } } miBand = null; IsMiBand2 = false; } else { AddLog($"Disconnectiong from {ChosenDevice.Name}...", AppLog.LogCategory.Info); try { await HRReaderCharacteristic. WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); // notify the device the deisconnection HRReaderCharacteristic.Service.Dispose(); HRReaderService.Dispose(); BluetoothDevice.Dispose(); } catch { AddLog("Device comunication problem. Can't send disconnect signal.", AppLog.LogCategory.Debug); } } DispatcherTimer.Stop(); HrTimerController.Stop(); ChosenDevice = null; InitializeUIComponents(); AddLog($"{delDev.Name} sucessfully disconnected.", AppLog.LogCategory.Info); } else { AddLog($"There is no connected device.", AppLog.LogCategory.Info); return; } }
public void Dispose() { _reader?.Close(); _writer?.Close(); _socket?.Close(); _device?.Dispose(); _reader = _writer = null; _socket = null; _device = null; IsConnected = false; }
public void Disconnect() { if (IsConnected) { IsConnected = false; _bluetoothDevice.Dispose(); _bluetoothSocket.OutputStream.Close(); _bluetoothSocket.Close(); _bluetoothSocket = null; _bluetoothDevice = null; _bluetoothAdapter = null; } }
private void PlatformDispose(bool disposing) { if (disposing) { CloseGATT(); _callback.ConnectionStateChanged -= OnConnectionStateChanged; _callback.ReadRemoteRSSI -= OnReadRemoteRSSI; _callback.ServicesDiscovered -= OnServicesDiscovered; _device.Dispose(); _callback.Dispose(); } }
public bool Connect() { if (!adapter.IsEnabled) { BluetoothDisabledEvent.Invoke(this, new EventArgs()); return(false); } adapter.StartDiscovery(); try { device = adapter.BondedDevices.Where(x => x.Name == "HC-06").FirstOrDefault(); device.SetPairingConfirmation(false); device.Dispose(); device.SetPairingConfirmation(true); device.CreateBond(); } catch (Exception exception) { Log.Debug(TAG, exception.ToString()); } adapter.CancelDiscovery(); socket = device.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")); try { socket.Connect(); listenThread = new Thread(Listener); if (listenThread.IsAlive == false) { listenThread.Start(); } } catch (Exception exception) { Toast.MakeText(Application.Context, "Cannot connect to HC-06.", ToastLength.Short).Show(); Log.Debug(TAG, exception.ToString()); return(false); } return(true); }
public void Disconnect() { lock (_lock) { if (_bluetoothGatt != null) { _bluetoothGatt.Disconnect(); _bluetoothGatt.Close(); _bluetoothGatt.Dispose(); _bluetoothGatt = null; _bluetoothDevice.Dispose(); _bluetoothDevice = null; } State = BluetoothLEDeviceState.Disconnected; } }
private async void CloseCurrentlyConnectedDevice() { if (bluetoothDevice != null) { // notify collback that we are about to close the device if (deviceCloseCallback != null) { deviceCloseCallback(this, deviceInformation); } bluetoothDevice.Dispose(); bluetoothDevice = null; String btdeviceId = deviceId; await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { rootPage.StatusBar(btdeviceId + " is closed", BarStatus.Warnning); })); } }
public void Disconnect() { try { listenThread.Abort(); listenThread = null; device.Dispose(); socket.OutputStream.WriteByte(187); socket.OutputStream.Close(); socket.Close(); socket = null; } catch (Exception exception) { Log.Debug(TAG, exception.ToString()); }; }
public void Disconnect() { lock (_lock) { _onDeviceDisconnected = null; _onCharacteristicChanged = null; if (_bluetoothGatt != null) { _bluetoothGatt.Disconnect(); _bluetoothGatt.Close(); _bluetoothGatt.Dispose(); _bluetoothGatt = null; _bluetoothDevice.Dispose(); _bluetoothDevice = null; } State = BluetoothLEDeviceState.Disconnected; } }
public override void Dispose() { nativeDevice.Dispose(); }
private bool PrintToDevice(string text, int noofcopy) { bool isPrinted = false; msg = ""; Stream mmOutputStream = null; try { UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); mmSocket = mmDevice.CreateInsecureRfcommSocketToServiceRecord(uuid); if (mmSocket == null) { msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound); return(isPrinted); } if (mmDevice.BondState == Bond.Bonded) { TrytoConnect(mmSocket); Thread.Sleep(300); mmOutputStream = mmSocket.OutputStream; byte[] charfont; if (iSPrintCompLogo) { PrintLogo(mmOutputStream); } charfont = new Byte[] { 27, 64 }; //Char font 9x17 mmOutputStream.Write(charfont, 0, charfont.Length); if (apara.PaperSize == "58mm") { charfont = new Byte[] { 27, 33, 1 }; //Char font 9x17 mmOutputStream.Write(charfont, 0, charfont.Length); } if (apara.PaperSize == "80mm") { charfont = new Byte[] { 27, 33, 0 }; //Char font 12x24 mmOutputStream.Write(charfont, 0, charfont.Length); } charfont = new Byte[] { 28, 38 }; mmOutputStream.Write(charfont, 0, charfont.Length); byte[] cc = Encoding.GetEncoding("GB18030").GetBytes(text); for (int i = 0; i < noofcopy; i++) { int rem; int result = Math.DivRem(cc.Length, 2048, out rem); int pos = 0; for (int line = 0; line < result; line++) { IsStreamCanWrite(mmOutputStream); mmOutputStream.Write(cc, pos, 2048); pos += 2048; } if (rem > 0) { mmOutputStream.Write(cc, pos, rem); } Thread.Sleep(3000); } Thread.Sleep(300); charfont = new Byte[] { 28, 46 }; mmOutputStream.Write(charfont, 0, charfont.Length); mmOutputStream.Close(); mmSocket.Close(); isPrinted = true; } else { //txtv.Text = "Device not connected"; msg = callingActivity.Resources.GetString(Resource.String.msg_bluetoothnofound); //errmsg.Append(msg); } } catch (Exception ex) { msg = ex.Message; } finally { if (mmOutputStream != null) { mmOutputStream.Close(); mmOutputStream = null; } if (mmSocket != null) { mmSocket.Close(); mmSocket = null; } if (mmDevice != null) { mmDevice.Dispose(); mmDevice = null; } } return(isPrinted); }