Пример #1
0
        public void InitiateDefault()
        {
            var heartrateSelector = GattDeviceService
                                    .GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate);

            var devices = AsyncResult(DeviceInformation
                                      .FindAllAsync(heartrateSelector));

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                throw new ArgumentNullException(
                          nameof(device),
                          "Unable to locate heart rate device.");
            }

            GattDeviceService service;

            lock (_disposeSync)
            {
                if (_isDisposed)
                {
                    throw new ObjectDisposedException(GetType().Name);
                }

                Cleanup();

                service = AsyncResult(GattDeviceService.FromIdAsync(device.Id));

                _service = service;
            }

            var heartrate = service.GetCharacteristics(
                GattDeviceService.ConvertShortIdToUuid(
                    _heartRateMeasurementCharacteristicId))
                            .FirstOrDefault();

            if (heartrate == null)
            {
                throw new ArgumentOutOfRangeException(
                          $"Unable to locate heart rate measurement on device {device.Name} ({device.Id}).");
            }

            var status = AsyncResult(
                heartrate.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify));

            heartrate.ValueChanged += HeartRate_ValueChanged;

            Debug.WriteLine($"Started {status}");
        }
Пример #2
0
        private static async void DeviceAdded(DeviceWatcher watcher, DeviceInformation device)
        {
            try
            {
                var service = await GattDeviceService.FromIdAsync(device.Id);

                WriteLine("Opened Service!!");
            }
            catch
            {
                WriteLine("Failed to open service.");
            }
        }
Пример #3
0
        public async Task InitAsync()
        {
            var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(_servcieUuid), new string[] { "System.Devices.ContainerId" });

            var defaultDevice = devices.FirstOrDefault();

            if (defaultDevice == null)
            {
                throw new Exception("Device not found");
            }

            _service = await GattDeviceService.FromIdAsync(defaultDevice.Id);
        }
Пример #4
0
        public void InitiateDefault()
        {
            filename = "polar" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
            var heartrateSelector = GattDeviceService
                                    .GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate);

            var devices = AsyncResult(DeviceInformation
                                      .FindAllAsync(heartrateSelector));

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                throw new ArgumentOutOfRangeException(
                          "Unable to locate heart rate device.");
            }

            GattDeviceService service;

            lock (_disposeSync)
            {
                if (_isDisposed)
                {
                    throw new ObjectDisposedException(GetType().Name);
                }

                Cleanup();

                service = AsyncResult(GattDeviceService.FromIdAsync(device.Id));

                _service = service;
            }

            var uuid      = BluetoothUuidHelper.FromShortId(_heartRateMeasurementCharacteristicId);
            var heartrate = AsyncResult(service.GetCharacteristicsForUuidAsync(uuid)).Characteristics.FirstOrDefault();

            if (heartrate == null)
            {
                throw new ArgumentOutOfRangeException(
                          $"Unable to locate heart rate measurement on device {device.Name} ({device.Id}).");
            }

            var status = AsyncResult(
                heartrate.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify));

            heartrate.ValueChanged += HeartRate_ValueChanged;

            Debug.WriteLine($"Started {status}");
        }
Пример #5
0
        /// <summary>
        /// Finds the GattDeviceService by sensorServiceUuid.
        /// IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it
        /// </summary>
        /// <returns></returns>
        /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which matches the sensor service id.</exception>
        private async Task <GattDeviceService> GetDeviceService()
        {
            string selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensorServiceUuid));
            var    devices  = await DeviceInformation.FindAllAsync(selector);

            DeviceInformation di = devices.FirstOrDefault();

            if (di == null)
            {
                throw new DeviceNotFoundException();
            }

            return(await GattDeviceService.FromIdAsync(di.Id));
        }
