Beispiel #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}");
        }
        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));
        }
        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));
        }
Beispiel #4
0
        private async Task Connect()
        {
            try
            {
                _device = await Windows.Devices.Bluetooth.BluetoothLEDevice.FromBluetoothAddressAsync(220989373023087);

                _device.ConnectionStatusChanged += Device_ConnectionStatusChanged;
                _service = _device.GattServices.Where(s => s.Uuid == GattDeviceService.ConvertShortIdToUuid(0xFFE0)).SingleOrDefault();
                if (_service != null)
                {
                    _characteristic = _service.GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(0xFFE1)).Single();
                    _characteristic.ProtectionLevel = GattProtectionLevel.Plain;
                    _characteristic.ValueChanged   += Characteristic_ValueChanged;
                    bool status = false;
                    switch (_device.ConnectionStatus)
                    {
                    case Windows.Devices.Bluetooth.BluetoothConnectionStatus.Disconnected:
                        status = false;
                        break;

                    case Windows.Devices.Bluetooth.BluetoothConnectionStatus.Connected:
                        status = true;
                        break;
                    }
                    OnConnectionStatusChanged(new ConnectionStatusChangedEventArgs(status));
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Nie można nawiązać łączności z urządzeniem sterującym. Możliwe przyczyny: \n\r- Brak odbiornika Bluetooth\n\r- Urządzenie nie jest sparowane\n\r- Brak sterowników Bluetooth.\n\rBez podłączonego urządzenia sterującego korzystanie z aplikacji nie jest możliwe.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //switch ((uint)e.HResult)
                //{
                //    case 0x80070490:
                //        MessageBox.Show("Wykonaj parowanie urządzenia sterującego z komputerem. Informacje dotyczące parowania znajdziesz w zakładce Help", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //        break;
                //}
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("1. Device List -> Service List");
            Console.WriteLine("2. Service List");
            Console.WriteLine("3. Battery Service Only");
            Console.WriteLine("4. Health Thermometer Service Only");
            Console.Write("Input: ");
            var workflow = int.Parse(Console.ReadLine());

            Console.WriteLine();

            DeviceInformationCollection servicesInfo;

            switch (workflow)
            {
            case 1:
            {
                // BluetoothLEデバイス一覧を表示します。
                #region MjDeviceInformation.FindGattDevicesAsync()
                var devicesInfoResult = MjDeviceInformation.FindGattDevicesAsync();
                while (devicesInfoResult.Status == AsyncStatus.Started)
                {
                    System.Threading.Thread.Sleep(10);
                }
                var devicesInfo = devicesInfoResult.GetResults();
                for (int i = 0; i < devicesInfo.Count; i++)
                {
                    Console.WriteLine("{0}. [{1}]", i + 1, devicesInfo[i].Name);
                }
                Console.Write("Input: ");
                var deviceInfo = devicesInfo[int.Parse(Console.ReadLine()) - 1];
                Console.WriteLine();
                #endregion

                // GATTサービス一覧を取得します。
                #region MjDeviceInformation.FindGattServicesAsync(deviceInfo)
                var servicesInfoResult = MjDeviceInformation.FindGattServicesAsync(deviceInfo);
                while (servicesInfoResult.Status == AsyncStatus.Started)
                {
                    System.Threading.Thread.Sleep(10);
                }
                servicesInfo = servicesInfoResult.GetResults();
                #endregion
            }
            break;

            case 2:
            {
                // GATTサービス一覧を取得します。
                #region MjDeviceInformation.FindGattServicesAsync()
                var servicesInfoResult = MjDeviceInformation.FindGattServicesAsync();
                while (servicesInfoResult.Status == AsyncStatus.Started)
                {
                    System.Threading.Thread.Sleep(10);
                }
                servicesInfo = servicesInfoResult.GetResults();
                #endregion
            }
            break;

            case 3:
            {
                // GATTサービス一覧を取得します。
                #region MjDeviceInformation.FindGattServicesAsync(0x180f)
                var servicesInfoResult = MjDeviceInformation.FindGattServicesAsync(0x180f);
                while (servicesInfoResult.Status == AsyncStatus.Started)
                {
                    System.Threading.Thread.Sleep(10);
                }
                servicesInfo = servicesInfoResult.GetResults();
                #endregion
            }
            break;

            case 4:
            {
                // GATTサービス一覧を取得します。
                #region MjDeviceInformation.FindGattServicesAsync(0x1809)
                var servicesInfoResult = MjDeviceInformation.FindGattServicesAsync(0x1809);
                while (servicesInfoResult.Status == AsyncStatus.Started)
                {
                    System.Threading.Thread.Sleep(10);
                }
                servicesInfo = servicesInfoResult.GetResults();
                #endregion
            }
            break;

            default:
                return;
            }

            // GATTサービスを選択します。
            for (int i = 0; i < servicesInfo.Count; i++)
            {
                var uuid       = MjGattDeviceService.UuidFromServiceInformation(servicesInfo[i]);
                var uuidString = MjGattDeviceService.ServiceSpecificationNameFromServiceUuid(uuid);
                Console.WriteLine("{0}. [{1}.{2}]", i + 1, servicesInfo[i].Name, uuidString);
            }
            Console.Write("Input: ");
            var serviceInfo = servicesInfo[int.Parse(Console.ReadLine()) - 1];
            Console.WriteLine();

            // GATTサービスインスタンスを取得します。
            var service = GattDeviceServiceFromId(serviceInfo.Id);

            // Battery Service?
            if (service.Uuid == GattDeviceService.ConvertShortIdToUuid(0x180f))
            {
                // Battery Level
                var characteristics = service.GetCharacteristics(GattDeviceService.ConvertShortIdToUuid(0x2a19));
                if ((characteristics[0].CharacteristicProperties & GattCharacteristicProperties.Notify) != 0)
                {
                    characteristics[0].ValueChanged += BatteryLevelChanged;
                    characteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);      // TODO
                }
            }
            // Health Thermometer Service?
            else if (service.Uuid == GattDeviceService.ConvertShortIdToUuid(0x1809))
            {
                // Temperature Measurement
                var characteristics = service.GetCharacteristics(GattDeviceService.ConvertShortIdToUuid(0x2a1c));

                if ((characteristics[0].CharacteristicProperties & GattCharacteristicProperties.Indicate) != 0)
                {
                    characteristics[0].ValueChanged += TemperatureMeasurementChanged;
                    characteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);    // TODO
                }
            }

            Console.WriteLine("Hit any key to Quit.");
            Console.WriteLine();
            Console.ReadKey();
        }