private static async Task <BluetoothDevice> PlatformFromId(string id)
        {
            BluetoothLEDevice device = null;

            if (ulong.TryParse(id, System.Globalization.NumberStyles.HexNumber, null, out var parsedId))
            {
                if (Bluetooth.KnownDevices.ContainsKey(parsedId))
                {
                    BluetoothDevice knownDevice = (BluetoothDevice)Bluetooth.KnownDevices[parsedId].Target;
                    if (knownDevice != null)
                    {
                        return(knownDevice);
                    }
                }
                device = await BluetoothLEDevice.FromBluetoothAddressAsync(parsedId);
            }
            else
            {
                device = await BluetoothLEDevice.FromIdAsync(id);
            }

            if (device != null)
            {
                var success = await device.RequestAccessAsync();

                System.Diagnostics.Debug.WriteLine($"RequestAccessAsync {success}");
            }

            return(device);
        }
Exemple #2
0
        public async void ListCurrentDeviceServicesToLog()
        {
            //CheckBluetoothStatus(true);
            BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(ChosenDevice.Id);

            if (device == null)
            {
                return;
            }
            DeviceAccessStatus accessStatus = await device.RequestAccessAsync();

            var deviceServicesResult = await device.GetGattServicesAsync();

            // build the string to add in the log
            string services = "[Services list of " + device.Name + "]";
            int    i        = 0;

            foreach (GattDeviceService service in deviceServicesResult.Services)
            {
                services += "\n -- Handle: \t" + service.AttributeHandle.ToString();
                services += "\n --> UUID: \t" + service.Uuid.ToString();
                services += "\n --> Access Info: \t" + service.DeviceAccessInformation.CurrentStatus.ToString();
                i++;
                if (i < deviceServicesResult.Services.Count)
                {
                    services += "\n----------------------------------------------------------------";
                }
            }
            services += "\n\nFor info on Bluetooth Standard codes and identifiers, please visit https://www.bluetooth.com/specifications/assigned-numbers" + "\n";
            // add log
            AddLog(services, AppLog.LogCategory.Debug);
        }
        /// <summary>
        /// Try to connect with the pen.
        /// </summary>
        /// <param name="penInformation">PenInformation instance that holds the pen's information</param>
        /// <returns>True or false if the connection is successful</returns>
        public async Task <bool> Connect(PenInformation penInformation)
        {
            try
            {
                if (penInformation.Protocol != Protocols.V2)
                {
                    throw new NotSupportedException("Not supported protocol version");
                }

                await semaphreSlime.WaitAsync();

                Debug.WriteLine("");

                bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(penInformation.Id);

                var status = await bluetoothLEDevice.RequestAccessAsync();

                Debug.WriteLine("RequestAccessAsync result is " + status.ToString());

                if (status != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
                {
                    throw new Exception();
                }

                GattDeviceServicesResult result = await bluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                if (result.Status != GattCommunicationStatus.Success || await Bind(result.Services) == false)
                {
                    Debug.WriteLine("GetGattServicesAsync status is " + result.Status.ToString());
                    throw new Exception();
                }

                bluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged;

                return(true);
            }
            catch
            {
                DisposeBluetoothResource();
                return(false);
            }
            finally
            {
                semaphreSlime.Release();
            }
        }
        private bool BluetoothSetup()
        {
            BluetoothLEDevice device = this.Waitfor(
                "connection to Bluetooth device",
                BluetoothLEDevice.FromBluetoothAddressAsync(System.Convert.ToUInt64("001580912553", 16)));

            if (device == null)
            {
                this.logEol("Device wasn't found");
                return(false);
            }

            GattDeviceServicesResult deviceServices = this.Waitfor(
                "device services", device.GetGattServicesAsync());

            DeviceAccessStatus deviceAccessStatus = this.Waitfor(
                "device access", device.RequestAccessAsync());

            this.logEol($"Device access status: {deviceAccessStatus}");

            System.Guid       gyroServiceGuid = System.Guid.Parse("0000ffe0-0000-1000-8000-00805f9b34fb");
            GattDeviceService gyroService     = deviceServices.Services.Single(x => x.Uuid.Equals(gyroServiceGuid));

            var gyroServiceAccessStatus = this.Waitfor(
                "gro data service access", gyroService.RequestAccessAsync());

            this.logEol($"Gyro service access status: {gyroServiceAccessStatus}");

            GattCharacteristicsResult characteristics = this.Waitfor(
                "gyro data service", gyroService.GetCharacteristicsAsync());

            this.txRxChannel = characteristics
                               .Characteristics
                               .SingleOrDefault(x => x.UserDescription.Replace(" ", "") == "TX&RX");

            if (this.txRxChannel == default(GattCharacteristic))
            {
                this.logEol("Couldn't find TXRX channel...disconnected?");
                return(false);
            }

            this.txRxChannel.ValueChanged += this.TxRx_ValueChanged;
            return(true);
        }
Exemple #5
0
        public async Task DiscoverServicesAsync()
        {
            m_Device = await BluetoothLEDevice.FromBluetoothAddressAsync(BluetoothAddress);

            var info = m_Device.DeviceInformation;

            PrintInfo(info);
            m_Device.ConnectionStatusChanged += OnConnectionChanged;
            m_Device.GattServicesChanged     += OnGattServicesChanged;
            var access = await m_Device.RequestAccessAsync();

            if (access != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
            {
                throw new Exception("could not access BLE");
            }
            await Task.Delay(2000);

            await FillServices();
        }
Exemple #6
0
        public static async Task Connect(string deviceId)
        {
            deviceReference = await BluetoothLEDevice.FromIdAsync(deviceId);

            await deviceReference.RequestAccessAsync();

            GattDeviceServicesResult result = await deviceReference.GetGattServicesAsync();

            //Allways check result!
            if (result.Status == GattCommunicationStatus.Success)
            {
                //Put following two lines in try/catch to or check for null!!
                var characs = await result.Services.Single(s => s.Uuid == Uuids.PoolLabSvc).GetCharacteristicsAsync();

                cmdMisoCharacteristic = characs.Characteristics.Single(c => c.Uuid == Uuids.CmdMiso);
                cmdMosiCharacteristic = characs.Characteristics.Single(c => c.Uuid == Uuids.CmdMosi);
                misoSigCharacteristic = characs.Characteristics.Single(c => c.Uuid == Uuids.MisoSig);

#if DEBUG
                if (BitConverter.IsLittleEndian)
                {
                    Debug.WriteLine("LittleEndian");
                }
                else
                {
                    Debug.WriteLine("BigEndian");
                }

                if (cmdMisoCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                {
                    Debug.WriteLine("CommandMISO characteristic supports reading from it.");
                }
                if (cmdMisoCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                {
                    Debug.WriteLine("CommandMISO characteristic supports writing.");
                }
                if (cmdMisoCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.ReliableWrites))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports reliable writing.");
                }
                if (cmdMisoCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports writing without response.");
                }
                if (cmdMisoCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    Debug.WriteLine("CommandMISO characteristic supports subscribing to notifications.");
                }

                if (cmdMosiCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                {
                    Debug.WriteLine("CommandMOSI characteristic supports reading from it.");
                }
                if (cmdMosiCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                {
                    Debug.WriteLine("CommandMOSI characteristic supports writing.");
                }
                if (cmdMosiCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.ReliableWrites))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports reliable writing.");
                }
                if (cmdMosiCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports writing without response.");
                }
                if (cmdMosiCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    Debug.WriteLine("CommandMOSI characteristic supports subscribing to notifications.");
                }

                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports reading from it.");
                }
                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports writing.");
                }
                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.ReliableWrites))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports reliable writing.");
                }
                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports writing without response.");
                }
                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports subscribing to notifications.");
                }
                if (misoSigCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                {
                    Debug.WriteLine("MISO_Signal characteristic supports indicate.");
                }
#endif

                IsConnected = true;
            }
            else
            {
                Debug.WriteLine("No services found");
            }
        }