Пример #6
0
        public async Task ConnectToServcie()
        {
            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(BATTERY_SERVICE_ID),
                new string[] { "System.Devices.ContainerId" });

            var defaultDevice = devices.FirstOrDefault();

            if (defaultDevice != null)
            {
                var service = await GattDeviceService.FromIdAsync(defaultDevice.Id);

                var Characteristics = service.GetCharacteristics(BATTERY_LEVEL_CHARACTERISTIC_ID);

                GattCharacteristic characteristic = Characteristics.FirstOrDefault();

                if (characteristic != null)
                {
                    characteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired;

                    characteristic.ValueChanged += characteristic_ValueChanged;

                    var currentDescriptorValue = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();

                    var CHARACTERISTIC_NOTIFY_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;

                    if (currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != CHARACTERISTIC_NOTIFY_TYPE)
                    {
                        // Set the Client Characteristic Configuration Descriptor to enable the device to indicate
                        // when the Characteristic value changes
                        GattCommunicationStatus status =
                            await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                                CHARACTERISTIC_NOTIFY_TYPE);
                    }

                    //GattReadResult result = await characteristic.ReadValueAsync();

                    //if (result.Status == GattCommunicationStatus.Success)
                    //{
                    //    var reader = DataReader.FromBuffer(result.Value);

                    //    byte[] bytes = new byte[result.Value.Length];

                    //    reader.ReadBytes(bytes);

                    //    _deviceManufacturer = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    //}
                }
            }
        }
        public async Task <byte[]> GetValue(Guid gattCharacteristicUuids)
        {
            try
            {
                var gattDeviceService = await GattDeviceService.FromIdAsync(Device.Id);

                if (gattDeviceService != null)
                {
                    var characteristics = gattDeviceService.GetCharacteristics(gattCharacteristicUuids).First();

                    //If the characteristic supports Notify then tell it to notify us.
                    try
                    {
                        if (characteristics.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                        {
                            characteristics.ValueChanged += characteristics_ValueChanged;
                            await characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                        }
                    }
                    catch { }

                    //Read
                    if (characteristics.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                    {
                        var result = await characteristics.ReadValueAsync(BluetoothCacheMode.Uncached);

                        if (result.Status == GattCommunicationStatus.Success)
                        {
                            byte[] forceData = new byte[result.Value.Length];
                            DataReader.FromBuffer(result.Value).ReadBytes(forceData);
                            return(forceData);
                        }
                        else
                        {
                            await new MessageDialog(result.Status.ToString()).ShowAsync();
                        }
                    }
                }
                else
                {
                    await new MessageDialog("Access to the device has been denied =(").ShowAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return(null);
        }
Пример #8
0
        private static async Task <GattDeviceService> Initialize(string serviceUuid)
        {
            GattDeviceService deviceService = null;
            string            selector      = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(serviceUuid));
            var devices = await DeviceInformation.FindAllAsync(selector, new string[] { "System.Devices.ContainerId" });

//            devicesTask.Wait();
            var deviceInfo = devices[0];

            if (deviceInfo != null)
            {
                deviceService = await GattDeviceService.FromIdAsync(deviceInfo.Id);
            }
            return(deviceService);
        }
Пример #9
0
    /*-----------------
     *    Methods
     * ------------------*/
    public async void InitializeDevice()
    {
        /*** Get a list of devices that match desired service UUID  ***/
        var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(selectedService));

        /*** Create an instance of the eTDS device ***/
        eTdsDevice = devices[0];       // Only one device should be matching the eTDS-specific service UUID, hence [0]

        /*** Create an instance of the specified eTDS service ***/
        myService = await GattDeviceService.FromIdAsync(eTdsDevice.Id);

        /*** Create an instance of the characteristic of the specified service ***/
        myCharacteristic = myService.GetCharacteristics(selectedCharacteristic)[0];
        myCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;   // Set security level to "No encryption"
    }// end method InitializeDevice
Пример #10
0
        // retornar el servicio principal de la pulsera
        private async Task getService()
        {
            Debug.WriteLine("[miband] accediendo a servicio");
            GattDeviceService _service;

            if (device != null)
            {
                _service = await GattDeviceService.FromIdAsync(device.Id);

                if (_service != null)
                {
                    this.service = _service;
                }
            }
        }
Пример #11
0
        private async void ButtonAction1_Click(object sender, RoutedEventArgs e)
        {
            DevicesInformation = $"Device Id,Name,service.Uuid,service Name,service.AttributeHandle,characteristic.Uuid,Char Name,CharacteristicProperties,Char ProtectionLevel,UserDescription,,,{Environment.NewLine}";
            Debug.WriteLine(DevicesInformation);
            var bts = await DeviceInformation.FindAllAsync();

            foreach (var device in bts.Where(di => di.Name == RsServiceDiscovery.DeviceName))
            {
                try
                {
                    var service = await GattDeviceService.FromIdAsync(device.Id);

                    if (null == service)
                    {
                        continue;
                    }
                    var characteristics = service.GetAllCharacteristics();
                    if (null == characteristics || characteristics.Count <= 0)
                    {
                        return;
                    }

                    foreach (var characteristic in characteristics)
                    {
                        try
                        {
                            var serviceName = CharacteristicUuidsResolver.GetNameFromUuid(service.Uuid);
                            var charName    = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid);

                            string msg =
                                $"{device.Id}, {device.Name}, {service.Uuid}, {serviceName}, {service.AttributeHandle}, {characteristic.Uuid}, {charName}, {characteristic.CharacteristicProperties}, {characteristic.ProtectionLevel}, {characteristic.UserDescription}{Environment.NewLine}";
                            Debug.WriteLine(msg);
                            DevicesInformation += msg;
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
                catch
                {
                    string msg = $"{device.Id}, {device.Name}, , , , , , , , {Environment.NewLine}";
                    Debug.WriteLine(msg);
                    DevicesInformation += msg;
                }
            }
        }
Пример #12
0
        static public async void bluetoothle()
        {
            //デバイスを検索
            string deveiceSelector = GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HealthThermometer);//uuidから取得
            DeviceInformationCollection themometerServices = await DeviceInformation.FindAllAsync(deveiceSelector, null);

            Console.WriteLine(themometerServices[0].Name);
            Console.ReadLine();

            //デバイの指定
            if (themometerServices.Count > 0)
            {
                DeviceInformation themometerService = themometerServices.First();
                string            ServiceNameText   = "Using service: " + themometerService.Name;

                // サービスを作成
                GattDeviceService firstThermometerService = await GattDeviceService.FromIdAsync(themometerService.Id);

                if (firstThermometerService != null)
                {
                    //Gattの選択
                    // キャラクタリスティックを取得
                    GattCharacteristic thermometerCharacteristic = firstThermometerService.GetCharacteristics(GattCharacteristicUuids.TemperatureMeasurement).First();

                    // 通知イベントを登録

                    Console.WriteLine("Connect:" + ServiceNameText + "\n");

                    await thermometerCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

                    thermometerCharacteristic.ValueChanged += TemperatureMeasurementChanged;
                }
                else
                {
                    // サービスを見つけられなかった
                    // Capabilityの設定漏れはここへ
                    Console.WriteLine("Notfound:" + ServiceNameText + "\n");
                    return;
                }
            }
            else
            {
                // 発見できなかった
                // BluetoothがOFFの場合はここへ
                Console.WriteLine("Notfound : Bluetooth" + "\n");
                return;
            }
        }
Пример #13
0
        private async Task <GattDeviceService> getDeviceService()
        {
            Debug.WriteLine("*getDeviceService: enter=" + sensorServiceUuid);

            string selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensorServiceUuid));
            var    devices  = await DeviceInformation.FindAllAsync(selector);

            DeviceInformation di = devices.FirstOrDefault();

            if (di == null)
            {
                throw new ArgumentOutOfRangeException();
            }

            return(await GattDeviceService.FromIdAsync(di.Id));
        }
Пример #14
0
        /// <summary>
        /// Finds the GattDeviceService by sensorServiceUuid.
        /// IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it.
        /// </summary>
        /// <returns>Returns the gatt device service of the first device that supports it. Returns null if access is denied.</returns>
        /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which provides the service Uuid.</exception>
        public async static Task <GattDeviceService> GetDeviceService(string serviceUuid)
        {
            Validator.RequiresNotNullOrEmpty(serviceUuid);

            string selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(serviceUuid));
            var    devices  = await DeviceInformation.FindAllAsync(selector);

            DeviceInformation di = devices.FirstOrDefault();

            if (di == null)
            {
                throw new DeviceNotFoundException();
            }

            return(await GattDeviceService.FromIdAsync(di.Id));
        }
