5.2.3 BLE ANCS Application

This section explains how to enable BLE ANCS (Apple Notification Center Service) profile on the PIC32-BZ6 Curiosity Board using MCC. In this application example ANCS client is implemented.

Users can choose to either run the precompiled Application Example hex file provided on the PIC32-BZ6 Curiosity Board or follow the steps to develop the application from scratch.

It is recommended to follow the examples in sequence to understand the basic concepts before progressing to the advanced topics.

Hardware Requirement

Table 5-37. Hardware Prerequisites
S. No. Tool Quantity
1PIC32-BZ6 Curiosity Board1
2Micro USB cable1
3iPhone1

SDK Setup

Refer to Getting Started with Software Development from Related Links.

Software

To install Tera Term tool, refer to the Tera Term web page in Reference Documentation from Related Links.

Smartphone App

None

Programming the Precompiled Hex File or Application Example

Using MPLAB® X IPE:

  1. Import and program the precompiled hex file: <Harmony Content Path>\wireless_apps_pic32_bz6\apps\ble\advanced_applications\ble_ancs_app\precompiled_hex .
  2. For detailed steps, refer to Programming a Device in MPLAB® IPE in Reference Documentation from Related Links.
    Note: Ensure to choose the correct Device and Tool information.

Using MPLAB® X IDE:

  1. Perform the following the steps mentioned in Running a Precompiled Example. For more information, refer to Running a Precompiled Application Example from Related Links.

  2. Open and program the application example ble_ancs_app.X located in "<Harmony Content Path>\wireless_apps_pic32_bz6\apps\ble\advanced_applications\ble_ancs_app\firmware".
  3. For more details on how to find the Harmony Content Path, refer to Installing the MCC Plugin from Related Links.

Demo Description

This application demonstrates on how to simulate an ANCS client on the curiosity board . The on-board user USR BTN1, LEDs and UART are used as user interface during the demo.

  • UART Settings
    • Baud Rate/Speed – 115200 bps
    • Parity – None
    • Data Bits – 8
    • Stop Bits – 1
    • Flow Control – None
    • Character Encoding: UTF-8
  • USR BTN1 Behavior
    • Press: Press the button for less than 500 ms
    • Long press: Press the button for more than 500 ms
    • Double-click: Click the button twice in 500 ms
  • LED Behavior
    • All LEDs are OFF
    • Green LED flashes one time every 3 seconds
    • Green LED flashes two times every 3 seconds
    • Green LED flashes two times every 1.5 seconds

Testing

  1. Connect the PIC32-BZ6 Curiosity Board to PC, program the precompiled .hex file or application example as mentioned.
  2. Open TeraTerm and configure as mentioned below:
    Terminal Settings
    • Baud Rate/Speed – 115200 bps
    • Parity – None
    • Data Bits – 8
    • Stop Bits – 1
    • Flow Control – None
  3. Reset the board. After reset, the device will be advertising device name “M-dev”.
  4. On the iPhone, remove “M-dev” if it was previously paired.
  5. Clear all notifications on the iPhone and it will display “No Older Nofitifcation”.
  6. Connect USB cable to the curiosity board from the computer.
  7. On the iPhone, open Settings>Bluetooth and click M-dev to connect to and pair with curiosity board.
  8. Open Calendar App on phone and set an event that will alert 2 minutes later.
  9. The notification of the event pops out when time is up.
    Figure 5-193. Notification Event
  10. The below texts will be printed on Tera Term:
    • BLE_ANCS_EVT_NTFY_ADDED_IND
    • connHandle: 0x0071
    • NotificationUID: 0x00000000
    • EventFlags
    • -silent: 0
    • -important: 0
    • -preExisting: 0
    • -positiveAction: 0
    • -negativeAction: 1
    • CategoryID: 0x05
    • CategoryCount: 0x01
    • -> Press USR BTN1 to Get Notification Attributes
  11. On the curiosity board, press USR BTN1 as the printed texts instruct.
  12. The below texts will be printed on Tera Term:
    • BLE_ANCS_EVT_NTFY_ATTR_IND
    • connHandle: 0x0071
    • NotificationUID: 0x00000000
    • bitmask
    • appId: com.apple.mobilecal
    • title: Gggg
    • subtitle
    • msg: Today at 17:04
    • msgSize: 14
    • date: 20230721T170400
    • positiveAction
    • negativeAction: Clear
    • -> Press USR BTN1 to Get App Attributes
  13. On the curiosity board, press USR BTN1 as the printed texts instruct.
  14. The below texts will be printed on Tera Term:
    • BLE_ANCS_EVT_APP_ATTR_IND
    • connHandle: 0x0071
    • appId: com.apple.mobilecal
    • displayName: Calendar
    • -> Double-click USR Button 2: Clear
  15. On the curiosity board, double-click USR BTN1 as the printed texts instruct.
  16. The below texts will be printed on Tera Term:
    • BLE_ANCS_EVT_NTFY_REMOVED_IND
    • connHandle: 0x0071
    • NotificationUID: 0x00000001
    • EventFlags
    • -silent: 0
    • -important: 0
    • -preExisting: 0
    • -positiveAction: 0
    • -negativeAction: 1
    • CategoryID: 0x05
    • CategoryCount: 0x00
  17. Reset the board and the iphone will automatically link back.
    Note:

    The NotificationUID (Notification Unique Identifier) you see in your output is increasing because each new notification generated by the iOS device is assigned a unique by the Apple Notification Center Service (ANCS).

