Simvik

Parse BLE advertising data

Read the flags, name and service UUIDs from an advertising packet, and reject malformed ones. A medium embedded C problem (Bluetooth Low Energy), run and…

medium · Bluetooth Low Energy · ble · parsing · tlv · robustness

A BLE advertising packet's payload is a list of structures, each [length][type][data...], where length counts the type byte and the data. Write adv_parse(d, len, out), which clears *out, then fills it in:

  • AD_FLAGS: one data byte, into flags.
  • AD_NAME_SHORT or AD_NAME_COMPLETE: the name (not zero-terminated in the packet). A complete name replaces a shortened one; a shortened name never replaces a complete one. Keep at most 31 characters.
  • AD_UUID16_SOME or AD_UUID16_ALL: 16-bit UUIDs, each little-endian. Keep the first 8.
  • Any other type: skip it.
  • A length of 0 ends the data early (the rest is padding).

These packets come over the air from any device in range, so check everything. Return false if a structure runs past len, or a UUID list has an odd number of data bytes. Otherwise return true.

Starter code

bool adv_parse(const uint8_t *d, uint8_t len, adv_t *out) {
  memset(out, 0, sizeof *out);
  int i = 0;
  while (i < len) {
    uint8_t l = d[i];
    uint8_t type = d[i + 1];
    if (type == AD_FLAGS) out->flags = d[i + 2];
    if (type == AD_NAME_COMPLETE) memcpy(out->name, &d[i + 2], l - 1);
    i += l + 1;
  }
  return true;
}

Example tests

A typical sensor advertisement

uint8_t d[] = { 0x02, 0x01, 0x06,
                0x05, 0x09, 'T', 'E', '-', '1',
                0x05, 0x03, 0x0F, 0x18, 0x0A, 0x18 };
show(d, sizeof d);

Expected output:

flags 06 name TE-1 uuids 180F 180A

A length that runs past the end

uint8_t d[] = { 0x02, 0x01, 0x06, 0x09, 0x09, 'A', 'B' };
show(d, sizeof d);

Expected output:

malformed

Learn it first

More Bluetooth Low Energy problems