4.1.2.8 BLE Custom Service

Getting Started

Getting Started with Peripheral Building Blocks

BLE Connection –> BLE Custom Service

Introduction

This document will help users create a peripheral device with custom profile and control. The GREEN LED and user button on the WBZ351 Curiosity board shall be used to enable or disable the LED status. The peripheral device will be the WBZ351 Curiosity board and the central device can either be a smartphone with a Light Blue app or another WBZ351 Curiosity board. The instructions mentioned below are applicable for a BLE peripheral device.

Users can choose to just run the precompiled Application Example hex file on the WBZ351 Curiosity board and experience the demo or can go through the steps involved in developing this application from scratch.

It is recommended to follow the examples in order, by learning the basic concepts first and then progressing to the more advanced topics.

Recommended Reading

  1. BLE Software Specification
  2. BLE Connection

Hardware Requirement

Table 4-18. Hardware Requirement

Tool

Qty

WBZ351 Curiosity Board

1

Micro USB Cable

1

Android/iOS Smart phone

1

SDK Setup

Software

Smartphone App

  • Light Blue iOS/Android app available in stores

Programming the Precompiled Hex File or Application Example

Programming the .hex file using MPLAB X IPE
  1. 1. Import and program the Precompiled Hex file: <Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\custom_service\hex\custom_service.X.production.signed.hex
  2. For more details on the steps, go to Programming a Device
    Note: Users must choose the correct device and tool information

Programming the Application using MPLAB X IDE

  1. Follow steps mentioned in the Running a Precompiled Example
  2. Open and program the Application: <Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\custom_service\firmware\custom_service.X

    For more details on finding the Harmony content path, refer to Installing the MCC Plugin

Demo Description

This application enables users to control a GREEN LED on the WBZ351 Curiosity board and read its status using a central device. On reset, demo will print "[BLE] Device Initialized. Ready for connection" which denotes the start of advertisements and then "[BLE] Connected to Peer Device:” when connection is established. Application data to be sent to the connected central device (smartphone or another WBZ351 Curiosity board) is entered in a terminal emulator like Tera Term.

Testing

  1. Using a micro USB cable, connect the Debug USB on the Curiosity board to a PC
  2. Program the precompiled hex file or application example as mentioned
  3. Open Tera Term and set the “Serial Port” to USB Serial Device and “Speed” to 115200.

    For more details on how to set the “Serial Port” and “Speed”, refer to COM Port Setup

  4. Press the Reset Switch on the Curiosity board. This must be displayed in Tera Term
    Figure 4-117. Tera Term
  5. Launch the Light Blue mobile app and search for the device name “pic32cx-bz” and press Connect
    Figure 4-118. LightBlue® App
    Figure 4-119. Tera Term
  6. Once connected, basic information like Advertisement Data and Device Information will be available

    Figure 4-120 4-121. LightBlue® App
  7. Find the custom service with the UUID: 4d434850-5255-42d0-aef8-881facf4ceea. Two characteristics will be available with the custom service. The button characteristics with the Readable/Notify property and GREEN LED characteristics with Readable/Writable property.
    Figure 4-120 4-121. LightBlue® App
  8. Click on the button characteristics and press subscribe. Press the User button on the curiosity board. The Read Value in the app will give its current status. Pressing the button will also toggle the GREEN LED.
    Figure 4-122. 
    Figure 4-123. 
  9. Go back and click on the GREEN LED characteristics which has a read/write option. The write option changes the GREEN LED On/Off status by writing a hex value in the form of XXXXXX. A value of 000000 will turn OFF the LED and value of FFFFFF turns it ON. The read option will give the current value stored for the GREEN LED.
    Figure 4-124. 
    Figure 4-125. 
    Figure 4-126. 
  10. Press back two times to disconnect the BLE connection. A disconnected device will advertise again.
    Figure 4-127. Tera Term

Developing the Application from Scratch using MCC

This section explains the steps required by a user to develop this application example from scratch using the MPLAB Code Configurator.
Note: It is recommended that new users of the MPLAB Code Configurator to go through this overview.
  1. Create a new MCC Harmony Project.
  2. To setup the basic components and configuration required to develop this application, import component configuration: <Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\custom_service\firmware\custom_service.X\custom_service.mc3

    For more details, refer to Importing Existing App Example Configuration

    Note: Import and Export functionality of the Harmony component configuration will help users to start from a known working setup of the MCC configuration.
  3. To accept dependencies or satisfiers, select "Yes"
  4. Verify if the project graph window has all the expected configuration as illustrated in the following figure:
    Figure 4-128. Project Graph

