public async void InitializeServiceAsync(string deviceId, Guid characteristicUuid)
        {
            try
            {
                Deinitialize();

                _service = await GattDeviceService.FromIdAsync(deviceId);
                if (_service != null)
                {
                    _characteristic = _service.GetCharacteristics(characteristicUuid)[0];
                    if (DeviceConnectionUpdated != null && (_service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected))
                    {
                        DeviceConnectionUpdated(true, null);
                    }
                    _service.Device.ConnectionStatusChanged += OnConnectionStatusChanged;
                }
                else if (DeviceConnectionUpdated != null)
                {
                    DeviceConnectionUpdated(false, "No services found from the selected device");
                }
            }
            catch (Exception e)
            {
                if (DeviceConnectionUpdated != null)
                {
                    DeviceConnectionUpdated(false, "Accessing device failed: " + e.Message);
                }
            }
        }
Example #2
0
        public async void SendTestData(List<DeviceInformation> parrotDevices)
        {
            DeviceInformation motorDevice = null;
            foreach (var device in parrotDevices)
            {
                Debug.WriteLine("device " + device.Id);

                // get device service
                _service = await GattDeviceService.FromIdAsync(device.Id);
                if (null == _service) return;

                try
                {

                //var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors);
                var characteristics = _service.GetAllCharacteristics();
                TakeOff(characteristics);
                var res = await Motors(false, 0, 0, 0, 0, 0.0f, 18, characteristics);
                if (!res) continue;
                res = await Motors(true, 0, 100, 0, 0, 0.0f, 6, characteristics);
                if (res) continue;
                EmergencyStop(characteristics);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception);
                }
            }

        }
		public void Dispose()
		{
			if (service_ != null)
			{
				service_.Dispose();
				service_ = null;
			}
		}
		public async Task<bool> Start(GattDeviceService batteryService)
		{
			if (batteryService == null || batteryService.Uuid != GattServiceUuids.Battery)
				return IsServiceStarted = false;
			DeviceBatteryService = batteryService;
			await SetBatterylevelCharacteristics();
			return IsServiceStarted = true;
		}
		public async Task<bool> Start(GattDeviceService bloodPressureService)
		{
			if (bloodPressureService == null || bloodPressureService.Uuid != GattServiceUuids.BloodPressure)
				return IsServiceStarted = false;
			this.BloodPressureDeviceService = bloodPressureService;
			await EnableBloodPressureMeasurementIndication();
			return IsServiceStarted = true;
		}
		public async Task<bool> Start(GattDeviceService glucoseService) 
		{
			if (glucoseService == null || glucoseService.Uuid != GattServiceUuids.Glucose)
				return IsServiceStarted = false;
			this.glucoseService = glucoseService;
			await EnableGlucoseMeasurementNotification();
			await EnableRecordAccessControlPointIndication();
			return IsServiceStarted = true;
		}