Exemple #7
0
        public async Task <bool> TryToConnect(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                this.logger.Error($"'{nameof(deviceId)}' argument is null or empty");
                return(false);
            }

            bool success = false;

            try
            {
                GattDeviceService  service = null;
                GattCharacteristic responseCharacteristic = null;
                BluetoothLEDevice  bluetoothLeDevice      = await BluetoothLEDevice.FromIdAsync(deviceId)
                                                            .AsTask()
                                                            .ConfigureAwait(false);

                if (bluetoothLeDevice == null)
                {
                    this.logger.Error($"failed to create BLE device with id = '{deviceId}'");
                    return(false);
                }

                this.bluetoothLeDevice = bluetoothLeDevice;
                bluetoothLeDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                DeviceAccessStatus deviceStatus = await bluetoothLeDevice.RequestAccessAsync()
                                                  .AsTask()
                                                  .ConfigureAwait(false);

                if (deviceStatus != DeviceAccessStatus.Allowed)
                {
                    this.logger.Error($"failed to get access to BLE device with id = '{deviceId}'");
                    return(false);
                }

                // the following method connects to BLE device (and will call OnConnectionStatusChanged)

                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached)
                                                  .AsTask()
                                                  .ConfigureAwait(false);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    service = result.Services.Where(s => s.Uuid == SERVICE_GUID)
                              .FirstOrDefault();

                    if (service == null)
                    {
                        this.logger.Error($"BLE device with id = '{deviceId}' doesn't have '{SERVICE_GUID}' service");
                        return(false);
                    }

                    GattOpenStatus status = await service.OpenAsync(GattSharingMode.Exclusive)
                                            .AsTask()
                                            .ConfigureAwait(false);

                    if (status != GattOpenStatus.Success)
                    {
                        this.logger.Error($"failed to open '{SERVICE_GUID}' service on BLE device with id = '{deviceId}', result = '{status}'");
                        return(false);
                    }

                    GattCharacteristicsResult characteristicsResult = characteristicsResult = await service.GetCharacteristicsForUuidAsync(RESPONSE_CHARACTERISTICS_GUID)
                                                                                              .AsTask()
                                                                                              .ConfigureAwait(false);

                    if (characteristicsResult.Status != GattCommunicationStatus.Success)
                    {
                        this.logger.Error($"failed to get '{RESPONSE_CHARACTERISTICS_GUID}' characteristic from '{SERVICE_GUID}' " +
                                          $"service on BLE device with id = '{deviceId}', result = '{characteristicsResult.Status}', protocol error = {characteristicsResult.ProtocolError}");
                        return(false);
                    }

                    responseCharacteristic = characteristicsResult.Characteristics.FirstOrDefault();

                    if (responseCharacteristic == null)
                    {
                        this.logger.Error($"'{RESPONSE_CHARACTERISTICS_GUID}' characteristic doesn't seem to have any characteristics in '{SERVICE_GUID}' service on BLE device with id = '{deviceId}'");
                        return(false);
                    }
                }
                else
                {
                    this.logger.Error($"failed to retreive services provided by BLE device with id = '{deviceId}', result = '{result.Status}', protocol error = '{result.ProtocolError}'");
                    return(false);
                }

                this.service = service;
                this.responseCharacteristic = responseCharacteristic;
                this.responseCharacteristic.ValueChanged += OnCharacteristicValueChanged;

                success = true;

                return(true);
            }
            catch (Exception e)
            {
                this.logger.Error(e, "unexpected exception while connecting to BLE device");
                return(false);
            }
            finally
            {
                if (!success)
                {
                    Disconnect();
                }
            }
        }
