예제 #1
0
        private void EnableCharacteristicPanels(GattCharacteristicProperties properties)
        {
            // BT_Code: Hide the controls which do not apply to this characteristic.
            SetVisibility(CharacteristicReadPanel, properties.HasFlag(GattCharacteristicProperties.Read));

            SetVisibility(CharacteristicWritePanel,
                          properties.HasFlag(GattCharacteristicProperties.Write) ||
                          properties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse));
            CharacteristicWriteValue.Text = "";

            SetVisibility(CharacteristicIndicatePanel, properties.HasFlag(GattCharacteristicProperties.Indicate));
            SetVisibility(CharacteristicNotifyPanel, properties.HasFlag(GattCharacteristicProperties.Notify));

            CharacteristicLatestValue.Text = "";
        }
예제 #2
0
        /// <summary>
        ///     Converts the <see cref="GattCharacteristicProperties" /> into a
        ///     string containing the property names separated by comma.
        /// </summary>
        /// <param name="properties">
        ///     This <see cref="GattCharacteristicProperties" /> to convert into a string.
        /// </param>
        /// <returns>
        ///     A string containing the property names separated by a comma.
        /// </returns>
        public static string ToCsv(this GattCharacteristicProperties properties)
        {
            var list = new List <GattCharacteristicProperties> ( );

            foreach (GattCharacteristicProperties property in
                     Enum.GetValues(typeof(GattCharacteristicProperties)))
            {
                if ((properties & property) == property)
                {
                    list.Add(property);
                }
            }

            return(string.Join(", ",
                               list));
        }
예제 #3
0
        public static object ReadGattCharacteristic(string characteristic_name)
        {
            GattCharacteristic           chr      = GetGattCharacteristic(characteristic_name);
            GattCharacteristicProperties property = chr.CharacteristicProperties;

            if (property.HasFlag(GattCharacteristicProperties.Read))
            {
                GattReadResult result = chr.ReadValueAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                if (result.Status == GattCommunicationStatus.Success)
                {
                    var reader = DataReader.FromBuffer(result.Value);
                    return(reader);
                }
            }
            return(null);
        }
예제 #4
0
        public async Task ConnectDevice(string id)
        {
            BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(id);

            if (bluetoothLeDevice != null)
            {
                GattDeviceServicesResult gattDeviceServicesResult = await bluetoothLeDevice.GetGattServicesAsync();

                Log.Debug($"{bluetoothLeDevice.Name} Services: {gattDeviceServicesResult.Services.Count}, {gattDeviceServicesResult.Status}, {gattDeviceServicesResult.ProtocolError}");

                if (gattDeviceServicesResult.Status == GattCommunicationStatus.Success)
                {
                    _selectedDeviceServices = gattDeviceServicesResult.Services.FirstOrDefault(x => x.Uuid.ToString() == ServiceUUID);
                    foreach (var service in gattDeviceServicesResult.Services)
                    {
                        Log.Debug("service: " + service.Uuid);
                    }
                    if (_selectedDeviceServices != null)
                    {
                        GattCharacteristicsResult gattCharacteristicsResult = await _selectedDeviceServices.GetCharacteristicsAsync();

                        if (gattCharacteristicsResult.Status == GattCommunicationStatus.Success)
                        {
                            var characteristics = gattCharacteristicsResult.Characteristics.Where(x => x.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write));
                            _commandCharacteristic = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == CommandUUID);
                            _serialCharacteristic  = gattCharacteristicsResult.Characteristics.FirstOrDefault(x => x.Uuid.ToString() == SerialPortUUID);
                            GattCharacteristicProperties properties = _serialCharacteristic.CharacteristicProperties;
                            if (_serialCharacteristic != null)
                            {
                                if (properties.HasFlag(GattCharacteristicProperties.Read))
                                {
                                    ReadBLESerial();
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.Write))
                                {
                                    WriteBlunoSettings();
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                                {
                                    // This characteristic supports subscribing to notifications.
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #5
0
        private async void startReaderAsync(GattCharacteristic characteristic)
        {
            GattCharacteristicProperties properties = characteristic.CharacteristicProperties;

            if (properties.HasFlag(GattCharacteristicProperties.Read))
            {
                Console.WriteLine("This characteristic supports reading from it.");

                while (true)
                {
                    GattReadResult result = await this.txCharacteristic.ReadValueAsync();

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        /*
                         * byte[] value = new byte[result.Value.Length];
                         * DataReader.FromBuffer(result.Value).ReadBytes(value);
                         * Console.WriteLine(value.ToString());
                         */
                        DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(result.Value);
                        dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                        string text = dataReader.ReadString(result.Value.Length);
                        Console.WriteLine(text);
                    }
                    Thread.Sleep(1000);
                }
            }
            if (properties.HasFlag(GattCharacteristicProperties.Write))
            {
                Console.WriteLine("This characteristic supports reading from it.");
            }
            if (properties.HasFlag(GattCharacteristicProperties.Notify))
            {
                Console.WriteLine("This characteristic supports subscribing to notifications.");

                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify);

                if (status == GattCommunicationStatus.Success)
                {
                    Console.WriteLine("Success");
                    characteristic.ValueChanged += Characteristic_ValueChangedTest;
                    // ...
                }
            }
        }
예제 #6
0
        public static void WriteGattCharacteristic(string characteristic_name, byte[] dataToWrite)
        {
            GattCharacteristic           chr      = GetGattCharacteristic(characteristic_name);
            GattCharacteristicProperties property = chr.CharacteristicProperties;

            if (property.HasFlag(GattCharacteristicProperties.Write))
            {
                var writer = new DataWriter();
                writer.WriteBytes(dataToWrite);

                GattCommunicationStatus result = chr.WriteValueAsync(writer.DetachBuffer()).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                if (result == GattCommunicationStatus.Success)
                {
                    //Do stg. if success
                }
            }
        }
예제 #7
0
        public static async void WriteGattCharacteristic(string characteristic_name, string dataToWrite)
        {
            GattCharacteristic           chr      = GetGattCharacteristic(characteristic_name);
            GattCharacteristicProperties property = chr.CharacteristicProperties;

            if (property.HasFlag(GattCharacteristicProperties.Write))
            {
                var writer = new DataWriter();

                writer.WriteString(dataToWrite);
                GattCommunicationStatus result = await chr.WriteValueAsync(writer.DetachBuffer());

                if (result == GattCommunicationStatus.Success)
                {
                    //Do stg. if success
                }
            }
        }
예제 #8
0
        public async Task <Boolean> PerformAction(GattCharacteristic characteristic, TypedEventHandler <GattCharacteristic, GattValueChangedEventArgs> OnValueChanged)
        {
            var currentDescriptorValue = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();

            GattCharacteristicProperties properties = characteristic.CharacteristicProperties;

            if (properties.HasFlag(GattCharacteristicProperties.Notify))
            {
                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                if (status == GattCommunicationStatus.Success)
                {
                    characteristic.ValueChanged += OnValueChanged;
                    return(true);
                }
            }
            return(true);
        }
        private async Task UnregisterCharacteristic(GattCharacteristic characteristic)
        {
            GattCharacteristicProperties properties = characteristic.CharacteristicProperties;

            if ((properties & GattCharacteristicProperties.Notify) != 0)
            {
                // stop notifying.
                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.None);

                if (status == GattCommunicationStatus.Unreachable)
                {
                    OnError("Unregistering notification from the device failed saying device is unreachable.");
                }

                characteristic.ValueChanged -= OnCharacteristicValueChanged;
            }
        }
예제 #10
0
        // Not used but can be usefull for debugging
        public async void EnumeratingUsages()
        {
            if (!HasDeviceConnected())
            {
                return;
            }

            GattDeviceServicesResult services = await connectedDevice.GetGattServicesAsync();

            if (services.Status == GattCommunicationStatus.Success)
            {
                foreach (GattDeviceService s in services.Services)
                {
                    await s.RequestAccessAsync();

                    GattCharacteristicsResult characteristicsResult = await s.GetCharacteristicsAsync();

                    Console.WriteLine("Service : " + s.Uuid);
                    if (characteristicsResult.Status == GattCommunicationStatus.Success)
                    {
                        foreach (GattCharacteristic c in characteristicsResult.Characteristics)
                        {
                            GattCharacteristicProperties props = c.CharacteristicProperties;
                            Console.WriteLine("\t characteristics : " + c.Uuid + " / " + c.UserDescription);
                            if (props.HasFlag(GattCharacteristicProperties.Read))
                            {
                                Console.WriteLine("\t\tRead");
                            }
                            if (props.HasFlag(GattCharacteristicProperties.Write))
                            {
                                Console.WriteLine("\t\tWrite");
                            }
                            if (props.HasFlag(GattCharacteristicProperties.Notify))
                            {
                                Console.WriteLine("\t\tNotify");
                            }
                        }
                    }

                    s.Dispose();
                }
            }
        }
예제 #11
0
        public static GattCharacteristicProperties ToGattCharacteristicProperties(this CoreBluetooth.CBCharacteristicProperties value)
        {
            GattCharacteristicProperties p = GattCharacteristicProperties.None;

            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.AuthenticatedSignedWrites))
            {
                p |= GattCharacteristicProperties.AuthenticatedSignedWrites;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.Broadcast))
            {
                p |= GattCharacteristicProperties.Broadcast;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.ExtendedProperties))
            {
                p |= GattCharacteristicProperties.ExtendedProperties;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.Indicate))
            {
                p |= GattCharacteristicProperties.Indicate;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.Notify))
            {
                p |= GattCharacteristicProperties.Notify;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.Read))
            {
                p |= GattCharacteristicProperties.Read;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.Write))
            {
                p |= GattCharacteristicProperties.Write;
            }
            if (value.HasFlag(CoreBluetooth.CBCharacteristicProperties.WriteWithoutResponse))
            {
                p |= GattCharacteristicProperties.WriteWithoutResponse;
            }

            return(p);
        }