Пример #15
0
        private async void DeviceAdded(DeviceWatcher watcher, DeviceInformation device)
        {
            if (_devices.Contains(device.Name))
            {
                try
                {
                    var service = await GattDeviceService.FromIdAsync(device.Id);

                    Debug.WriteLine("Opened Service!!");
                }
                catch
                {
                    Debug.WriteLine("Failed to open service.");
                }
            }
        }
Пример #16
0
        private async void ScaleAdded(DeviceWatcher watcher, DeviceInformation device)
        {
            if (device.Name == ScaleName)
            {
                try
                {
                    var service = await GattDeviceService.FromIdAsync(device.Id);

                    var characteristics = service.GetAllCharacteristics();
                }
                catch
                {
                    Debug.WriteLine("Failed to open service.");
                }
            }
        }
Пример #17
0
        // Get currently selected service using the device id.
        // This is called everytime before an attempt to get data is made, due to the possiblity of the device disconnecting.
        internal async Task <GattDeviceService> GetService()
        {
            // Attempt to get the servcei using device id.
            var service = await GattDeviceService.FromIdAsync(this.DeviceID);

            if (service == null)
            {
                // Error accessing the service.
                throw new UnauthorizedAccessException();
            }
            else
            {
                // Have succesfully retrieved the service, return it.
                return(service);
            }
        }
        private static async Task <GattReadResult> ReadDeviceIdAsync(string selector)
        {
            var devices = await DeviceInformation.FindAllAsync(selector, new string[] { devicesContainerId });

            DeviceInformation di = devices.FirstOrDefault();
            var containerId      = di.Properties[devicesContainerId].ToString();

            var selectorWithContainer = String.Format("{0} AND System.Devices.ContainerId:=\"{{{1}}}\"", selector, containerId);
            var serviceInformations   = await DeviceInformation.FindAllAsync(selectorWithContainer);

            var deviceInformationService = await GattDeviceService.FromIdAsync(serviceInformations.Single().Id);

            var systemId = deviceInformationService.GetCharacteristics(GattDeviceService.ConvertShortIdToUuid(0x2a23)).First(); // System ID

            return(await systemId.ReadValueAsync(BluetoothCacheMode.Uncached));
        }