Verify Custom Service Configuration

  1. Select BLE Stack component the Project Graph and configure the following in the Configuration Options panel

    Figure 4-129. BLE Stack Configuration
    Note: If users cannot see the Configuration Options panel in the right-hand side of the MPLAB X IDE, it might be minimized. Hover the cursor towards the Configuration Options side tab and click the “dot” on the top right-hand corner to pin it (see the following figure)
    Figure 4-130. Configuration Panel
    .
  2. Select the FreeRTOS component in the Project Graph and configure the following
    Figure 4-131. FreeRTOS Configuration
  3. Select the SERCOM0 component in the Project Graph and configure the following
    Figure 4-132. SERCOM0 Configuration
  4. Select the System component in the Project Graph and configure the following
    Figure 4-133. System Configuration
  5. Select the EIC component in the Project Graph and configure the following
    Figure 4-134. EIC Configuration
  6. Select the Customized Service component in the Project Graph and configure the following
    Figure 4-135. Customized Service Configuration
    Figure 4-136. Customized Service Configuration
    Figure 4-137. Customized Service Configuration
  7. Verify the Clock Configuration as per the Low Power BLE Application Design.

Files and Routines Automatically generated by the MCC

After generating the program source from the MCC interface by clicking Generate Code, the BLE configuration source and header files can then be found in the following project directories.
Figure 4-138. Project Files

The OSAL, RF System and BLE System initialization routine executed during program initialization can be found in the project file. This initialization routine is automatically generated by the MCC.

Figure 4-139. initialization.c

The BLE stack initialization routine executed during Application Initialization can be found in project files. This initialization routine is automatically generated by the MCC. This call initializes and configures the GAP, GATT, SMP, L2CAP and BLE middleware layers.

Figure 4-140. 
Here are also the autogenerated Advertisement Data (AD) structures and types as reference
Figure 4-141. AD Structures and Types
Table 4-19. Source Files
Source FilesUsage
app.cApplication State machine, includes calls for Initialization of all BLE stack (GAP,GATT, SMP, L2CAP) related component configurations
app_ble\app_ble.cSource Code for the BLE stack related component configurations, code related to function calls from app.c
app_ble\app_ble_handler.cAll GAP, GATT, SMP and L2CAP Event handlers
ble_button_led_svc.cAll Custom Service button GREEN LED configurations and functions
Note: app.c is autogenerated and has a state machine-based application code. Users can use this template to develop their own application.

User Application Development

Add the code to enable advertisement, call the button external interrupt callback functions and initialize custom service in APP_STATE_INIT of the function APP_Tasks() in app.c

