Skip to content

lynxal/csharp-bgapi

CsharpBgapi -- Silicon Labs BGAPI Library for C# / .NET

NuGet Build License: MIT

CsharpBgapi is a C# / .NET library for the Silicon Labs BGAPI protocol, enabling serial communication with EFR32 NCP (Network Co-Processor) devices for Bluetooth and Bluetooth Mesh applications.

This is the only actively maintained .NET implementation of the modern Silicon Labs BGAPI protocol (EFR32 series, XAPI-driven -- not the legacy Bluegiga/BLED112 protocol). It provides command/response framing, event selectors with parameter matching, retry logic, and XAPI-driven protocol definitions.

Ported from the official Python pyBGAPI library by Silicon Labs, CsharpBgapi brings the same capabilities to the .NET ecosystem.

Why CsharpBgapi?

  • Modern BGAPI v3+ -- targets the current EFR32 NCP platform, not the discontinued Bluegiga/BLED112 hardware
  • XAPI-driven -- protocol definitions are loaded from Silicon Labs' own XML API files, so the library stays current with new firmware versions
  • .NET 9.0+ / .NET 10.0+ -- built for modern .NET with dependency injection, async/await, and IOptions<T> configuration
  • Production-ready -- retry logic, event selectors, thread-safe serial I/O, and configurable timeouts
  • Drop-in NuGet package -- dotnet add package CsharpBgapi with built-in Bluetooth and Bluetooth Mesh XAPI definitions included

Architecture

BgapiDevice (main entry point)
+-- BgapiConnector   -- Serial port I/O with framing and device ID validation
+-- BgapiProtocol    -- BGAPI message encoding/decoding from XAPI definitions
+-- BgapiEventQueue  -- Selector-based event waiting with retry support
  • BgapiDevice orchestrates the connector, protocol, and event queue. It runs a background reader thread that dispatches responses and events.
  • BgapiConnector handles raw serial communication with thread-safe send/receive locks.
  • BgapiProtocol encodes commands and decodes messages using XAPI XML definitions.
  • BgapiEventQueue provides WaitEvents (selector-based event matching) and RetryUntilAsync (command retry with event confirmation).

Prerequisites

  • .NET 9.0 or later
  • Silicon Labs NCP hardware (e.g., EFR32 series with Bluetooth/Bluetooth Mesh firmware)
  • Silicon Labs Gecko SDK (optional -- only needed if you want custom XAPI files instead of the built-in defaults)

Installation

dotnet add package CsharpBgapi

XAPI Setup

XAPI definition files describe the BGAPI protocol surface (commands, events, parameters). This library includes built-in XAPI definitions for Bluetooth and Bluetooth Mesh (v10.1.1), so most users can get started immediately.

Using Built-in Defaults

device.LoadDefaultXapis(); // Loads Bluetooth + Bluetooth Mesh definitions

Using Custom XAPI Files

If you need XAPI definitions from a different Gecko SDK version, you can load them manually:

  1. Install Silicon Labs Gecko SDK (via Simplicity Studio or standalone)
  2. Locate the XAPI files:
    • Bluetooth: <gecko_sdk>/protocol/bluetooth/api/sl_bt.xapi
    • Bluetooth Mesh: <gecko_sdk>/protocol/bluetooth/api/sl_btmesh.xapi
  3. Load them at runtime:
device.LoadXapi("/path/to/sl_bt.xapi");
device.LoadXapi("/path/to/sl_btmesh.xapi");

Note: Use XAPI files that match your NCP firmware version for correct protocol definitions.

Quick Start

using CsharpBgapi;

var device = new BgapiDevice();
device.LoadDefaultXapis();
device.Open("/dev/ttyACM0"); // or "COM3" on Windows

var response = await device.SendCommandAsync("bt", "system", "hello");
Console.WriteLine($"Status: {response.Status}");

device.Close();

Configuration

All tunable parameters are exposed via CsharpBgapiOptions:

Property Default Description
DefaultBaudRate 115200 Default baud rate for serial port communication
SerialReadTimeoutMs 1000 Serial port read timeout (ms)
SerialWriteTimeoutMs 1000 Serial port write timeout (ms)
ReadExactMaxRetries 5 Max retries for partial read timeouts
ResponseTimeoutSeconds 2.0 Default timeout for command responses
ReaderLoopReadTimeoutMs 100 Read timeout for background reader loop (ms)
StopReaderTimeoutSeconds 2.0 Timeout for stopping the reader thread
WaitEventsDefaultMaxTimeSeconds 10.0 Default max time for WaitEvents
RetryMax 5 Max outer retries in RetryUntilAsync
RetryIntervalSeconds 1.0 Interval between outer retries
RetryCmdMax 6 Max command-level retries for transient errors
RetryCmdIntervalSeconds 1.0 Interval between command retries

Dependency Injection

Basic (loads built-in XAPI definitions automatically)

services.AddCsharpBgapi();

Without Built-in XAPI Defaults

services.AddCsharpBgapi(loadDefaultXapis: false);

With Configuration Binding

services.Configure<CsharpBgapiOptions>(configuration.GetSection("CsharpBgapi"));
services.AddCsharpBgapi();

With Inline Configuration

services.AddCsharpBgapi(options =>
{
    options.ResponseTimeoutSeconds = 5.0;
    options.RetryMax = 10;
});

appsettings.json

{
  "CsharpBgapi": {
    "DefaultBaudRate": 115200,
    "SerialReadTimeoutMs": 1000,
    "SerialWriteTimeoutMs": 1000,
    "ReadExactMaxRetries": 5,
    "ResponseTimeoutSeconds": 2.0,
    "ReaderLoopReadTimeoutMs": 100,
    "StopReaderTimeoutSeconds": 2.0,
    "WaitEventsDefaultMaxTimeSeconds": 10.0,
    "RetryMax": 5,
    "RetryIntervalSeconds": 1.0,
    "RetryCmdMax": 6,
    "RetryCmdIntervalSeconds": 1.0
  }
}

Usage Examples

Wait for Events

var selector = new EventSelector("bt", "mesh", "vendor_model_receive");
var events = device.WaitEvents(selector, TimeSpan.FromSeconds(5), finalEventCount: 3);

Retry Pattern

var events = await device.RetryUntilAsync(
    command: () => device.SendCommandAsync("bt", "mesh", "vendor_model_send", parameters),
    eventSelector: new EventSelector("bt", "mesh", "vendor_model_receive"),
    retryParams: new RetryParams { RetryMax = 3, RetryInterval = TimeSpan.FromSeconds(2) },
    finalEventCount: 1);

Subscribe to Events

device.Subscribe("evt_mesh_vendor_model_receive", message =>
{
    Console.WriteLine($"Received vendor event: {message.EventName}");
});

API Reference

Class Responsibility
BgapiDevice Main entry point -- open/close, send commands, wait events, subscribe
BgapiConnector Serial port I/O with framing and device ID validation
BgapiProtocol BGAPI message encoding/decoding
BgapiEventQueue Event queue with selector-based waiting and retry logic
XapiDefinitions XAPI XML definition loading and lookup
EventSelector Event matching criteria for WaitEvents
CsharpBgapiOptions Configuration POCO for all tunable parameters
CsharpBgapiServiceExtensions DI registration extension methods
SlStatus Silicon Labs status/error code enum (275+ codes)
CommandBuilder Fluent command builder for constructing BGAPI commands

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

This project is licensed under the MIT License -- see LICENSE for details.

Note: The bundled XAPI definition files (sl_bt.xapi, sl_btmesh.xapi) originate from the Silicon Labs Gecko SDK. See the Gecko SDK license for terms governing these files.

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages