Пример #1
0
        public async void SendTestData(List<DeviceInformation> parrotDevices)
        {
            DeviceInformation motorDevice = null;
            foreach (var device in parrotDevices)
            {
                Debug.WriteLine("device " + device.Id);

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

                try
                {

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

        }
Пример #2
0
 public static void DeviceService(GattDeviceService service)
 {
     Console.WriteLine($"Service: {service.AttributeHandle} - {service.Uuid}");
     foreach (var characteristic in service.GetAllCharacteristics())
     {
         Characteristic(characteristic);
     }
 }
Пример #3
0
 /// <summary>
 /// Get all characteristics of the defined service.
 /// </summary>
 /// <param name="service"></param>
 /// <returns>characteristic list</returns>
 public List <string> getCharacteristicList(GattDeviceService service)
 {
     foreach (var characteristic in service.GetAllCharacteristics())
     {
         characteristicList.Add(characteristic.Uuid.ToString());
     }
     return(characteristicList);
 }
Пример #4
0
        public void Test02()
        {
            if (_service == null)
            {
                return;
            }
            var cs = _service.GetAllCharacteristics();

            byte[] commandToWrite = { 4, 1, 2, 0, 1, 0 };
            SendCommandToAllChar(cs, commandToWrite);
            _settingsCounter++;
        }
Пример #5
0
        /// <summary>
        /// Loads characteristics when GATT service is selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void lstGattServices_Tapped(object sender, TappedRoutedEventArgs e)
        {
            await Task.Delay(1);

            lstCharacteristics.Items.Clear();
            GattDeviceService selectedService = (lstGattServices.SelectedItem as MyGattService).GattDeviceService;

            foreach (var characteristic in selectedService.GetAllCharacteristics())
            {
                lstCharacteristics.Items.Add(characteristic.UserDescription + " " + characteristic.Uuid);
            }
        }
Пример #6
0
        public IReadOnlyList <GattCharacteristic> GetCharacteristics(GattDeviceService service)
        {
            try
            {
                return(service.GetAllCharacteristics());
            }
            catch (System.IO.FileLoadException)
            {
                MessageBox.Show("Seems like Device is already in use.", "Wait Sparky!!!");
            }

            return(Array.Empty <GattCharacteristic>());
        }
Пример #7
0
        private void GetGattCharacteristicsForGPSService()
        {
            IReadOnlyList <GattCharacteristic> characteristicList =
                _gnGPSservice.GetAllCharacteristics();

            foreach (GattCharacteristic characteristic in characteristicList)
            {
                if (characteristic.Uuid == Guid.Parse(IHSUuids.AllInOne))
                {
                    _gpsAllInOneCharacteristic = characteristic;

                    System.Diagnostics.Debug.WriteLine(
                        "GetGattCharacteristicsForGPSService(): GPS GATT characteristic properties: "
                        + _accelerometerCharacteristic.CharacteristicProperties);
                }
            }
        }
Пример #8
0
        private async void _watcher_Received2(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            var bleServiceUUIDs = args.Advertisement.ServiceUuids;

            foreach (var uuidone in bleServiceUUIDs)
            {
                Debug.WriteLine(uuidone);
                //
                if (uuidone == new Guid("0000fe9a-0000-1000-8000-00805f9b34fb")) //generic attribute
                {
                    Debug.WriteLine("Custom UUID of Estimote");
                    BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    //GattDeviceService service = dev.GetGattService(new Guid("00001809-0000-1000-8000-00805f9b34fb"));
                    Debug.WriteLine("-------------------------------------");
                }
                else if (uuidone == new Guid("00001800-0000-1000-8000-00805f9b34fb")) //generic access
                {
                    Debug.WriteLine("generic access");
                    Debug.WriteLine("-------------------------------------");
                }
                else if (uuidone == new Guid("00001801-0000-1000-8000-00805f9b34fb")) //generic attribute
                //https://gist.github.com/sam016/4abe921b5a9ee27f67b3686910293026
                {
                    this.watcher.Stop();
                    Debug.WriteLine("generic attribute");
                    Debug.WriteLine("-------------------------------------");
                    //BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
                    //GattDeviceService service = dev.GetGattService(new Guid("00001809-0000-1000-8000-00805f9b34fb"));

                    // service
                }
                //https://learn.adafruit.com/introducing-adafruit-ble-bluetooth-low-energy-friend/uart-service
                else if (uuidone == new Guid("6e400001-b5a3-f393-e0a9-e50e24dcca9e"))
                {
                    Debug.WriteLine("UART Service. his service simulates a basic UART connection over two lines, TXD and RXD.");

                    BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    GattDeviceService service = dev.GetGattService(uuidone);
                    var characteristics       = service.GetAllCharacteristics();

                    Debug.WriteLine("-------------------------------------");
                }
            }
        }
Пример #9
0
        private GattCharacteristic GetCharacteristicData(GattDeviceService service, string characteristicUuidString)
        {
            GattCharacteristic characteristic = null;

            try
            {
                characteristic = service.GetAllCharacteristics().Single(
                    c => c.Uuid == new Guid(wantedCharacteristicUuidString));
            }
            catch
            {
                Exception e = new Exception("Retrieving bluetooth GATT characteristic data failed");
                throw e;
            }

            return(characteristic);
        }
Пример #10
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var bts = await DeviceInformation.FindAllAsync();

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

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

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

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

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

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

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch
            {
            }
        }
Пример #11
0
        /// <summary>
        /// Resolves the battery information.
        /// </summary>
        public async Task ReadDeviceBatteryInformationAsync()
        {
            if (_batteryInfoService != null)
            {
                IReadOnlyList <GattCharacteristic> characteristicList = _batteryInfoService.GetAllCharacteristics();

                foreach (var characteristic in characteristicList)
                {
                    if (characteristic.Uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.BatteryLevel))
                    {
                        GattReadResult readResult = await characteristic.ReadValueAsync();

                        byte[] data = WindowsRuntimeBufferExtensions.ToArray(readResult.Value);
                        // TODO: Store value
                    }
                }
            }
        }
