private async Task CreateCharacteristics(GattServiceProvider gattServiceProvider)
        {
            var statusCharacteristicParams = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify,
                WriteProtectionLevel     = GattProtectionLevel.Plain,
                UserDescription          = "Status Characteristic"
            };

            statusCharacteristicParams.PresentationFormats.Add(GattPresentationFormat.FromParts(GattPresentationFormatTypes.Utf8,
                                                                                                GattPresentationFormatExponent,
                                                                                                GattPresentationFormatUnitless,
                                                                                                GattPresentationFormatNamespaceId,
                                                                                                GattPresentationFormatDescription));

            var statusCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.StatusCharacteristicUuid,
                statusCharacteristicParams);

            if (statusCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT status characteristic with error {statusCharacteristicResult.Error}");
            }

            _statusCharacteristic = statusCharacteristicResult.Characteristic;

            var commandCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.CommandCharacteristicUuid,
                new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Write
                                           | GattCharacteristicProperties.WriteWithoutResponse,
                WriteProtectionLevel = GattProtectionLevel.Plain,
                UserDescription      = "Command Characteristic"
            });

            if (commandCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT command characteristic with error {commandCharacteristicResult.Error}");
            }

            var brightnessCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.BrightnessCharacteristicUuid,
                new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Write
                                           | GattCharacteristicProperties.WriteWithoutResponse,
                WriteProtectionLevel = GattProtectionLevel.Plain,
                UserDescription      = "Brightness Characteristic"
            });

            if (brightnessCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT brightness characteristic with error {brightnessCharacteristicResult.Error}");
            }

            _statusCharacteristic.ReadRequested += StatusCharacteristic_ReadRequested;
            commandCharacteristicResult.Characteristic.WriteRequested    += CommandCharacteristic_WriteRequested;
            brightnessCharacteristicResult.Characteristic.WriteRequested += BrightnessCharacteristic_WriteRequested;
        }
Exemple #2
0
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(GattServiceUuids.Battery);

            // Preparing the Battery Level characteristics
            GattLocalCharacteristicParameters batteryCharacteristicsParameters = PlainReadNotifyParameters;

            // Set the user descriptions
            batteryCharacteristicsParameters.UserDescription = "Battery Level percentage remaining";

            // Add presentation format - 16-bit integer, with exponent 0, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            batteryCharacteristicsParameters.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.Unsigned8BitInteger),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Percentage),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            // Create the characteristic for the service
            GattLocalCharacteristicResult result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    GattCharacteristicUuids.BatteryLevel,
                    batteryCharacteristicsParameters);

            // Grab the characterist object from the service set it to the BatteryLevel property which is of a specfic Characteristic type
            GattLocalCharacteristic baseBatteryLevel = null;

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseBatteryLevel);

            if (baseBatteryLevel != null)
            {
                BatteryLevel = new Characteristics.BatteryLevelCharacteristic(baseBatteryLevel, this);
            }
        }
Exemple #3
0
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(GattServiceUuids.Battery);

            // Preparing the Battery Level characteristics
            GattLocalCharacteristicParameters batteryCharacteristicsParameters = PlainReadParameters;

            // Set the user descriptions
//            batteryCharacteristicsParameters.UserDescription = "Battery Level percentage remaining";

            // Create the characteristic for the service
            GattLocalCharacteristicResult result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    GattCharacteristicUuids.BatteryLevel,
                    batteryCharacteristicsParameters);

            // Grab the characterist object from the service set it to the BatteryLevel property which is of a specfic Characteristic type
            GattLocalCharacteristic baseBatteryLevel = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseBatteryLevel);

            if (baseBatteryLevel != null)
            {
                BatteryLevel = new BLEServices.BatteryLevelCharacteristic(baseBatteryLevel, this);
            }
        }