Пример #19
0
        private async void ButtonAction2_Click(object sender, RoutedEventArgs e)
        {
            var serviceIds = new[]
            {
                "00001800-0000-1000-8000-00805F9B34FB",
                "00001801-0000-1000-8000-00805F9B34FB",
                "9A66FA00-0800-9191-11E4-012D1540CB8E",
                "9A66FB00-0800-9191-11E4-012D1540CB8E",
                "9A66FC00-0800-9191-11E4-012D1540CB8E",
                "9A66FD21-0800-9191-11E4-012D1540CB8E",
                "9A66FD51-0800-9191-11E4-012D1540CB8E",
                "9A66FE00-0800-9191-11E4-012D1540CB8E"
            };

            DevicesInformation = "";
            var bts = await DeviceInformation.FindAllAsync();

            foreach (var serviceId in serviceIds)
            {
                DevicesInformation += $"{serviceId}{Environment.NewLine}";

                foreach (var device in bts)
                {
                    if (!device.Id.ToUpper().Contains(serviceId))
                    {
                        continue;
                    }

                    DevicesInformation += $"    {device.Id}{Environment.NewLine}";
                    try
                    {
                        var service = await GattDeviceService.FromIdAsync(device.Id);

                        if (null == service)
                        {
                            continue;
                        }
                        var characteristicsFa00 = service.GetAllCharacteristics();
                        DevicesInformation += $"    Allow Chars{Environment.NewLine}";
                    }
                    catch
                    {
                        DevicesInformation += $"    Don't Allow Chars{Environment.NewLine}";
                    }
                }
            }
        }