Пример #12
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
            await progressbar.ShowAsync();

            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(GattDeviceService)))
            {
                _service = ((GattDeviceService)e.Parameter);
                this.lblDeviceName.Text     = _service.Device.Name;
                this.lblServiceName.Text    = (string)_conv.Convert(_service.Uuid, typeof(string), null, null);
                this.lblServiceAddress.Text = _service.Uuid.ToString();

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


                    if (((int)c.CharacteristicProperties & (int)GattCharacteristicProperties.Read) != 0)
                    {
                        try
                        {
                            GattReadResult readResult = await c.ReadValueAsync();

                            if (readResult.Status == GattCommunicationStatus.Success)
                            {
                                val.Value = new byte[readResult.Value.Length];
                                DataReader.FromBuffer(readResult.Value).ReadBytes(val.Value);
                            }
                        }
                        catch { }
                    }
                    _characteristics.Add(val);
                }

                lstCharacteristics.ItemsSource = _characteristics;
            }

            this.navigationHelper.OnNavigatedTo(e);
            await progressbar.HideAsync();
        }
Пример #13
0
        async Task ReadDeviceInformation(GattDeviceService genericAccess)
        {
            var characteristics = genericAccess.GetAllCharacteristics();

            foreach (var characteristic in characteristics)
            {
                if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                {
                    var description = await GetDescription(characteristic) ?? GATTDefaultCharacteristic.Find(characteristic.Uuid)?.Description ?? characteristic.Uuid.ToString();

                    var result = await characteristic.ReadValueAsync();

                    var value = GetString(result.Value);
                    if (!this.properties.ContainsKey(description))
                    {
                        this.properties.Add(description, value);
                    }
                }
            }
        }
Пример #14
0
        private void GetGattCharacteristicsForImuService()
        {
            IReadOnlyList <GattCharacteristic> characteristicList =
                _gnImuService.GetAllCharacteristics();

            foreach (GattCharacteristic characteristic in characteristicList)
            {
                if (characteristic.Uuid == Guid.Parse(IHSUuids.AccVector))
                {
                    _accelerometerCharacteristic = characteristic;

                    System.Diagnostics.Debug.WriteLine(
                        "GetGattCharacteristicsForSensors(): Accelerometer GATT characteristic properties: "
                        + _accelerometerCharacteristic.CharacteristicProperties);
                }
                else if (characteristic.Uuid == Guid.Parse(IHSUuids.ComboHpr))
                {
                    _comboHprCharacteristic = characteristic;

                    System.Diagnostics.Debug.WriteLine(
                        "GetGattCharacteristicsForSensors(): Gyro GATT characteristic properties: "
                        + _comboHprCharacteristic.CharacteristicProperties);
                }
                else if (characteristic.Uuid == Guid.Parse(IHSUuids.Calibration))
                {
                    _magnetometerCalibrationCharacteristic = characteristic;

                    System.Diagnostics.Debug.WriteLine(
                        "GetGattCharacteristicsForSensors(): Magnetometer calibration GATT characteristic properties: "
                        + _magnetometerCalibrationCharacteristic.CharacteristicProperties);
                }
                else if (characteristic.Uuid == Guid.Parse(IHSUuids.MagVector))
                {
                    _magnetometerCharacteristic = characteristic;

                    System.Diagnostics.Debug.WriteLine(
                        "GetGattCharacteristicsForSensors(): Magnetometer GATT characteristic properties: "
                        + _magnetometerCharacteristic.CharacteristicProperties);
                }
            }
        }
Пример #15
0
        public async void SendTestData(List <DeviceInformation> parrotDevices)
        {
            DeviceInformation motorDevice = null;

            foreach (var device in parrotDevices)
            {
                Debug.WriteLine("device " + device.Id);

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

                if (null == _service)
                {
                    return;
                }

                try
                {
                    //var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors);
                    var characteristics = _service.GetAllCharacteristics();
                    TakeOff(characteristics);
                    var res = await Motors(false, 0, 0, 0, 0, 0.0f, 18, characteristics);

                    if (!res)
                    {
                        continue;
                    }
                    res = await Motors(true, 0, 100, 0, 0, 0.0f, 6, characteristics);

                    if (res)
                    {
                        continue;
                    }
                    EmergencyStop(characteristics);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Resolves the device information.
        /// </summary>
        public async Task ReadDeviceInformationAsync()
        {
            if (_deviceInfoService != null)
            {
                IReadOnlyList <GattCharacteristic> characteristicList =
                    _deviceInfoService.GetAllCharacteristics();

                foreach (var characteristic in characteristicList)
                {
                    Guid           uuid       = characteristic.Uuid;
                    GattReadResult readResult = await characteristic.ReadValueAsync();

                    byte[] data = WindowsRuntimeBufferExtensions.ToArray(readResult.Value);

                    if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.SystemId))
                    {
                        // Not implemented
                    }
                    else if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.ModelNumber))
                    {
                        _deviceInfo.ModelNumber = Encoding.UTF8.GetString(data);
                    }
                    else if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.SerialNumber))
                    {
                        _deviceInfo.SerialNumber = Encoding.UTF8.GetString(data);
                    }
                    else if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.FirmwareRevision))
                    {
                        _deviceInfo.FirmwareRevision = Encoding.UTF8.GetString(data);
                    }
                    else if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.HardwareRevision))
                    {
                        _deviceInfo.HardwareRevision = Encoding.UTF8.GetString(data);
                    }
                    else if (uuid == GattCharacteristic.ConvertShortIdToUuid(IHSUuids.SoftwareRevision))
                    {
                        _deviceInfo.SoftwareRevision = Encoding.UTF8.GetString(data);
                    }
                }
            }
        }