Exemple #4
0
        internal async Task <bool> Initialize()
        {
            try
            {
                GattServiceProviderResult result = await GattServiceProvider.CreateAsync(_serviceId);

                if (result.Error != BluetoothError.Success)
                {
                    Robot.Message("can't create GATT BlueTooth service with id " + _serviceId.ToString(), MessageType.Error);
                    Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
                    return(_init);
                }
                _service = result.ServiceProvider;

                byte[] value = new byte[] { 0x21 };
                var    constantParameters = new GattLocalCharacteristicParameters
                {
                    CharacteristicProperties = (GattCharacteristicProperties.Read),
                    StaticValue         = value.AsBuffer(),
                    ReadProtectionLevel = GattProtectionLevel.Plain,
                };

                GattLocalCharacteristicResult characteristicResult = await _service.Service.CreateCharacteristicAsync(_notifyId, new GattLocalCharacteristicParameters
                {
                    CharacteristicProperties = GattCharacteristicProperties.Notify,
                    ReadProtectionLevel      = GattProtectionLevel.Plain,
                    StaticValue = value.AsBuffer()
                });

                if (characteristicResult.Error != BluetoothError.Success)
                {
                    Robot.Message("can't create GATT BlueTooth service with id " + _serviceId.ToString(), MessageType.Error);
                    Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
                    return(_init);
                }
                _notifyCharacteristic = characteristicResult.Characteristic;
                //_notifyCharacteristic.SubscribedClientsChanged += _btNotify_SubscribedClientsChanged;

                GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
                {
                    IsDiscoverable = true,
                    IsConnectable  = true
                };
                _service.StartAdvertising(advParameters);
                Robot.Message("created Bluetooth GATT service with id " + _serviceId.ToString(), MessageType.Success);
                _init = true;
            }
            catch (Exception x)
            {
                while (x != null)
                {
                    Robot.Message(x.Message, MessageType.Error);
                    x = x.InnerException;
                }
                Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
            }
            return(_init);
        }
        /// <summary>
        /// 创建特征
        /// </summary>
        private async void CreateCharacteristics()
        {
            var characteristicParameters = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Notify | GattCharacteristicProperties.Read
            };
            GattLocalCharacteristicResult characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(keyboardControlGuid, characteristicParameters);

            characteristic = characteristicResult.Characteristic;
            characteristic.ReadRequested += Characteristic_ReadRequested;
        }
Exemple #6
0
        /// <summary>
        /// Write Only Characteristic
        /// </summary>
        /// <param name="characteristicId"></param>
        /// <param name="userDescription"></param>
        /// <returns></returns>
        public async Task <bool> AddWriteCharacteristicAsync(Guid characteristicId, string userDescription = "N/A")
        {
            await _logger.LogMessageAsync($"Adding write characteristic to service: description: {userDescription}, guid: {characteristicId}");

            var charactericticParameters = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.WriteWithoutResponse,
                WriteProtectionLevel     = GattProtectionLevel.Plain,
                UserDescription          = userDescription
            };

            var characteristicResult = await _gattServiceProvider.Service.CreateCharacteristicAsync(characteristicId, charactericticParameters);

            if (characteristicResult.Error != BluetoothError.Success)
            {
                await _logger.LogMessageAsync("Adding write characteristic failed");

                return(false);
            }

            var characteristic = characteristicResult.Characteristic;

            characteristic.WriteRequested += async(sender, args) =>
            {
                using (args.GetDeferral())
                {
                    // For this you need UWP bluetooth manifest enabled on app !!!!!!!!
                    var request = await args.GetRequestAsync();

                    if (request == null)
                    {
                        return;
                    }

                    using (var dataReader = DataReader.FromBuffer(request.Value))
                    {
                        var characteristicValue = dataReader.ReadString(request.Value.Length);

                        if (OnChararteristicWrite != null)
                        {
                            OnChararteristicWrite(null, new CharacteristicEventArgs(characteristic.Uuid, characteristicValue));
                        }
                    }

                    if (request.Option == GattWriteOption.WriteWithResponse)
                    {
                        request.Respond();
                    }
                }
            };
            return(true);
        }
