Example #1
0
            /// <summary>
            /// Returns a GATT characteristic for a sensor's data service.
            /// </summary>
            /// <param name="sensor">the sensor you want to read</param>
            /// <returns>the GATT characteristic</returns>
            static async Task <GattCharacteristic> GetCharacteristic(Sensor sensor)
            {
                //Get a query for devices with this service
                string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensor.GetServiceUUID()));

                //seek devices using the query
                var deviceCollection = await DeviceInformation.FindAllAsync(deviceSelector);

                //return info for the first device you find
                DeviceInformation device = deviceCollection.FirstOrDefault();

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

                // using the id get the service
                GattDeviceService service = await GattDeviceService.FromIdAsync(device.Id);

                //get all characteristics
                IReadOnlyList <GattCharacteristic> characteristics = service.GetCharacteristics(new Guid(sensor.GetDataUUID()));

                if (characteristics.Count == 0)
                {
                    throw new Exception("characteristic not found.");
                }

                //Reaturn event handler for first characteristic
                return(characteristics[0]);
            }
Example #2
0
        //
        // Summary:
        //      Initializes all the CRTP service and characteristic objects
        //      Uses the first of each that's found
        public async Task <Boolean> InitCrtpService()
        {
            var bthServices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(
                    crtpServiceGuid), null);

            // Use the first instance of this guid
            if (bthServices.Count >= 1)
            {
                crtpService = await GattDeviceService.FromIdAsync(bthServices[0].Id);

                if (crtpService != null)
                {
                    var chars = crtpService.GetCharacteristics(crtpCharacteristicGuid);
                    if (chars.Count >= 1)
                    {
                        crtpChar = chars[0];
                    }
                    var upChars = crtpService.GetCharacteristics(crtpUpCharacteristicGuid);
                    if (upChars.Count >= 1)
                    {
                        crtpUpChar = upChars[0];
                    }
                    var downChars = crtpService.GetCharacteristics(crtpDownCharacteristicGuid);
                    if (downChars.Count >= 1)
                    {
                        crtpDownChar = downChars[0];
                    }
                }
            }

            return((crtpService != null) && (crtpChar != null) && (crtpUpChar != null) && (crtpDownChar != null));
        }
Example #3
0
        private async void ReFreshDevicesList()
        {
            System.Diagnostics.Debug.WriteLine("FindAllAsync hearth : " + GattServiceUuids.HeartRate);
            System.Diagnostics.Debug.WriteLine("FindAllAsync hearth : " + GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));

            String findStuff = "System.DeviceInterface.Bluetooth.ServiceGuid:= \"{0000180D-0000-1000-8000-00805F9B34FB}\" AND System.Devices.InterfaceEnabled:= System.StructuredQueryType.Boolean#True";

            var devices = await DeviceInformation.FindAllAsync(findStuff);

            // this is the right way, stuff above is for debugging untill things works
            //  var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
            var items = new List <DeviceViewModel>();

            if (devices != null && devices.Count > 0)
            {
                System.Diagnostics.Debug.WriteLine("FindAllAsync devices.Count : " + devices.Count);
                foreach (DeviceInformation device in devices)
                {
                    if (device != null && device.Kind == DeviceInformationKind.DeviceInterface)
                    {
                        System.Diagnostics.Debug.WriteLine("Found : " + device.Name + ", id: " + device.Id);
                        items.Add(new DeviceViewModel(device));
                    }
                }
            }
            DeviceSelectionListView.ItemsSource = items;

            noDevicesLabel.Visibility          = items.Count > 0 ? Visibility.Collapsed : Visibility.Visible;
            DeviceSelectionListView.Visibility = items.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
        }
        private async void ReFreshDevicesList()
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
                var items   = new List <DeviceViewModel>();

                if (devices != null && devices.Count > 0)
                {
                    System.Diagnostics.Debug.WriteLine("FindAllAsync devices.Count : " + devices.Count);
                    foreach (DeviceInformation device in devices)
                    {
                        if (device != null)
                        {
                            System.Diagnostics.Debug.WriteLine("Found : " + device.Name + ", id: " + device.Id);
                            items.Add(new DeviceViewModel(device));
                        }
                    }
                }
                DeviceSelectionListView.ItemsSource = items;

                noDevicesLabel.Visibility          = items.Count > 0 ? Visibility.Collapsed : Visibility.Visible;
                DeviceSelectionListView.Visibility = items.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            });
        }