Пример #17
0
        private void ListServices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GattDeviceService service = (GattDeviceService)listServices.SelectedItem;
            var characteristics       = service.GetAllCharacteristics();

            if (characteristics.Count > 0)
            {
                foreach (var characteristic in characteristics)
                {
                    if (MicroBits.UUIDToName(characteristic.Uuid) != null)
                    {
                        listCharacteristic.Items.Add(characteristic);
                    }
                }
                showChracteristicsList();
            }
            else
            {
                Console.WriteLine("No services found");
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
            await progressbar.ShowAsync();
            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(GattDeviceService)))
            {
                _service = ((GattDeviceService)e.Parameter);
                this.lblDeviceName.Text = _service.Device.Name;
                this.lblServiceName.Text = (string)_conv.Convert(_service.Uuid, typeof(string), null, null);
                this.lblServiceAddress.Text = _service.Uuid.ToString();

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


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

                lstCharacteristics.ItemsSource = _characteristics;
            }

            this.navigationHelper.OnNavigatedTo(e);
            await progressbar.HideAsync();
        }
Пример #19
0
        /// <summary>
        /// Resolves the nonce value from the connected headset.
        /// </summary>
        /// <returns>True, if successful. False otherwise.</returns>
        private async Task <bool> ReadDeviceGnSystemServiceAsync()
        {
            bool success = false;

            if (IsInitialized)
            {
                IReadOnlyList <GattCharacteristic> characteristicList = _gnSystemService.GetAllCharacteristics();

                foreach (var characteristic in characteristicList)
                {
                    if (characteristic.Uuid == Guid.Parse(IHSUuids.Nonce))
                    {
                        GattReadResult readResult = await characteristic.ReadValueAsync(BluetoothCacheMode.Uncached);

                        byte[] data = WindowsRuntimeBufferExtensions.ToArray(readResult.Value);
                        _nonce  = BitConverter.ToUInt32(data, 0);
                        success = true;
                    }
                }
            }

            return(success);
        }
Пример #20
0
        /// <summary>
        /// Writes the command asynchronously to the MW Board.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        internal async Task <GattCommunicationStatus> WriteCommandAsync(byte[] data)
        {
            try
            {
                GattDeviceService service = await GattDeviceService.FromIdAsync(_id);

                var characterisitics = service.GetAllCharacteristics();
                var cmd = characterisitics.Where(c => c.Uuid == COMMAND_UUID).FirstOrDefault();

                GattCharacteristic command = service.GetCharacteristics(COMMAND_UUID)[0];
                byte[]             buf     = data;
                DataWriter         writer  = new DataWriter();
                writer.WriteBytes(buf);
                GattCommunicationStatus st = await command.WriteValueAsync(writer.DetachBuffer());

                return(st);
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(ex.Message);
            }
            return(GattCommunicationStatus.Unreachable);
        }
Пример #21
0
        async Task ReadBatteryService(GattDeviceService deviceService)
        {
            var characteristics = deviceService.GetAllCharacteristics();

            foreach (var characteristic in characteristics)
            {
                var description = await GetDescription(characteristic) ?? "";

                await this.Connect(description, characteristic);

                for (int i = 0; i < this.Fingers.Count; ++i)
                {
                    if (this.HasSensor(i))
                    {
                        this.State |= SensorStates[i];
                    }
                    if (this.HasMotor(i))
                    {
                        this.State |= MotorStates[i];
                    }
                }
            }
        }
Пример #22
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var bts = await DeviceInformation.FindAllAsync();
            const string deviceId = @"\\?\BTHLEDevice#{9a66fa00-0800-9191-11e4-012d1540cb8e}_e0144d4f3d49#a&1f09a1af&0&0020#{6e3bb679-4372-40c8-9eaa-4509df260cd8}";

            var device = bts.First(di => di.Name == DeviceName && di.Id == deviceId);
            if (null == device)
                return;
            _service = await GattDeviceService.FromIdAsync(device.Id);
            if (null == _service)
                return;
            _characteristics = _service.GetAllCharacteristics();
            if (null == _characteristics || _characteristics.Count <= 0)
                return;

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

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

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch
            {
            }

        }
Пример #23
0
        private void getCharacterstics(string id)
        {
            Guid g = new Guid(id);

            currentSvc = bluetoothLeDevice.GetGattService(g);
            IReadOnlyList <GattCharacteristic> chrs = currentSvc.GetAllCharacteristics();

            listView3.Clear();
            listView3.Columns.Add("Characterstic UUID", 150);
            listView3.Columns.Add("Description", 150);
            foreach (GattCharacteristic c in chrs)
            {
                string[]     arr = new string[2];
                ListViewItem itm;
                //add items to ListView
                arr[0] = c.Uuid.ToString();
                arr[1] = c.CharacteristicProperties.ToString();

                itm = new ListViewItem(arr);

                listView3.Items.Add(itm);
            }
            //do nothing
        }
