示例#1
0
        /// <summary>
        /// Get the UUID's for the device details and sets the list
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        private void getDeviceDetails(BluetoothGatt gatt)
        {
            try
            {
                UUID deviceInfoUUID = UUID.FromString(BluetoothConstants.DEVICE_INFO_SERVICE);
                BluetoothGattService deviceInfoSer = gatt.GetService(deviceInfoUUID);

                deviceChar = new List <BluetoothGattCharacteristic> {
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SERIALNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_MODELNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SOFTWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_FIRMWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_HARDWARE_REV))
                };

                foreach (BluetoothGattCharacteristic c in deviceChar)
                {
                    try
                    {
                        gatt.SetCharacteristicNotification(c, false);
                        requestCharacteristic(gatt);
                    }
                    catch (System.Exception e)
                    {
                        string t = "";
                        // if the char dont exit for thiss
                    }
                }
            } catch (System.Exception e)
            {
                // stop ourselves
                sendStateUpdate(gatt.Device.Address, false, "Device could not be read from: " + e.Message);
            }
        }
示例#2
0
 /// <summary>
 ///
 /// </summary>
 public virtual void OnServicesDiscovered(BluetoothGatt gatt, int status)
 {
     Log.i("BluetoothScannerGUI", "OnServicesDiscovered:" + status.ToString());
     if (status == BluetoothGatt.GATT_SUCCESS)
     {
         BluetoothGattService        srv = gatt.GetService(UUID.FromString("0000faea-0000-1000-8000-00805f9b34fb"));
         BluetoothGattCharacteristic chr = srv.GetCharacteristic(UUID.FromString("0000faeb-0000-1000-8000-00805f9b34fb"));
         gatt.SetCharacteristicNotification(chr, true);
     }
 }
示例#3
0
        protected static Java.Util.UUID CHAR_APPEARANCE  = Java.Util.UUID.FromString("00002A01-0000-1000-8000-00805f9b34fb");   //org.bluetooth.characteristic.gap.appearance

        public GenericAccessService(BluetoothGatt gatt, BluetoothGattService service, GattDevice device) : base(gatt, service, device)
        {
            if (service != null)
            {
                BluetoothGattCharacteristic characteristic = service.GetCharacteristic(CHAR_DEVICE_NAME);
                if (characteristic != null)
                {
                    gatt.ReadCharacteristic(characteristic);
                }
            }
        }
