This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

CC2541: Not Bonding

Part Number: CC2541

Hello,

My controller CC2541 is not bonding with Motog power phone. Below is the log:

nRF Connect, 2021-11-25
No name (B0:B1:13:85:DD:88)
V 23:21:19.615 Starting pairing...
D 23:21:19.615 device.createBond()
D 23:21:19.681 [Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_BONDING (11)
D 23:21:19.690 [Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_NONE (10)
I 23:21:19.690 Bonding failed
D 23:21:21.583 [Callback] Connection state changed with status: 0 and new state: CONNECTED (2)
I 23:21:21.583 Connected to B0:B1:13:85:DD:88
I 23:21:21.599 Notification received from 0000fd02-0000-1000-8000-00805f9b34fb, value: (0x) 81-FF-00-42-00-02-19-5E-0E
A 23:21:21.599 "(0x) 81-FF-00-42-00-02-19-5E-0E" received
V 23:21:21.646 Discovering services...
D 23:21:21.646 gatt.discoverServices()
I 23:21:22.042 Connection parameters updated (interval: 7.5ms, latency: 0, timeout: 5000ms)
D 23:21:22.747 [Callback] Services discovered with status: 0
I 23:21:22.747 Services discovered
V 23:21:22.796 Generic Access (0x1800)
- Device Name [R] (0x2A00)
- Appearance [R] (0x2A01)
- Peripheral Privacy Flag [R] (0x2A02)
- Reconnection Address [W] (0x2A03)
- Peripheral Preferred Connection Parameters [R] (0x2A04)
Generic Attribute (0x1801)
- Service Changed [I] (0x2A05)
   Client Characteristic Configuration (0x2902)
Device Information (0x180A)
- System ID [R] (0x2A23)
- Model Number String [R] (0x2A24)
- Serial Number String [R] (0x2A25)
- Firmware Revision String [R] (0x2A26)
- Hardware Revision String [R] (0x2A27)
- Software Revision String [R] (0x2A28)
- Manufacturer Name String [R] (0x2A29)
- IEEE 11073-20601 Regulatory Certification Data List [R] (0x2A2A)
- PnP ID [R] (0x2A50)
Unknown Service (0000fa00-0000-1000-8000-00805f9b34fb)
- Unknown Characteristic [R W] (0000fa01-0000-1000-8000-00805f9b34fb)
- Unknown Characteristic [N WNR] (0000fa02-0000-1000-8000-00805f9b34fb)
   Client Characteristic Configuration (0x2902)
Unknown Service (0000fb00-0000-1000-8000-00805f9b34fb)
- Unknown Characteristic [N R] (0000fb01-0000-1000-8000-00805f9b34fb)
   Client Characteristic Configuration (0x2902)
- Unknown Characteristic [R W] (0000fb02-0000-1000-8000-00805f9b34fb)
- Unknown Characteristic [N W] (0000fb03-0000-1000-8000-00805f9b34fb)
   Client Characteristic Configuration (0x2902)
- Unknown Characteristic [N R] (0000fb04-0000-1000-8000-00805f9b34fb)
   Client Characteristic Configuration (0x2902)

Controller is getting bonded in other phone Sometimes loses the bond there too and goes undiscoverable. A powercycle rest is required then.

My init code is here:

 

uint16 scanduration = 6000U; 
  uint16 advertOffTime = 2000U;
  uint16 advertisingduration = 2000U;
  uint8 enable_update_request = FALSE;//TRUE;
  uint16 desired_min_interval = 20U;
  uint16 desired_max_interval = 20U;
  uint16 desired_slave_latency = 0U;
  uint16 desired_conn_timeout = 1000U;
  uint16 rssi_read_rate = 500U;
  uint8 initial_advertising_enable = TRUE;

  // Set the GAP Role Parameters
  GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
  GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &advertOffTime );
  GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, scanResponseLength, scanRspData );
  GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );
  GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
  GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
  GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
  GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
  GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
  GAPRole_SetParameter( GAPROLE_RSSI_READ_RATE, sizeof( uint16 ), &rssi_read_rate );
  GAPRole_SetParameter( TGAP_LIM_DISC_SCAN, sizeof( uint16 ), &scanduration );
  GAPRole_SetParameter( TGAP_GEN_DISC_ADV_MIN, sizeof( uint16 ), &advertisingduration );
  

  // Set the GAP Characteristics
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );

  //GAP_SetParamValue( TGAP_GEN_DISC_ADV_MIN, advertisingduration );
  // Set up the advertising interval
  static const uint16 advInt = 500U; //500before
  GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt );
  GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt );
  GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt );
  GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt );    

  // Initialise the observer
  {
    uint8 scanRes = 60;
    GAPRole_SetParameter ( GAPOBSERVERROLE_MAX_SCAN_RES, sizeof( uint8 ), &scanRes );
  }
  // Setuo Scanning interval 

  GAP_SetParamValue( TGAP_LIM_DISC_SCAN_INT, 160  ); //Interval between the start of two consecutive scan windows (100ms)
  GAP_SetParamValue( TGAP_LIM_DISC_SCAN_WIND, 128 ); //The duration in which the Link Layer scans on one channel, (80 ms)
  
  // Setup the GAP Bond Manager
  uint32 passkey = 0;
  uint8 pairMode = GAPBOND_PAIRING_MODE_INITIATE;
  uint8 mitm = FALSE;
  uint8 ioCap = GAPBOND_IO_CAP_NO_INPUT_NO_OUTPUT;
  uint8 bonding = TRUE;
  //uint8 bondAction = GAPBOND_FAIL_TERMINATE_ERASE_BONDS;//GAPBOND_FAIL_TERMINATE_LINK;
  
  
  GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey );
  GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode );
  GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm );
  GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap );
  GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding );
  //GAPBondMgr_SetParameter( GAPBOND_BOND_FAIL_ACTION, sizeof ( uint8 ), &bondAction );

  
  //GAPBondMgr_SetParameter(GAPBOND_ERASE_ALLBONDS, 0U, NULL);
  
  // Initialize required GATT services
  GGS_AddService( GATT_ALL_SERVICES );

Do I need periodically invoke advertising when device is not connected (like below) or BLE stack will automatically take care of it?

 if(gapRole_state != GAPROLE_CONNECTED && gapRole_state != GAPROLE_CONNECTED_ADV)
 {
        periph_mode = osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, 1 );
 }

And when I check bonds[index].publicAddr , I see motog's bluetooth device address still present in the register.

I cannot find any reason why this is happening? My ram memory is almost consumed. Does it have any dependency here?

Looking forward to your advice. Thank you.

Best,

