LE Nordic SPP-like Heartbeat Server

Source Code: nordic_ssp_le_counter.c

Main Application Setup

Listing here shows main application code. It initializes L2CAP, the Security Manager and configures the ATT Server with the pre-compiled ATT Database generated from nordic_spp_le_counter.gatt. Additionally, it enables the Battery Service Server with the current battery level. Finally, it configures the advertisements and the heartbeat handler and boots the Bluetooth stack. In this example, the Advertisement contains the Flags attribute and the device name. The flag 0x06 indicates: LE General Discoverable Mode and BR/EDR not supported.

static btstack_timer_source_t heartbeat;
static hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
static btstack_context_callback_registration_t send_request;

const uint8_t adv_data[] = {
  // Flags general discoverable, BR/EDR not supported
  2, BLUETOOTH_DATA_TYPE_FLAGS, 0x06, 
  // Name
  8, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'n', 'R', 'F',' ', 'S', 'P', 'P',
  // UUID ...
  17, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_128_BIT_SERVICE_CLASS_UUIDS, 0x9e, 0xca, 0xdc, 0x24, 0xe, 0xe5, 0xa9, 0xe0, 0x93, 0xf3, 0xa3, 0xb5, 0x1, 0x0, 0x40, 0x6e,
};
const uint8_t adv_data_len = sizeof(adv_data);

Heartbeat Handler

The heartbeat handler updates the value of the single Characteristic provided in this example, and request a ATT_EVENT_CAN_SEND_NOW to send a notification if enabled see Listing here.

static int  counter = 0;
static char counter_string[30];
static int  counter_string_len;

static void beat(void){
  counter++;
  counter_string_len = <a href="https://github.com/bluekitchen/btstack/blob/develop/src/btstack_util.h#L425">btstack_snprintf_assert_complete</a>(counter_string, sizeof(counter_string), "BTstack counter %03u", counter);
}

static void nordic_can_send(void * context){
  UNUSED(context);
  printf("SEND: %s\n", counter_string);
  <a href="https://github.com/bluekitchen/btstack/blob/develop/src/ble/gatt-service/nordic_spp_service_server.h#L82">nordic_spp_service_server_send</a>(con_handle, (uint8_t*) counter_string, counter_string_len);
}

static void heartbeat_handler(struct btstack_timer_source *ts){
  if (con_handle != HCI_CON_HANDLE_INVALID) {
    beat();
    send_request.callback = &amp;nordic_can_send;
    <a href="https://github.com/bluekitchen/btstack/blob/develop/src/ble/gatt-service/nordic_spp_service_server.h#L74">nordic_spp_service_server_request_can_send_now</a>(&amp;send_request, con_handle);
  }
  <a href="https://github.com/bluekitchen/btstack/blob/develop/src/btstack_run_loop.h#L233">btstack_run_loop_set_timer</a>(ts, HEARTBEAT_PERIOD_MS);
  <a href="https://github.com/bluekitchen/btstack/blob/develop/src/btstack_run_loop.h#L260">btstack_run_loop_add_timer</a>(ts);
}