Exemple #7
0
 public async Task Build(GattServiceProviderResult native)
 {
     var parameters = new GattLocalCharacteristicParameters
     {
         CharacteristicProperties = this.properties,
         ReadProtectionLevel      = this.readProtection,
         WriteProtectionLevel     = this.writeProtection
     };
     var characteristic = await native
                          .ServiceProvider
                          .Service
                          .CreateCharacteristicAsync(this.Uuid, parameters);
 }
        public async Task Build(GattServiceProviderResult native)
        {
            var parameters = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = this.properties
                                           //ReadProtectionLevel = this.EncryptedRead
                                           //    ? GattProtectionLevel.EncryptionAndAuthenticationRequired
                                           //    : GattProtectionLevel.Plain,

                                           //WriteProtectionLevel = this.Write
            };
            var characteristic = await native
                                 .ServiceProvider
                                 .Service
                                 .CreateCharacteristicAsync(this.Uuid, parameters);
        }
Exemple #9
0
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(GattServiceUuids.CurrentTime);

            GattLocalCharacteristicParameters currentTimeCharacteristicsParameters = PlainReadNotifyParameters;

            // Set the user descriptions
            currentTimeCharacteristicsParameters.UserDescription = "Current Time!";


            GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync(
                GattCharacteristicUuids.CurrentTime,
                PlainReadNotifyParameters);

            GattLocalCharacteristic currentTimeCharacterisitic = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref currentTimeCharacterisitic);
            if (currentTimeCharacterisitic != null)
            {
                CurrentTime = new BLEServices.CurrentTimeCharacteristic(currentTimeCharacterisitic, this);
            }
        }
