cannot read (in central) the 2nd custom characteristic value defined within a custom service (of a peripheral)

Dear Nordic Experts,

Hello,

i have defined a custom service containing a custom char. value in a peripheral according to https://github.com/NordicPlayground/nRF5x-custom-ble-service-tutorial . i edited the code so that i define two char. values within the same custom service (with separate char. value UUIDs). i connect to the peripheral through nrf-connect on my phone and edit the values of both char. values. in a central device i can successfully read the first char. value, but do not manage reading the second, trying various codes and tricks. 

i attach my code for the central.

/**
 * Copyright (c) 2014 - 2019, 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.
 *
 */
/**
 * @brief BLE LED Button Service central and client application main file.
 *
 * This file contains the source code for a sample client application using the LED Button service.
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "nrf_sdh_soc.h"
#include "nrf_pwr_mgmt.h"
#include "app_timer.h"
#include "boards.h"
#include "bsp.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "ble_lbs_c.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_scan.h"

#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include "nrf_gpio.h"
//#include "app_uart.c"
#include "app_error.h"
#include "app_uart.h"
#include "nrf_delay.h"
#include "nrf_uart.h"

#include "fds.h"
#include "nrf_fstorage.h"

//#include "app_fifo.h"
#define UART_TX_BUF_SIZE        256                                     /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE        256 


#define CENTRAL_SCANNING_LED            BSP_BOARD_LED_0                     /**< Scanning LED will be on when the device is scanning. */
#define CENTRAL_CONNECTED_LED           BSP_BOARD_LED_1                     /**< Connected LED will be on when the device is connected. */
#define LEDBUTTON_LED                   BSP_BOARD_LED_2                     /**< LED to indicate a change of state of the the Button characteristic on the peer. */

#define SCAN_INTERVAL                   0x00A0                              /**< Determines scan interval in units of 0.625 millisecond. */
#define SCAN_WINDOW                     0x0050                              /**< Determines scan window in units of 0.625 millisecond. */
#define SCAN_DURATION                   0x0000                              /**< Timout when scanning. 0x0000 disables timeout. */

#define MIN_CONNECTION_INTERVAL         MSEC_TO_UNITS(7.5, UNIT_1_25_MS)    /**< Determines minimum connection interval in milliseconds. */
#define MAX_CONNECTION_INTERVAL         MSEC_TO_UNITS(30, UNIT_1_25_MS)     /**< Determines maximum connection interval in milliseconds. */
#define SLAVE_LATENCY                   0                                   /**< Determines slave latency in terms of connection events. */
#define SUPERVISION_TIMEOUT             MSEC_TO_UNITS(4000, UNIT_10_MS)     /**< Determines supervision time-out in units of 10 milliseconds. */

#define LEDBUTTON_BUTTON_PIN            BSP_BUTTON_0                        /**< Button that will write to the LED characteristic of the peer */
#define BUTTON_DETECTION_DELAY          APP_TIMER_TICKS(50)                 /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */

#define APP_BLE_CONN_CFG_TAG            1                                   /**< A tag identifying the SoftDevice BLE configuration. */
#define APP_BLE_OBSERVER_PRIO           3                                   /**< Application's BLE observer priority. You shouldn't need to modify this value. */

#define TARGET_UUID  0x180D
#define CUSTOM_PIN 17 

#define FILE_ID    0x1111
#define REC_KEY    0x2222


