Standard library · Hardware

hw.ble

Bluetooth Low Energy for boards: advertise, scan, a small GATT server with write events and notifications, and central connect, read and write, with a simulated radio on a computer.

import hw.ble

hw.ble is Bluetooth Low Energy for boards. A device can be a peripheral (advertise, serve a small GATT table, receive writes from a phone and notify it) or a central (scan, connect to a device, read and write its characteristics). Calls return plain values, so a failure is an answer you check.

Where it runsWhat answers the calls
A computerA deterministic fake radio in memory: SimAddBleDevice fills the air, SimInjectWrite plays a central writing to you and SimSetRemoteValue gives a remote device something to read.
An ESP32-C3 through ESP-IDFThe salam_rt_ble_* hooks implemented in idf_radio.c on the NimBLE host. See the ESP32-C3 section of docs/FREESTANDING.md. This path has not been run on a device.
A board without a radioThe runtime's default hooks answer "unsupported", so Init returns false and the program still links.

Things to know:

•

No hidden threads. Writes from a central are queued; check Poll in your own loop and fetch each one with Take.

•

Add services first. On a board the GATT table is frozen when the radio starts, so call AddService and AddCharacteristic before the first Advertise, Scan or Connect.

•

Bytes are Vector<u8>. Values, events and remote reads all use it, up to max_value bytes.

•

Properties are flags. Combine prop_read, prop_write and prop_notify with |.

•

Read fields with functions. DeviceName, DeviceAddress, DeviceRssi, ServiceOk, CharacteristicOk, EventUuid, EventValue and EventOk read the records.

A peripheral that receives writes

Add a service with one writable characteristic, advertise, then wait for a central to write. The example plays the central with SimInjectWrite.

hw-ble-guide-peripheral.salam
Try it
import hw.ble

func one(v: int): Vector<u8>:
    out := Vector {} as Vector<u8>
    out.Push(v as u8)
    ret out
end

func main:
    ble.Init("salam-led")
    svc := ble.AddService("12345678-1234-1234-1234-123456789abc")
    led := ble.AddCharacteristic(svc, "2a56", ble.prop_read | ble.prop_write, one(0))
    ble.Advertise(true)
    println "advertising:", ble.Advertising()
    ble.SimInjectWrite(led, one(1))
    until not ble.Poll():
        continue
    end
    e := ble.Take()
    println "central wrote", ble.EventValue(e).Get(0), "to", ble.EventUuid(e)
    ret 0
end
Output
advertising: true
central wrote 1 to 2a56

A central that reads a device

Scan, connect to a device by its address, read a characteristic by UUID and disconnect.

hw-ble-guide-central.salam
Try it
import hw.ble

func main:
    ble.Init("reader")
    ble.SimAddBleDevice("Battery", "c0:ff:ee:00:00:09", -55)
    level := Vector {} as Vector<u8>
    level.Push(87 as u8)
    ble.SimSetRemoteValue("c0:ff:ee:00:00:09", "2a19", level)
    each d in ble.Scan(1000):
        println "found", ble.DeviceName(d), ble.DeviceRssi(d)
        if ble.Connect(ble.DeviceAddress(d)):
            println "battery", ble.Read("2a19").Get(0)
            ble.Disconnect()
        end
    end
    ret 0
end
Output
found Battery -55
battery 87

Types

Device

#
struct Device

A device seen by a scan. Read its parts with DeviceName, DeviceAddress and DeviceRssi.

NameTypeDescription
namestr = ""The advertised name, possibly empty.
addressstr = ""The device address as six hex pairs, such as c0:ff:ee:00:00:01.
rssiint = 0The signal strength in dBm.
hw-ble-Scan.salam
Try it
import hw.ble

func main:
    ble.Init("scanner")
    ble.SimAddBleDevice("Sensor", "c0:ff:ee:00:00:01", -60)
    ble.SimAddBleDevice("Lamp", "c0:ff:ee:00:00:02", -75)
    println ble.max_scan, ble.Scan(0).Len()
    each d in ble.Scan(500):
        println ble.DeviceName(d), ble.DeviceAddress(d), ble.DeviceRssi(d)
    end
end
Output
32 0
Sensor c0:ff:ee:00:00:01 -60
Lamp c0:ff:ee:00:00:02 -75

Service

#
struct Service

A GATT service added with AddService.

NameTypeDescription
handleint = -1The number the radio gave the service, or -1 when adding failed.
uuidstr = ""The UUID the service was added with.
okbool = falseTrue when the service was added. ServiceOk returns this value.
hw-ble-Gatt.salam
Try it
import hw.ble

func two(a: int, b: int): Vector<u8>:
    v := Vector {} as Vector<u8>
    v.Push(a as u8)
    v.Push(b as u8)
    ret v
end