Example #7
0
        public virtual async Task<InitResult> Init()
        {
            // On recherche un device supportant le service du sensor
            // Si le device trouvé est un SensorTag on retourne le service
            // Sinon on retourne null

            var deviceService = await GetDeviceService(pServiceUUID);

            if (deviceService == null)
            {
                // Aucun SensorTag ne supporte ce service

                return InitResult.DeviceNotFound;
            }

#if WINDOWS_PHONE_APP

            if (deviceService.Device.ConnectionStatus == Windows.Devices.Bluetooth.BluetoothConnectionStatus.Disconnected)
            {
                // SensorTag déconnecté
                return InitResult.DeviceDisconnected;
            }
#endif

            // On stocke le DeviceService

            pDeviceService = deviceService;

            // On a le DeviceService, on peut maintenant se brancher sur les caractéristiques
            // Configuration et Data

            var configCharacteristic = GetCharacteristic(pDeviceService, pConfigurationUUID);

            if (configCharacteristic == null)
            {
                return InitResult.DeviceNotFound;
            }

            var dataCharacteristic = GetCharacteristic(pDeviceService, pDataUUID);

            if (dataCharacteristic == null)
            {
                return InitResult.DeviceNotFound;
            }

            // On peut stocker les caractéristiques trouvées

            pConfigurationCharacteristic = configCharacteristic;
            pDataCharacteristic = dataCharacteristic;

            // On peut se brancher sur l'événement de changement de valeur des données

            await pDataCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
            pDataCharacteristic.ValueChanged += pDataCharacteristic_ValueChanged;

            return InitResult.Ok;
        }
        public async Task<string> GetSensorID(GattDeviceService deviceService)
        {
            Exception exc = null;
            string SensorData = "";

            try
            {
                

                using (this._deviceInfoService)
                 {
                    //await this._deviceInfoService.Initialize();
                                        
                    //foreach (GattDeviceService deviceService in _deviceInfoService.deviceServices)
                    //{
                    _deviceInfoService.deviceService = deviceService;

                    // read these values so that I can save them
                    _sensorSystemID = await _deviceInfoService.ReadSystemId();
                    string _serialNumber = await _deviceInfoService.ReadSerialNumber();
                    if (_sensorSystemID == SensorIDMappings.Left_Front) _sensorFriendlyName = "Left Front";
                    if (_sensorSystemID == SensorIDMappings.Right_Front) _sensorFriendlyName = "Right Front";
                    if (_sensorSystemID == SensorIDMappings.Left_Hind) _sensorFriendlyName = "Left Hind";
                    if (_sensorSystemID == SensorIDMappings.Right_Hind) _sensorFriendlyName = "Right Hind";

                    SensorData += "Sensor: " + _sensorFriendlyName + "(" + _sensorSystemID + ")\n";
                    //SensorData += "Model Nr: " + await _deviceInfoService.ReadModelNumber() + "\n";
                    //SensorData += "Serial Nr: " + _serialNumber + "\n";
                    SensorData += "Firmware: " + await _deviceInfoService.ReadFirmwareRevision() + "Hardware: " + await _deviceInfoService.ReadHardwareRevision() + "\n";
                    //SensorData += "Sofware Revision: " + await _deviceInfoService.ReadSoftwareRevision() + "\n";
                    //SensorData += "Manufacturer Name: " + await _deviceInfoService.ReadManufacturerName() + "\n";
                    //SensorData += "Cert: " + await _deviceInfoService.ReadCert() + "\n";
                    //SensorData += "PNP ID: " + await _deviceInfoService.ReadPnpId();
                    SensorData += "\n";

                    // save the friendly name and the system id
                    CurrentValues.SensorFriendlyName = _sensorFriendlyName;
                    CurrentValues.SensorSystemID = _sensorSystemID;
                    CurrentValues.DeviceInfoService = _deviceInfoService;
                    CurrentValues.IOService = _ioService;
                
                    }
                    
                //}

                return SensorData;
            }
            catch (Exception ex)
            {
                exc = ex;
            }

            if (exc != null)
                SensorData += exc.Message;

            return SensorData;
        }
		public async Task<bool> Start(GattDeviceService immediateDeviceService)
		{
			if (immediateDeviceService != null && immediateDeviceService.Uuid != GattServiceUuids.ImmediateAlert)
				 return IsServiceStarted = false;
			else
			{
				this.immediateDeviceService = immediateDeviceService;
				return IsServiceStarted = true;
			}
		}
        public void Deinitialize()
        {
            _characteristic = null;

            if (_service != null)
            {
                _service.Device.ConnectionStatusChanged -= OnConnectionStatusChanged;
                _service = null;
            }
        }
 /// <summary>
 /// Retrieves the sensor device and saves it for further usage.
 /// 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>Indicates if the gatt service could be retrieved and set successfully</returns>
 /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which matches the sensor service id.</exception>
 public async Task<bool> Initialize()
 {
     if (this.deviceService != null)
     {
         Clean();
     }
     this.deviceService = await GattUtils.GetDeviceService(SensorTagUuid.UUID_INF_SERV);
     if (this.deviceService == null)
         return false;
     return true;
 }
Example #12
0
 public async Task<bool> Initialize()
 {
     if (this.deviceService != null)
     {
         Clean();
     }
     this.deviceService = await getDeviceService();
     if (this.deviceService == null)
         return false;
     return true;
 }
		public async Task<bool> Start(GattDeviceService linkLossDeviceService)
		{
			if (linkLossDeviceService != null && linkLossDeviceService.Uuid != GattServiceUuids.LinkLoss)
				 return IsServiceStarted = false;
			this.linkLossDeviceService = linkLossDeviceService;
			var result = await RegisterDeviceServiceAsBackgroundTask(linkLossDeviceService);
			alertLevel = linkLossDeviceService.GetCharacteristics(GattCharacteristicUuids.AlertLevel).FirstOrDefault();
			if (result != null)
				return IsServiceStarted = true;
			else
				return IsServiceStarted = false;
		}
Example #14
0
        public bool Disconnect()
        {
            if (GattService != null)
            {
                GattService.Dispose();
                GattService = null;
            }

            Characteristics = null;
            ServiceUuid     = Guid.Empty;
            BleDevice       = null;

            return(true);
        }