NRF_BLE_SCAN_DEF(m_scan);                                       /**< Scanning module instance. */
BLE_LBS_C_DEF(m_ble_lbs_c);                                     /**< Main structure used by the LBS client module. */
NRF_BLE_GATT_DEF(m_gatt);                                       /**< GATT module instance. */
BLE_DB_DISCOVERY_DEF(m_db_disc);                                /**< DB discovery 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 ble_gap_scan_params_t m_scan_param = {
    .active        = 1,                     // To receive scan response
    .interval      = NRF_BLE_SCAN_SCAN_INTERVAL,
    .window        = NRF_BLE_SCAN_SCAN_WINDOW,
    .timeout       = 0,                     // Scanning forever unless you stop manually
    .scan_phys     = BLE_GAP_PHY_1MBPS,
    .filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL,
};

#define CUSTOM_SERVICE_UUID_BASE         {0xBC, 0x8A, 0xBF, 0x45, 0xCA, 0x05, 0x50, 0xBA, \
                                          0x40, 0x42, 0xB0, 0x00, 0xC9, 0xAD, 0x64, 0xF3}

#define CUSTOM_SERVICE_UUID               0x1400
#define CUSTOM_VALUE_CHAR_UUID            0x1401
#define CUSTOM_VALUE_CHAR_UUID2            0x1402

static uint16_t          m_conn_handle       = BLE_CONN_HANDLE_INVALID;
static ble_uuid_t        m_custom_uuid;
static ble_gattc_handle_range_t m_service_handle_range;
static ble_gattc_handle_range_t m_service_handle_range2;

static uint16_t          m_custom_char_handle = BLE_GATT_HANDLE_INVALID;
static uint16_t          m_custom_char2_handle = BLE_GATT_HANDLE_INVALID;

bool charnum =0;



static char srvr_id[20]; 
static uint16_t srvr_id_len = 0;

/**@brief Function to handle 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] 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);
}

static void save_message(uint8_t * data, uint16_t length)
{
    static fds_record_t        record;
    static fds_record_desc_t   record_desc;

    // Convert length from bytes to words (FDS stores in 4-byte words)
    uint32_t length_words = (length + 3) / 4;

    record.file_id              = FILE_ID;
    record.key                  = REC_KEY;
    record.data.p_data          = data;
    record.data.length_words    = length_words;

    ret_code_t err_code = fds_record_write(&record_desc, &record);
    APP_ERROR_CHECK(err_code);
}

void uart_send(const char * msg)
{
        for (int i = 0; msg[i] != '\0'; i++)
        {
            while (app_uart_put(msg[i]) != NRF_SUCCESS);
        }

        uint8_t dummy;
        while (app_uart_get(&dummy) == NRF_SUCCESS) {
            // Keep reading until the buffer is empty
        }

}

static void load_message(void)
{
    fds_record_desc_t desc = {0};
    fds_find_token_t  tok  = {0};

    // Search for the record
    if (fds_record_find(FILE_ID, REC_KEY, &desc, &tok) == NRF_SUCCESS)
    {
        fds_flash_record_t flash_record = {0};

        // Open the record
        if (fds_record_open(&desc, &flash_record) == NRF_SUCCESS)
        {
            // Access the data
            //char *saved_data = (char *)flash_record.p_data;
            //srvr_id_len  = flash_record.p_header->length_words * 4; // in bytes

            memcpy(srvr_id, (char *)flash_record.p_data, srvr_id_len);
            uart_send("message loaded");
            nrf_delay_ms(100);
            uart_send(srvr_id);

            // Print or use it
            NRF_LOG_INFO("Recovered message: %s", (uint32_t)srvr_id);

            // Close the record
            fds_record_close(&desc);
        }
    }
    else
    {
        NRF_LOG_INFO("No saved message found.");
    }
}


static void fds_evt_handler(fds_evt_t const * const p_evt)
{
    switch (p_evt->id)
    {
        case FDS_EVT_INIT:
            if (p_evt->result == NRF_SUCCESS)
            {
                NRF_LOG_INFO("FDS initialized.");
            }
            else
            {
                NRF_LOG_ERROR("FDS init failed (0x%x).", p_evt->result);
            }
            break;

        case FDS_EVT_WRITE:
            if (p_evt->result == NRF_SUCCESS)
            {
                NRF_LOG_INFO("Record written successfully.");
            }
            else
            {
                NRF_LOG_ERROR("Write failed (0x%x).", p_evt->result);
            }
            break;

        case FDS_EVT_UPDATE:
            if (p_evt->result == NRF_SUCCESS)
            {
                NRF_LOG_INFO("Record updated successfully.");
            }
            break;

        case FDS_EVT_DEL_RECORD:
            NRF_LOG_INFO("Record deleted.");
            break;

        case FDS_EVT_GC:
            NRF_LOG_INFO("Garbage collection complete.");
            break;

        default:
            break;
    }
}


static void fds_init_helper(void)
{
    ret_code_t err_code = fds_register(fds_evt_handler);
    APP_ERROR_CHECK(err_code);

    err_code = fds_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the LED Button Service client errors.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void lbs_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@brief Function for the LEDs initialization.
 *
 * @details Initializes all LEDs used by the application.
 */
