Table of Contents

C++ Integration Guide

This guide explains how to integrate the BLE service into a C++ OpenView application. The companion demo project, Ahsoka.CPP.BLE, provides working source code for everything described here and ships inside the package under demos/.

The concepts are the same as on the C# side — a GATT peripheral, services declared up front, values pushed out and notifications received. What differs is the authoring model: C++ subclasses a base class and fills in protobuf property objects, where C# uses attributes. If you have read Defining GATT Services, the mapping will be obvious.

Start with BLE Overview & Stack Lifecycle for what BLE support does and does not include — in particular, the display is always the peripheral and the central role is not implemented.

Table of Contents

Classes at a Glance

Step 1 — Define a GATT Service

Step 2 — Handle Characteristic Writes

Step 3 — Handle Dynamic Reads

Step 4 — Update Values from App Logic

Step 5 — Wire Up the Application

Step 6 — Handle Pairing

Step 7 — Shutdown

Startup Order Summary

Classes at a Glance

Class Purpose
AhsokaBLE::BLEServiceClient IPC client for the BLE service
AhsokaDevice::DeviceServiceClient Notifies your app when Bluetooth hardware becomes available
BLEServiceBase Base class — subclass this to define a GATT service
BLEServiceManager Registers your services with the BLE stack and routes callbacks
AhsokaCore::SignalHandler Blocks until a shutdown signal is received, then returns so the process can exit

Step 1 — Define a GATT Service

Subclass BLEServiceBase and implement OnConfigure() to declare the service structure.

#include "BLEServiceBase.h"

class MyService : public BLEServiceBase
{
public:
    static constexpr const char* ServiceUUID = "your-service-uuid-here";
    static constexpr const char* MyValueUUID = "your-characteristic-uuid-here";

    void OnConfigure(AhsokaBLE::BLEServiceProperties& props,
                     AhsokaBLE::BLEAdvertisementProperties& advertProps) override
    {
        props.set_uuid(ServiceUUID);
        props.set_local_name("MyService");
        props.set_primary(true);

        // Optional: advertise this service so central devices can discover it.
        advertProps.add_service_uuids(ServiceUUID);

        // Add a characteristic.
        auto* ch = props.add_characteristics();
        ch->set_uuid(MyValueUUID);
        ch->set_name("MyValue");
        ch->add_flags(READ);
        ch->add_flags(WRITE);
        ch->add_flags(NOTIFY);
    }
};

Characteristic Flags

Flag Effect
READ Central can read the stored value
WRITE Central can write a new value
NOTIFY Central can subscribe to value-change notifications
ENCRYPT_READ Read requires an encrypted (paired) connection
ENCRYPT_WRITE Write requires an encrypted (paired) connection

These are the same flags as the C# BLECharacteristicFlag values, in C++ naming. Using an ENCRYPT_* flag is what causes a pairing request to be raised — see Step 6.

Dynamic Characteristics (callback-driven reads and writes)

By default the BLE stack serves stored values directly. Setting use_notify_for_read or use_notify_for_write causes the stack to notify your app instead, so you can generate or process the value in code:

auto* ch = props.add_characteristics();
ch->set_uuid(MyValueUUID);
ch->set_name("MyValue");
ch->add_flags(READ);
ch->add_flags(WRITE);
ch->set_use_notify_for_read(true);   // App receives CHARACTERISTIC_VALUE_READ notification
ch->set_use_notify_for_write(true);  // App receives CHARACTERISTIC_VALUE_WRITE notification

This is the C++ equivalent of the C# [BLECharacteristicReadMethod] and [BLECharacteristicWriteMethod] attributes — a characteristic backed by code rather than by a stored value.

To include vendor-specific data in the BLE advertisement:

std::string payload = {'\x01', '\x02', '\x03', '\x04'};
(*advertProps.mutable_manufacture_datas())[0xYOUR_COMPANY_ID] = payload;

This field is used for device identification or broadcasting state without requiring a connection. The company ID must be a registered Bluetooth SIG value for production use.

Keep the payload small — advertisement packets are tight, and the local name plus every advertised service UUID compete for the same budget.

Step 2 — Handle Characteristic Writes

Override OnCharacteristicWrite() to receive values written by the central device. Always check value.uuid() to confirm the write targets your characteristic.

void OnCharacteristicWrite(AhsokaBLE::BLECharacteristicValue& value) override
{
    if (value.uuid() != MyValueUUID)
        return;

    // value.value() contains the raw bytes written by the central.
    std::string data = value.value();
    // Update your application state here.
}

Step 3 — Handle Dynamic Reads

If you set use_notify_for_read = true, override OnCharacteristicRead(). Populate value with the current data and return true. Return false if the UUID does not belong to this service.

bool OnCharacteristicRead(AhsokaBLE::BLECharacteristicValue& value) override
{
    if (value.uuid() != MyValueUUID)
        return false;

    // Generate or fetch the current value.
    int result = computeCurrentValue();
    value.set_value(reinterpret_cast<const char*>(&result), sizeof(int));
    return true;
}

BLEServiceManager::HandleRead() calls CharacteristicValueReadResult() automatically when your method returns true.

Step 4 — Update Values from App Logic

Call SetValue() (inherited from BLEServiceBase) from anywhere in your service class to push a new value to the BLE stack. These calls are valid only after BLEServiceManager::Start() has been called.

