public override void OnDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, GattStatus status)
 {
     base.OnDescriptorWrite(gatt, descriptor, status);
     System.Diagnostics.Debug.WriteLine("Descriptor written to: " + descriptor.Uuid + " get value: " + descriptor.GetValue() + " status: " + status);
     if (status == GattStatus.Success)
     {
         Bluetooth_CMD.poll_queue();
     }
     else
     {
         System.Diagnostics.Debug.WriteLine("Got gatt descriptor write failure: " + status);
         Bluetooth_CMD.retry_last_command((int)status);
     }
 }
Пример #2
0
        public void connect(string deviceAddress)
        {
            if (gattConnection != null)
            {
                disconnect();
            }
            var device = devices.FirstOrDefault((dev) => dev.Address.ToUpper().Equals(deviceAddress.ToUpper()));

            if (device != null)
            {
                gattConnection = device.ConnectGatt(MainActivity.MainContext, false, bluetoothGattCallback);
                gattConnection.Connect();
            }
        }
Пример #3
0
        public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
        {
            try
            {
                //if (LastCharacteristicChange.HasValue)
                //    Console.WriteLine(DateTime.Now.Subtract(LastCharacteristicChange.Value).TotalMilliseconds + " " + FlowManager.CurrentStep1);

                if (BluetoothSensorTagAttributes.MovementData.ToString() != characteristic.Uuid.ToString())
                {
                    return;
                }

                if (Sensor.Instance.Status != SensorStatus.Connected)
                {
                    lock (Sensor.Instance)
                        Sensor.Instance.Status = SensorStatus.Connected;
                }

                if (ConnectionVerification == null || !ConnectionVerification.IsAlive)
                {
                    StartConnectionVerification();
                }

                LastCharacteristicChange = DateTime.Now;


                var gyroscopeX = (int)characteristic.GetIntValue(GattFormat.Sint16, 0);
                var gyroscopeY = (int)characteristic.GetIntValue(GattFormat.Sint16, 2);
                var gyroscopeZ = (int)characteristic.GetIntValue(GattFormat.Sint16, 4);

                var accelerometerX = (int)characteristic.GetIntValue(GattFormat.Sint16, 6);
                var accelerometerY = (int)characteristic.GetIntValue(GattFormat.Sint16, 8);
                var accelerometerZ = (int)characteristic.GetIntValue(GattFormat.Sint16, 10);

                var magnetometerX = (int)characteristic.GetIntValue(GattFormat.Sint16, 12);
                var magnetometerY = (int)characteristic.GetIntValue(GattFormat.Sint16, 14);
                var magnetometerZ = (int)characteristic.GetIntValue(GattFormat.Sint16, 16);

                Sensor.Instance.SetAcc(accelerometerX, accelerometerY, accelerometerZ);
                Sensor.Instance.SetGyro(gyroscopeX, gyroscopeY, gyroscopeZ);

                base.OnCharacteristicChanged(gatt, characteristic);
            }
            catch (System.Exception ex)
            {
                string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name;
                BalizaFacil.App.Instance.UnhandledException(title, ex);
            }
        }
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            base.OnConnectionStateChange(gatt, status, newState);
            var devicesDataNormalized = from c in _listOfSavedDevices
                                        where c.Address == gatt.Device.Address
                                        select new { c.Name, c.Address, c.DeviceType };

            ((GlucoseDeviceActivity)_context).isDeviceConnected = true;
            switch (newState)
            {
            case ProfileState.Connected:
                DisplayMessageToUi($"S-a conectat la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                gatt.DiscoverServices();
                break;

            case ProfileState.Connecting:
                DisplayMessageToUi($"Se conecteaza la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;

            case ProfileState.Disconnected:
                ((GlucoseDeviceActivity)_context).isDeviceConnected = false;
                gatt.Close();
                gatt.Disconnect();
                DisplayMessageToUi("Citirea s-a efectuat cu succes");
                if (_records.Count > 0)
                {
                    var oderedRecords = _records.OrderByDescending(r => r.Value.DateTimeRecord).ToList();
                    Task.Run(() => {
                        ((GlucoseDeviceActivity)_context).RunOnUiThread(async() =>
                                                                        await((GlucoseDeviceActivity)_context).UpdateUi(oderedRecords.First().Value
                                                                                                                        .GlucoseData));
                    });
                }
                else
                {
                    DisplayMessageToUi("Nu s-au gasit date");
                    Task.Run(() => {
                        ((GlucoseDeviceActivity)_context).RunOnUiThread(async() =>
                                                                        await((GlucoseDeviceActivity)_context).UpdateUi());
                    });
                }

                break;

            case ProfileState.Disconnecting:
                DisplayMessageToUi($"Se deconecteaza de la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;
            }
        }
Пример #5
0
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            Console.WriteLine("OnConnectionStateChange: ");
            base.OnConnectionStateChange(gatt, status, newState);

            //TODO: need to pull the cached RSSI in here, or read it (requires the callback)
            Device device = new Device(gatt.Device, gatt, this, 0);

            switch (newState)
            {
            // disconnected
            case ProfileState.Disconnected:
                Console.WriteLine("disconnected");
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    Console.WriteLine("Changing connection priority to balanced");
                    gatt.RequestConnectionPriority(BluetoothGatt.ConnectionPriorityBalanced);
                }
                this.DeviceDisconnected(this, new DeviceConnectionEventArgs()
                {
                    Device = device
                });
                break;

            // connecting
            case ProfileState.Connecting:
                Console.WriteLine("Connecting");
                break;

            // connected
            case ProfileState.Connected:
                Console.WriteLine("Connected");
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    Console.WriteLine("Changing connection priority to high");
                    gatt.RequestConnectionPriority(BluetoothGatt.ConnectionPriorityHigh);
                }
                this.DeviceConnected(this, new DeviceConnectionEventArgs()
                {
                    Device = device
                });
                break;

            // disconnecting
            case ProfileState.Disconnecting:
                Console.WriteLine("Disconnecting");
                break;
            }
        }