static void leds_init(void)
{
    bsp_board_init(BSP_INIT_LEDS);
}


/**@brief Function to start scanning.
 */
static void scan_start(void)
{
    ret_code_t err_code;

    err_code = nrf_ble_scan_start(&m_scan);
    APP_ERROR_CHECK(err_code);

    bsp_board_led_off(CENTRAL_CONNECTED_LED);
    bsp_board_led_on(CENTRAL_SCANNING_LED);
}


/**@brief Handles events coming from the LED Button central module.
 */
static void lbs_c_evt_handler(ble_lbs_c_t * p_lbs_c, ble_lbs_c_evt_t * p_lbs_c_evt)
{
    switch (p_lbs_c_evt->evt_type)
    {
        case BLE_LBS_C_EVT_DISCOVERY_COMPLETE:
        {
            ret_code_t err_code;

            err_code = ble_lbs_c_handles_assign(&m_ble_lbs_c,
                                                p_lbs_c_evt->conn_handle,
                                                &p_lbs_c_evt->params.peer_db);
            NRF_LOG_INFO("LED Button service discovered on conn_handle 0x%x.", p_lbs_c_evt->conn_handle);

            err_code = app_button_enable();
            APP_ERROR_CHECK(err_code);

            // LED Button service discovered. Enable notification of Button.
            err_code = ble_lbs_c_button_notif_enable(p_lbs_c);
            APP_ERROR_CHECK(err_code);
        } break; // BLE_LBS_C_EVT_DISCOVERY_COMPLETE

        case BLE_LBS_C_EVT_BUTTON_NOTIFICATION:
        {
            NRF_LOG_INFO("Button state changed on peer to 0x%x.", p_lbs_c_evt->params.button.button_state);
            if (p_lbs_c_evt->params.button.button_state)
            {
                bsp_board_led_on(LEDBUTTON_LED);
            }
            else
            {
                bsp_board_led_off(LEDBUTTON_LED);
            }
        } break; // BLE_LBS_C_EVT_BUTTON_NOTIFICATION

        default:
            // No implementation needed.
            break;
    }
}