Varun

  • Hi Varun,

    For the bonding issue, I would recommend to use a BLE sniffer log to get more information on the reasons why it is failing.
    At the moment it is a bit difficult to debug as the CC2541 believes the bonding process succeeded while the phone does not provide any detail.

    I have review the parameters set in your init code. It may be worth to see if changing some of these could help. For example, I am wondering if the phone could refuse the bonding attempts with MITM=false.

    In all the cases, with the RAM almost full, it is expected you run into some memory corruptions potentially leading to unresponsive device.

    I hope this will help,

    Best regards,

  • Hi Clement,

    Thanks for giving some directions. I am attahcing the sniffer logs here.

    nRF Connect, 2021-11-26
    WirelessONE-000PCT (B0:B1:13:85:DD:88)
    V	13:49:21.885	Connecting to B0:B1:13:85:DD:88...
    D	13:49:21.886	gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, preferred PHY = LE 1M)
    D	13:49:23.340	[Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_BONDING (11)
    D	13:49:23.371	[Broadcast] Action received: android.bluetooth.device.action.PAIRING_REQUEST, pairing variant: PAIRING_VARIANT_CONSENT (3)
    D	13:49:24.876	[Broadcast] Action received: android.bluetooth.device.action.ACL_CONNECTED
    D	13:49:24.877	[Callback] Connection state changed with status: 0 and new state: CONNECTED (2)
    I	13:49:24.877	Connected to B0:B1:13:85:DD:88
    I	13:49:24.917	Connection parameters updated (interval: 7.5ms, latency: 0, timeout: 5000ms)
    I	13:49:24.938	Connection parameters updated (interval: 45.0ms, latency: 0, timeout: 5000ms)
    D	13:49:27.585	[Broadcast] Action received: android.bluetooth.device.action.PAIRING_REQUEST, pairing variant: PAIRING_VARIANT_CONSENT (3)
    D	13:50:00.204	[Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_NONE (10)
    I	13:50:00.204	Bonding failed
    V	13:50:00.271	Discovering services...
    D	13:50:00.271	gatt.discoverServices()
    D	13:50:00.285	[Callback] Services discovered with status: 0
    I	13:50:00.285	Services discovered
    V	13:50:00.436	Generic Access (0x1800)
    - Device Name [R] (0x2A00)
    - Appearance [R] (0x2A01)
    - Peripheral Privacy Flag [R W] (0x2A02)
    - Reconnection Address [W] (0x2A03)
    - Peripheral Preferred Connection Parameters [R] (0x2A04)
    Generic Attribute (0x1801)
    - Service Changed [I] (0x2A05)
       Client Characteristic Configuration (0x2902)
    Device Information (0x180A)
    - System ID [R] (0x2A23)
    - Model Number String [R] (0x2A24)
    - Serial Number String [R] (0x2A25)
    - Firmware Revision String [R] (0x2A26)
    - Hardware Revision String [R] (0x2A27)
    - Software Revision String [R] (0x2A28)
    - Manufacturer Name String [R] (0x2A29)
    - IEEE 11073-20601 Regulatory Certification Data List [R] (0x2A2A)
    - PnP ID [R] (0x2A50)
    Unknown Service (0000fa00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fa01-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N WNR] (0000fa02-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    Unknown Service (0000fb00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R] (0000fb01-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fb02-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N W] (0000fb03-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [N R] (0000fb04-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [W] (0000fb05-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [W] (0000fb06-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fb07-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R] (0000fb08-0000-1000-8000-00805f9b34fb)
    Unknown Service (0000fc00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc10-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc13-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc14-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc16-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc18-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc1a-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc2e-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc42-0000-1000-8000-00805f9b34fb)
    Unknown Service (0000fe00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R W] (0000fe01-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fe02-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R W] (0000fe03-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fe04-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fe05-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fe06-0000-1000-8000-00805f9b34fb)
    D	13:50:00.437	gatt.setCharacteristicNotification(00002a05-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.439	gatt.setCharacteristicNotification(0000fa02-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.447	gatt.setCharacteristicNotification(0000fb01-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.455	gatt.setCharacteristicNotification(0000fb03-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.466	gatt.setCharacteristicNotification(0000fb04-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.481	gatt.setCharacteristicNotification(0000fe01-0000-1000-8000-00805f9b34fb, true)
    D	13:50:00.493	gatt.setCharacteristicNotification(0000fe03-0000-1000-8000-00805f9b34fb, true)
    D	13:50:03.385	[Callback] Connection state changed with status: 22 and new state: DISCONNECTED (0)
    D	13:50:03.385	[Broadcast] Action received: android.bluetooth.device.action.ACL_DISCONNECTED
    E	13:50:03.389	Error 22 (0x16): GATT CONN TERMINATE LOCAL HOST
    I	13:50:03.389	Disconnected
    D	13:56:55.752	gatt.close()
    D	13:56:55.764	wait(200)
    V	13:56:55.966	Connecting to B0:B1:13:85:DD:88...
    D	13:56:55.966	gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, preferred PHY = LE 1M)
    D	13:56:56.819	[Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_BONDING (11)
    D	13:56:56.853	[Broadcast] Action received: android.bluetooth.device.action.PAIRING_REQUEST, pairing variant: PAIRING_VARIANT_CONSENT (3)
    D	13:57:00.569	[Broadcast] Action received: android.bluetooth.device.action.ACL_CONNECTED
    D	13:57:00.571	[Callback] Connection state changed with status: 0 and new state: CONNECTED (2)
    I	13:57:00.571	Connected to B0:B1:13:85:DD:88
    I	13:57:00.576	Connection parameters updated (interval: 7.5ms, latency: 0, timeout: 5000ms)
    I	13:57:00.578	Connection parameters updated (interval: 45.0ms, latency: 0, timeout: 5000ms)
    D	13:57:00.715	[Broadcast] Action received: android.bluetooth.device.action.PAIRING_REQUEST, pairing variant: PAIRING_VARIANT_CONSENT (3)
    D	13:57:33.691	[Broadcast] Action received: android.bluetooth.device.action.BOND_STATE_CHANGED, bond state changed to: BOND_NONE (10)
    I	13:57:33.691	Bonding failed
    V	13:57:33.708	Discovering services...
    D	13:57:33.708	gatt.discoverServices()
    D	13:57:33.790	[Callback] Services discovered with status: 0
    I	13:57:33.790	Services discovered
    V	13:57:34.226	Generic Access (0x1800)
    - Device Name [R] (0x2A00)
    - Appearance [R] (0x2A01)
    - Peripheral Privacy Flag [R W] (0x2A02)
    - Reconnection Address [W] (0x2A03)
    - Peripheral Preferred Connection Parameters [R] (0x2A04)
    Generic Attribute (0x1801)
    - Service Changed [I] (0x2A05)
       Client Characteristic Configuration (0x2902)
    Device Information (0x180A)
    - System ID [R] (0x2A23)
    - Model Number String [R] (0x2A24)
    - Serial Number String [R] (0x2A25)
    - Firmware Revision String [R] (0x2A26)
    - Hardware Revision String [R] (0x2A27)
    - Software Revision String [R] (0x2A28)
    - Manufacturer Name String [R] (0x2A29)
    - IEEE 11073-20601 Regulatory Certification Data List [R] (0x2A2A)
    - PnP ID [R] (0x2A50)
    Unknown Service (0000fa00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fa01-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N WNR] (0000fa02-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    Unknown Service (0000fb00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R] (0000fb01-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fb02-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N W] (0000fb03-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [N R] (0000fb04-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [W] (0000fb05-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [W] (0000fb06-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fb07-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R] (0000fb08-0000-1000-8000-00805f9b34fb)
    Unknown Service (0000fc00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc10-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc13-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc14-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc16-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc18-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc1a-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc2e-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fc42-0000-1000-8000-00805f9b34fb)
    Unknown Service (0000fe00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R W] (0000fe01-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fe02-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R W] (0000fe03-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [R W] (0000fe04-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fe05-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [R W] (0000fe06-0000-1000-8000-00805f9b34fb)
    Unknown Service (0000fd00-0000-1000-8000-00805f9b34fb)
    - Unknown Characteristic [N R W] (0000fd01-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    - Unknown Characteristic [N R] (0000fd02-0000-1000-8000-00805f9b34fb)
       Client Characteristic Configuration (0x2902)
    D	13:57:34.226	gatt.setCharacteristicNotification(00002a05-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.228	gatt.setCharacteristicNotification(0000fa02-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.233	gatt.setCharacteristicNotification(0000fb01-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.240	gatt.setCharacteristicNotification(0000fb03-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.243	gatt.setCharacteristicNotification(0000fb04-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.246	gatt.setCharacteristicNotification(0000fe01-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.249	gatt.setCharacteristicNotification(0000fe03-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.258	gatt.setCharacteristicNotification(0000fd01-0000-1000-8000-00805f9b34fb, true)
    D	13:57:34.262	gatt.setCharacteristicNotification(0000fd02-0000-1000-8000-00805f9b34fb, true)
    D	13:57:36.775	[Callback] Connection state changed with status: 22 and new state: DISCONNECTED (0)
    D	13:57:36.776	[Broadcast] Action received: android.bluetooth.device.action.ACL_DISCONNECTED
    E	13:57:36.776	Error 22 (0x16): GATT CONN TERMINATE LOCAL HOST
    I	13:57:36.776	Disconnected
    

    My memory usage originally is below:

    132 261 bytes of CODE memory (+ 14 923 range fill )
    35 bytes of DATA memory (+ 80 absolute )
    7 859 bytes of XDATA memory
    179 bytes of IDATA memory (+ 1 absolute )
    8 bits of BIT memory
    900 bytes of CONST memory

    I tried disabling some of my part to reduce the memory (not much some 400 bytes) like below

    126 204 bytes of CODE memory (+ 20 980 range fill )
    35 bytes of DATA memory (+ 80 absolute )
    7 742 bytes of XDATA memory
    179 bytes of IDATA memory (+ 1 absolute )
    8 bits of BIT memory
    763 bytes of CONST memory

    and made MITM= TRUE. But no luck.

    Best,

    Varun

  • Hi,

    It would help if you could provide the log provided by a BLE sniffer showing the detail of the Bluetooth packets exchanged.

    Based on the last log you have provided, I see occurrences of  "Error 22 (0x16): GATT CONN TERMINATE LOCAL HOST". This probably means the phone closes the connection. It would be interesting to understand why.

    Best regards,

  • Hi Clement,

    I am new to BLE. Just to make sure. by BLE sniffer you mean apps like nRF connect, right? The log which i sent you earlier, I logged it from this app. Are you suggesting me to run it for a while and get a detailed log? Do I need to enable any option here? Can you give me an example log ?

    Thank you !

    Best,

    Varun 

  • Hi,

    I was rather referring to tools showing the details of each packet, like the systems provided by Elisys or TI packet sniffer

    With that being said, I would recommend to look into the error I have mentioned in my previous message.

    Best regards,

  • Hi Clement,

    I don't have the dongle (launch pad) for this. However, I have an interesting observation. When I flash the SW with older BLE-CC254x-1.4.2.2 , moto g connects well,  but with the latest BLE-CC254x-1.5.2.0, it is giving the above error.

    I am wondering if you have also experienced this with the latest BLE stack?

    Best,

    Varun

  • Hi Varun,

    Based on our test results none of the phone we have tested with BLE-CC254x-1.5.2.0 have raised an error. However, I do not think we have specifically tested the Moto G power phone. Let me double check this with my team. 

    Best regards,

  • Hi Clement,

    If you may allow, shall I share this file with you? 

    /******************************************************************************
    
     @file  peripheral.c
    
     @brief GAP Peripheral Role
    
     Group: WCS, BTS
     Target Device: CC2540, CC2541
    
     ******************************************************************************
     
     Copyright (c) 2009-2021, Texas Instruments Incorporated
     All rights reserved.
    
     IMPORTANT: Your use of this Software is limited to those specific rights
     granted under the terms of a software license agreement between the user
     who downloaded the software, his/her employer (which must be your employer)
     and Texas Instruments Incorporated (the "License"). You may not use this
     Software unless you agree to abide by the terms of the License. The License
     limits your use, and you acknowledge, that the Software may not be modified,
     copied or distributed unless embedded on a Texas Instruments microcontroller
     or used solely and exclusively in conjunction with a Texas Instruments radio
     frequency transceiver, which is integrated into your product. Other than for
     the foregoing purpose, you may not use, reproduce, copy, prepare derivative
     works of, modify, distribute, perform, display or sell this Software and/or
     its documentation for any purpose.
    
     YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
     PROVIDED �AS IS� WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
     INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
     NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
     TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
     NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
     LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
     INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
     OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
     OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
     (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
    
     Should you have any questions regarding your right to use this Software,
     contact Texas Instruments Incorporated at www.TI.com.
    
     ******************************************************************************
     Release Name: ble_sdk_1.5.2.0
     Release Date: 2021-03-10 17:38:59
     *****************************************************************************/
    
    /*********************************************************************
     * INCLUDES
     */
    #include "bcomdef.h"
    #include "OSAL.h"
    #include "hci_tl.h"
    #include "l2cap.h"
    #include "gap.h"
    #include "linkdb.h"
    #include "att.h"
    #include "gatt.h"
    #include "osal_snv.h"
    
    #include "peripheral.h"
    #include "gapbondmgr.h"
       
    #include "ConnectionManager.h"
    
    /*********************************************************************
     * MACROS
     */
    
    /*********************************************************************
     * CONSTANTS
     */
    // Profile Events
    #define START_ADVERTISING_EVT         0x0001  // Start Advertising
    #define RSSI_READ_EVT                 0x0002  // Read RSSI
    #define START_CONN_UPDATE_EVT         0x0004  // Start Connection Update Procedure
    #define CONN_PARAM_TIMEOUT_EVT        0x0008  // Connection Parameters Update Timeout
    
    #define DEFAULT_ADVERT_OFF_TIME       30000   // 30 seconds
    
    #define RSSI_NOT_AVAILABLE            127
    
    #define DEFAULT_MIN_CONN_INTERVAL     0x0006  // 100 milliseconds
    #define DEFAULT_MAX_CONN_INTERVAL     0x0C80  // 4 seconds
    
    #define MIN_CONN_INTERVAL             0x0006
    #define MAX_CONN_INTERVAL             0x0C80
    
    #define DEFAULT_TIMEOUT_MULTIPLIER    1000
    
    #define CONN_INTERVAL_MULTIPLIER      6
    
    #define MIN_SLAVE_LATENCY             0
    #define MAX_SLAVE_LATENCY             500
    
    #define MIN_TIMEOUT_MULTIPLIER        0x000a
    #define MAX_TIMEOUT_MULTIPLIER        0x0c80
    
    #define MAX_TIMEOUT_VALUE             0xFFFF
    
    // Discovey mode (limited, general, all)
    #define DEFAULT_DISCOVERY_MODE                DEVDISC_MODE_ALL
    
    // TRUE to use active scan
    #define DEFAULT_DISCOVERY_ACTIVE_SCAN         FALSE
    
    // TRUE to use white list during discovery
    #define DEFAULT_DISCOVERY_WHITE_LIST          FALSE
       
    #define C_PERIPHERAL_TASK_1MIN_SCALE_COUNT 20U
    
    /*********************************************************************
     * TYPEDEFS
     */
    
    /*********************************************************************
     * GLOBAL VARIABLES
     */
    
    /*********************************************************************
     * EXTERNAL VARIABLES
     */
    
    /*********************************************************************
     * EXTERNAL FUNCTIONS
     */
    
    /*********************************************************************
     * LOCAL VARIABLES
     */
    static uint8 gapRole_TaskID;   // Task ID for internal task/event processing
    
    static gaprole_States_t gapRole_state;
    
    /*********************************************************************
     * Profile Parameters - reference GAPROLE_PROFILE_PARAMETERS for
     * descriptions
     */
    
    static uint8  gapRole_profileRole;
    static uint8  gapRole_IRK[KEYLEN];
    static uint8  gapRole_SRK[KEYLEN];
    static uint32 gapRole_signCounter;
    static uint8  gapRole_bdAddr[B_ADDR_LEN];
    static uint8  gapRole_AdvEnabled = TRUE;
    static uint8  gapRole_AdvNonConnEnabled = FALSE;
    static uint16 gapRole_AdvertOffTime = DEFAULT_ADVERT_OFF_TIME;
    static uint8  gapRole_AdvertDataLen = 3;
    static uint8  gapRole_AdvertData[B_MAX_ADV_LEN] =
    {
      0x02,   // length of this data
      GAP_ADTYPE_FLAGS,   // AD Type = Flags
      // Limited Discoverable & BR/EDR not supported
      (GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED),
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
    };
    static uint8  gapRole_ScanRspDataLen = 0;
    static uint8  gapRole_ScanRspData[B_MAX_ADV_LEN] = {0};
    static uint8  gapRole_AdvEventType;
    static uint8  gapRole_AdvDirectType;
    static uint8  gapRole_AdvDirectAddr[B_ADDR_LEN] = {0};
    static uint8  gapRole_AdvChanMap;
    static uint8  gapRole_AdvFilterPolicy;
    
    static uint16 gapRole_ConnectionHandle = INVALID_CONNHANDLE;
    static uint16 gapRole_RSSIReadRate = 0;
    
    static uint8  gapRole_ConnectedDevAddr[B_ADDR_LEN] = {0};
    
    static uint8  gapRole_ParamUpdateEnable = FALSE;
    static uint16 gapRole_MinConnInterval = DEFAULT_MIN_CONN_INTERVAL;
    static uint16 gapRole_MaxConnInterval = DEFAULT_MAX_CONN_INTERVAL;
    static uint16 gapRole_SlaveLatency = MIN_SLAVE_LATENCY;
    static uint16 gapRole_TimeoutMultiplier = DEFAULT_TIMEOUT_MULTIPLIER;
    
    static uint16 gapRole_ConnInterval = 0;
    static uint16 gapRole_ConnSlaveLatency = 0;
    static uint16 gapRole_ConnTimeout = 0;
    
    static uint8 paramUpdateNoSuccessOption = GAPROLE_NO_ACTION;
    
    //static uint8  gapObserverRoleBdAddr[B_ADDR_LEN];
    static uint8  gapObserverRoleMaxScanRes = 10;
    
    // Application callbacks
    static gapRolesCBs_t *pGapRoles_AppCGs = NULL;
    static gapRolesParamUpdateCB_t *pGapRoles_ParamUpdateCB = NULL;
    
    
    static uint8 periphtest = 20;
    static uint8 periph_mode = 99; 
    static uint8 event_count = 7;
    /* TPMS counter for 1min scaling from task rate */
    static uint8 TPMS_1MinElapseCntr_u8= 0U;
    uint8 peripheraltest(void) {return periphtest; }
    uint8 periphmode(void) {return periph_mode; }
    uint8 eventcount(void) {return event_count;}
    
    /*********************************************************************
     * Profile Attributes - variables
     */
    
    /*********************************************************************
     * Profile Attributes - Table
     */
    
    /*********************************************************************
     * LOCAL FUNCTIONS
     */
    static void gapRole_ProcessOSALMsg( osal_event_hdr_t *pMsg );
    static void gapRole_ProcessGattEvent(gattMsgEvent_t *pMsg);
    static void gapRole_ProcessGAPMsg( gapEventHdr_t *pMsg );
    static void gapRole_SetupGAP( void );
    static void gapRole_HandleParamUpdateNoSuccess( void );
    static void gapRole_startConnUpdate( uint8 handleFailure );
    
    /*********************************************************************
     * NETWORK LAYER CALLBACKS
     */
    
    /*********************************************************************
     * PUBLIC FUNCTIONS
     */
    
    /*********************************************************************
     * @brief   Set a GAP Role parameter.
     *
     * Public function defined in peripheral.h.
     */
    bStatus_t GAPRole_SetParameter( uint16 param, uint8 len, void *pValue )
    {
      bStatus_t ret = SUCCESS;
      switch ( param )
      {
        case GAPROLE_IRK:
          if ( len == KEYLEN )
          {
            VOID osal_memcpy( gapRole_IRK, pValue, KEYLEN ) ;
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_SRK:
          if ( len == KEYLEN )
          {
            VOID osal_memcpy( gapRole_SRK, pValue, KEYLEN ) ;
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_SIGNCOUNTER:
          if ( len == sizeof ( uint32 ) )
          {
            gapRole_signCounter = *((uint32*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADVERT_ENABLED:
          if ( len == sizeof ( uint8 ) )
          {  
            // Non-connectable advertising must be disabled.
            if ( gapRole_AdvNonConnEnabled != TRUE )
            {
              uint8 oldAdvEnabled = gapRole_AdvEnabled;
              gapRole_AdvEnabled = *((uint8*)pValue);
    
              if ( (oldAdvEnabled) && (gapRole_AdvEnabled == FALSE) )
              { 
                // Turn off advertising.
                if ( (gapRole_state == GAPROLE_ADVERTISING) 
                    || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) )
                { 
                  VOID GAP_EndDiscoverable( gapRole_TaskID );
                }
              }
              else if ( (oldAdvEnabled == FALSE) && (gapRole_AdvEnabled) )
              {
                // Turn on advertising.
                if ( (gapRole_state == GAPROLE_STARTED)
                    || (gapRole_state == GAPROLE_WAITING)
                    || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) )
                {
                  VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT );
                }
              }
            }
            else
            {
              ret = bleIncorrectMode;
            }
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
          
        case GAPROLE_ADV_NONCONN_ENABLED:
          if ( len == sizeof ( uint8 ) )
          {
            // Connectable advertising must be disabled.
            if ( gapRole_AdvEnabled != TRUE )
            {
              uint8 oldAdvEnabled = gapRole_AdvNonConnEnabled;
              gapRole_AdvNonConnEnabled = *((uint8*)pValue);
              
              if ( (oldAdvEnabled) && (gapRole_AdvNonConnEnabled == FALSE) )
              {
                if ( (gapRole_state == GAPROLE_ADVERTISING_NONCONN) 
                    || (gapRole_state == GAPROLE_CONNECTED_ADV)
                    || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) )
                {
                  VOID GAP_EndDiscoverable( gapRole_TaskID );
                }
              }
              else if ( (oldAdvEnabled == FALSE) && (gapRole_AdvNonConnEnabled) )
              {
                // Turn on advertising.
                if ( (gapRole_state == GAPROLE_STARTED)
                    || (gapRole_state == GAPROLE_WAITING)
                    || (gapRole_state == GAPROLE_CONNECTED)
                    || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT) )
                {
                  VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT );
                }
              }
            }
            else
            {
              ret = bleIncorrectMode;
            }
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;      
        
        case GAPROLE_ADVERT_OFF_TIME:
          if ( len == sizeof ( uint16 ) )
          {
            gapRole_AdvertOffTime = *((uint16*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADVERT_DATA:
          if ( len <= B_MAX_ADV_LEN )
          {
            VOID osal_memset( gapRole_AdvertData, 0, B_MAX_ADV_LEN );
            VOID osal_memcpy( gapRole_AdvertData, pValue, len );
            gapRole_AdvertDataLen = len;
            
            // Update the advertising data
            ret = GAP_UpdateAdvertisingData( gapRole_TaskID,
                                  TRUE, gapRole_AdvertDataLen, gapRole_AdvertData );
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_SCAN_RSP_DATA:
          if ( len <= B_MAX_ADV_LEN )
          {
            VOID osal_memset( gapRole_ScanRspData, 0, B_MAX_ADV_LEN );
            VOID osal_memcpy( gapRole_ScanRspData, pValue, len );
            gapRole_ScanRspDataLen = len;
            
            // Update the Response Data
            ret = GAP_UpdateAdvertisingData( gapRole_TaskID,
                                  FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData );
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADV_EVENT_TYPE:
          if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_ADTYPE_ADV_LDC_DIRECT_IND) )
          {
            gapRole_AdvEventType = *((uint8*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADV_DIRECT_TYPE:
          if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= ADDRTYPE_PRIVATE_RESOLVE) )
          {
            gapRole_AdvDirectType = *((uint8*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADV_DIRECT_ADDR:
          if ( len == B_ADDR_LEN )
          {
            VOID osal_memcpy( gapRole_AdvDirectAddr, pValue, B_ADDR_LEN ) ;
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADV_CHANNEL_MAP:
          if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= 0x07) )
          {
            gapRole_AdvChanMap = *((uint8*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_ADV_FILTER_POLICY:
          if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= GAP_FILTER_POLICY_WHITE) )
          {
            gapRole_AdvFilterPolicy = *((uint8*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_RSSI_READ_RATE:
          if ( len == sizeof ( uint16 ) )
          {
            gapRole_RSSIReadRate = *((uint16*)pValue);
    
            if ( (gapRole_RSSIReadRate) && (gapRole_state == GAPROLE_CONNECTED) )
            {
              // Start the RSSI Reads
              VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate );
            }
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_PARAM_UPDATE_ENABLE:
          if ( (len == sizeof ( uint8 )) && (*((uint8*)pValue) <= TRUE) )
          {
            gapRole_ParamUpdateEnable = *((uint8*)pValue);
          }
          else
          {
            ret = bleInvalidRange;
          }
          break;
    
        case GAPROLE_MIN_CONN_INTERVAL:
          {
            uint16 newInterval = *((uint16*)pValue);
            if (   len == sizeof ( uint16 )           &&
                 ( newInterval >= MIN_CONN_INTERVAL ) &&
                 ( newInterval <= MAX_CONN_INTERVAL ) )
            {
              gapRole_MinConnInterval = newInterval;
            }
            else
            {
              ret = bleInvalidRange;
            }
          }
          break;
    
        case GAPROLE_MAX_CONN_INTERVAL:
          {
            uint16 newInterval = *((uint16*)pValue);
            if (   len == sizeof ( uint16 )          &&
                 ( newInterval >= MIN_CONN_INTERVAL) &&
                 ( newInterval <= MAX_CONN_INTERVAL) )
            {
              gapRole_MaxConnInterval = newInterval;
            }
            else
            {
              ret = bleInvalidRange;
            }
          }
          break;
    
        case GAPROLE_SLAVE_LATENCY:
          {
            uint16 latency = *((uint16*)pValue);
            if ( len == sizeof ( uint16 ) && (latency < MAX_SLAVE_LATENCY) )
            {
              gapRole_SlaveLatency = latency;
            }
            else
            {
              ret = bleInvalidRange;
            }
          }
          break;
    
        case GAPROLE_TIMEOUT_MULTIPLIER:
          {
            uint16 newTimeout = *((uint16*)pValue);
            if ( len == sizeof ( uint16 )
                && (newTimeout >= MIN_TIMEOUT_MULTIPLIER) && (newTimeout <= MAX_TIMEOUT_MULTIPLIER) )
            {
              gapRole_TimeoutMultiplier = newTimeout;
            }
            else
            {
              ret = bleInvalidRange;
            }
          }
          break;
    
          case GAPROLE_PARAM_UPDATE_REQ:
            {
              uint8 req = *((uint8*)pValue);
              if ( len == sizeof ( uint8 ) && (req == TRUE) )
              {
                // Make sure we don't send an L2CAP Connection Parameter Update Request
                // command within TGAP(conn_param_timeout) of an L2CAP Connection Parameter
                // Update Response being received.
                if ( osal_get_timeoutEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT ) == 0 )
                {             
                  // Start connection update procedure
                  gapRole_startConnUpdate( GAPROLE_NO_ACTION );
                  
                  // Connection update requested by app, cancel such pending procedure (if active)
                  VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT );
                }
                else
                {
                  ret = blePending;
                }
              }
              else
              {
                ret = bleInvalidRange;
              }
            }
            break;
    
          case GAPOBSERVERROLE_MAX_SCAN_RES:
            if ( len == sizeof ( uint8 ) )
            {
              gapObserverRoleMaxScanRes = *((uint8*)pValue);
            }
            else
            {
              ret = bleInvalidRange;
            }
            break;
            
        default:
          // The param value isn't part of this profile, try the GAP.
          if ( (param < TGAP_PARAMID_MAX) && (len == sizeof ( uint16 )) )
          {
            ret = GAP_SetParamValue( param, *((uint16*)pValue) );
          }
          else
          {
            ret = INVALIDPARAMETER;
          }
          break;
      }
    
      return ( ret );
    }
    
    /*********************************************************************
     * @brief   Get a GAP Role parameter.
     *
     * Public function defined in peripheral.h.
     */
    bStatus_t GAPRole_GetParameter( uint16 param, void *pValue )
    {
      bStatus_t ret = SUCCESS;
      switch ( param )
      {
        case GAPROLE_PROFILEROLE:
          *((uint8*)pValue) = gapRole_profileRole;
          break;
    
        case GAPROLE_IRK:
          VOID osal_memcpy( pValue, gapRole_IRK, KEYLEN ) ;
          break;
    
        case GAPROLE_SRK:
          VOID osal_memcpy( pValue, gapRole_SRK, KEYLEN ) ;
          break;
    
        case GAPROLE_SIGNCOUNTER:
          *((uint32*)pValue) = gapRole_signCounter;
          break;
    
        case GAPROLE_BD_ADDR:
          VOID osal_memcpy( pValue, gapRole_bdAddr, B_ADDR_LEN ) ;
          break;
    
        case GAPROLE_ADVERT_ENABLED:
          *((uint8*)pValue) = gapRole_AdvEnabled;
          break;
          
        case GAPROLE_ADV_NONCONN_ENABLED:
          *((uint8*)pValue) = gapRole_AdvNonConnEnabled;
          break;
          
        case GAPROLE_ADVERT_OFF_TIME:
          *((uint16*)pValue) = gapRole_AdvertOffTime;
          break;
    
        case GAPROLE_ADVERT_DATA:
          VOID osal_memcpy( pValue , gapRole_AdvertData, gapRole_AdvertDataLen );
          break;
    
        case GAPROLE_SCAN_RSP_DATA:
          VOID osal_memcpy( pValue, gapRole_ScanRspData, gapRole_ScanRspDataLen ) ;
          break;
    
        case GAPROLE_ADV_EVENT_TYPE:
          *((uint8*)pValue) = gapRole_AdvEventType;
          break;
    
        case GAPROLE_ADV_DIRECT_TYPE:
          *((uint8*)pValue) = gapRole_AdvDirectType;
          break;
    
        case GAPROLE_ADV_DIRECT_ADDR:
          VOID osal_memcpy( pValue, gapRole_AdvDirectAddr, B_ADDR_LEN ) ;
          break;
    
        case GAPROLE_ADV_CHANNEL_MAP:
          *((uint8*)pValue) = gapRole_AdvChanMap;
          break;
    
        case GAPROLE_ADV_FILTER_POLICY:
          *((uint8*)pValue) = gapRole_AdvFilterPolicy;
          break;
    
        case GAPROLE_CONNHANDLE:
          *((uint16*)pValue) = gapRole_ConnectionHandle;
          break;
    
        case GAPROLE_RSSI_READ_RATE:
          *((uint16*)pValue) = gapRole_RSSIReadRate;
          break;
    
        case GAPROLE_PARAM_UPDATE_ENABLE:
          *((uint16*)pValue) = gapRole_ParamUpdateEnable;
          break;
    
        case GAPROLE_MIN_CONN_INTERVAL:
          *((uint16*)pValue) = gapRole_MinConnInterval;
          break;
    
        case GAPROLE_MAX_CONN_INTERVAL:
          *((uint16*)pValue) = gapRole_MaxConnInterval;
          break;
    
        case GAPROLE_SLAVE_LATENCY:
          *((uint16*)pValue) = gapRole_SlaveLatency;
          break;
    
        case GAPROLE_TIMEOUT_MULTIPLIER:
          *((uint16*)pValue) = gapRole_TimeoutMultiplier;
          break;
    
        case GAPROLE_CONN_BD_ADDR:
          VOID osal_memcpy( pValue, gapRole_ConnectedDevAddr, B_ADDR_LEN ) ;
          break;
    
        case GAPROLE_CONN_INTERVAL:
          *((uint16*)pValue) = gapRole_ConnInterval;
          break;
    
        case GAPROLE_CONN_LATENCY:
          *((uint16*)pValue) = gapRole_ConnSlaveLatency;
          break;
    
        case GAPROLE_CONN_TIMEOUT:
          *((uint16*)pValue) = gapRole_ConnTimeout;
          break;
    
        case GAPROLE_STATE:
          *((uint8*)pValue) = gapRole_state;
          break;
        
        default:
          // The param value isn't part of this profile, try the GAP.
          if ( param < TGAP_PARAMID_MAX )
          {
            *((uint16*)pValue) = GAP_GetParamValue( param );
          }
          else
          {
            ret = INVALIDPARAMETER;
          }
          break;
      }
    
      return ( ret );
    }
    
    /*********************************************************************
     * @brief   Does the device initialization.
     *
     * Public function defined in peripheral.h.
     */
    bStatus_t GAPRole_StartDevice( gapRolesCBs_t *pAppCallbacks )
    {
      if ( gapRole_state == GAPROLE_INIT )
      {   
        // Clear all of the Application callbacks
        if ( pAppCallbacks )
        {
          pGapRoles_AppCGs = pAppCallbacks;
        }
    
        // Start the GAP
        gapRole_SetupGAP();
    
        return ( SUCCESS );
      }
      else
      {
        return ( bleAlreadyInRequestedMode );
      }
    }
    
    /*********************************************************************
     * @brief   Register application's callbacks.
     *
     * Public function defined in peripheral.h.
     */
    void GAPRole_RegisterAppCBs( gapRolesParamUpdateCB_t *pParamUpdateCB )
    {
      if ( pParamUpdateCB != NULL )
      {
        pGapRoles_ParamUpdateCB = pParamUpdateCB;
      }
    }
    
    /*********************************************************************
     * @brief   Terminates the existing connection.
     *
     * Public function defined in peripheral.h.
     */
    bStatus_t GAPRole_TerminateConnection( void )
    {
      if ( gapRole_state == GAPROLE_CONNECTED )
      {
        return ( GAP_TerminateLinkReq( gapRole_TaskID, gapRole_ConnectionHandle, 
                                       HCI_DISCONNECT_REMOTE_USER_TERM ) );
      }
      else
      {
        return ( bleIncorrectMode );
      }
    }
    
    /*********************************************************************
     * LOCAL FUNCTION PROTOTYPES
     */
    
    /*********************************************************************
     * @brief   Task Initialization function.
     *
     * Internal function defined in peripheral.h.
     */
    void GAPRole_Init( uint8 task_id )
    {
      gapRole_TaskID = task_id;
    
      gapRole_state = GAPROLE_INIT;
      gapRole_ConnectionHandle = INVALID_CONNHANDLE;
    
      // Register for HCI/Host messages (for RSSI)
      GAP_RegisterForMsgs( gapRole_TaskID );
    
      // Initialize the Profile Advertising and Connection Parameters
      gapRole_profileRole = GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER;
      VOID osal_memset( gapRole_IRK, 0, KEYLEN );
      VOID osal_memset( gapRole_SRK, 0, KEYLEN );
      gapRole_signCounter = 0;
      gapRole_AdvEventType = GAP_ADTYPE_ADV_IND;
      gapRole_AdvDirectType = ADDRTYPE_PUBLIC;
      gapRole_AdvChanMap = GAP_ADVCHAN_ALL;
      gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL;
    
      // Restore Items from NV
      VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapRole_IRK );
      VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapRole_SRK );
      VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter );
    }
    
    /*********************************************************************
     * @brief   Task Event Processor function.
     *
     * Internal function defined in peripheral.h.
     */
    uint16 GAPRole_ProcessEvent( uint8 task_id, uint16 events )
    {
      VOID task_id; // OSAL required parameter that isn't used in this function
    
      if ( events & SYS_EVENT_MSG )
      {
        uint8 *pMsg;
    
        if ( (pMsg = osal_msg_receive( gapRole_TaskID )) != NULL )
        {
          gapRole_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
    
          // Release the OSAL message
          VOID osal_msg_deallocate( pMsg );
        }
    
        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
      }
    
      if ( events & GAP_EVENT_SIGN_COUNTER_CHANGED )
      {
        // Sign counter changed, save it to NV
        VOID osal_snv_write( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter );
    
        return ( events ^ GAP_EVENT_SIGN_COUNTER_CHANGED );
      }
    
      if ( events & START_ADVERTISING_EVT )
      {
        if ( gapRole_AdvEnabled || gapRole_AdvNonConnEnabled )
        {
          gapAdvertisingParams_t params;
    
          // Setup advertisement parameters
          if ( gapRole_AdvNonConnEnabled )
          {
            // Only advertise non-connectable undirected.
            params.eventType = GAP_ADTYPE_ADV_NONCONN_IND;
          }
          else
          {
            params.eventType = gapRole_AdvEventType;
            params.initiatorAddrType = gapRole_AdvDirectType;
            VOID osal_memcpy( params.initiatorAddr, gapRole_AdvDirectAddr, B_ADDR_LEN );
          }
          params.channelMap = gapRole_AdvChanMap;
          params.filterPolicy = gapRole_AdvFilterPolicy;
    
          if ( GAP_MakeDiscoverable( gapRole_TaskID, &params ) != SUCCESS )
          {
            gapRole_state = GAPROLE_ERROR;
            
            // Notify the application with the new state change
            if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange )
            {
              pGapRoles_AppCGs->pfnStateChange( gapRole_state );
            }
          }
        }
        return ( events ^ START_ADVERTISING_EVT );
      }
    
      if ( events & RSSI_READ_EVT )
      {
        // Only get RSSI when in a connection
        if ( gapRole_state == GAPROLE_CONNECTED )
        {
          // Ask for RSSI
          VOID HCI_ReadRssiCmd( gapRole_ConnectionHandle );
    
          // Setup next event
          if ( gapRole_RSSIReadRate )
          {
            VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate );
          }
        }
        return ( events ^ RSSI_READ_EVT );
      }
    
      if ( events & START_CONN_UPDATE_EVT )
      {
        // Start connection update procedure
        gapRole_startConnUpdate( GAPROLE_NO_ACTION );
    
        return ( events ^ START_CONN_UPDATE_EVT );
      }
      
      if ( events & CONN_PARAM_TIMEOUT_EVT )
      {
        // Unsuccessful in updating connection parameters
        gapRole_HandleParamUpdateNoSuccess();
    
        return ( events ^ CONN_PARAM_TIMEOUT_EVT );
      }
      
      //catch a new event here that starts a scan 
      
      // Discard unknown events
      return 0;
    }
    
    /*********************************************************************
     * @fn      gapRole_ProcessOSALMsg
     *
     * @brief   Process an incoming task message.
     *
     * @param   pMsg - message to process
     *
     * @return  none
     */
    static void gapRole_ProcessOSALMsg( osal_event_hdr_t *pMsg )
    {
      switch ( pMsg->event )
      {
        case HCI_GAP_EVENT_EVENT:
          if ( pMsg->status == HCI_COMMAND_COMPLETE_EVENT_CODE )
          {
            hciEvt_CmdComplete_t *pPkt = (hciEvt_CmdComplete_t *)pMsg;
    
            if ( pPkt->cmdOpcode == HCI_READ_RSSI )
            {
              int8 rssi = (int8)pPkt->pReturnParam[3];
    
              if ( (gapRole_state == GAPROLE_CONNECTED) && (rssi != RSSI_NOT_AVAILABLE) )
              {
                // Report RSSI to app
                if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnRssiRead )
                {
                  pGapRoles_AppCGs->pfnRssiRead( rssi );
                }
              }
            }
          }
          break;
    
        case GATT_MSG_EVENT:
          // Process GATT event
          gapRole_ProcessGattEvent((gattMsgEvent_t *)pMsg);
          break;
                  
        case GAP_MSG_EVENT:
          gapRole_ProcessGAPMsg( (gapEventHdr_t *)pMsg );
          break;
    
        case L2CAP_SIGNAL_EVENT:
          {
            l2capSignalEvent_t *pPkt = (l2capSignalEvent_t *)pMsg;
    
            // Process the Parameter Update Response
            if ( pPkt->opcode == L2CAP_PARAM_UPDATE_RSP )
            {
              l2capParamUpdateRsp_t *pRsp = (l2capParamUpdateRsp_t *)&(pPkt->cmd.updateRsp);
                      
              if ( ( pRsp->result == L2CAP_CONN_PARAMS_REJECTED ) &&
                   ( paramUpdateNoSuccessOption == GAPROLE_TERMINATE_LINK ) )
              {
                // Cancel connection param update timeout timer
                VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT );
                          
                // Terminate connection immediately
                GAPRole_TerminateConnection();
              }
              else
              {
                uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT );
                
                // Let's wait for Controller to update connection parameters if they're
                // accepted. Otherwise, decide what to do based on no success option.
                VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout );
              }
            }
          }
          break;
    
        default:
          break;
      }
    }
    
    /*********************************************************************
     * @fn      gapRole_ProcessGattEvent
     *
     * @brief   Process an incoming GATT Event.
     *
     * @return  None.
     */
    static void gapRole_ProcessGattEvent(gattMsgEvent_t *pMsg)
    {
      switch (pMsg->method)
      {
        case ATT_FLOW_CTRL_VIOLATED_EVENT:
          // ATT request-response or indication-confirmation flow control is
          // violated. All subsequent ATT requests or indications will be dropped.
          // The profile is informed in case it wants to drop the connection.
          break;
          
        case ATT_MTU_UPDATED_EVENT:
          // MTU size updated
          break;
          
        default:
          break;
      }
    }
    
    /*********************************************************************
     * @fn      gapRole_ProcessGAPMsg
     *
     * @brief   Process an incoming task message.
     *
     * @param   pMsg - message to process
     *
     * @return  none
     */
    static void gapRole_ProcessGAPMsg( gapEventHdr_t *pMsg )
    {
      uint8 notify = FALSE;   // State changed notify the app? (default no)
      uint8 isObserverMsg = FALSE;
    
      
      periphtest = pMsg->opcode;
      
      event_count++;
      
      switch ( pMsg->opcode )
      {
        case GAP_DEVICE_INIT_DONE_EVENT:
          {
            gapDeviceInitDoneEvent_t *pPkt = (gapDeviceInitDoneEvent_t *)pMsg;
            bStatus_t stat = pPkt->hdr.status;
    
            if ( stat == SUCCESS )
            {
              // Save off the generated keys
              VOID osal_snv_write( BLE_NVID_IRK, KEYLEN, gapRole_IRK );
              VOID osal_snv_write( BLE_NVID_CSRK, KEYLEN, gapRole_SRK );
    
              // Save off the information
              VOID osal_memcpy( gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN );
    
              gapRole_state = GAPROLE_STARTED;
    
              // Update the advertising data
              stat = GAP_UpdateAdvertisingData( gapRole_TaskID,
                                  TRUE, gapRole_AdvertDataLen, gapRole_AdvertData );
            }
    
            if ( stat != SUCCESS )
            {
              gapRole_state = GAPROLE_ERROR;
            }
    
            notify = TRUE;
          }
          break;
    
        case GAP_ADV_DATA_UPDATE_DONE_EVENT:
          {
            gapAdvDataUpdateEvent_t *pPkt = (gapAdvDataUpdateEvent_t *)pMsg;
    
            if ( pPkt->hdr.status == SUCCESS )
            {
              if ( pPkt->adType )
              {
                // Setup the Response Data
                pPkt->hdr.status = GAP_UpdateAdvertisingData( gapRole_TaskID,
                                  FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData );
              }
              else if ( ( gapRole_state != GAPROLE_ADVERTISING )   &&
                        ( gapRole_state != GAPROLE_CONNECTED_ADV ) &&
                        ( osal_get_timeoutEx( gapRole_TaskID, START_ADVERTISING_EVT ) == 0 ) )
              {
                // Start advertising
                VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT );
              }
            }
    
            if ( pPkt->hdr.status != SUCCESS )
            {
              // Set into Error state
              gapRole_state = GAPROLE_ERROR;
              notify = TRUE;
            }
          }
          break;
    
        case GAP_MAKE_DISCOVERABLE_DONE_EVENT:
        case GAP_END_DISCOVERABLE_DONE_EVENT:
          {
            gapMakeDiscoverableRspEvent_t *pPkt = (gapMakeDiscoverableRspEvent_t *)pMsg;
    
            if ( pPkt->hdr.status == SUCCESS )
            {
              if ( pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT )
              {
                if (gapRole_state == GAPROLE_CONNECTED)
                {
                  gapRole_state = GAPROLE_CONNECTED_ADV;
                }
                else if (gapRole_AdvEnabled)
                {
                  gapRole_state = GAPROLE_ADVERTISING;
                }
                else
                {
                  gapRole_state = GAPROLE_ADVERTISING_NONCONN;
                }
              }
              else // GAP_END_DISCOVERABLE_DONE_EVENT
              {
                if (gapRole_AdvertOffTime != 0)
                {
                  if ( (gapRole_AdvEnabled) || (gapRole_AdvNonConnEnabled) )
                  {
                     VOID osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, gapRole_AdvertOffTime );
                  }
                }
                else
                {
                  // Since gapRole_AdvertOffTime is set to 0, the device should not
                  // automatically become discoverable again after a period of time.
                  // Set enabler to FALSE; device will become discoverable again when
                  // this value gets set to TRUE
                  if ( gapRole_AdvEnabled == TRUE )
                  {
                    gapRole_AdvEnabled = FALSE;
                  }
                  else
                  {
                    gapRole_AdvNonConnEnabled = FALSE;
                  }
                }
                
                // Update state.
                if ( gapRole_state == GAPROLE_CONNECTED_ADV )
                {
                  // In the Advertising Off period
                  gapRole_state = GAPROLE_CONNECTED;
                }
                else
                {
                  // In the Advertising Off period
                  gapRole_state = GAPROLE_WAITING;
                }
              }
            }
            else
            {
              gapRole_state = GAPROLE_ERROR;
            }
    
            notify = TRUE;
          }
          break;
    
        case GAP_LINK_ESTABLISHED_EVENT:
          {
            gapEstLinkReqEvent_t *pPkt = (gapEstLinkReqEvent_t *)pMsg;
    
            if ( pPkt->hdr.status == SUCCESS )
            {
              VOID osal_memcpy( gapRole_ConnectedDevAddr, pPkt->devAddr, B_ADDR_LEN );
              gapRole_ConnectionHandle = pPkt->connectionHandle;
              gapRole_state = GAPROLE_CONNECTED;
    
              if ( gapRole_RSSIReadRate )
              {
                // Start the RSSI Reads
                VOID osal_start_timerEx( gapRole_TaskID, RSSI_READ_EVT, gapRole_RSSIReadRate );
              }
    
              // Store connection information
              gapRole_ConnInterval = pPkt->connInterval;
              gapRole_ConnSlaveLatency = pPkt->connLatency;
              gapRole_ConnTimeout = pPkt->connTimeout;
    
              // Check whether update parameter request is enabled
              if ( gapRole_ParamUpdateEnable == TRUE )
              {
                // Get the minimum time upon connection establishment before the 
                // peripheral can start a connection update procedure.
                uint16 timeout = GAP_GetParamValue( TGAP_CONN_PAUSE_PERIPHERAL );
                
                osal_start_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT, timeout*1000 );
              }
    
              // Notify the Bond Manager to the connection
              VOID GAPBondMgr_LinkEst( pPkt->devAddrType, pPkt->devAddr, pPkt->connectionHandle, GAP_PROFILE_PERIPHERAL );
            }
            else if ( pPkt->hdr.status == bleGAPConnNotAcceptable )
            {
              // Set enabler to FALSE; device will become discoverable again when
              // this value gets set to TRUE
              gapRole_AdvEnabled = FALSE;
    
              // Go to WAITING state, and then start advertising
              gapRole_state = GAPROLE_WAITING;
            }
            else
            {
              gapRole_state = GAPROLE_ERROR;
            }
            notify = TRUE;
          }
          break;
    
        case GAP_LINK_TERMINATED_EVENT:
          {
            gapTerminateLinkEvent_t *pPkt = (gapTerminateLinkEvent_t *)pMsg;
    
            VOID GAPBondMgr_ProcessGAPMsg( (gapEventHdr_t *)pMsg );
            osal_memset( gapRole_ConnectedDevAddr, 0, B_ADDR_LEN );
    
            // Erase connection information
            gapRole_ConnInterval = 0;
            gapRole_ConnSlaveLatency = 0;
            gapRole_ConnTimeout = 0;
    
            // Cancel all connection parameter update timers (if any active)
            VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT );
            VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT );
    
            notify = TRUE;
            
            gapRole_ConnectionHandle = INVALID_CONNHANDLE;
            
            // If device was advertising when connection dropped
            if (gapRole_AdvNonConnEnabled)
            {
              // Continue advertising.
              gapRole_state = GAPROLE_ADVERTISING_NONCONN;
            }
            // Else go to WAITING state.
            else
            {
              if( pPkt->reason == LL_SUPERVISION_TIMEOUT_TERM )
              {
                gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT;
              }
              else
              {
                gapRole_state = GAPROLE_WAITING;
              }
              
              // Start advertising, if enabled.
              VOID osal_set_event( gapRole_TaskID, START_ADVERTISING_EVT );
            }
          }
          break;
    
        case GAP_LINK_PARAM_UPDATE_EVENT:
          {
            gapLinkUpdateEvent_t *pPkt = (gapLinkUpdateEvent_t *)pMsg;
    
            // Cancel connection param update timeout timer (if active)
            VOID osal_stop_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT );
            
            if ( pPkt->hdr.status == SUCCESS )
            {
              // Store new connection parameters
              gapRole_ConnInterval = pPkt->connInterval;
              gapRole_ConnSlaveLatency = pPkt->connLatency;
              gapRole_ConnTimeout = pPkt->connTimeout;
              
              // Make sure there's no pending connection update procedure
              if ( osal_get_timeoutEx( gapRole_TaskID, START_CONN_UPDATE_EVT ) == 0 )
              {
                // Notify the application with the new connection parameters
                if ( pGapRoles_ParamUpdateCB != NULL )
                {
                  (*pGapRoles_ParamUpdateCB)( gapRole_ConnInterval, 
                                              gapRole_ConnSlaveLatency, 
                                              gapRole_ConnTimeout );
                }
              }
            }
          }
          break;
          
       case GAP_DEVICE_DISCOVERY_EVENT:
           //JED start advertising again if we aren't connected to someone already 
    
          /* if(gapRole_state != GAPROLE_CONNECTED && gapRole_state != GAPROLE_CONNECTED_ADV)
            {
              periph_mode = osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, 1 ); //jed go now WAIT NOT 
            }*/
           break;
    
       case GAP_DEVICE_INFO_EVENT:
          {
            isObserverMsg = TRUE;
          } 
          break;
    
        default:
          break;
      }
    
      if ( notify == TRUE )
      {
        // Notify the application with the new state change
        if ( pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange )
        {
          pGapRoles_AppCGs->pfnStateChange( gapRole_state );
        }
      }
      else if ( isObserverMsg == TRUE )
      {
        if (pGapRoles_AppCGs && pGapRoles_AppCGs->observerCB )
        {
          pGapRoles_AppCGs->observerCB( (observerRoleEvent_t *) pMsg );
        }
      }
      
      
    }
    
    /*********************************************************************
     * @fn      gapRole_SetupGAP
     *
     * @brief   Call the GAP Device Initialization function using the
     *          Profile Parameters.
     *
     * @param   none
     *
     * @return  none
     */
    static void gapRole_SetupGAP( void )
    {
      VOID GAP_DeviceInit( gapRole_TaskID,
              gapRole_profileRole, gapObserverRoleMaxScanRes,
              gapRole_IRK, gapRole_SRK,
              &gapRole_signCounter );
    }
    
    /*********************************************************************
     * @fn      gapRole_HandleParamUpdateNoSuccess
     *
     * @brief   Handle unsuccessful connection parameters update.
     *
     * @param   none
     *
     * @return  none
     */
    static void gapRole_HandleParamUpdateNoSuccess( void )
    {
      // See which option was choosen for unsuccessful updates
      switch ( paramUpdateNoSuccessOption )
      {
        case GAPROLE_RESEND_PARAM_UPDATE:
          GAPRole_SendUpdateParam( gapRole_MinConnInterval, gapRole_MaxConnInterval,
                                   gapRole_SlaveLatency, gapRole_TimeoutMultiplier,
                                   GAPROLE_RESEND_PARAM_UPDATE );
          break;
    
        case GAPROLE_TERMINATE_LINK:
          GAPRole_TerminateConnection();
          break;
    
        case GAPROLE_NO_ACTION:
          // fall through
        default:
          //do nothing
          break;
      }
    }
    
    /********************************************************************
     * @fn          gapRole_startConnUpdate
     *
     * @brief       Start the connection update procedure
     *
     * @param       handleFailure - what to do if the update does not occur.
     *              Method may choose to terminate connection, try again, or take no action
     *
     * @return      none
     */
    static void gapRole_startConnUpdate( uint8 handleFailure )
    {
      // First check the current connection parameters versus the configured parameters
      if ( (gapRole_ConnInterval < gapRole_MinConnInterval)   ||
           (gapRole_ConnInterval > gapRole_MaxConnInterval)   ||
           (gapRole_ConnSlaveLatency != gapRole_SlaveLatency) ||
           (gapRole_ConnTimeout  != gapRole_TimeoutMultiplier) )
      {
        gapUpdateLinkParamReq_t linkParams;
        uint16 timeout = GAP_GetParamValue( TGAP_CONN_PARAM_TIMEOUT );
    
        linkParams.connectionHandle = gapRole_ConnectionHandle;
        linkParams.intervalMin = gapRole_MinConnInterval;
        linkParams.intervalMax = gapRole_MaxConnInterval;
        linkParams.connLatency = gapRole_SlaveLatency;
        linkParams.connTimeout = gapRole_TimeoutMultiplier;
                
        VOID GAP_UpdateLinkParamReq( &linkParams );
            
        paramUpdateNoSuccessOption = handleFailure;
            
        // Let's wait either for L2CAP Connection Parameters Update Response or
        // for Controller to update connection parameters
        VOID osal_start_timerEx( gapRole_TaskID, CONN_PARAM_TIMEOUT_EVT, timeout );
      }
    }
    
    /********************************************************************
     * @fn          GAPRole_SendUpdateParam
     *
     * @brief       Update the parameters of an existing connection
     *
     * @param       minConnInterval - the new min connection interval
     * @param       maxConnInterval - the new max connection interval
     * @param       latency - the new slave latency
     * @param       connTimeout - the new timeout value
     * @param       handleFailure - what to do if the update does not occur.
     *              Method may choose to terminate connection, try again, or take no action
     *
     * @return      SUCCESS, bleNotConnected, or bleInvalidRange
     */
    bStatus_t GAPRole_SendUpdateParam( uint16 minConnInterval, uint16 maxConnInterval,
                                       uint16 latency, uint16 connTimeout, uint8 handleFailure )
    {    
      // If there is no existing connection no update need be sent
      if ( gapRole_state != GAPROLE_CONNECTED )
      {
        return ( bleNotConnected );
      }
      
      // Check that all parameters are in range before sending request
      if ( ( minConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) &&
           ( minConnInterval < DEFAULT_MAX_CONN_INTERVAL  ) &&
           ( maxConnInterval >= DEFAULT_MIN_CONN_INTERVAL ) &&
           ( maxConnInterval < DEFAULT_MAX_CONN_INTERVAL  ) &&
           ( latency         < MAX_SLAVE_LATENCY          ) &&
           ( connTimeout     >= MIN_TIMEOUT_MULTIPLIER    ) &&
           ( connTimeout     < MAX_TIMEOUT_MULTIPLIER     ) )
      {
        gapRole_MinConnInterval = minConnInterval;
        gapRole_MaxConnInterval = maxConnInterval;
        gapRole_SlaveLatency = latency;
        gapRole_TimeoutMultiplier = connTimeout;
    
        // Start connection update procedure
        gapRole_startConnUpdate( handleFailure );
    
        // Connection update requested by app, cancel such pending procedure (if active)
        VOID osal_stop_timerEx( gapRole_TaskID, START_CONN_UPDATE_EVT );
                  
        return ( SUCCESS );
      }
    
      return ( bleInvalidRange );
    }
    
    /*********************************************************************
    *********************************************************************/
    
    
    
    /**
     * @brief   Start a device discovery scan.
     *
     * Public function defined in observer.h.
     */
    bStatus_t GAPObserverRole_StartDiscovery( uint8 mode, uint8 activeScan, uint8 whiteList )
    {
      gapDevDiscReq_t params;
    
      params.taskID = gapRole_TaskID;
      params.mode = mode;
      params.activeScan = activeScan;
      params.whiteList = whiteList;
    
      return GAP_DeviceDiscoveryRequest( &params );
    }
    bStatus_t GAPObserverRole_CancelDiscovery(void)
    {
      return GAP_DeviceDiscoveryCancel(gapRole_TaskID);
    }
    
    void Peripheral_Update(void)
    {
      /* Increment the elapse counter */
        TPMS_1MinElapseCntr_u8++;
        if (TPMS_1MinElapseCntr_u8 > C_PERIPHERAL_TASK_1MIN_SCALE_COUNT)
        {
           if(gapRole_state != GAPROLE_CONNECTED && gapRole_state != GAPROLE_CONNECTED_ADV)
          {
            periph_mode = osal_start_timerEx( gapRole_TaskID, START_ADVERTISING_EVT, 1 ); //jed go now WAIT NOT 
          }
           TPMS_1MinElapseCntr_u8 = 0U;
        }
    }

    Here in the code, when I disable observer part (gapRole_profileRole = GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER;), it works well for the connection and point here to be noted is that I didint include start scan discovery at all. 

    Could you please be kind to look into it?

    Best,

    Varun

  • Hi Varun,

    So far, I haven't spotted any issue in the file you have shared.

    Your observation related to set gapRole_profileRole to GAP_PROFILE_PERIPHERAL (instead of GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER) is interesting. Actually, this allows to save at least 120 bytes of memory. I think it could be enough to trigger or not an issue with bonding.

    - Could you please evaluate the amount of free RAM you have?

    - Could you please verify if setting gapRole_profileRole to GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER and reduce gapObserverRoleMaxScanRes to 1 could allow bonding to work properly?

    Best regards,

  • Hi Clement,

    I am so sorry. DOn't know how i missed the notification. Yes, I have already tested with reducing gapObserverRoleMaxScanRes. But it didnt work. 

    My memmory statistics looks like below:

     132 312 bytes of CODE memory (+ 14 872 range fill )
    35 bytes of DATA memory (+ 80 absolute )
    7 859 bytes of XDATA memory
    179 bytes of IDATA memory (+ 1 absolute )
    8 bits of BIT memory
    900 bytes of CONST memory

    Basically when I did switched the role from GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER to GAP_PROFILE_PERIPHERAL, I still used the same library file and hence the memory consumption was same I believe. May be it is something to do with the multi role configuration?

    I am attaching a video recording of connection issue here.

    Also when it connects you can see it doesnot remember the bonding, even  i chec in the bond register and I se the phone's  bluetooth id is still stored in the register,

    Best,

    Varun

  • Hi Clement,

    I am so sorry. DOn't know how i missed the notification. Yes, I have already tested with reducing gapObserverRoleMaxScanRes. But it didnt work. 

    My memmory statistics looks like below:

     132 312 bytes of CODE memory (+ 14 872 range fill )
    35 bytes of DATA memory (+ 80 absolute )
    7 859 bytes of XDATA memory
    179 bytes of IDATA memory (+ 1 absolute )
    8 bits of BIT memory
    900 bytes of CONST memory

    Basically when I did switched the role from GAP_PROFILE_PERIPHERAL|GAP_PROFILE_OBSERVER to GAP_PROFILE_PERIPHERAL, I still used the same library file and hence the memory consumption was same I believe. May be it is something to do with the multi role configuration?

    I am attaching a video recording of connection issue here.

    Also when it connects you can see it doesnot remember the bonding, even  i chec in the bond register and I se the phone's  bluetooth id is still stored in the register,

    Best,

    Varun

  • Hi Clement,

    I have an interesting observation. I disabled all the services and saved around 1000 bytes of ram and now there is no connection or bonding problem... What workaround would you suggest?  So how can I analyze this further? Is there a way to understand the heap memory usage? As you can see in the video, we are using split platform it makes it difficult to use the debugger. Is there a way to monitor heap usage by reading any variable or APIs? For 8k ram, what shall be the free memory(minimum) we shall allocate. 

    Best,

    Varun

  • Hi Varun,

    It looks like the root cause of the issue is now identified - well done.

    I would recommend to look into https://www.ti.com/lit/swru271 (especially §3.4 heap manager) to debug this issue.

    For additional support related to RAM / heap, please open a new thread.

    Best regards,