Developing the Application from Scratch using MCC

Follow the steps below to build the application manually:
Note: It is recommended for the new users of the MPLAB Code Configurator to refer MPLAB® Code Configurator (MCC) User’s Guide in Reference Documentation from Related Links.
  1. Create a new harmony project. For more details, see Creating a New MCC Harmony Project from Related Links.
  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_pic32_bz6\apps\ble\advanced_applications\ble_ancs_app\firmware\ble_ancs_app.X.
  3. Accept dependencies or satisfiers when prompted.
  4. Verify if the project graph window has all the expected configuration.
    Figure 5-194. Project Graph

Verify MCC Component Settings

  1. Select Apple Notification Center Service Profile component in project graph.
    1. Enable ANCS Client Role.

      Figure 5-195. ANCS Configuration
  2. Select BLE Stack component in project graph, and configure as mentioned below:
    1. GAP(Generic Access Profile) Settings:
      1. Set Device Name to M-dev
      2. Include <<Flag>> type of Advertising Data (AD)
      3. Include <<Local Name>> AD
      4. Include 128bit UUID of the ANCS in advertising Data so that iphone will list the M-dev in its Bluetooth page of Setting App. The ANCS UUID is 7905F431-B5CE-4E99-A40F-4B1E122D00D0 that will be encoded into <<Service UUID>>/0x15 type of AD

        0x11: the AD length indicating how many bytes are appendixed

        0x15: the value of <<Service UUID>> type

        D0002D121E4B0FA4994ECEB531F40579: the ANCS UUID in little endian

        1115D0002D121E4B0FA4994ECEB531F40579
      5. Enable “Peripheral”
        Figure 5-196. BLE Stack Configuration

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 5-197. Project File

Initialization routines for OSAL, RF System, and BLE System are auto-generated by the MCC. See OSAL Libraries Help in Reference Documentation from Related Links. Initialization routine executed during program initialization can be found in the project file.

Figure 5-198. 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 5-199. app.c
Autogenerated, Advertisement Data Format
Figure 5-200. AD Structures and Types
Table 5-38. Source Files
Source Files Usage
app.cApplication State machine, includes calls for Initialization of all BLE stack (GAP,GATT, SMP, L2CAP) related component configurations
app_ble.cSource code for the BLE stack related component configurations, code related to function calls from app.c
app_ble_handler.cAll GAP, GATT, SMP and L2CAP event handlers
src\app_ble\app_ancs_handler.cHandle ANCS client event from application level
src\config\default\ble\profile_ble\ble_ancs\ble_ancs.cHandle ANCS client event from profile level
Note: app.c is autogenerated and has a state machine based Application code sample. Users can use this template to develop their application.

Header Files

  • ble_gap.h This header file contains BLE GAP functions and is automatically included in the app.c file

Function Calls

MCC generates and adds the code to initialize the BLE Stack GAP, GATT, L2CAP and SMP in APP_BleStackInit() function

  • APP_BleStackInit() is the API that will be called inside the Applications Initial State -- APP_STATE_INIT in app.c

User Application Development

Include

  • Include the user action. For more information, refer to User Action from Related Links.
  • definitions.h in all the files where UART will be used to print debug information
Note: definitions.h is not specific to UART peripheral, instead it must be included in all application source files where peripheral functionality will be exercised.

Configure the Advertisement

  • APP_BleConfigBasic( )