Example #5
0
        private void StartWatchers()
        {
            // aqsFilter = System.Devices.Aep.ProtocolId:="{bb7bb05e-5972-42b5-94fc-76eaa7084d49}"
            // association endpoint (AEP)
            string aqsFilter = "System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\"";

            deviceWatcher = DeviceInformation.CreateWatcher(
                aqsFilter,
                null, // don't request additional properties for this sample
                DeviceInformationKind.AssociationEndpoint);
            InitializeBtleWatcher(aqsFilter);
            deviceWatcher.Start();

            // Start the second watcher for the UP Band Stream Service: GATT_STREAM_SERVICE_UUID
            aqsFilter = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(UuidDefs.GATT_STREAM_SERVICE_UUID));
            _watcher2 = new BtleWatcher(this, "W2");
            _watcher2.InitializeBtleWatcher(aqsFilter);

            // Hook a function to the watcher events
            _watcher2.WacherEvent += Wacher2EventFired;

            //// Start the third watcher for the UP Band Control Service: JAWBONE_CONTROL_SERVICE_UUID
            //aqsFilter = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(UuidDefs.JAWBONE_CONTROL_SERVICE_UUID));
            //_watcher3 = new BtleWatcher(this, "W3");
            //_watcher3.InitializeBtleWatcher(aqsFilter);

            //// Start the third watcher for the UP Band Control Service: DEVICE_INFORMATION_SERVICE_UUID
            //aqsFilter = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(UuidDefs.DEVICE_INFORMATION_SERVICE_UUID));
            //_watcher4 = new BtleWatcher(this, "W4");
            //_watcher4.InitializeBtleWatcher(aqsFilter);

            //_rootPage.NotifyUser("Starting Watchers Done...", NotifyType.StatusMessage);

            //AppBarButtonStop.IsEnabled = true;
        }
Example #6
0
        private async Task <bool> GetHrAndBatteryDevice()
        {
            StatusInformation = "Start search for devices, HR";
            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));

            if (null == devices || devices.Count <= 0)
            {
                return(true);
            }
            foreach (var device in devices.Where(device => device.Name == "Polar H7 498C1817"))
            {
                _devicePolarHr     = device;
                StatusInformation2 = "Found hr device";
                break;
            }

            StatusInformation = "Start search for devices, Battery";
            devices           = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.Battery));

            if (null == devices || devices.Count <= 0)
            {
                return(true);
            }
            foreach (var device in devices.Where(device => device.Name == "Polar H7 498C1817"))
            {
                _devicePolarBattery = device;
                StatusInformation2  = "Found battery device";
                break;
            }
            StatusInformation = $"Found HR [{(_devicePolarHr != null)}] Battery [{(_devicePolarBattery != null)}]";
            return(_devicePolarHr != null && _devicePolarBattery != null);
        }
Example #7
0
        public void InitiateDefault()
        {
            var heartrateSelector = GattDeviceService
                                    .GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate);

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

            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 = GattDeviceService.FromIdAsync(device.Id)
                          .AsyncResult();

                _service = service;
            }

            if (service == null)
            {
                throw new ArgumentOutOfRangeException(
                          $"Unable to get service to {device.Name} ({device.Id}). Is the device inuse by another program? The Bluetooth adaptor may need to be turned off and on again.");
            }

            var heartrate = service
                            .GetCharacteristics(_heartRateMeasurementCharacteristicUuid)
                            .FirstOrDefault();

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

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

            heartrate.ValueChanged += HeartRate_ValueChanged;

            Debug.WriteLine($"Started {status}");
        }
Example #8
0
 async void Search_Clicked(object sender, EventArgs e)
 {
     foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(BluetoothUuidHelper.FromShortId(0xfff0))))
     {
         System.Diagnostics.Debug.WriteLine(di);
     }
 }
Example #9
0
        /// <summary>
        /// Search paired device
        /// </summary>
        private async void Init()
        {
            try
            {
                //Clear MyoList
                pairedMyos    = new List <MyoHw>();
                connectedMyos = new List <MyoHw>();
                //Search paired Myo
                devicesCollection = await DeviceInformation.FindAllAsync(
                    GattDeviceService.GetDeviceSelectorFromUuid(MYO_MAIN_UUID),
                    new string[] { "System.Devices.ContainerId" });

                if (devicesCollection.Count > 0)
                {
                    StartDeviceConnectionWatcher();
                    foreach (var device in devicesCollection)
                    {
                        pairedMyos.Add(new MyoHw(device));
                    }
                }
                else
                {
                    throw new Exception("No Myo Found, Please Pair Your Myo First");
                }
            }
            catch (Exception e)
            {
                throw(new Exception("Search Fail!" + e.Message));
            }
        }
