Esempio n. 1
0
        private static async void Commands()
        {
            _errorCode = 0;
            //Search for polar device
            Console.WriteLine(" | Searching device...");
            ListDevices();

            DeviceInformation tempDevice = null;

            while (tempDevice == null)
            {
                ListDevices();
                tempDevice = _deviceList.FirstOrDefault(d => d.Name.Contains("Polar", StringComparison.OrdinalIgnoreCase));
                if (tempDevice == null)
                {
                    Thread.Sleep(1000);
                }
            }

            //Connecting to device
            Console.WriteLine(" | Connecting...");
            _errorCode += await OpenDevice(tempDevice.Name);

            //Search for correct service
            Console.WriteLine(" | Searching service...");

            BluetoothLEAttributeDisplay tempService = null;

            while (tempService == null)
            {
                tempService = _services.FirstOrDefault(d => d.Name.Contains("Heart", StringComparison.OrdinalIgnoreCase));
                if (tempService == null)
                {
                    Thread.Sleep(1000);
                }
            }

            Thread.Sleep(1000);
            //Subscribing to service
            Console.WriteLine(" | Registerring service...");
            Console.WriteLine($" > set ");
            _errorCode += await SetService(tempService.Name);

            Console.WriteLine($" > subs");
            _errorCode += await SubscribeToCharacteristic(tempService.Name);

            Console.WriteLine(" | Listening...");
        }
Esempio n. 2
0
        /// <summary>
        /// Set active service for current device
        /// </summary>
        /// <param name="parameters"></param>
        static async Task <int> SetService(string serviceName)
        {
            int retVal = 0;

            if (_selectedDevice != null)
            {
                if (!string.IsNullOrEmpty(serviceName))
                {
                    string foundName = Utilities.GetIdByNameOrNumber(_services, serviceName);

                    // If device is found, connect to device and enumerate all services
                    if (!string.IsNullOrEmpty(foundName))
                    {
                        var attr = _services.FirstOrDefault(s => s.Name.Equals(foundName));
                        IReadOnlyList <GattCharacteristic> characteristics = new List <GattCharacteristic>();

                        try
                        {
                            // Ensure we have access to the device.
                            var accessStatus = await attr.service.RequestAccessAsync();

                            if (accessStatus == DeviceAccessStatus.Allowed)
                            {
                                // BT_Code: Get all the child characteristics of a service. Use the cache mode to specify uncached characterstics only
                                // and the new Async functions to get the characteristics of unpaired devices as well.
                                var result = await attr.service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                                if (result.Status == GattCommunicationStatus.Success)
                                {
                                    characteristics  = result.Characteristics;
                                    _selectedService = attr;
                                    _characteristics.Clear();
                                    if (!Console.IsInputRedirected)
                                    {
                                        Console.WriteLine($"Selected service {attr.Name}.");
                                    }

                                    if (characteristics.Count > 0)
                                    {
                                        for (int i = 0; i < characteristics.Count; i++)
                                        {
                                            var charToDisplay = new BluetoothLEAttributeDisplay(characteristics[i]);
                                            _characteristics.Add(charToDisplay);
                                            if (!Console.IsInputRedirected)
                                            {
                                                Console.WriteLine($"#{i:00}: {charToDisplay.Name}\t{charToDisplay.Chars}");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!Console.IsOutputRedirected)
                                        {
                                            Console.WriteLine("Service don't have any characteristic.");
                                        }
                                        retVal += 1;
                                    }
                                }
                                else
                                {
                                    if (!Console.IsOutputRedirected)
                                    {
                                        Console.WriteLine("Error accessing service.");
                                    }
                                    retVal += 1;
                                }
                            }
                            // Not granted access
                            else
                            {
                                if (!Console.IsOutputRedirected)
                                {
                                    Console.WriteLine("Error accessing service.");
                                }
                                retVal += 1;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!Console.IsOutputRedirected)
                            {
                                Console.WriteLine($"Restricted service. Can't read characteristics: {ex.Message}");
                            }
                            retVal += 1;
                        }
                    }
                    else
                    {
                        if (!Console.IsOutputRedirected)
                        {
                            Console.WriteLine("Invalid service name or number");
                        }
                        retVal += 1;
                    }
                }
                else
                {
                    if (!Console.IsOutputRedirected)
                    {
                        Console.WriteLine("Invalid service name or number");
                    }
                    retVal += 1;
                }
            }
            else
            {
                if (!Console.IsOutputRedirected)
                {
                    Console.WriteLine("Nothing to use, no BLE device connected.");
                }
                retVal += 1;
            }

            return(retVal);
        }
Esempio n. 3
0
        static async Task <int> OpenDevice(string deviceName)
        {
            int retVal = 0;

            if (!string.IsNullOrEmpty(deviceName))
            {
                var    devs    = _deviceList.OrderBy(d => d.Name).Where(d => !string.IsNullOrEmpty(d.Name)).ToList();
                string foundId = Utilities.GetIdByNameOrNumber(devs, deviceName);

                // If device is found, connect to device and enumerate all services
                if (!string.IsNullOrEmpty(foundId))
                {
                    _selectedService = null;
                    _services.Clear();

                    try
                    {
                        // only allow for one connection to be open at a time
                        if (_selectedDevice != null)
                        {
                            CloseDevice();
                        }

                        _selectedDevice = await BluetoothLEDevice.FromIdAsync(foundId).AsTask().TimeoutAfter(_timeout);

                        if (!Console.IsInputRedirected)
                        {
                            Console.WriteLine($"Connecting to {_selectedDevice.Name}.");
                        }

                        var result = await _selectedDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                        if (result.Status == GattCommunicationStatus.Success)
                        {
                            if (!Console.IsInputRedirected)
                            {
                                Console.WriteLine($"Found {result.Services.Count} services:");
                            }

                            for (int i = 0; i < result.Services.Count; i++)
                            {
                                var serviceToDisplay = new BluetoothLEAttributeDisplay(result.Services[i]);
                                _services.Add(serviceToDisplay);
                                if (!Console.IsInputRedirected)
                                {
                                    Console.WriteLine($"#{i:00}: {_services[i].Name}");
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine($"Device {deviceName} is unreachable.");
                            retVal += 1;
                        }
                    }
                    catch
                    {
                        Console.WriteLine($"Device {deviceName} is unreachable.");
                        retVal += 1;
                    }
                }
                else
                {
                    retVal += 1;
                }
            }
            else
            {
                Console.WriteLine("Device name can not be empty.");
                retVal += 1;
            }
            return(retVal);
        }