/**@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;
   
    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            NRF_LOG_INFO("Connected");
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;

            // Discover primary service
            err_code = sd_ble_gattc_primary_services_discover(
                m_conn_handle, 1, &m_custom_uuid);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            NRF_LOG_INFO("Disconnected");
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;

        case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
        {
            const ble_gattc_evt_prim_srvc_disc_rsp_t * p_rsp =
                &p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp;

            if (p_rsp->count > 0)
            {
                m_service_handle_range = p_rsp->services[0].handle_range;
                


                // Discover characteristic in this service
                err_code = sd_ble_gattc_characteristics_discover(
                    m_conn_handle, &m_service_handle_range);
                APP_ERROR_CHECK(err_code);


            }
            else
            {
                NRF_LOG_WARNING("Service not found");
            }
        } break;

        case BLE_GATTC_EVT_CHAR_DISC_RSP:
        {
            const ble_gattc_evt_char_disc_rsp_t * p_rsp =
                &p_ble_evt->evt.gattc_evt.params.char_disc_rsp;
            char cip_cmd[32];
            snprintf(cip_cmd, sizeof(cip_cmd), "p_rsp->count=%d\r\n",p_rsp->count );
            uart_send(cip_cmd);
            nrf_delay_ms(100);

                

            for (uint8_t i = 0; i < p_rsp->count; i++)
            {
                if (p_rsp->chars[i].uuid.uuid == CUSTOM_VALUE_CHAR_UUID)
                {
                    m_custom_char_handle = p_rsp->chars[i].handle_value;
                    NRF_LOG_INFO("Custom characteristic handle: %d", m_custom_char_handle);
                }
                else if (p_rsp->chars[i].uuid.uuid == CUSTOM_VALUE_CHAR_UUID2)
                {
                    m_custom_char2_handle = p_rsp->chars[i].handle_value;
                    uart_send("orega!");
                }

                 if (m_custom_char_handle != BLE_GATT_HANDLE_INVALID)
                {
                   // Read characteristic
                    err_code = sd_ble_gattc_read(m_conn_handle, m_custom_char_handle, 0);
                    APP_ERROR_CHECK(err_code);}

                if (m_custom_char2_handle != BLE_GATT_HANDLE_INVALID)
                {
                   // Read characteristic
                    err_code = sd_ble_gattc_read(m_conn_handle, m_custom_char2_handle, 0);
                    APP_ERROR_CHECK(err_code);}

                  
            }
        } break;

        case BLE_GATTC_EVT_READ_RSP:
        {
            const ble_gattc_evt_read_rsp_t * p_rsp =
                &p_ble_evt->evt.gattc_evt.params.read_rsp;

            NRF_LOG_INFO("Read %d bytes", p_rsp->len);
            NRF_LOG_HEXDUMP_INFO(p_rsp->data, p_rsp->len);
            // uart_send((const char *) p_rsp->data);
             //srvr_id=(const char)*(p_rsp->data);
            srvr_id_len = p_rsp->len;
            memcpy(srvr_id, p_rsp->data, srvr_id_len);
            srvr_id[srvr_id_len] = '\0';  // null-terminate if it's a string
            uart_send(srvr_id);
            save_message((uint8_t *)srvr_id, strlen(srvr_id));


        } break;

        default:
            break;
    }
}



/**@brief LED Button client initialization.
 */
static void lbs_c_init(void)
{
    ret_code_t       err_code;
    ble_lbs_c_init_t lbs_c_init_obj;

    lbs_c_init_obj.evt_handler   = lbs_c_evt_handler;
    lbs_c_init_obj.p_gatt_queue  = &m_ble_gatt_queue;
    lbs_c_init_obj.error_handler = lbs_error_handler;

    err_code = ble_lbs_c_init(&m_ble_lbs_c, &lbs_c_init_obj);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupts.
 */
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 button handler module.
 *
 * @param[in] pin_no        The pin that the event applies to.
 * @param[in] button_action The button action (press/release).
 */
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
    ret_code_t err_code;

    switch (pin_no)
    {
        case LEDBUTTON_BUTTON_PIN:
            err_code = ble_lbs_led_status_send(&m_ble_lbs_c, button_action);
            if (err_code != NRF_SUCCESS &&
                err_code != BLE_ERROR_INVALID_CONN_HANDLE &&
                err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            if (err_code == NRF_SUCCESS)
            {
                NRF_LOG_INFO("LBS write LED state %d", button_action);
            }
            break;

        default:
            APP_ERROR_HANDLER(pin_no);
            break;
    }
}


/**@brief Function for handling Scaning events.
 *
 * @param[in]   p_scan_evt   Scanning event.
 */

static void scan_evt_handler0(scan_evt_t const * p_scan_evt)
{
    ret_code_t err_code;
    char cip_cmd[32];
    
    //char message1 [8];

    switch(p_scan_evt->scan_evt_id)
    {
        case NRF_BLE_SCAN_EVT_FILTER_MATCH:
        {
          //nrf_gpio_pin_set(CUSTOM_PIN);
          
          //ble_gap_evt_adv_report_t const * p_adv_report = p_scan_evt->params.filter_match.p_adv_report;
          //ble_gap_addr_t const * addr = &p_adv_report->peer_addr;
        }
        break;

        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
            break;
        default:
          break;
    }
}
static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
    ret_code_t err_code;
    char cip_cmd[32];
    //char rssi_msg[32];
    char rssi_msg2[64];

    switch(p_scan_evt->scan_evt_id)
    {
        case NRF_BLE_SCAN_EVT_FILTER_MATCH:
        {
          nrf_gpio_pin_set(CUSTOM_PIN);
          
          ble_gap_evt_adv_report_t const * p_adv_report = p_scan_evt->params.filter_match.p_adv_report;
          

          int8_t rssi = p_adv_report->rssi;
          
          //snprintf(rssi_msg, sizeof(rssi_msg), "RSSI: %d dBm\r\n", rssi);
          //int len =strlen(rssi_msg);
          
          snprintf(rssi_msg2, sizeof(rssi_msg2), "Beacon Address: %02X:%02X:%02X:%02X:%02X:%02X RSSI: %d dBm\r\n",
                         p_adv_report->peer_addr.addr[0],
                         p_adv_report->peer_addr.addr[1],
                         p_adv_report->peer_addr.addr[2],
                         p_adv_report->peer_addr.addr[3],
                         p_adv_report->peer_addr.addr[4],
                         p_adv_report->peer_addr.addr[5], rssi);
          int len2 =strlen(rssi_msg2);

          snprintf(cip_cmd, sizeof(cip_cmd), "AT+CIPSEND=%d\r\n", len2);

         
          uart_send(cip_cmd);
          nrf_delay_ms(30);
          uart_send(rssi_msg2);
          nrf_delay_ms(30);

        }
        break;

        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
            break;
        default:
          break;
    }
}