Пример #6
0
        public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
        {
            String intentAction;

            logger.TAG = "ServiceBluetothGattCallback";

            if (newState == ProfileState.Connected)
            {
                intentAction = SensorService.ACTION_GATT_CONNECTED;
                sensorService.connectionState = ProfileState.Connected;
                if (SensorDataPage.Instance != null)
                {
                    SensorDataPage.Instance.connectionStopwatch.Stop();
                    SensorDataPage.Instance.SensorView.ConnectionTimeSpan = SensorDataPage.Instance.connectionStopwatch.Elapsed;
                    SensorDataPage.Instance.connectionStopwatch.Reset();
                    SensorDataPage.Instance.firstDataStopwatch.Reset();
                    SensorDataPage.Instance.firstDataStopwatch.Start();
                    SensorDataPage.Instance.SensorView.ConnectionState = "Connected";
                    SensorDataPage.Instance.SensorView.Connected       = true;
                }
                bool rssiStatus = gatt.ReadRemoteRssi();
                sensorService.BroadcastUpdate(intentAction);

                logger.TraceInformation("Connected to GATT server.");
                // Attempts to discover services after successful connection.
                logger.TraceInformation("Attempting to start service discovery:" +
                                        gatt.DiscoverServices());
            }
            else if (newState == ProfileState.Disconnected)
            {
                intentAction = SensorService.ACTION_GATT_DISCONNECTED;
                sensorService.connectionState = ProfileState.Disconnected;

                logger.TraceInformation("Disconnected from GATT server.");
                sensorService.BroadcastUpdate(intentAction);
                sensorService.Close();

                if (SensorDataPage.Instance != null)
                {
                    SensorDataPage.Instance.disconnectionStopwatch.Stop();
                    SensorDataPage.Instance.SensorView.DisconnectionTimeSpan = SensorDataPage.Instance.disconnectionStopwatch.Elapsed;
                    SensorDataPage.Instance.disconnectionStopwatch.Reset();
                    SensorDataPage.Instance.firstData = false;
                    SensorDataPage.Instance.SensorView.ConnectionState = "Disconnected";
                    SensorDataPage.Instance.SensorView.Connected       = false;
                }
                sensorService.HideProgressDialog();
            }
        }
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            Console.WriteLine("OnConnectionStateChange: ");
            base.OnConnectionStateChange(gatt, status, newState);

            switch (newState)
            {
            case ProfileState.Connected:
                gatt.DiscoverServices();
                break;

            case ProfileState.Disconnected:
                break;
            }
        }
        public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [GeneratedEnum] GattStatus status)
        {
            base.OnCharacteristicRead(gatt, characteristic, status);

            Debug.WriteLine($"Read Action for Characteristic with UUID of {characteristic.Uuid}");

            if (status == GattStatus.Success)
            {
                ExecuteNextCommand();
            }
            else
            {
                ExecutePreviousCommand();
            }
        }