func main:
    ble.Init("thermo")
    svc := ble.AddService("181a")
    mode := ble.prop_read | ble.prop_write | ble.prop_notify
    temp := ble.AddCharacteristic(svc, "2a6e", mode, two(21, 5))
    println ble.ServiceOk(svc), ble.CharacteristicOk(temp), ble.Value(temp).Get(0), ble.max_value
    println ble.Notify(temp), ble.SetValue(temp, two(22, 0)), ble.Value(temp).Get(0)
    ble.SimSetClient(true)
    println ble.Notify(temp), ble.SimNotified()
    println ble.Poll(), ble.SimInjectWrite(temp, two(9, 8)), ble.Poll()
    e := ble.Take()
    println ble.EventOk(e), ble.EventUuid(e), ble.EventValue(e).Get(0), ble.Value(temp).Get(1)
    println ble.Poll(), ble.EventOk(ble.Take())
    println ble.prop_read, ble.prop_write, ble.prop_notify
end
Output
true true 21 512
false true 22
true 1
false true true
true 2a6e 9 8
false false
1 2 4

Characteristic

#
struct Characteristic

A GATT characteristic added with AddCharacteristic.

NameTypeDescription
handleint = -1The number the radio gave the characteristic, or -1 when adding failed.
uuidstr = ""The UUID of the characteristic.
propsint = 0The combined prop_ flags it was added with.
okbool = falseTrue when the characteristic was added. CharacteristicOk returns this value.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Event

#
struct Event

A write a central made to one of your characteristics. Read it with EventUuid, EventValue and EventOk.

NameTypeDescription
handleint = -1The characteristic that was written, or -1 for an empty event.
uuidstr = ""The UUID of the characteristic that was written.
valueVector<u8>The bytes the central wrote.
okbool = falseTrue for a real event and false for the empty one Take returns when nothing is queued.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Constants and variables

max_scan

#
const max_scan: i32 = 32

The most devices one Scan returns, 32.

The example for this item is shown with the ones above: hw-ble-Scan.salam

max_value

#
const max_value: i32 = 512

The longest value a characteristic or a remote write can carry, 512 bytes.

hw-ble-Advertise.salam
Try it
import hw.ble

func main:
    println ble.Init("salam-led"), ble.Ready(), ble.Advertising()
    println ble.Advertise(true), ble.Advertising()
    println ble.Advertise(false), ble.Advertising()
    println ble.Init(""), ble.ValidUuid("180f"), ble.ValidUuid("12345678-1234-1234-1234-123456789abc"), ble.ValidUuid("12g4")
    ble.SimReset()
    println ble.Ready(), ble.Advertise(true)
end
Output
true true false
true true
true false
false true true false
false false

prop_read

#
const prop_read: i32 = 1

Characteristic property 1: a central may read the value.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

prop_write

#
const prop_write: i32 = 2

Characteristic property 2: a central may write the value.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

prop_notify

#
const prop_notify: i32 = 4

Characteristic property 4: the device may push the value with Notify. Combine properties with the | operator.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Functions

ValidUuid

#
func ValidUuid(uuid: str): bool

Checks a UUID without any radio: 4 hex digits (16 bit), 8 hex digits (32 bit) or the 36 character form 12345678-1234-1234-1234-123456789abc.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

Init

#
func Init(name: str): bool

Prepares the Bluetooth controller and sets the device name (1 to 29 bytes). Returns true when ready and false on a board with no radio or with a bad name. Add services before the first Advertise, Scan or Connect.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

Ready

#
func Ready(): bool

True after a successful Init.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

Advertise

#
func Advertise(enable: bool): bool

Starts or stops advertising the device name so centrals can find and connect to it. Returns true on success.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

Advertising

#
func Advertising(): bool

True while the device is advertising.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

Scan

#
func Scan(timeout_ms: int): Vector<Device>

Listens for advertising devices for timeout_ms milliseconds and returns up to max_scan of them as a Vector of Device. A zero timeout or a missing Init gives an empty Vector.

The example for this item is shown with the ones above: hw-ble-Scan.salam

AddService

#
func AddService(uuid: str): Service

Adds a primary service with the given UUID to the GATT table. On a board this must happen before the first Advertise, Scan or Connect. A bad UUID or a missing Init returns a Service for which ServiceOk is false.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

AddCharacteristic

#
func AddCharacteristic(service: Service, uuid: str, props: int, value: Vector<u8>): Characteristic

Adds a characteristic to a service with the prop_ flags and an initial value of up to max_value bytes. A bad UUID, zero or unknown properties or a failed service return a Characteristic for which CharacteristicOk is false.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

SetValue

#
func SetValue(c: Characteristic, value: Vector<u8>): bool

Replaces the value a central reads. Returns false for a failed characteristic or a value that is too long.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Value

#
func Value(c: Characteristic): Vector<u8>

The current value of a characteristic as a Vector of bytes. It also shows what a central last wrote.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Notify

