Adverting is started, stopped and started ... over and over

Hi,

My advertising initial is as follow.

  manuf_specific_data.data.p_data = (uint8_t *) m_beacon_info;
  manuf_specific_data.data.size   = APP_BEACON_INFO_LENGTH;

  // Build and set advertising data.
  memset(&advdata, 0, sizeof(advdata));

  advdata.name_type     = BLE_ADVDATA_NO_NAME;
  advdata.flags   = flags;
  advdata.p_manuf_specific_data = &manuf_specific_data;

  // Initialize advertising parameters (used when starting advertising).
  memset(&m_adv_params, 0, sizeof(m_adv_params));

  m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED;
  m_adv_params.p_peer_addr   = NULL;  // Undirected advertisement.
  m_adv_params.filter_policy   = BLE_GAP_ADV_FP_ANY;
  m_adv_params.interval  = NON_CONNECTABLE_ADV_INTERVAL;
  m_adv_params.duration  = 0;     // Never time out.

  err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len);
  APP_ERROR_CHECK(err_code);

  err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params);

But, 10~11 packet are sent and stop.
After 7~8 sec. resent advertisement packet again.... and 10~10 packet send, 7~8 sec stop...

What is the problem?

BR
Paul

Parents
  • Hi Paul,

    I do not see anything here that should cause advertising to stop. Can you share all your advertising related code, or perhaps the whole application?

    Einar

  • Hi,

    I attached full source file here.

    /**
     * Copyright (c) 2014 - 2021, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *  list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *  Semiconductor ASA integrated circuit in a product or a software update for
     *  such product, must reproduce the above copyright notice, this list of
     *  conditions and the following disclaimer in the documentation and/or other
     *  materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *  contributors may be used to endorse or promote products derived from this
     *  software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *  Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *  engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    /** @file
     *
     * @defgroup ble_sdk_app_beacon_main main.c
     * @{
     * @ingroup ble_sdk_app_beacon
     * @brief Beacon Transmitter Sample Application main file.
     *
     * This file contains the source code for an Beacon transmitter sample application.
     */
    
    #include <stdbool.h>
    #include <stdint.h>
    #include <stdarg.h>
    
    #include "nordic_common.h"
    #include "nrf.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_soc.h"
    #include "nrf_sdh_ble.h"
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    #include "nrf_log_internal.h"
    #include "nrf_ble_qwr.h"
    #include "nrf_gpio.h"
    #include "nrf_gpiote.h"
    #include "nrf_pwr_mgmt.h"
    #include "nrf_delay.h"
    #include "nrf_drv_gpiote.h"
    #include "nrf_drv_saadc.h"
    #include "nrf_drv_twi.h"
    #include "nrfx_twi.h"
    #include "ble_hci.h"
    #include "ble_gap.h"
    #include "ble_advdata.h"
    #include "ble_advertising.h"
    #include "ble_conn_params.h"
    #include "bsp_btn_ble.h"
    #include "boards.h"
    #include "app_timer.h"
    #include "app_uart.h"
    #include "app_util_platform.h"
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "def.h"
    #include "decl.h"
    
    
    #define APP_BLE_CONN_CFG_TAG    1      /**< A tag identifying the SoftDevice BLE configuration. */
    
    #define NON_CONNECTABLE_ADV_INTERVAL  MSEC_TO_UNITS(500, UNIT_0_625_MS)  /**< The advertising interval for non-connectable advertisement (100 ms). This value can vary between 100ms to 10.24s). */
    
    #define APP_BEACON_INFO_LENGTH  0x17       /**< Total length of information advertised by the Beacon. */
    #define APP_ADV_DATA_LENGTH     0x15       /**< Length of manufacturer specific data in the advertisement. */
    #define APP_DEVICE_TYPE         0x02       /**< 0x02 refers to Beacon. */
    #define APP_MEASURED_RSSI       0xC3       /**< The Beacon's measured RSSI at 1 meter distance in dBm. */
    #define APP_COMPANY_IDENTIFIER  0x0059       /**< Company identifier for Nordic Semiconductor ASA. as per www.bluetooth.org. */
    #define APP_MAJOR_VALUE   0x01, 0x02     /**< Major value used to identify Beacons. */
    #define APP_MINOR_VALUE   0x03, 0x04     /**< Minor value used to identify Beacons. */
    #define APP_BEACON_UUID   0x4b, 0x33, 0xc0, 0xbf, \
                              0x54, 0x13, 0x00, 0x02, \
                              0x00, 0x11, 0x22, 0x33, \
                              0x44, 0x55, 0x66, 0x77    /**< Proprietary UUID for Beacon. */
    
    #define DEAD_BEEF         0xDEADBEEF     /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
    
    #if defined(USE_UICR_FOR_MAJ_MIN_VALUES)
    #define MAJ_VAL_OFFSET_IN_BEACON_INFO   18     /**< Position of the MSB of the Major Value in m_beacon_info array. */
    #define UICR_ADDRESS      0x10001080     /**< Address of the UICR register used by this example. The major and minor versions to be encoded into the advertising data will be picked up from this location. */
    #endif
    
    static ble_gap_adv_params_t m_adv_params;      /**< Parameters to be passed to the stack when starting advertising. */
    static uint8_t    m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET; /**< Advertising handle used to identify an advertising set. */
    static uint8_t    m_enc_advdata[BLE_GAP_ADV_SET_DATA_SIZE_MAX];  /**< Buffer for storing an encoded advertising set. */
    
    /**@brief Struct that contains pointers to the encoded advertising data. */
    static ble_gap_adv_data_t m_adv_data =
    {
      .adv_data =
      {
      .p_data = m_enc_advdata,
      .len  = BLE_GAP_ADV_SET_DATA_SIZE_MAX
      },
      .scan_rsp_data =
      {
      .p_data = NULL,
      .len  = 0
    
      }
    };
    
    APP_TIMER_DEF(m_app_timer_id);
    APP_TIMER_DEF(m_led_off_timer_id);
    
    int hostConnected = 0;
    int moduleId = TAG_MODULE;
    static int idle_cnt = IDLE_CNT;
    
    static uint8_t m_beacon_info[APP_BEACON_INFO_LENGTH] =    /**< Information advertised by the Beacon. */
    {
      APP_DEVICE_TYPE,   // Manufacturer specific information. Specifies the device type in this
         // implementation.
      APP_ADV_DATA_LENGTH, // Manufacturer specific information. Specifies the length of the
         // manufacturer specific data in this implementation.
      APP_BEACON_UUID,   // 128 bit UUID value.
      APP_MAJOR_VALUE,   // Major arbitrary value that can be used to distinguish between Beacons.
      APP_MINOR_VALUE,   // Minor arbitrary value that can be used to distinguish between Beacons.
      APP_MEASURED_RSSI  // Manufacturer specific information. The Beacon's measured TX power in
         // this implementation.
    };
    
    
    /**@brief Callback function for asserts in the SoftDevice.
     *
     * @details This function will be called in case of an assert in the SoftDevice.
     *
     * @warning This handler is an example only and does not fit a final product. You need to analyze
     *  how your product is supposed to react in case of Assert.
     * @warning On assert from the SoftDevice, the system can only recover on reset.
     *
     * @param[in]   line_num   Line number of the failing ASSERT call.
     * @param[in]   file_name  File name of the failing ASSERT call.
     */
    void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
    {
      app_error_handler(DEAD_BEEF, line_num, p_file_name);
    }
    
    /**@brief Function for initializing the Advertising functionality.
     *
     * @details Encodes the required advertising data and passes it to the stack.
     *  Also builds a structure to be passed to the stack when starting advertising.
     */
    static void advertising_init(void)
    {
      uint32_t    err_code;
      ble_advdata_t advdata;
      uint8_t     flags = BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
    
      ble_advdata_manuf_data_t manuf_specific_data;
    
      manuf_specific_data.company_identifier = APP_COMPANY_IDENTIFIER;
    
    #if defined(USE_UICR_FOR_MAJ_MIN_VALUES)
      // If USE_UICR_FOR_MAJ_MIN_VALUES is defined, the major and minor values will be read from the
      // UICR instead of using the default values. The major and minor values obtained from the UICR
      // are encoded into advertising data in big endian order (MSB First).
      // To set the UICR used by this example to a desired value, write to the address 0x10001080
      // using the nrfjprog tool. The command to be used is as follows.
      // nrfjprog --snr <Segger-chip-Serial-Number> --memwr 0x10001080 --val <your major/minor value>
      // For example, for a major value and minor value of 0xabcd and 0x0102 respectively, the
      // the following command should be used.
      // nrfjprog --snr <Segger-chip-Serial-Number> --memwr 0x10001080 --val 0xabcd0102
      uint16_t major_value = ((*(uint32_t *)UICR_ADDRESS) & 0xFFFF0000) >> 16;
      uint16_t minor_value = ((*(uint32_t *)UICR_ADDRESS) & 0x0000FFFF);
    
      uint8_t index = MAJ_VAL_OFFSET_IN_BEACON_INFO;
    
      m_beacon_info[index++] = MSB_16(major_value);
      m_beacon_info[index++] = LSB_16(major_value);
    
      m_beacon_info[index++] = MSB_16(minor_value);
      m_beacon_info[index++] = LSB_16(minor_value);
    #endif
    
      manuf_specific_data.data.p_data = (uint8_t *) m_beacon_info;
      manuf_specific_data.data.size   = APP_BEACON_INFO_LENGTH;
    
      // Build and set advertising data.
      memset(&advdata, 0, sizeof(advdata));
    
      advdata.name_type     = BLE_ADVDATA_NO_NAME;
      advdata.flags   = flags;
      advdata.p_manuf_specific_data = &manuf_specific_data;
    
      // Initialize advertising parameters (used when starting advertising).
      memset(&m_adv_params, 0, sizeof(m_adv_params));
    
      m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED;
      m_adv_params.p_peer_addr   = NULL;  // Undirected advertisement.
      m_adv_params.filter_policy   = BLE_GAP_ADV_FP_ANY;
      m_adv_params.interval  = NON_CONNECTABLE_ADV_INTERVAL;
      m_adv_params.duration  = 0;     // Never time out.
    
      err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len);
      APP_ERROR_CHECK(err_code);
    
      err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params);
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for starting advertising.
     */
    static void advertising_start(void)
    {
      ret_code_t err_code;
    
      err_code = sd_ble_gap_adv_start(m_adv_handle, APP_BLE_CONN_CFG_TAG);
      APP_ERROR_CHECK(err_code);
    
      err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupt.
     */
    static void ble_stack_init(void)
    {
      ret_code_t err_code;
    
      err_code = nrf_sdh_enable_request();
      APP_ERROR_CHECK(err_code);
    
      // Configure the BLE stack using the default settings.
      // Fetch the start address of the application RAM.
      uint32_t ram_start = 0;
      err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
      APP_ERROR_CHECK(err_code);
    
      // Enable BLE stack.
      err_code = nrf_sdh_ble_enable(&ram_start);
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing logging. */
    static void log_init(void)
    {
      return;
      ret_code_t err_code = NRF_LOG_INIT(NULL);
      APP_ERROR_CHECK(err_code);
    
      NRF_LOG_DEFAULT_BACKENDS_INIT();
    }
    
    /**@brief Function for initializing LEDs. */
    static void leds_init(void)
    {
      return;
      ret_code_t err_code = bsp_init(BSP_INIT_LEDS, NULL);
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing timers. */
    static void timers_init(void)
    {
      ret_code_t err_code = app_timer_init();
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing power management.
     */
    static void power_management_init(void)
    {
      ret_code_t err_code;
      err_code = nrf_pwr_mgmt_init();
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling the idle state (main loop).
     *
     * @details If there is no pending log operation, then sleep until next the next event occurs.
     */
    static void idle_state_handle(void)
    {
      if (NRF_LOG_PROCESS() == false)
      {
      nrf_pwr_mgmt_run();
      }
    }
    
    /**@brief   Function for handling app_uart events.
     *
     * @details This function receives a single character from the app_uart module and appends it to
     *  a string. The string is sent over BLE when the last character received is a
     *  'new line' '\n' (hex 0x0A) or if the string reaches the maximum data length.
     */
    static uint8_t uart_data_ring_buf[UART_MAX_DATA_LEN];
    static uint16_t wr_ptr = 0, rd_ptr = 0;
    
    void uart_event_handle(app_uart_evt_t * p_event)
    {
      return;
    
      switch (p_event->evt_type)
        {
        /**@snippet [Handling data from UART] */
        case APP_UART_DATA_READY:
          {
          uint8_t ch;
          UNUSED_VARIABLE(app_uart_get(&ch));
          //app_uart_put (ch);
          uart_data_ring_buf[wr_ptr ++] = ch;
          if (wr_ptr == UART_MAX_DATA_LEN)
            {
             wr_ptr = 0; 
            }
          }
          break;
    
        /**@snippet [Handling data from UART] */
        case APP_UART_COMMUNICATION_ERROR:
          NRF_LOG_ERROR("Communication error occurred while handling UART.");
          APP_ERROR_HANDLER(p_event->data.error_communication);
          break;
    
        case APP_UART_FIFO_ERROR:
          NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
          APP_ERROR_HANDLER(p_event->data.error_code);
          break;
    
        default:
          break;
        }
    }
    
    void
    uart_rx_handler (void)
    {
      uint8_t ch;
      if (wr_ptr != rd_ptr)
        {
        ch = uart_data_ring_buf [rd_ptr ++]; 
        DBG ("%c", ch);
        if (rd_ptr == UART_MAX_DATA_LEN)
          {
           rd_ptr = 0; 
          }
        }
    }
    
    /**@brief Function for initializing the UART. */
    static void uart_init(void)
    {
      ret_code_t err_code;
    
      app_uart_comm_params_t const comm_params =
      {
      .rx_pin_no  = DBG_UART_RX_PIN,
      .tx_pin_no  = DBG_UART_TX_PIN,
      .rts_pin_no   = 0,
      .cts_pin_no   = 0,
      .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
      .use_parity   = false,
      .baud_rate  = UART_BAUDRATE_BAUDRATE_Baud115200
      };
    
      APP_UART_FIFO_INIT(&comm_params,
           UART_RX_BUF_SIZE,
           UART_TX_BUF_SIZE,
           uart_event_handle,
           APP_IRQ_PRIORITY_LOWEST,
           err_code);
    
      APP_ERROR_CHECK(err_code);
    }
    
    static void 
    app_timer_event_handler (void * p_context)
    {
      nrf_gpio_pin_clear (OP_LED_1_PIN);
    
      app_timer_start(m_app_timer_id, APP_TIMER_TICKS(APP_TIMER_INTERVAL), NULL);
      app_timer_start(m_led_off_timer_id, APP_TIMER_TICKS(1), NULL);
    }
    
    static void 
    led_off_timer_event_handler (void * p_context)
    {
      nrf_gpio_pin_set (OP_LED_1_PIN);
    }
    
    static 
    void lis2dw_int_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
    {
      idle_cnt = IDLE_CNT;
    }
    
    static void
    lis2dw_interrupt_port_ini (void)
    {
      ret_code_t err_code;
    
      err_code = nrf_drv_gpiote_init();
      APP_ERROR_CHECK(err_code);
    
      // This is because the IN event requires the HF clock to be running, i.e. adding about 250uA.
      // The PORT event on the other hand does not require the HF clock to be running and
      // is therefore better suited for low power applications. 
      nrf_drv_gpiote_in_config_t in_config = GPIOTE_CONFIG_IN_SENSE_HITOLO(false);  // port interrupt, not IN_Event
      in_config.pull = NRF_GPIO_PIN_PULLDOWN;
    
      err_code = nrf_drv_gpiote_in_init(LIS2DW_INT1_PIN, &in_config, lis2dw_int_handler);
      APP_ERROR_CHECK(err_code);
    
      nrf_drv_gpiote_in_event_enable(LIS2DW_INT1_PIN, true);
    }
    
    /**@brief Function for initializing buttons and leds. */
    static void 
    port_init(void)
    {
      nrf_gpio_cfg_input(MODULE_ID_PIN, NRF_GPIO_PIN_NOPULL );
      moduleId = nrf_gpio_pin_read (MODULE_ID_PIN);
    
      nrf_gpio_cfg_output(OP_LED_1_PIN);
      nrf_gpio_cfg_output(OP_LED_2_PIN);
    
      nrf_gpio_pin_clear (OP_LED_1_PIN);
      nrf_gpio_pin_clear (OP_LED_2_PIN);
    }
    
    void 
    tx_power_set (int tx_power)
    {
      sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_ADV, m_adv_handle, tx_power);
    }
    
    /**
     * @brief Function for application main entry.
     */
    int main(void)
    {
      // Initialize.
      log_init();
      port_init();
      uart_init ();
    
      timers_init();
      leds_init();
      power_management_init();
      ble_stack_init();
      advertising_init();
    
      sd_power_dcdc_mode_set (NRF_POWER_DCDC_ENABLE);
    
      app_timer_create(&m_app_timer_id, APP_TIMER_MODE_SINGLE_SHOT, app_timer_event_handler);  
      app_timer_start(m_app_timer_id, APP_TIMER_TICKS(1), NULL);
    
      app_timer_create(&m_led_off_timer_id, APP_TIMER_MODE_SINGLE_SHOT, led_off_timer_event_handler);  
    
      // Start execution.
      NRF_LOG_INFO("Beacon example started.");
      DBG ("Start AIoT Tag\n");
      DBG ("Advertising started !!\n");
    
      advertising_start();
    
      tx_power_set (0);
      DBG ("Power is set to 0\n");
    
      if (0)
        {
        lis2dw_init ();
    
        // LFCLK on for power saving
        NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
        NRF_CLOCK->TASKS_LFCLKSTART = 1;
        while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0);
    
        lis2dw_interrupt_port_ini ();
        }
      // Enter main loop.
      for (;; )
        {
        idle_state_handle();
        uart_rx_handler ();
        }
    }
    
    
    /**
     * @}
     */

  • I remove all uart part and did test, but same result.

  • Hi,

    I do not see anything in your code that explains the described behavior where the device sends a short burst of advertising packets, then pausing for some seconds before sending a burst again.

    Have you checked (for instance by enabling logging) to see if the device resets and that is how advertising is re-started? If not, can you check? Also, what else have you learned by debugging?

    If you don't make progress, perhaps you can make a project that reproduce this on a DK so that I can test on mye end?

  • Hi,

    I'm testing on nrf52840 DK board, not custom board.
    I insert the LED blink test part in next of port_init(); call as follow.

      for (int i = 0; i < 5; i ++)
        {
        nrf_gpio_pin_toggle (OP_LED_1_PIN);
        nrf_delay_ms (100);
        }
      nrf_gpio_pin_clear (OP_LED_1_PIN);
    


    After starting the DK board, I found only once executed this. so, It looks no reset is occurred during running.

    I am testing on s140_nrf52_7.2.0_softdevice.hex.

  • I have change 

    #define NON_CONNECTABLE_ADV_INTERVAL  MSEC_TO_UNITS(500, UNIT_0_625_MS) to
    #define NON_CONNECTABLE_ADV_INTERVAL  MSEC_TO_UNITS(50, UNIT_0_625_MS)
    500 to 50

    then, no stop...

    But I want  every 1 sec period advertisement for battery saving.
  • Hi,
    My test seems wrong.

    Test config is as follows.
    My custom H/W using 52840 is used for scanner to be receiving adv packets nearby.
    And 52840 DK is for generating adv packet, interval is 1 sec.

    I made scan f/w to receive all advertisement packet.
    And I though it was working well.
    Because, other adv packet nearby are received during my 52840 DK adv packet is not received.

    But, I installed wireshark plugin and did monitor. I found 52480 DK is sending adv packet every 1 sec well.

    So, I think my scanner F/W has something wrong.
    I have to check my scanner F/W first.

    It is possible to not receive specific packet? 

    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
    {
      ret_code_t      err_code;
      ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
    
      switch (p_ble_evt->header.evt_id)
      {
        case BLE_GAP_EVT_ADV_REPORT:
          {
          int i;
          // pass all beacon
          if (tag_prefix[0] == 0xff && tag_prefix[1] == 0xff && tag_prefix[2] == 0xff &&
              tag_prefix[3] == 0xff && tag_prefix[4] == 0xff && tag_prefix[5] == 0xff)
            {
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (17);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 16; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 9]);
              }
            }
          else
            {
            // compare prefix, if not match, then drop
            if (memcmp (&m_scan.scan_buffer.p_data[9], tag_prefix, 6) != 0)
              {
              // not my tag
              break;
              }
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (11);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 10; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 15]);
              }
            }
    
          nrf_gpio_pin_toggle (OP_LED_1_PIN);
          }
          break;
    
        case BLE_GAP_EVT_CONNECTED:
          break;
    
        case BLE_GAP_EVT_DISCONNECTED:
    
          NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
                 p_gap_evt->conn_handle,
                 p_gap_evt->params.disconnected.reason);
          break;
    
        case BLE_GAP_EVT_TIMEOUT:
          if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
          {
            NRF_LOG_INFO("Connection Request timed out.");
          }
          break;
    
        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
          // Pairing not supported.
          err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
          // Accepting parameters requested by peer.
          err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                              &p_gap_evt->params.conn_param_update_request.conn_params);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
          NRF_LOG_DEBUG("PHY update request.");
          ble_gap_phys_t const phys =
          {
            .rx_phys = BLE_GAP_PHY_AUTO,
            .tx_phys = BLE_GAP_PHY_AUTO,
          };
          err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
          APP_ERROR_CHECK(err_code);
        } break;
    
        case BLE_GATTC_EVT_TIMEOUT:
          // Disconnect on GATT Client timeout event.
          NRF_LOG_DEBUG("GATT Client Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GATTS_EVT_TIMEOUT:
          // Disconnect on GATT Server timeout event.
          NRF_LOG_DEBUG("GATT Server Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        default:
          break;
      }
    }
    

    Change to scanner issue :(

    BR
    Paul

Reply
  • Hi,
    My test seems wrong.

    Test config is as follows.
    My custom H/W using 52840 is used for scanner to be receiving adv packets nearby.
    And 52840 DK is for generating adv packet, interval is 1 sec.

    I made scan f/w to receive all advertisement packet.
    And I though it was working well.
    Because, other adv packet nearby are received during my 52840 DK adv packet is not received.

    But, I installed wireshark plugin and did monitor. I found 52480 DK is sending adv packet every 1 sec well.

    So, I think my scanner F/W has something wrong.
    I have to check my scanner F/W first.

    It is possible to not receive specific packet? 

    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
    {
      ret_code_t      err_code;
      ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
    
      switch (p_ble_evt->header.evt_id)
      {
        case BLE_GAP_EVT_ADV_REPORT:
          {
          int i;
          // pass all beacon
          if (tag_prefix[0] == 0xff && tag_prefix[1] == 0xff && tag_prefix[2] == 0xff &&
              tag_prefix[3] == 0xff && tag_prefix[4] == 0xff && tag_prefix[5] == 0xff)
            {
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (17);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 16; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 9]);
              }
            }
          else
            {
            // compare prefix, if not match, then drop
            if (memcmp (&m_scan.scan_buffer.p_data[9], tag_prefix, 6) != 0)
              {
              // not my tag
              break;
              }
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (11);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 10; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 15]);
              }
            }
    
          nrf_gpio_pin_toggle (OP_LED_1_PIN);
          }
          break;
    
        case BLE_GAP_EVT_CONNECTED:
          break;
    
        case BLE_GAP_EVT_DISCONNECTED:
    
          NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
                 p_gap_evt->conn_handle,
                 p_gap_evt->params.disconnected.reason);
          break;
    
        case BLE_GAP_EVT_TIMEOUT:
          if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
          {
            NRF_LOG_INFO("Connection Request timed out.");
          }
          break;
    
        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
          // Pairing not supported.
          err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
          // Accepting parameters requested by peer.
          err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                              &p_gap_evt->params.conn_param_update_request.conn_params);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
          NRF_LOG_DEBUG("PHY update request.");
          ble_gap_phys_t const phys =
          {
            .rx_phys = BLE_GAP_PHY_AUTO,
            .tx_phys = BLE_GAP_PHY_AUTO,
          };
          err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
          APP_ERROR_CHECK(err_code);
        } break;
    
        case BLE_GATTC_EVT_TIMEOUT:
          // Disconnect on GATT Client timeout event.
          NRF_LOG_DEBUG("GATT Client Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GATTS_EVT_TIMEOUT:
          // Disconnect on GATT Server timeout event.
          NRF_LOG_DEBUG("GATT Server Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        default:
          break;
      }
    }
    

    Change to scanner issue :(

    BR
    Paul

Children
  • Hi Paul,

    I assume the only relevant event from your event handler here is BLE_GAP_EVT_ADV_REPORT? I cannot say if the way you filter makes sense, but this part of the code should always work as far as  I can see, so any received advertising packet that match your filters will be (partially) printed on UART.

    A few potential problems:

    • Too much/fast printing over UART (if the UART itself is the bottleneck), causing lost data there.
    • Some issue with the scanner itself, do you stop and restart scanning at some point (deliberately or not)? Or do you experience resets or other unexpected behaviours?

    Adding some logging if you have not done so could help in seeing what happens on your application. I may also need to see more of your code in order to comment further.

  • Hi,
    Yes, I deal only BLE_GAP_EVT_ADV_REPORT event.
    I change uart FIFO size to 1024, but same result.

    Specific adv packet is generated very long interval(1 sec). so, bottleneck seems not problem.
    Only one 52840 DK for sending adv packet is used for test.

    If experience reset, I can aware. but no reset is occurred.

    I add m_scan_param variable,

    #define SCAN_INTERVAL               0x0320                              /**< Determines scan interval in units of 0.625 millisecond. */
    #define SCAN_WINDOW                 0x0320                              /**< Determines scan window in units of 0.625 millisecond. */
    #define SCAN_DURATION           	0x0000                              /**< Duration of the scanning in units of 10 milliseconds. If set to 0x0000, scanning continues until it is explicitly disabled. */
    
    
    static ble_gap_scan_params_t m_scan_param =                 /**< Scan parameters requested for scanning and connection. */
    {
        .active        = 0x00,
        .interval      = SCAN_INTERVAL,
        .window        = SCAN_WINDOW,
        .filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL,
        .timeout       = SCAN_DURATION,
    //    .scan_phys     = BLE_GAP_PHY_CODED,                                 // Choose only one of the following scan_phys
        .scan_phys     = BLE_GAP_PHY_1MBPS,
    //    .scan_phys     = BLE_GAP_PHY_2MBPS,
        .extended      = 1,
    };

    and modify scan_init function as follow.

      init_scan.connect_if_match = false;
      init_scan.conn_cfg_tag   = APP_BLE_CONN_CFG_TAG;
      init_scan.p_scan_param   = &m_scan_param;

    3rd line.
    But, experience reset... after scan_start() is called

  • That is odd... Can you share your whole scanner project?

  • /**
     * Copyright (c) 2016 - 2021, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *  list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *  Semiconductor ASA integrated circuit in a product or a software update for
     *  such product, must reproduce the above copyright notice, this list of
     *  conditions and the following disclaimer in the documentation and/or other
     *  materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *  contributors may be used to endorse or promote products derived from this
     *  software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *  Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *  engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    #include <stdio.h>
    #include <stdint.h>
    #include <stdbool.h>
    #include <stdarg.h>
    
    #include "nordic_common.h"
    #include "app_error.h"
    #include "app_uart.h"
    #include "ble_db_discovery.h"
    #include "app_timer.h"
    #include "app_util.h"
    #include "bsp_btn_ble.h"
    #include "ble.h"
    #include "ble_gap.h"
    #include "ble_hci.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "nrf_sdh_soc.h"
    #include "ble_nus_c.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_pwr_mgmt.h"
    #include "nrf_ble_scan.h"
    
    #include "nrf_log.h"
    #include "nrf_delay.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "def.h"
    
    
    #define APP_BLE_CONN_CFG_TAG  1                     /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
    #define APP_BLE_OBSERVER_PRIO   3                     /**< BLE observer priority of the application. There is no need to modify this value. */
    
    #define UART_TX_BUF_SIZE    1024                  /**< UART TX buffer size. */
    #define UART_RX_BUF_SIZE    256                   /**< UART RX buffer size. */
    
    #define NUS_SERVICE_UUID_TYPE   BLE_UUID_TYPE_VENDOR_BEGIN        /**< UUID type for the Nordic UART Service (vendor specific). */
    
    #define ECHOBACK_BLE_UART_DATA  1                     /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
    
    #define SCAN_INTERVAL               0x0320                              /**< Determines scan interval in units of 0.625 millisecond. */
    #define SCAN_WINDOW                 0x0320                              /**< Determines scan window in units of 0.625 millisecond. */
    #define SCAN_DURATION           	0x0000                              /**< Duration of the scanning in units of 10 milliseconds. If set to 0x0000, scanning continues until it is explicitly disabled. */
    
    NRF_BLE_GATT_DEF(m_gatt);                         /**< GATT module instance. */
    BLE_DB_DISCOVERY_DEF(m_db_disc);                    /**< Database discovery module instance. */
    NRF_BLE_SCAN_DEF(m_scan);                         /**< Scanning Module instance. */
    NRF_BLE_GQ_DEF(m_ble_gatt_queue,                    /**< BLE GATT Queue instance. */
             NRF_SDH_BLE_CENTRAL_LINK_COUNT,
             NRF_BLE_GQ_QUEUE_SIZE);
    
    static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
    
    static uint8_t tag_prefix [6] =  
    	{
      0x4b, 0x22, 0x4d, 0xbf, 0x54, 0x13
    	};
    
    #if 0
    static ble_gap_scan_params_t m_scan_param =                 /**< Scan parameters requested for scanning and connection. */
    {
        .active        = 0x00,
        .interval      = SCAN_INTERVAL,
        .window        = SCAN_WINDOW,
        .filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL,
        .timeout       = SCAN_DURATION,
    //    .scan_phys     = BLE_GAP_PHY_CODED,                                 // Choose only one of the following scan_phys
        .scan_phys     = BLE_GAP_PHY_1MBPS,
    //    .scan_phys     = BLE_GAP_PHY_2MBPS,
        .extended      = 1,
    };
    #endif
    
    /**@brief NUS UUID. */
    static ble_uuid_t const m_nus_uuid =
    {
      .uuid = BLE_UUID_NUS_SERVICE,
      .type = NUS_SERVICE_UUID_TYPE
    };
    
    APP_TIMER_DEF(m_app_timer_id);
    
    int uart_event_handle_enable = 0;
    
    int hostConnected = 0;
    int moduleId = GW_MODULE;
    
    void
    DBG (const char *fmt, ...)
    {
      va_list argptr;
      char buff [100];
      int i, len;
    
      va_start(argptr, fmt);
      vsprintf(&buff[0], fmt, argptr);
      va_end(argptr);
    
      len = strlen(&buff[0]);
    
      app_uart_put ('$');
      app_uart_put (0x13);
      app_uart_put (len);
    
      for (i = 0; i < len; i ++)
        {
        app_uart_put (buff[i]);
        if (buff[i] == '\n')
          {
          //app_uart_put ('\r');
          }
      }
    }
    
    /**@brief Function for handling asserts in the SoftDevice.
     *
     * @details This function is called in case of an assert in the SoftDevice.
     *
     * @warning This handler is only an example and is not meant for the final product. You need to analyze
     *      how your product is supposed to react in case of assert.
     * @warning On assert from the SoftDevice, the system can only recover on reset.
     *
     * @param[in] line_num   Line number of the failing assert call.
     * @param[in] p_file_name  File name of the failing assert call.
     */
    void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
    {
      app_error_handler(0xDEADBEEF, line_num, p_file_name);
    }
    
    /**@brief Function to start scanning. */
    static void scan_start(void)
    {
      ret_code_t ret;
    
      ret = nrf_ble_scan_start(&m_scan);
      APP_ERROR_CHECK(ret);
    
      ret = bsp_indication_set(BSP_INDICATE_SCANNING);
      APP_ERROR_CHECK(ret);
    }
    
    
    /**@brief Function for handling Scanning Module events.
     */
    static void scan_evt_handler(scan_evt_t const * p_scan_evt)
    {
      ret_code_t err_code;
    
      switch(p_scan_evt->scan_evt_id)
      {
         case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
         {
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
         } break;
    
         case NRF_BLE_SCAN_EVT_CONNECTED:
         {
          ble_gap_evt_connected_t const * p_connected =
                     p_scan_evt->params.connected.p_connected;
          // Scan is automatically stopped by the connection.
          NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
                p_connected->peer_addr.addr[0],
                p_connected->peer_addr.addr[1],
                p_connected->peer_addr.addr[2],
                p_connected->peer_addr.addr[3],
                p_connected->peer_addr.addr[4],
                p_connected->peer_addr.addr[5]
                );
         } break;
    
         case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
         {
           NRF_LOG_INFO("Scan timed out.");
           DBG ("Scan timed out. And restart");
           scan_start();
         } break;
    
         default:
           break;
      }
    }
    
    
    /**@brief Function for initializing the scanning and setting the filters.
     */
    static void scan_init(void)
    {
      ret_code_t      err_code;
      nrf_ble_scan_init_t init_scan;
    
      memset(&init_scan, 0, sizeof(init_scan));
    
      init_scan.connect_if_match = false;
      init_scan.conn_cfg_tag   = APP_BLE_CONN_CFG_TAG;
      //init_scan.p_scan_param   = &m_scan_param;
    
      err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
      APP_ERROR_CHECK(err_code);
    
      err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
      APP_ERROR_CHECK(err_code);
    
      err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_UUID_FILTER, false);
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief   Function for handling app_uart events.
     *
     * @details This function receives a single character from the app_uart module and appends it to
     *      a string. The string is sent over BLE when the last character received is a
     *      'new line' '\n' (hex 0x0A) or if the string reaches the maximum data length.
     */
    static uint8_t uart_data_ring_buf[UART_MAX_DATA_LEN];
    static uint16_t wr_ptr = 0, rd_ptr = 0;
    
    void uart_event_handle(app_uart_evt_t * p_event)
    {
      switch (p_event->evt_type)
        {
          /**@snippet [Handling data from UART] */
        case APP_UART_DATA_READY:
          {
          uint8_t ch;
          UNUSED_VARIABLE(app_uart_get(&ch));
          //app_uart_put (ch);
          uart_data_ring_buf[wr_ptr ++] = ch;
          if (wr_ptr == UART_MAX_DATA_LEN)
            {
            wr_ptr = 0; 
            }
          }
          break;
    
        /**@snippet [Handling data from UART] */
        case APP_UART_COMMUNICATION_ERROR:
          NRF_LOG_ERROR("Communication error occurred while handling UART.");
          //APP_ERROR_HANDLER(p_event->data.error_communication);
          break;
    
        case APP_UART_FIFO_ERROR:
          NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
          //APP_ERROR_HANDLER(p_event->data.error_code);
          break;
    
        default:
          break;
      }
    }
    
    uint8_t
    uart_rx_handler (void)
    {
      uint8_t ch;
      if (wr_ptr != rd_ptr)
        {
        ch = uart_data_ring_buf [rd_ptr ++]; 
        //DBG ("%c", ch);
        if (rd_ptr == UART_MAX_DATA_LEN)
          {
           rd_ptr = 0; 
          }
        return ch;
        }
      return 0;
    }
    
    /**
     * @brief Function for handling shutdown events.
     *
     * @param[in]   event     Shutdown type.
     */
    static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
    {
      ret_code_t err_code;
    
      err_code = bsp_indication_set(BSP_INDICATE_IDLE);
      APP_ERROR_CHECK(err_code);
    
      switch (event)
      {
        case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
          // Prepare wakeup buttons.
          err_code = bsp_btn_ble_sleep_mode_prepare();
          APP_ERROR_CHECK(err_code);
          break;
    
        default:
          break;
      }
    
      return true;
    }
    
    NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
    
    
    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
    {
      ret_code_t      err_code;
      ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
    
      switch (p_ble_evt->header.evt_id)
      {
        case BLE_GAP_EVT_ADV_REPORT:
          {
          // pass all beacon
    #ifndef DK_BOARD
          int i;
    #if 0
          if (tag_prefix[0] == 0xff && tag_prefix[1] == 0xff && tag_prefix[2] == 0xff &&
              tag_prefix[3] == 0xff && tag_prefix[4] == 0xff && tag_prefix[5] == 0xff)
            {
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (17);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 16; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 9]);
              }
            }
          else
    #endif
            {
            // compare prefix, if not match, then drop
            if (memcmp (&m_scan.scan_buffer.p_data[9], tag_prefix, 6) != 0)
              {
              // not my tag
              break;
              }
            app_uart_put ('$');
            app_uart_put (0x12);  // tag_info msg_id
            app_uart_put (11);    // len
    
            app_uart_put (p_gap_evt->params.adv_report.rssi);
            for (i = 0; i < 10; i ++)
              {
              app_uart_put (m_scan.scan_buffer.p_data[i + 15]);
              }
            }
    #endif
          nrf_gpio_pin_toggle (OP_LED_1_PIN);
          }
          break;
    
        case BLE_GAP_EVT_CONNECTED:
          break;
    
        case BLE_GAP_EVT_DISCONNECTED:
    
          NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
                 p_gap_evt->conn_handle,
                 p_gap_evt->params.disconnected.reason);
          break;
    
        case BLE_GAP_EVT_TIMEOUT:
          if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
          {
            NRF_LOG_INFO("Connection Request timed out.");
          }
          break;
    
        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
          // Pairing not supported.
          err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
          // Accepting parameters requested by peer.
          err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                              &p_gap_evt->params.conn_param_update_request.conn_params);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
          NRF_LOG_DEBUG("PHY update request.");
          ble_gap_phys_t const phys =
          {
            .rx_phys = BLE_GAP_PHY_AUTO,
            .tx_phys = BLE_GAP_PHY_AUTO,
          };
          err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
          APP_ERROR_CHECK(err_code);
        } break;
    
        case BLE_GATTC_EVT_TIMEOUT:
          // Disconnect on GATT Client timeout event.
          NRF_LOG_DEBUG("GATT Client Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        case BLE_GATTS_EVT_TIMEOUT:
          // Disconnect on GATT Server timeout event.
          NRF_LOG_DEBUG("GATT Server Timeout.");
          err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                           BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
          APP_ERROR_CHECK(err_code);
          break;
    
        default:
          break;
      }
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupt.
     */
    static void ble_stack_init(void)
    {
      ret_code_t err_code;
    
      err_code = nrf_sdh_enable_request();
      APP_ERROR_CHECK(err_code);
    
      // Configure the BLE stack using the default settings.
      // Fetch the start address of the application RAM.
      uint32_t ram_start = 0;
      err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
      APP_ERROR_CHECK(err_code);
    
      // Enable BLE stack.
      err_code = nrf_sdh_ble_enable(&ram_start);
      APP_ERROR_CHECK(err_code);
    
      // Register a handler for BLE events.
      NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
    }
    
    
    /**@brief Function for handling events from the GATT library. */
    void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
    {
      if (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
      {
        NRF_LOG_INFO("ATT MTU exchange completed.");
    
        m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
        NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
      }
    }
    
    
    /**@brief Function for initializing the GATT library. */
    void gatt_init(void)
    {
      ret_code_t err_code;
    
      err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
      APP_ERROR_CHECK(err_code);
    
      err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling events from the BSP module.
     *
     * @param[in] event  Event generated by button press.
     */
    void bsp_event_handler(bsp_event_t event)
    {
      switch (event)
      {
        case BSP_EVENT_SLEEP:
          nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
          break;
    
        case BSP_EVENT_DISCONNECT:
          break;
    
        default:
          break;
      }
    }
    
    /**@brief Function for initializing the UART. */
    static void uart_init(void)
    {
      ret_code_t err_code;
    
      app_uart_comm_params_t const comm_params =
      {
        .rx_pin_no  = HOST_UART_RX_PIN,
        .tx_pin_no  = HOST_UART_TX_PIN,
        .rts_pin_no   = 0,
        .cts_pin_no   = 0,
        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
        .use_parity   = false,
        .baud_rate  = UART_BAUDRATE_BAUDRATE_Baud115200
      };
    
      APP_UART_FIFO_INIT(&comm_params,
                 UART_RX_BUF_SIZE,
                 UART_TX_BUF_SIZE,
                 uart_event_handle,
                 APP_IRQ_PRIORITY_LOWEST,
                 err_code);
    
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for initializing buttons and leds. */
    static void port_init(void)
    {
      nrf_gpio_cfg_input(MODULE_ID_PIN, NRF_GPIO_PIN_NOPULL );
      moduleId = nrf_gpio_pin_read (MODULE_ID_PIN);
    
      nrf_gpio_cfg_output(OP_LED_1_PIN);
      nrf_gpio_pin_clear (OP_LED_1_PIN);
    }
    
    
    /**@brief Function for initializing the timer. */
    static void timer_init(void)
    {
      ret_code_t err_code = app_timer_init();
      APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the nrf log module. */
    static void log_init(void)
    {
      ret_code_t err_code = NRF_LOG_INIT(NULL);
      APP_ERROR_CHECK(err_code);
    
      NRF_LOG_DEFAULT_BACKENDS_INIT();
    }
    
    
    /**@brief Function for initializing power management.
     */
    static void power_management_init(void)
    {
      ret_code_t err_code;
      err_code = nrf_pwr_mgmt_init();
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for handling the idle state (main loop).
     *
     * @details Handles any pending log operations, then sleeps until the next event occurs.
     */
    static void idle_state_handle(void)
    {
      if (NRF_LOG_PROCESS() == false)
      {
        nrf_pwr_mgmt_run();
      }
    }
    
    static void
    get_prefix_info (void)
    {
      static int st = 0;
      uint8_t ch, len = 0, msg_id, cnt = 0, timeout = 0;
      uint8_t rx_data [64];
      int exit_flag = 1;
    
      while (exit_flag)
        {
        timeout ++;
        if (timeout == 10)
          {
          timeout = 0;
          st = 0; 
          }
        if ((ch = uart_rx_handler ()) != 0)
          {
          timeout = 0;
          switch (st)
            {
            case 0:
              {
              if (ch == '$')
                {
                st = 1;  
                }
              }
              break; 
            case 1:
              {
              if (ch == 0x92) // ble_cfg_req
                {
                msg_id = ch;
                cnt = 0;
                st = 2;
                }
              }
              break; 
            case 2:
              {
              len = ch;
              st = 3;
              }
              break;
            case 3:
              {
              rx_data [cnt ++] = ch;
              if (cnt == len)
                {
                if (msg_id == 0x92)
                  {
                  for (int i = 0; i < 6; i ++)
                    {
                    tag_prefix [i] = rx_data [i];
                    }
                  }
                exit_flag = 0;  // exit from while
                st = 0;
                cnt = 0;
                }
              }
              break;
            }
          }
        else 
          {
          nrf_gpio_pin_toggle (OP_LED_1_PIN);
          nrf_delay_ms (100);
          }
        }
    }
    
    static void 
    app_timer_event_handler (void * p_context)
    {
      nrf_gpio_pin_toggle (OP_LED_1_PIN);
    
      app_timer_start(m_app_timer_id, APP_TIMER_TICKS(APP_TIMER_INTERVAL), NULL);
    }
    
    int main(void)
    {
      // Initialize.
      port_init ();
      log_init();
      timer_init();
      uart_init();
    
    #ifndef DK_BOARD
      get_prefix_info ();
    #endif
      hostConnected = 1;
    
      power_management_init();
      ble_stack_init();
      gatt_init();
      scan_init();
    
      app_timer_create(&m_app_timer_id, APP_TIMER_MODE_SINGLE_SHOT, app_timer_event_handler);  
      app_timer_start(m_app_timer_id, APP_TIMER_TICKS(1), NULL);
    
      // Start execution.
      DBG ("BLE scanner started.\r\n");
      scan_start();
    
    
      // Enter main loop.
      for (;;)
      {
        idle_state_handle();
      }
    }

    https://www.nordicsemi.com/Products/Development-tools/nRF-Sniffer-for-Bluetooth-LE/Download?lang=en#infotabs

    sniffer source is not released?

    I cannot understand specific adv packet is not received while other adv packets are received, but wireshark can detect all specific adv packet well.

    If collision is, wireshark can not receive that packet....

Related