Exemple #10
0
        /// <summary>
        /// Read Only Characteristic
        /// </summary>
        /// <param name="characteristicId"></param>
        /// <param name="characteristicValue"></param>
        /// <param name="userDescription"></param>
        /// <returns></returns>
        public async Task <bool> AddReadCharacteristicAsync(Guid characteristicId, string characteristicValue, string userDescription = "N/A")
        {
            await _logger.LogMessageAsync($"Adding read characteristic to gatt service: description: {userDescription}, guid: {characteristicId}, value: {characteristicValue}.");

            var charactericticParameters = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read,
                StaticValue         = Encoding.UTF8.GetBytes(characteristicValue).AsBuffer(),
                ReadProtectionLevel = GattProtectionLevel.Plain,
                UserDescription     = userDescription
            };

            var characteristicResult = await _gattServiceProvider.Service.CreateCharacteristicAsync(characteristicId, charactericticParameters);

            var readCharacteristic = characteristicResult.Characteristic;

            readCharacteristic.ReadRequested += async(a, b) =>
            {
                await _logger.LogMessageAsync("read requested..");
            }; // Warning, dont remove this...

            return(characteristicResult.Error == BluetoothError.Success);
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var adapter = await BluetoothAdapter.GetDefaultAsync();

            var serviceResult =
                await GattServiceProvider.CreateAsync(Guid.Parse(SensorUUIDs.UUID_ACC_SERV));

            accService = serviceResult.ServiceProvider;
            accService.AdvertisementStatusChanged += AccService_AdvertisementStatusChanged;

            var param = new GattLocalCharacteristicParameters();

            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.WriteProtectionLevel = GattProtectionLevel.Plain;

            param.UserDescription = "accelerometer";

            var charResult =
                await accService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ACC_DATA), param);

            accData = charResult.Characteristic;
            accData.ReadRequested += AccData_ReadRequested;
            accService.StartAdvertising(new GattServiceProviderAdvertisingParameters()
            {
                IsDiscoverable = true, IsConnectable = true
            });

            serviceResult =
                await GattServiceProvider.CreateAsync(Guid.Parse(SensorUUIDs.UUID_ENV_SERV));

            envService = serviceResult.ServiceProvider;

            param = new GattLocalCharacteristicParameters();
            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.UserDescription = "temperature";

            charResult =
                await envService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ENV_TEMP), param);

            tempData = charResult.Characteristic;
            tempData.ReadRequested += TempData_ReadRequested;

            param = new GattLocalCharacteristicParameters();
            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.UserDescription = "pressure";

            charResult =
                await envService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ENV_PRES), param);

            pressData = charResult.Characteristic;
            pressData.ReadRequested += PressData_ReadRequested;
            envService.StartAdvertising(new GattServiceProviderAdvertisingParameters()
            {
                IsDiscoverable = true, IsConnectable = true
            });

            timer          = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick    += Timer_Tick;
            //timer.Start();

            base.OnNavigatedTo(e);
        }
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(Constants.LightBulbServiceUuid);

            //Light Bulb Switch characteristic
            GattLocalCharacteristicParameters lightBulbSwitchCharacteristicsParameters = PlainReadWriteParameters;

            // Set the user descriptions
            lightBulbSwitchCharacteristicsParameters.UserDescription = "Light bulb on/off";
            // Create the characteristic for the service
            GattLocalCharacteristicResult result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.LightBulbSwitchCharacteristicUuid,
                    lightBulbSwitchCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseLightBulbSwitch = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseLightBulbSwitch);

            if (baseLightBulbSwitch != null)
            {
                LightBulbSwitch = new BLEServices.LightBulbSwitchCharacteristic(baseLightBulbSwitch, this);
            }



            //Light Bulb Text To Speech characteristic
            GattLocalCharacteristicParameters lightBulbTTSCharacteristicsParameters = PlainWriteOrWriteWithoutResponseParameters;

            // Set the user descriptions
            lightBulbTTSCharacteristicsParameters.UserDescription = "Light bulb text to speech";
            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.LightBulbTTSCharacteristicUuid,
                    lightBulbTTSCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseLightBulbTTS = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseLightBulbTTS);

            if (baseLightBulbTTS != null)
            {
                LightBulbTTS = new BLEServices.LightBulbTTSCharacteristic(baseLightBulbTTS, this);
            }



            //Light Bulb Color characteristic
            GattLocalCharacteristicParameters lightBulbColorCharacteristicsParameters = PlainWriteOrWriteWithoutResponseParameters;

            // Set the user descriptions
            lightBulbColorCharacteristicsParameters.UserDescription = "Light bulb color/dim";
            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.LightBulbColorCharacteristicUuid,
                    lightBulbColorCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseLightBulbColor = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseLightBulbColor);

            if (baseLightBulbColor != null)
            {
                LightBulbColor = new BLEServices.LightBulbColorCharacteristic(baseLightBulbColor, this);
            }
        }