// Push a string value. Pass true to also send a BLE notification.
SetValue(MyValueUUID, std::string("hello"), true);

// Push raw bytes.
SetValue(MyValueUUID, std::vector<uint8_t>{0x01, 0x02, 0x03}, false);

// Send a notification without changing the stored value.
SendNotification(MyValueUUID);

A typical pattern is to expose a public method on your service class that your application calls when relevant state changes:

void UpdateMyValue(const std::string& newValue)
{
    SetValue(MyValueUUID, newValue, true);  // true = notify subscribed centrals
}

Step 5 — Wire Up the Application

Members your app class needs

AhsokaDevice::DeviceServiceClient deviceClient;
AhsokaBLE::BLEServiceClient       bleClient;
BLEServiceManager                 serviceManager;
MyService                         myService;
AhsokaCore::SignalHandler         signals;

Startup sequence

void Run()
{
    AhsokaRuntimeProcess::StartLocalServiceManager();

    // Wait for Bluetooth hardware to become available before starting the BLE stack.
    deviceClient.RegisterListener([this](DeviceMessageTypes_Ids id,
                                         google::protobuf::Message& msg) {
        if (id != DeviceMessageTypes_Ids_DEVICE_ENABLED) return;

        auto& info = static_cast<DeviceInfo&>(msg);
        if (info.device_type() == USB_WIRELESS_COMBO_MODULE ||
            info.device_type() == ONBOARD_WIRELESS_COMBO_MODULE)
        {
            StartBLE();
        }
    });
    deviceClient.Start();
    deviceClient.EnableDeviceNotifications();

    // Register services before the stack starts.
    serviceManager.Add(&myService);

    AhsokaRuntime::ReleaseStartup();
    signals.WaitForExit();  // Block until SIGTERM / SIGINT / SIGHUP / SIGQUIT

    // Shut down running services before exiting. BlueZ automatically cleans up
    // GATT registrations and advertising when the session ends.
    AhsokaRuntime::StopAll();
}

Starting the BLE stack

void StartBLE()
{
    // Register the listener before Start() so no notifications are missed.
    bleClient.RegisterListener([this](BLEMessageTypes_Ids id,
                                      google::protobuf::Message& msg) {
        OnBLENotification(id, msg);
    });
    bleClient.Start();

    BLEStackRequest req;
    req.set_local_name("YourDeviceName");
    bleClient.StartStack(req);
}

Handling BLE notifications

void OnBLENotification(BLEMessageTypes_Ids id, google::protobuf::Message& msg)
{
    switch (id)
    {
        case BLEMessageTypes_Ids_STACK_STARTED:
        {
            auto& notif = static_cast<BLEConnectionNotification&>(msg);
            if (notif.state() == AhsokaBLE::CLIENT_READY)
            {
                // Stack is ready — register GATT services and initialize values.
                serviceManager.Start(bleClient);
                myService.InitializeValues();
            }
            break;
        }

        case BLEMessageTypes_Ids_CHARACTERISTIC_VALUE_WRITE:
            serviceManager.HandleWrite(static_cast<BLECharacteristicValue&>(msg));
            break;

        case BLEMessageTypes_Ids_CHARACTERISTIC_VALUE_READ:
            serviceManager.HandleRead(static_cast<BLECharacteristicValue&>(msg), bleClient);
            break;

        case BLEMessageTypes_Ids_PAIRING_REQUESTED:
            // See Step 6.
            break;

        default:
            break;
    }
}

Step 6 — Handle Pairing

When a central initiates pairing, the BLE service sends a PAIRING_REQUESTED notification containing a passkey. Unless display_only() is set, your app must confirm or reject it.

case BLEMessageTypes_Ids_PAIRING_REQUESTED:
{
    auto& req = static_cast<BLEPairingRequest&>(msg);
    // req.passkey() is the numeric passkey to display to the user.
    if (req.display_only())
        break;  // the user types it on the central; there is nothing to confirm

    BLEPairingConfirmation confirm;
    confirm.set_confirmed(true);  // false to reject
    bleClient.ConfirmPairing(confirm);
    break;
}

In a UI application, display the passkey to the user and wait for their confirmation before calling ConfirmPairing. When display_only() is set, show the passkey without asking anything, and hide it on PAIRING_COMPLETE or PAIRING_CANCELED.

Pairing is requested only because a characteristic carries an ENCRYPT_* flag. If you did not expect a pairing prompt, that is where to look.

Step 7 — Shutdown

After signals.WaitForExit() returns, call AhsokaRuntime::StopAll() to shut down running services. BlueZ automatically cleans up GATT registrations and advertising when the session ends.

Warning

Do not call StopStack, RemoveService, or RemoveAdvertisement directly at this point. The IPC transport is no longer accepting outbound calls and those calls will fail.

Startup Order Summary

  1. Start service processes (AhsokaRuntimeProcess::StartLocalServiceManager)
  2. Register DeviceServiceClient listener and call Start() + EnableDeviceNotifications()
  3. Call BLEServiceManager::Add() for each service
  4. Call AhsokaRuntime::ReleaseStartup()
  5. (On DEVICE_ENABLED for the wireless combo module) — register BLEServiceClient listener, call Start(), call StartStack()
  6. (On STACK_STARTED / CLIENT_READY) — call BLEServiceManager::Start(), then InitializeValues() on each service
  7. (On shutdown signal) — call AhsokaRuntime::StopAll() to shut down running services