/**@brief Function for initializing the button handler module.
 */
static void buttons_init(void)
{
    ret_code_t err_code;

    //The array must be static because a pointer to it will be saved in the button handler module.
    static app_button_cfg_t buttons[] =
    {
        {LEDBUTTON_BUTTON_PIN, false, BUTTON_PULL, button_event_handler}
    };

    err_code = app_button_init(buttons, ARRAY_SIZE(buttons),
                               BUTTON_DETECTION_DELAY);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling database discovery events.
 *
 * @details This function is callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function should forward the events
 *          to their respective services.
 *
 * @param[in] p_event  Pointer to the database discovery event.
 */
static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
{
    ble_lbs_on_db_disc_evt(&m_ble_lbs_c, p_evt);
}


/**@brief Database discovery initialization.
 */
static void db_discovery_init(void)
{
    ble_db_discovery_init_t db_init;

    memset(&db_init, 0, sizeof(db_init));

    db_init.evt_handler  = db_disc_handler;
    db_init.p_gatt_queue = &m_ble_gatt_queue;

    ret_code_t err_code = ble_db_discovery_init(&db_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the log.
 */
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 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 Power manager. */
static void power_management_init(void)
{
    ret_code_t err_code;
    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}

static void scan_init0(char *td)
{
    ret_code_t          err_code;
    nrf_ble_scan_init_t init_scan;

    memset(&init_scan, 0, sizeof(init_scan));

    init_scan.connect_if_match = true;
    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_handler0);
    APP_ERROR_CHECK(err_code);

    // Setting filters for scanning.
    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
    APP_ERROR_CHECK(err_code);
    
    
    //NRF_LOG_INFO(" TD: %d ",td[0]);


    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, td);
    //NRF_LOG_INFO(" TD: %d ",td);
    APP_ERROR_CHECK(err_code);

}
static void scan_init(char *td)
{
    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;   //true
    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;

    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
    APP_ERROR_CHECK(err_code);

    // Setting filters for scanning.
    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
    APP_ERROR_CHECK(err_code);
    
    
    //NRF_LOG_INFO(" TD: %d ",td[0]);


    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, td);
    //NRF_LOG_INFO(" TD: %d ",td);
    APP_ERROR_CHECK(err_code);


}


/**@brief Function for initializing the GATT module.
 */