Exemple #13
0
        private async void Init(MessageAccount account)
        {
            foreach (var msg in account.GetMessages())
            {
                queue.Add(msg.Binary);
            }

            var result = await GattServiceProvider.CreateAsync(ServiceId);

            if (result.Error == BluetoothError.Success)
            {
                var serviceProvider = result.ServiceProvider;

                var prm = new GattLocalCharacteristicParameters()
                {
                    CharacteristicProperties = GattCharacteristicProperties.WriteWithoutResponse,
                    UserDescription          = "DMsg"
                };
                var characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(cServiceId, prm);

                if (characteristicResult.Error != BluetoothError.Success)
                {
                    // An error occurred.
                    return;
                }
                var _readCharacteristic = characteristicResult.Characteristic;
                _readCharacteristic.WriteRequested += OnWriteMessage;

                var advParameters = new GattServiceProviderAdvertisingParameters
                {
                    IsDiscoverable = true,
                    //IsConnectable = true
                };
                serviceProvider.StartAdvertising(advParameters);
            }

            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
            var      deviceWatcher       = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                                                                           requestedProperties,
                                                                           DeviceInformationKind.AssociationEndpoint);

            deviceWatcher.Added += OnAddDevice;
            deviceWatcher.Start();

            var udp = new UdpClient(AddressFamily.InterNetworkV6);

            udp.EnableBroadcast = true;
            udp.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
            udp.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, 24680));
            MessageBroadcast(udp);

            while (true)
            {
                var ures = await udp.ReceiveAsync();

                try
                {
                    account.AddMessage(ures.Buffer);
                }
                catch (Exception) { }
            }
        }
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(Constants.QuickLockHistoryServiceUuid);


            // history control

            GattLocalCharacteristicParameters quickLockHistoryControlCharacteristicsParameters = PlainReadWriteParameters;

            // Set the user descriptions
            quickLockHistoryControlCharacteristicsParameters.UserDescription = "control!";

            // Create the characteristic for the service
            GattLocalCharacteristicResult result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockHistoryControlCharacteristicUuid,
                    quickLockHistoryControlCharacteristicsParameters);

            // Grab the characteristic object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockHistoryControl = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockHistoryControl);

            if (baseQuickLockHistoryControl != null)
            {
                QuickLockHistoryControl = new BLEServices.QuickLockHistoryControlCharacteristic(baseQuickLockHistoryControl, this);
            }


            // history data

            GattLocalCharacteristicParameters quickLockHistoryDataCharacteristicsParameters = PlainReadNotifyParameters;

            // Set the user descriptions
            quickLockHistoryDataCharacteristicsParameters.UserDescription = "history!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockHistoryDataCharacteristicUuid,
                    quickLockHistoryDataCharacteristicsParameters);

            // Grab the characteristic object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockHistoryData = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockHistoryData);

            if (baseQuickLockHistoryData != null)
            {
                QuickLockHistoryData = new BLEServices.QuickLockHistoryDataCharacteristic(baseQuickLockHistoryData, this);
            }


            // "imei" (username)

            // Preparing the characteristics
            GattLocalCharacteristicParameters quickLockUsernameCharacteristicsParameters = PlainReadWriteParameters;

            // Set the user descriptions
            quickLockUsernameCharacteristicsParameters.UserDescription = "phone id!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockUsernameCharacteristicUuid,
                    quickLockUsernameCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockUsername = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockUsername);

            if (baseQuickLockUsername != null)
            {
                QuickLockUsername = new BLEServices.QuickLockUsernameCharacteristic(baseQuickLockUsername, this);
            }
        }