Example #10
0
        private async void StartScanAsync()
        {
            if (false == this.scanning)
            {
                return;
            }

            var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(serviceUuid), new string[] { "System.Devices.ContainerId" });

            if (devices.Count > 0)
            {
                var remoteService = new RemoteService(devices[0]);

                remoteService.Disconnected += RemoteServiceDisconnected;
                remoteService.Connected    += RemoteServiceConnected;

                remoteService.Connect();
            }
            else
            {
                await Task.Delay(100);

                StartWatcher();
                StartScanAsync();
            }
        }
        /// <summary>
        /// Returns a GATT characteristic for a sensor's data service.
        /// </summary>
        /// <param name="sensor">the sensor you want to read</param>
        /// <returns>the GATT characteristic</returns>
        public static async Task <GattCharacteristic> GetCharacteristic(Sensor sensor, Attribute attribute)
        {
            //Get a query for devices with this service
            string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(sensor.GetUUID(Attribute.Service)));

            //seek devices using the query
            var deviceCollection = await DeviceInformation.FindAllAsync(deviceSelector);

            //return info for the first device you find
            DeviceInformation device = deviceCollection.FirstOrDefault();

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

            // use the id to get the service
            GattDeviceService service = await GattDeviceService.FromIdAsync(device.Id);

            //get matching characteristic
            IReadOnlyList <GattCharacteristic> characteristics = service.GetCharacteristics(new Guid(sensor.GetUUID(attribute)));

            if (characteristics.Count == 0)
            {
                throw new Exception("characteristic not found.");
            }

            //Return first characteristic in the list.
            return(characteristics[0]);
        }
        public void Stop()
        {
            if (this.DeviceWatcher == null)
            {
                // Request additional properties
                string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

                string serviceDeviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(this.ANCSUuid);
                this.DeviceWatcher = DeviceInformation.CreateWatcher(serviceDeviceSelector, requestedProperties);
            }

            if (this.DeviceWatcher != null)
            {
                // Unregister the event handlers.
                this.DeviceWatcher.Added   -= DeviceWatcher_Added;
                this.DeviceWatcher.Updated -= DeviceWatcher_Updated;
                this.DeviceWatcher.Removed -= DeviceWatcher_Removed;
                this.DeviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted;
                this.DeviceWatcher.Stopped -= DeviceWatcher_Stopped;

                // Stop the watcher.
                if (DeviceWatcher.Status == DeviceWatcherStatus.Started)
                {
                    this.DeviceWatcher.Stop();
                }
                DeviceWatcher = null;
            }

            // Clear the devices list
            Devices.Clear();
        }
Example #13
0
        public async Task <bool> Initialize(string serviceUuid)
        {
            string selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(serviceUuid));
            var    devices  = await DeviceInformation.FindAllAsync(selector, new string[] { "System.Devices.ContainerId" });

            var deviceInfo = devices[0];

            if (deviceInfo != null)
            {
                if (this.deviceService != null)
                {
                    Clean();
                }


                this.deviceService = await GattDeviceService.FromIdAsync(deviceInfo.Id);

                if (this.deviceService == null)
                {
                    return(false);
                }
                return(true);
            }
            return(false);
        }
Example #14
0
        private async void OHbtnSearch_Click(object sender, RoutedEventArgs e)
        {
            OHbtnSearch.IsEnabled = false;

            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate),
                new string[] { "System.Devices.ContainerId" });

            if (devices.Count > 0)
            {
                foreach (var device in devices)
                {
                    lstDevices.Items.Add(device);
                }
                lstDevices.Visibility = Visibility.Visible;
            }
            else
            {
                var dialog = new MessageDialog("Could not find any Heart Rate devices. Please make sure your device is paired and powered on!");
                await dialog.ShowAsync();
            }


            OHbtnSearch.IsEnabled = true;
        }