Пример #9
0
 public SampleService(BluetoothGatt gatt, BluetoothGattService service, GattDevice device) : base(gatt, service, device)
 {
     index = 0;
     Log.Debug(TAG, "SampleService(0x{0:X})", BlutoothService.GetAssignedNumber(service.Uuid));
     if (service != null)
     {
         nCharacteristics = service.Characteristics.Count;
         if (nCharacteristics > 0)
         {
             BluetoothGattCharacteristic characteristic = service.Characteristics[0];
             Log.Debug(TAG, "ReadCharacteristic(0x{0:X})", BlutoothService.GetAssignedNumber(characteristic.Uuid));
             gatt.ReadCharacteristic(characteristic);
         }
     }
 }
Пример #10
0
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            if (status == GattStatus.Success)
            {
                Log.Debug(TAG, string.Format("services of '{0}' successfully retrieved", gattServerName));

                System.Threading.ThreadPool.QueueUserWorkItem(o => ReadService(gatt));
            }
            else if (status == GattStatus.Success)
            {
                Log.Error(TAG, string.Format("failed to retrieve services of '{0}'", gattServerName));
            }

            //base.OnServicesDiscovered(gatt, status);
        }
Пример #11
0
        public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status)
        {
            Log.Debug(TAG, "OnCharacteristicRead(0x{0:X})", BlutoothService.GetAssignedNumber(characteristic.Uuid));
            if (sampleService != null)
            {
                sampleService.ReadCharacteristic(characteristic);
                sampleService.ReadNextCharacteristic();
            }

            /*if (BlutoothService.GetAssignedNumber(characteristic.Service.Uuid) == 0x1800)   //org.bluetooth.service.generic_access
             * {
             *  if (genericAccess != null)
             *      genericAccess.ReadCharacteristic(characteristic);
             * }*/
        }
 private void RequestBleAll(BluetoothGatt gatt)
 {
     _handler.Post(() => {
         if (GetAllRecords(gatt))
         {
             return;
         }
         try {
             Thread.Sleep(500);
             GetAllRecords(gatt);
         } catch (Exception e) {
             Log.Error("requestBleAll", e.Message);
         }
     });
 }
 private void RequestSequence(BluetoothGatt gatt)
 {
     _handler.Post(() => {
         if (GetSequenceNumber(gatt))
         {
             return;
         }
         try {
             Thread.Sleep(500);
             GetSequenceNumber(gatt);
         } catch (Exception e) {
             Log.Error("error Sequence", e.Message);
         }
     });
 }
Пример #14
0
 public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                                            [GeneratedEnum] GattStatus status)
 {
     try
     {
         base.OnCharacteristicWrite(gatt, characteristic, status);
         Log.Info(TAG + DexService.Operation,
                  $"Characteristic {characteristic.Uuid} Wrote => {characteristic.GetValue().ToListOfByte()}");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         Log.Error(TAG, $"Error in OnCharacteristicWrite => {e.Message}");
     }
 }