Пример #24
0
        /// <summary>
        /// Authenticates and subscribes to characteristics.
        /// </summary>
        private async Task AuthenticateAndSubscribeToCharacteristicsAsync()
        {
            // Trace.
            Trace("Attempting to authenticate and subscribe to characteristics.");

            // Try to authenticate and subscribe to characteristics.
            try
            {
                // Get the nonce characteristic.
                Guid nonceGuid           = Guid.Parse(Identifiers.Nonce);
                var  nonceCharacteristic = _systemService.GetAllCharacteristics()?.Where(c => c.Uuid == nonceGuid).FirstOrDefault();
                if (nonceCharacteristic == null)
                {
                    // Trace.
                    Trace("Unable to authenticate and subscribe to characteristics. Unable to get NONCE characteristic.");

                    // Throw exception.
                    throw new IntelligentHeadsetSensorPeripheralException(IntelligentHeadsetSensorPeripheralException.ErrorCode.AuthenticateSubscribeFailed,
                                                                          "Unable to authenticate and subscribe to characteristics. Unable to get NONCE characteristic.",
                                                                          null);
                }

                // Read the nonce characteristic value.
                uint           nonce;
                GattReadResult readResult = await nonceCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);

                if (readResult.Status == GattCommunicationStatus.Success && readResult.Value.Length != 0)
                {
                    byte[] data = WindowsRuntimeBufferExtensions.ToArray(readResult.Value);
                    nonce = BitConverter.ToUInt32(data, 0);
                }
                else
                {
                    // Trace.
                    Trace("Unable to authenticate and subscribe to characteristics. Unable to read NONCE characteristic.");

                    // Throw exception.
                    throw new IntelligentHeadsetSensorPeripheralException(IntelligentHeadsetSensorPeripheralException.ErrorCode.AuthenticateSubscribeFailed,
                                                                          "Unable to authenticate and subscribe to characteristics. Unable to read NONCE characteristic.",
                                                                          null);
                }

                // Read the access key characteristic.
                var characteristic = _systemService.GetCharacteristics(Guid.Parse(Identifiers.Key))?.FirstOrDefault();
                if (characteristic == null)
                {
                    // Trace.
                    Trace("Unable to authenticate and subscribe to characteristics. Unable to get IDENTIFIER characteristic.");

                    // Throw exception.
                    throw new IntelligentHeadsetSensorPeripheralException(IntelligentHeadsetSensorPeripheralException.ErrorCode.AuthenticateSubscribeFailed,
                                                                          "Unable to authenticate and subscribe to characteristics. Unable to get IDENTIFIER characteristic.",
                                                                          null);
                }

                // Authenticate.
                uint   authKey            = CalculateAuthenticationKey(nonce);
                byte[] authKeyAsByteArray = BitConverter.GetBytes(authKey);
                await characteristic.WriteValueAsync(authKeyAsByteArray.AsBuffer(), GattWriteOption.WriteWithResponse);

                // Subscribe to the ValueChanged event for the ComboHPR characteristic.
                _comboHprCharacteristic.ValueChanged += ComboHprCharacteristicValueChanged;
                await _comboHprCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                _accelerometerCharacteristic.ValueChanged += Accelerometer_ValueChanged;
                await _accelerometerCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                // Subscribe to the ValueChanged event for AllInOne characteristic.
                _gpsAllInOneCharacteristic.ValueChanged += AllInOneCharacteristicValueChanged;
                await _gpsAllInOneCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
            }
            catch (IntelligentHeadsetSensorPeripheralException)
            {
                throw;
            }
            catch (Exception exception)
            {
                Trace("Unable to authenticate and subscribe to characteristics. Exception was: " + exception.Message);
                throw new IntelligentHeadsetSensorPeripheralException(IntelligentHeadsetSensorPeripheralException.ErrorCode.AuthenticateSubscribeFailed,
                                                                      "Unable to authenticate and subscribe to characteristics.",
                                                                      exception);
            }

            // Trace.
            Trace("Succesfully authenticated and subscribed to characteristics.");
        }
Пример #25
0
        private Dictionary<string, RsCharacteristic> CompletePropsFromServiceChars(GattDeviceService service, string deviceId, Dictionary<string, RsCharacteristic> dicCharacteristics)
        {
            var characteristics = service.GetAllCharacteristics();
            foreach (var characteristic in characteristics)
            {
                var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid);
                Debug.WriteLine(characteristic.Uuid + " - " + charName);
                if (charName == "undefined") continue;

                var rsCharacteristic = new RsCharacteristic
                {
                    Characteristic = characteristic,
                    CharName = charName,
                    DeviceId = deviceId
                };
                dicCharacteristics.Add(charName, rsCharacteristic);

                switch (charName)
                {
                    case "undefined":
                        Undefined = characteristic;
                        break;
                    case "GapDeviceName":
                        GapDeviceName = characteristic;
                        break;
                    case "GapAppearance":
                        GapAppearance = characteristic;
                        break;
                    case "GapPeripheralPreferredConnectionParameters":
                        GapPeripheralPreferredConnectionParameters = characteristic;
                        break;
                    case "GattServiceChanged":
                        GattServiceChanged = characteristic;
                        break;
                    case "Parrot_TourTheStairsParrotA01":
                        TourTheStairsParrotA01 = characteristic;
                        break;
                    case "Parrot_Stop":
                        Stop = characteristic;
                        break;
                    case "Parrot_PowerMotors":
                        PowerMotors = characteristic;
                        break;
                    case "Parrot_DateTime":
                        DateTime = characteristic;
                        break;
                    case "Parrot_EmergencyStop":
                        EmergencyStop = characteristic;
                        break;
                    case "Parrot_InitCount1_20":
                        InitCount1To20 = characteristic;
                        break;
                    case "Parrot_AIF":
                        Aif = characteristic;
                        break;
                    case "Parrot_B01":
                        B01 = characteristic;
                        break;
                    case "Parrot_B0E_BC_BD":
                        B0E_BC_BD = characteristic;
                        break;
                    case "Parrot_Battery_B0F_BF_C0":
                        B0F_BF_C0 = characteristic;
                        break;
                    case "Parrot_B1B_E3_E4":
                        B1B_E3_E4 = characteristic;
                        break;
                    case "Parrot_B1C_E6_E7":
                        B1C_E6_E7 = characteristic;
                        break;
                    case "Parrot_B1F":
                        B1F = characteristic;
                        break;
                    case "Parrot_FC1":
                        Fc1 = characteristic;
                        break;
                    case "Parrot_D22":
                        D22 = characteristic;
                        break;
                    case "Parrot_D23":
                        D23 = characteristic;
                        break;
                    case "Parrot_D24":
                        D24 = characteristic;
                        break;
                    case "Parrot_D52":
                        D52 = characteristic;
                        break;
                    case "Parrot_D53":
                        D53 = characteristic;
                        break;
                    case "Parrot_D54":
                        Fc1 = characteristic;
                        break;
                    default:
                        Debug.WriteLine("not found for " + charName);
                        break;
                }
            }

            return dicCharacteristics;
        }
