3.1.2.7 BLE Custom service

Getting Started

Getting Started with Peripheral Building Blocks

BLE Connection –> BLE Custom Service

Introduction

This tutorial will help users create a peripheral device with custom profile and control the RGB LEDs on the WBZ451 Curiosity board and button on the WBZ451 Curiosity board shall be used to enable or disable the LED status. Peripheral device will be WBZ451 Device and Central device can be a Smartphone with Light Blue App.The instructions mentioned below are applicable for a BLE Peripheral device.

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

Recommended Reads

  1. BLE Software Specification

  2. BLE Connection

Hardware Required

Tool Required

Qty

WBZ451 Curiosity Board

1

Micro USB Cable

1

SDK Setup

  1. Getting Started with Software Development

Software

  1. TeraTerm

Smartphone App

  1. Light Blue

Programming the precompiled hex file or Application Example

Programming the hex file using MPLABX IPE

  1. Precompiled Hex file is located in "<Harmony Content Path>\wireless_apps_pic32cxbz2_wbz45\apps\ble\building_blocks\peripheral\profiles_services\custom_service\hex" folder

  2. Follow the steps mentioned here

Caution: Users should choose the correct Device and Tool information

Programming the Application using MPLABX IDE

  1. Follow steps mentioned in of Running a Precompiled Example document

  2. Open and program the Application Example "peripheral_trp_uart.x" located in "<Harmony Content Path>\wireless_apps_pic32cxbz2_wbz45\apps\ble\building_blocks\peripheral\profiles_services\custom_service\firmware" using MPLABX IDE

<Harmony Content Path> how to find what is my Harmony Content Path

Demo Description

Upon programming the demo application, WBZ451 will start Advertising (connectable), central device (Smartphone) scanning for these advertisements will connect to the device. In case of using Light Blue App search for “pic32cx-bz” and connect. After a connection has been made Button and RGB LED status can be read and RGB LED can be controlled from the central device (Smartphone - Light Blue App). Button status will be notified if subscribed from central device (Smartphone).

Demo will print various events on a terminal emulator like Tera Term @ (Speed: 115200, Data: 8-bit,Partity: none, stop bits: bit, Flow control: none)

  • Start of the advertisement - "[BLE] Device Initialized. Ready for connection"

  • Connection completed - "[BLE] Connected to Peer Device: "&" [BLE ] Connection Handle:"

  • Write Request Received - "[BLE] GATT Write ATTR Handle 0x"

  • Read Request Received - "[BLE] GATT Read ATTR Handle 0x"

  • Received RGB Data - "[BLE] RGB LED data 0x 0x 0x"

  • Button press event - “[BLE] Custom Service Button Event : RGB LED ON” & “[BLE] Custom Service Button Event : RGB LED OFF”

  • BLE Disconnected - “[BLE] Disconnected Handle: %d, Reason: 0x<reason_code>”.

Testing

This section assumes that user has programmed the Application Example on the WBZ451 Curiosity Board Demo Experience when using a Smartphone (Light Blue App) as Central Device

  • Reset the WBZ451 Curiosity board, Open Terminal emulator like Tera Term, select the right COM port@ (Speed: 115200, Data: 8-bit, Parity: none, stop bits: 1 bit, Flow control: none).

  • open Light Blue App on your smartphone, Search and select the advertisement with Device Name "pic32cx-bz"
    Figure 3-10. .
  • Once connected on Blue App on your smartphone, basic info like Adervetisement Data and Device information will be avilable"
    Figure 3-11. .
  • Once connected on Blue App on your smartphone, find the custom service with the UUID 4d434850-5255-42d0-aef8-881facf4ceea" Two characteristics will be avilable on the custom service.Button characteristics with Readable,Notify property and RGB LED characteristics with Readable,Writable property
    Figure 3-12. .
  • Click on the button characteristics which will have read option and subscribe. Read will give the current status of the button
    Figure 3-13. .
  • Click on the button characteristics subscribe option to listen for button change events.Button press activity will be notified to the central device without read intiated and toggle the RGB LEDs.
    Figure 3-14. .
    Figure 3-15. .
  • Click on the RGB LED characteristics which will have read and write option. Read will give the current values stored for the RGB LEDs.Value of zero will turn off the LED. Other than zero value will turn on LED.
    Figure 3-16. .
  • Click on the button characteristics write option provides option to write info which will change the RGB LED on/off condition.Read again to get the updated value for RGB LEDs.
    Figure 3-17. .
    Figure 3-18. .
  • press back to disconnect the ble connection. Disconnected device will advertise again.
    Figure 3-19. .
  • Every event will be notified in the terminal emulator.

Developing this Application from scratch using MPLAB Code Configurator

This section explains the steps required by a user to develop this application example from scratch using MPLABx Code Configurator

Tip: New users of MPLAB Code Configurator are recommended to go through the overview.

  1. Create a new MCC Harmony Project -- link for instructions

  2. Import component configuration -- This step helps users setup the basic components and configuration required to develop this application. The imported file is of format .mc3 and is located in the path "<Harmony Content Path>\wireless_apps_pic32cxbz2_wbz45\apps\ble\building_blocks\peripheral\profiles_services\custom_service\firmware\custom_service.X". Users should follow the instructions mentioned here to import the component configuration.

  3. Accept Dependencies or satisfiers, select "Yes"

  4. Verify if the Project Graph window has all the expected configuration
    Figure 3-20. .

Verify Custom Service Configuration

  1. Select BLE_Stack component in project graph
    Figure 3-21. .
  2. Select FreeRTOS component in project graph
    Figure 3-22. .
  3. Select SERCOM0 component in project graph
    Figure 3-23. .
  4. Select System component in project graph
    Figure 3-24. .
  5. Select EIC component in project graph
    Figure 3-25. .
  6. Select Customized Service component in project graph
    Figure 3-26. .
    Figure 3-27. .
    Figure 3-28. .
  7. Verify the Clock Configuration from tools option as per low power guide.

Files and Routines Automatically generated by the MCC

After generating the program source from MCC interface by clicking Generate Code, the BLE configuration can be found in the following project directories
Figure 3-29. .

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

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 RGB LEDs configurations and functions
app_ble_custom_service header and source files can be copied from the reference application.

Tip: app.c is autogenerated and has a state machine based Application code sample, users can use this template to develop their application

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

Figure 3-30. .

User Application Development

Initialize Advertisement,Custom Service and EIC in APP_Tasks function in file app.c

Add the code for enable advertisement,customer service intilization and button external interrupt callback functions in the APP_STATE_INIT.

Figure 3-31. .
 /* 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");

Handle the button and RGB LED events in APP_Tasks function in file app.c

Add the RGB and button handlers to the function APP_Tasks() in app.c file.
Figure 3-32. .
 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 msg ids for the button and RGB LED events in file app.h
Figure 3-33. .
 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 file(\custom_service\firmware\src\app_ble_custom_service.c/.h) which has the supporting functions for Button LED Custom service file.
Figure 3-34. .
Print the required information on the connect and discoonect events in file app_ble_handler.cAdd the required variables, functions and callback handlers for GATT read/write response in the file ble_handler.c along with the connect and disconnect .
Figure 3-35. .
Figure 3-36. .
Figure 3-37. .
Figure 3-38. .
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 and write handlers which will act on the received GATT request in file app_ble_handler.c.
Figure 3-39. .
Figure 3-40. .
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;
            }
        }
    }
}

Tip: Manual read and write response,permissions and other standard events like GAP and GATT can be executed in the app_ble_handler

Users can exercise various other BLE functionalities by usingBLE Stack API