/// <summary> /// Starts the Heart rate service /// </summary> public override async Task Init() { await CreateServiceProvider(GattServiceUuids.HeartRate); // Preparing the Blood pressure characteristics var heartRateCharacteristics = PlainNotifyParameters; heartRateCharacteristics.UserDescription = "Heart Rates in Beats per Minute"; heartRateCharacteristics.PresentationFormats.Add( GattPresentationFormat.FromParts( Convert.ToByte(PresentationFormats.FormatTypes.Unsigned16BitInteger), PresentationFormats.Exponent, Convert.ToUInt16(PresentationFormats.Units.PeriodBeatsPerMinute), Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber), PresentationFormats.Description)); // Create the heart rate characteristic for the service GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.HeartRateMeasurement, PlainNotifyParameters); // Grab the characterist object from the service set it to the HeartRate property which is of a specfic Characteristic type GattLocalCharacteristic baseHeartRateMeasurement = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref baseHeartRateMeasurement); if (baseHeartRateMeasurement != null) { HeartRateMeasurement = new Characteristics.HeartRateMeasurementCharacteristic(baseHeartRateMeasurement, this); } }
/// <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); } }
/// <summary> /// Starts the Alert Notification Services for Specific categories /// </summary> /// <param name="connectable">True, starts the service as Connectable. False, starts the service as only Discoverable</param> /// <param name="value">Category ID</param> public async void StartWithValue(bool connectable, byte[] value) { await CreateServiceProvider(GattServiceUuids.AlertNotification); GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.SupportedNewAlertCategory, GetPlainReadParameterWithValue(value)); GattServicesHelper.GetCharacteristicsFromResult(result, ref supportNewAlert); result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.SupportUnreadAlertCategory, GetPlainReadParameterWithValue(value)); GattServicesHelper.GetCharacteristicsFromResult(result, ref supportUnreadAlert); result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.NewAlert, PlainNotifyParameters); GattServicesHelper.GetCharacteristicsFromResult(result, ref newAlert); result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.UnreadAlertStatus, PlainNotifyParameters); GattServicesHelper.GetCharacteristicsFromResult(result, ref unreadAlertStatus); result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.AlertNotificationControlPoint, PlainWriteOrWriteWithoutRespondsParameter); GattServicesHelper.GetCharacteristicsFromResult(result, ref alertNotificationCtrlPnt); if (alertNotificationCtrlPnt != null) { alertNotificationCtrlPnt.WriteRequested += AlertNotificationCtrlPntOnWriteRequested; } // Once all characteristics have been added - publish to the system base.Start(connectable); }
/// <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); } }
/// <summary> /// Starts the Heart rate service /// </summary> public override async Task Init() { await CreateServiceProvider(GattServiceUuids.HeartRate); // Preparing the heart rate characteristics var heartRateCharacteristicsParameters = PlainReadNotifyParameters; //random 4 digits added to manufacturer specific advertisement text Random rnd = new Random(); randomForDescriptor = Convert.ToString(rnd.Next(1000, 9999)); heartRateCharacteristicsParameters.UserDescription = $"{Constants.heartRateDescriptorText}{randomForDescriptor}"; // Create the heart rate characteristic for the service GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.HeartRateMeasurement, heartRateCharacteristicsParameters); // Grab the characteristic object from the service set it to the HeartRate property which is of a specfic Characteristic type GattLocalCharacteristic baseHeartRateMeasurement = null; BLEServices.Helpers.GetCharacteristicsFromResult(result, ref baseHeartRateMeasurement); if (baseHeartRateMeasurement != null) { HeartRateMeasurement = new BLEServices.HeartRateMeasurementCharacteristic(baseHeartRateMeasurement, this); } }
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> /// Asynchronous initialization /// </summary> /// <returns>Initialization task</returns> public override async Task Init() { await CreateServiceProvider(GattServiceUuids.AlertNotification); // Please refer Category ID bit mask https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.alert_category_id_bit_mask.xml // The value 0x21 is interpreted as "Simple Alert and SMS bits set" var categoryBitMask = new AlertCategoryIdBitMask(AlertCategoryIdBitMask_0.SimpleAlert); // SupportedNewAlertCategory GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.SupportedNewAlertCategory, GetPlainReadParameterWithValue(categoryBitMask.Value)); GattServicesHelper.GetCharacteristicsFromResult(result, ref supportNewAlert); // SupportedUnreadAlertCatagory result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.SupportUnreadAlertCategory, GetPlainReadParameterWithValue(categoryBitMask.Value)); GattServicesHelper.GetCharacteristicsFromResult(result, ref supportUnreadAlert); // NewAlert result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.NewAlert, PlainNotifyParameters); GattLocalCharacteristic newAlertCharacteristic = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref newAlertCharacteristic); if (newAlertCharacteristic != null) { NewAlert = new Characteristics.NewAlertCharacteristic(newAlertCharacteristic, this); } // UnreadAlertStatus result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.UnreadAlertStatus, PlainNotifyParameters); GattLocalCharacteristic unreadAlertCharacteristic = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref unreadAlertCharacteristic); if (unreadAlertCharacteristic != null) { UnreadAlertStatus = new Characteristics.UnreadAlertStatusCharacteristic(unreadAlertCharacteristic, this); } // Control Point result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.AlertNotificationControlPoint, PlainWriteOrWriteWithoutRespondsParameter); GattLocalCharacteristic alertNotificationControlPointCharacteristic = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref alertNotificationControlPointCharacteristic); if (alertNotificationControlPointCharacteristic != null) { AlertNotificationControlPoint = new Characteristics.AlertNotificationControlPointCharacteristic(alertNotificationControlPointCharacteristic, this); } }
/// <summary> /// Get Characteristics from the Characteristics Result /// </summary> /// <param name="result">Gatt Characteristics Result</param> /// <param name="characteristics">Gatt characteristics</param> public static void GetCharacteristicsFromResult(GattLocalCharacteristicResult result, ref GattLocalCharacteristic characteristics) { if (result.Error == BluetoothError.Success) { characteristics = result.Characteristic; } else { Debug.WriteLine(result.Error.ToString()); } }
/// <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; }
/// <summary> /// Starts the Current time service /// </summary> /// <param name="connectable">True, starts the service as Connectable. False, starts the service as only Discoverable</param> public override async void Start(bool connectable) { await CreateServiceProvider(GattServiceUuids.CurrentTime); GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.CurrentTime, PlainReadNotifyParameters); GattServicesHelper.GetCharacteristicsFromResult(result, ref currentTime); if (currentTime != null) { currentTime.ReadRequested += ReadCharacteristicReadRequested; } base.Start(connectable); }
/// <summary> /// Asynchronous initialization /// </summary> /// <returns>Initialization Task</returns> public override async Task Init() { await CreateServiceProvider(GattServiceUuids.CurrentTime); GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.CurrentTime, PlainReadNotifyParameters); GattLocalCharacteristic currentTimeCharacterisitic = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref currentTimeCharacterisitic); if (currentTimeCharacterisitic != null) { CurrentTime = new Characteristics.CurrentTimeCharacteristic(currentTimeCharacterisitic, this); } }
/// <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); } }
/// <summary> /// Check that the service has started, start up the characteristics required for the BLE Service /// </summary> /// <returns></returns> private async Task ServiceProviderInitAsync() { // Initialize and starting a custom GATT Service MainService = await GattServiceProvider.CreateAsync(Constants.serviceProviderUuid); if (MainService.Error == BluetoothError.Success) { serviceProvider = MainService.ServiceProvider; } else { // An error occurred. serviceStarted = false; } characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ReadCharacteristicUuid, Constants.gattReadParameters); if (characteristicResult.Error != BluetoothError.Success) { // An error occurred. serviceStarted = false; } readCharacteristic = characteristicResult.Characteristic; readCharacteristic.ReadRequested += ReadCharacteristic_ReadRequested; characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(Constants.WriteCharacteristicUuid, Constants.gattWriteParameters); if (characteristicResult.Error != BluetoothError.Success) { // An error occurred. serviceStarted = false; } writeCharacteristic = characteristicResult.Characteristic; writeCharacteristic.WriteRequested += WriteCharacteristic_WriteRequested; }
//--------------------------------------------------------------------- // Asynchronous initialization //--------------------------------------------------------------------- public override async Task InitAsync() { await CreateServiceProvider(Constants.IPv6ToBlePacketProcessingServiceUuid); GattLocalCharacteristicResult characteristicResult = null; // // Step 1 // Create the packet write characteristic // GattLocalCharacteristic createdPacketWriteCharacteristic = null; characteristicResult = await ServiceProvider.Service.CreateCharacteristicAsync( Constants.IPv6ToBlePacketWriteCharacteristicUuid, GattHelpers.packetWriteParameters ); // // Step 2 // Assign the created packet write characteristic to this service's internal one // GattHelpers.GetCharacteristicFromResult(characteristicResult, ref createdPacketWriteCharacteristic ); if (createdPacketWriteCharacteristic != null) { PacketWriteCharacteristic = new IPv6ToBlePacketWriteCharacteristic( createdPacketWriteCharacteristic, this ); } characteristicResult = null; // // Step 3 // Create the compressed header length characteristic // GattLocalCharacteristic createdCompressedHeaderLengthCharacteristic = null; characteristicResult = await ServiceProvider.Service.CreateCharacteristicAsync( Constants.IPv6ToBleCompressedHeaderLengthCharacteristicUuid, GattHelpers.packetWriteParameters ); // // Step 4 // Assign the created compressed header length characteristic to this service's internal one // GattHelpers.GetCharacteristicFromResult(characteristicResult, ref createdCompressedHeaderLengthCharacteristic ); if (createdCompressedHeaderLengthCharacteristic != null) { CompressedHeaderLengthCharacteristic = new CompressedHeaderLengthCharacteristic( createdCompressedHeaderLengthCharacteristic, this ); } characteristicResult = null; // // Step 5 // Create the payload length characteristic // GattLocalCharacteristic createdPayloadLengthCharacteristic = null; characteristicResult = await ServiceProvider.Service.CreateCharacteristicAsync( Constants.IPv6ToBlePayloadLengthCharacteristicUuid, GattHelpers.packetWriteParameters ); // // Step 6 // Assign the created payload length characteristic to this service's internal one // GattHelpers.GetCharacteristicFromResult(characteristicResult, ref createdPayloadLengthCharacteristic ); if (createdPayloadLengthCharacteristic != null) { PayloadLengthCharacteristic = new PayloadLengthCharacteristic( createdPayloadLengthCharacteristic, this ); } characteristicResult = null; // // Step 7 // Create the IPv6 address read characteristic // // Generate the device's link-local IPv6 address IPAddress address = await StatelessAddressConfiguration.GenerateLinkLocalAddressFromBlThRadioIdAsync(2); if (address == null) { Debug.WriteLine("Could not generate a link-local IPv6 address" + " from the Bluetooth address." ); return; } // Create the characteristic GattLocalCharacteristic createdIPv6AddressReadCharacteristic = null; characteristicResult = await ServiceProvider.Service.CreateCharacteristicAsync( Constants.IPv6ToBleIPv6AddressCharacteristicUuid, GattHelpers.ipv6AddressReadParameters ); // // Step 8 // Assign the created IPv6 address read characteristic to this service's internal one // GattHelpers.GetCharacteristicFromResult(characteristicResult, ref createdIPv6AddressReadCharacteristic ); if (createdIPv6AddressReadCharacteristic != null) { IPv6AddressCharacteristic = new IPv6ToBleIPv6AddressCharacteristic( createdIPv6AddressReadCharacteristic, this, address ); } }
/// <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; }
/// <summary> /// Uses the relevant Service/Characteristic UUIDs to initialize, hook up event handlers and start a service on the local system. /// </summary> /// <returns></returns> private async Task <bool> ServiceProviderInitAsync() { // BT_Code: Initialize and starting a custom GATT Service using GattServiceProvider. GattServiceProviderResult serviceResult = await GattServiceProvider.CreateAsync(Constants.CalcServiceUuid); if (serviceResult.Error == BluetoothError.Success) { serviceProvider = serviceResult.ServiceProvider; } else { rootPage.NotifyUser($"Could not create service provider: {serviceResult.Error}", NotifyType.ErrorMessage); return(false); } GattLocalCharacteristicResult result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op1CharacteristicUuid, Constants.gattOperandParameters); if (result.Error == BluetoothError.Success) { op1Characteristic = result.Characteristic; } else { rootPage.NotifyUser($"Could not create operand1 characteristic: {result.Error}", NotifyType.ErrorMessage); return(false); } op1Characteristic.WriteRequested += Op1Characteristic_WriteRequestedAsync; result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op2CharacteristicUuid, Constants.gattOperandParameters); if (result.Error == BluetoothError.Success) { op2Characteristic = result.Characteristic; } else { rootPage.NotifyUser($"Could not create operand2 characteristic: {result.Error}", NotifyType.ErrorMessage); return(false); } op2Characteristic.WriteRequested += Op2Characteristic_WriteRequestedAsync; result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.OperatorCharacteristicUuid, Constants.gattOperatorParameters); if (result.Error == BluetoothError.Success) { operatorCharacteristic = result.Characteristic; } else { rootPage.NotifyUser($"Could not create operator characteristic: {result.Error}", NotifyType.ErrorMessage); return(false); } operatorCharacteristic.WriteRequested += OperatorCharacteristic_WriteRequestedAsync; // Add presentation format - 32-bit unsigned integer, with exponent 0, the unit is unitless, with no company description GattPresentationFormat intFormat = GattPresentationFormat.FromParts( GattPresentationFormatTypes.UInt32, PresentationFormats.Exponent, Convert.ToUInt16(PresentationFormats.Units.Unitless), Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber), PresentationFormats.Description); Constants.gattResultParameters.PresentationFormats.Add(intFormat); result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ResultCharacteristicUuid, Constants.gattResultParameters); if (result.Error == BluetoothError.Success) { resultCharacteristic = result.Characteristic; } else { rootPage.NotifyUser($"Could not create result characteristic: {result.Error}", NotifyType.ErrorMessage); return(false); } resultCharacteristic.ReadRequested += ResultCharacteristic_ReadRequestedAsync; resultCharacteristic.SubscribedClientsChanged += ResultCharacteristic_SubscribedClientsChanged; // BT_Code: Indicate if your sever advertises as connectable and discoverable. GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters { // IsConnectable determines whether a call to publish will attempt to start advertising and // put the service UUID in the ADV packet (best effort) IsConnectable = peripheralSupported, // IsDiscoverable determines whether a remote device can query the local device for support // of this service IsDiscoverable = true }; serviceProvider.AdvertisementStatusChanged += ServiceProvider_AdvertisementStatusChanged; serviceProvider.StartAdvertising(advParameters); return(true); }
/// <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() { 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); } }
/// <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); } }
/// <summary> /// Asynchronous initialization /// </summary> /// <returns>Initialization Task</returns> public override async Task Init() { await CreateServiceProvider(GattServiceUuids.BloodPressure); // Preparing the Blood pressure characteristics var bloodPressureCharacteristics = PlainIndicateParameters; bloodPressureCharacteristics.UserDescription = "Blood Pressure in mm Hg"; bloodPressureCharacteristics.PresentationFormats.Add( GattPresentationFormat.FromParts( Convert.ToByte(PresentationFormats.FormatTypes.OpaqueStructure), PresentationFormats.Exponent, Convert.ToUInt16(PresentationFormats.Units.PressureMilliMetreofmercury), Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber), PresentationFormats.Description)); // Create the blood pressure measurement characteristic for the service GattLocalCharacteristicResult result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.BloodPressureMeasurement, bloodPressureCharacteristics); // Grab the characterist object from the service GattLocalCharacteristic baseBloodPressureMeasurement = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref baseBloodPressureMeasurement); if (baseBloodPressureMeasurement != null) { BloodPressureMeasurement = new Characteristics.BloodPressureMeasurementCharacteristic(baseBloodPressureMeasurement, this); } result = null; // Preparing the Blood pressure feature characteristics var bloodPressureFeatureCharacteristics = PlainReadParameter; bloodPressureFeatureCharacteristics.UserDescription = "The Blood Pressure Feature characteristic is used to describe the supported features of the Blood Pressure Sensor."; bloodPressureFeatureCharacteristics.PresentationFormats.Add( GattPresentationFormat.FromParts( Convert.ToByte(PresentationFormats.FormatTypes.Unsigned16BitInteger), PresentationFormats.Exponent, Convert.ToUInt16(PresentationFormats.Units.Unitless), Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber), PresentationFormats.Description)); // Create the blood pressure measurement characteristic for the service result = await ServiceProvider.Service.CreateCharacteristicAsync( GattCharacteristicUuids.BloodPressureFeature, bloodPressureFeatureCharacteristics); // Grab the characterist object from the service GattLocalCharacteristic baseBloodPressureFeature = null; GattServicesHelper.GetCharacteristicsFromResult(result, ref baseBloodPressureFeature); if (baseBloodPressureFeature != null) { BloodPressureFeature = new Characteristics.BloodPressureFeatureCharacteristic(baseBloodPressureFeature, this); } }
/// <summary> /// Uses the relevant Service/Characteristic UUIDs to initialize, hook up event handlers and start a service on the local system. /// </summary> /// <returns></returns> private async Task <bool> ServiceProviderInitAsync() { var requestStatus = await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync(); if (requestStatus == BackgroundAccessStatus.Denied || requestStatus == BackgroundAccessStatus.DeniedByUser || requestStatus == BackgroundAccessStatus.DeniedBySystemPolicy) { rootPage.NotifyUser("BackgroundTask cannot to be registered", NotifyType.ErrorMessage); return(false); } // Depending on the value of requestStatus, provide an appropriate response // such as notifying the user which functionality won't work as expected //await RegisterBlAdvertisementTask(); await RegisterAppTriggeredTask(); await RegisterTimeTriggeredTask(); // BT_Code: Initialize and starting a custom GATT Service using GattServiceProvider. //GattServiceProviderResult serviceResult = await GattServiceProvider.CreateAsync(Constants.CalcServiceUuid); var serviceResultTriggerResult = await GattServiceProviderTrigger.CreateAsync(TaskName, Constants.CalcServiceUuid); if (serviceResultTriggerResult.Error == BluetoothError.Success) { serviceProviderTrigger = serviceResultTriggerResult.Trigger; } else { rootPage.NotifyUser($"Could not create service provider: {serviceResultTriggerResult.Error}", NotifyType.ErrorMessage); return(false); } GattLocalCharacteristicResult result = await serviceProviderTrigger.Service.CreateCharacteristicAsync(Constants.Op1CharacteristicUuid, Constants.gattOperand1Parameters); if (result.Error == BluetoothError.Success) { op1Characteristic = result.Characteristic; } else { rootPage.NotifyUser($"Could not create operand1 characteristic: {result.Error}", NotifyType.ErrorMessage); return(false); } GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters { // IsConnectable determines whether a call to publish will attempt to start advertising and // put the service UUID in the ADV packet (best effort) IsConnectable = peripheralSupported, // IsDiscoverable determines whether a remote device can query the local device for support // of this service IsDiscoverable = true }; //serviceProviderTrigger.AdvertisementStatusChanged += ServiceProvider_AdvertisementStatusChanged; //serviceProvider.StartAdvertising(advParameters); //var triggerResult = await GattServiceProviderTrigger.CreateAsync("ttt", Constants.CalcServiceUuid); serviceProviderTrigger.AdvertisingParameters = advParameters; RegistarGattServerBgTaskTrigger(); return(true); }