Example #15
0
        public BluetoothLEDevice Get(Guid serviceUuid)
        {
            // Uuid = serviceUuidのデバイスをサーチ
            string selector = "(" + GattDeviceService.GetDeviceSelectorFromUuid(serviceUuid) + ")";

            dw        = DeviceInformation.CreateWatcher(selector);
            dw.Added += Watcher_DeviceAdded;
            dw.Start();
            Debug.WriteLine("scan start");

            condition.Wait();

            return(this.bleDevice);
        }
        public async Task SetDesiredLedStatusAsync(GattDeviceService service, bool ledStatus)
        {
            Debug.WriteLine("Setting desired LED status: %d.", ledStatus);
            currentService = service;

            // Set the desired LED status
            deviceControlGetDesiredLedStatusResponse = new DeviceControlGetDesiredLedStatusResponse(ledStatus);

            // Set desired LED status request notification
            bluetoothLeHelper.NotificationReceived += DeviceControlGetDesiredLedStatusRequest_NotificationReceived;
            await bluetoothLeHelper.StartNotificationListenerAsync(service, MessageProtocolTxCharacteristicId);

            await SendEventMessageAsync(service, CategoryIdType.DeviceControl, (ushort)DeviceControlEventId.DesiredLedStatusAvailable);
        }
Example #17
0
        public static void SetUpBattery(GattDeviceService service)
        {
            DeviceBatteryService = service;
            var DeviceBatteryLevelCharacteristicList = DeviceBatteryService.GetCharacteristics(new Guid(DEVICE_BATTERY_LEVEL));

            DeviceBatteryLevelCharacteristic = null;
            if (DeviceBatteryLevelCharacteristicList != null)
            {
                if (DeviceBatteryLevelCharacteristicList.Count() > 0)
                {
                    DeviceBatteryLevelCharacteristic = DeviceBatteryLevelCharacteristicList[0];
                }
            }
        }
Example #18
0
        private async void AchieveCharateristic(GattDeviceService service)
        {
            var result = await service.GetCharacteristicsAsync();

            var characteristics = result.Characteristics;

            _ListCharacteristics = new ObservableCollection <GattCharacteristicModel>();
            foreach (var characteristic in characteristics)
            {
                Debug.WriteLine(characteristic.Service.Uuid + ": " + characteristic.Uuid);
                _ListCharacteristics.Add(new GattCharacteristicModel(characteristic));
            }
            lvBTDevice.ItemsSource = _ListCharacteristics;
        }
        /// <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));
        }
Example #20
0
        /// <summary>
        /// Gets the characteristic.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="guid">The unique identifier.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private static async Task <GattCharacteristic> GetCharacteristic(GattDeviceService service, Guid guid)
        {
            var result = await service.GetCharacteristicsForUuidAsync(guid);

            if (result.Status != GattCommunicationStatus.Success)
            {
                throw new Exception("Connection error: " + result.Status.ToString());
            }
            if (result.Characteristics.Count == 0)
            {
                throw new Exception("Characteristic is not found");
            }
            return(result.Characteristics[0]);
        }
Example #21
0
        public static async Task <DeviceInformation[]> FindAllAsync(CancellationToken cancellationToken)
        {
            var selector   = GattDeviceService.GetDeviceSelectorFromUuid(ServiceUuid);
            var collection = await DeviceInformation.FindAllAsync(selector, new[] { ContainerIdProperty }).AsTask(cancellationToken);

            var tasks = collection
                        .Select(service => (string)service.Properties[ContainerIdProperty])
                        .Distinct()
                        .Select(deviceId => Windows.Devices.Enumeration.DeviceInformation.CreateFromIdAsync(deviceId).AsTask(cancellationToken))
                        .ToArray();
            await Task.WhenAll(tasks);

            return(tasks.Select(task => task.Result).ToArray());
        }
Example #22
0
        public async Task <List <MWBoard> > GetConnectedMWBoards()
        {
            var devices = new List <MWBoard>();

            foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(
                         GattDeviceService.GetDeviceSelectorFromUuid(MW_UUID),
                         new string[] { "System.Devices.ContainerId" }))

            {
                devices.Add(new MWBoard(di.Id, di.Name));
            }

            return(devices);
        }