Example #15
0
        private async void FindPolarHrDevices()
        {
            if (_lastBpm != null)
            {
                var dif = DateTime.Now - _lastBpm.Time;
                if (dif.Seconds > 3)
                {
                    SuscribeToReadBpmValues();
                }
            }
            if (_devicePolarHr != null)
            {
                return;
            }
            StatusInformation = $"Searching ...";
            var devices =
                await
                DeviceInformation.FindAllAsync(
                    GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));

            if (null == devices || devices.Count <= 0)
            {
                return;
            }
            foreach (var device in devices.Where(device => device.Name.Contains("Polar H7")))
            {
                _devicePolarHr    = device;
                StatusInformation = $"Polar HR [{_devicePolarHr.Name}], connect to Heart service ...";
                Debug.WriteLine(_devicePolarHr.Id);
                break;
            }
        }
        /// <summary>
        /// Finds connected Bluetooth device with the service GUID.
        /// </summary>
        /// <exception cref="System.TimeoutException">
        /// Could not find connected IrDA bridge within timeout.
        /// </exception>
        /// <returns></returns>
        public async void InitializeTranciever()
        {
            device = (await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(serviceGuid)))[0];
            if (device != null)
            {
                GattCommunicationStatus status;

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

                commandData            = service.GetCharacteristics(new Guid("d40c53c0-4462-4714-99cc-f90772bd7f61"))[0];
                respData               = service.GetCharacteristics(new Guid("54d8deac-1c1d-4841-947f-ac4406f3034e"))[0];
                error                  = service.GetCharacteristics(new Guid("c29a164e-9406-4d81-800b-29efcb447933"))[0];
                respData.ValueChanged += Characteristic_ValueChanged;
                error.ValueChanged    += Characteristic_ValueChanged;

                status = await respData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                status = await error.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                if (status == GattCommunicationStatus.Success)
                {
                    DeviceInitialized();
                }
                else
                {
                    DeviceNotInitialied();
                }
            }
        }
Example #17
0
        private void StartDeviceWatcher()
        {
            this.RefreshButton.Enabled = false;
            this.RefreshButton.Text    = "Stop";

            // Additional properties we would like about the device.
            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

            string serviceDeviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(this.ANCSUuid);

            this.DeviceWatcher = DeviceInformation.CreateWatcher(serviceDeviceSelector, requestedProperties);

            // Register event handlers before starting the watcher.
            this.DeviceWatcher.Added += DeviceWatcher_Added;
            this.DeviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
            this.DeviceWatcher.Stopped += DeviceWatcher_Stopped;
            //deviceWatcher.Added += DeviceWatcher_Added;
            //deviceWatcher.Updated += DeviceWatcher_Updated;
            //deviceWatcher.Removed += DeviceWatcher_Removed;
            //deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
            //deviceWatcher.Stopped += DeviceWatcher_Stopped;

            // Clear the devices list view
            this.DevicesListView.BeginUpdate();
            this.DevicesListView.Clear();
            this.DevicesListView.EndUpdate();

            // Start listening
            this.DeviceWatcher.Start();

            // Enable the button
            this.RefreshButton.Enabled = true;
        }
Example #18
0
        private async void StartGattServiceWatcher(DeviceInformation deviceInfoDisp)
        {
            //Get the Bluetooth address for filtering the watcher
            var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfoDisp.Id);

            var selector = "(" + GattDeviceService.GetDeviceSelectorFromUuid(IoServiceUuid) + ")"
                           + " AND (System.DeviceInterface.Bluetooth.DeviceAddress:=\""
                           + bleDevice.BluetoothAddress.ToString("X") + "\")";

            gattServiceWatcher = DeviceInformation.CreateWatcher(selector);

            // Hook up handlers for the watcher events before starting the watcher
            gattServiceWatcher.Added += async(watcher, deviceInfo) =>
            {
                weDoIoService = await GattDeviceService.FromIdAsync(deviceInfo.Id);

                outputCommandCharacteristic = weDoIoService.GetCharacteristics(OutputCommandCharacteristicGuid)[0];
            };

            //gattServiceWatcher.Updated += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => );

            //gattServiceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => );

            //gattServiceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) => );

            //gattServiceWatcher.Stopped += new TypedEventHandler<DeviceWatcher, Object>(async (watcher, obj) => );

            gattServiceWatcher.Start();
        }
    //~HRGATTConnect()
    //{
    //    Dispose(false);
    //}
    public async void Initialize()
    {
        try
        {
            var heartrateServices = await Windows.Devices.Enumeration
                                    .DeviceInformation.FindAllAsync(GattDeviceService
                                                                    .GetDeviceSelectorFromUuid(
                                                                        GattServiceUuids.HeartRate),
                                                                    null);

            firstHeartRateMonitorService = await
                                           GattDeviceService.FromIdAsync(heartrateServices[0].Id);

            Debug.WriteLine("serviceName:  " + heartrateServices[0].Name);

            hrMonitorCharacteristics =
                firstHeartRateMonitorService.GetCharacteristics(
                    GattCharacteristicUuids.HeartRateMeasurement)[0];

            hrMonitorCharacteristics.ValueChanged += hrMeasurementChanged;

            await hrMonitorCharacteristics
            .WriteClientCharacteristicConfigurationDescriptorAsync(
                GattClientCharacteristicConfigurationDescriptorValue.Notify);

            disposed = false;
        }
        catch (Exception e)
        {
        }
    }