示例#4
0
            public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
            {
                System.Threading.Tasks.Task.Run(() =>
                {
                    base.OnServicesDiscovered(gatt, status);
                    if (gatt != null)
                    {
                        try
                        {
                            var serviceUuid = ParcelUuid.FromString(_tracingInformation.ServiceId);
                            BluetoothGattService service = gatt.GetService(serviceUuid.Uuid);

                            if (service != null)
                            {
                                _deviceManager.HandleDeviceCommunicationDiscoveredService(_descriptor, (d) =>
                                {
                                    var characteristicUuid = ParcelUuid.FromString(_tracingInformation.CharacteristicId);
                                    BluetoothGattCharacteristic characteristic = service.GetCharacteristic(characteristicUuid.Uuid);

                                    if (characteristic != null)
                                    {
                                        _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristic(_descriptor, (d) =>
                                        {
                                            gatt.ReadCharacteristic(characteristic);
                                        });
                                    }
                                    else
                                    {
                                        _deviceManager.HandleIncorrectDevice(_descriptor, (d) =>
                                        {
                                            gatt.Disconnect();
                                        });
                                    }
                                });
                            }
                            else
                            {
                                _deviceManager.HandleIncorrectDevice(_descriptor, (d) =>
                                {
                                    gatt.Disconnect();
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            _deviceManager.HandleDeviceCommunicationDiscoveryServiceError(_descriptor, ex.Message, (d) =>
                            {
                                gatt.Disconnect();
                            });
                        }
                    }
                }).FireAndForget();
            }
示例#5
0
        /// <summary>
        /// Process a callback from the Gatt for device services discovered while we're connecting
        /// </summary>
        private void GattCallback_ServicesDiscovered(object sender, EventArgs e)
        {
            Debug.WriteLineIf(sw.TraceInfo, "++> GattCallback_ServicesDiscovered");
            _service = _gatt.GetService(uuidService);
            _TX      = _service.GetCharacteristic(uuidTX);
            _RX      = _service.GetCharacteristic(uuidRX);
            BluetoothGattDescriptor config = _RX.GetDescriptor(uuidCharacteristicConfig);

            if (config == null)
            {
                Debug.WriteLineIf(sw.TraceError, "--> _RX.GetDescriptor failed");
                ErrorMessage = "RX.GetDescriptor failed";
                Disconnect();
                return;
            }
            bool b = _gatt.SetCharacteristicNotification(_RX, true);

            b = config.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
            b = _gatt.WriteDescriptor(config);
            // now that services are connected, we're ready to go
            State = BlueState.Connected;
        }
示例#6
0
        public override void OnServicesDiscovered(BluetoothGatt peripheral, GattStatus status)
        {
            BluetoothGattService service = null;

            try
            {
                service = peripheral.GetService(_service.Uuid);

                if (service == null)
                {
                    SensusServiceHelper.Get().Logger.Log("Null service returned. The device is not running Senus.", LoggingLevel.Normal, GetType());

                    _readCompletionSource.SetResult(null);
                }
            }
            catch (Exception ex)
            {
                SensusServiceHelper.Get().Logger.Log("Exception while getting peripheral service:  " + ex, LoggingLevel.Normal, GetType());
            }

            if (service != null)
            {
                BluetoothGattCharacteristic characteristic = null;
                try
                {
                    characteristic = service.GetCharacteristic(_characteristic.Uuid);

                    if (characteristic == null)
                    {
                        throw new Exception("Null characteristic returned.");
                    }
                }
                catch (Exception ex)
                {
                    SensusServiceHelper.Get().Logger.Log("Exception while getting peripheral characteristic:  " + ex, LoggingLevel.Normal, GetType());
                }

                if (characteristic != null)
                {
                    try
                    {
                        peripheral.ReadCharacteristic(characteristic);
                    }
                    catch (Exception ex)
                    {
                        SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral characteristic:  " + ex, LoggingLevel.Normal, GetType());
                    }
                }
            }
        }
示例#7
0
        /// <summary>
        ///
        /// </summary>
        public virtual void EnableTXNotification()
        {
            if (m_Gatt == null)
            {
                Log.e("BleSerialPort", "No BluetoothGatt to EnableTXNotification!!!");
                return;
            }

            // Get the service.
            BluetoothGattService RxService = m_Gatt
                                             .GetService(m_UuidServ);

            if (RxService == null)
            {
                Log.e("BleSerialPort", "RxService==null");
                return;
            }

            // Get the characteristic.
            BluetoothGattCharacteristic txChar = RxService
                                                 .GetCharacteristic(m_UuidTx);

            if (txChar == null)
            {
                Log.e("BleSerialPort", "txChar==null");
                return;
            }

            // Set the characteristic notification.
            bool result = m_Gatt.SetCharacteristicNotification(txChar, true);

            if (!result)
            {
                Log.e("BleSerialPort", "m_Gatt.SetCharacteristicNotification(txChar,true) failed!!!");
            }

            // (Set the characteristic notification ???).
            BluetoothGattDescriptor descriptor = txChar
                                                 .GetDescriptor(m_UuidCCCD);

            descriptor.SetValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            m_Gatt.WriteDescriptor(descriptor);

            Log.i("BleSerialPort", "EnableTXNotification successfully.");
        }
            public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
            {
                if (status == GattStatus.Success)
                {
                    Debug.WriteLine(TAG, "mBluetoothGatt = " + Service.Gatt);
                    BluetoothGattCharacteristic TxChar;
                    BluetoothGattService        RxService = Service.Gatt.GetService(RX_SERVICE_UUID2);
                    if (RxService == null)
                    {
                        Service.ShowMessage("mBluetoothGatt null" + Service.Gatt);
                        Service.ShowMessage("Rx service not found!");
                        Service.BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
                        return;
                    }
                    TxChar = RxService.GetCharacteristic(TX_CHAR_UUID2);
                    if (TxChar == null)
                    {
                        Service.ShowMessage("Rx charateristic not found!");
                        Service.BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
                        return;
                    }
                    Debug.WriteLine(TAG, "RxChar = " + TX_CHAR_UUID2.ToString());
                    Service.Gatt.SetCharacteristicNotification(TxChar, true);

                    BluetoothGattDescriptor descriptor = TxChar.GetDescriptor(CCCD);
                    var ilistValue = BluetoothGattDescriptor.EnableNotificationValue;
                    var arrayValue = new byte[ilistValue.Count];
                    for (int index = 0; index < arrayValue.Length; index++)
                    {
                        arrayValue[index] = ilistValue[index];
                    }
                    descriptor.SetValue(arrayValue);
                    Service.Gatt.WriteDescriptor(descriptor);

                    Service.BroadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                }
                else
                {
                    Debug.WriteLine(TAG, "onServicesDiscovered received: " + status);
                }
            }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        public virtual int WriteRXCharacteristic(byte[] value)
        {
            BluetoothGattService rxService = m_Gatt
                                             .GetService(m_UuidServ);

            if (rxService == null)
            {
                return(-1);
            }
            BluetoothGattCharacteristic rxChar = rxService
                                                 .GetCharacteristic(m_UuidRx);

            if (rxChar == null)
            {
                return(-2);
            }
            rxChar.SetValue(value);
            bool status = m_Gatt.WriteCharacteristic(rxChar);

            return((status)?0:-3);
        }
示例#10
0
            /// <summary>
            /// Method that loads service and characteristics and checks they are suitable
            /// </summary>
            /// <param name="p0">Gatt server</param>
            /// <returns>True if successful</returns>
            protected override bool IsRequiredServiceSupported(BluetoothGatt p0)
            {
                if (_manager._services != null)
                {
                    foreach (ServiceAndCharacteristicsParcel parcel in _manager._services)
                    {
                        // Get the service
                        BluetoothGattService service = p0.GetService(UUID.FromString(parcel.Service.ToString()));
                        if (service != null)
                        {
                            // Check each characteristic
                            foreach (KeyValuePair <Guid, CharacteristicsParcel> characteristicsParcel in parcel.Characteristics)
                            {
                                if (!_manager._characteristics.ContainsKey(characteristicsParcel.Key))
                                {
                                    // Get the characteristic
                                    BluetoothGattCharacteristic characteristic = service.GetCharacteristic(UUID.FromString(characteristicsParcel.Key.ToString()));

                                    if (characteristic != null)
                                    {
                                        // Add the service to the local dictionary
                                        _manager._characteristics.Add(characteristicsParcel.Key, characteristic);

                                        // Find the required properties of this characteristic
                                        CharacteristicProperties properties = characteristicsParcel.Value.Properties;

                                        // Now check that the characteristic supports the required properties
                                        GattProperty rxProperties = characteristic.Properties;

                                        // Read request
                                        if (properties.HasFlag(CharacteristicProperties.Read))
                                        {
                                            if (!rxProperties.HasFlag(GattProperty.Read))
                                            {
                                                return(false);
                                            }
                                        }

                                        // Write request
                                        if (properties.HasFlag(CharacteristicProperties.Write))
                                        {
                                            if (!rxProperties.HasFlag(GattProperty.Write))
                                            {
                                                return(false);
                                            }
                                        }

                                        // Notifications
                                        if (properties.HasFlag(CharacteristicProperties.Notify))
                                        {
                                            if (!rxProperties.HasFlag(GattProperty.Notify))
                                            {
                                                return(false);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        return(false);
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }
示例#11
0
        /// <summary>
        /// Connets the service and enable notifications for the chars we need
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        public void connectToService(BluetoothGatt gatt)
        {
            try
            {
                if (handle == null)
                {
                    handle = new SensorHandler(deviceDetails, AppConfig.UserID);
                }

                BluetoothDevice d = gatt.Device;

                // Getting Char/services UUIDS
                UUID serviceUUID = null;
                UUID charUUID    = null;
                UUID ccdUUID     = UUID.FromString(BluetoothConstants.CCD_UUID);

                // Can add other ones later or maybe swap out config files?
                if (gatt.Device.Name.StartsWith("MVSS", StringComparison.CurrentCulture))
                {
                    serviceUUID = UUID.FromString(BluetoothConstants.MVSS_SERVICE);
                    charUUID    = UUID.FromString(BluetoothConstants.MVSS_CHAR);
                }

                if (gatt.Device.Name.StartsWith("Zephyr", StringComparison.CurrentCulture))
                {
                    serviceUUID = UUID.FromString(BluetoothConstants.HEART_RATE_SERVICE);
                    charUUID    = UUID.FromString(BluetoothConstants.HEART_RATE_CHAR);
                }


                /*	if (serviceUUID == null || charUUID == null || ccdUUID == null)
                 *  {
                 *      // dont continue
                 *      // throw error?
                 *  }*/

                notifyChars.Add(serviceUUID.ToString());
                notifyChars.Add(charUUID.ToString());

                // Getting Service
                BluetoothGattService ser = gatt.GetService(serviceUUID);

                // Getting custom characteristic and enabling the notifications for it
                BluetoothGattCharacteristic cha = ser.GetCharacteristic(charUUID);

                // Getting Descriptor from characteristic
                BluetoothGattDescriptor ds = cha.GetDescriptor(ccdUUID);

                // Setting desc to notify
                ds.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                //ds.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                gatt.WriteDescriptor(ds);

                // Enabling the notifications
                gatt.SetCharacteristicNotification(cha, true);
            }
            catch (NullReferenceException e)
            {
                // Service could not be reached
                // How to get this back to the user?
                string t = e.ToString();
            }
        }
示例#12
0
        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);
            }
        }
示例#13
0
 public sealed override void BuildService(BluetoothGattService service)
 {
     foreach (var c in service.Characteristics)
     {
         _concreteCharacteristics.FirstOrDefault(x => x.Uuid.Equals(c.Uuid))?.BuildCharacteristic(service.GetCharacteristic(c.Uuid));
     }
 }