Defining GATT Services
The declarative layer is the intended way to build a GATT server. You write a class, decorate it with attributes, and the extension builds the GATT database, wires reads and writes to your properties, sends notifications when values change, and builds the advertisement.
Table of Contents
Advertisements and Manufacturer Data
The Shape of a Service
Derive from BLEServiceViewModelBase, put [BLEService] on the class and [BLECharacteristic] on
properties:
using Ahsoka.Services.BLE;
using Ahsoka.Services.BLE.ViewModel;
[BLEService("ExampleService", ServiceUUID)]
[BLEManufactureData(0xFFFE, 0xFF, 0xFF, 0xFF, 0xFF)]
public class ExampleService : BLEServiceViewModelBase
{
const string ServiceUUID = "78e4de00-1e75-4032-a619-4d97982a479d";
const string StringValueUUID = "78e4de01-1e75-4032-a619-4d97982a479d";
const string ByteValueUUID = "78e4de02-1e75-4032-a619-4d97982a479d";
string stringValue = string.Empty;
byte[] byteValue;
[BLECharacteristic("StringValue", StringValueUUID,
BLECharacteristicFlag.EncryptRead,
BLECharacteristicFlag.EncryptWrite,
BLECharacteristicFlag.Notify)]
public string StringValue
{
get { return stringValue; }
set { OnSetObject(ref stringValue, value); }
}
[BLECharacteristic("ByteValue", ByteValueUUID,
BLECharacteristicFlag.Read,
BLECharacteristicFlag.Write)]
public byte[] ByteValue
{
get { return byteValue; }
set { OnSetObject(ref byteValue, value); }
}
public ExampleService()
{
StringValue = "MyStartValue";
ByteValue = [0, 1, 2, 3];
}
}
flowchart TB
cls["[BLEService] class<br/>ExampleService"]
mfg["[BLEManufactureData]"]
p1["[BLECharacteristic]<br/>StringValue"]
p2["[BLECharacteristic]<br/>ByteValue"]
gsvc["GATT service<br/>78e4de00-…"]
gc1["Characteristic 78e4de01-…<br/>EncryptRead · EncryptWrite · Notify"]
gc2["Characteristic 78e4de02-…<br/>Read · Write"]
adv["Advertisement<br/>service UUID + manufacturer data"]
cls --> gsvc
p1 --> gc1
p2 --> gc2
gsvc --> gc1
gsvc --> gc2
cls --> adv
mfg --> adv
BLEService
[BLEService(string name, string uUID, bool isPrimary = true, bool advertise = true)]
| Parameter | Meaning |
|---|---|
name |
Friendly name, used in logs and diagnostics |
uUID |
The GATT service UUID |
isPrimary |
Whether this is a primary service. Defaults to true. |
advertise |
Whether the service UUID goes in the advertisement. Defaults to true. |
Important
These are positional constructor arguments. There is no parameterless constructor, and UUID, Name,
and Flags are init-only, so the named-argument form [BLEService(UUID = "…", Name = "…")] will not
compile. Pass name and UUID positionally, as above.
A service that should be reachable but not advertised sets advertise to false — a central that already
knows the UUID can still discover it after connecting:
[BLEService("ExampleService2", ServiceUUID, true, false)]
Characteristics as Properties
[BLECharacteristic(string name, string uUID, params BLECharacteristicFlag[] flags)]
Put it on a property whose setter calls the base helper. Which helper depends on the type:
| Property type | Setter helper |
|---|---|
Reference types — string, byte[] |
OnSetObject(ref field, value) |
Value types — byte, int, bool |
OnSetValue(ref field, value) |
[BLECharacteristic("BatteryLevel", BatteryLevelUUID,
BLECharacteristicFlag.Read, BLECharacteristicFlag.Notify)]
public byte BatteryLevel
{
get { return batteryLevel; }
set { OnSetValue(ref batteryLevel, value); }
}
Calling the helper is what makes the characteristic work. It updates the backing field, pushes the new value
into the GATT database, and — when the characteristic has Notify or Indicate — notifies subscribed
centrals. A plain assignment does neither, so a characteristic whose value never reaches the central is
almost always a setter that skipped the helper.
Updating a value from application code is then just a property set:
service.BatteryLevel = 87; // read by centrals, and notified to subscribers
Characteristic Flags
BLECharacteristicFlag maps to the GATT flags. The ones in ordinary use:
| Flag | Effect |
|---|---|
Read |
Central may read |
Write |
Central may write, with response |
WriteWithoutResponse |
Central may write, unacknowledged |
Notify |
Server may push updates; central subscribes |
Indicate |
Like Notify, but acknowledged |
Broadcast |
Value may be broadcast |
Encrypted variants require pairing before access, which is what triggers the pairing flow in BLE Overview:
| Flag | Effect |
|---|---|
EncryptRead, EncryptWrite |
Require an encrypted link |
EncryptNotify, EncryptIndicate |
Require an encrypted link for notifications |
EncryptAuthenticatedRead, EncryptAuthenticatedWrite, EncryptAuthenticatedNotify, EncryptAuthenticatedIndicate |
Require authenticated encryption — pairing with confirmation |
SecureRead, SecureWrite, SecureNotify |
Require LE Secure Connections |
Also available for completeness: AuthenticatedSignedWrites, ExtendedProperties, ReliableWrite,
WritableAuxiliaries.
Combine flags by listing them — the parameter is params, so there is no array syntax and no |:
[BLECharacteristic("Value", ValueUUID,
BLECharacteristicFlag.EncryptRead,
BLECharacteristicFlag.EncryptWrite,
BLECharacteristicFlag.Notify)]
Note that Notify alongside encrypted read and write is not automatically encrypted. Use EncryptNotify
if the notification itself must be protected.
Characteristics as Methods
A property holds a value. Sometimes you want to compute one at read time, or act on a write without storing it. Use the method attributes instead:
[BLECharacteristicReadMethod("DataValue", DataValueUUID, BLECharacteristicFlag.Read)]
public void ReadDataValue(BLECharacteristicValue updateNotification)
{
int value = Random.Shared.Next(0, 99999);
updateNotification.Value = BitConverter.GetBytes(value);
}
[BLECharacteristicWriteMethod("DataValue", DataValueUUID, BLECharacteristicFlag.Write)]
public void WriteDataValue(BLECharacteristicValue updateNotification)
{
DataValue = updateNotification.Value;
}
The read method is called when a central reads, and you set updateNotification.Value to whatever should be
returned right now.
A read method and a write method with the same UUID are combined into one characteristic, with the union of their flags. That is how you get a single read/write characteristic backed by methods rather than a property — declare both, give them the same UUID, and give each the flag it needs.
Reacting to Writes
Override OnHandleWriteRequest to observe or validate every write to the service:
protected override void OnHandleWriteRequest(BLECharacteristicValue updateNotification)
{
AhsokaLogger.Default.LogMessage(Severity.Medium, BluetoothLogGroups.BLE,
$"Characteristic written: {updateNotification.Uuid}");
}
The default implementation accepts a value whose UUID matches a declared characteristic. Override it to add
range checks, cross-field validation, or a side effect such as updating your UI. updateNotification.Uuid
tells you which characteristic was written.
This fires for property-backed characteristics. Method-backed ones are handled by their own write method.
Advertisements and Manufacturer Data
By default a service with advertise set to true contributes its UUID to the advertisement, and
StartServiceModels starts advertising. For most applications that is all that is needed.
To add manufacturer-specific data, decorate the class:
[BLEManufactureData(0xFFFE, 0xFF, 0xFF, 0xFF, 0xFF)]
[BLEManufactureData(ushort key, params byte[] data)]
key is the 16-bit company identifier and data is the payload bytes. This is the usual way a companion
phone app recognises your display among other advertisers without connecting first.
Keep the payload small. BLE advertisement packets are tight, and the local name passed to StartStack plus
every advertised service UUID compete for the same budget. If your advertisement stops appearing after you
add data, it has overflowed — shorten the local name, drop a service's advertise flag, or trim the payload.
For full control there is CreateAdvertisement(BLEAdvertisementProperties, timeoutInMs) and
RemoveAdvertisement(BLEAdvertisementInfo, timeoutInMs) on the client, alongside
EnableService(client, advertProps) on the service base. Reach for these only when the attributes cannot
express what you need.
Registering
Register after the stack reports ClientReady:
bleClient.StartServiceModels(serviceExample, serviceExample2);
This registers every decorated service and begins advertising. To remove them:
bleClient.StopServiceModels(serviceExample, serviceExample2);
Construct your service objects early — their constructors set initial characteristic values — but register them only once the stack is up. See BLE Overview.
Gotchas
Positional attribute arguments only. [BLEService(UUID = "…", Name = "…")] does not compile. Same for
[BLECharacteristic].
Flags is a params list, not an array. Write the flags out; do not pass new[] { … }.
Use the right setter helper. OnSetObject for reference types, OnSetValue for value types. A plain
assignment silently does nothing useful.
Register after ClientReady, not before. Registration against a stack that is not up fails.
Encrypted flags trigger pairing. If you did not expect a pairing prompt, check for an Encrypt* flag.
Notify needs a subscriber. Notifications go to centrals that have subscribed via the CCCD. A value
change with nobody subscribed goes nowhere, which is correct behavior rather than a fault.
Verify on hardware. The BLE desktop implementation is a stub that does not advertise or serve GATT.