static void gatt_init(void)
{
    ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the idle state (main loop).
 *
 * @details Handle any pending log operation(s), then sleep until the next event occurs.
 */
static void idle_state_handle(void)
{
    NRF_LOG_FLUSH();
    nrf_pwr_mgmt_run();
}

void uart_error_handle(app_uart_evt_t * p_event)
{
    if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}

/**@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    = RX_PIN_NUMBER,
        .tx_pin_no    = TX_PIN_NUMBER,
        .rts_pin_no   = RTS_PIN_NUMBER,
        .cts_pin_no   = CTS_PIN_NUMBER,
        .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_error_handle,
                       APP_IRQ_PRIORITY_HIGH,
                       err_code);

    APP_ERROR_CHECK(err_code);
}

uint32_t get_timestamp_diff(uint32_t start_ticks)
{
    uint32_t current_ticks = app_timer_cnt_get();
    uint32_t diff_ticks = app_timer_cnt_diff_compute(current_ticks, start_ticks);
    return ((uint64_t)diff_ticks ) / APP_TIMER_CLOCK_FREQ;
}

int main(void)
{
    // Initialize.
    nrf_gpio_cfg_output(CUSTOM_PIN);
    nrf_gpio_pin_clear(CUSTOM_PIN);
    log_init();
    timer_init();
    leds_init();
    buttons_init();
    power_management_init();
    fds_init_helper();
    ble_stack_init();
    
    gatt_init();
    db_discovery_init();
    lbs_c_init();

    // Start execution.
    NRF_LOG_INFO("Blinky CENTRAL example started.");
    
    uart_init();
    // Turn on the LED to signal scanning.
    bsp_board_led_on(CENTRAL_SCANNING_LED);
    char td[][6]= {{0xD5, 0x2A, 0x9D, 0x99, 0xE3, 0xDA},{0xD2, 0xE8, 0x6B, 0x15, 0xD0, 0xD6},{0x3F, 0xCE, 0xC6, 0xF4, 0x40, 0xDA}};
    //char *comand2 

    fds_init_helper();

    load_message();

    char comand1a[]="AT+CWJAP=\"";
    //char comand1c[]= 
    char comand2a[] = "AT+CIPSTART=\"TCP\",\"";
    char comand2c[] = "\",3000\r\n";
    char comand20[36];
    char comand2[47];
  
    //uart_send("HelloESP01\r\n");
    nrf_delay_ms(3000);

    uart_send("AT\r\n");
    nrf_delay_ms(1000);

    uart_send("AT+CIPSEND=10\r\n");
    nrf_delay_ms(100);
    uart_send("HelloESP03\r\n");
    nrf_delay_ms(100);

    uart_send("AT+CIPSTART=\"POCO M5s\",\"bdsdnhhvdmk12\"\r\n");
    nrf_delay_ms(4000);


    char cip_cmd[32];
    uint32_t start_ticks = app_timer_cnt_get();
    
    //uint32_t current_ticks = app_timer_cnt_get();
    while ((get_timestamp_diff(start_ticks) < 15))
    {
        // Let SoftDevice handle BLE events
        sd_app_evt_wait();  // This avoids freezing BLE stack
        scan_init0(td[2]);
        ble_uuid128_t base_uuid = { CUSTOM_SERVICE_UUID_BASE };
        sd_ble_uuid_vs_add(&base_uuid, &m_custom_uuid.type);
        m_custom_uuid.uuid = CUSTOM_SERVICE_UUID;

        scan_start();    
    }
    sprintf(comand20, "%s%s", comand2a,srvr_id); 
    sprintf(comand2, "%s%s", comand20,comand2c);
    uart_send(comand2);

    nrf_delay_ms(2000);
    // Enter main loop.
    for (;;)
    {
        scan_init(td[0]);
        scan_start();
        
        //gatt_init();
        //db_discovery_init();
        idle_state_handle();
        scan_init(td[1]);
        scan_start();

        //gatt_init();
        //db_discovery_init();
        idle_state_handle();
        

    }
}

Parents Reply Children
No Data
Related