Figure 4-142. app.c
 /* Application's initial state. */
 case APP_STATE_INIT:
 {  
    bool appInitialized = true;
    //appData.appQueue = xQueueCreate( 10, sizeof(APP_Msg_T) );
    APP_BleStackInit();
    RTC_Timer32Start();
    BLE_GAP_SetAdvEnable(0x01, 0); //Enable BLE Advertisement
    BLE_BUTTON_LED_Add();
    APP_Button_Init();
    SYS_CONSOLE_PRINT("[BLE] Device Initialized. Ready for connection. \r\n");
Add the GREEN LED and button handlers to the function APP_Tasks() in app.c
Figure 4-143. app.c
 case APP_STATE_SERVICE_TASKS:
 { 
    if (OSAL_QUEUE_Receive(&appData.appQueue, &appMsg, OSAL_WAIT_FOREVER))
    {
     // if(p_appMsg->msgId==APP_MSG_BLE_STACK_EVT)
     // {
     // // Pass BLE Stack Event Message to User Application for handling
     // APP_BleStackEvtHandler((STACK_Event_T *)p_appMsg->msgData);
     // }
     switch (p_appMsg->msgId)
     {
        case APP_MSG_BLE_STACK_EVT:
        {
            APP_BleStackEvtHandler((STACK_Event_T *)p_appMsg->msgData);
         }
         break;
         case APP_MSG_BLE_CS_LED_EVT:
         {
             APP_CustomService_RGB_Handler((uint8_t *)((STACK_Event_T *)p_appMsg->msgData));
          }
          break;
          case APP_MSG_BLE_CS_BUTTON_EVT:
          {
              APP_CustomService_Button_Handler();
          }
          break;
       }
   }
  break;
 }

Add the message IDs for the GREEN LED and button events in app.h

Figure 4-144. app.h
 typedef enum APP_MsgId_T
 {
     APP_MSG_BLE_STACK_EVT,
     APP_MSG_ZB_STACK_EVT,
     APP_MSG_ZB_STACK_CB,
     APP_MSG_BLE_CS_LED_EVT,
     APP_MSG_BLE_CS_BUTTON_EVT,
     APP_MSG_STACK_END
 } APP_MsgId_T;

Add the custom service source and header files “<Harmony Content Path>\wireless_apps_pic32cxbz3_wbz35\apps\ble\building_blocks\peripheral\profiles_services\custom_service\firmware\src\app_ble_custom_service.c and app_ble_custom_service.h and app_ble_custom_service.h which has the supporting functions for the button LED custom service file

Figure 4-145. Project Files
Add the required variables, functions and callback handlers for the GATT read/write response in app_ble_handler.c along with the connect and disconnect message information
Figure 4-146. app_ble_handler.c
Figure 4-147. app_ble_handler.c
Figure 4-148. app_ble_handler.c
Figure 4-149. app_ble_handler.c
void APP_BleGapEvtHandler(BLE_GAP_Event_T *p_event)
{ 
    switch(p_event->eventId)
    {
        case BLE_GAP_EVT_CONNECTED:
        {
        /* TODO: implement your application code.*/
        SYS_CONSOLE_PRINT("[BLE] Connected to Peer Device: 0x");
        for(int8_t idx=(GAP_MAX_BD_ADDRESS_LEN-1); idx>=0; idx--)
        {
            SYS_CONSOLE_PRINT("%02x", p_event->eventField.evtConnect.remoteAddr.addr[idx]);
        }
        SYS_CONSOLE_PRINT("\n\r[BLE] Connection Handle: %d\n\r",p_event->eventField.evtConnect.connHandle);
        G_ConnHandle = p_event->eventField.evtConnect.connHandle;
        }
        break;
        case BLE_GAP_EVT_DISCONNECTED:
        {
           /* TODO: implement your application code.*/
           SYS_CONSOLE_PRINT("[BLE] Disconnected Handle: %d, Reason: 0x%X\n\r",p_event->eventField.evtDisconnect.connHandle, p_event->eventField.evtDisconnect.reason);
           G_ConnHandle = 0;
           BLE_GAP_SetAdvEnable(0x01, 0); //Enable BLE Advertisement          
        }
        break;

Add the functions for the GATT read/write handlers which will act on the received GATT request in app_ble_handler.c

Figure 4-150. app_ble_handler.c
Figure 4-151. app_ble_handler.c
void APP_GattSEvtReadHandler(GATT_EvtRead_T p_event)
{

    uint8_t error = 0;
    uint16_t status;
    SYS_CONSOLE_PRINT("[BLE] GATT Read ATTR Handle 0x%X \r\n",p_event.attrHandle);
    
    if ((p_event.attrHandle <= BUTTON_LED_START_HDL) ||
        (p_event.attrHandle > BUTTON_LED_END_HDL))
    {
        /* Not BLE Custom Service characteristic. */
        return;
    }

        switch(p_event.attrHandle)
        {
            case BUTTON_LED_HDL_CHAR_0:                            /**< Handle of characteristic 0. */
            case BUTTON_LED_HDL_CCCD_0:                            /**< Handle of characteristic 0 CCCD . */
            case BUTTON_LED_HDL_CHAR_1:                            /**< Handle of characteristic 1. */
            case BUTTON_LED_HDL_CHARVAL_1:                         /**< Handle of characteristic 1 value. */
                error = ATT_ERRCODE_APPLICATION_ERROR;
                break;
            case BUTTON_LED_HDL_CHARVAL_0:                         /**< Handle of characteristic 0 value. */                
//                SYS_CONSOLE_PRINT(" ATTR Handle Read 0x%X \r\n",p_event.attrHandle);
                break;
        }

    if ((p_event.readType == ATT_READ_REQ)
    || (p_event.readType == ATT_READ_BLOB_REQ))
    {
        if (!error)
        {
            sp_trsReadRespParams = (GATTS_SendReadRespParams_T *)OSAL_Malloc(sizeof(GATTS_SendReadRespParams_T));
            if (sp_trsReadRespParams == NULL)
            {
                return;
            }
            trsRespErrConnHandle = p_event.connHandle;
            sp_trsReadRespParams->responseType = ATT_READ_RSP;
            sp_trsReadRespParams->attrLength = 0x01;
            sp_trsReadRespParams->attrValue[0]= bleCSdata.rgbOnOffStatus;            
//            sp_trsReadRespParams->attrLength = 0x03;
//            sp_trsReadRespParams->attrValue[0]= bleCSdata.RGB_LED.Red;
//            sp_trsReadRespParams->attrValue[1]= bleCSdata.RGB_LED.Green;
//            sp_trsReadRespParams->attrValue[2]= bleCSdata.RGB_LED.Blue;
            status = GATTS_SendReadResponse(p_event.connHandle, sp_trsReadRespParams);
            if (status == MBA_RES_SUCCESS)
            {
                OSAL_Free(sp_trsReadRespParams);
                sp_trsReadRespParams = NULL;
            }
        }
        else
        {
            sp_trsErrParams = (GATTS_SendErrRespParams_T *)OSAL_Malloc(sizeof(GATTS_SendErrRespParams_T));
            if (sp_trsErrParams == NULL)
            {
                return;
            }
            trsRespErrConnHandle = p_event.connHandle;
            sp_trsErrParams->reqOpcode = p_event.readType;
            sp_trsErrParams->attrHandle = p_event.attrHandle;
            sp_trsErrParams->errorCode = error;
            status = GATTS_SendErrorResponse(p_event.connHandle, sp_trsErrParams);
            if (status == MBA_RES_SUCCESS)
            {
                OSAL_Free(sp_trsErrParams);
                sp_trsErrParams = NULL;
            }
        }
    }   
}
void APP_GattSEvtWriteHandler(GATT_EvtWrite_T p_event)
{
    uint8_t error = 0;
    uint16_t status;
    SYS_CONSOLE_PRINT("[BLE] GATT Write ATTR Handle 0x%X \r\n",p_event.attrHandle);
    
    if ((p_event.attrHandle <= BUTTON_LED_START_HDL) ||
        (p_event.attrHandle > BUTTON_LED_END_HDL))
    {
        /* Not BLE Custom Service characteristic. */
        error = ATT_ERRCODE_INVALID_HANDLE;
        return;
    }
    
        switch(p_event.attrHandle)
        {
            case BUTTON_LED_HDL_CHAR_0:                            /**< Handle of characteristic 0. */
            case BUTTON_LED_HDL_CHARVAL_0:                         /**< Handle of characteristic 0 value. */
            case BUTTON_LED_HDL_CCCD_0:                            /**< Handle of characteristic 0 CCCD . */
            case BUTTON_LED_HDL_CHAR_1:                            /**< Handle of characteristic 1. */
                error = ATT_ERRCODE_APPLICATION_ERROR;
                break;
            case BUTTON_LED_HDL_CHARVAL_1:                         /**< Handle of characteristic 1 value. */
//                SYS_CONSOLE_PRINT(" ATTR Handle %d \r\n",p_event.attrHandle);
                APP_CustomService_RGB_Callback(p_event.writeValue);
                break;
        }

    if ((p_event.writeType == ATT_WRITE_REQ)
    || (p_event.writeType == ATT_PREPARE_WRITE_REQ))
    {
        if (!error)
        {
            sp_trsRespParams = (GATTS_SendWriteRespParams_T *)OSAL_Malloc(sizeof(GATTS_SendWriteRespParams_T));
            if (sp_trsRespParams == NULL)
            {
                return;
            }
            trsRespErrConnHandle = p_event.connHandle;
            sp_trsRespParams->responseType = ATT_WRITE_RSP;
            status = GATTS_SendWriteResponse(p_event.connHandle, sp_trsRespParams);
            if (status == MBA_RES_SUCCESS)
            {
                OSAL_Free(sp_trsRespParams);
                sp_trsRespParams = NULL;
            }
        }
        else
        {
            sp_trsErrParams = (GATTS_SendErrRespParams_T *)OSAL_Malloc(sizeof(GATTS_SendErrRespParams_T));
            if (sp_trsErrParams == NULL)
            {
                return;
            }
            trsRespErrConnHandle = p_event.connHandle;
            sp_trsErrParams->reqOpcode = p_event.writeType;
            sp_trsErrParams->attrHandle = p_event.attrHandle;
            sp_trsErrParams->errorCode = error;
            status = GATTS_SendErrorResponse(p_event.connHandle, sp_trsErrParams);
            if (status == MBA_RES_SUCCESS)
            {
                OSAL_Free(sp_trsErrParams);
                sp_trsErrParams = NULL;
            }
        }
    }
}
Note: Manual read/write responses, permissions and other standard events like GAP and GATT can be executed in app_ble_handler.c
Note: Users can exercise various other BLE advertisement functionalities by using BLE Stack APIs