Example #20
0
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.Battery)))
     {
         Devices.Add(di);
     }
 }
Example #21
0
        public async Task <bool> UpdateAvailableDevice()
        {
            DeviceSelectionViewModel.ClearCachedDevices();
            try
            {
                DeviceSelectionViewModel.ClearCachedDevices();
                var result = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));

                if (result.Count > 0)
                {
                    foreach (var device in result)
                    {
                        var ble = await BluetoothLEDevice.FromIdAsync(device.Id) as BluetoothLEDevice;

                        DeviceSelectionViewModel.AddBLEDevice(ble);
                    }
                }
                else
                {
                    if (!await DeviceSelectionViewModel.IsBluetoothSettingOn())
                    {
                        ShowErrorMessage();
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #22
0
        private static async void PrintService(Guid serviceGuid, int indent)
        {
            try
            {
                DebugLine("BT LE SERVICE LOOKUP", indent);
                var device = await BluetoothLEDevice.FromIdAsync(serviceGuid.ToString());

                Print(device, indent + 1);
            }
            catch
            {
                DebugLine("Failure getting device from service id.", indent);
            }

            try
            {
                DebugLine("DEVICE INFORMATION GATT SERVICE LOOKUP", indent);
                var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(serviceGuid));

                DebugLine($"Found Devices: {devices.Count}", indent);
                foreach (var device in devices)
                {
                    Print(device, indent + 1);
                }
            }
            catch
            {
                DebugLine("Failure getting device from service id.", indent);
            }
        }
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            RunButton.IsEnabled = false;

            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate),
                new string[] { "System.Devices.ContainerId" });

            DevicesListBox.Items.Clear();

            if (devices.Count > 0)
            {
                foreach (var device in devices)
                {
                    DevicesListBox.Items.Add(device);
                }
                DevicesListBox.Visibility = Visibility.Visible;
            }
            else
            {
                rootPage.NotifyUser("Could not find any Heart Rate devices. Please make sure your device is paired " +
                                    "and powered on!",
                                    NotifyType.StatusMessage);
            }
            RunButton.IsEnabled = true;
        }
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            RunButton.IsEnabled = false;

            //var devices = await DeviceInformation.FindAllAsync();


            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(UARTService.Instance.SERVICE_UUID),
                new string[] { "System.Devices.ContainerId" });

            DevicesListBox.Items.Clear();

            if (devices.Count > 0)
            {
                foreach (var device in devices)
                {
                    DevicesListBox.Items.Add(device);
                }
                DevicesListBox.Visibility = Visibility.Visible;
            }
            else
            {
                statusTextBlock.Text = "No Devices with UART Service Found!";
            }
            RunButton.IsEnabled = true;
        }
Example #25
0
        private void StartBLEWatcher()
        {
            string aqs = "";

            for (int i = 0; i < NUM_SENSORS; i++)
            {
                Guid BLE_GUID;
                if (i < 6)
                {
                    BLE_GUID = new Guid(SENSOR_GUID_PREFIX + i + SENSOR_GUID_SUFFFIX);
                }
                else
                {
                    BLE_GUID = BUTTONS_GUID;
                }

                aqs += "(" + GattDeviceService.GetDeviceSelectorFromUuid(BLE_GUID) + ")";

                if (i < NUM_SENSORS - 1)
                {
                    aqs += " OR ";
                }
            }

            blewatcher          = DeviceInformation.CreateWatcher(aqs);
            blewatcher.Added   += OnBLEAdded;
            blewatcher.Updated += OnBLEUpdated;
            blewatcher.Removed += OnBLERemoved;
            blewatcher.Stopped += OnBLEStopped;
            blewatcher.Start();
        }