Пример #26
0
        public async void CheckArgs(BluetoothLEAdvertisementReceivedEventArgs args)
        {
            Console.WriteLine("★アドバタイズパケットスキャン");

            bool find = false;

            {
                var bleServiceUUIDs = args.Advertisement.ServiceUuids;
                foreach (var uuidone in bleServiceUUIDs)
                {
                    if (uuidone == Common.CreateFullUUID(SERVICE_UUID))
                    {
                        // 発見
                        find = true;
                        break;
                    }
                }
            }

            if (find)
            {
                try {
                    Console.WriteLine($"Service Find!");

                    // スキャンStop
                    this.advWatcher.Stop();

                    BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    this.Service = dev.GetGattService(Common.CreateFullUUID(SERVICE_UUID));

                    // for log
                    {
                        Console.WriteLine($"Service.Uuid...{Service.Uuid}");
                        Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}");
                        Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}");

                        var characteristics = Service.GetAllCharacteristics();
                        foreach (var ch in characteristics)
                        {
                            Console.WriteLine($"CharacteristicUUID...{ch.Uuid}");
                            Console.WriteLine($"CharacteristicProperties...{ch.CharacteristicProperties}");
                        }
                    }

                    // Blood Pressure Measurement
                    // Requirement = M , Mandatory Properties = Indicate
                    {
                        var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A35"));
                        if (characteristics.Count > 0)
                        {
                            this.Characteristic_Blood_Pressure_Measurement = characteristics.First();
                            if (this.Characteristic_Blood_Pressure_Measurement == null)
                            {
                                Console.WriteLine("Characteristicに接続できない...");
                            }
                            else
                            {
                                if (this.Characteristic_Blood_Pressure_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    // イベントハンドラ追加
                                    this.Characteristic_Blood_Pressure_Measurement.ValueChanged += characteristicChanged_Blood_Pressure_Measurement;

                                    // これで有効になる
                                    await this.Characteristic_Blood_Pressure_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                                }
                            }
                        }
                    }

                    // Blood Pressure Feature
                    // Requirement = M , Mandatory Properties = Read
                    {
                        var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A49"));
                        if (characteristics.Count > 0)
                        {
                            var chara = characteristics.First();
                            if (chara == null)
                            {
                                Console.WriteLine("Characteristicに接続できない...");
                            }
                            else
                            {
                                if (chara.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
                                {
                                    GattReadResult result = await chara.ReadValueAsync();

                                    if (result.Status == GattCommunicationStatus.Success)
                                    {
                                        var    reader = Windows.Storage.Streams.DataReader.FromBuffer(result.Value);
                                        byte[] input  = new byte[reader.UnconsumedBufferLength];
                                        reader.ReadBytes(input);

                                        var tmp = BitConverter.ToString(input);
                                        Console.WriteLine($"Blood Pressure Feature...{tmp}");
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    Console.WriteLine($"Exception...{ex.Message})");
                }
            }
            else
            {
                Console.WriteLine($"...");
            }
        }
Пример #27
0
        private Dictionary <string, RsCharacteristic> CompletePropsFromServiceChars(GattDeviceService service, string deviceId, Dictionary <string, RsCharacteristic> dicCharacteristics)
        {
            var characteristics = service.GetAllCharacteristics();

            foreach (var characteristic in characteristics)
            {
                var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid);
                Debug.WriteLine(characteristic.Uuid + " - " + charName);
                if (charName == "undefined")
                {
                    continue;
                }

                var rsCharacteristic = new RsCharacteristic
                {
                    Characteristic = characteristic,
                    CharName       = charName,
                    DeviceId       = deviceId
                };
                dicCharacteristics.Add(charName, rsCharacteristic);

                switch (charName)
                {
                case "undefined":
                    Undefined = characteristic;
                    break;

                case "GapDeviceName":
                    GapDeviceName = characteristic;
                    break;

                case "GapAppearance":
                    GapAppearance = characteristic;
                    break;

                case "GapPeripheralPreferredConnectionParameters":
                    GapPeripheralPreferredConnectionParameters = characteristic;
                    break;

                case "GattServiceChanged":
                    GattServiceChanged = characteristic;
                    break;

                case "Parrot_TourTheStairsParrotA01":
                    TourTheStairsParrotA01 = characteristic;
                    break;

                case "Parrot_Stop":
                    Stop = characteristic;
                    break;

                case "Parrot_PowerMotors":
                    PowerMotors = characteristic;
                    break;

                case "Parrot_DateTime":
                    DateTime = characteristic;
                    break;

                case "Parrot_EmergencyStop":
                    EmergencyStop = characteristic;
                    break;

                case "Parrot_InitCount1_20":
                    InitCount1To20 = characteristic;
                    break;

                case "Parrot_AIF":
                    Aif = characteristic;
                    break;

                case "Parrot_B01":
                    B01 = characteristic;
                    break;

                case "Parrot_B0E_BC_BD":
                    B0E_BC_BD = characteristic;
                    break;

                case "Parrot_Battery_B0F_BF_C0":
                    B0F_BF_C0 = characteristic;
                    break;

                case "Parrot_B1B_E3_E4":
                    B1B_E3_E4 = characteristic;
                    break;

                case "Parrot_B1C_E6_E7":
                    B1C_E6_E7 = characteristic;
                    break;

                case "Parrot_B1F":
                    B1F = characteristic;
                    break;

                case "Parrot_FC1":
                    Fc1 = characteristic;
                    break;

                case "Parrot_D22":
                    D22 = characteristic;
                    break;

                case "Parrot_D23":
                    D23 = characteristic;
                    break;

                case "Parrot_D24":
                    D24 = characteristic;
                    break;

                case "Parrot_D52":
                    D52 = characteristic;
                    break;

                case "Parrot_D53":
                    D53 = characteristic;
                    break;

                case "Parrot_D54":
                    Fc1 = characteristic;
                    break;

                default:
                    Debug.WriteLine("not found for " + charName);
                    break;
                }
            }

            return(dicCharacteristics);
        }
Пример #28
0
        public async Task <bool> Connect()
        {
            UpdateStatue(TrackerStatus.Connecting, "Connecting...");

            try
            {
                _service = await GattDeviceService.FromIdAsync(_deviceInfo.Id);

                if (_service == null)
                {
                    return(false);
                }
                IReadOnlyCollection <GattCharacteristic> characteristicList = _service.GetAllCharacteristics();
                foreach (var item in characteristicList)
                {
                    if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_CONFIG))
                    {
                        _config_characteristic = item;
                    }
                    else if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_PERIOD))
                    {
                        _period_characteristic = item;
                    }
                    else if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_DATA))
                    {
                        _data_characteristic = item;
                    }
                }
                if (_config_characteristic == null || _period_characteristic == null || _data_characteristic == null)
                {
                    UpdateStatue(TrackerStatus.Disconnected, "Device not support");
                    return(false);
                }


                DataWriter configWriter = new DataWriter();
                Utility.WriteBigEndian16bit(configWriter, (ushort)(0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40));
                var result = await _config_characteristic.WriteValueAsync(configWriter.DetachBuffer());

                if (result == GattCommunicationStatus.Unreachable)
                {
                    UpdateStatue(TrackerStatus.Disconnected, "Device unreachable");
                    return(false);
                }

                DataWriter periodWriter = new DataWriter();
                periodWriter.WriteBytes(new byte[] { 10 });
                result = await _period_characteristic.WriteValueAsync(periodWriter.DetachBuffer());

                if (result == GattCommunicationStatus.Unreachable)
                {
                    UpdateStatue(TrackerStatus.Disconnected, "Device unreachable");
                    return(false);
                }

                _bLEDevice = await BluetoothLEDevice.FromIdAsync(_deviceInfo.Id);

                _bLEDevice.ConnectionStatusChanged += _bLEDevice_ConnectionStatusChanged;
                _data_characteristic.ValueChanged  += _data_characteristic_ValueChanged;
                result = await _data_characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                if (result == GattCommunicationStatus.Unreachable)
                {
                    UpdateStatue(TrackerStatus.Disconnected, "Device unreachable");
                    return(false);
                }
                UpdateStatue(TrackerStatus.Connected, "Device connected. Calibrate magnetometer ");
                return(true);
            }
            catch
            {
                if (_service != null)
                {
                    _service.Dispose();
                }
                return(false);
            }
        }