예제 #12
0
        private async Task UnregisterForValueChangeEventsAsync(GattDeviceService service, Guid guid)
        {
            try
            {
                var res = await service.GetCharacteristicsForUuidAsync(guid);

                if (res.Status == GattCommunicationStatus.Success)
                {
                    GattCharacteristic characteristic = res.Characteristics.FirstOrDefault();

                    if (characteristic == null)
                    {
                        OnError("Characteristic " + guid + " not available");
                        return;
                    }

                    GattCharacteristicProperties properties = characteristic.CharacteristicProperties;

                    if ((properties & GattCharacteristicProperties.Notify) != 0)
                    {
                        // stop notifying.
                        GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                            GattClientCharacteristicConfigurationDescriptorValue.None);

                        if (status == GattCommunicationStatus.Unreachable)
                        {
                            OnError("Unregistering notification from the device failed saying device is unreachable.");
                        }

                        characteristic.ValueChanged -= OnCharacteristicValueChanged;
                    }
                }
            }
            catch (Exception ex)
            {
                OnError("Unhandled exception unregistering for notifications. " + ex.Message);
            }
        }
예제 #13
0
        public async Task subscribeToNotify()
        {
            // Service
            Guid serviceGuid = Guid.Parse(Globals.UUID_SERVICE);
            GattDeviceServicesResult serviceResult = await device.GetGattServicesForUuidAsync(serviceGuid);

            device.ConnectionStatusChanged += OnConnectionChange;

            // Characteristic (Handle 17 - Sensor Command)
            Guid charGiud = Guid.Parse(Globals.UUID_CHAR);
            var  characs  = await serviceResult.Services.Single(s => s.Uuid == serviceGuid).GetCharacteristicsAsync();

            var charac = characs.Characteristics.Single(c => c.Uuid == charGiud);

            GattCharacteristicProperties properties = charac.CharacteristicProperties;


            //Write the CCCD in order for server to send notifications.
            var notifyResult = await charac.WriteClientCharacteristicConfigurationDescriptorAsync(
                GattClientCharacteristicConfigurationDescriptorValue.Notify);

            charac.ValueChanged += Charac_ValueChangedAsync;
        }