Exemple #15
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // FitnessMachine service
            var gattServiceFitnessMachineRequest = await GattServiceProvider.CreateAsync(FitnessMachineServiceUuid);

            if (gattServiceFitnessMachineRequest.Error != BluetoothError.Success)
            {
                throw new Exception("Cannot create Gatt Service Provider");
            }

            _gattServiceProviderFitnessMachine = gattServiceFitnessMachineRequest.ServiceProvider;

            // Fitness Machine Feature characteristic
            var fitnessMachineFeatureData = new byte[]
            {
                0x08, 0x00, 0x00, 0x00
            };
            var targetSettingsData = new byte[]
            {
                0x00, 0x00, 0x00, 0x00
            };
            var fitnessMachineFeatureDataFull = fitnessMachineFeatureData.Concat(targetSettingsData).ToArray();
            var fitnessMachineFeatureCharacteristicRequest = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read,
                StaticValue         = fitnessMachineFeatureDataFull.AsBuffer(),
                ReadProtectionLevel = GattProtectionLevel.Plain,
            };
            var characteristicResult = await _gattServiceProviderFitnessMachine.Service.CreateCharacteristicAsync(
                FitnessMachineFeatureCharacteristicUuid, fitnessMachineFeatureCharacteristicRequest);

            if (characteristicResult.Error != BluetoothError.Success)
            {
                throw new Exception("Cannot create Characteristic");
            }

            // Treadmill Data characteristic
            var treadmillDataCharacteristicRequest = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify,
                ReadProtectionLevel      = GattProtectionLevel.Plain
            };

            characteristicResult = await _gattServiceProviderFitnessMachine.Service.CreateCharacteristicAsync(TreadmillDataCharacteristicUuid, treadmillDataCharacteristicRequest);

            if (characteristicResult.Error != BluetoothError.Success)
            {
                throw new Exception("Cannot create Characteristic");
            }

            _treadmillDataCharacteristic = characteristicResult.Characteristic;
            _treadmillDataCharacteristic.ReadRequested += TreadmillDataCharacteristic_ReadRequestedAsync;

            // Advertising
            byte[] flagsData =
            {
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            byte[] fitnessMachineTypeData =
            {
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            var serviceData   = flagsData.Concat(fitnessMachineTypeData).ToArray();
            var advParameters = new GattServiceProviderAdvertisingParameters
            {
                IsDiscoverable = true,
                IsConnectable  = true,
                ServiceData    = serviceData.AsBuffer()
            };

            // Go
            _gattServiceProviderFitnessMachine.StartAdvertising(advParameters);

            while (true)
            {
                await Task.Delay(1000, cancellationToken);

                await _treadmillDataCharacteristic.NotifyValueAsync(GetTreadmillDataPackage(_currentSpeed));
            }
        }
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            await CreateServiceProvider(Constants.QuickLockMainServiceUuid);


            // Quicklock auth

            GattLocalCharacteristicParameters quickLockAuthCharacteristicsParameters = PlainWriteParameters;

            // Set the user descriptions
            quickLockAuthCharacteristicsParameters.UserDescription = "Password!";

            // Create the characteristic for the service
            GattLocalCharacteristicResult result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockAuthCharacteristicUuid,
                    quickLockAuthCharacteristicsParameters);

            // Grab the characteristic object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockAuth = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockAuth);

            if (baseQuickLockAuth != null)
            {
                QuickLockAuth = new BLEServices.QuickLockAuthCharacteristic(baseQuickLockAuth, this);
            }


            // Quicklock auth status

            GattLocalCharacteristicParameters quickLockAuthStatusCharacteristicsParameters = PlainReadNotifyParameters;

            // Set the user descriptions
            quickLockAuthStatusCharacteristicsParameters.UserDescription = "Password Result!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockAuthStatusCharacteristicUuid,
                    quickLockAuthStatusCharacteristicsParameters);

            // Grab the characteristic object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockAuthStatus = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockAuthStatus);

            if (baseQuickLockAuthStatus != null)
            {
                QuickLockAuthStatus = new BLEServices.QuickLockAuthStatusCharacteristic(baseQuickLockAuthStatus, this);
            }


            // quick lock open time

            GattLocalCharacteristicParameters quickLockOpenTimeCharacteristicsParameters = PlainReadWriteParameters;

            // Set the user descriptions
            quickLockOpenTimeCharacteristicsParameters.UserDescription = "Open Time!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockOpenTimeCharacteristicUuid,
                    quickLockOpenTimeCharacteristicsParameters);

            // Grab the characteristic object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockOpenTime = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockOpenTime);

            if (baseQuickLockOpenTime != null)
            {
                QuickLockOpenTime = new BLEServices.QuickLockOpenTimeCharacteristic(baseQuickLockOpenTime, this);
            }


            // quick lock command

            GattLocalCharacteristicParameters quickLockCommandCharacteristicsParameters = PlainWriteParameters;

            // Set the user descriptions
            quickLockCommandCharacteristicsParameters.UserDescription = "Lock Control!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockCommandCharacteristicUuid,
                    quickLockCommandCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockCommand = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockCommand);

            if (baseQuickLockCommand != null)
            {
                QuickLockCommand = new BLEServices.QuickLockCommandCharacteristic(baseQuickLockCommand, this);
            }


            // quick lock unlock status

            GattLocalCharacteristicParameters quickLockUnlockStatusCharacteristicsParameters = PlainReadNotifyParameters;

            // Set the user descriptions
            quickLockUnlockStatusCharacteristicsParameters.UserDescription = "Lock Status!";

            // Create the characteristic for the service
            result =
                await ServiceProvider.Service.CreateCharacteristicAsync(
                    Constants.QuickLockUnlockStatusCharacteristicUuid,
                    quickLockUnlockStatusCharacteristicsParameters);

            // Grab the characterist object from the service set it to the property which is of a specfic Characteristic type
            GattLocalCharacteristic baseQuickLockUnlockStatus = null;

            BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseQuickLockUnlockStatus);

            if (baseQuickLockUnlockStatus != null)
            {
                QuickLockUnlockStatus = new BLEServices.QuickLockUnlockStatusCharacteristic(baseQuickLockUnlockStatus, this);
            }
        }
        /// <summary>
        /// Asynchronous initialization
        /// </summary>
        /// <returns>Initialization Task</returns>
        public override async Task Init()
        {
            var serviceData = new byte[] {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
            };

            ServiceData = WindowsRuntimeBuffer.Create(serviceData, 0, serviceData.Length, serviceData.Length);

            await CreateServiceProvider(MSFTServiceUuid);

            GattLocalCharacteristicResult result = null;

            // Prepare the Read Characteristic
            GattLocalCharacteristicParameters readParam = PlainReadParameter;

            readParam.UserDescription = "Microsoft Read characteristic";

            // Add presentation format - 16-bit integer, with exponent 0, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            readParam.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.Signed32BitInteger),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Unitless),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            GattLocalCharacteristic baseReadChar = null;

            result = await ServiceProvider.Service.CreateCharacteristicAsync(MSFTReadChar, readParam);

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseReadChar);
            if (baseReadChar != null)
            {
                ReadCharacteristic = new Characteristics.MicrosoftReadCharacteristic(baseReadChar, this);
            }

            result = null;

            // Prepare the Write Characteristic
            GattLocalCharacteristicParameters writeParam = PlainWriteOrWriteWithoutRespondsParameter;

            writeParam.UserDescription = "Microsoft Write characteristic";

            // Add presentation format - 16-bit integer, with exponent 0, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            writeParam.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.UTF8String),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Unitless),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            GattLocalCharacteristic baseWriteChar = null;

            result = await ServiceProvider.Service.CreateCharacteristicAsync(MSFTWriteChar, writeParam);

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseWriteChar);
            if (baseWriteChar != null)
            {
                WriteCharacteristic = new Characteristics.MicrosoftWriteCharacteristic(baseWriteChar, this);
            }

            result = null;

            // Prepare the Notify Characteristic
            GattLocalCharacteristicParameters notifyParam = PlainReadNotifyParameters;

            notifyParam.UserDescription = "Microsoft Notify characteristic";

            // Add presentation format - string, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            notifyParam.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.UTF8String),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Unitless),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            GattLocalCharacteristic baseNotifyChar = null;

            result = await ServiceProvider.Service.CreateCharacteristicAsync(MSFTNotifyChar, notifyParam);

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseNotifyChar);
            if (baseNotifyChar != null)
            {
                NotifyCharacteristic = new Characteristics.MicrosoftNotifyCharacteristic(baseNotifyChar, this);
            }

            result = null;

            // Prepare the Indicate Characteristic
            GattLocalCharacteristicParameters indicateParam = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read | GattCharacteristicProperties.Indicate,
                WriteProtectionLevel     = GattProtectionLevel.Plain,
                ReadProtectionLevel      = GattProtectionLevel.Plain
            };

            indicateParam.UserDescription = "Microsoft Indicate characteristic";

            // Add presentation format - 16-bit integer, with exponent 0, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            indicateParam.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.UTF8String),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Unitless),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            GattLocalCharacteristic baseIndicateChar = null;

            result = await ServiceProvider.Service.CreateCharacteristicAsync(MSFTIndicateChar, indicateParam);

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseIndicateChar);
            if (baseIndicateChar != null)
            {
                IndicateCharacteristic = new Characteristics.MicrosoftNotifyCharacteristic(baseIndicateChar, this);
            }

            result = null;

            // Prepare the Read Long Characteristic
            GattLocalCharacteristicParameters longParam = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read,
                WriteProtectionLevel     = GattProtectionLevel.Plain,
                ReadProtectionLevel      = GattProtectionLevel.Plain
            };

            longParam.UserDescription = "Microsoft Read Long characteristic";

            // Add presentation format - 16-bit integer, with exponent 0, the unit is percentage, defined per Bluetooth SIG with Microsoft as descriptor
            longParam.PresentationFormats.Add(
                GattPresentationFormat.FromParts(
                    Convert.ToByte(PresentationFormats.FormatTypes.OpaqueStructure),
                    PresentationFormats.Exponent,
                    Convert.ToUInt16(PresentationFormats.Units.Unitless),
                    Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                    PresentationFormats.Description));

            GattLocalCharacteristic baseLongReadChar = null;

            result = await ServiceProvider.Service.CreateCharacteristicAsync(MSFTLongChar, longParam);

            GattServicesHelper.GetCharacteristicsFromResult(result, ref baseLongReadChar);
            if (baseLongReadChar != null)
            {
                ReadLongCharacteristic = new Characteristics.MicrosoftReadLongCharacteristic(baseLongReadChar, this);
            }

            result = null;
        }