Example #23
0
        public async Task <bool> Initialize()
        {
            if (this.deviceService != null)
            {
                Clean();
            }
            this.deviceService = await getDeviceService();

            if (this.deviceService == null)
            {
                return(false);
            }
            return(true);
        }
        public async Task AddWifiNetworkAsync(GattDeviceService service, byte[] ssid, SecurityType securityType, string psk)
        {
            Debug.WriteLine("Adding new Wi-Fi network.");
            currentService = service;

            // Set the details of the new Wi-Fi network
            wifiGetNewDetailsResponse = new WifiGetNewDetailsResponse(ssid, securityType, psk);

            // Set new Wi-Fi network
            bluetoothLeHelper.NotificationReceived += WifiGetNewDetailsRequest_NotificationReceived;
            await bluetoothLeHelper.StartNotificationListenerAsync(service, MessageProtocolTxCharacteristicId);

            await SendEventMessageAsync(service, WifiEventId.NewWifiDetailsAvailable);
        }
        private async void ListCharactericsButton_Click(object sender, RoutedEventArgs e)
        {
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => listView.Items.Clear());

            service = ((GattDeviceServiceListItem)selectedListItem).service;
            var characteristics = await service.GetCharacteristicsAsync();

            foreach (GattCharacteristic characteristic in characteristics.Characteristics)
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => listView.Items.Add(new GattCharacteristicListItem(characteristic)));

                Debug.WriteLine($"Characteristic UUID: {characteristic.Uuid}");
            }
        }
Example #26
0
        /// <summary>
        /// Bind the inquired GattDeviceService to send and receive data to and from the pen.
        /// (It is not used unless it is a special case.)
        /// </summary>
        /// <param name="gattDeviceServices">GattDeviceService found</param>
        /// <returns>True on success false on failure</returns>
        public async Task <bool> Bind(IReadOnlyList <GattDeviceService> gattDeviceServices)
        {
            Debug.WriteLine("Bind Try");
            try
            {
                foreach (var gds in gattDeviceServices)
                {
                    if (gds.Uuid.Equals(OldServiceUuidV2) || gds.Uuid.Equals(ServiceUuidV2))
                    {
                        gattDeviceService = gds;
                        mtuSize           = gattDeviceService.Session.MaxPduSize;
                        var result = await gds.GetCharacteristicsAsync();

                        if (result.Status == GattCommunicationStatus.Success)
                        {
                            var characteristics = result.Characteristics;

                            await InitCharacteristics(characteristics);

                            if (writeCharacteristic != null && indicateCharacteristic != null)
                            {
                                writeTask = Task.Run(GattSendDataTask);
                                PenController.PenClient = this;
                                PenController.Protocol  = Protocols.V2;
                                PenController.OnConnected();
                                return(true);
                            }
                            else
                            {
                                // TODO error
                                Debug.WriteLine("Bind cannot init Characteristics");
                            }
                        }
                        else
                        {
                            // todo error
                            Debug.WriteLine("Bind GattCommunicationStatus is not Success");
                        }

                        break;
                    }
                }
                return(false);
            }
            catch (Exception exp)
            {
                Debug.WriteLine("Bind Exception occured : " + exp.Message);
                return(false);
            }
        }
        private async static Task <GattDeviceService> waitConnection(AnkiBLE.anki_vehicle vehicle)
        {
            BluetoothLEDevice bluetoothLeDevice = null;
            GattDeviceService service           = null;

            bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address);

            while (bluetoothLeDevice.ConnectionStatus != BluetoothConnectionStatus.Connected)
            {
                throw new Exception("Not connected!");
            }
            service = bluetoothLeDevice.GetGattService(Guid.Parse("be15beef-6186-407e-8381-0bd89c4d8df4"));
            return(service);
        }
Example #28
0
        private async Task <IReadOnlyList <GattCharacteristic> > GetCharacteristics(GattDeviceService service)
        {
            if (service != null)
            {
                var characteristicsResult = await service.GetCharacteristicsAsync();

                if (characteristicsResult.Status == GattCommunicationStatus.Success)
                {
                    return(characteristicsResult.Characteristics);
                }
            }

            return(null);
        }
        /// <summary>
        /// Retrieves the sensor device and saves it for further usage.
        /// 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>Indicates if the gatt service could be retrieved and set successfully</returns>
        /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which matches the sensor service id.</exception>
        public async Task <bool> Initialize()
        {
            if (this.deviceService != null)
            {
                Clean();
            }
            this.deviceService = await GattUtils.GetDeviceService(SensorTagUuid.UUID_INF_SERV);

            if (this.deviceService == null)
            {
                return(false);
            }
            return(true);
        }
Example #30
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}");
        }
