bgapi

2026-11-29

Silicon Labs BGAPI for Common Lisp.

Upstream URL

github.com/lispnik/bgapi

Author

Matthew Kennedy <burnsidemk@gmail.com>

Maintainer

Matthew Kennedy <burnsidemk@gmail.com>

License

Zlib
README

bgapi

CI

A Common Lisp implementation of BGAPI, the binary protocol used to drive Silicon Labs Bluetooth and 802.15.4 network co-processor (NCP) targets over a serial port or a socket.

BGAPI is data-driven: an XML "XAPI" file shipped with the Gecko/Simplicity SDK describes every class, command, event, enum and parameter type the target understands. This library reads that file and gives you the whole command surface from it — either resolved at run time, or generated into real functions at compile time.

It is a port of pyBGAPI, faithful at the byte level: the wire encoding, the tolerant decoding behaviour and the robust framing all match, and pyBGAPI's own test vectors are the test suite here.

It also does something pyBGAPI does not: it can be the device. bgapi/sim answers commands and emits events, so a BGAPI host — this one, pyBGAPI, C BGLib, or NCP Commander — can be developed and tested with no hardware attached.

Installation

Dependencies are managed with ocicl:

ocicl install

SBCL. The library uses sb-posix termios, sb-bsd-sockets, sb-sys:wait-until-fd-usable and sb-thread directly, and does not pretend otherwise. CI tests 2.5.9 and 2.6.x; older versions are untested rather than unsupported.

There was briefly a hard 2.4.0 floor here, justified by two failures on Debian's 2.2.9. Both turned out to be bugs in this library — one ignoring SBCL's documented condition-wait contract, one an unescaped quote in a docstring — so the gate was removed. See bgapi.asd.

You will also need an .xapi file — the API description the whole library is driven by. Two come with the checkout, via a submodule:

git clone --recursive https://github.com/lispnik/bgapi
# or, in an existing clone:
git submodule update --init
vendor/pybgapi-examples/api/sl_bt.xapi      Bluetooth LE
vendor/pybgapi-examples/api/sl_btmesh.xapi  Bluetooth Mesh

That is a reference to SiliconLabs/pybgapi-examples, not a copy of it — nothing is redistributed here, and the fetch comes from Silicon Labs. That repository is Zlib-licensed, same as this one.

For other versions, scripts/fetch-xapi.sh pulls them from the public Gecko SDK into a gitignored xapi/:

scripts/fetch-xapi.sh          # gsdk_4.0 -> sl_bt 3.3.2, the default
scripts/fetch-xapi.sh gsdk_4.4 # -> sl_bt 7.3.0
scripts/fetch-xapi.sh --list   # tag-to-version mapping

The version matters, but not uniformly: commands survive a mismatch, events do not. Measured against real hardware in doc/hardware-test.md — a description eight releases newer than the firmware still reports the right stack version and address, and drops every advertisement report. Match it if you consume events.

Usage

The run-time path

Read an API, open a link, send commands, read events:

(defparameter *bt*
  (bgapi:read-xapi #p"/opt/sdk/protocol/bluetooth/api/sl_bt.xapi"))

(bgapi:with-open-link (link (bgapi:make-serial-connector "/dev/tty.usbmodem1421"
                                                         :baud 115200)
                            *bt*)
  (bgapi:command link :system :hello)

  ;; The response is the primary value; its parameters follow, in order.
  (multiple-value-bind (response result tx rx crc-errors)
      (bgapi:command link :system :get-counters 0)
    (declare (ignore response result))
    (format t "tx ~d  rx ~d  crc errors ~d~%" tx rx crc-errors))

  ;; Or reach into it by name.
  (bgapi:msg-value (bgapi:command link :system :get-identity-address) :address)

  (bgapi:command link :system :reset 0)
  (bgapi:do-events (event link :timeout 10)
    (bgapi:event-case event
      ((:bt-evt-system-boot major minor patch build)
       (format t "stack booted: v~d.~d.~d-b~d~%" major minor patch build)
       (return))
      (t nil))))

A command that fails signals command-failed, carrying the response and the errorcode:

(handler-case (bgapi:command link :advertiser :start 0 0 0)
  (bgapi:command-failed (condition)
    (format t "error 0x~x -- create an advertising set first~%"
            (bgapi:command-failed-errorcode condition))))

command-failed also establishes a continue restart that returns the response as if it had succeeded, and ignoring-command-errors wraps the whole family:

(bgapi:ignoring-command-errors
  (bgapi:command link :advertiser :stop handle))

The compile-time path

define-bgapi reads the .xapi during macroexpansion and defines a real function per command, with the vendor's own parameter names and documentation, so your editor can complete and describe them:

(defpackage #:sl-bt (:use #:cl))
(in-package #:sl-bt)

(bgapi:define-bgapi #p"/opt/sdk/protocol/bluetooth/api/sl_bt.xapi"
  :prefix "bt-")

(bt-system-hello link)
(bt-le-gap-set-mode link 2 2)
(describe 'bt-le-gap-set-advertise-timing)   ; the vendor's own prose
+bt-connection-role-peripheral+              ; enums become constants

The parsed API is written into the fasl, so a delivered binary contains the whole model and never loads cxml — or needs the .xapi file to still exist.

Connectors

Servers listen with make-socket-listener / accept-connection, which is how the simulator gets its connection.

ConstructorTransport
make-serial-connectorA serial port, with baud and optional RTS/CTS
make-socket-connectorTCP (:inet, :inet6) or a Unix-domain socket (:unix)
make-robust-connectorWraps another connector in the 0x5A framing with CRCs
make-cpc-connectorNot implemented — see Known gaps
(bgapi:make-serial-connector "/dev/ttyACM0" :baud 921600 :rtscts t)
(bgapi:make-socket-connector "127.0.0.1" :port 4901)
(bgapi:make-socket-connector "/var/run/bgapi.sock" :family :unix)
(bgapi:make-robust-connector (bgapi:make-serial-connector "/dev/ttyACM0"))

Implementing your own is four methods: connector-open, connector-close, connector-write, connector-read.

Simulating a device

Everything above speaks the host half of the protocol. bgapi/sim speaks the other half — it reads commands, answers them, and pushes events:

(bgapi:with-socket-listener (listener "127.0.0.1" :port 4901 :reuse-address t)
  (let ((sim (bgapi:make-simulator api :trace-stream *standard-output*)))
    (bgapi:simulator-serve sim (bgapi:accept-connection listener))

    ;; Every command answers successfully until you say otherwise, so a host
    ;; can run its whole start-up sequence before a single handler exists.

    ;; A command that fails, on demand — an integer is an errorcode.
    (bgapi:define-command-handler (sim :advertiser :start ())
      #x0521)

    ;; A command that answers with real values.
    (bgapi:define-command-handler (sim :simple :returns (device command))
      (list (1+ (bgapi:msg-value command :param))))

    ;; A command that provokes events.
    (bgapi:define-command-handler (sim :le-gap :start-discovery (device))
      (bgapi:emit-event device :scanner :scan-report 0 "00:0b:57:49:2b:47" -42 ...)
      (list 0))

    ;; A device that goes silent, so the host's timeout path gets exercised.
    (bgapi:define-command-handler (sim :system :reset ())
      :silent)))

A handler returns the response's return values as a list, or an integer as a shorthand for "fail with this errorcode", or :silent to say nothing, or :succeed for the generated success response. no_return commands are never answered, whatever the handler says.

This is a simulator, not an emulator: it answers the protocol, it does not implement Bluetooth. What each command means is up to your handlers — which is the point, since that is how you script the cases real hardware will not produce on demand.

examples/simulator.lisp runs one standalone over TCP; point pyBGAPI or NCP Commander at it.

Events

Events either queue up for get-event / get-events / do-events, or go straight to an :event-handler given to make-link, which is called on the receive thread.

pyBGAPI compares events to strings (evt == 'bt_evt_system_boot'). Here every message carries an EQ-comparable keyword, so plain case works:

(case (bgapi:message-id event)
  (:bt-evt-system-boot ...)
  (:bt-evt-le-connection-opened ...))

event-case adds destructuring by parameter name, and message-typep matches partially ((bgapi:message-typep event :evt :system)).

Tracing

(setf (bgapi:trace-stream link) *standard-output*)
TestLogID > #<bt_cmd_system_hello()>
TestLogID < #<bt_rsp_system_hello(result=0)>
TestLogID < #<bt_evt_system_boot(major=3, minor=2, patch=0, build=169)>

Tracing and decoding warnings are per-link settings, not dynamic variables, because half the traffic is handled on the receive thread, where a let binding or handler-bind established in your thread cannot reach. Use (setf trace-stream) and (setf warning-handler). The specials *trace* and *warning-handler* supply defaults at make-link time.

The bgapi command

make bin        # builds bin/bgapi

Five subcommands. api needs no hardware at all:

bgapi api  -x vendor/pybgapi-examples/api/sl_bt.xapi   # classes, counts, indices
bgapi api  -x sl_bt.xapi scanner               # drill into one class
bgapi info -x sl_bt.xapi -d /dev/ttyUSB0       # hello, version, address, counters
bgapi scan -x sl_bt.xapi -d /dev/ttyUSB0 -s 30
bgapi scan -x sl_bt.xapi -d /dev/ttyUSB0 --hex   # dump advertising payloads
bgapi scan -x sl_bt.xapi -d /dev/ttyUSB0 --phy coded   # LE Long Range
bgapi scan -x sl_bt.xapi -d /dev/ttyUSB0 --active      # + scan responses

The transport is flags, not a positional argument, because a BGAPI target is very often not a local serial port:

bgapi scan -x sl_bt.xapi -H 192.168.1.10 -p 9000      # through a TCP bridge
bgapi info -x sl_bt.xapi -u /dev/cpcd/bluetooth       # a cpcd endpoint
bgapi info -x sl_bt.xapi -d /dev/ttyUSB0 --robust     # with the 0x5A framing
bgapi info -x sl_bt.xapi -d /dev/ttyUSB0 --trace      # every packet, both ways

And it can be the device, which makes the two halves demonstrable with no hardware:

bgapi simulate -x sl_bt.xapi -p 4901 -a 5 &
bgapi scan -x sl_bt.xapi -H 127.0.0.1 -p 4901 -s 3
a0:11:20:00:00:00   -40 dBm  ch37  sim-device-0
a1:22:21:00:00:01   -47 dBm  ch37  sim-device-1
...
5 events, 5 distinct advertisers

scan copes with the API drifting between SDK generations: it tries the scanner class and falls back to le_gap, and accepts either scan_report or *_advertisement_report events.

nus — a byte pipe to a Nordic UART Service device

nus connects to a device exposing the Nordic UART Service and joins stdin and stdout to it, so it composes like nc or socat:

echo -n hello | bgapi nus -x sl_bt.xapi -d /dev/ttyUSB0 -A cd:52:c6:52:53:d1
bgapi nus ... -A ... < firmware.bin           # stream a file to the device
bgapi nus ... -A ... | hexdump -C             # pipe replies onward
bgapi nus ... -A ... --listen 30 --hex        # watch, with boundaries kept
bgapi nus ... -A ... --addr-type random --phy coded   # a long-range device

Three rules make that work:

  • stdout carries device bytes and nothing else. Every diagnostic — including --trace, which the other subcommands print to stdout — goes to stderr.
  • stdin is forwarded as it arrives, as binary, not line by line, so piping a file and typing interactively both work. --after-eof (default 2s) decides how long to keep listening once stdin ends; -1 waits for the device.
  • Boundaries are lost on stdout, by design. --hex is the human-facing mode and does keep them, one block per notification.

simulate --nus answers as a NUS device that echoes what it is sent, so the whole path can be demonstrated with no radio present:

bgapi simulate -x sl_bt.xapi -p 4901 --nus &
echo -n hello | bgapi nus -x sl_bt.xapi -H 127.0.0.1 -p 4901 -A 00:11:22:33:44:55
hello

The library underneath is bgapi/nus: nus-connect, nus-send, nus-recv, nus-close, and a binary Gray stream via nus-stream for code already written against a serial port. nus-recv keeps notification boundaries; the stream flattens them.

Three things worth knowing beyond the basics:

  • nus-reconnect re-opens a dropped connection in place — the same object comes back, so a nus-stream over it survives the drop. It rediscovers rather than trusting the old handles, because a peripheral may renumber its attributes between connections.
  • nus-set-parameters is the throughput lever. A reliable write costs one connection event, so at the 37.5 ms interval a peripheral typically proposes you get roughly 26 a second whatever the MTU. Arguments are in milliseconds; the peer may grant something else, so read nus-interval-ms back afterwards. (bgapi nus --interval 15 does exactly that.)
  • :security :encrypted or :bonded raises security before discovery, so a device that hides its service behind pairing is not reported as simply not having one. Just Works pairing only — authenticated pairing needs a passkey and therefore a user interface, so drive the sm class directly for that.

Testing

make test
make fuzz     # 500k malformed packets against the decoder

Two suites are worth knowing about, because they cover the cases that are awkward to reach any other way:

  • fuzz feeds the decoder noise, plausible-but-wrong headers, and corrupted real packets. The property is that no input, however malformed, may produce anything but a bgapi-error — a type-error escaping would kill the receive thread and leave the caller holding a link that had silently gone deaf.
  • robust-corruption runs the 0x5A framing over a byte source that corrupts, truncates and drops octets, including one byte per read. It asserts both halves: a damaged frame is never delivered as good, and the receiver gets back in step afterwards. The bound is real and worth knowing — one damaged frame costs itself and at most one more, because a length field is believed before it can be checked, so a wrong length reads straight through the frame that follows.

181 tests. The codec and framing tests are byte-exact ports of pyBGAPI's own vectors, so they check this implementation against the reference rather than against hand-written expectations. The link tests drive the full stack — receive thread, response rendezvous, event queue, every error path — over a scripted mock connector, and the I/O tests drive a real pseudo-terminal and a real Unix-domain socket. No hardware required.

The strongest tests are the last group: this library's host driven against this library's simulator over a real socket and a real pty, each end decoding what the other encoded. That is a stronger statement than either half passing alone, because the wire format is pinned independently by pyBGAPI's vectors — a symmetric mistake would still be caught.

On a loaded machine, stretch every timeout at once:

BGAPI_TEST_TIME_SCALE=4 make test

Conformance against the reference implementation

The suite above compares against vectors copied from pyBGAPI, which catches encoding mistakes but not behavioural ones — anywhere this port reproduces a byte sequence correctly while implementing the surrounding logic differently, both sides of a copied-vector test agree and nothing fails.

make warnings compiles everything and fails on any compiler warning. That is not fussiness — an unescaped double quote inside a docstring once ended the string early and left its words as executable forms; SBCL deleted them as dead code and only warned, so the suite stayed green here while the code failed on another SBCL. The error it produced was the text of the docstring itself.

make crosscheck closes the other gap, by running the real thing:

pip install pybgapi
make crosscheck                                  # or PYTHON=venv/bin/python make crosscheck

It starts the simulator on a free port and drives it with actual pyBGAPI as the host — commands, responses, events, no_return, a failing errorcode, and every parameter type round-tripped through both codecs in both directions. It runs in CI on every push.

One thing it has to work around: pyBGAPI's SocketConnector.read returns "" — a str — on timeout, and BGApiConnHandler then calls bytearray.extend(""), which raises TypeError on Python 3. Since the read timeout fires on every idle poll, the stock socket connector cannot survive a quiet moment. scripts/crosscheck.py subclasses it to return b"". That is an unrelated defect in the reference, not a disagreement about the protocol.

Known gaps

  • CPC is a stub. The Co-Processor Communication connector needs the Linux-only libcpc from cpc-daemon, which could not be installed or exercised on the machine this port was written on. bgapi/cpc therefore ships as a placeholder that signals a clear error, with implementation notes in src/cpc.lisp. In the meantime, cpcd's socket works: (bgapi:make-socket-connector "/dev/cpcd/bluetooth" :family :unix).

  • Hardware coverage is narrow. It has been run against a real Silicon Labs EFR32 (Bluetooth stack 3.2.4) — identify, reset, and scan all work, and the results are written up in doc/hardware-test.md. But only reads and a scan were exercised: no advertising, no OTA. The robust connector has never run over a physically noisy link (its recovery is covered by a corrupting fixture — see below), and the serial path has only ever driven a pty, not a real UART.

  • bgapi/nus is proven on real hardware for the paths a target existed for. Against real Nordic-based sensors over Coded PHY: the open sequence, a command round trip, the Gray stream, reliable writes, and two concurrent connections on one link all work — written up in doc/hardware-test.md. Still simulator-only, for want of a suitable device rather than for want of code: 1M PHY (this fleet is Coded-only), indications (everything here notifies), and replies spanning several notifications (no command this firmware answers produces one).

    Worth knowing before blaming the code: a peripheral is only connectable while it is advertising, so a single failed connect means very little. nus retries by default (--connect-retries).

  • Enum decoding is off by default. *decode-enums* defaults to NIL, so values come back as integers and arithmetic works. pyBGAPI defaults it on, but both of its conversion paths are dead code that raises NameError or AttributeError if reached, so nothing depends on the behaviour. Use enum-name, enum-value, encode-flags and decode-flags explicitly.

TODO

Grouped by what unblocks them rather than by importance, because for most of these the blocker is the difficulty. The "why" for each is in Known gaps above; this is the short version of what would actually be done.

Needs a board plugged into a machine — the serial path has only ever driven a pty, so this one hardware session would close several of these at once:

  • Drive src/serial.lisp against a real UART: verify the baud constants (the gateway's port runs at 500000, which is not one of the common B values), that --rtscts does anything, and that the read timeout behaves on a real driver.
  • Run --robust over that UART. Its recovery is covered by a corrupting fixture, but never by a link whose corruption and timing are real.
  • Advertising and OTA/DFU, neither of which has been exercised at all.

Needs a peripheral this fleet does not contain:

  • NUS on 1M PHY. The fleet on hand is Coded-only by design, so this needs a different device — any stock Nordic NUS example will do.
  • NUS indications. Everything here notifies, so the confirmation path and the chore thread that keeps it off the receive thread are simulator-only.
  • A reply spanning several notifications, to exercise reassembly on air.

Needs a Linux host with cpc-daemon:

  • Implement bgapi/cpc against libcpc. The notes in src/cpc.lisp say what the binding needs; make-socket-connector on cpcd's Unix socket is the workaround until then.

Pure software, no hardware required:

  • Arbitrary GATT: read and write characteristics other than the NUS pair, descriptor access, and unsubscribe. bgapi/nus currently exposes only the byte pipe.
  • An automatic reconnect policy on top of nus-reconnect — the mechanism exists, the decision of when to apply it does not.
  • A NUS example under examples/; there are only scan and simulator.
  • Publish to ocicl.

Acknowledgements

This is an independent Common Lisp port of pyBGAPI by Silicon Laboratories Inc., used under the Zlib license. It is not a Silicon Laboratories product, is not endorsed by or affiliated with them, and is not supported by them — please do not report issues with this port to Silicon Laboratories.

Silicon Labs, Bluegiga, BGAPI, EFR32 and Simplicity Studio are trademarks of Silicon Laboratories Inc., used here only to identify the protocol and hardware this library speaks to.

See NOTICE for the full attribution and LICENSE for the terms.

License

Zlib, the same license as the original pyBGAPI. See LICENSE and NOTICE.

Dependencies (5)

  • alexandria
  • clingon
  • cxml
  • fiveam
  • nibbles

Dependents (0)

    • GitHub
    • Quicklisp