Пример #15
0
        public void Disconnect()
        {
            if (gatt != null)
            {
                gatt.Disconnect();
                gatt.Close();

                if (onConnectionStateChanged != null)
                {
                    onConnectionStateChanged(this);
                }
            }

            gatt = null;
        }
Пример #16
0
        public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status)
        {
            base.OnCharacteristicRead(gatt, characteristic, status);

            ReadSemaphore.Release();

            if (characteristic.Uuid == BcoreUuid.BatteryVol)
            {
                ReadBatteryResult?.Invoke(this, new ReadBatteryVoltageEventArgs(characteristic.GetValue()));
            }
            else if (characteristic.Uuid == BcoreUuid.GetFunctions)
            {
                ReadFunctionResult?.Invoke(this, new ReadFunctionsEventArgs(characteristic.GetValue()));
            }
        }
Пример #17
0
        public override void OnMtuChanged(BluetoothGatt gatt, int mtu, GattStatus status)
        {
            base.OnMtuChanged(gatt, mtu, status);

            Trace.Message("OnMtuChanged to value: {0}", mtu);

            IDevice device;

            if (!_adapter.ConnectedDeviceRegistry.TryGetValue(gatt.Device.Address, out device))
            {
                Trace.Message("Device for MTU changed is not in connected list. This should not happen.");
            }

            MtuRequested?.Invoke(this, new MtuRequestCallbackEventArgs(device, GetExceptionFromGattStatus(status), mtu));
        }
Пример #18
0
 public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
 {
     if (newState == ProfileState.Connected)
     {
         Android.Util.Log.Info(ScannerService.TAG, "Connected to GATT server.");
         _scannerService.DiscoverServices();
         _scannerService.IsConnected = true;
     }
     else if (newState == ProfileState.Disconnected)
     {
         _scannerService.IsConnected = false;
         _scannerService.Reconnnect();
         Android.Util.Log.Info(ScannerService.TAG, "Disconnected from GATT server.");
     }
 }
Пример #19
0
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            base.OnServicesDiscovered(gatt, status);

            var device = GetCommonDevice(gatt);

            foreach (var service in gatt.Services)
            {
                var serviceModel = ConvertService(service);
                serviceModel.Device = device;
                device.Services.Add(serviceModel);
            }

            _bluetoothLeService._deviceConnectedEvent.Set();
        }
Пример #20
0
        // Implemented from IRig
        public void Connect()
        {
            if (gatt != null)
            {
                return;
            }

            gatt = device.ConnectGatt(service, false, this);

/*
 *                      handler.PostDelayed(() => {
 *                              this.UpdateMockData();
 *                      }, 100);
 */
        }
Пример #21
0
        public override void OnServicesDiscovered(BluetoothGatt peripheral, GattStatus status)
        {
            BluetoothGattService service = null;

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

                if (service == null)
                {
                    throw new Exception("Null service returned.");
                }
            }
            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());
                    }
                }
            }
        }
Пример #22
0
        public override void OnReadRemoteRssi(BluetoothGatt gatt, int rssi, GattStatus status)
        {
            base.OnReadRemoteRssi(gatt, rssi, status);

            Trace.Message("OnReadRemoteRssi: device {0} status {1} value {2}", gatt.Device.Name, status, rssi);

            IDevice device;

            if (!_adapter.ConnectedDeviceRegistry.TryGetValue(gatt.Device.Address, out device))
            {
                device = new Device(_adapter, gatt.Device, gatt, this, rssi);
                Trace.Message("Rssi updated for device not in connected list. This should not happen.");
            }

            RemoteRssiRead?.Invoke(this, new RssiReadCallbackEventArgs(device, GetExceptionFromGattStatus(status), rssi));
        }