Example #31
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 static async Task <BLETISensor> Sensor(SensorTag sensorType)
        {
            string selector = null;

            switch (sensorType)
            {
            case SensorTag.CC2541:
                sensor            = new CC2541.CC2541Sensor();
                sensor.tagService = await Initialize(CC2541.SensorTagUuid.UUID_INF_SERV);

                if (sensor.tagService == null)
                {
                    sensor.ConnectionStatus = "Need Pairing";
                    throw new Exception("Need to make CC2541 Pairing before start!");
                }
                sensor.ManifactureName = await sensor.ReadCharacteristicStringAsync(CC2541.SensorTagUuid.UUID_INF_MANUF_NR);

                sensor.FirmwareRevision = await sensor.ReadCharacteristicStringAsync(CC2541.SensorTagUuid.UUID_INF_FW_NR);

                selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(CC2541.SensorTagUuid.UUID_INF_SERV));
                Debug.WriteLine("CC2541:" + sensor.ManifactureName + "," + sensor.FirmwareRevision);
                break;

            case SensorTag.CC2650:
                sensor            = new CC2650.CC2650Sensor();
                sensor.tagService = await Initialize(CC2650.SensorTagUuid.UUID_INF_SERV);

                if (sensor.tagService == null)
                {
                    sensor.ConnectionStatus = "Need Pairing";
                    throw new Exception("Need to make CC2650 Pairing before start!");
                }
                sensor.ManifactureName = await sensor.ReadCharacteristicStringAsync(CC2650.SensorTagUuid.UUID_INF_MANUF_NR);

                sensor.FirmwareRevision = await sensor.ReadCharacteristicStringAsync(CC2650.SensorTagUuid.UUID_INF_FW_NR);

                selector = GattDeviceService.GetDeviceSelectorFromUuid(new Guid(CC2650.SensorTagUuid.UUID_INF_SERV));
                Debug.WriteLine("CC2650:" + sensor.ManifactureName + "," + sensor.FirmwareRevision);
                break;
            }
            sensor.ConnectionStatus = "Waiting to connect...";
            Debug.WriteLine(sensor.ConnectionStatus);

            sensor.deviceNameValue = await ReadDeviceNameAsync(selector);

            sensor.systemIdValue = await ReadDeviceIdAsync(selector);

            return(sensor);
        }
        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);
        }
        public async Task setupInternal(string deviceName)
        {
            try
            {
                DeviceInformation deviceInfo = null;

                var devices = await DeviceInformation.FindAllAsync
                              (
                    GattDeviceService.GetDeviceSelectorFromUuid(new Guid("0000180A-0000-1000-8000-00805F9B34FB")), // Device Information Service
                    new string[] { "System.Devices.ContainerId" }
                              );

                if (devices.Count > 0)
                {
                    foreach (var device in devices)
                    {
                        if (device.Name.Equals(deviceName))
                        {
                            deviceInfo = device;
                            break;
                        }
                    }
                }
                else
                {
                    throw new Exception("Could not find any devices. Please make sure your device is paired and powered on!");
                }

                // Check if the device is initially connected, and display the appropriate message to the user
                var deviceObject = await PnpObject.CreateFromIdAsync
                                   (
                    PnpObjectType.DeviceContainer,
                    deviceInfo.Properties["System.Devices.ContainerId"].ToString(),
                    new string[] { "System.Devices.Connected" }
                                   );

                bool isConnected;
                Boolean.TryParse(deviceObject.Properties["System.Devices.Connected"].ToString(), out isConnected);

                if (isConnected)
                {
                    await InitializeServiceAsync(deviceInfo);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Retrieving device properties failed with message: " + e.Message);
            }
        }
Example #35
0
        private static async void GetCharacteristics(GattDeviceService service)
        {
            IReadOnlyList <GattCharacteristic> characteristics = null;
            string device = service.Device.DeviceInformation.Id.Substring(41);

            try
            {
                DeviceAccessStatus accessStatus = await service.RequestAccessAsync();

                if (accessStatus == DeviceAccessStatus.Allowed)
                {
                    GattCharacteristicsResult result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        characteristics = result.Characteristics;
                        Console.WriteLine("Found Characteristics");
                    }
                    else
                    {
                        blePowermates[device].isSubscribing = false;
                        Console.WriteLine("Error accessing service.");
                        characteristics = new List <GattCharacteristic>();
                    }
                }
                else
                {
                    blePowermates[device].isSubscribing = false;
                    Console.WriteLine("Error accessing service.");
                }
            } catch (Exception ex)
            {
                blePowermates[device].isSubscribing = false;
                Console.WriteLine("Error: Restricted service. Can't read characteristics: " + ex.ToString());
            }

            if (characteristics != null)
            {
                foreach (GattCharacteristic characteristic in characteristics)
                {
                    Console.WriteLine("└Characteristic uuid: " + characteristic.Uuid.ToString());
                    if (UuidEquals(uuidRead, characteristic.Uuid))
                    {
                        SubscribeToValueChange(characteristic);
                        Console.WriteLine(" └Subscribing to Read Characteristic");
                    }
                }
            }
        }
        private async Task <bool> FindService()
        {
            foreach (GattDeviceService s in _services)
            {
                Debug.WriteLine("Found Service: " + s.Uuid);

                if (s.Uuid == new Guid("0000fff0-0000-1000-8000-00805f9b34fb"))
                {
                    _service = s;
                    return(true);
                }
            }
            await new MessageDialog("Unable to find VICTOR Service 0000fff0").ShowAsync();
            return(false);
        }
		public async Task<bool> Start(GattDeviceService uARTService)
		{
			if (uARTService == null || uARTService.Uuid != ToolboxIdentifications.GattServiceUuids.Nordic_UART)
			{
				iSServiceStarted = false;
				return iSServiceStarted;
			}
			else
			{
				UARTGattService = uARTService;
				rxCharacteristic = this.UARTGattService.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.RX).FirstOrDefault();
				iSServiceStarted = await EnableRXNotification();
				return iSServiceStarted;
			}
		}