#
func Notify(c: Characteristic): bool

Pushes the current value to the connected central. Returns false without the NOTIFY property, without a central or on a failed characteristic.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Poll

#
func Poll(): bool

True when a central write is waiting. Call it from your loop; there is no callback and no hidden thread.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Take

#
func Take(): Event

Removes and returns the oldest waiting write. When nothing is queued the result has Ok false.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

Connect

#
func Connect(address: str): bool

Connects to a device by address as a central. Returns true on success. In the simulation only devices from SimAddBleDevice can be reached.

hw-ble-Central.salam
Try it
import hw.ble

func two(a: int, b: int): Vector<u8>:
    v := Vector {} as Vector<u8>
    v.Push(a as u8)
    v.Push(b as u8)
    ret v
end

func main:
    ble.Init("phone")
    ble.SimAddBleDevice("Sensor", "c0:ff:ee:00:00:01", -60)
    ble.SimSetRemoteValue("c0:ff:ee:00:00:01", "2a19", two(77, 0))
    println ble.Connect("00:00:00:00:00:00"), ble.IsConnected()
    println ble.Connect("c0:ff:ee:00:00:01"), ble.IsConnected()
    println ble.Read("2a19").Get(0), ble.Read("2a1a").Len()
    println ble.Write("2a19", two(5, 6)), ble.SimRemoteWritten("c0:ff:ee:00:00:01", "2a19").Get(1)
    ble.Disconnect()
    println ble.IsConnected(), ble.Read("2a19").Len()
end
Output
false false
true true
77 0
true 6
false 0

Disconnect

#
func Disconnect()

Drops the central connection. Safe to call when not connected.

The example for this item is shown with the ones above: hw-ble-Central.salam

IsConnected

#
func IsConnected(): bool

True while a central connection is open.

The example for this item is shown with the ones above: hw-ble-Central.salam

Read

#
func Read(uuid: str): Vector<u8>

Reads a characteristic of the connected device by UUID and returns its bytes. The result is empty when not connected, for a bad UUID or an unknown characteristic.

The example for this item is shown with the ones above: hw-ble-Central.salam

Write

#
func Write(uuid: str, value: Vector<u8>): bool

Writes bytes to a characteristic of the connected device by UUID. Returns true on success.

The example for this item is shown with the ones above: hw-ble-Central.salam

DeviceName

#
func DeviceName(d: Device): str

The name of a scanned device.

The example for this item is shown with the ones above: hw-ble-Scan.salam

DeviceAddress

#
func DeviceAddress(d: Device): str

The address of a scanned device.

The example for this item is shown with the ones above: hw-ble-Scan.salam

DeviceRssi

#
func DeviceRssi(d: Device): int

The signal strength of a scanned device in dBm.

The example for this item is shown with the ones above: hw-ble-Scan.salam

EventUuid

#
func EventUuid(e: Event): str

The UUID of the characteristic an event wrote.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

EventValue

#
func EventValue(e: Event): Vector<u8>

The bytes of an event.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

EventOk

#
func EventOk(e: Event): bool

True for a real event.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

ServiceOk

#
func ServiceOk(s: Service): bool

True when the service was added.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

CharacteristicOk

#
func CharacteristicOk(c: Characteristic): bool

True when the characteristic was added.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

SimReset

#
func SimReset()

Forgets everything the simulation holds: devices, services, queued writes and the Init state. Does nothing on a board.

The example for this item is shown with the ones above: hw-ble-Advertise.salam

SimAddBleDevice

#
func SimAddBleDevice(name: str, address: str, rssi: int)

Adds a fake device to the simulated air. Connect works only for devices added this way.

The example for this item is shown with the ones above: hw-ble-Scan.salam

SimSetRemoteValue

#
func SimSetRemoteValue(address: str, uuid: str, value: Vector<u8>)

Sets the value a simulated device holds for a UUID, which Read returns and Write accepts.

The example for this item is shown with the ones above: hw-ble-Central.salam

SimRemoteWritten

#
func SimRemoteWritten(address: str, uuid: str): Vector<u8>

The bytes the program last wrote to a UUID on a simulated device, or an empty Vector.

The example for this item is shown with the ones above: hw-ble-Central.salam

SimInjectWrite

#
func SimInjectWrite(c: Characteristic, value: Vector<u8>): bool

Pretends a central wrote bytes to a characteristic. Only characteristics with the WRITE property accept it. The value changes and an event is queued; returns whether that happened.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

SimSetClient

#
func SimSetClient(connected: bool)

Tells the simulation whether a central is subscribed, which Notify needs.

The example for this item is shown with the ones above: hw-ble-Gatt.salam

SimNotified

#
func SimNotified(): int

How many notifications have been sent in the simulation.

The example for this item is shown with the ones above: hw-ble-Gatt.salam