Exemple #18
0
        private async void InitializeInternal()
        {
            mInitializationCancelTokenSource = new CancellationTokenSource(ACCEPTANCE_TIMEOUT);

            try
            {
                var serviceProviderResult = await GattServiceProvider.CreateAsync(mServiceUUID).AsTask(mInitializationCancelTokenSource.Token);

                if (serviceProviderResult.Error != BluetoothError.Success)
                {
                    Utils.Error("failed to create service provider: {0}", serviceProviderResult.Error.ToString());

                    if (serviceProviderResult.Error == BluetoothError.RadioNotAvailable)
                    {
                        mCallback.OnBluetoothRequire();
                    }

                    HandleError();
                    return;
                }

                mServiceProvider = serviceProviderResult.ServiceProvider;
                mServiceProvider.AdvertisementStatusChanged += OnAdvertisementStatusChanged;

                var uploadParameters = new GattLocalCharacteristicParameters()
                {
                    CharacteristicProperties = GattCharacteristicProperties.Write,
                };

                var uploadCharacteristicResult = await mServiceProvider.Service.CreateCharacteristicAsync(mUploadUUID, uploadParameters).
                                                 AsTask(mInitializationCancelTokenSource.Token);

                if (uploadCharacteristicResult.Error != BluetoothError.Success)
                {
                    Utils.Error("failed to create uploading characteristic: {0}", uploadCharacteristicResult.Error.ToString());
                    HandleError();
                    return;
                }

                mUploadCharacteristic = uploadCharacteristicResult.Characteristic;
                mUploadCharacteristic.WriteRequested += OnCharacteristicWriteRequested;

                var downloadParameters = new GattLocalCharacteristicParameters
                {
                    CharacteristicProperties = GattCharacteristicProperties.Read | GattCharacteristicProperties.Indicate,
                };

                var downloadCharacteristicResult = await mServiceProvider.Service.CreateCharacteristicAsync(mDownloadUUID, downloadParameters).
                                                   AsTask(mInitializationCancelTokenSource.Token);

                if (downloadCharacteristicResult.Error != BluetoothError.Success)
                {
                    Utils.Error("failed to create downloading characteristic: {0}", downloadCharacteristicResult.Error.ToString());
                    HandleError();
                    return;
                }

                mDownloadCharacteristic = downloadCharacteristicResult.Characteristic;
                mDownloadCharacteristic.SubscribedClientsChanged += OnCharacteristicSubscribedClientsChanged;
                mDownloadCharacteristic.ReadRequested            += OnCharacteristicReadRequested;
            }
            catch (OperationCanceledException)
            {
                Utils.Info("canceled");
                HandleError();
                return;
            }
            catch (Exception e)
            {
                Utils.Error(e.ToString());
                HandleError();
                return;
            }

            lock (mLockObject)
            {
                SetStatus(Status.Ready);

                mCallback.OnReady();
            }
        }