private void connectToGattForceBleTransportAPI(IDevice device, bool autoconnect) { BluetoothDevice nativeDevice = ((BluetoothDevice)device.NativeDevice); //This parameter is present from API 18 but only public from API 23 //So reflection is used before API 23 if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { //no transport mode before lollipop, it will probably not work... gattCallBackError 133 again alas nativeDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback); } else if (Build.VERSION.SdkInt < BuildVersionCodes.M) { Method m = nativeDevice.Class.GetDeclaredMethod("connectGatt", new Java.Lang.Class[] { Java.Lang.Class.FromType(typeof(Context)) , Java.Lang.Boolean.Type , Java.Lang.Class.FromType(typeof(BluetoothGattCallback)) , Java.Lang.Integer.Type }); int transport = nativeDevice.Class.GetDeclaredField("TRANSPORT_LE").GetInt(null); // LE = 2, BREDR = 1, AUTO = 0 BluetoothGatt mGatt = (BluetoothGatt)m.Invoke(nativeDevice, new Java.Lang.Object[] { Application.Context, false, _gattCallback, transport }); } else { nativeDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback, BluetoothTransports.Le); } }
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); }
/// <summary> /// Connects to the GATT server hosted on the Bluetooth LE device. /// </summary> /// <param name="address"> The device address of the destination device. /// </param> /// <returns> Return true if the connection is initiated successfully. The connection result /// is reported asynchronously through the /// {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} /// callback. </returns> public virtual bool Connect(Context context, BluetoothDevice device) { if (device == null) { Debug.WriteLine(TAG, "Device not found. Unable to connect."); return(false); } // Previously connected device. Try to reconnect. if (DeviceAddress != null && device.Address.Equals(DeviceAddress) && Gatt != null) { Debug.WriteLine(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (Gatt.Connect()) { SetmConnectionState(STATE_CONNECTING); return(true); } else { return(false); } } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. Gatt = device.ConnectGatt(context, false, mGattCallback); RefreshDeviceCache(Gatt); Debug.WriteLine(TAG, "Trying to create a new connection."); DeviceAddress = device.Address; SetmConnectionState(STATE_CONNECTING); return(true); }
public void connect() { if (adapter == null) { Log.Debug(tag, "BluetoothAdapter is null"); } BluetoothLeScanner scaner = adapter.BluetoothLeScanner; if (scaner == null) { Log.Error(tag, "BluetoothLeScanner is null"); } try { device = adapter.GetRemoteDevice(mac); if (device == null) { Log.Debug(tag, "Device não encontrado"); } gatt = device.ConnectGatt(this, true, gattCallBack); } catch (System.Exception ex) { Log.Debug(tag, ex.ToString()); } }
private void ConnectToGattForceBleTransportAPI(bool autoconnect, CancellationToken cancellationToken) { //This parameter is present from API 18 but only public from API 23 //So reflection is used before API 23 if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { //no transport mode before lollipop, it will probably not work... gattCallBackError 133 again alas var connectGatt = BluetoothDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback); _connectCancellationTokenRegistration.Dispose(); _connectCancellationTokenRegistration = cancellationToken.Register(() => DisconnectAndClose(connectGatt)); } else if (Build.VERSION.SdkInt < BuildVersionCodes.M) { var m = BluetoothDevice.Class.GetDeclaredMethod("connectGatt", new Java.Lang.Class[] { Java.Lang.Class.FromType(typeof(Context)), Java.Lang.Boolean.Type, Java.Lang.Class.FromType(typeof(BluetoothGattCallback)), Java.Lang.Integer.Type }); var transport = BluetoothDevice.Class.GetDeclaredField("TRANSPORT_LE").GetInt(null); // LE = 2, BREDR = 1, AUTO = 0 m.Invoke(BluetoothDevice, Application.Context, false, _gattCallback, transport); } else { var connectGatt = BluetoothDevice.ConnectGatt(Application.Context, autoconnect, _gattCallback, BluetoothTransports.Le); _connectCancellationTokenRegistration.Dispose(); _connectCancellationTokenRegistration = cancellationToken.Register(() => DisconnectAndClose(connectGatt)); } }
private void bluetoothScan() { if (Ble == null) { Ble = BluetoothAdapter.DefaultAdapter; } Debug.Write("\tStarting BLE analysis"); Debug.WriteLine("\t========================================================="); foreach (var device in Ble.BondedDevices) { Debug.WriteLine("\t Device Paired -- " + device.Name); } Debug.WriteLine("\t========================================================="); BluetoothDevice accuChek = Ble.BondedDevices.FirstOrDefault(x => x.Name == "Accu-Chek"); if (accuChek == null) { Debug.WriteLine("\t No Accu-Chek Found"); return; } GattCallbackService.AttachCharacteristicConsumer(new GlucoseCharacteristicConsumer(), new GlucoseContextCharacteristicConsumer()); var connection = accuChek.ConnectGatt(Android.App.Application.Context, true, GattCallbackService); }
public void Connect(ConnectParameters connectParameters, CancellationToken token) { if (token.IsCancellationRequested) { return; } _currentConnectionToken = token; IsOperationRequested = true; if (connectParameters.ForceBleTransport) { ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect); } else { /*_gatt = */ var t = BluetoothDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback); if (t == null) { throw new Exception("Unknown error"); } } }
public void Connect() { if (gatt == null) { gatt = device.ConnectGatt(service, false, this); } }
//Connetti da device Bond (paired) private void MyReceiver_Bounded_ConnectDevice_Event(BluetoothDevice obj) { BluetoothGatt g = obj.ConnectGatt(context, false, this); Java.Lang.Reflect.Method m = g.Class.GetMethod("refresh", new Java.Lang.Class[0]); if (m != null) { m.Invoke(g, new Java.Lang.Object[0]); } }
private void PlatformConnect() { if (_gatt == null) { if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { // 使用 LE 传输方式进行连接, 避免设备不支持 BR/EDR 方式时出现 133 连接失败 _gatt = _device.ConnectGatt(Application.Context, false, _callback, BluetoothTransports.Le); } else { _gatt = _device.ConnectGatt(Application.Context, false, _callback); } } else { _gatt.Connect(); } }
private void OnDeviceConnect() { Log.Error("dana.ye->xamarin->bt", "手动点击按钮来停止扫描周围的蓝牙设备"); btAdapter.CancelDiscovery(); /*try * { #pragma warning disable CS0618 // 类型或成员已过时 * btAdapter.StopLeScan(bleScanCallback); #pragma warning restore CS0618 // 类型或成员已过时 * } * catch (Exception e) * { * Log.Error("dana.ye->xamarin->bt", "stopLeScan时出错 : " + e.Message); * }*/ handler.RemoveCallbacks(action); if (gatt != null) { gatt.Disconnect(); gatt.Close(); } Log.Error("dana.ye->xamarin->bt", "即将进行BLE的设备连接"); String addr = searchedDevices[adapter.GetChooseItem()].Address; SingleGattService.GetInstance().Address = addr; BluetoothDevice device = btAdapter.GetRemoteDevice(addr); GattCallBack mGattCallback = new GattCallBack(this); SingleGattService.GetInstance().CurCallback = mGattCallback; if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M) { Log.Error("dana.ye->xamarin->bt", "SdkInt >= M"); gatt = device.ConnectGatt(this, false, mGattCallback, BluetoothTransports.Le); } else { Log.Error("dana.ye->xamarin->bt", "SdkInt < M"); gatt = device.ConnectGatt(this, false, mGattCallback); } }
private void LeSensorConnect(Object sender, DoWorkEventArgs e, BluetoothDevice dev) { SensorStateBroadcastReceiver rec = new SensorStateBroadcastReceiver(); System.Timers.Timer sensorTimeOut = new System.Timers.Timer(); BGattCallback bcallback = new BGattCallback(); BluetoothGatt g = dev.ConnectGatt(Application.Context, true, bcallback); sensorTimeOut.AutoReset = false; sensorTimeOut.Interval = AppUtil.SENSOR_CONNECT_TIMEOUT; sensorTimeOut.Elapsed += delegate { sensorTimeOut.Enabled = false; sendDisconnectStateUpdate(dev.Address); Android.App.Application.Context.UnregisterReceiver(rec); }; rec.SensorConnect += delegate { sensorTimeOut.Enabled = false; Android.App.Application.Context.UnregisterReceiver(rec); }; rec.SensorDisconnect += delegate { sensorTimeOut.Enabled = false; Android.App.Application.Context.UnregisterReceiver(rec); }; sensorTimeOut.Enabled = true; IntentFilter fil = new IntentFilter(); fil.AddAction(AppUtil.SENSOR_CONNECT_ACTION); fil.AddAction(AppUtil.SENSOR_DISCONNECT_ACTION); fil.Priority = 98; Android.App.Application.Context.RegisterReceiver(rec, fil); System.Timers.Timer cancelCheck = new System.Timers.Timer(); cancelCheck.AutoReset = true; cancelCheck.Interval = 5 * 1000; cancelCheck.Elapsed += delegate { BackgroundWorker worker = (BackgroundWorker)sender; if (worker.CancellationPending) { g.Close(); cancelCheck.Enabled = false; } }; cancelCheck.Enabled = true; }
public bool Connect() { this.IsConnected = false; var startTime = DateTime.Now; var isWait = true; while (isWait) { if (_receiver.Device != null) { isWait = false; } else { var timeout = DateTime.Now - startTime; if (timeout.TotalMilliseconds > this.Timeout) { isWait = false; } } Task.Delay(50).Wait(); } if (_receiver.Device == null) { throw new Exception("Scanner not found."); } _device = _receiver.Device; _bluetoothGatt = _device.ConnectGatt(Xamarin.Forms.Forms.Context, false, _scannerServiceCallback); isWait = true; while (isWait) { isWait = !this.IsConnected; if (isWait) { var timeout = DateTime.Now - startTime; if (timeout.TotalMilliseconds > this.Timeout) { throw new Exception("Scanner connection timeout."); } Task.Delay(50).Wait(); } } return(this.IsConnected); }
public void Connect() { BluetoothManager bluetoothManager = (BluetoothManager)ctx.GetSystemService(Context.BluetoothService); if (bluetoothManager == null) { LogMessage("Unable to initialize BluetoothManager."); throw new Exception("Unable to initialize BluetoothManager."); } if (bluetoothManager.Adapter == null) { LogMessage("Unable to obtain a BluetoothAdapter."); throw new Exception("Unable to obtain a BluetoothAdapter."); } //stop scanning if scanning still in progress bluetoothManager.Adapter.StopLeScan(leScanCallback); mGattCallback = new BluetoothReaderGattCallback(); mGattCallback.ConnectionStateChange += MGattCallback_ConnectionStateChange; mBluetoothReaderManager = new BluetoothReaderManager(); mBluetoothReaderManager.ReaderDetection += MBluetoothReaderManager_ReaderDetection; if (mBluetoothGatt != null) { LogMessage("Clear old GATT connection"); mBluetoothGatt.Disconnect(); mBluetoothGatt.Close(); mBluetoothGatt = null; } BluetoothDevice device = bluetoothManager.Adapter.GetRemoteDevice(mDeviceAddress); if (device == null) { LogMessage("Device not found. Unable to connect."); OnStateChanged(new StateChangedEventArgs() { State = DriverState.ReaderDiconnected }); throw new Exception("Device not found. Unable to connect."); } //Connect gat will connect and call mGattCallback which in turn calls detect reader mBluetoothGatt = device.ConnectGatt(ctx, false, mGattCallback); }
public void Connect(ConnectParameters connectParameters) { IsOperationRequested = true; if (connectParameters.ForceBleTransport) { ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect); } else { /*_gatt = */ BluetoothDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback); } }
public void Connect(ConnectParameters connectParameters, CancellationToken cancellationToken) { IsOperationRequested = true; if (connectParameters.ForceBleTransport) { ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect, cancellationToken); } else { var connectGatt = BluetoothDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback); _connectCancellationTokenRegistration.Dispose(); _connectCancellationTokenRegistration = cancellationToken.Register(() => DisconnectAndClose(connectGatt)); } }
// Implemented from IRig public void Connect() { if (gatt != null) { return; } gatt = device.ConnectGatt(service, false, this); /* * handler.PostDelayed(() => { * this.UpdateMockData(); * }, 100); */ }
public void ConnectGatt(BluetoothDevice device) { if (device == null) { if (Gatt != null) { Gatt.Close(); Gatt = null; } return; } Gatt = device.ConnectGatt(this, false, new DT1WatchDogGattCallback(this)); Gatt.RequestConnectionPriority(GattConnectionPriority.High); }
public void Connetti(BluetoothDevice device) { Android.Bluetooth.Bond b = device.BondState; if ((b == Bond.Bonded))// | (b==Bond.None)) { BluetoothGatt g = device.ConnectGatt(this.context, false, this); /* * Java.Lang.Reflect.Method m = g.Class.GetMethod("refresh", new Java.Lang.Class[0]); * if (m != null) * { * m.Invoke(g, new Java.Lang.Object[0]); * } */ } else { // Richidedere permessi per Android 6.0 // ActivityCompat.RequestPermissions(activity, new String[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation}, 1001); this.myReceiver = new BondStatusBroadcastReceiver(); this.myReceiver.Bounded_ConnectDevice_Event += this.MyReceiver_Bounded_ConnectDevice_Event; this.myReceiver.Bounded_ConnectDevice_Event_ERROR += this.MyReceiver_Bounded_ConnectDevice_Event_ERROR; IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ActionFound); /* * intentFilter.AddAction(BluetoothDevice.ActionNameChanged); * intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryStarted); * intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryFinished); * intentFilter.AddAction(BluetoothAdapter.ActionStateChanged); * */ intentFilter.AddAction(BluetoothDevice.ActionBondStateChanged); context.RegisterReceiver(this.myReceiver, intentFilter); //BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter; //adapter.StartDiscovery(); device.CreateBond(); } }
public override void OnScanResult([GeneratedEnum] ScanCallbackType callbackType, ScanResult result) { base.OnScanResult(callbackType, result); if (!deviceFound) { if (MainActivity.connectedHandleAddress == null || !MainActivity.connectedHandleAddress.Equals(result.Device.Address)) { return; } Log.Info(TAG + DexService.Operation, "Device Found: " + result.Device.Name); deviceFound = true; BluetoothDevice = result.Device; ConnectedGatt = BluetoothDevice.ConnectGatt(Context, false, GattCallback); StopLeScan(); Log.Info(TAG + DexService.Operation + DexService.Operation, "onScanResult: " + result.Device.Name); } }
public Task ConnectAsync() { connectTCS = new TaskCompletionSource <bool>(); try { _gatt = _nativeDevice.ConnectGatt(Application.Context, false, this); var connectionState = _bluetoothManager.GetConnectionState(_nativeDevice, ProfileType.Gatt); if (connectionState != ProfileState.Connected) { _gatt.Connect(); } } catch (Exception e) { connectTCS.TrySetException(e); } return(connectTCS.Task); }
/// <summary> /// Process a device discovered during the scan. /// </summary> /// <param name="result">The ScanResult containing device information.</param> public void DeviceResult(ScanResult result) { if (result == null) { return; } Debug.WriteLineIf(sw.TraceVerbose, $"++> DeviceResult: {result.Device.Name}"); if (_device == null && result.Device.Name == TargetDeviceName) { // found the device we're looking for! _device = result.Device; // stop the scan _adapter.BluetoothLeScanner.FlushPendingScanResults(this); _adapter.BluetoothLeScanner.StopScan(this); // shout it to the world State = BlueState.Found; // connecting will spawn further events for setting up the device _device.ConnectGatt(Android.App.Application.Context, true, _gattCallback); } }
public void EnumServices(Context ctx, string identifer) { BluetoothDevice device = mapDevices[identifer]; if (device != null) { GattDevice gattdevice = new GattDevice(ctx, identifer); if (gatt != null) { //gatt.Disconnect(); gatt.Close(); //or gatt.Connect() to re-connect to device gatt.Dispose(); } gatt = device.ConnectGatt(ctx, false, gattdevice); //-> OnConnectionStateChange() -> DiscoverServices() -> OnServicesDiscovered() -> GattDevice.Initialize() if (gatt == null) { Log.Error(TAG, string.Format("failed to connect to GATT server '{0}'", identifer)); } } }
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public bool Connect(String address) { if (mBluetoothAdapter == null || address == null) { Log.Warn(TAG, "BluetoothAdapter not initialized or unspecified address."); return(false); } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address == mBluetoothDeviceAddress && mBluetoothGatt != null) { Log.Debug(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.Connect()) { mConnectionState = State.Connecting; return(true); } else { return(false); } } BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address); if (device == null) { Log.Warn(TAG, "Device not found. Unable to connect."); return(false); } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.ConnectGatt(this, false, new BGattCallback(this)); Log.Debug(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = State.Connecting; return(true); }
public void Connect(ConnectParameters connectParameters, CancellationToken cancellationToken) { IsOperationRequested = true; IsAutoConnectRequested = connectParameters.AutoConnect; if (connectParameters.ForceBleTransport) { ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect, cancellationToken); } else { // If gatt is null then initiate the connection process by passing application context , connection parameters //and gattcallbacks. if (null == _gatt) { _gatt = BluetoothDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback); } //else a valid gatt object is already exist.Just call connect. DO NOT craete new Gatt object by calling ConnectGatt. else { _gatt.Connect(); } } }
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public bool Connect(String address) { logger.TraceInformation("Try connect to device"); if (bluetoothAdapter == null || address == null) { logger.TraceWarning("BluetoothAdapter not initialized or unspecified address."); Toast.MakeText(thisActivity.ApplicationContext, "BluetoothAdapter not initialized or unspecified address.", ToastLength.Short).Show(); return(false); } BluetoothDevice device = bluetoothAdapter.GetRemoteDevice(address); if (device == null) { logger.TraceWarning("Device not found. Unable to connect."); Toast.MakeText(thisActivity.ApplicationContext, "Device not found. Unable to connect..", ToastLength.Short).Show(); return(false); } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. bluetoothGatt = device.ConnectGatt(this, false, gattCallback); logger.TraceInformation("Trying to create a new connection."); bluetoothDeviceAddress = address; connectionState = ProfileState.Connecting; if (SensorDataPage.Instance != null) { SensorDataPage.Instance.connectionStopwatch.Reset(); SensorDataPage.Instance.connectionStopwatch.Start(); //SensorDataPage.Instance.firstDataStopwatch.Start(); SensorDataPage.Instance.SensorView.ConnectionState = "Connecting..."; } progressDialog = ProgressDialog.Show(thisActivity, "Please wait...", "Connecting...", true); return(true); }
protected override Task ConnectAsync() { if (bluetoothAdapter == null) { return(Task.FromException(new BluetoothLEException("BluetoothAdapter not initialized."))); } if (bluetoothGatt == null) { gattCallback = new GattCallbacks( (gatt, status, newState) => // onConnectionStateChange { if (newState == ProfileState.Connected) { //intentAction = BluetoothLeService.ACTION_GATT_CONNECTED; //BluetoothLeService.this.mConnectionState = 2; //BluetoothLeService.this.broadcastUpdate(intentAction); System.Diagnostics.Debug.WriteLine("Connected to GATT server."); System.Diagnostics.Debug.WriteLine($"Attempting to start service discovery:{gatt?.DiscoverServices()}"); } else if (newState == ProfileState.Disconnected) { //intentAction = BluetoothLeService.ACTION_GATT_DISCONNECTED; //BluetoothLeService.this.mConnectionState = 0; System.Diagnostics.Debug.WriteLine("Disconnected from GATT server."); //BluetoothLeService.this.broadcastUpdate(intentAction); } }, (gatt, status) => // onServicesDiscovered { if (status == GattStatus.Success) { //BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); foreach (var service in gatt.Services) { System.Diagnostics.Debug.WriteLine($"GattService, UUID=[{service.Uuid}]"); } Services.AddRange(gatt.Services.Select(S => new BluetoothGattServiceAndroid(this, S))); RaiseServicesUpdated(); } else { System.Diagnostics.Debug.WriteLine($"onServicesDiscovered received: {status}"); } }, (gatt, characteristic, status) => // onCharacteristicRead { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), characteristic); }, (gatt, characteristic) => // onCharacteristicChanged { //BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_CHAR_CHANGED, characteristic); }, (gatt, characteristic, status) => // onCharacteristicWrite { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), characteristic); }, (gatt, descriptor, status) => // onDescriptorRead { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), descriptor); }, (gatt, descriptor, status) => // onDescriptorWrite { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), descriptor); }, (gatt, status) => //onReliableWriteCompleted { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response")); }, (gatt, rssi, status) => //onReadRemoteRssi { //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), rssi); }); bluetoothGatt = device.ConnectGatt(Android.App.Application.Context, false, gattCallback); //Log.d(TAG, "Trying to create a new connection."); //this.mBluetoothDeviceAddress = address; //this.mConnectionState = 1; //return true; return(Task.CompletedTask); } else { //Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (bluetoothGatt.Connect() != true) { return(Task.FromException(new BluetoothLEException("BluetoothGatt connect fail."))); } else { //this.mConnectionState = 1; return(Task.CompletedTask); } } }
internal void Connect() { gatt = nativePeripheral.ConnectGatt(Application.Context, false, this); }
//TODO: this really should be async. in the xplat API, make sure to asyncify // Q: how to return in same context (requires a callback) public void ConnectToDevice(BluetoothDevice device) { // returns the BluetoothGatt, which is the API for BLE stuff // TERRIBLE API design on the part of google here. device.ConnectGatt(Android.App.Application.Context, true, this._gattCallback); }
public bool ConnectLeGattDevice(Context context, BluetoothDevice device) { try { BtGattDisconnect(); _gattConnectionState = State.Connecting; _gattServicesDiscovered = false; _btGattSppInStream = new MemoryQueueBufferStream(true); _btGattSppOutStream = new BGattOutputStream(this); _bluetoothGatt = device.ConnectGatt(context, false, new BGattCallback(this)); if (_bluetoothGatt == null) { LogString("*** ConnectGatt failed"); return(false); } _btGattConnectEvent.WaitOne(2000, false); if (_gattConnectionState != State.Connected) { LogString("*** GATT connection timeout"); return(false); } _btGattDiscoveredEvent.WaitOne(2000, false); if (!_gattServicesDiscovered) { LogString("*** GATT service discovery timeout"); return(false); } IList <BluetoothGattService> services = _bluetoothGatt.Services; if (services == null) { LogString("*** No GATT services found"); return(false); } #if DEBUG foreach (BluetoothGattService gattService in services) { if (gattService.Uuid == null || gattService.Characteristics == null) { continue; } Android.Util.Log.Info(Tag, string.Format("GATT service: {0}", gattService.Uuid)); foreach (BluetoothGattCharacteristic gattCharacteristic in gattService.Characteristics) { if (gattCharacteristic.Uuid == null) { continue; } Android.Util.Log.Info(Tag, string.Format("GATT characteristic: {0}", gattCharacteristic.Uuid)); Android.Util.Log.Info(Tag, string.Format("GATT properties: {0}", gattCharacteristic.Properties)); } } #endif _gattCharacteristicSppRead = null; _gattCharacteristicSppWrite = null; _gattCharacteristicUuidSppRead = null; _gattCharacteristicUuidSppWrite = null; BluetoothGattService gattServiceSpp = _bluetoothGatt.GetService(GattServiceCarlySpp); BluetoothGattCharacteristic gattCharacteristicSpp = gattServiceSpp?.GetCharacteristic(GattCharacteristicCarlySpp); if (gattCharacteristicSpp != null) { if ((gattCharacteristicSpp.Properties & (GattProperty.Read | GattProperty.Write | GattProperty.Notify)) == (GattProperty.Read | GattProperty.Write | GattProperty.Notify)) { _gattCharacteristicSppRead = gattCharacteristicSpp; _gattCharacteristicSppWrite = gattCharacteristicSpp; _gattCharacteristicUuidSppRead = GattCharacteristicCarlySpp; _gattCharacteristicUuidSppWrite = GattCharacteristicCarlySpp; #if DEBUG Android.Util.Log.Info(Tag, "SPP characteristic Carly found"); #endif } } else { gattServiceSpp = _bluetoothGatt.GetService(GattServiceWgSoftSpp); BluetoothGattCharacteristic gattCharacteristicSppRead = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppRead); BluetoothGattCharacteristic gattCharacteristicSppWrite = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppWrite); if (gattCharacteristicSppRead != null && gattCharacteristicSppWrite != null) { if (((gattCharacteristicSppRead.Properties & (GattProperty.Read | GattProperty.Notify)) == (GattProperty.Read | GattProperty.Notify)) && ((gattCharacteristicSppWrite.Properties & (GattProperty.Write)) == (GattProperty.Write))) { _gattCharacteristicSppRead = gattCharacteristicSppRead; _gattCharacteristicSppWrite = gattCharacteristicSppWrite; _gattCharacteristicUuidSppRead = GattCharacteristicWgSoftSppRead; _gattCharacteristicUuidSppWrite = GattCharacteristicWgSoftSppWrite; } #if DEBUG Android.Util.Log.Info(Tag, "SPP characteristic WgSoft found"); #endif } } if (_gattCharacteristicSppRead == null || _gattCharacteristicSppWrite == null) { LogString("*** No GATT SPP characteristic found"); return(false); } if (!_bluetoothGatt.SetCharacteristicNotification(_gattCharacteristicSppRead, true)) { LogString("*** GATT SPP enable notification failed"); return(false); } BluetoothGattDescriptor descriptor = _gattCharacteristicSppRead.GetDescriptor(GattCharacteristicConfig); if (descriptor == null) { LogString("*** GATT SPP config descriptor not found"); return(false); } if (BluetoothGattDescriptor.EnableNotificationValue == null) { LogString("*** GATT SPP EnableNotificationValue not present"); return(false); } _gattWriteStatus = GattStatus.Failure; descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()); if (!_bluetoothGatt.WriteDescriptor(descriptor)) { LogString("*** GATT SPP write config descriptor failed"); return(false); } if (!_btGattWriteEvent.WaitOne(2000)) { LogString("*** GATT SPP write config descriptor timeout"); return(false); } if (_gattWriteStatus != GattStatus.Success) { LogString("*** GATT SPP write config descriptor status failure"); return(false); } #if false byte[] sendData = Encoding.UTF8.GetBytes("ATI\r"); _btGattSppOutStream.Write(sendData, 0, sendData.Length); while (_btGattReceivedEvent.WaitOne(2000, false)) { #if DEBUG Android.Util.Log.Info(Tag, "GATT SPP data received"); #endif } while (_btGattSppInStream.HasData()) { int data = _btGattSppInStream.ReadByteAsync(); if (data < 0) { break; } #if DEBUG Android.Util.Log.Info(Tag, string.Format("GATT SPP byte: {0:X02}", data)); #endif } #endif return(true); } catch (Exception) { _gattConnectionState = State.Disconnected; _gattServicesDiscovered = false; return(false); } }