Ejemplo n.º 1
0
        /// <summary>
        /// Configuration to recieved notifications whenever the characteristic value changes
        /// </summary>
        private async Task ConfigureServiceForNotificationsAsync()
        {
            characteristic.ValueChanged += eegNotification;

            GattCommunicationStatus status =
                await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            if (status == GattCommunicationStatus.Unreachable)
            {
                throw new Exception(status.ToString());
            }
        }
Ejemplo n.º 2
0
        async public void WriteToDevice(GattCharacteristic gattCharacteristic, byte[] data)
        {
            using (var stream = new DataWriter())
            {
                stream.WriteBytes(data);
                GattCommunicationStatus gattCommunication = await gattCharacteristic.WriteValueAsync(stream.DetachBuffer());

                if (gattCommunication > 0)
                {
                    throw new Exception("Write FAILED " + gattCommunication.ToString());
                }
            }
        }
Ejemplo n.º 3
0
        async void BeginBluetoothReadProcess()
        {
            GattCommunicationStatus communicationStatus = GattCommunicationStatus.ProtocolError;

            try {
                AddLog("Sending notify request to device", AppLog.LogCategory.Debug);
                communicationStatus = await HRReaderCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify);
            } catch (Exception e) {
                // the device refuses the notification request
                AddLog("Request refused by device. Please retry.", AppLog.LogCategory.Warning);
                AddLog($"Exception StackTrace: \n+ {e.StackTrace}\nMessage: {e.Message}", AppLog.LogCategory.Debug);
            }

            DeviceConnected = false;

            switch (communicationStatus)
            {
            case GattCommunicationStatus.Success: {
                AddLog($"Notify request activated. " +
                       $"\n[Gatt Comunication Status {communicationStatus.ToString()}", AppLog.LogCategory.Debug); // log

                DeviceConnected = true;                                                                            // change connection status

                DispatcherTimerSetup();
                ReadFromDevice();
                break;
            }

            default: {
                AddLog($"Notify request error" +
                       $"\n[Gatt Comunication Status {communicationStatus.ToString()}", AppLog.LogCategory.Debug);       // log
                break;
            }
            }
        }