Example #38
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);
        }
Example #39
0
        private async void pairDeviceAsync(BluetoothLEDevice device)
        {
            var pairingResult = await device.GetGattServicesAsync();

            foreach (var service in pairingResult.Services)
            {
                Console.WriteLine(service.Uuid.ToString());
                if (service.Uuid.ToString().Equals("6e400001-b5a3-f393-e0a9-e50e24dcca9e")) //Compare the UUID with the one in ESP32
                {
                    deviceService = service;
                }
            }

            EnableNotifications(); //Enable to receive the notifications from ESP32
        }
Example #40
0
        public void Deinitialize()
        {
            if (_characteristic != null)
            {
                _characteristic.ValueChanged -= Oncharacteristic_ValueChanged;
                _characteristic = null;
            }

            if (_service != null)
            {
                _service.Device.ConnectionStatusChanged -= OnConnectionStatusChanged;
                //_service.Dispose();// appears that we should not call this here!!
                _service = null;
            }
        }
        public void Deinitialize()
        {
            if (_characteristic != null)
            {
                _characteristic.ValueChanged -= Oncharacteristic_ValueChanged;
                _characteristic = null;
            }

            if (_service != null)
            {
                _service.Device.ConnectionStatusChanged -= OnConnectionStatusChanged;
                //_service.Dispose();// appears that we should not call this here!!
                _service = null;
            }
        }
        /// <summary>
        /// Helper function, enumerates a service searching for a specific characteristic.
        /// </summary>
        /// <param name="service">Service to enumerate.</param>
        /// <param name="characteristicAssignedNumber">Characteristic to find.</param>
        /// <returns><see cref="GattCharacteristic"/> of found characteristic, or null.</returns>
        private async Task <GattCharacteristic> FindCharacteristicInService(GattDeviceService service, ushort characteristicAssignedNumber)
        {
            var characteristics = await service.GetCharacteristicsAsync();

            foreach (var characteristic in characteristics.Characteristics)
            {
                var can = Bluetooth.Utility.UuidToAssignedNumber(characteristic.Uuid);
                if (can == characteristicAssignedNumber)
                {
                    return(characteristic);
                }
            }

            return(null);
        }
        /**
         * Writes a command to MetaWear via the command register UUID
         * @see Characteristics.MetaWear#COMMAND
         */
        private static async Task <GattCommunicationStatus> writeCommandAsync()
        {
            GattDeviceService  service = deviceService;
            GattCharacteristic command = service.GetCharacteristics(MetaWear.COMMAND.uuid)[0];

            byte[]     buf    = commandBytes.Dequeue();
            DataWriter writer = new DataWriter();

            writer.WriteBytes(buf);
            GattCommunicationStatus st = await command.WriteValueAsync(writer.DetachBuffer());

            deviceState = DeviceState.READY;

            return(st);
        }
Example #44
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
Example #45
0
        public async void FindAndConnect()
        {
//			Task.Factory.StartNew(new Action(async () =>
            {
                String sid = GattDeviceService.GetDeviceSelectorFromShortId(serviceId);

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

                if (devices.Count > 0)
                {
                    InitializeService(devices[0]);
                }
            }
            //));
        }