Пример #29
0
        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            // Tell the user we see an advertisement and print some properties
            Console.WriteLine(String.Format("Advertisement:"));
            Console.WriteLine(String.Format("  BT_ADDR: {0}", eventArgs.BluetoothAddress));
            Console.WriteLine(String.Format("  FR_NAME: {0}", eventArgs.Advertisement.LocalName));
            Console.WriteLine();

            watcher.Stop();

            device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

            if (device != null)
            {
                Console.WriteLine();
                Console.WriteLine("Successfully connected to device\nAvailable services: " + device.GattServices.Count);

                foreach (GattDeviceService service in device.GattServices)
                {
                    Console.WriteLine("Uuid: " + service.Uuid);
                }

                Console.WriteLine("Searching for service: {" + bleChannelServiceUuidString + "}");

                GattDeviceService bleChannelService = null;
                try
                {
                    bleChannelService = device.GattServices.Single(service => service.Uuid == new Guid(bleChannelServiceUuidString));
                }
                catch (Exception e)
                {
                    Console.WriteLine("More than one service found");
                    device.Dispose();
                    return;
                }
                if (bleChannelService == null)
                {
                    Console.WriteLine("Service not found");
                    device.Dispose();
                    return;
                }

                Console.WriteLine("Available characteristics: " + bleChannelService.GetAllCharacteristics().Count);

                foreach (GattCharacteristic characteristic in bleChannelService.GetAllCharacteristics())
                {
                    Console.WriteLine("Uuid: " + characteristic.Uuid);
                }

                try
                {
                    bleChannel = bleChannelService.GetAllCharacteristics().Single(
                        characteristic => characteristic.Uuid == new Guid(bleChannelCharacteristicUuidString));
                }
                catch (Exception e)
                {
                    Console.WriteLine("More than one characteristic found");
                    device.Dispose();
                    return;
                }
                if (bleChannel == null)
                {
                    Console.WriteLine("Characteristic not found");
                    device.Dispose();
                    return;
                }

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

                if (status == GattCommunicationStatus.Success)
                {
                    bleChannel.ValueChanged += BleChannel_ValueChanged;
                    Console.WriteLine("Subscribed to notifications");
                }
                else
                {
                    Console.WriteLine("Couldn't subscribe to notifications");
                }
            }
        }