Ejemplo n.º 4
0
        private async void UnsubscribeFromNotification()
        {
            try
            {
                Console.WriteLine(tag, "UnsubscribeFromNotification");
                var service = await GetServiceAsync(Constants.SUOTA_SERVICE_UUID);

                var characteristic = await GetCharacteristicAsync(Constants.SUOTA_STATUS_NTF_UUID, service);

                characteristic.ValueChanged += Characteristic_ValueChanged;
                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

                if (status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(status.ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(tag, "Exception while UnsubscribeFromNotification. " + ex.Message);
            }
        }
Ejemplo n.º 5
0
        private async void GetAllInfoSensor()
        {
            //<begincode*****GetAllServices*****>
            try
            {
                if (cadence != null)
                {
                    string BluetoothAddressHex = cadence.BluetoothAddress.ToString("x"); // convert decimal to hex
                    for (int i = 2; i < BluetoothAddressHex.Length; i += 2)              // om het leesbaar te houden plaatsen we om de 2 hex getallen een :
                    {
                        BluetoothAddressHex = BluetoothAddressHex.Insert(i, ":");
                        i = i + 1;
                    }
                    BTAddresTextBlock.Text = "Sensor: Bluetooth address = " + BluetoothAddressHex;
                    //Debug.WriteLine("sensor is " + cadence.ConnectionStatus.ToString());

                    //<begincode***** get all services and putt them in the list of observableServices*****>
                    result = await cadence.GetGattServicesAsync();

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        //Debug.WriteLine("sensor is " + cadence.ConnectionStatus.ToString());
                        List <GattDeviceService> services = result.Services.ToList();
                        observableServices = new ObservableCollection <GattServiceWrapper>();
                        observableServices.Clear();
                        foreach (GattDeviceService service in services)
                        {
                            observableServices.Add(new GattServiceWrapper(service));
                        }
                        connectionStatusTextBlock.Text       = "Sensor: Connection established!";
                        connectionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        TimerConnectToSensor.Stop();
                    }
                    else
                    {
                        Debug.WriteLine("could not read the services");
                        connectionStatusTextBlock.Text       = "Sensor: Couldn't establish connection";
                        connectionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        NoError = false;
                        // TimerConnectToSensor.Start();
                        goto HandleFault;
                    }
                    //<endcode***** get all services and putt them in the list of observableServices*****>
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetAllServices " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetAllServices*****>

            //<begincode*****GetValuesSensor*****>
            try
            {
                //<begincode***** select characteristic Measurement and putt them in the list of observableCharacteristics*****>
                var wrapper5 = observableServices.Single(i => i.Service.Uuid.ToString() == "00001816-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper5.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics = new ObservableCollection <GattCharacteristicWrapper>();
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the characteristic measurement");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic device Measurement and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic measurement*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a5b-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic measurement*****>
                //<begincode***** subscribe to measurement*****>
                characteristic2 = selectedCharacteristicWrapper.Characteristic;
                GattCharacteristicProperties properties = characteristic2.CharacteristicProperties;
                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    GattCommunicationStatus status = await characteristic2.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    if (status == GattCommunicationStatus.Success)
                    {
                        // Server has been informed of clients interest.
                        SubscribeMeasurement                   = true;
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement Subscribed.";
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        characteristic2.ValueChanged          += Characteristic_ValueChanged;
                    }
                    else
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement " + status.ToString();
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        Debug.WriteLine("could not subscribe to measurement");
                        NoError = false;
                        goto HandleFault;
                    }
                }
                else if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                {
                    GattCommunicationStatus status = await characteristic2.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

                    if (status == GattCommunicationStatus.Success)
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement.";
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        characteristic2.ValueChanged          += Characteristic_ValueChanged;
                    }
                    else
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement " + status.ToString();
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        Debug.WriteLine("could not indicate to measurement");
                        NoError = false;
                        goto HandleFault;
                    }
                }
                //<endcode***** subscribe to measurement*****>
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetValuesSensor " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetValuesSensor*****>

            //<begincode*****GetInformationSensor*****>
            try
            {
                //<begincode***** select characteristic GenericAccess level and putt them in the list of observableCharacteristics*****>
                var wrapper2 = observableServices.Single(i => i.Service.Uuid.ToString() == "00001800-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper2.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    bool Doublecharastic = false; //preventing to add the same charateristic in de list observableCharacteristics, else get a fault
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        Doublecharastic = false;
                        for (int i = 0; i < observableCharacteristics.Count; i += 1)
                        {
                            if (observableCharacteristics[i].Characteristic.Uuid == characteristic.Uuid)
                            {
                                Doublecharastic = true;
                            }
                        }
                        if (Doublecharastic == false)
                        {
                            observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));;
                        }
                    }
                    //Debug.WriteLine("Getinformationsensor add");
                }
                else
                {
                    Debug.WriteLine("could not read the characterstics");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic GenericAccess and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic device name*****>

                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a00-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic device name*****>
                //<begincode*****read device name*****>
                GattReadResult result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    string utf8result = System.Text.Encoding.UTF8.GetString(input);
                    DeviceNameTextBlock.Text = "Sensor: name = " + utf8result;
                }
                else
                {
                    Debug.WriteLine("could not read the device name");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read Firmware revision*****>

                //<begincode***** select characteristic Device information and putt them in the list of observableCharacteristics*****>
                // Het is niet zeker dat de service firmware bestaat, daarom eerst controleren of de service wel bestaat, want als er niets is te selecteren dan krijgen we een fout
                for (int ii = 0; ii < observableServices.Count; ii += 1)
                {
                    if (observableServices[ii].Service.Uuid.ToString() == "0000180a-0000-1000-8000-00805f9b34fb")
                    {
                        wrapper3 = observableServices.Single(i => i.Service.Uuid.ToString() == "0000180a-0000-1000-8000-00805f9b34fb");
                        NoError  = true;
                        break;
                    }
                    else
                    {
                        NoError = false;
                    }
                }
                if (NoError == false)
                {
                    goto HandleFault;
                }
                result2 = await wrapper3.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    NoError = false;
                }
                //<endcode***** select characteristic device information and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic Firmware*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a26-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic Firmware*****>
                //<begincode*****read firmware*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    string utf8result = System.Text.Encoding.UTF8.GetString(input);
                    FirmwareTextBlock.Text = "Sensor: Firmware = " + utf8result;
                }
                else
                {
                    Debug.WriteLine("could not read the firmware revision");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read firmware*****>

                //<begincode***** select characteristic Hardware*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a27-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic Hardware*****>
                //<begincode*****read hardware*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    StringBuilder hex = new StringBuilder(input.Length * 2);
                    foreach (byte b in input)
                    {
                        hex.AppendFormat("{0:x2}", b);
                    }
                    int Hardwarevalue = Convert.ToInt32(hex.ToString(), 16);
                    HardwareTextBlock.Text = "Sensor: Hardware Revision = " + Hardwarevalue.ToString();
                }
                else
                {
                    Debug.WriteLine("could not read the hardware revision");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read hardware*****>

                //<begincode***** select characteristic battery level and putt them in the list of observableCharacteristics*****>
                var wrapper4 = observableServices.Single(i => i.Service.Uuid.ToString() == "0000180f-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper4.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the characteristic battery level");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic battery level and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic battery level*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a19-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic battery level*****>
                //<begincode*****read battery level*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    StringBuilder hex2 = new StringBuilder(input.Length * 2);
                    foreach (byte b in input)
                    {
                        hex2.AppendFormat("{0:x2}", b);
                    }
                    int Batteryvalue = Convert.ToInt32(hex2.ToString(), 16);
                    readingsTextBlock.Text = "Sensor: Battery level = " + Batteryvalue.ToString() + "%";
                    if (Batteryvalue < 40)
                    {
                        readingsTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                    }
                    else
                    {
                        readingsTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the battery level");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read battery level*****>
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetInformationSensor " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetInformationSensor*****>
HandleFault:
            if (NoError == false)
            {
                //ErrorTextBlock.Text = "Error sensor!";
                //ErrorTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                ErrorTextBlock.Text       = "Sensor: Searching...";
                ErrorTextBlock.Foreground = new SolidColorBrush(Colors.DarkGreen);
                //characteristic2.ValueChanged -= Characteristic_ValueChanged;
                TimerConnectToSensor.Start();
                //return;
            }
            else
            {
                ErrorTextBlock.Text = "Sensor: Found.";
                //Debug.WriteLine("3 sensor is " + cadence.ConnectionStatus.ToString());
                ErrorTextBlock.Foreground = new SolidColorBrush(Colors.DarkGreen);
                localSettings.Values["StorageBluetoothAddress"] = cadence.DeviceId; //save to harddisk
                //<begincode*****get the value of the cadence counter and te time between two measurements*****>
                cadence.ConnectionStatusChanged += Cadence_ConnectionStatusChanged;
                //<endcode*****get the value of the cadence counter and te time between two measurements*****>
            }
        }
Ejemplo n.º 6
0
        /// <summary>Write a block of data to the UWP characteristic</summary>
        /// <param name="data">Buffer with data to write</param>
        /// <param name="index">Start index of data to read</param>
        /// <param name="size">Number of bytes to read</param>
        /// <returns>true on success, otherwise false with error raised</returns>
        private async Task <bool> WriteBlock(byte[] data, int index, int size)
        {
            try {
                this.log.Info("WriteBlock", "Write to Gatt");
                using (var ms = new DataWriter()) {
                    byte[] part = new byte[size];
                    Array.Copy(data, index, part, 0, part.Length);
                    ms.WriteBytes(part);
                    GattCommunicationStatus result = await
                                                     this.OSCharacteristic.WriteValueAsync(ms.DetachBuffer());

                    this.log.Info("WriteBlock", () => string.Format("WriteValueAsync result:{0}", result.ToString()));

                    return(this.ParseGattStatue(result));
                }
            }
            catch (Exception e) {
                this.log.Exception(9999, "WriteBlock", "", e);
                return(false);
            }
        }
Ejemplo n.º 7
0
        // -->> Aquire data <<--
        // Subscribes to the notifications for the specefied characteristic
        // thus enabling the data acquisition
        //_________________________________________________________________
        private async void acquireButton_Click(object sender, RoutedEventArgs e)
        {
            acquireButton.IsEnabled = false;
            if (!IsValueChangedHandlerRegistered)
            {// Not registered to notifications
                try
                {
                    GattCharacteristic      characteristic = selectedCharacteristic.Last();
                    GattCommunicationStatus result         =
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                            GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    if (result == GattCommunicationStatus.Success)
                    {
                        characteristic.ValueChanged    += Characteristic_ValueChanged;
                        OnNewDataEnqueued              += new ElementEnqueued(OnNewDataEnqueuedFxn);
                        OnNewPointsAdded               += new PointsAdded(OnNewPointsAddedFxn);
                        IsValueChangedHandlerRegistered = true;
                        acquireButton.Label             = "Stop";
                        acquireButton.Icon              = new SymbolIcon(Symbol.Stop);
                        stopwatch.Start();
                    }
                    else
                    {
                        rootPage.notifyFlyout("Error acquiring! " + result.ToString(), acquireButton);
                    }
                }
                catch (Exception ex) //(UnauthorizedAccessException ex)
                {
                    rootPage.notifyFlyout("Can't subscribe to notifications: " + ex.Message, acquireButton);
                }
            }
            else
            {// Unregister for notifications
                GattCharacteristic characteristic = selectedCharacteristic.Last();
                characteristic.ValueChanged    -= Characteristic_ValueChanged;
                OnNewDataEnqueued              -= OnNewDataEnqueuedFxn;
                OnNewPointsAdded               -= OnNewPointsAddedFxn;
                IsValueChangedHandlerRegistered = false;
                acquireButton.Label             = "Acquire";
                acquireButton.Icon              = new FontIcon {
                    Glyph = "\uE9D9"
                };
            }
            acquireButton.IsEnabled = true;

            #region //Code for direct reading

            /*GattReadResult result = null;
             * try
             * {
             *  result = await selectedCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
             * }
             * catch (Exception ex)
             * {
             *  notifyFlyout("Acquiring failed! " + ex.Message);
             * }
             *
             * if (result.Status == GattCommunicationStatus.Success)
             * {
             *  byte[] data;
             *  CryptographicBuffer.CopyToByteArray(result.Value, out data);
             *  dataTextBlock.Text = BitConverter.ToInt32(data, 0).ToString();
             * }
             * else
             * {
             *  notifyFlyout("Acquiring failed");
             * }*/
            #endregion
        }
Ejemplo n.º 8
0
        private async void EnableUpgradeMode()
        {
            string             upTag = "EnableUpgradeMode";
            GattDeviceService  service;
            GattCharacteristic characteristic;
            GattWriteResult    gattWriteResult;

            byte[] buffer;

            try
            {
                Console.WriteLine(upTag, "Step 1");
                service = await GetServiceAsync(Constants.CERTIFICATE_SERVICE);

                characteristic = await GetCharacteristicAsync(Constants.CENTRAL_TO_SIFA, service);

                buffer          = new byte[] { 0 };
                gattWriteResult = await characteristic.WriteValueWithResultAsync(buffer.AsBuffer());

                if (gattWriteResult.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(gattWriteResult.Status.ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(upTag, "Step 1 failed:" + ex.Message);
                goto ForceUpdate;
            }

            try
            {
                Console.WriteLine(upTag, "Step 2");
                service = await GetServiceAsync(Constants.CERTIFICATE_SERVICE);

                characteristic = await GetCharacteristicAsync(Constants.SIFA_COMMANDS, service);

                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                if (status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(status.ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(upTag, "Step 2 failed:" + ex.Message);
                RemoveDevice();
            }


ForceUpdate:
            try
            {
                Console.WriteLine(upTag, "ForceUpdate");
                service = await GetServiceAsync(Constants.CERTIFICATE_SERVICE);

                characteristic = await GetCharacteristicAsync(Constants.CENTRAL_TO_SIFA, service);

                buffer          = new byte[] { 0xfe, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                gattWriteResult = await characteristic.WriteValueWithResultAsync(buffer.AsBuffer());

                if (gattWriteResult.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(gattWriteResult.Status.ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(upTag, "ForceUpdate failed:" + ex.Message);
                RemoveDevice();
                return;
            }

            try
            {
                Console.WriteLine(upTag, "Confirmation");
                service = await GetServiceAsync(Constants.CONTROL_SERVICE);

                characteristic = await GetCharacteristicAsync(Constants.FW_VERSION, service);

                var ReadResult = await characteristic.ReadValueAsync();

                if (ReadResult.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(ReadResult.Status.ToString()));
                }
                string confirmationString = Encoding.UTF8.GetString(ReadResult.Value.ToArray());
                Console.WriteLine(upTag, confirmationString);
                if (!confirmationString.Contains("Datel"))
                {
                    throw (new Exception("Invalid confirmation recieved"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(upTag, "Confirmation failed:" + ex.Message);
                RemoveDevice();
            }

            try
            {
                Console.WriteLine(upTag, "Enable Upgrade mode");
                buffer  = new byte[] { 1 };
                service = await GetServiceAsync(Constants.CONTROL_SERVICE);

                characteristic = await GetCharacteristicAsync(Constants.FW_REQUEST, service);

                gattWriteResult = await characteristic.WriteValueWithResultAsync(buffer.AsBuffer());

                if (gattWriteResult.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception(gattWriteResult.Status.ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(upTag, "Enable Upgrade mode failed:" + ex.Message);
                RemoveDevice();
            }
            RemoveDevice();
        }
        private async void SetupConnection(BluetoothLEDevice device)
        {
            GattDeviceServicesResult result = await device.GetGattServicesAsync();

            if (result.Status == GattCommunicationStatus.Success)
            {
                DeviceConnected(this, null);

                var IMUServices = GetIMUServices(result);

                Debug.WriteLine("get acc char");
                GattCharacteristicsResult accCharResult = await AccelerationService.GetCharacteristicsAsync();

                Debug.WriteLine("get vel char");
                GattCharacteristicsResult velCharResult = await VelocityService.GetCharacteristicsAsync();

                Debug.WriteLine("get pos char");
                GattCharacteristicsResult posCharResult = await PositionService.GetCharacteristicsAsync();

                Debug.WriteLine("set chars");
                if (accCharResult.Status == GattCommunicationStatus.Success)
                {
                    foreach (GattCharacteristic accChar in accCharResult.Characteristics)
                    {
                        if (accChar.Uuid.Equals(AccXCharUuid))
                        {
                            AccXChar = accChar;
                        }
                        else if (accChar.Uuid.Equals(AccYCharUuid))
                        {
                            AccYChar = accChar;
                        }
                        else if (accChar.Uuid.Equals(AccZCharUuid))
                        {
                            AccZChar = accChar;
                        }
                    }
                }

                if (velCharResult.Status == GattCommunicationStatus.Success)
                {
                    foreach (GattCharacteristic velChar in velCharResult.Characteristics)
                    {
                        if (velChar.Uuid.Equals(VelXCharUuid))
                        {
                            VelXChar = velChar;
                        }
                        else if (velChar.Uuid.Equals(VelYCharUuid))
                        {
                            VelYChar = velChar;
                        }
                        else if (velChar.Uuid.Equals(VelZCharUuid))
                        {
                            VelZChar = velChar;
                        }
                    }
                }

                if (posCharResult.Status == GattCommunicationStatus.Success)
                {
                    foreach (GattCharacteristic posChar in posCharResult.Characteristics)
                    {
                        if (posChar.Uuid.Equals(PosXCharUuid))
                        {
                            PosXChar = posChar;
                        }
                        else if (posChar.Uuid.Equals(PosYCharUuid))
                        {
                            PosYChar = posChar;
                        }
                        else if (posChar.Uuid.Equals(PosZCharUuid))
                        {
                            PosZChar = posChar;
                        }
                    }
                }

                List <GattCharacteristic> chars = new List <GattCharacteristic>()
                {
                    AccXChar, AccYChar, AccZChar,
                    VelXChar, VelYChar, VelZChar,
                    PosXChar, PosYChar, PosZChar
                };

                Debug.WriteLine("set notify");
                foreach (GattCharacteristic c in chars)
                {
                    GattCommunicationStatus status = await c.WriteClientCharacteristicConfigurationDescriptorAsync(
                        GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    Debug.WriteLine(status.ToString());
                    if (status == GattCommunicationStatus.Success)
                    {
                        c.ValueChanged += CharValueChangedSubscription;
                    }
                }
            }
        }