Exemple #8
0
        private async Task DisplayBluetooth(NameDevice knownDevice, DeviceInformationWrapper di, BluetoothLEDevice ble)
        {
            var jsonFormat   = Newtonsoft.Json.Formatting.Indented;
            var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
                NullValueHandling    = Newtonsoft.Json.NullValueHandling.Ignore,
                ContractResolver     = IgnoreEmptyEnumerableResolver.Instance,
            };

            var wireAllDevices = new NameAllBleDevices();

            WireDevice          = new NameDevice();
            WireDevice.Name     = di.di.Name;
            WireDevice.Details += $"Id:{di.di.Id}\nCanPair:{di.di.Pairing.CanPair} IsPaired:{di.di.Pairing.IsPaired}";
            wireAllDevices.AllDevices.Add(WireDevice);

            WireDevice.ClassModifiers = knownDevice.ClassModifiers;
            WireDevice.ClassName      = knownDevice.ClassName;
            WireDevice.Description    = knownDevice.Description;


            uiRawData.Text = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat);
            string raw = null;

            if (ble == null)
            {
                // Happens if another program is trying to use the device!
                raw = $"BLE: ERROR: Another app is using this device.\n";
            }
            else
            {
                // TODO: remove this code which is only here while I investigate the WESCALE scale
#if NEVER_EVER_DEFINED
                {
                    // WESCALE: no gatt services
                    var services     = ble.GattServices;
                    var count        = services.Count;
                    var devacc       = ble.DeviceAccessInformation;
                    var devaccstatus = devacc.CurrentStatus;

                    foreach (var service in services)
                    {
                        var chars = service.GetAllCharacteristics();
                    }
                    try
                    {
                        var guid    = Guid.Parse("0000fff0-0000-1000-8000-00805f9b34fb");
                        var request = await ble.RequestAccessAsync();

                        var allservice = await ble.GetGattServicesForUuidAsync(guid);

                        var servicefff0 = ble.GetGattService(guid);
                        var charsfff0   = servicefff0.GetAllCharacteristics();
                        var countfff0   = charsfff0.Count;
                        foreach (var ch in charsfff0)
                        {
                            ;
                        }
                    }
                    catch (Exception ex)
                    {
                        ;
                    }
                }
#endif

                var result = await ble.GetGattServicesAsync();

                if (result.Status != GattCommunicationStatus.Success)
                {
                    raw += GetStatusString(result.Status, result.ProtocolError);
                }
                else
                {
                    var header = new BleDeviceHeaderControl();
                    await header.InitAsync(ble);

                    int serviceCount = 0;

                    foreach (var service in result.Services)
                    {
                        await header.AddServiceAsync(ble, service);

                        var shouldDisplay = ServiceShouldBeEdited(service);

                        var defaultService = knownDevice.GetService(service.Uuid.ToString("D"));
                        var wireService    = new NameService(service, defaultService, serviceCount++);
                        WireDevice.Services.Add(wireService);

                        try
                        {
                            var cresult = await service.GetCharacteristicsAsync();

                            if (cresult.Status != GattCommunicationStatus.Success)
                            {
                                raw += GetStatusString(cresult.Status, cresult.ProtocolError);
                            }
                            else
                            {
                                var characteristicCount = 0;

                                foreach (var characteristic in cresult.Characteristics)
                                {
                                    //The descriptors don't seem to be actually interesting. it's how we read and write.
                                    var descriptorStatus = await characteristic.GetDescriptorsAsync();

                                    if (descriptorStatus.Status == GattCommunicationStatus.Success)
                                    {
                                        foreach (var descriptor in descriptorStatus.Descriptors)
                                        {
                                            ;
                                        }
                                    }

                                    var defaultCharacteristic = defaultService?.GetChacteristic(characteristic.Uuid.ToString("D"));
                                    var wireCharacteristic    = new NameCharacteristic(characteristic, defaultCharacteristic, characteristicCount++);
                                    wireService.Characteristics.Add(wireCharacteristic);

                                    if (wireCharacteristic.Suppress)
                                    {
                                        continue; // don't show a UI for a supressed characteristic.
                                    }
                                    //
                                    // Here are each of the editor children items
                                    //
                                    var edit = new BleCharacteristicControl(knownDevice, service, characteristic);
                                    uiEditor.Children.Add(edit);

                                    var dc = DeviceCharacteristic.Create(characteristic);

                                    //NOTE: does any device have a presentation format?
                                    foreach (var format in characteristic.PresentationFormats)
                                    {
                                        raw += $"    Fmt: Description:{format.Description} Namespace:{format.Namespace} Type:{format.FormatType} Unit: {format.Unit} Exp:{format.Exponent}\n";
                                    }


                                    try
                                    {
                                        if (wireCharacteristic.IsRead)
                                        {
                                            var vresult = await characteristic.ReadValueAsync();

                                            if (vresult.Status != GattCommunicationStatus.Success)
                                            {
                                                raw += GetStatusString(vresult.Status, vresult.ProtocolError);
                                            }
                                            else
                                            {
                                                var dt         = BluetoothLEStandardServices.GetDisplayInfo(service, characteristic);
                                                var hexResults = dt.AsString(vresult.Value);
                                                wireCharacteristic.ExampleData.Add(hexResults);

                                                // And add as a converted value
                                                var NC     = BleNames.Get(knownDevice, service, characteristic);
                                                var decode = NC?.Type;
                                                if (decode != null && !decode.StartsWith("BYTES|HEX"))
                                                {
                                                    var decoded = ValueParser.Parse(vresult.Value, decode);
                                                    wireCharacteristic.ExampleData.Add(decoded.UserString);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        raw += $"    Exception reading value: {e.HResult} {e.Message}\n";
                                    }

                                    // Update the UI with the latest discovery
                                    // Later: or not. The raw data isn't super useful.
                                    //uiRawData.Text = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            raw += $"    Exception reading characteristic: {e.HResult} {e.Message}\n";
                        }
                    }
                }
            }
            JsonAsList   = Newtonsoft.Json.JsonConvert.SerializeObject(wireAllDevices, jsonFormat, jsonSettings);
            JsonAsSingle = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat, jsonSettings);

            uiProgress.IsActive = false;
            uiRawData.Text     += raw;
            return;
        }
            private async void Bleaw_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
            {
                if (sender == null)
                {
                    return;
                }
                bool OK = false;

                if (System.Threading.Interlocked.Increment(ref barrier) == 1)
                {
                    BLEAdvWatcher.Stop();
                    Guid  guidNotification;
                    ulong blAdress = args.BluetoothAddress;;

                    BluetoothLEDevice blDevice = await
                                                 Windows.Devices.Bluetooth.BluetoothLEDevice.FromBluetoothAddressAsync(blAdress);

                    if (!(blDevice == null))
                    {
                        var name = blDevice.Name;
                        System.Diagnostics.Debug.WriteLine("Device Name=:", name);
                        if ((blDevice.DeviceInformation.Kind ==
                             Windows.Devices.Enumeration.DeviceInformationKind.AssociationEndpoint) &&
                            (NameFilter == ""?true:name.ToLower().Contains(NameFilter.ToLower())))
                        {
                            System.Diagnostics.Debug.WriteLine("Bluetooth Address: {0}", blAdress);
                            await CC2650SensorTag.PrependTextStatic(string.Format("Bluetooth Address: {0}", blAdress));


                            byte[]
                                   bytes = BitConverter.GetBytes(blAdress);
                            string res   = System.Text.Encoding.UTF8.GetString(bytes);

                            string addrStr = bytes[bytes.Length - 3].ToString("X2");
                            for (int i = bytes.Length - 4; i > -1; i--)
                            {
                                addrStr += ":" + bytes[i].ToString("X2");
                            }

                            System.Diagnostics.Debug.WriteLine("Bluetooth Address: {0}", addrStr);
                            await CC2650SensorTag.PrependTextStatic(string.Format("Bluetooth Address: {0}", addrStr));

                            var scanresp = args.AdvertisementType;
                            Windows.Devices.Enumeration.DeviceAccessStatus result;
                            try
                            {
                                result = await blDevice.RequestAccessAsync();
                            }
                            catch (Exception ex)
                            {
                                result = Windows.Devices.Enumeration.DeviceAccessStatus.DeniedBySystem;
                            }
                            if (result == Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
                            {
                                name = blDevice.Name;
                                System.Diagnostics.Debug.WriteLine("Endpoint Device Name: {0}", name);
                                await CC2650SensorTag.PrependTextStatic(string.Format("Endpoint Device Name: {0}", name));

                                var services = await blDevice.GetGattServicesAsync();

                                var svcs = services.Services;
                                System.Diagnostics.Debug.WriteLine("Endpoint Device Id: {0}", blDevice.DeviceId);
                                await CC2650SensorTag.PrependTextStatic(string.Format("Endpoint Device Id: {0}", blDevice.DeviceId));

                                System.Diagnostics.Debug.WriteLine("Start");
                                string nm   = blDevice.Name;
                                string did  = blDevice.DeviceId;
                                string info = blDevice.DeviceInformation.Name;
                                if (svcs != null)
                                {
                                    int num = svcs.Count;

                                    if (num != 0)
                                    {
                                        foreach (var x in svcs)
                                        {
                                            string sdf   = x.Uuid.ToString();
                                            string asdcb = x.DeviceId;
                                            System.Diagnostics.Debug.WriteLine("{0} = {1}", sdf, asdcb);
                                        }
                                        await TagServices.InterogateServices(svcs);

                                        OK = true;
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("No Services.");
                                        OK = false;
                                    }
                                }
                                else
                                {
                                    System.Diagnostics.Debug.WriteLine("ull Services.");
                                    OK = false;
                                }
                            }
                        }
                    }
                }
                if (!OK)
                {
                    System.Threading.Interlocked.Decrement(ref barrier);
                    BLEAdvWatcher.Start();
                }
            }
Exemple #10
0
        public async Task <Boolean> TryLocateServices(BluetoothLEDevice bluetoothLeDevice)
        {
            // Only one init
            if (GattDeviceServiceTemperature != null || GattDeviceServiceLuminosity != null || GattDeviceServiceBattery != null)
            {
                return(true);
            }

            // Try get access to device
            Windows.Devices.Enumeration.DeviceAccessStatus result;
            try
            {
                result = await bluetoothLeDevice.RequestAccessAsync();
            }
            catch (Exception)
            {
                result = Windows.Devices.Enumeration.DeviceAccessStatus.DeniedBySystem;
            }

            // Access denied
            if (result != DeviceAccessStatus.Allowed)
            {
                return(false);
            }

            // Get services of device in loop with timeout of 100 ms
            GattDeviceServicesResult gattDeviceServicesResult = null;

            for (int i = 0; i < 5; i++)
            {
                // Try get list of services
                gattDeviceServicesResult = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                // Any services in list
                if (gattDeviceServicesResult?.Services.Count > 0)
                {
                    break;
                }

                // Wait 100 ms
                await Task.Delay(100).ConfigureAwait(false);
            }

            // No services available
            if (gattDeviceServicesResult == null || gattDeviceServicesResult?.Services.Count == 0)
            {
                return(false);
            }

            // Iterate services
            foreach (var service in gattDeviceServicesResult.Services)
            {
                // 9dc84838-7619-4f09-a1ce-ddcf63225b20 is the luminosity service
                if (String.Compare(LuminosityGattServiceUuuid, service.Uuid.ToString(),
                                   StringComparison.OrdinalIgnoreCase) == 0)
                {
                    GattDeviceServiceLuminosity = service;
                }

                if (String.Compare(BatteryGattServiceUuuid, service.Uuid.ToString(),
                                   StringComparison.OrdinalIgnoreCase) == 0)
                {
                    GattDeviceServiceBattery = service;
                }

                if (String.Compare(TemperatureGattServiceUuid, service.Uuid.ToString(),
                                   StringComparison.OrdinalIgnoreCase) == 0)
                {
                    GattDeviceServiceTemperature = service;
                }
            }

            double batteryLevel = await ReadBatteryValue().ConfigureAwait(true);

            double lux = await ReadLuminosityValue().ConfigureAwait(true);

            Debug.WriteLine($"SensorBug Lux {lux} lx battery level {batteryLevel} %");

            await ReadValues().ConfigureAwait(true);

            // we can read values => start imer
            ThreadHelper.RunOnMainThread(() =>
            {
                Timer?.Start();
            });


            return(true);
        }
Exemple #11
0
        //Connect to the chosen device
        private async void ConnectDevice()
        {
            if (DeviceInterfacesOutputLst.SelectedItem != null)
            {
                string DeviceID = "";                                                                                             //Device ID
                foreach (var device in devices.Where(device => device.Name == DeviceInterfacesOutputLst.SelectedItem.ToString())) //selext the chosen device from the listview
                {
                    DeviceID = device.Id;
                }
                BluetoothDevice = await BluetoothLEDevice.FromIdAsync(DeviceID);   //request access to the Device

                DeviceAccessStatus x = await BluetoothDevice.RequestAccessAsync(); //wait for the permission

                OutputList.Items.Insert(0, "Connection: " + x.ToString() + " - BluetoothLE Device is " + BluetoothDevice.Name);
                //Create the service and characteristic values to fill with the chosen device information
                GattDeviceService         HRservice         = null;
                GattCharacteristicsResult HRcharacteristics = null;

                try //read the device characteristics, if the characteristics are not found, an exception get thrown
                {
                    HRservice         = BluetoothDevice.GetGattService(HRserviceGuid);
                    HRcharacteristics = await HRservice.GetCharacteristicsAsync();
                }
                catch
                {
                    OutputList.Items.Insert(0, "Chosen device does not support HR service, choose another one");
                    return;
                }
                //TFind the characteristics UUID and assign them to the variable
                foreach (GattCharacteristic caratteristica in HRcharacteristics.Characteristics.Where(caratteristica => caratteristica.Uuid.Equals(HRMeasurement)))
                {
                    HRreader = caratteristica; //assegno la caratteristica ad HRreader
                    OutputList.Items.Insert(0, "Heart Rate Monitor characteristic found - Handle: " + HRreader.AttributeHandle.ToString());
                }

                //check the server port data
                try
                {
                    int serverPortInt;
                    serverPortInt = Int32.Parse(tcpPortText.Text);
                    serverPort    = tcpPortText.Text;
                }
                catch
                {
                    OutputList.Items.Insert(0, "Invalid TCP Port, using 13000");
                    tcpPortText.Text = "13000";
                    serverPort       = tcpPortText.Text;
                }

                if (HRreader == null)//if the HR characteristic in not found, show an error
                {
                    OutputList.Items.Insert(0, "Heart Rate Monitor characteristic not found");
                }
                else //If the characteristic have been found, start the readings
                {
                    //Requesting notify
                    //NOTE: we are not allowed to read the value on request, we have to ask the device to be notified when the HR value change
                    GattCommunicationStatus status = GattCommunicationStatus.ProtocolError; //setting the status as "protocol error", just in case...
                    OutputList.Items.Insert(0, "Waiting for notify handshake...");

                    try
                    {
                        status = await HRreader.WriteClientCharacteristicConfigurationDescriptorAsync(
                            GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                    catch
                    {
                        //f**k, i don't know
                    }

                    //We are now ready to receive the informations and send them via TCP
                    if (status == GattCommunicationStatus.Success)
                    {
                        OutputList.Items.Insert(0, "Notify Activated");
                        OutputList.Items.Insert(0, "Now reading... give me a few seconds");
                        deviceConnectionState = true;
                        serverPort            = tcpPortText.Text;
                        OutputList.Items.Insert(0, "Connecting to port " + serverPort);

                        DispatcherTimerSetup();
                        read();
                    }
                    else
                    {
                        if (status == GattCommunicationStatus.ProtocolError)
                        {
                            OutputList.Items.Insert(0, "Notify Failed - Protocol Error");
                        }
                        if (status == GattCommunicationStatus.Unreachable)
                        {
                            OutputList.Items.Insert(0, "Notify Failed - Unreachable");
                        }
                        if (status == GattCommunicationStatus.AccessDenied)
                        {
                            OutputList.Items.Insert(0, "Notify Failed - Access Denied");
                        }
                        OutputList.Items.Insert(0, "Sorry, I'm far from perfect");
                    }
                }
            }
            else
            {
                OutputList.Items.Insert(0, "Select a device from the list"); //nel caso in cui non venga selezionato un dispositivo dalla lista
            }
        }