Пример #30
0
        // Method for when the user selects the UART device from the UI
        private async void OnDeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            // Convert MAC Address to BluetoothAddress
            // remove the colons
            macAddress = macAddress.Replace(":", "");
            Debug.WriteLine("Formatted MAC Address " + macAddress);
            bluetoothAddress = ulong.Parse(macAddress, System.Globalization.NumberStyles.HexNumber);
            Debug.WriteLine("Converted Bluetooth Address is " + bluetoothAddress);

            // Connect via the BluetoothAddress

            leDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress);

            Debug.WriteLine("============");
            Debug.WriteLine("============");
            Debug.WriteLine("============");

            Debug.WriteLine("Made it past BluetoothLEDevice");
            Debug.WriteLine("Name is " + leDevice.Name);
            Debug.WriteLine("ConnectionStatus is " + leDevice.ConnectionStatus);
            Debug.WriteLine("DeviceId is " + leDevice.DeviceId);
            Debug.WriteLine("Number of GattServices are " + leDevice.GattServices.Count);

            Debug.WriteLine("=GATT SERVICES=");
            GattDeviceService selectedService = null;

            foreach (GattDeviceService gds in leDevice.GattServices)
            {
                Debug.WriteLine("GattDeviceService.uuid: " + gds.Uuid);
                selectedService = gds;
            }

            Debug.WriteLine("============");
            Debug.WriteLine("============");
            Debug.WriteLine("============");

            Debug.WriteLine("=GATT CHARACTERISTICS FOR " + selectedService.Uuid + " =");

            var allCharacteristics = selectedService.GetAllCharacteristics();
            GattCharacteristic selectedCharacteristic = null;

            foreach (GattCharacteristic gc in allCharacteristics)
            {
                Debug.WriteLine("GattCharacteristic.Uuid: " + gc.Uuid);
                Debug.WriteLine("GattCharacteristic.UserDescriptions: " + gc.UserDescription);
                Debug.WriteLine("GattCharacteristic.AttributeHandle: " + gc.AttributeHandle);
                Debug.WriteLine("GattCharacteristic.CharacteristicProperties: " + gc.CharacteristicProperties);
                Debug.WriteLine("***");

                selectedCharacteristic = gc;
            }

            Debug.WriteLine("Selected Characteristic: " + selectedCharacteristic.Uuid);

            // There are two things to take care of before getting notifications:
            // 1. Write to Client Characteristic Configuration Description (CCCD)

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

            if (status == GattCommunicationStatus.Success)
            {
                Debug.WriteLine("Successfully wrote to CCCD");
                selectedCharacteristic.ValueChanged += Characteristic_ValueChanged;
            }
            else
            {
                Debug.WriteLine("Unsuccessful writing to CCCD");
            }

            // 2. Handle the Characteristic.valueChanged event



            // MAYBE OBSOLETE: InitializeRingSensor(selectedService);
        }
        async static Task BLE()
        {
            GattReadResult    result = null;
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(000000000002);

            // Get the service containing our characteristic
            Guid ServiceId             = new Guid("6D617931-3733-3500-0000-000000000000");
            GattDeviceService services = device.GetGattService(ServiceId);

            string preTimeData = "";
            string curTimeData = "";


            // This block assumes multiple characteristics and polls from each separate characteristic containing the needed data
            while (true)
            {
                foreach (var gc in services.GetAllCharacteristics())
                {
                    string output = "";

                    if (gc.Uuid != ServiceId)
                    {
                        result = await gc.ReadValueAsync(BluetoothCacheMode.Uncached);

                        var dataReader = DataReader.FromBuffer(result.Value);
                        output = dataReader.ReadString(result.Value.Length);
                        //Console.WriteLine(output);
                    }

                    switch (gc.Uuid.ToString())
                    {
                    // AccelX AccelY AccelZ
                    case "01100000-0000-0000-0000-000000000000":
                        string[] AccelValues = output.Split(' ');
                        accel_x = AccelValues[0];
                        accel_y = AccelValues[1];
                        accel_z = AccelValues[2];

                        break;

                    // GyroX GyroY GyroZ
                    case "02100000-0000-0000-0000-000000000000":
                        string[] GyroValues = output.Split(' ');
                        gyro_x = GyroValues[0];
                        gyro_y = GyroValues[1];
                        gyro_z = GyroValues[2];
                        break;

                    // MagX MagY MagZ
                    case "03100000-0000-0000-0000-000000000000":
                        string[] MagValues = output.Split(' ');
                        mag_x = MagValues[0];
                        mag_y = MagValues[1];
                        mag_z = MagValues[2];
                        break;

                    // JoystickX JoystickY JoystickZ Buttons
                    case "04100000-0000-0000-0000-000000000000":
                        string[] JoyButValues = output.Split(' ');
                        joy_x   = JoyButValues[0];
                        joy_y   = JoyButValues[1];
                        buttons = JoyButValues[2];
                        break;

                    // Time
                    case "05100000-0000-0000-0000-000000000000":
                        curTimeData = output;
                        if (preTimeData.Equals(curTimeData))
                        {
                            dataChanged = false;
                        }
                        else
                        {
                            dataChanged = true;
                        }
                        preTimeData = curTimeData;

                        time = int.Parse(output, System.Globalization.NumberStyles.HexNumber).ToString();

                        break;

                    default:
                        break;
                    }
                }
            }
        }