The below code snippet is to set ADs (Advertising Data) including <<Flag>> AD, <<Local Name>>> AD, and the <<Service UUID>> AD for ANCS UUID which will enable the device appearing in device list of Bluetooth page of iphones Setting APP.
static void APP_BleConfigBasic(void)
{
    int8_t                          connTxPower;
    int8_t                          advTxPower;
    BLE_GAP_AdvParams_T             advParam;
    uint8_t advData[]=CONFIG_BLE_GAP_ADV_DATA;
    BLE_GAP_AdvDataParams_T         appAdvData;
    uint8_t scanRspData[]=CONFIG_BLE_GAP_SCAN_RSP_DATA;
    BLE_GAP_AdvDataParams_T         appScanRspData;
Check the pairing status and apply different advertising filter policy. Windows, Android and iOS support the reconnection using ADV_IND. Thus ADV_IND is used for pairing and reconnection.
//Windows/ Android/ iOS support the reconnection using ADV_IND. So using ADV_IND for pairing and reconnection.
    advParam.type = BLE_GAP_ADV_TYPE_ADV_IND;        /* Advertising Type */
    advParam.advChannelMap = BLE_GAP_ADV_CHANNEL_ALL;        /* Advertising Channel Map */
    if (g_pairedDevInfo.bPaired)//Paired already
    {
        advParam.filterPolicy = BLE_GAP_ADV_FILTER_SCAN_CONNECT;     /* Advertising Filter Policy */
    }
    else
    {
        advParam.filterPolicy = BLE_GAP_ADV_FILTER_DEFAULT;     /* Advertising Filter Policy */
    }
    BLE_GAP_SetAdvParams(&advParam);
Start Advertisement
  • APP_EnableAdvDirect(g_pairedDevInfo.bPaired);

Custom function EnableAdvDirect() is called during the Applications initialization - APP_STATE_INIT in app.c.

Figure 5-201. app.c
This custom function will call API BLE_GAP_SetAdvEnable( ) to start or stop advertising.
Note: Users can explore more BLE Advertisement functionalities using the BLE Stack APIs. For more information, refer to BLE Stack in Reference Documentation from Related Links.

Initialize ANCS Client

ANCS Client functionality initialization is done in APP_BleStackInitAdvance( )

BLE_ANCS_Init( ) requests the Device Discovery (DD) middleware to explore the ANCS service of the connecting peer device.

APP_AncsEvtHandler( ) is registered to handle the ANCS event from application level that will not handle the ANCS profile.

    BLE_ANCS_Init();
    BLE_ANCS_EventRegister(APP_AncsEvtHandler);

Implement ANCS Profile

ANCS Profile is implemented in ble_ancs.c. BLE_ANCS_BleEventHandler( ) will handle all ANCS events.
void BLE_ANCS_BleEventHandler(STACK_Event_T *p_stackEvent)
{
    switch (p_stackEvent->groupId)
    {
        case STACK_GRP_BLE_GAP:
            ble_ancs_GapEventProcess((BLE_GAP_Event_T *)p_stackEvent->p_event);
        break;

        case STACK_GRP_GATT:
            ble_ancs_GattEventProcess((GATT_Event_T *)p_stackEvent->p_event);
        break;

        default:
        break;
    }
}

Firmware FSM (Finite State Machine)

This application firmware implements an ANCS client on the curiosity board:

  • APP_ANCS_STATE_IDLE: This application stays in the Idle mode.
  • APP_ANCS_STATE_ADV: The application is waiting for pairing for timeout_adv seconds.
  • APP_ANCS_STATE_ADV_DIR: The application is waiting for reconnection for timeout_adv_dir seconds.
  • APP_ANCS_STATE_CONN: The application is ready for sending commands/receiving notifications.
    Figure 5-202. Finite State Machine
    Table 5-39. Time Out Parameters
    VariableValueDescription
    timeout_adv60sThe timeout of advertising
    timeout_adv_dir30sThe timeout of directed advertising
    Table 5-40. LED vs. State
    Firmware StateLED behavior
    APP_ANCS_STATE_IDLEAll LEDs are OFF
    APP_ANCS_STATE_ADVBlue LED flashes one time every 3 seconds. (ON: 50 ms, OFF: 2950 ms)
    APP_ANCS_STATE_ADV_DIRBlue LED flashes two time every 3 seconds. (ON: 50 ms, OFF: 50 ms)
    APP_ANCS_STATE_CONNBlue LED flashes two times every 1.5 seconds. (ON: 50 ms, OFF: 150 ms)

FSM of the Connection State

State machine when connected:

  • APP_ANCS_IND_INIT: The application enters this state when connected.
  • APP_ANCS_IND_NTFY_ADDED: The application received the event "Notification Added" and is waiting for a button-pressing to send the command "Get Notification Attributes".
  • APP_ANCS_IND_NTFY_ATTR: The application received the data related to "Notification Attributes" and is waiting for a button-pressing to send the command "Get App Attributes".
  • APP_ANCS_IND_APP_ATTR: The application received the data related to "App Attributes" and is waiting for a button action to send the command "Perform Notification Action-Positive"/"Perform Notification Action-Negative".
  • APP_ANCS_IND_NTFY_REMOVED: The application received the event "Notification Removed" and is waiting for another event "Notification Added".
Figure 5-203. Connection State FSM

References

Refer Apple Notification Center Service (ANCS) Specification in Reference Documentation from Related Links.