Пример #23
0
        private void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            if (_connectTaskCompletionSource.Task.IsCanceled)
            {
                return;
            }

            if (status == GattStatus.Success)
            {
                gatt.DiscoverServices();
            }
            else
            {
                _connectTaskCompletionSource.SetResult(false);
            }
        }
 public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
 {
     if (ValidateServices())
     {
         if (!gatt.SetCharacteristicNotification(readCharacteristic, true))
         {
             Log.E(this, "Failed to set rigado read characteristic to notify");
             Disconnect();
             return;
         }
         if (onConnectionStateChanged != null)
         {
             onConnectionStateChanged(this);
         }
     }
 }
Пример #25
0
 /// <summary>
 ///
 /// </summary>
 public virtual void OnServicesDiscovered(BluetoothGatt gatt, int status)
 {
     Log.i("BleSerialPort", "OnServicesDiscovered:" + status.ToString());
     if (status == BluetoothGatt.GATT_SUCCESS)
     {
         EnableTXNotification();
         m_IsOpen = true;
         if (m_OpenCallback != null)
         {
             m_OpenCallback.OnStreamOpenSuccess(this);
         }
     }
     else
     {
     }
 }
        private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid)
        {
            try {
                BluetoothGattCharacteristic characteristic = gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid);
                gatt.SetCharacteristicNotification(characteristic, true);
                BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig);
                bool indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0;
                descriptor.SetValue(indication
                    ? BluetoothGattDescriptor.EnableIndicationValue.ToArray()
                    : BluetoothGattDescriptor.EnableNotificationValue.ToArray());

                gatt.WriteDescriptor(descriptor);
            } catch (Exception e) {
                Log.Error("BloodPressureGattCallbackerror", e.Message);
            }
        }
Пример #27
0
        public void ConfigureMovement(BluetoothGatt gatt)
        {
            try
            {
                var characteristic = gatt.GetService(BluetoothSensorTagAttributes.MovementService).GetCharacteristic(BluetoothSensorTagAttributes.MovementConfiguration);
                characteristic.SetValue(new byte[] { 0x7F, 0x02 });
                gatt.WriteCharacteristic(characteristic);

                SensorTagConfigurationStep = SensorTagConfigurationStep.Movement;
            }
            catch (System.Exception ex)
            {
                string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name;
                BalizaFacil.App.Instance.UnhandledException(title, ex);
            }
        }
Пример #28
0
        public void Connect(ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            this.IsOperationRequested = true;

            if (connectParameters.ForceBleTransport)
            {
                this.ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect, cancellationToken);
            }
            else
            {
                BluetoothGatt connectGatt = this.BluetoothDevice.ConnectGatt(Application.Context,
                                                                             connectParameters.AutoConnect, this._gattCallback);
                this._connectCancellationTokenRegistration.Dispose();
                this._connectCancellationTokenRegistration = cancellationToken.Register(() => connectGatt.Disconnect());
            }
        }
Пример #29
0
            public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, [GeneratedEnum] GattStatus status)
            {
                base.OnCharacteristicRead(gatt, characteristic, status);

                if (status == GattStatus.Success)
                {
                    gatt.ReadCharacteristic(characteristic);
                    byte[] valor = characteristic.GetValue();
                    textCharacteristic = gatt.ReadCharacteristic(characteristic).ToString();
                    Log.Debug(tag, "CHARACTERISTIC: " + valor);
                }
                else
                {
                    Log.Debug(tag, "characteristic GET VALUE IS NULL");
                }
            }
Пример #30
0
 private bool ResetGattCache(BluetoothGatt gatt)
 {
     Java.Lang.Reflect.Method method = gatt.Class.GetMethod("refresh", null);
     if (method != null)
     {
         try
         {
             method.Invoke(gatt, null);
             return(true);
         }
         catch (Exception ex)
         {
         }
     }
     return(false);
 }