Пример #32
0
        public async void CheckArgs(BluetoothLEAdvertisementReceivedEventArgs args)
        {
            Console.WriteLine("★アドバタイズパケットスキャン");

            bool find = false;

            {
                var bleServiceUUIDs = args.Advertisement.ServiceUuids;
                foreach (var uuidone in bleServiceUUIDs)
                {
                    if (uuidone == Common.CreateFullUUID(SERVICE_UUID))
                    {
                        // 発見
                        find = true;
                        break;
                    }
                }
            }

            if (find)
            {
                try {
                    Console.WriteLine($"Service Find!");

                    // スキャンStop
                    this.advWatcher.Stop();

                    BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    this.Service = dev.GetGattService(Common.CreateFullUUID(SERVICE_UUID));

                    // for log
                    {
                        Console.WriteLine($"Service.Uuid...{Service.Uuid}");
                        Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}");
                        Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}");

                        var characteristics = Service.GetAllCharacteristics();
                        foreach (var ch in characteristics)
                        {
                            Console.WriteLine($"CharacteristicUUID...{ch.Uuid}");
                            Console.WriteLine($"CharacteristicProperties...{ch.CharacteristicProperties}");
                        }
                    }

                    // Weight Scale Measurement
                    {
                        var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A9D"));
                        if (characteristics.Count > 0)
                        {
                            this.Characteristic_WeightScale_Measurement = characteristics.First();
                            if (this.Characteristic_WeightScale_Measurement == null)
                            {
                                Console.WriteLine("Characteristicに接続できない...");
                            }
                            else
                            {
                                if (this.Characteristic_WeightScale_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    // イベントハンドラ追加
                                    this.Characteristic_WeightScale_Measurement.ValueChanged += characteristicChanged_WeightScale_Measurement;

                                    // これで有効になる
                                    await this.Characteristic_WeightScale_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    Console.WriteLine($"Exception...{ex.Message})");
                }
            }
            else
            {
                Console.WriteLine($"...");
            }
        }
Пример #33
0
        public virtual async void Start1()
        {
            var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(Common.CreateFullUUID(SERVICE_UUID)));

            if (devices.Count <= 0)
            {
                // デバイス無し
                Console.WriteLine("デバイス無し...");
                return;
            }

            this.Service = await GattDeviceService.FromIdAsync(devices.First().Id);

            if (this.Service == null)
            {
                Console.WriteLine("サービスに接続できない...");
                return;
            }

            // for log
            {
                Console.WriteLine($"Service.Uuid...{Service.Uuid}");
                Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}");
                Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}");

                var characteristics = Service.GetAllCharacteristics();
                foreach (var ch in characteristics)
                {
                    Console.WriteLine($"Characteristic...");
                    Console.WriteLine($"...AttributeHandle=0x{ch.AttributeHandle.ToString("X2")}");
                    Console.WriteLine($"...Properties={ch.CharacteristicProperties}");
                    Console.WriteLine($"...ProtectionLevel={ch.ProtectionLevel}");
                    Console.WriteLine($"...UUID={ch.Uuid}");
                }
            }

            // Temperature Measurement
            // Requirement = M , Mandatory Properties = Indicate
            {
                var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1C"));
                if (characteristics.Count > 0)
                {
                    this.Characteristic_Temperature_Measurement = characteristics.First();
                    if (this.Characteristic_Temperature_Measurement == null)
                    {
                        Console.WriteLine("Characteristicに接続できない...");
                    }
                    else
                    {
                        if (this.Characteristic_Temperature_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                        {
                            // イベントハンドラ追加
                            this.Characteristic_Temperature_Measurement.ValueChanged += characteristicChanged_Temperature_Measurement;

                            // これで有効になる
                            await this.Characteristic_Temperature_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                        }
                    }
                }
            }

            // Intermediate Temperature:Notify
            // Requirement = O , Mandatory Properties = Notify
            {
                var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1E"));
                if (characteristics.Count > 0)
                {
                    this.Characteristic_Intermediate_Temperature = characteristics.First();
                    if (this.Characteristic_Intermediate_Temperature == null)
                    {
                        Console.WriteLine("Characteristicに接続できない...");
                    }
                    else
                    {
                        if (this.Characteristic_Intermediate_Temperature.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                        {
                            this.Characteristic_Intermediate_Temperature.ValueChanged += characteristicChanged_Intermediate_Temperature;
                            await this.Characteristic_Intermediate_Temperature.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                        }
                    }
                }
            }
        }
Пример #34
0
        public async void CheckArgs(BluetoothLEAdvertisementReceivedEventArgs args)
        {
            Console.WriteLine("★アドバタイズパケットスキャン");

            // Health Thermometerサービスを検索
            bool find = false;

            {
                var bleServiceUUIDs = args.Advertisement.ServiceUuids;
                foreach (var uuidone in bleServiceUUIDs)
                {
                    if (uuidone == Common.CreateFullUUID(SERVICE_UUID))
                    {
                        // 発見
                        find = true;
                        break;
                    }
                }
            }

            if (find)
            {
                try {
                    Console.WriteLine($"Service Find!");
                    // スキャンStop
                    this.advWatcher.Stop();

                    BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    this.Service = dev.GetGattService(Common.CreateFullUUID(SERVICE_UUID));

                    // for log
                    {
                        Console.WriteLine($"Service.Uuid...{Service.Uuid}");
                        Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}");
                        Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}");

                        var characteristics = Service.GetAllCharacteristics();
                        foreach (var ch in characteristics)
                        {
                            Console.WriteLine($"Characteristic...");
                            Console.WriteLine($"...AttributeHandle=0x{ch.AttributeHandle.ToString("X2")}");
                            Console.WriteLine($"...Properties={ch.CharacteristicProperties}");
                            Console.WriteLine($"...ProtectionLevel={ch.ProtectionLevel}");
                            Console.WriteLine($"...UUID={ch.Uuid}");
                        }
                    }

                    // Temperature Measurement
                    // Requirement = M , Mandatory Properties = Indicate
                    {
                        var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1C"));
                        if (characteristics.Count > 0)
                        {
                            this.Characteristic_Temperature_Measurement = characteristics.First();
                            if (this.Characteristic_Temperature_Measurement == null)
                            {
                                Console.WriteLine("Characteristicに接続できない...");
                            }
                            else
                            {
                                if (this.Characteristic_Temperature_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    // イベントハンドラ追加
                                    this.Characteristic_Temperature_Measurement.ValueChanged += characteristicChanged_Temperature_Measurement;

                                    // これで有効になる
                                    await this.Characteristic_Temperature_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                                }
                            }
                        }
                    }

                    // Intermediate Temperature:Notify
                    // Requirement = O , Mandatory Properties = Notify
                    {
                        var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1E"));
                        if (characteristics.Count > 0)
                        {
                            this.Characteristic_Intermediate_Temperature = characteristics.First();
                            if (this.Characteristic_Intermediate_Temperature == null)
                            {
                                Console.WriteLine("Characteristicに接続できない...");
                            }
                            else
                            {
                                if (this.Characteristic_Intermediate_Temperature.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                                {
                                    this.Characteristic_Intermediate_Temperature.ValueChanged += characteristicChanged_Intermediate_Temperature;
                                    await this.Characteristic_Intermediate_Temperature.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    Console.WriteLine($"Exception...{ex.Message})");
                }
            }
            else
            {
                Console.WriteLine($"...");
            }
        }