Example #46
0
        public async void SendTestData(List<DeviceInformation> parrotDevices)
        {
            DeviceInformation motorDevice = null;
            foreach (var device in parrotDevices.Where(device => device.Id == ParrotConstants.DeviceIdMotor))
            {
                motorDevice = device;
            }
            if (motorDevice == null) return;

            // get device service
            _service = await GattDeviceService.FromIdAsync(motorDevice.Id);
            if (null == _service) return;

            // get service characteristics
            Test02();
        }
        /// <summary>
        /// Retrieves the sensors GATT device service from a specified DeviceInformation and saves it for further usage.
        /// 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>Indicates if the gatt service could be retrieved and set successfully</returns>
        public async Task<bool> Initialize(DeviceInformation deviceInfo)
        {
            Validator.RequiresNotNull(deviceInfo);
            if (!deviceInfo.Id.Contains(SensorTagUuid.UUID_INF_SERV))
                throw new ArgumentException("Wrong DeviceInformation passed. You need to get the right DeviceInformation via DeviceInfoService.ServiceUuid.");

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

            this.deviceService = await GattDeviceService.FromIdAsync(deviceInfo.Id);
            if (this.deviceService == null)
                return false;
            return true;
        }
Example #48
0
        /// <summary>
        /// Retrieves the sensors GATT device service from a specified DeviceInformation and saves it for further usage.
        /// 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>Indicates if the gatt service could be retrieved and set successfully</returns>
        public async Task<bool> Initialize(DeviceInformation deviceInfo)
        {
            if (deviceInfo == null)
                throw new DeviceNotInitializedException();

            if (!deviceInfo.Id.Contains(SensorServiceUuid))
                throw new ArgumentException("Wrong DeviceInformation passed. You need to get the right DeviceInformation via SPECIFICSENSORCLASS.SensorServiceUuid.");

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

            this.deviceService = await GattDeviceService.FromIdAsync(deviceInfo.Id);
            if (this.deviceService == null)
                return false;
            return true;
        }
Example #49
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;
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
            await progressbar.ShowAsync();
            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(GattDeviceService)))
            {
                _service = ((GattDeviceService)e.Parameter);
                this.lblDeviceName.Text = _service.Device.Name;
                this.lblServiceName.Text = (string)_conv.Convert(_service.Uuid, typeof(string), null, null);
                this.lblServiceAddress.Text = _service.Uuid.ToString();

                _characteristics = new List<CharacteristicWithValue>();
                foreach (var c in _service.GetAllCharacteristics())
                {
                    var val = new CharacteristicWithValue();
                    val.GattCharacteristic = c;


                    if (((int)c.CharacteristicProperties & (int)GattCharacteristicProperties.Read) != 0)
                    {
                        try
                        {
                            GattReadResult readResult = await c.ReadValueAsync();
                            if (readResult.Status == GattCommunicationStatus.Success)
                            {
                                val.Value = new byte[readResult.Value.Length];
                                DataReader.FromBuffer(readResult.Value).ReadBytes(val.Value);
                            }
                        }
                        catch { }
                    }
                    _characteristics.Add(val);
                }

                lstCharacteristics.ItemsSource = _characteristics;
            }

            this.navigationHelper.OnNavigatedTo(e);
            await progressbar.HideAsync();
        }
        public async void InitializeServiceAsync(string deviceId)
        {
            try
            {
                Deinitialize();
                _service = await GattDeviceService.FromIdAsync(deviceId);

                if (_service != null)
                {
                    //we could be already connected, thus lets check that before we start monitoring for changes
                    if (DeviceConnectionUpdated != null && (_service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected))
                    {
                        DeviceConnectionUpdated(true, null);
                    }

                    _service.Device.ConnectionStatusChanged += OnConnectionStatusChanged;

                    _characteristic = _service.GetCharacteristics(GattCharacteristicUuids.HeartRateMeasurement)[0];
                    _characteristic.ValueChanged += Oncharacteristic_ValueChanged;

                    var currentDescriptorValue = await _characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();
                    if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) ||
                    (currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != GattClientCharacteristicConfigurationDescriptorValue.Notify))
                    {
                        // most likely we never get here, though if for any reason this value is not Notify, then we should really set it to be
                        await _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("ERROR: Accessing your device failed." + Environment.NewLine + e.Message);

                if(DeviceConnectionUpdated != null)
                {
                    DeviceConnectionUpdated(false, "Accessing device failed: " + e.Message);
                }
            }
        }
        /// <summary>
        /// Reads a value from from a service of a device
        /// </summary>
        /// <param name="gattDeviceService">GattDeviceService of a connected bluetooth device</param>
        /// <param name="valueServiceUuid">Uuid of the characteristic you want to read from</param>
        /// <returns>Raw data read from the sensor</returns>
        /// <exception cref="DeviceUnreachableException">Thrown if it wasn't possible to communicate with the device.</exception>
        /// <exception cref="Exception">Thrown on purpose if the GattDeviceService doesn't provide the specified characteristic.</exception>
        public async static Task<byte[]> ReadValue(GattDeviceService gattDeviceService, string valueServiceUuid)
        {
            Validator.RequiresNotNull(gattDeviceService, "gattDeviceService");
            Validator.RequiresNotNullOrEmpty(valueServiceUuid, "valueServiceUuid");

            IReadOnlyList<GattCharacteristic> characteristics = gattDeviceService.GetCharacteristics(new Guid(valueServiceUuid));

            if (characteristics.Count == 0)
                throw new Exception("Could not find specified characteristic.");

            GattCharacteristic sidCharacteristic = characteristics[0];

            GattReadResult res = await sidCharacteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);

            if (res.Status == GattCommunicationStatus.Unreachable)
                throw new DeviceUnreachableException(DeviceUnreachableException.DEFAULT_UNREACHABLE_MESSAGE);

            var data = new byte[res.Value.Length];

            DataReader.FromBuffer(res.Value).ReadBytes(data);

            return data;
        }