Example #26
0
        private async void ButtonConnect_Click(object sender, RoutedEventArgs e)
        {
            // SensorTagを取得
            var selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(SensorTagUuid.UuidIrtService));
            var devices  = await DeviceInformation.FindAllAsync(selector);


            var deviceInformation = devices.FirstOrDefault();

            if (deviceInformation == null)
            {
                //MessageBox.Show("not found");
                return;
            }


            this.GattDeviceService = await GattDeviceService.FromIdAsync(deviceInformation.Id);

            //MessageBox.Show($"found {deviceInformation.Id}");

            // センサーの有効化?
            var configCharacteristic = this.GattDeviceService.GetCharacteristics(new Guid(SensorTagUuid.UuidIrtConf)).First();
            var status = await configCharacteristic.WriteValueAsync(new byte[] { 1 }.AsBuffer());

            if (status == GattCommunicationStatus.Unreachable)
            {
                //MessageBox.Show("Initialize failed");
                return;
            }
        }
        private async void StartGattServiceWatcher()
        {
            //Get the Bluetooth address for filtering the watcher
            BluetoothLEDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as BluetoothLEDeviceDisplay;
            BluetoothLEDevice        bleDevice      = await BluetoothLEDevice.FromIdAsync(deviceInfoDisp.Id);

            string selector = "(" + GattDeviceService.GetDeviceSelectorFromUuid(IoServiceUuid) + ")"
                              + " AND (System.DeviceInterface.Bluetooth.DeviceAddress:=\""
                              + bleDevice.BluetoothAddress.ToString("X") + "\")";

            gattServiceWatcher = DeviceInformation.CreateWatcher(selector);

            // Hook up handlers for the watcher events before starting the watcher
            gattServiceWatcher.Added += new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // If the selected device is a WeDo device, enable the controls
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    weDoIoService = await GattDeviceService.FromIdAsync(deviceInfo.Id);
                    outputCommandCharacteristic = weDoIoService.GetCharacteristics(OutputCommandCharacteristicGuid)[0];
                    ForwardButton.IsEnabled     = true;
                    StopButton.IsEnabled        = true;
                    BackwardButton.IsEnabled    = true;
                });
            });

            gattServiceWatcher.Updated += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //Do nothing
                });
            });

            gattServiceWatcher.EnumerationCompleted += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //Do nothing
                });
            });

            gattServiceWatcher.Removed += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //Do nothing
                });
            });

            gattServiceWatcher.Stopped += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //Do nothing
                });
            });

            gattServiceWatcher.Start();
        }
        public async Task <bool> Connect()
        {
            //Find a device that is advertising the ancs service uuid
            var serviceDeviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(_ancsServiceUiid);
            var devices = await DeviceInformation.FindAllAsync(serviceDeviceSelector, null);

            // sanity check
            if (devices.Count == 0)
            {
                return(false);
            }

            try
            {
                this.AncsDevice = devices.First();

                //Resolve the service
                this.AncsService = await GattDeviceService.FromIdAsync(this.AncsDevice.Id);

                this.AncsService.Device.ConnectionStatusChanged += DeviceOnConnectionStatusChanged;

                //Get charasteristics of service
                this.NotificationSourceCharacteristic = this.AncsService.GetCharacteristics(_notificationSourceCharacteristicUuid).First();
                this.ControlPointCharacteristic       = this.AncsService.GetCharacteristics(_controlPointCharacteristicUuid).First();
                this.DataSourceCharacteristic         = this.AncsService.GetCharacteristics(_dataSourceCharacteristicUuid).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(true);
        }
        /* Method */
        public async void InitializeDevice()
        {
            /*** Get a list of devices that match desired service UUID  ***/
            Guid selectedService = new Guid("0000AA10-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

            Console.WriteLine("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);

            Console.WriteLine("Service UUID: {0}", myService.Uuid.ToString());

            /*** Create an instance of the characteristic of the specified service ***/
            Guid               selectedCharacteristic = new Guid("0000AA11-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"

            /*** Create an event handler when the characteristic value changes ***/
            myCharacteristic.ValueChanged -= myCharacteristic_ValueChanged;
            GattCommunicationStatus disableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

            Console.WriteLine("Disable Notification Status: {0}", disableNotifStatus);

            myCharacteristic.ValueChanged += myCharacteristic_ValueChanged;
            GattCommunicationStatus enableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            Console.WriteLine("Enable Notification Status: {0}", disableNotifStatus);
        }//end method InitializeDevice
 public GATTDefaultService(string description, Guid uuid)
 {
     this.Description = description;
     this.UUID        = uuid;
     this.Filter      = GattDeviceService.GetDeviceSelectorFromUuid(uuid);
     lookup.Add(this.UUID, this);
 }