Пример #20
0
        // Setup
        // Saves GATT service object in array
        private async Task <bool> init()
        {
            // Retrieve instances of the GATT services that we will use
            for (int i = 0; i < NUM_SENSORS; i++)
            {
                // Setting Service GUIDs
                // Built in enumerations are found in the GattServiceUuids class like this: GattServiceUuids.GenericAccess
                Guid BLE_GUID;
                if (i < 6)
                {
                    BLE_GUID = new Guid("F000AA" + i + "0-0451-4000-B000-000000000000");
                }
                else
                {
                    BLE_GUID = new Guid("0000FFE0-0000-1000-8000-00805F9B34FB");
                }

                // Retrieving and saving GATT services
                var services = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(BLE_GUID), null);

                if (services != null && services.Count > 0)
                {
                    if (services[0].IsEnabled)
                    {
                        GattDeviceService service = await GattDeviceService.FromIdAsync(services[0].Id);

                        if (service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected)
                        {
                            serviceList[i] = service;
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #21
0
        async Task <bool> ConnectDaydream(DeviceInformation info)
        {
            try
            {
                Console.WriteLine(string.Format("Trying to connect {0} {1}", info.Name, info.Id));
                service = await AsTask(GattDeviceService.FromIdAsync(info.Id));

                if (service == null)
                {
                    Console.WriteLine("Error: Another program is using the device.");
                    return(false);
                }

                var list = service.GetCharacteristics(Constants.DAYDREAM_CHARACTERISTICS_UUID);
                if (list.Count == 0)
                {
                    Console.WriteLine("Error: No characteristics. uuid=DAYDREAM_CHARACTERISTICS_UUID.");
                    return(false);
                }

                daydreamCharacteristic = list[0];
                daydreamCharacteristic.ValueChanged += CallbackDaydream;
                var status = await AsTask(daydreamCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify));

                //Console.WriteLine("Write: {0}", status.ToString());
                if (status == GattCommunicationStatus.Success)
                {
                    Console.WriteLine("Connected.");
                    type       = Constants.TYPE_DAYDREAM;
                    bdaddr     = BDAddrToString(service.Device.BluetoothAddress);
                    deviceId   = service.Device.DeviceId;
                    deviceName = info.Name;
                    return(true);
                }
                else
                {
                    Console.WriteLine("Error: Cannot connect. (Timeout)");
                    return(false);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: Caught exception. " + e.Message);
            }

            return(false);
        }
Пример #22
0
        private async void startButton_Click(object sender, RoutedEventArgs e)
        {
            int count = 0;

            /*** Get a list of devices that match desired service UUID  ***/
            Guid selectedService = new Guid("0000AA00-0000-1000-8000-00805F9B34FB");
            var  devices         = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(selectedService));

            /*** Create an instance of the eTDS device ***/
            DeviceInformation eTdsDevice = devices[0];                                // Only one device should be matching the eTDS-specific service UUID

            displayTextBox.Text = string.Format("Device Name: {0}", eTdsDevice.Name); // Display the name of the device

            /*** Create an instance of the specified eTDS service ***/
            GattDeviceService myService = await GattDeviceService.FromIdAsync(eTdsDevice.Id);

            displayTextBox.Text = string.Format("\r\nService UUID: {0}", myService.Uuid.ToString());

            /*** Create an instance of the characteristic of the specified service ***/
            Guid               selectedCharacteristic = new Guid("0000AA01-0000-1000-8000-00805F9B34FB");
            const int          CHARACTERISTIC_INDEX   = 0;
            GattCharacteristic myCharacteristic       = myService.GetCharacteristics(selectedCharacteristic)[CHARACTERISTIC_INDEX];

            myCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;    // Set security level to "No encryption"

            /*** Reading 1000 data samples ***/
            //GattReadResult bleData;
            //byte[] bleDataArray = new byte[6];

//           for (int i = 0; i < 1000; i++)
//           {
//              /* Read data from a buffer */
//              bleData = await myCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
//              DataReader.FromBuffer(bleData.Value).ReadBytes(bleDataArray);

//              /* Display each element of raw data */
//              count++;
//              displayTextBox.Text = string.Format("\r\nValue {0}: {1} {2} {3} {4} {5} {6}", count, bleDataArray[0], bleDataArray[1], bleDataArray[2], bleDataArray[3], bleDataArray[4], bleDataArray[5]);

//              /* Pause thread execution */
////              await Task.Delay(TimeSpan.FromMilliseconds(100));
//           }

            /*** Create an event handler when the characteristic value changes ***/
            myCharacteristic.ValueChanged += myCharacteristic_ValueChanged;
            await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
        }
Пример #23
0
        public async Task <int> Subscribe(String ID)
        {
            service = await GattDeviceService.FromIdAsync(ID);

            characteristics = service.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement)[0];
            if (!subscribedForNotifications)
            {
                // initialize status
                GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
                var cccdValue = GattClientCharacteristicConfigurationDescriptorValue.None;
                if (characteristics.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                {
                    cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
                }

                else if (characteristics.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
                }

                try
                {
                    // BT_Code: Must write the CCCD in order for server to send indications.
                    // We receive them in the ValueChanged event handler.
                    status = await characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);

                    if (status == GattCommunicationStatus.Success)
                    {
                        characteristics.ValueChanged += Characteristic_ValueChanged;
                        subscribedForNotifications    = true;
                        Debug.WriteLine("Successfully subscribed for value changes");
                        return(1);
                    }
                    else
                    {
                        Debug.WriteLine($"Error registering for value changes: {status}");
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    // This usually happens when a device reports that it support indicate, but it actually doesn't.
                    Debug.WriteLine(ex.Message);
                }
            }
            return(0);
        }
Пример #24
0
        }//end constructor

        /* Methods */
        public async Task InitializationAsync()
        {
            /*** Get a list of devices that match desired service UUID  ***/
            var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(gattService));

            /*** Create an instance of the eTDS device ***/
            TdsDevice = devices[0];      // Only one device should be matching the eTDS-specific service UUID

            /*** Create an instance of the specified eTDS service ***/
            myService = await GattDeviceService.FromIdAsync(TdsDevice.Id);

            /*** Create an instance of the characteristic of the specified service ***/
            const int CHARACTERISTIC_INDEX = 0;

            myCharacteristic = myService.GetCharacteristics(gattCharacteristic)[CHARACTERISTIC_INDEX];
            myCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;  // Set security level to "No encryption"
        }
Пример #25
0
        private static async Task ReadShockSensor(Guid charId)
        {
            var gattDevices = await DeviceInformation.FindAllAsync(GetServiceSelector());

            foreach (var gattDevice in gattDevices)
            {
                try
                {
                    var gattServce = await GattDeviceService.FromIdAsync(gattDevice.Id);

                    if (gattServce == null)
                    {
                        Console.WriteLine("Failed to open device: {0}", gattDevice.Id);
                        continue;
                    }


                    var allCharacteristics = gattServce.GetCharacteristics(charId);
                    if (allCharacteristics == null || allCharacteristics.Count == 0)
                    {
                        continue;
                    }

                    var gattCharacteristic = allCharacteristics[0];

                    Console.WriteLine("Setting chararcteristic config to Indicate....");
                    var charConfig = await gattCharacteristic.ReadClientCharacteristicConfigurationDescriptorAsync();

                    if (charConfig.Status == GattCommunicationStatus.Success &&
                        charConfig.ClientCharacteristicConfigurationDescriptor != GattClientCharacteristicConfigurationDescriptorValue.Indicate)
                    {
                        await gattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                    }

                    Console.WriteLine("Reading characteristic value....");
                    var charValue = await gattCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);

                    var strValue = BitConverter.ToString(charValue.Value.ToArray());
                    Console.WriteLine("Characteristic={0} Handle={2} Value={1}", gattCharacteristic.Uuid, strValue, gattCharacteristic.AttributeHandle);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Пример #26
0
        private async Task <Dictionary <string, RsCharacteristic> > GetCharsFromDeviceId(string deviceId, Dictionary <string, RsCharacteristic> dicCharacteristics)
        {
            try
            {
                var service = await GattDeviceService.FromIdAsync(deviceId);

                if (null != service)
                {
                    dicCharacteristics = CompletePropsFromServiceChars(service, deviceId, dicCharacteristics);
                }
            }
            catch
            {
                // ignored
            }
            return(dicCharacteristics);
        }
Пример #27
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var bts = await DeviceInformation.FindAllAsync();

            const string deviceId = @"\\?\BTHLEDevice#{9a66fa00-0800-9191-11e4-012d1540cb8e}_e0144d4f3d49#a&1f09a1af&0&0020#{6e3bb679-4372-40c8-9eaa-4509df260cd8}";

            var device = bts.First(di => di.Name == DeviceName && di.Id == deviceId);

            if (null == device)
            {
                return;
            }
            _service = await GattDeviceService.FromIdAsync(device.Id);

            if (null == _service)
            {
                return;
            }
            _characteristics = _service.GetAllCharacteristics();
            if (null == _characteristics || _characteristics.Count <= 0)
            {
                return;
            }

            var characteristic = _characteristics.First(charact => charact.Uuid == RollingSpiderCharacteristicUuids.Parrot_PowerMotors);

            try
            {
                var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid);
                Debug.WriteLine(charName);
                for (int i = 0; i < 255; i++)
                {
                    Debug.WriteLine(i);
                    byte[] arr    = { (byte)02, (byte)40, (byte)20, (byte)0D, 00, 09, 00, 04, 00, 52, 43, 00, 04, (byte)i, 02, 00, 01, 00, };
                    var    writer = new DataWriter();
                    writer.WriteBytes(arr);
                    await characteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch
            {
            }
        }
Пример #28
0
        public async Task Connect()
        {
            // create service
            DeviceServices.Add(await GattDeviceService.FromIdAsync(DeviceInformations[0].Id));
            DeviceServices.Add(await GattDeviceService.FromIdAsync(DeviceInformations[1].Id));
            DeviceServices.Add(await GattDeviceService.FromIdAsync(DeviceInformations[2].Id));
            DeviceServices.Add(await GattDeviceService.FromIdAsync(DeviceInformations[3].Id));
            DeviceServices.Add(await GattDeviceService.FromIdAsync(DeviceInformations[4].Id));

            // register characteristics A00
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A01);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A02);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A0A_Movement);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A0B_SimpleCommands);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A0C_EmergencyStop);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A1E_InitCount1To20);
            RegisterCharacteristic(ParrotUuids.Service_A00, ParrotUuids.Characteristic_A1F);

            // register characteristics B00
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B01);
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B0E_DroneState);
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B1B);
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B1C);
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B1F);
            RegisterCharacteristic(ParrotUuids.Service_B00, ParrotUuids.Characteristic_B0F_Battery);

            // register characteristics C00
            RegisterCharacteristic(ParrotUuids.Service_C00, ParrotUuids.Characteristic_C1);

            // register characteristics D21
            RegisterCharacteristic(ParrotUuids.Service_D21, ParrotUuids.Characteristic_D22);
            RegisterCharacteristic(ParrotUuids.Service_D21, ParrotUuids.Characteristic_D23);
            RegisterCharacteristic(ParrotUuids.Service_D21, ParrotUuids.Characteristic_D24);

            // register characteristics D51
            RegisterCharacteristic(ParrotUuids.Service_D51, ParrotUuids.Characteristic_D52);
            RegisterCharacteristic(ParrotUuids.Service_D51, ParrotUuids.Characteristic_D53);
            RegisterCharacteristic(ParrotUuids.Service_D51, ParrotUuids.Characteristic_D54);

            await RegisterEventhandling(ParrotUuids.Service_B00);
            await RegisterEventhandling(ParrotUuids.Service_D21);
            await RegisterEventhandling(ParrotUuids.Service_D51);

            //await InitChannelA1E();
        }
        private static async Task <GattReadResult> ReadDeviceNameAsync(string selector)
        {
            var devices = await DeviceInformation.FindAllAsync(selector, new string[] { devicesContainerId });

            DeviceInformation di = devices.FirstOrDefault();
            var containerId      = di.Properties[devicesContainerId].ToString();

            // Access to Generic Attribute Profile service
            var genericSlector        = GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess);
            var selectorWithContainer = String.Format("{0} AND System.Devices.ContainerId:=\"{{{1}}}\"", genericSlector, containerId);
            var serviceInformations   = await DeviceInformation.FindAllAsync(selectorWithContainer);

            var gapService = await GattDeviceService.FromIdAsync(serviceInformations.Single().Id);

            var deviceName = gapService.GetCharacteristics(GattDeviceService.ConvertShortIdToUuid(0x2a00)).First();

            return(await deviceName.ReadValueAsync(BluetoothCacheMode.Uncached));
        }
Пример #30
0
        async Task <GattDeviceService> GetService(GATTDefaultService service)
        {
            var devices = await DeviceInformation.FindAllAsync(service.Filter);

            foreach (var device in devices)
            {
                if (device.Name == DEVICE_NAME)
                {
                    var deviceService = await GattDeviceService.FromIdAsync(device.Id);

                    if (deviceService.Device.DeviceInformation.Id == this.Device.Id)
                    {
                        return(deviceService);
                    }
                }
            }
            return(null);
        }