예제 #14
0
        private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            if (args.Advertisement.LocalName.Contains("HMSoft"))
            {
                BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();

                if (result.Status == GattCommunicationStatus.Success)
                {
                    var services = result.Services;
                    foreach (var service in services)
                    {
                        if (!foundServices.Contains(service))
                        {
                            Dispatcher.Invoke(() =>
                            {
                                tb.Text += service.Uuid;
                                tb.Text += Environment.NewLine;
                                foundServices.Add(service);
                            });
                        }
                        if (!service.Uuid.ToString().StartsWith("0000ffe0"))
                        {
                            continue;
                        }
                        GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();

                        if (characteristicsResult.Status == GattCommunicationStatus.Success)
                        {
                            var characteristics = characteristicsResult.Characteristics;
                            foreach (var characteristic in characteristics)
                            {
                                if (!foundCharacters.Contains(characteristic))
                                {
                                    Dispatcher.Invoke(() =>
                                    {
                                        tb.Text += characteristic.Uuid;
                                        tb.Text += Environment.NewLine;
                                        foundCharacters.Add(characteristic);
                                    });
                                }

                                if (!characteristic.Uuid.ToString().StartsWith("0000ffe1"))
                                {
                                    continue;
                                }
                                GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
                                if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    GattWriteResult status =
                                        await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

                                    return;
                                }

                                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                                {
                                    GattCommunicationStatus status =
                                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                                            GattClientCharacteristicConfigurationDescriptorValue.Notify);

                                    if (status == GattCommunicationStatus.Success)
                                    {
                                        characteristic.ValueChanged += Characteristic_ValueChanged;
                                    }
                                }

                                if (properties.HasFlag(GattCharacteristicProperties.Read))
                                {
                                    GattReadResult gattResult = await characteristic.ReadValueAsync();

                                    if (gattResult.Status == GattCommunicationStatus.Success)
                                    {
                                        var    reader = DataReader.FromBuffer(gattResult.Value);
                                        byte[] input  = new byte[reader.UnconsumedBufferLength];
                                        reader.ReadBytes(input);
                                        Dispatcher.Invoke(() =>
                                        {
                                            tb.Text += "connected: ";
                                            tb.Text += Encoding.ASCII.GetString(input);
                                            tb.Text += Environment.NewLine;
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #15
0
 public GattServerCharacteristic(Guid uuid, GattCharacteristicProperties properties, GattPermissions permission)
 {
     DroidCharacteristic = new Android.Bluetooth.BluetoothGattCharacteristic(uuid.ToJavaUuid(), properties.ToDroidGattProperty(), permission.ToDroidGattPermission());
     _Descritptor        = new List <GattServerDescriptor>();
 }
        protected void RegisterForValueChangeEvents(Guid guid)
        {
            _requestedCharacteristics.Add(guid);

            if (_service == null || !this._connected)
            {
                // wait till we are connected...
                return;
            }
            try
            {
                GattCharacteristic characteristic = _service.GetCharacteristics(guid).FirstOrDefault();

                if (characteristic == null)
                {
                    OnError("Characteristic " + guid + " not available");
                    return;
                }

                GattCharacteristicProperties properties = characteristic.CharacteristicProperties;


                Debug.WriteLine("Characteristic {0} supports: ", guid.ToString("b"));
                if ((properties & GattCharacteristicProperties.Broadcast) != 0)
                {
                    Debug.WriteLine("    Broadcast");
                }
                if ((properties & GattCharacteristicProperties.Read) != 0)
                {
                    Debug.WriteLine("    Read");
                }
                if ((properties & GattCharacteristicProperties.WriteWithoutResponse) != 0)
                {
                    Debug.WriteLine("    WriteWithoutResponse");
                }
                if ((properties & GattCharacteristicProperties.Write) != 0)
                {
                    Debug.WriteLine("    Write");
                }
                if ((properties & GattCharacteristicProperties.Notify) != 0)
                {
                    Debug.WriteLine("    Notify");
                }
                if ((properties & GattCharacteristicProperties.Indicate) != 0)
                {
                    Debug.WriteLine("    Indicate");
                }
                if ((properties & GattCharacteristicProperties.AuthenticatedSignedWrites) != 0)
                {
                    Debug.WriteLine("    AuthenticatedSignedWrites");
                }
                if ((properties & GattCharacteristicProperties.ExtendedProperties) != 0)
                {
                    Debug.WriteLine("    ExtendedProperties");
                }
                if ((properties & GattCharacteristicProperties.ReliableWrites) != 0)
                {
                    Debug.WriteLine("    ReliableWrites");
                }
                if ((properties & GattCharacteristicProperties.WritableAuxiliaries) != 0)
                {
                    Debug.WriteLine("    WritableAuxiliaries");
                }

                if ((properties & GattCharacteristicProperties.Notify) != 0)
                {
                    try {
                        characteristic.ValueChanged -= OnCharacteristicValueChanged;
                    } catch { }

                    QueueAsyncEnableNotification(characteristic);
                }
                else
                {
                    OnError("Registering for notification on characteristic that doesn't support notification: " + guid);
                }
            }
            catch (Exception ex)
            {
                OnError("Unhandled exception registering for notifications. " + ex.Message);
            }
        }
            /// <summary>
            /// Look up battery level from Battery Service
            /// </summary>
            /// <returns>%Battery level (0-100)</returns>
            public async Task <byte[]> GetBatteryLevel()
            {
                Debug.WriteLine("Begin GetBatteryLevel");
                if (!Properties.Keys.Contains(SensorTagProperties.BatteryService))
                {
                    Debug.WriteLine("Error: Battery Service not available.");
                    Debug.WriteLine("End GetBatteryLevel");
                    return(null);
                }

                if (!Properties[SensorTagProperties.BatteryService].CharcteristicsP.Keys.Contains
                        (SensorTagProperties.BatteryLevel)
                    )
                {
                    Debug.WriteLine("Missing Property {0}", SensorTagProperties.BatteryLevel);
                    Debug.WriteLine("End GetBatteryLevel");
                    return(null);
                }

                byte[] bytes = null;
                GattCharacteristicProperties flag = GattCharacteristicProperties.Read;
                GattCharacteristic           deviceBatteryLevelCharacteristic = Properties[SensorTagProperties.BatteryService].CharcteristicsP[SensorTagProperties.BatteryLevel];

                if (deviceBatteryLevelCharacteristic != null)
                {
                    if (deviceBatteryLevelCharacteristic.CharacteristicProperties.HasFlag(flag))
                    {
                        try
                        {
                            GattReadResult result = null;
                            try
                            {
                                result = await deviceBatteryLevelCharacteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
                            }
                            catch (Exception ex)
                            {
                                string msg = ex.Message;
                                Debug.WriteLine("Error GetBatteryLevel1(): " + msg);
                            }

                            var status = result.Status;
                            if (status == GattCommunicationStatus.Success)
                            {
                                var dat = result.Value;
                                var xx  = dat.GetType();
                                var yy  = dat.Capacity;
                                var zz  = dat.Length;

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

                                Windows.Storage.Streams.DataReader.FromBuffer(result.Value).ReadBytes(bytes);
                            }
                        }

                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            Debug.WriteLine("Error GetBatteryLevel2(): " + msg);
                        }
                    }
                }
                if (bytes != null)
                {
                    if (bytes.Length == CC2650SensorTag.SensorServicesCls.DataLength[CC2650SensorTag.SensorServicesCls.BATT_INDX])
                    {
                        Debug.WriteLine("Battery Level: {0}", bytes[0]);
                        SetBatteryLevel?.Invoke((int)bytes[0]);
                        IncProgressCounter();
                    }
                }
                Debug.WriteLine("End GetBatteryLevel");
                return(bytes);
            }
            /// <summary>
            /// Look up a specific SensorTag property using Property Service
            /// </summary>
            /// <param name="property">The property to look upo</param>
            /// <param name="showStartEndMsg">Debugging option</param>
            /// <returns>Byte[]</returns>
            public async Task <byte[]> ReadProperty(SensorTagProperties property, bool showStartEndMsg)
            {
                if (showStartEndMsg)
                {
                    Debug.WriteLine("Begin read property: {0} ", property);
                }

                byte[] bytes = null;

                if (!Properties.Keys.Contains(SensorTagProperties.PropertiesService))
                {
                    Debug.WriteLine("Error: Properties database not set up.");
                    return(null);
                }

                if (!Properties[SensorTagProperties.PropertiesService].CharcteristicsP.Keys.Contains(property))
                {
                    Debug.WriteLine("Missing Property {0}", property);
                    return(null);
                }

                GattCharacteristicProperties flag           = GattCharacteristicProperties.Read;
                GattCharacteristic           characteristic = Properties[SensorTagProperties.PropertiesService].CharcteristicsP[property];

                if (characteristic.CharacteristicProperties.HasFlag(flag))
                {
                    try
                    {
                        GattReadResult result = null;
                        try
                        {
                            result = await characteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            Debug.WriteLine("Error ReadProperty1(): " + msg);
                        }

                        var status = result.Status;
                        if (status == GattCommunicationStatus.Success)
                        {
                            var dat = result.Value;
                            var xx  = dat.GetType();
                            var yy  = dat.Capacity;
                            var zz  = dat.Length;

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

                            Windows.Storage.Streams.DataReader.FromBuffer(result.Value).ReadBytes(bytes);
                            IncProgressCounter();
                        }
                    }

                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                        Debug.WriteLine("Error ReadProperty2(): " + msg);
                    }
                }

                if (showStartEndMsg)
                {
                    Debug.WriteLine("End read property: {0} ", property);
                }

                return(bytes);
            }
예제 #19
0
        private async void OnAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher watcher,
                                                        BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            // Filter for specific Device by name
            if (eventArgs.Advertisement.LocalName == bleDevicName)
            {
                watcher.Stop();
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

                //always check for null!!
                if (device != null)
                {
                    deviceFoundMilis = stopwatch.ElapsedMilliseconds;
                    Debug.WriteLine("Device found in " + deviceFoundMilis + " ms");

                    var rssi = eventArgs.RawSignalStrengthInDBm;
                    Debug.WriteLine("Signalstrengt = " + rssi + " DBm");

                    var bleAddress = eventArgs.BluetoothAddress;
                    Debug.WriteLine("Ble address = " + bleAddress);

                    var advertisementType = eventArgs.AdvertisementType;
                    Debug.WriteLine("Advertisement type = " + advertisementType);

                    var result = await device.GetGattServicesForUuidAsync(MyService_GUID);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        connectedMilis = stopwatch.ElapsedMilliseconds;
                        Debug.WriteLine("Connected in " + (connectedMilis - deviceFoundMilis) + " ms");
                        var services = result.Services;
                        service = services[0];
                        if (service != null)
                        {
                            serviceFoundMilis = stopwatch.ElapsedMilliseconds;
                            Debug.WriteLine("Service found in " +
                                            (serviceFoundMilis - connectedMilis) + " ms");
                            var charResult = await service.GetCharacteristicsForUuidAsync(MYCharacteristic_GUID);

                            if (charResult.Status == GattCommunicationStatus.Success)
                            {
                                charac = charResult.Characteristics[0];
                                if (charac != null)
                                {
                                    characteristicFoundMilis = stopwatch.ElapsedMilliseconds;
                                    Debug.WriteLine("Characteristic found in " +
                                                    (characteristicFoundMilis - serviceFoundMilis) + " ms");

                                    var descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.None;
                                    GattCharacteristicProperties properties = charac.CharacteristicProperties;
                                    string descriptor = string.Empty;

                                    if (properties.HasFlag(GattCharacteristicProperties.Read))
                                    {
                                        Debug.WriteLine("This characteristic supports reading .");
                                    }
                                    if (properties.HasFlag(GattCharacteristicProperties.Write))
                                    {
                                        Debug.WriteLine("This characteristic supports writing .");
                                    }
                                    if (properties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
                                    {
                                        Debug.WriteLine("This characteristic supports writing  whithout responce.");
                                    }
                                    if (properties.HasFlag(GattCharacteristicProperties.Notify))
                                    {
                                        descriptor      = "notifications";
                                        descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
                                        Debug.WriteLine("This characteristic supports subscribing to notifications.");
                                    }
                                    if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                                    {
                                        descriptor      = "indications";
                                        descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
                                        Debug.WriteLine("This characteristic supports subscribing to Indication");
                                    }
                                    try
                                    {
                                        var descriptorWriteResult = await charac.WriteClientCharacteristicConfigurationDescriptorAsync(descriptorValue);

                                        if (descriptorWriteResult == GattCommunicationStatus.Success)
                                        {
                                            WriteDescriptorMilis = stopwatch.ElapsedMilliseconds;
                                            Debug.WriteLine("Successfully registered for " + descriptor + " in " +
                                                            (WriteDescriptorMilis - characteristicFoundMilis) + " ms");
                                            charac.ValueChanged += Charac_ValueChanged;;
                                        }
                                        else
                                        {
                                            Debug.WriteLine($"Error registering for " + descriptor + ": {result}");
                                            device.Dispose();
                                            device = null;
                                            watcher.Start();//Start watcher again for retry
                                        }
                                    }
                                    catch (UnauthorizedAccessException ex)
                                    {
                                        Debug.WriteLine(ex.Message);
                                    }
                                }
                            }
                            else
                            {
                                Debug.WriteLine("No characteristics  found");
                            }
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No services found");
                    }
                }
                else
                {
                    Debug.WriteLine("No device found");
                }
            }
        }
예제 #20
0
        private async void GetAllInfoSensor()
        {
            //<begincode*****GetAllServices*****>
            try
            {
                if (cadence != null)
                {
                    string BluetoothAddressHex = cadence.BluetoothAddress.ToString("x"); // convert decimal to hex
                    for (int i = 2; i < BluetoothAddressHex.Length; i += 2)              // om het leesbaar te houden plaatsen we om de 2 hex getallen een :
                    {
                        BluetoothAddressHex = BluetoothAddressHex.Insert(i, ":");
                        i = i + 1;
                    }
                    BTAddresTextBlock.Text = "Sensor: Bluetooth address = " + BluetoothAddressHex;
                    //Debug.WriteLine("sensor is " + cadence.ConnectionStatus.ToString());

                    //<begincode***** get all services and putt them in the list of observableServices*****>
                    result = await cadence.GetGattServicesAsync();

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        //Debug.WriteLine("sensor is " + cadence.ConnectionStatus.ToString());
                        List <GattDeviceService> services = result.Services.ToList();
                        observableServices = new ObservableCollection <GattServiceWrapper>();
                        observableServices.Clear();
                        foreach (GattDeviceService service in services)
                        {
                            observableServices.Add(new GattServiceWrapper(service));
                        }
                        connectionStatusTextBlock.Text       = "Sensor: Connection established!";
                        connectionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        TimerConnectToSensor.Stop();
                    }
                    else
                    {
                        Debug.WriteLine("could not read the services");
                        connectionStatusTextBlock.Text       = "Sensor: Couldn't establish connection";
                        connectionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        NoError = false;
                        // TimerConnectToSensor.Start();
                        goto HandleFault;
                    }
                    //<endcode***** get all services and putt them in the list of observableServices*****>
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetAllServices " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetAllServices*****>

            //<begincode*****GetValuesSensor*****>
            try
            {
                //<begincode***** select characteristic Measurement and putt them in the list of observableCharacteristics*****>
                var wrapper5 = observableServices.Single(i => i.Service.Uuid.ToString() == "00001816-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper5.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics = new ObservableCollection <GattCharacteristicWrapper>();
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the characteristic measurement");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic device Measurement and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic measurement*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a5b-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic measurement*****>
                //<begincode***** subscribe to measurement*****>
                characteristic2 = selectedCharacteristicWrapper.Characteristic;
                GattCharacteristicProperties properties = characteristic2.CharacteristicProperties;
                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    GattCommunicationStatus status = await characteristic2.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    if (status == GattCommunicationStatus.Success)
                    {
                        // Server has been informed of clients interest.
                        SubscribeMeasurement                   = true;
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement Subscribed.";
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        characteristic2.ValueChanged          += Characteristic_ValueChanged;
                    }
                    else
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement " + status.ToString();
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        Debug.WriteLine("could not subscribe to measurement");
                        NoError = false;
                        goto HandleFault;
                    }
                }
                else if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                {
                    GattCommunicationStatus status = await characteristic2.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

                    if (status == GattCommunicationStatus.Success)
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement.";
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                        characteristic2.ValueChanged          += Characteristic_ValueChanged;
                    }
                    else
                    {
                        subscriptionStatusTextBlock.Text       = "Sensor: Measurement " + status.ToString();
                        subscriptionStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                        Debug.WriteLine("could not indicate to measurement");
                        NoError = false;
                        goto HandleFault;
                    }
                }
                //<endcode***** subscribe to measurement*****>
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetValuesSensor " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetValuesSensor*****>

            //<begincode*****GetInformationSensor*****>
            try
            {
                //<begincode***** select characteristic GenericAccess level and putt them in the list of observableCharacteristics*****>
                var wrapper2 = observableServices.Single(i => i.Service.Uuid.ToString() == "00001800-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper2.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    bool Doublecharastic = false; //preventing to add the same charateristic in de list observableCharacteristics, else get a fault
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        Doublecharastic = false;
                        for (int i = 0; i < observableCharacteristics.Count; i += 1)
                        {
                            if (observableCharacteristics[i].Characteristic.Uuid == characteristic.Uuid)
                            {
                                Doublecharastic = true;
                            }
                        }
                        if (Doublecharastic == false)
                        {
                            observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));;
                        }
                    }
                    //Debug.WriteLine("Getinformationsensor add");
                }
                else
                {
                    Debug.WriteLine("could not read the characterstics");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic GenericAccess and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic device name*****>

                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a00-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic device name*****>
                //<begincode*****read device name*****>
                GattReadResult result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    string utf8result = System.Text.Encoding.UTF8.GetString(input);
                    DeviceNameTextBlock.Text = "Sensor: name = " + utf8result;
                }
                else
                {
                    Debug.WriteLine("could not read the device name");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read Firmware revision*****>

                //<begincode***** select characteristic Device information and putt them in the list of observableCharacteristics*****>
                // Het is niet zeker dat de service firmware bestaat, daarom eerst controleren of de service wel bestaat, want als er niets is te selecteren dan krijgen we een fout
                for (int ii = 0; ii < observableServices.Count; ii += 1)
                {
                    if (observableServices[ii].Service.Uuid.ToString() == "0000180a-0000-1000-8000-00805f9b34fb")
                    {
                        wrapper3 = observableServices.Single(i => i.Service.Uuid.ToString() == "0000180a-0000-1000-8000-00805f9b34fb");
                        NoError  = true;
                        break;
                    }
                    else
                    {
                        NoError = false;
                    }
                }
                if (NoError == false)
                {
                    goto HandleFault;
                }
                result2 = await wrapper3.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    NoError = false;
                }
                //<endcode***** select characteristic device information and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic Firmware*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a26-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic Firmware*****>
                //<begincode*****read firmware*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    string utf8result = System.Text.Encoding.UTF8.GetString(input);
                    FirmwareTextBlock.Text = "Sensor: Firmware = " + utf8result;
                }
                else
                {
                    Debug.WriteLine("could not read the firmware revision");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read firmware*****>

                //<begincode***** select characteristic Hardware*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a27-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic Hardware*****>
                //<begincode*****read hardware*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    StringBuilder hex = new StringBuilder(input.Length * 2);
                    foreach (byte b in input)
                    {
                        hex.AppendFormat("{0:x2}", b);
                    }
                    int Hardwarevalue = Convert.ToInt32(hex.ToString(), 16);
                    HardwareTextBlock.Text = "Sensor: Hardware Revision = " + Hardwarevalue.ToString();
                }
                else
                {
                    Debug.WriteLine("could not read the hardware revision");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read hardware*****>

                //<begincode***** select characteristic battery level and putt them in the list of observableCharacteristics*****>
                var wrapper4 = observableServices.Single(i => i.Service.Uuid.ToString() == "0000180f-0000-1000-8000-00805f9b34fb");
                result2 = await wrapper4.Service.GetCharacteristicsAsync();

                if (result2.Status == GattCommunicationStatus.Success)
                {
                    observableCharacteristics.Clear();
                    foreach (GattCharacteristic characteristic in result2.Characteristics)
                    {
                        observableCharacteristics.Add(new GattCharacteristicWrapper(characteristic));
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the characteristic battery level");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode***** select characteristic battery level and putt them in the list of observableCharacteristics*****>
                //<begincode***** select characteristic battery level*****>
                selectedCharacteristicWrapper = observableCharacteristics.Single(i => i.Characteristic.Uuid.ToString() == "00002a19-0000-1000-8000-00805f9b34fb");
                //<endcode***** select characteristic battery level*****>
                //<begincode*****read battery level*****>
                result3 = await selectedCharacteristicWrapper.Characteristic.ReadValueAsync();

                if (result3.Status == GattCommunicationStatus.Success)
                {
                    reader = DataReader.FromBuffer(result3.Value);
                    byte[] input = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(input);
                    StringBuilder hex2 = new StringBuilder(input.Length * 2);
                    foreach (byte b in input)
                    {
                        hex2.AppendFormat("{0:x2}", b);
                    }
                    int Batteryvalue = Convert.ToInt32(hex2.ToString(), 16);
                    readingsTextBlock.Text = "Sensor: Battery level = " + Batteryvalue.ToString() + "%";
                    if (Batteryvalue < 40)
                    {
                        readingsTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                    }
                    else
                    {
                        readingsTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                    }
                }
                else
                {
                    Debug.WriteLine("could not read the battery level");
                    NoError = false;
                    goto HandleFault;
                }
                //<endcode*****read battery level*****>
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Fault GetInformationSensor " + ex);
                NoError = false;
                goto HandleFault;
            }
            //<endcode*****GetInformationSensor*****>
HandleFault:
            if (NoError == false)
            {
                //ErrorTextBlock.Text = "Error sensor!";
                //ErrorTextBlock.Foreground = new SolidColorBrush(Colors.Red);
                ErrorTextBlock.Text       = "Sensor: Searching...";
                ErrorTextBlock.Foreground = new SolidColorBrush(Colors.DarkGreen);
                //characteristic2.ValueChanged -= Characteristic_ValueChanged;
                TimerConnectToSensor.Start();
                //return;
            }
            else
            {
                ErrorTextBlock.Text = "Sensor: Found.";
                //Debug.WriteLine("3 sensor is " + cadence.ConnectionStatus.ToString());
                ErrorTextBlock.Foreground = new SolidColorBrush(Colors.DarkGreen);
                localSettings.Values["StorageBluetoothAddress"] = cadence.DeviceId; //save to harddisk
                //<begincode*****get the value of the cadence counter and te time between two measurements*****>
                cadence.ConnectionStatusChanged += Cadence_ConnectionStatusChanged;
                //<endcode*****get the value of the cadence counter and te time between two measurements*****>
            }
        }
예제 #21
0
파일: Connector.cs 프로젝트: Budochka/Robot
        //connect to bluetooth device
        public bool Connect()
        {
            try
            {
                var device = AsyncHelpers.RunSync(() => BluetoothLEDevice.FromBluetoothAddressAsync(ConnectionConstants.AdreessLEGO).AsTask());
                if (device != null)
                {
                    if (device.DeviceInformation.Pairing.IsPaired == false)
                    {
                        /* Optional Below - Some examples say use FromIdAsync
                         * to get the device. I don't think that it matters.   */
                        var did = device.DeviceInformation.Id; //I reuse did to reload later.
                        device.Dispose();
                        device = null;
                        device = AsyncHelpers.RunSync(() => BluetoothLEDevice.FromIdAsync(did).AsTask());
                        /* end optional */
                        var handlerPairingRequested = new TypedEventHandler <DeviceInformationCustomPairing, DevicePairingRequestedEventArgs>(handlerPairingReq);
                        device.DeviceInformation.Pairing.Custom.PairingRequested += handlerPairingRequested;
                        LoggerHelper.Instance.Debug("Paired to device");

                        var prslt = AsyncHelpers.RunSync(() => device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None).AsTask());
                        LoggerHelper.Instance.Debug($"Custom PAIR complete status: {prslt.Status}, Connection Status: {device.ConnectionStatus}");

                        device.DeviceInformation.Pairing.Custom.PairingRequested -= handlerPairingRequested; //Don't need it anymore once paired.

                        if (prslt.Status != DevicePairingResultStatus.Paired)
                        {
                            //This should not happen. If so we exit to try again.
                            LoggerHelper.Instance.Debug("prslt exiting.  prslt.status=" + prslt.Status); // so the status may have updated.  lets drop out of here and get the device again.  should be paired the 2nd time around?
                            return(false);
                        }
                    }

                    _bluetoothLEDevice = device;

                    //get the Lego Boost service
                    var services = AsyncHelpers.RunSync(()
                                                        => device.GetGattServicesForUuidAsync(Guid.Parse(ConnectionConstants.ServiceUUID)).AsTask());
                    if (services.Services.Count > 0)
                    {
                        //there is should be only one service with such UUID
                        _deviceService = services.Services[0];
                        //get the characteristic
                        var characteristics = AsyncHelpers.RunSync(()
                                                                   => _deviceService.GetCharacteristicsForUuidAsync(Guid.Parse(ConnectionConstants.CharacteristicUUID)).AsTask());
                        if (characteristics.Characteristics.Count > 0)
                        {
                            //there is should be only one characteristic with such UUID
                            _characteristic = characteristics.Characteristics[0];
                            GattCharacteristicProperties properties = _characteristic.CharacteristicProperties;
                            LoggerHelper.Instance.Debug("Characteristic properties:");
                            foreach (GattCharacteristicProperties property in Enum.GetValues(typeof(GattCharacteristicProperties)))
                            {
                                if (properties.HasFlag(property))
                                {
                                    LoggerHelper.Instance.Debug($"{property} ");
                                }
                            }
                            LoggerHelper.Instance.Debug("Connector::Connect characteristic created");

                            //subscribe to the GATT characteristic notification
                            var status = AsyncHelpers.RunSync(() =>
                                                              _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify).AsTask());

                            if (status == GattCommunicationStatus.Success)
                            {
                                LoggerHelper.Instance.Debug("Subscribing to the Indication/Notification");
                                _characteristic.ValueChanged += DataCharacteristic_ValueChanged;
                            }
                            else
                            {
                                LoggerHelper.Instance.Debug($"Connetor::Connect set notification failed: {status}");
                                throw new Exception("Connetor::Connect set notification failed");
                            }

                            return(true);
                        }

                        LoggerHelper.Instance.Debug("Connector::Connect characteristic not found");
                        return(false);
                    }

                    LoggerHelper.Instance.Debug("Connector::Connect service not found");
                    return(false);
                }

                LoggerHelper.Instance.Debug("Connector::Connect device not found");
                return(false);
            }
            catch (Exception e)
            {
                //0x800710df - ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on
                if ((uint)e.HResult == 0x800710df)
                {
                    var s = "ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on";
                    LoggerHelper.Instance.Error(s);
                    throw (new Exception(s, e));
                }
                throw;
            }
        }
예제 #22
0
        /// <summary>
        /// Read a readable sensor characteristic, typically the Data characteristic
        /// </summary>
        /// <param name="character">The characteristic to read from.</param>
        /// <returns>Buffer for data. Is created in the call</returns>
        public async Task <byte[]> ReadSensorBase(ServiceCharacteristicsEnum character)
        {
            byte[] bytes = null;
            Debug.WriteLine("Begin ReadSensorBase: " + SensorIndex.ToString());
            bool ret = false;

            try
            {
                if (GattService != null)
                {
                    bytes = new byte[DataLength[(int)SensorIndex]];
                    GattCharacteristic           characteristic = null;
                    GattCharacteristicProperties flag           = GattCharacteristicProperties.Read;
                    switch (character)
                    {
                    case ServiceCharacteristicsEnum.Data:
                        characteristic = this.Data;
                        break;

                    case ServiceCharacteristicsEnum.Notification:
                        characteristic = this.Notification;
                        break;

                    case ServiceCharacteristicsEnum.Configuration:
                        characteristic = this.Configuration;
                        break;

                    case ServiceCharacteristicsEnum.Period:
                        characteristic = this.GattCharacteristicPeriod;
                        break;

                    case ServiceCharacteristicsEnum.Address:
                        characteristic = this.Address;
                        break;

                    case ServiceCharacteristicsEnum.Device_Id:
                        characteristic = this.Device_Id;
                        break;
                    }
                    if (characteristic != null)
                    {
                        if (characteristic.CharacteristicProperties.HasFlag(flag))
                        {
                            GattReadResult result = null;
                            try
                            {
                                result = await characteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Error-1: ReadSensorBase(): " + SensorIndex.ToString() + " " + ex.Message);
                                result = await characteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Cached);
                            }
                            if (result != null)
                            {
                                var status = result.Status;
                                if (status == GattCommunicationStatus.Success)
                                {
                                    ret = true;
                                    var dat = result.Value;
                                    var xx  = dat.GetType();
                                    var yy  = dat.Capacity;
                                    var zz  = dat.Length;

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

                                    Windows.Storage.Streams.DataReader.FromBuffer(result.Value).ReadBytes(bytes);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: ReadSensorBase(): " + SensorIndex.ToString() + " " + ex.Message);
            }
            Debug.WriteLine("End ReadSensorBase: " + SensorIndex.ToString());
            if (!ret)
            {
                bytes = null;
            }
            return(bytes);
        }
예제 #23
0
파일: FormLCD.cs 프로젝트: bleckers/DoMSnif
        private async void GetBytesAsync()
        {
            Guid guid      = new Guid("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); // Base UUID for UART service
            Guid charachID = new Guid("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); // RX characteristic UUID

            var Services = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(guid), null);

            BluetoothUARTService = await GattDeviceService.FromIdAsync(Services[0].Id);

            while (BluetoothUARTService == null)
            {
            }
            gattCharacteristic = BluetoothUARTService.GetCharacteristics(charachID)[0];

            try
            {
                GattReadResult result = await gattCharacteristic.ReadValueAsync();

                GattCharacteristicProperties properties = gattCharacteristic.CharacteristicProperties;
                if (properties.HasFlag(GattCharacteristicProperties.Read))
                {
                    //Console.WriteLine("This characteristic supports reading from it.");
                }
                if (properties.HasFlag(GattCharacteristicProperties.Write))
                {
                    //Console.WriteLine("This characteristic supports writing.");
                }
                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                {
                    //Console.WriteLine("This characteristic supports subscribing to notifications.");
                }
                try
                {
                    //Write the CCCD in order for server to send notifications.
                    var notifyResult = await gattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                        GattClientCharacteristicConfigurationDescriptorValue.Notify);

                    if (notifyResult == GattCommunicationStatus.Success)
                    {
                        //Console.WriteLine("Successfully registered for notifications");
                        this.Invoke((MethodInvoker) delegate
                        {
                            toolStripStatusLabel.Text = "Connected";

                            //Turn on, since it's off by default and we could be mid transaction at this point.
                            LCD.DisplayOn();
                        });
                    }
                    else
                    {
                        Console.WriteLine($"Error registering for notifications: {notifyResult}");
                        this.Invoke((MethodInvoker) delegate
                        {
                            try
                            {
                                dataProcess.Abort();
                            }
                            catch (Exception ex) { }

                            checkBoxSlow.Enabled = true;

                            buttonRun.Text            = "Run";
                            toolStripStatusLabel.Text = "Connection Failed!";
                            try
                            {
                                BluetoothUARTService.Dispose();
                            }
                            catch (Exception ex) { }
                        });
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine(ex.Message);
                    this.Invoke((MethodInvoker) delegate
                    {
                        try
                        {
                            dataProcess.Abort();
                        }
                        catch (Exception ex2) { }
                        buttonRun.Text            = "Run";
                        checkBoxSlow.Enabled      = true;
                        toolStripStatusLabel.Text = "Connection Failed!";
                        try
                        {
                            BluetoothUARTService.Dispose();
                        }
                        catch (Exception ex2) { }
                    });
                }

                gattCharacteristic.ValueChanged += Charac_ValueChangedAsync;
            }
            catch (Exception blue) { }
            // }
        }
예제 #24
0
        private async Task RegisterForValueChangeEventsAsync(GattDeviceService service, Guid guid)
        {
            try
            {
                var res = await service.GetCharacteristicsForUuidAsync(guid);

                if (res.Status == GattCommunicationStatus.Success)
                {
                    GattCharacteristic characteristic = res.Characteristics.FirstOrDefault();

                    if (characteristic == null)
                    {
                        OnError("Characteristic " + guid + " not available");
                        return;
                    }

                    GattCharacteristicProperties properties = characteristic.CharacteristicProperties;


                    Debug.WriteLine("Characteristic {0} supports: ", guid.ToString("b"));
                    if ((properties & GattCharacteristicProperties.Broadcast) != 0)
                    {
                        Debug.WriteLine("    Broadcast");
                    }
                    if ((properties & GattCharacteristicProperties.Read) != 0)
                    {
                        Debug.WriteLine("    Read");
                    }
                    if ((properties & GattCharacteristicProperties.WriteWithoutResponse) != 0)
                    {
                        Debug.WriteLine("    WriteWithoutResponse");
                    }
                    if ((properties & GattCharacteristicProperties.Write) != 0)
                    {
                        Debug.WriteLine("    Write");
                    }
                    if ((properties & GattCharacteristicProperties.Notify) != 0)
                    {
                        Debug.WriteLine("    Notify");
                    }
                    if ((properties & GattCharacteristicProperties.Indicate) != 0)
                    {
                        Debug.WriteLine("    Indicate");
                    }
                    if ((properties & GattCharacteristicProperties.AuthenticatedSignedWrites) != 0)
                    {
                        Debug.WriteLine("    AuthenticatedSignedWrites");
                    }
                    if ((properties & GattCharacteristicProperties.ExtendedProperties) != 0)
                    {
                        Debug.WriteLine("    ExtendedProperties");
                    }
                    if ((properties & GattCharacteristicProperties.ReliableWrites) != 0)
                    {
                        Debug.WriteLine("    ReliableWrites");
                    }
                    if ((properties & GattCharacteristicProperties.WritableAuxiliaries) != 0)
                    {
                        Debug.WriteLine("    WritableAuxiliaries");
                    }

                    if ((properties & GattCharacteristicProperties.Notify) != 0)
                    {
                        try
                        {
                            characteristic.ValueChanged -= OnCharacteristicValueChanged;
                        }
                        catch { }

                        await EnableNotification(characteristic);
                    }
                    else
                    {
                        OnError("Registering for notification on characteristic that doesn't support notification: " + guid);
                    }
                }
            }
            catch (Exception ex)
            {
                OnError("Unhandled exception registering for notifications. " + ex.Message);
            }
        }
예제 #25
0
        public IGattCharacteristicBuilder SetRead(Func <ReadRequest, ReadResult> request, bool encrypted = false)
        {
            this.properties |= GattCharacteristicProperties.Read;

            return(this);
        }
예제 #26
0
 public IGattCharacteristicBuilder SetProperties(GattCharacteristicProperties properties)
 {
     Properties = properties;
     return(this);
 }
예제 #27
0
        public static async Task <byte[]> ReadProperty(SensorTagProperties property, bool showStartEndMsg)
        {
            //if (showStartEndMsg)
            Debug.WriteLine("Begin read property: {0} ", property);
            string guidstr = "";

            byte[] bytes = null;
            switch (property)
            {
            case SensorTagProperties.FirmwareDate:
                guidstr = UUID_PROPERTY_FW_NR;
                break;

            case SensorTagProperties.HardwareRevision:
                guidstr = UUID_PROPERTY_HW_NR;
                break;

            case SensorTagProperties.ManufacturerId:
                guidstr = UUID_PROPERTY_MANUF_NR;
                break;

            case SensorTagProperties.ModelName:
                guidstr = UUID_PROPERTY_MODEL_NR;
                break;

            case SensorTagProperties.PNPId:
                guidstr = UUID_PROPERTY_PNP_ID;
                break;

            case SensorTagProperties.SerialNumber:
                guidstr = UUID_PROPERTY_SERIAL_NR;
                break;

            case SensorTagProperties.SoftwareRevision:
                guidstr = UUID_PROPERTY_SW_NR;
                break;

            case SensorTagProperties.SysId:
                guidstr = UUID_PROPERTY_SYSID;
                break;

            case SensorTagProperties.BTSigCertification:
                guidstr = UUID_PROPERTY_CERT;
                break;

            case SensorTagProperties.DeviceName:
                guidstr = UUID_PROPERTY_NAME;
                break;

            case SensorTagProperties.BatteryLevel:
                return(bytes);
            }

            IReadOnlyList <GattCharacteristic> sidCharacteristicList = DevicePropertyService.GetCharacteristics(new Guid(guidstr));
            GattCharacteristicProperties       flag = GattCharacteristicProperties.Read;

            if (sidCharacteristicList != null)
            {
                if (sidCharacteristicList.Count != 0)
                {
                    GattCharacteristic characteristic = sidCharacteristicList[0];
                    if (characteristic.CharacteristicProperties.HasFlag(flag))
                    {
                        try
                        {
                            GattReadResult result = null;
                            try
                            {
                                result = await characteristic.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
                            }
                            catch (Exception ex)
                            {
                                string msg = ex.Message;
                                Debug.WriteLine("Error ReadProperty1(): " + msg);
                            }

                            var status = result.Status;
                            if (status == GattCommunicationStatus.Success)
                            {
                                var dat = result.Value;
                                var xx  = dat.GetType();
                                var yy  = dat.Capacity;
                                var zz  = dat.Length;

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

                                Windows.Storage.Streams.DataReader.FromBuffer(result.Value).ReadBytes(bytes);
                                IncProgressCounter();
                            }
                        }

                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            Debug.WriteLine("Error ReadProperty2(): " + msg);
                        }
                    }
                }
            }
            //if(showStartEndMsg)
            Debug.WriteLine("End read property: {0} ", property);

            return(bytes);
        }
예제 #28
0
        public Program()
        {
            // Create Bluetooth Listener
            var watcher = new BluetoothLEAdvertisementWatcher();

            //watcher.AdvertisementFilter.BytePatterns
            // Query for extra properties you want returned
            //string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

            watcher.ScanningMode = BluetoothLEScanningMode.Active;

            watcher.AdvertisementFilter.Advertisement.LocalName = "Bangle.js 23b0";
            //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(new Guid("6e400001b5a3f393e0a9e50e24dcca9e"));
            //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(new Guid("6e400002b5a3f393e0a9e50e24dcca9e"));
            //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(new Guid("6e400003b5a3f393e0a9e50e24dcca9e"));

            // Only activate the watcher when we're recieving values >= -80
            // watcher.SignalStrengthFilter.InRangeThresholdInDBm = -99;

            // Stop watching if the value drops below -90 (user walked away)
            //watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -10;

            // Register callback for when we see an advertisements
            // watcher.Received += OnAdvertisementReceived;

            // Wait 5 seconds to make sure the device is really out of range
            watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
            watcher.SignalStrengthFilter.SamplingInterval  = TimeSpan.FromMilliseconds(2000);

            // Starting watching for advertisements


            watcher.Received += async(w, btAdv) => {
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);

                Debug.WriteLine($"BLEWATCHER Found: {device.DeviceInformation.Name}");

                // SERVICES!!
                var gatt = device.GattServices.FirstOrDefault();
                //Debug.WriteLine($"{device.Name} Services: {gatt.`.Count}, {gatt.Status}, {gatt.ProtocolError}");

                //// CHARACTERISTICS!!
                //var characs = device.GattServices.Single(s => s.Uuid == new Guid("6e400003b5a3f393e0a9e50e24dcca9e")).GetCharacteristics(new Guid("6e400003b5a3f393e0a9e50e24dcca9e"));
                var characs2 = device.GattServices.Single(s => s.Uuid == new Guid("6e400001b5a3f393e0a9e50e24dcca9e"));


                var cah2 = characs2.GetCharacteristics(new Guid("6e400002b5a3f393e0a9e50e24dcca9e"));

                GattCharacteristic           vvv        = cah2.FirstOrDefault();
                GattCharacteristicProperties properties = vvv.CharacteristicProperties;

                //var charac = characs.Single(c => c.Uuid == SAMPLECHARACUUID);


                var writer = new DataWriter();
                writer.WriteString("LED1.reset();\n");
                var res = await vvv.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);

                //writer.WriteString("LED2.set();\n");
                //res = await vvv.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
            };


            watcher.Start();
        }
예제 #29
0
        private async Task <bool> WriteSensor(byte[] bytes, ServiceCharacteristicsEnum characteristicEnum)
        {
            bool ret = false;

            Debug.WriteLine("Begin WriteSensor: " + SensorIndex.ToString());
            try
            {
                if (GattService != null)
                {
                    GattCharacteristic           characteristic = null;
                    GattCharacteristicProperties flag           = GattCharacteristicProperties.Write;
                    switch (characteristicEnum)
                    {
                    case ServiceCharacteristicsEnum.Data:
                        characteristic = this.Data;
                        break;

                    case ServiceCharacteristicsEnum.Notification:
                        flag           = GattCharacteristicProperties.Notify;
                        characteristic = this.Notification;
                        break;

                    case ServiceCharacteristicsEnum.Configuration:
                        characteristic = this.Configuration;
                        break;

                    case ServiceCharacteristicsEnum.Period:
                        characteristic = this.GattCharacteristicPeriod;
                        break;

                    case ServiceCharacteristicsEnum.Address:
                        characteristic = this.Address;
                        break;

                    case ServiceCharacteristicsEnum.Device_Id:
                        characteristic = this.Device_Id;
                        break;
                    }
                    if (characteristic != null)
                    {
                        if (characteristic.CharacteristicProperties.HasFlag(flag))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            writer.WriteBytes(bytes);

                            var status = await characteristic.WriteValueAsync(writer.DetachBuffer());

                            if (status == GattCommunicationStatus.Success)
                            {
                                ret = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: WriteSensor(): " + SensorIndex.ToString() + " " + ex.Message);
            }
            Debug.WriteLine("End WriteSensor " + SensorIndex.ToString());
            return(ret);
        }
        private void EnableCharacteristicPanels(GattCharacteristicProperties properties)
        {
            // BT_Code: Hide the controls which do not apply to this characteristic.
            SetVisibility(CharacteristicReadPanel, properties.HasFlag(GattCharacteristicProperties.Read));

            SetVisibility(CharacteristicWritePanel,
                properties.HasFlag(GattCharacteristicProperties.Write) ||
                properties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse));
            CharacteristicWriteValue.Text = "";

            SetVisibility(CharacteristicIndicatePanel, properties.HasFlag(GattCharacteristicProperties.Indicate));
            SetVisibility(CharacteristicNotifyPanel, properties.HasFlag(GattCharacteristicProperties.Notify));

            CharacteristicLatestValue.Text = "";
        }
예제 #31
0
        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            if (eventArgs.Advertisement.LocalName.Trim() == "")
            {
                //Debug.WriteLine("Something wrong");
                return;
            }
            var address = eventArgs.BluetoothAddress;

            //Int16 rssi = eventArgs.RawSignalStrengthInDBm;

            //if (address.Equals(== "219300284384772")
            //Debug.WriteLine(rssi + " " + buf + " " + address + " " + localName);
            // -56 C773D38CC604 219300284384772

            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(address);

            if (device != null && !bFoundDev)
            {
                deviceFoundMilis = stopwatch.ElapsedMilliseconds;
                Debug.WriteLine("Device found in " + deviceFoundMilis + " ms");
                bFoundDev = true;

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
                    //UI code here
                    textBlock1.Text = "Device ID : " + device.DeviceId;
                });


                Int16 rssi = eventArgs.RawSignalStrengthInDBm;
                //Debug.WriteLine("Signalstrengt = " + rssi + " DBm");
                string localName         = eventArgs.Advertisement.LocalName;
                String buf               = String.Format("{0:X}", address);
                var    advertisementType = eventArgs.AdvertisementType;
                Debug.WriteLine(rssi + " " + buf + " " + address + " " + localName + " " + advertisementType);


                var result = await device.GetGattServicesForUuidAsync(MyService_GUID);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    connectedMilis = stopwatch.ElapsedMilliseconds;
                    Debug.WriteLine("Connected in " + (connectedMilis - deviceFoundMilis) + " ms");
                    var services = result.Services;

                    if (services.Count > 0)
                    {
                        service = services[0];
                    }


                    if (service != null)
                    {
                        serviceFoundMilis = stopwatch.ElapsedMilliseconds;
                        Debug.WriteLine("Service found in " +
                                        (serviceFoundMilis - connectedMilis) + " ms");

                        var charResult = await service.GetCharacteristicsForUuidAsync(MYCharacteristic_GUID);

                        if (charResult.Status == GattCommunicationStatus.Success)
                        {
                            charac = charResult.Characteristics[0];

                            if (charac != null)
                            {
                                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
                                    textBlock2.Text = charac.Uuid.ToString().ToUpper();
                                });

                                characteristicFoundMilis = stopwatch.ElapsedMilliseconds;
                                Debug.WriteLine("Characteristic found in " +
                                                (characteristicFoundMilis - serviceFoundMilis) + " ms");

                                var    descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.None;
                                string descriptor      = string.Empty;

                                GattCharacteristicProperties properties = charac.CharacteristicProperties;

                                if (properties.HasFlag(GattCharacteristicProperties.Read))
                                {
                                    Debug.WriteLine("This characteristic supports reading .");
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.Write))
                                {
                                    Debug.WriteLine("This characteristic supports writing .");
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
                                {
                                    Debug.WriteLine("This characteristic supports writing  whithout responce.");
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.Notify)) // this case !
                                {
                                    descriptor      = "notifications";
                                    descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
                                    Debug.WriteLine("This characteristic supports subscribing to notifications.");
                                }
                                if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    descriptor      = "indications";
                                    descriptorValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
                                    Debug.WriteLine("This characteristic supports subscribing to Indication");
                                }
                                try
                                {
                                    var descriptorWriteResult = await charac.WriteClientCharacteristicConfigurationDescriptorAsync(descriptorValue);

                                    if (descriptorWriteResult == GattCommunicationStatus.Success)
                                    {
                                        WriteDescriptorMilis = stopwatch.ElapsedMilliseconds;
                                        Debug.WriteLine("Successfully registered for " + descriptor + " in " +
                                                        (WriteDescriptorMilis - characteristicFoundMilis) + " ms");
                                        charac.ValueChanged += Charac_ValueChanged;
                                    }
                                    else
                                    {
                                        Debug.WriteLine($"Error registering for " + descriptor + ": {result}");
                                        device.Dispose();
                                        device = null;
                                        watcher.Start();//Start watcher again for retry
                                    }
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    Debug.WriteLine(ex.Message);
                                }
                                Debug.WriteLine("---------------------------");
                            }

                            else
                            {
                                Debug.WriteLine("No characteristics  found");
                            }
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No services found");
                    }
                }
                else
                {
                    Debug.WriteLine("No device found");
                }


                //Debug.WriteLine("Advertisement type = " + advertisementType);
            }
        }