Example #53
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
            {
            }

        }
        private async void DevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RunButton.IsEnabled = false;

            var device = DevicesListBox.SelectedItem as DeviceInformation;
            DevicesListBox.Visibility = Visibility.Collapsed;

            nrfService = await GattDeviceService.FromIdAsync(device.Id);
            writeCharacteristic = nrfService.GetCharacteristics(new Guid("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"))[0];
            readCharacteristic = nrfService.GetCharacteristics(new Guid("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"))[0];

            if (nrfService != null)
            {
                bleInfoTextBlock.Text = "Using service Id: " + nrfService.DeviceId;

                readCharacteristic.ValueChanged += incomingData_ValueChanged;
                await readCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            }
            else
            {
                bleInfoTextBlock.Text = "Error: gattService is null";
            }
        }
 private static void ValidateChars(string deviceId, GattDeviceService service, Guid charsUuid)
 {
     var chars = service.GetCharacteristics(charsUuid);
     if (chars == null || chars.Count == 0) return;
     var charsName = CharacteristicUuidsResolver.GetNameFromUuid(charsUuid);
     Debug.WriteLine($"    {chars.Count} found for {charsName}");
     foreach (GattCharacteristic characteristic in chars)
     {
         var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid);
         var friendlyDesc = characteristic.UserDescription;
         Debug.WriteLine($"        {charName} - {friendlyDesc} - {characteristic.ProtectionLevel}");
     }
 }
		private void RetrieveImmediateAlertService(GattDeviceService immediateAlertService)
		{
			ImmediateAlertService.Start(immediateAlertService);
		}
 public BluetoothLEAttributeDisplay(GattDeviceService service)
 {
     this.service = service;
     AttributeDisplayType = AttributeType.Service;
 }
Example #58
0
        /// <summary>
        /// Register a ValueChanged callback on a device Characteristic.
        /// The Characteristic must be readable and send Notifications.
        /// </summary>
        /// <param name="service">The Service containing the Characteristic</param>
        /// <param name="readCharacteristicUUID">The UUID of the Characteristic</param>
        /// <param name="valueChangedHandler">The event handler callback</param>
        /// <returns>A GattCharacteristic for the which the event handler was 
        /// registered or null if the Characteristic wasn’t found</returns>   
        private async Task<GattCharacteristic> registerCharacteristicChangedCallback(GattDeviceService service,
            string readCharacteristicUUID, 
            TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> valueChangedHandler)
        {
            Debug.Assert(service != null, "Null service passed as argument.");
            Debug.Assert(readCharacteristicUUID != null, "Null Characteristic UUID pass as argument.");

            //Obtain the characteristic we want to interact with
            var characteristics = service.GetCharacteristics(new Guid(readCharacteristicUUID));
            if (characteristics.Count == 0) return null;

            var characteristic = characteristics[0];

            //Subscribe to value changed event
            characteristic.ValueChanged += valueChangedHandler;

            //Set configuration to notify  
            await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                GattClientCharacteristicConfigurationDescriptorValue.Notify);

            return characteristic;
        }
Example #59
0
 private void Clean()
 {
     if (deviceService != null)
         deviceService.Dispose();
     deviceService = null;
     if (dataCharacteristic != null)
         dataCharacteristic.ValueChanged -= dataCharacteristic_ValueChanged;
 }
		private async void RetrieveBatteryService(GattDeviceService gattDeviceService) 
		{
			await BatteryService.Start(gattDeviceService);
			BatteryService.ValueChangeCompleted += BatteryService_ValueChangeCompleted;
		}