This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Solution approach for handling GPIO interrupts. SDK 15.3 S132

Went through the pin_change_int example and of course it works fine.

Migrated that to custom board and it also worked fine with main loop.

So I then tried to use that as basis for real application that has to service an external interrupt.

In the main application, there are spi read and write functions.

When they are active and in a wait loop, the external interrupt is not triggered.

I am assuming that is because the priority level is the same and is therefore blocked.

I set the gpiote priority to 2 and still the interrupt is not triggered.

I am sure anyone reading sensors etc must deal with this type of problem everyday.

Right now the bluetooth stack and services are not being used and the interrupts still don't trigger.

The interrupt triggers once at startup but then never again.

In the pin_change_int example I did not see where the interrupt is cleared and enabled.

Is that what I am missing ? 

Parents
  • HI Clark, 

    are the SPI read and write functions being called from main's context or from an interrupt context, e.g. triggered by a application timer ? If its the latter what is the interrupt priority of the interrupt where you're calling the SPI write/read functions and in an active wait loop?

    If its possible for you to chare your main.c file, then that would make it easier to debug. 

    Best regards

    Bjørn

  • The spi functions are being called by main.c and are not interrupt based.

    But they commands/data they send over spi to a CC3100 SoC generate an interrupt when the CC3100 needs a reply.

    The functions are actually in another set of files, one the .c and the other a supporting header file.

    Those functions are used in the main body of main.c.

    I will include what I can from the main.c file below :

    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    #include "nordic_common.h"
    #include "nrf_sdm.h"
    
    #include "ble.h"
    #include "ble_hci.h"
    #include "ble_srv_common.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "nrf_sdh_soc.h"
    #include "nrf_drv_gpiote.h"
    #include "app_util.h"
    #include "app_error.h"
    #include "app_util.h"
    #include "app_timer.h"
    #include "app_gpiote.h"
    #include "bsp_btn_ble.h"
    #include "peer_manager.h"
    #include "peer_manager_handler.h"
    #include "fds.h"
    #include "nrf_fstorage.h"
    #include "ble_conn_state.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_ble_scan.h"
    #include "nrf_pwr_mgmt.h"
    
    
    #include "simplelink.h"
    #include "sl_common.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "SEGGER_RTT.h"
    //#include "SEGGER_RTT_printf.h"
    #include "medsense.h"
    #include "host_programming_1.0.1.13-2.11.0.1_ucf.h"
    #include "host_programming_1.0.1.13-2.11.0.1_ucf-signed.h"
    
    
    
    
    
    
    
    
    #define NRF_LOG_INFO(...)  SEGGER_RTT_printf(0 , __VA_ARGS__)
    
    
    #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 APP_SOC_OBSERVER_PRIO     1                                /**< Applications' SoC observer priority. You shouldn't need to modify this value. */
    
    #define SEC_PARAM_BOND            1                                /**< Perform bonding. */
    #define SEC_PARAM_MITM            0                                /**< Man In The Middle protection not required. */
    #define SEC_PARAM_LESC            0                                /**< LE Secure Connections not enabled. */
    #define SEC_PARAM_KEYPRESS        0                                /**< Keypress notifications not enabled. */
    #define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE             /**< No I/O capabilities. */
    #define SEC_PARAM_OOB             0                                /**< Out Of Band data not available. */
    #define SEC_PARAM_MIN_KEY_SIZE    7                                /**< Minimum encryption key size. */
    #define SEC_PARAM_MAX_KEY_SIZE    16                               /**< Maximum encryption key size. */
    
    #define SCAN_DURATION_WITELIST    3000                             /**< Duration of the scanning in units of 10 milliseconds. */
    
    #define TARGET_UUID               BLE_UUID_GATT                    /**< Target device name that application is looking for. */
    
    
    /**@brief Variable length data encapsulation in terms of length and pointer to data */
    typedef struct
    {
        uint8_t * p_data;   /**< Pointer to data. */
        uint16_t  data_len; /**< Length of data. */
    }data_t;
    
    NRF_BLE_GATT_DEF(m_gatt);                                 /**< GATT module instance. */
    NRF_BLE_SCAN_DEF(m_scan);                                 /**< Scanning Module instance. */
    
    static uint16_t              m_conn_handle;               /**< Current connection handle. */
    static bool                  m_whitelist_disabled;        /**< True if whitelist has been temporarily disabled. */
    static bool                  m_memory_access_in_progress; /**< Flag to keep track of ongoing operations on persistent memory. */
    static bool                  m_erase_bonds;               /**< Bool to determine if bonds should be erased before scanning starts. Based on button push upon startup. */
    
    /**< Scan parameters requested for scanning and connection. */
    static ble_gap_scan_params_t const m_scan_param =
    {
        .active        = 0x01,
        .interval      = NRF_BLE_SCAN_SCAN_INTERVAL,
        .window        = NRF_BLE_SCAN_SCAN_WINDOW,
        .filter_policy = BLE_GAP_SCAN_FP_WHITELIST,
        .timeout       = SCAN_DURATION_WITELIST,
        .scan_phys     = BLE_GAP_PHY_1MBPS,
    };
    
    bool startup = true;
    
    static void scan_start(void);
    
    static char const m_target_periph_name[] = "Nordic_GATTS"; /**< If you want to connect to a peripheral using a given advertising name, type its name here. */
    static bool       is_connect_per_addr    = false;          /**< If you want to connect to a peripheral with a given address, set this to true and put the correct address in the variable below. */
    
    static ble_gap_addr_t const m_target_periph_addr =
    {
        /* Possible values for addr_type:
           BLE_GAP_ADDR_TYPE_PUBLIC,
           BLE_GAP_ADDR_TYPE_RANDOM_STATIC,
           BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE,
           BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */
          .addr_type = BLE_GAP_ADDR_TYPE_RANDOM_STATIC,
          .addr      = {0x8D, 0xFE, 0x23, 0x86, 0x77, 0xD9}
    };
    
    
    //**********Simplelink items
    #define _u32 uint32_t
    #define _i32 int32_t
    #define i32 int32_t
    
    #define VERSION_OFFSET      	(8)
    #define UCF_OFFSET      		(20)
    #define CHUNK_LEN			(1024)
    #define LEN_128KB			(131072)
    
    #define find_min(a,b) (((a) < (b)) ? (a) : (b))
    
    char		  printBuffer[1024];
    
    typedef enum
    {
      size512KB = 0,
      size1MB,
      size2MB,
      size4MB,
      size8MB,
      size16MB
    }sflashSize_e;
    
    sflashSize_e	flashSize = size1MB;;
    
    #define APPLICATION_VERSION "1.3.0"
    
    
    
    /* Use bit 32:
     *      1 in a 'status_variable', the device has completed the ping operation
     *      0 in a 'status_variable', the device has not completed the ping operation
     */
    #define STATUS_BIT_PING_DONE  31
    
    #define HOST_NAME       "www.ti.com"
    
    /*
     * Values for below macros shall be modified for setting the 'Ping' properties
     */
    #define PING_INTERVAL   1000    /* In msecs */
    #define PING_TIMEOUT    3000    /* In msecs */
    #define PING_PKT_SIZE   20      /* In bytes */
    #define NO_OF_ATTEMPTS  3
    
    #define IS_PING_DONE(status_variable)           GET_STATUS_BIT(status_variable, \
                                                                   STATUS_BIT_PING_DONE)
    
    /*
     * GLOBAL VARIABLES -- Start
     */
    extern volatile  uint32_t g_Status;
    extern volatile uint32_t g_PingPacketsRecv;
    extern volatile uint32_t g_GatewayIP;
    /*
     * GLOBAL VARIABLES -- End
     */
    
    
    /*
     * STATIC FUNCTION DEFINITIONS -- Start
     */
    extern int32_t	 configureSimpleLinkToDefaultState();
    static int32_t	 establishConnectionWithAP();
    static int32_t	 checkLanConnection();
    static int32_t	 checkInternetConnection();
    static int32_t	 initializeAppVariables();
    static void displayBanner();
    
    // End if Simplelink items
    
    static app_gpiote_user_id_t   m_example_user_id;
    static void example_gpiote_event_handler(uint32_t event_pins_low_to_high, uint32_t event_pins_high_to_low);
    
    
    
    /**@brief 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] 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 for handling Peer Manager events.
     *
     * @param[in] p_evt  Peer Manager event.
     */
    static void pm_evt_handler(pm_evt_t const * p_evt)
    {
        pm_handler_on_pm_evt(p_evt);
        pm_handler_disconnect_on_sec_failure(p_evt);
        pm_handler_flash_clean(p_evt);
    
        switch (p_evt->evt_id)
        {
            case PM_EVT_PEERS_DELETE_SUCCEEDED:
                scan_start();
                break;
    
            default:
                break;
        }
    }
    
    
    /**
     * @brief Function for 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 SoftDevice SoC event handler.
     *
     * @param[in] evt_id    SoC event.
     * @param[in] p_context Context.
     */
    static void soc_evt_handler(uint32_t evt_id, void * p_context)
    {
        switch (evt_id)
        {
            case NRF_EVT_FLASH_OPERATION_SUCCESS:
            /* fall through */
            case NRF_EVT_FLASH_OPERATION_ERROR:
    
                if (m_memory_access_in_progress)
                {
                    m_memory_access_in_progress = false;
                    scan_start();
                }
                break;
    
            default:
                // No implementation needed.
                break;
        }
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupt.
      */
    
    
    /**@brief Function for disabling the use of whitelist for scanning.
     */
    static void whitelist_disable(void)
    {
        if (!m_whitelist_disabled)
        {
            NRF_LOG_INFO("Whitelist temporarily disabled.");
            m_whitelist_disabled = true;
            nrf_ble_scan_stop();
            scan_start();
        }
    }
    
    
    /**@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)
    {
        ret_code_t err_code;
    
        switch (event)
        {
            case BSP_EVENT_SLEEP:
                nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
                break;
    
            case BSP_EVENT_DISCONNECT:
                err_code = sd_ble_gap_disconnect(m_conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
                break;
    
            case BSP_EVENT_WHITELIST_OFF:
                whitelist_disable();
                break;
    
            case BSP_EVENT_KEY_2:
                // Note that to simplify this example, we are not actually making any changes to our
                // database (Which is normally when you would want to send this indication).
                // Acting upon this indication (doing a rediscovery) is pointless for the peer.
                pm_local_database_has_changed();
                break;
            default:
                break;
        }
    }
    
    
    /**@brief Function for the Peer Manager initialization.
     *
     * @param[in] erase_bonds  Indicates whether bonding information should be cleared from
     *                         persistent storage during initialization of the Peer Manager.
     */
    static void peer_manager_init()
    {
        ble_gap_sec_params_t sec_param;
        ret_code_t           err_code;
    
        err_code = pm_init();
        APP_ERROR_CHECK(err_code);
    
        memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
    
        // Security parameters to be used for all security procedures.
        sec_param.bond           = SEC_PARAM_BOND;
        sec_param.mitm           = SEC_PARAM_MITM;
        sec_param.lesc           = SEC_PARAM_LESC;
        sec_param.keypress       = SEC_PARAM_KEYPRESS;
        sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
        sec_param.oob            = SEC_PARAM_OOB;
        sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
        sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
        sec_param.kdist_own.enc  = 1;
        sec_param.kdist_own.id   = 1;
        sec_param.kdist_peer.enc = 1;
        sec_param.kdist_peer.id  = 1;
    
        err_code = pm_sec_params_set(&sec_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = pm_register(pm_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Clear bond information from persistent storage.
     */
    static void delete_bonds(void)
    {
        ret_code_t err_code;
    
        NRF_LOG_INFO("Erase bonds.");
        err_code = pm_peers_delete();
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Retrive a list of peer manager peer IDs.
     *
     * @param[inout] p_peers   The buffer where to store the list of peer IDs.
     * @param[inout] p_size    In: The size of the @p p_peers buffer.
     *                         Out: The number of peers copied in the buffer.
     */
    static void peer_list_get(pm_peer_id_t * p_peers, uint32_t * p_size)
    {
        pm_peer_id_t peer_id;
        uint32_t     peers_to_copy;
    
        peers_to_copy = (*p_size < BLE_GAP_WHITELIST_ADDR_MAX_COUNT) ?
                         *p_size : BLE_GAP_WHITELIST_ADDR_MAX_COUNT;
    
        peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID);
        *p_size = 0;
    
        while ((peer_id != PM_PEER_ID_INVALID) && (peers_to_copy--))
        {
            p_peers[(*p_size)++] = peer_id;
            peer_id              = pm_next_peer_id_get(peer_id);
        }
    }
    
    
    static void whitelist_load()
    {
        ret_code_t   ret;
        pm_peer_id_t peers[8];
        uint32_t     peer_cnt;
    
        memset(peers, PM_PEER_ID_INVALID, sizeof(peers));
        peer_cnt = (sizeof(peers) / sizeof(pm_peer_id_t));
    
        // Load all peers from flash and whitelist them.
        peer_list_get(peers, &peer_cnt);
    
        ret = pm_whitelist_set(peers, peer_cnt);
        APP_ERROR_CHECK(ret);
    
        // Setup the device identities list.
        // Some SoftDevices do not support this feature.
        ret = pm_device_identities_list_set(peers, peer_cnt);
        if (ret != NRF_ERROR_NOT_SUPPORTED)
        {
            APP_ERROR_CHECK(ret);
        }
    }
    
    
    static void on_whitelist_req(void)
    {
        // Whitelist buffers.
        ble_gap_addr_t whitelist_addrs[8];
        ble_gap_irk_t  whitelist_irks[8];
    
        memset(whitelist_addrs, 0x00, sizeof(whitelist_addrs));
        memset(whitelist_irks, 0x00, sizeof(whitelist_irks));
    
        uint32_t addr_cnt = (sizeof(whitelist_addrs) / sizeof(ble_gap_addr_t));
        uint32_t irk_cnt  = (sizeof(whitelist_irks) / sizeof(ble_gap_irk_t));
    
        // Reload the whitelist and whitelist all peers.
        whitelist_load();
    
        ret_code_t err_code;
    
        // Get the whitelist previously set using pm_whitelist_set().
        err_code = pm_whitelist_get(whitelist_addrs, &addr_cnt,
                                    whitelist_irks, &irk_cnt);
    
        if (((addr_cnt == 0) && (irk_cnt == 0)) ||
            (m_whitelist_disabled))
        {
            // Don't use whitelist.
            err_code = nrf_ble_scan_params_set(&m_scan, NULL);
            APP_ERROR_CHECK(err_code);
        }
    
        NRF_LOG_INFO("Starting scan.");
    
        err_code = bsp_indication_set(BSP_INDICATE_SCANNING);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function to start scanning.
     */
    static void scan_start(void)
    {
        ret_code_t err_code;
    
        // If there is any pending write to flash, defer scanning until it completes.
        if (nrf_fstorage_is_busy(NULL))
        {
            m_memory_access_in_progress = true;
            return;
        }
    
        err_code = nrf_ble_scan_params_set(&m_scan, &m_scan_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_start(&m_scan);
        APP_ERROR_CHECK(err_code);
    
    }
    
    
    /**@brief Function for initializing buttons and LEDs.
     *
     * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
     */
    static void buttons_leds_init(bool * p_erase_bonds)
    {
        ret_code_t  err_code;
        bsp_event_t startup_event;
    
        err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
        APP_ERROR_CHECK(err_code);
    
        err_code = bsp_btn_ble_init(NULL, &startup_event);
        APP_ERROR_CHECK(err_code);
    
        *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
    }
    
    
    /**@brief Function for initializing logging. */
    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 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 initializing the power management.
     */
    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_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_WHITELIST_REQUEST:
            {
                on_whitelist_req();
                m_whitelist_disabled = false;
            } break;
    
            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_SCAN_TIMEOUT:
            {
                NRF_LOG_INFO("Scan timed out.");
                scan_start();
            } break;
    
            case NRF_BLE_SCAN_EVT_FILTER_MATCH:
                break;
            case NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT:
                break;
    
            default:
              break;
        }
    }
    
    
    /**@brief Function for initializing scanning.
     */
    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.p_scan_param     = &m_scan_param;
        init_scan.connect_if_match = 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);
    }
    
    
    /**@ Function for settings scan filters.
     */
    static void scan_filters_set(void)
    {
        ret_code_t err_code;
        ble_uuid_t target_uuid = {.uuid = TARGET_UUID, .type = BLE_UUID_TYPE_BLE};
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &target_uuid);
        APP_ERROR_CHECK(err_code);
    
        if (is_connect_per_addr)
        {
            err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, m_target_periph_addr.addr);
            APP_ERROR_CHECK(err_code);
            err_code = nrf_ble_scan_filters_enable(&m_scan,
                           NRF_BLE_SCAN_NAME_FILTER | NRF_BLE_SCAN_UUID_FILTER | NRF_BLE_SCAN_ADDR_FILTER,
                           false);
            APP_ERROR_CHECK(err_code);
        }
        else
        {
            err_code = nrf_ble_scan_filters_enable(&m_scan,
                           NRF_BLE_SCAN_NAME_FILTER | NRF_BLE_SCAN_UUID_FILTER,
                           false);
            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)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            nrf_pwr_mgmt_run();
        }
    }
    
    
    /**@brief Function for starting a scan, or instead trigger it from peer manager (after
              deleting bonds).
    
       @param[in] p_erase_bonds Pointer to a bool to determine if bonds will be deleted before scanning.
    */
    void scanning_start(bool * p_erase_bonds)
    {
        // Start scanning for peripherals and initiate connection
        // with devices that advertise GATT Service UUID.
        if (*p_erase_bonds == true)
        {
            // Scan is started by the PM_EVT_PEERS_DELETE_SUCCEEDED event.
            delete_bonds();
        }
        else
        {
            scan_start();
        }
    }
    
    
    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;
    
        pm_handler_secure_on_connection(p_ble_evt);
    
        switch (p_ble_evt->header.evt_id)
        {
            case BLE_GAP_EVT_CONNECTED:
            {
                m_conn_handle = p_gap_evt->conn_handle;
                err_code      = bsp_indication_set(BSP_INDICATE_CONNECTED);
                APP_ERROR_CHECK(err_code);
    
                if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    scan_start();
                }
            } break;
    
            case BLE_GAP_EVT_TIMEOUT:
            {
                if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
                {
                    NRF_LOG_DEBUG("Connection Request timed out.");
                }
            } 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_DISCONNECTED:
            {
                NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
                             p_gap_evt->conn_handle,
                             p_gap_evt->params.disconnected.reason);
    
                if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    scan_start();
                }
            } 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;
        }
    }
    
    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 handlers for BLE and SoC events.
        NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
        NRF_SDH_SOC_OBSERVER(m_soc_observer, APP_SOC_OBSERVER_PRIO, soc_evt_handler, NULL);
    }
    
    /**@brief Function for initializing all the modules used in this example application.
     */
    static void modules_init(void)
    {
     int status = 0;
     int x;
        // Initialize.
        SEGGER_RTT_Init();
        log_init();
    
        output(CC_NHIB_PIN);
    output(LED_RED);
    output(LED_GREEN);
    output(LED_BLUE);
    
    NRF_GPIO->OUTSET = (1<<CC_NHIB_PIN);
    NRF_GPIO->OUTSET = (1<<LED_RED);
    NRF_GPIO->OUTSET = (1<<LED_GREEN);
    NRF_GPIO->OUTSET = (1<<LED_BLUE);
    
    NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;		// set as input with pullup
    
    /*
        NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000001;		// set as output
        NRF_P0->PIN_CNF[LED_RED] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_GREEN] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_BLUE] = 0x00000001;	// set as output
    
    */
    
    
        for (x = 0; x < 5 ; x++)
        {
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        delay_ms(200);
        NRF_P0->OUTSET = (1<<(LED_GREEN));
         delay_ms(200);
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        }
        NRF_P0->OUTSET = (1<<(LED_GREEN));
        CC3100_disable();
    
     //   NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[0] = 0x00010001;	
     
         NRF_P0->PIN_CNF[BUTTON_2] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[1] = 0x00020001|((BUTTON_2)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001;	
    
            
    
         gpio_init();
        // APP_GPIOTE_INIT(1);
       
       // initGPIOINT();
     // gpio_init();
     //  initGPIOINT();
        NRF_LOG_INFO("GPIO Init completed.\r\n");
      //  timer_init();
         NRF_LOG_INFO("lOGGING started.\r\n");
    status = SEGGER_RTT_WriteString(0, "writing to channel 0");
       // buttons_leds_init(&m_erase_bonds);
      //  power_management_init();
      //  ble_stack_init();
      //  gatt_init();
      //  peer_manager_init();
      //  scan_init();
       // scan_filters_set();
    }
    
    
    // Simplelink handlers and functions
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        if(pWlanEvent == NULL)
        {
            CLI_Write((_u8 *)" [WLAN EVENT] NULL Pointer Error \n\r");
            return;
        }
        
        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
    
                /*
                 * Information about the connected AP (like name, MAC etc) will be
                 * available in 'slWlanConnectAsyncResponse_t' - Applications
                 * can use it if required
                 *
                 * slWlanConnectAsyncResponse_t *pEventData = NULL;
                 * pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
                 *
                 */
                   CLI_Write((_u8 *)" WLAN connect event. \n\r");
            }
            break;
    
            case SL_WLAN_DISCONNECT_EVENT:
            {
                slWlanConnectAsyncResponse_t*  pEventData = NULL;
    
                CLR_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;
    
                /* If the user has initiated 'Disconnect' request, 'reason_code' is SL_USER_INITIATED_DISCONNECTION */
                if(SL_WLAN_DISCONNECT_USER_INITIATED_DISCONNECTION == pEventData->reason_code)
                {
                    CLI_Write((_u8 *)" Device disconnected from the AP on application's request \n\r");
                }
                else
                {
                    CLI_Write((_u8 *)" Device disconnected from the AP on an ERROR..!! \n\r");
                }
            }
            break;
    
            default:
            {
                CLI_Write((_u8 *)" [WLAN EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    /*!
        \brief This function handles events for IP address acquisition via DHCP
               indication
    
        \param[in]      pNetAppEvent is the event passed to the handler
    
        \return         None
    
        \note
    
        \warning
    */
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if(pNetAppEvent == NULL)
        {
            CLI_Write((_u8 *)" [NETAPP EVENT] NULL Pointer Error \n\r");
            return;
        }
     
        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;
    
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_GatewayIP = pEventData->gateway;
            }
            break;
    
            default:
            {
                CLI_Write((_u8 *)" [NETAPP EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    /*!
        \brief This function handles callback for the HTTP server events
    
        \param[in]      pHttpEvent - Contains the relevant event information
        \param[in]      pHttpResponse - Should be filled by the user with the
                        relevant response information
    
        \return         None
    
        \note
    
        \warning
    */
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent,
                                      SlHttpServerResponse_t *pHttpResponse)
    {
        /*
         * This application doesn't work with HTTP server - Hence these
         * events are not handled here
         */
        CLI_Write((_u8 *)" [HTTP EVENT] Unexpected event \n\r");
    }
    
    
    /*!
        \brief This function handles ping report events
    
        \param[in]      pPingReport holds the ping report statistics
    
        \return         None
    
        \note
    
        \warning
    */
    static void SimpleLinkPingReport(SlPingReport_t *pPingReport)
    {
        SET_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
    
        if(pPingReport == NULL)
        {
            CLI_Write((_u8 *)" [PING REPORT] NULL Pointer Error\r\n");
            return;
        }
    
        g_PingPacketsRecv = pPingReport->PacketsReceived;
    }
    
    /*!
        \brief This function handles general error events indication
    
        \param[in]      pDevEvent is the event passed to the handler
    
        \return         None
    */
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
    {
        /*
         * Most of the general errors are not FATAL are are to be handled
         * appropriately by the application
         */
        CLI_Write((_u8 *)" [GENERAL EVENT] handler \n\r");
    
        if(pDevEvent == NULL)
        {
            CLI_Write((_u8 *)" [General EVENT] NULL Pointer Error \n\r");
            return;
        }
     
    
    /*
    
     SL_DEVICE_GENERAL_ERROR_EVENT = 1,
        SL_DEVICE_ABORT_ERROR_EVENT,
        SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT,
        SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE,
        SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN,
        SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT,
        SL_DEVICE_ERROR_MAX
    
        */
    
        switch(pDevEvent->Event)
        {
    
        case SL_DEVICE_GENERAL_ERROR_EVENT :
    
         CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_GENERAL_ERROR_EVENT \n\r");
    break;
        case SL_DEVICE_ABORT_ERROR_EVENT :
        CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_ABORT_ERROR_EVENT\n\r");
        break;
    
        case SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT\n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE\n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN \n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT\n\r");
    break;
        case SL_DEVICE_ERROR_MAX :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_ERROR_MAX\n\r");
    break;
    
      default :
      CLI_Write((_u8 *)" [GENERAL EVENT] handler number %d \n\r", pDevEvent->Event );
    
        }
    }
    
    /*!
        \brief This function handles socket events indication
    
        \param[in]      pSock is the event passed to the handler
    
        \return         None
    */
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
        /*
         * This application doesn't work w/ socket - Hence not handling these events
         */
        CLI_Write((_u8 *)" [SOCK EVENT] Unexpected event \n\r");
    }
    /*
     * ASYNCHRONOUS EVENT HANDLERS -- End
     */
    
     //****End of Simplelink handlers and functions
    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    void ReadVersion(void)
    {
    	SlVersionFull 		ver;
        	_u8 				pConfigOpt, pConfigLen;
    	_i32         		retVal = 0;
    	
    	/* read the version and print it on terminal */
    	pConfigOpt = SL_DEVICE_GENERAL_VERSION;
    	pConfigLen = sizeof(SlVersionFull);
    	retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&pConfigOpt,&pConfigLen,(_u8 *)(&ver));
    
    	if(retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nReading version failed. Error code: %d\r\n", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    	}
    
    	if (ver.ChipFwAndPhyVersion.ChipId & 0x10)
    		CLI_Write((_u8 *)"\r\nThis is a CC3200");
    	else
    		CLI_Write((_u8 *)"\r\nThis is a CC3100");
    
    	if (ver.ChipFwAndPhyVersion.ChipId & 0x2)
    		CLI_Write((_u8 *)"Z device\r\n");
    	else
    		CLI_Write((_u8 *)"R device\r\n");
    
    	sprintf(printBuffer, "NWP %d.%d.%d.%d\n\rMAC 31.%d.%d.%d.%d\n\rPHY %d.%d.%d.%d\n\r\n\r", \
    			(_u8)ver.NwpVersion[0],(_u8)ver.NwpVersion[1],(_u8)ver.NwpVersion[2],(_u8)ver.NwpVersion[3], \
    				 (_u8)ver.ChipFwAndPhyVersion.FwVersion[0],(_u8)ver.ChipFwAndPhyVersion.FwVersion[1], \
    				 (_u8)ver.ChipFwAndPhyVersion.FwVersion[2],(_u8)ver.ChipFwAndPhyVersion.FwVersion[3], \
    				 ver.ChipFwAndPhyVersion.PhyVersion[0],(_u8)ver.ChipFwAndPhyVersion.PhyVersion[1], \
    				 ver.ChipFwAndPhyVersion.PhyVersion[2],(_u8)ver.ChipFwAndPhyVersion.PhyVersion[3]);
    
    	CLI_Write((_u8 *)printBuffer);
    }
     cc3100_fw()
     {
     i32         fileHandle = -1;
    
     _u32        Token = 0;
      _i32       retVal = 0;
        _u32     remainingLen, movingOffset, chunkLen;
    #define FORMAT_ENABLE = 1
    
      /* Initializing the CC3100 device */
    
      
        sl_Start(0, 0, 0);
    
     
    
        /* create/open the servicepack file for 128KB with rollback, secured and public write */
    	CLI_Write((_u8 *)"\r\nOpenning ServicePack file");
    	retVal = sl_FsOpen("/sys/servicepack.ucf" ,
    					   FS_MODE_OPEN_CREATE(LEN_128KB, _FS_FILE_OPEN_FLAG_SECURE | _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
    					   &Token, &fileHandle);
    	if(retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nCannot open ServicePack file. Error code: %d", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    		return -1;
    	}
    
    	/* program the servicepack */
    	CLI_Write((_u8 *)"\r\nProgramming ServicePack file");
    
    	remainingLen = sizeof(ota_1_0_1_13_2_11_0_1_ucf);
    	movingOffset = 0;
    	chunkLen = (_u32)find_min(CHUNK_LEN, remainingLen);
    
    	/* Flashing must be done in 1024 bytes chunks */
    	do
    	{
    		retVal = sl_FsWrite(fileHandle, movingOffset, (_u8 *)&ota_1_0_1_13_2_11_0_1_ucf[movingOffset], chunkLen);
    		if (retVal < 0)
    		{
    			sprintf(printBuffer, "\r\nCannot program ServicePack file. Error code: %d", (int)retVal);
    			CLI_Write((_u8 *)printBuffer);
    
    			//turnLedOn(LED1);
    			return -1;
    		}
    
    		remainingLen -= chunkLen;
    		movingOffset += chunkLen;
    		chunkLen = (_u32)find_min(CHUNK_LEN, remainingLen);
    	}while (chunkLen > 0);
    
    	/* close the servicepack file */
    	CLI_Write((_u8 *)"\r\nClosing ServicePack file");
    	retVal = sl_FsClose(fileHandle, 0, (_u8 *)ota_1_0_1_13_2_11_0_1_ucf, sizeof(ota_1_0_1_13_2_11_0_1_ucf));
    
    	if (retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nCannot close ServicePack file. Error code: %d", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    		return -1;
    	}
    
    	CLI_Write((_u8 *)"\r\nServicePack successfuly programmed\r\n\r\n");
    
    	/* Turn On the Green LED */
    	//turnLedOn(LED2);
    
    	CLI_Write((_u8 *)"Restarting CC3100... ");
    	/* Stop the CC3100 device */
    	sl_Stop(0xFF);
    
    	/* Initializing the CC3100 device */
    	sl_Start(0, 0, 0);
    
    	ReadVersion();
    
    	return 0;
    
    
     }
    
    void initGPIOINT(void)
    {
        ret_code_t err_code;
    	g_btn_state = (BTN_STATE_IDLE);
    
    	NRF_GPIOTE->EVENTS_IN[0] = 0;
    	NRF_GPIOTE->EVENTS_IN[1] = 0;
     
    	
    	NRF_P0->PIN_CNF[PBTN_PIN] = 0x0000000C;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00020001|((PBTN_PIN)<<8);	// event mode, high to low transition
    	
    	
    	NRF_GPIOTE->INTENCLR = 0x00000002;	
    	NRF_GPIOTE->INTENSET = 0x00000001;									
        NVIC_EnableIRQ(GPIOTE_IRQn);										
    
    #ifdef SYSTEM_DEBUG
    	printUART0("-> GPIOINT: init [DONE]\n",0);
    #endif
    
    }
    void Button_IRQHandler(void)
    {/// GPIOTE IRQ service routine
      
      nrf_drv_gpiote_out_toggle(LED_RED);
    
       if (startup) return;
    	
    	NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		//NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	
    	
    	
    }
    
    void CC3100_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	
    	chkCC3100IRQ();
          //  NRF_GPIOTE->EVENTS_IN[0] = 0;
    }
    
    
    
    void gpio_init(void)
    {
        ret_code_t err_code;
    
         // APP_GPIOTE_INIT(1);
    
         if (!nrf_drv_gpiote_is_init())
            {
                    err_code = nrf_drv_gpiote_init();
                    APP_ERROR_CHECK(err_code);
            }
            
    
        nrf_drv_gpiote_out_config_t out_config = GPIOTE_CONFIG_OUT_SIMPLE(true);
    
            err_code = nrf_drv_gpiote_out_init(CC_NRST_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
          err_code = nrf_drv_gpiote_out_init(LED_RED, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
            err_code = nrf_drv_gpiote_out_init(CC_NHIB_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
         // Make a configuration for input pins. This is suitable for both pins in this example.
        nrf_drv_gpiote_in_config_t in_config = {// = GPIOTE_CONFIG_IN_SENSE_LOTOHI(true);
          .is_watcher = false,                        \
           .hi_accuracy = true,                     \
            .pull = NRF_GPIO_PIN_PULLUP,                \
            .sense = NRF_GPIOTE_POLARITY_LOTOHI
            };
    
         err_code = nrf_drv_gpiote_in_init(CC_IRQ_PIN, &in_config, CC3100_IRQHandler);
        APP_ERROR_CHECK(err_code);
       
        in_config.hi_accuracy = true;
        in_config.pull = NRF_GPIO_PIN_PULLUP;
        in_config.sense = NRF_GPIOTE_POLARITY_HITOLO;
        
         err_code = nrf_drv_gpiote_in_init(BUTTON_2, &in_config, Button_IRQHandler);
        APP_ERROR_CHECK(err_code);
    
        //    nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
          nrf_drv_gpiote_in_event_enable(BUTTON_2, true);
        
      
     
    }
    
    static void example_gpiote_event_handler(uint32_t event_pins_low_to_high, uint32_t event_pins_high_to_low)
    {
      nrf_drv_gpiote_out_toggle(LED_RED);
    
    }
    
    void newint(void)
    {
    
    uint32_t  low_to_high_bitmask = (0x00000000 | (3<<26)); // Bitmask to be notified of transition from low to high for GPIO 0-3
    uint32_t  high_to_low_bitmask = (0x00000000 | (3<<26)); // Bitmask to be notified of transition from high to low for GPIO 0-2
    uint32_t retval;
    retval = app_gpiote_user_register(&m_example_user_id,
                                      low_to_high_bitmask,
                                      high_to_low_bitmask,
                                      example_gpiote_event_handler);
    if (retval != NRF_SUCCESS)
    {
        // Failed to register with user with GPIO module!
    }
    
    }
    
    int main(void)
    {
    
        // Initialize.
    
       // P_EVENT_HANDLER = &SimpleLinkGeneralEventHandler;
        
        modules_init();
      //  whitelist_load();
    
        // Start execution.
        NRF_LOG_INFO("GATT Service server started.\r\n");
      //  scanning_start(&m_erase_bonds);
    
      // GPIOTE user identifier for the example module.
    
    // GPIOTE event handler.
    
    
    
      //cc3100_fw();
      //newint();
     
     CC3100_InterruptEnable();
    
        // Enter main loop.
        for (;;)
        {
           __NOP();
    
        
        
        //    idle_state_handle();
             int32_t retVal = -1;
    
        retVal = initializeAppVariables();
        ASSERT_ON_ERROR(retVal);
    
        /* Stop WDT and initialize the system-clock of the MCU */
      //  stopWDT();
      //  initClk();
    
        /* Configure command line interface */
       // CLI_Configure();
    
        displayBanner();
    
        /*
         * Following function configures the device to default state by cleaning
         * the persistent settings stored in NVMEM (viz. connection profiles &
         * policies, power policy etc)
         *
         * Applications may choose to skip this step if the developer is sure
         * that the device is in its default state at start of application
         *
         * Note that all profiles and persistent settings that were done on the
         * device will be lost
         */
        retVal = configureSimpleLinkToDefaultState();
        if(retVal < 0)
        {
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
                CLI_Write((_u8 *)" Failed to configure the device in its default state \n\r");
    
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device is configured in default state \n\r");
    
        /*
         * Assumption is that the device is configured in station mode already
         * and it is in its default state
         */
        retVal = sl_Stop(SL_STOP_TIMEOUT);
        retVal = sl_Start(0, 0, 0);
        if ((retVal < 0) ||
            (ROLE_STA != retVal) )
        {
            CLI_Write((_u8 *)" Failed to start the device \n\r");
            LOOP_FOREVER();
        }
    
         ReadVersion();
    
        CLI_Write((_u8 *)" Device started as STATION \n\r");
    
        /* Connecting to WLAN AP */
        retVal = establishConnectionWithAP();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Failed to establish connection w/ an AP \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Connection established w/ AP and IP is acquired \n\r");
        CLI_Write((_u8 *)" Pinging...! \n\r");
    
        retVal = checkLanConnection();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Device couldn't connect to LAN \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device successfully connected to the LAN\r\n");
    
        retVal = checkInternetConnection();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Device couldn't connect to the internet \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device successfully connected to the internet \n\r");
        return 0;
        }
    }
    
    static int32_t establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    
    /*!
        \brief This function checks the LAN connection by pinging the AP's gateway
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 checkLanConnection()
    {
        SlPingStartCommand_t pingParams = {0};
        SlPingReport_t pingReport = {0};
    
        _i32 retVal = -1;
    
        CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    
        /* Set the ping parameters */
        pingParams.PingIntervalTime = PING_INTERVAL;
        pingParams.PingSize = PING_PKT_SIZE;
        pingParams.PingRequestTimeout = PING_TIMEOUT;
        pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
        pingParams.Flags = 0;
        pingParams.Ip = g_GatewayIP;
    
        /* Check for LAN connection */
        retVal = sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                                     (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while(!IS_PING_DONE(g_Status)) { _SlNonOsMainLoopTask(); }
    
        if(0 == g_PingPacketsRecv)
        {
            /* Problem with LAN connection */
            ASSERT_ON_ERROR(LAN_CONNECTION_FAILED);
        }
    
        /* LAN connection is successful */
        return SUCCESS;
    }
    
    /*!
        \brief This function checks the internet connection by pinging
               the external-host (HOST_NAME)
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 checkInternetConnection()
    {
        SlPingStartCommand_t pingParams = {0};
        SlPingReport_t pingReport = {0};
    
        _u32 ipAddr = 0;
    
        _i32 retVal = -1;
    
        CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    
        /* Set the ping parameters */
        pingParams.PingIntervalTime = PING_INTERVAL;
        pingParams.PingSize = PING_PKT_SIZE;
        pingParams.PingRequestTimeout = PING_TIMEOUT;
        pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
        pingParams.Flags = 0;
        pingParams.Ip = g_GatewayIP;
    
        /* Check for Internet connection */
        retVal = sl_NetAppDnsGetHostByName((_i8 *)HOST_NAME, pal_Strlen(HOST_NAME), &ipAddr, SL_AF_INET);
        ASSERT_ON_ERROR(retVal);
    
        /* Replace the ping address to match HOST_NAME's IP address */
        pingParams.Ip = ipAddr;
    
        /* Try to ping HOST_NAME */
        retVal = sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                                     (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while(!IS_PING_DONE(g_Status)) { _SlNonOsMainLoopTask(); }
    
        if (0 == g_PingPacketsRecv)
        {
            /* Problem with internet connection*/
            ASSERT_ON_ERROR(INTERNET_CONNECTION_FAILED);
        }
    
        /* Internet connection is successful */
        return SUCCESS;
    }
    
    /*!
        \brief This function initializes the application variables
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 initializeAppVariables()
    {
        g_Status = 0;
        g_PingPacketsRecv = 0;
        g_GatewayIP = 0;
    
        return SUCCESS;
    }
    
    /*!
        \brief This function displays the application's banner
    
        \param      None
    
        \return     None
    */
    static void displayBanner()
    {
        CLI_Write((_u8 *)"\n\r\n\r");
        CLI_Write((_u8 *)" Getting started with station application - Version ");
        CLI_Write((_u8 *) APPLICATION_VERSION);
        CLI_Write((_u8 *)"\n\r*******************************************************************************\n\r");
    }
    

    Here is the supporting .c file for the spi functions :
    #include "stdint.h"
    #include "sl_common.h"
    
    #include "medsense.h"
    #include "simplelink.h"
    #include "nrf_drv_gpiote.h"
    #include "nrf_delay.h"
    
    //#include "user.h"
    
    
    
    
    
    const uint8_t g_firmware_version[6] = "1.0.3";
    
    volatile uint8_t g_led_blink_pin;
    volatile uint32_t g_led_blink_period;
    volatile uint32_t g_led_blink_timer;
    volatile uint8_t g_led_flag;
    
    volatile uint8_t g_flash_sms;
    volatile uint32_t g_flash_timer;
    const uint32_t FLASH_USER_SIGN[FLASH_USER_SIGN_WSIZE] = {0x474F4749, 0x4341534D, 0x49523230, 0x31360000};
    volatile uint32_t g_flash_page[FLASH_PAGE_SIZE_IN_WORDS];
    
    static volatile SlSockAddrIn_t  Addr;
    static volatile SlSockAddrIn_t  LocalAddr;
    static volatile SlSockAddrIn_t  Rem_Addr;
    
    //void 		SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent);
    //void 		SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent);
    //void 		SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent, SlHttpServerResponse_t *pHttpResponse);
    void 		SimpleLinkPingReport(SlPingReport_t *pPingReport);
    void 		SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent);
    //void 		SimpleLinkSockEventHandler(SlSockEvent_t *pSock);
    
    volatile uint8_t g_btn_state;
    
    volatile uint8_t g_ble_rx_buff[BLE_RX_BUFF_SIZE];
    volatile uint16_t g_ble_rx_buff_len;
    volatile uint8_t g_ble_rx_data[BLE_RX_DATA_BUFF_SIZE];
    volatile uint16_t g_ble_rx_data_widx;
    volatile uint16_t g_ble_rx_data_ridx;
    volatile uint8_t g_ble_tx_buff[WIFI_BUFF_SIZE];
    volatile uint16_t g_blef_tx_count;
    
    volatile uint8_t g_flash_update;
    
    
    volatile uint8_t g_wifi_tx_buff[WIFI_BUFF_SIZE];
    volatile uint8_t g_wifi_rx_buff[WIFI_RX_BUFF_SIZE];
    volatile uint8_t g_wifi_pkt[WIFI_BUFF_SIZE];
    volatile uint16_t g_wifi_rx_buff_widx;
    volatile uint16_t g_wifi_rx_buff_ridx;
    volatile uint8_t g_wifi_status;
    volatile uint8_t g_wifi_error;
    volatile uint8_t g_wifi_mode;
    volatile uint8_t g_wifi_ssid[WIFI_SSID_SIZE];
    volatile uint8_t g_wifi_passwd[WIFI_PASSWD_SIZE];
    volatile uint32_t g_wifi_port;
    volatile uint32_t g_wifi_enc;
    volatile uint32_t g_wifi_remote_server_ip;
    volatile uint8_t g_device_name[DEVICE_NAME_SIZE];
    volatile uint8_t g_device_id[DEVICE_ID_SIZE];
    volatile uint8_t g_flash_write_data[FLASH_WRITE_DATA_SIZE];
    volatile uint8_t g_wifi_local_ip_str[20];
    volatile uint8_t g_wifi_remote_server_ip_str[20];
    volatile int16_t g_wifi_remote_cli_socket = -1;
    
    //#include "wifi.h"
    
    volatile int16_t g_wifi_ser_socket = -1;
    volatile int16_t g_wifi_local_cli_socket = -1;
    volatile uint8_t g_wifi_data[WIFI_BUFF_SIZE];
    volatile uint16_t g_wifi_rx_buff_byte_cnt;
    volatile uint16_t g_wifi_pkt_len;
    volatile uint8_t g_wifi_pkt_type;
    volatile uint32_t g_wifi_rc_conn_timer;
    
    typedef struct
    {
      unsigned char     connection_type;/* 0-STA,3-P2P_CL */
      unsigned char     ssid_len;
      unsigned char     ssid_name[32];
      unsigned char     go_peer_device_name_len;
      unsigned char     go_peer_device_name[32];
      unsigned char     bssid[6];
      unsigned char     reason_code;
      unsigned char     padding[2];
    } sl_protocol_wlanConnectAsyncResponse_t;
    
    
    volatile P_EVENT_HANDLER        pIrqEventHandler = 0;
    
    volatile bool IntIsMasked;
    
    
    
    const uint8_t c_wifi_preambule[3] = {0xA5, 0xAA, 0x5A};
    
    /*
    void CC3100_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    */
    void ASSERT_ON_ERROR(retVal)
    {
        NRF_LOG_INFO("Assert from simplelink function : %d", retVal);
        
       
    }
    void CC3100_disable()
    {
    	CC3100_NHIB_LOW;
          //  nrf_drv_gpiote_out_clear(CC_NHIB_PIN);
    	delay_ms(100);
    }
    
    
    void do_CC3100_NRST_HIGH(void)
    {
        CC3100_NRST_HIGH;
        // nrf_drv_gpiote_set(CC_NHIB_PIN);
    }
    
    void output(int pin)
    {
    	  NRF_GPIO->PIN_CNF[pin] = (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) |
                                       (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) |
                                       (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos) |
                                       (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) |
                                       (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
    }
    void CC3100_enable()
    {
    	CC3100_NHIB_HIGH;
           // nrf_drv_gpiote_out_set(CC_NHIB_PIN);
    	delay_ms(500);
    }
    
    void CC3100_InterruptEnable()
    {	
    	//NVIC_DisableIRQ(GPIOTE_IRQn);
            //NRF_GPIOTE->INTENSET = 0x00000002;	
    	//NRF_GPIOTE->EVENTS_IN[1] = 0;									
        //NVIC_EnableIRQ(GPIOTE_IRQn);
    
         nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
         
    }
    
    void CC3100_InterruptDisable()
    {
    	//NVIC_DisableIRQ(GPIOTE_IRQn);
    	//NRF_GPIOTE->INTENCLR = 0x00000002;	
    	//NRF_GPIOTE->EVENTS_IN[1] = 0;								
        NVIC_EnableIRQ(GPIOTE_IRQn);	
    
        nrf_drv_gpiote_in_event_disable(CC_IRQ_PIN);
    }
    
    void MaskIntHdlr()
    {
    	IntIsMasked = TRUE;
    }
    
    void UnMaskIntHdlr()
    {
    	IntIsMasked = FALSE;
    }
    
    void Delay(unsigned long interval)
    {/// system delay func
    	delay_ms(interval);
    }
    
    void chkCC3100IRQ(void)
    {
    	if(pIrqEventHandler)
    	{
    		pIrqEventHandler(0);
    	}
    }
    
    
    
    int spi_Close(Fd_t fd)
    {
        CC3100_InterruptDisable();
    
        return 0;
    }
    
    Fd_t spi_Open(char *ifName, unsigned long flags)
    {
    	NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000301;
    	CC3100_NHIB_LOW;
           // nrf_drv_gpiote_out_clear(CC_NHIB_PIN);
    	
    	NRF_P0->PIN_CNF[CC_CS_PIN] = 0x00000301;
    	SPI1_CS_HIGH;
    	
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// init SPI
    	//------------------------------------------------------------------
    	NRF_P0->PIN_CNF[CC_SCK_PIN] = 0x00000001;							// set as output
    	NRF_P0->PIN_CNF[CC_MISO_PIN] = 0x00000000;							// set as input
    	NRF_P0->PIN_CNF[CC_MOSI_PIN] = 0x00000001;							// set as output
    
    	NRF_SPI1->PSEL.SCK  = (CC_SCK_PIN);										
    	NRF_SPI1->PSEL.MISO = (CC_MISO_PIN);										
    	NRF_SPI1->PSEL.MOSI = (CC_MOSI_PIN);
    	
        NRF_SPI1->FREQUENCY = (SPI_DATARATE_1Mbps);							// set SPI clock rate
    	NRF_SPI1->CONFIG  = 0x00;											// Tx MSB first, CPHA_Leading, CPOL_ActiveHigh
        NRF_SPI1->EVENTS_READY = 0x00;										// clear the status flags
        NRF_SPI1->ENABLE = 0x00000001;										// enable SPI0
    
    
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// setup IRQ on falling edge
    	//------------------------------------------------------------------
    	NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;							// set as input with pullup
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	NRF_GPIOTE->CONFIG[1] = 0x00010001; // event mode, low to high transition
    	
    	delay_ms(100);
    	CC3100_InterruptEnable();
    
        return NONOS_RET_OK;
    }
    
    
    int spi_Write(Fd_t fd, unsigned char *pBuff, int len)
    {
        uint16_t k;
    
    	SPI1_CS_LOW;
    	//delay_us(5);
    	
    	for(k=0;k<len;k++)
    	{
    		txByteSPI1(pBuff[k]); 											// write data SPI data register
    		//delay_us(2);													// must be here as seen by spi test routine
    	}
    	
        SPI1_CS_HIGH;
    	//delay_us(5);
    	
        return len;
    }
    
    int spi_Read(Fd_t fd, unsigned char *pBuff, int len)
    {
        uint16_t k;
    
        SPI1_CS_LOW;
    	//delay_us(5);
        
        for(k=0;k<len;k++)
    	{
    		pBuff[k] = rxByteSPI1();
    		nrf_delay_us(1);													// must be here as seen by spi test routine
    	}
    	
        SPI1_CS_HIGH;
    	//delay_us(5);
    	
        return len;
    }
    
    int32_t initializeAppVariables(void)
    {
        g_Status = 0;
        g_PingPacketsRecv = 0;
        g_StationIP = 0;
        g_GatewayIP = 0;
    
        return SUCCESS;
    }
    
    int32_t  configureSimpleLinkToDefaultState()
    {
        SlVersionFull   ver = {0};
        _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};
    
        _u8           val = 1;
        _u8           configOpt = 0;
        _u8           configLen = 0;
        _u8           power = 0;
    
        _i32          retVal = -1;
        _i32          mode = -1;
    
        mode = sl_Start(0, 0, 0);
        ASSERT_ON_ERROR(mode);
    
        /* If the device is not in station-mode, try configuring it in station-mode */
        if (ROLE_STA != mode)
        {
            if (ROLE_AP == mode)
            {
                /* If the device is in AP mode, we need to wait for this event before doing anything */
                while(!IS_IP_ACQUIRED(g_Status)) { _SlNonOsMainLoopTask(); }
            }
    
            /* Switch to STA role and restart */
            retVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(retVal);
    
            retVal = sl_Stop(SL_STOP_TIMEOUT);
            ASSERT_ON_ERROR(retVal);
    
            retVal = sl_Start(0, 0, 0);
            ASSERT_ON_ERROR(retVal);
    
            /* Check if the device is in station again */
            if (ROLE_STA != retVal)
            {
                /* We don't want to proceed if the device is not coming up in station-mode */
                ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE);
            }
        }
    
        /* Get the device's version-information */
        configOpt = SL_DEVICE_GENERAL_VERSION;
        configLen = sizeof(ver);
        retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (_u8 *)(&ver));
        ASSERT_ON_ERROR(retVal);
    
        /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */
        retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Remove all profiles */
        retVal = sl_WlanProfileDel(0xFF);
        ASSERT_ON_ERROR(retVal);
    
        /*
         * Device in station-mode. Disconnect previous connection if any
         * The function returns 0 if 'Disconnected done', negative number if already disconnected
         * Wait for 'disconnection' event if 0 is returned, Ignore other return-codes
         */
        retVal = sl_WlanDisconnect();
        if(0 == retVal)
        {
            /* Wait */
            while(IS_CONNECTED(g_Status)) { _SlNonOsMainLoopTask(); }
        }
    
        /* Enable DHCP client*/
        retVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);
        ASSERT_ON_ERROR(retVal);
    
        /* Disable scan */
        configOpt = SL_SCAN_POLICY(0);
        retVal = sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Set Tx power level for station mode
           Number between 0-15, as dB offset from max power - 0 will set maximum power */
        power = 0;
        retVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (_u8 *)&power);
        ASSERT_ON_ERROR(retVal);
    
        /* Set PM policy to normal */
        retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Unregister mDNS services */
        retVal = sl_NetAppMDNSUnRegisterService(0, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Remove  all 64 filters (8*8) */
        pal_Memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
        retVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
                           sizeof(_WlanRxFilterOperationCommandBuff_t));
        ASSERT_ON_ERROR(retVal);
    
        retVal = sl_Stop(SL_STOP_TIMEOUT);
        ASSERT_ON_ERROR(retVal);
    
        retVal = initializeAppVariables();
        ASSERT_ON_ERROR(retVal);
    
        return retVal; /* Success */
    }
    /*
    void bsp_board_led_on(uint32_t led_idx)
    {
     // NRF_LOG_INFO("Turn on LED idx here .");
    }
    void bsp_board_leds_on(void)
    {
      //NRF_LOG_INFO("Turn on LEDs idx here .");
    }
    void bsp_board_leds_off(void)
    {
      //NRF_LOG_INFO("Turn off LEDs idx here .");
    }
    void bsp_board_led_off(uint32_t led_idx)
    {
     // NRF_LOG_INFO("Turn off LED idx here .");
    }
    void bsp_board_led_invert(uint32_t led_idx)
    {
    //  NRF_LOG_INFO("Turn invert LED idx here .");
    }
    bool bsp_board_led_state_get(uint32_t led_idx)
    {
    //  NRF_LOG_INFO("Get LED board state here .");
      return true;
    }
    void bsp_board_init(uint32_t led_idx)
    {
      //NRF_LOG_INFO("Get LED board init state here .");
    }
    
    uint32_t bsp_board_pin_to_button_idx(uint32_t pin_number)
    {
     //NRF_LOG_INFO("bsp_board_pin_to_button_idx function  .");
    }
    
    uint32_t bsp_board_button_idx_to_pin(uint32_t pin_number)
    {
     // NRF_LOG_INFO("bsp_board_button_idx_to_pin function  .");
    }
    */
    void initWIFI(void)
    {/// init CC3100 reset pin and socket id
    	g_wifi_rx_buff_widx = 0;
    	g_wifi_rx_buff_ridx = (WIFI_RX_BUFF_MASK);
    	g_wifi_status = (WIFI_ENABLED);
    	getStr4AddrMISC((uint8_t *)g_wifi_remote_server_ip_str, g_wifi_remote_server_ip);
    	g_wifi_rc_conn_timer = getRTC2();
    	
    	NRF_P0->PIN_CNF[CC_NRST_PIN] = 0x00000301;
    	CC3100_NRST_HIGH;
    	//g_wifi_mode = (WIFI_MODE_STA);
    	//g_wifi_enc = (SL_SEC_TYPE_WPA);
    	//cpyStrMISC(g_wifi_ssid, "Dune2");
    	//cpyStrMISC(g_wifi_passwd, "palas512");
    	//g_wifi_remote_server_ip = 0xC0A80168;
    	//g_wifi_remote_server_ip = 0xC0A80167;
    	
    	if(g_wifi_mode == (WIFI_MODE_AP))
    	{// configure CC31xx in AP mode
    		g_wifi_error = setAPmodeWIFI((uint8_t *)g_wifi_ssid, (uint8_t *)g_wifi_passwd, g_wifi_port, g_wifi_enc);	
    	}
    	else
    	{// configure CC31xx in STA mode
    		g_wifi_error = setSTAmodeWIFI((uint8_t *)g_wifi_ssid, (uint8_t *)g_wifi_passwd, g_wifi_port, g_wifi_enc);
    	}
    		
    	if(g_wifi_error != (WIFI_OK))
    	{
    		g_wifi_status = (WIFI_DISABLED);
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: failed, rebooting [%x]...\n",g_wifi_mode);
    #endif		
    		if(g_wifi_mode == (WIFI_MODE_STA))
    		{// restore default AP mode
    			setDefaultFLASH();
    		}
    		
    		NVIC_SystemReset();
    	}
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: init completed\n");
    #endif	
    
    }
    
    void rstWIFI(void)
    {/// reset CC3100 chip
    	CC3100_NRST_LOW;
    	delay_ms(5);
    	CC3100_NRST_HIGH;
    }
    
    void powerDownWIFI(void)
    {/// put the wifi module into sleep mode
    	g_wifi_ser_socket = -1;
    	g_wifi_local_cli_socket = -1;
    	g_wifi_remote_cli_socket = -1;
    	CC3100_disable();													// put CC3100 in sleep mode
    }
    
    uint8_t setAPmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc)
    {/// set AP mode for CC3100
    	uint32_t timer;
    	
    	uint32_t utmp32;
    	int16_t socket;
    	uint32_t addr_offset;
    	uint8_t str[4];
    	
    	SlPingStartCommand_t PingParams = {0};
        SlPingReport_t Report = {0};
        _NetCfgIpV4Args_t ipV4 = {0};
        SlNetAppDhcpServerBasicOpt_t dhcpParams = {0};
    
        unsigned char SecType = 0;
        uint32_t mode = ROLE_STA;
        uint32_t retVal = -1;
    
    #ifdef SYSTEM_DEBUG
    	printUART("\n-> WIFI: AP mode setup initiated....\n");
    #endif
    
    
        retVal = initializeAppVariables();									// init CC3100 variables
    	
    	rstWIFI();															
    	
    	
    	CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    	
        retVal = configureSimpleLinkToDefaultState();						// set default state to STA mode, clear all settings
       
        if(retVal != ROLE_STA)
        {
    #ifdef SYSTEM_DEBUG
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
            {
    			printUART("-> WIFI: Failed to configure the device to default state\n");
    		}
    		else
    		{
    			printUART("-> WIFI: Failed!\n");
    		}
    #endif			
            return (WIFI_ERROR_SET_DEF);
        }
    	    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device is configured in default state\n");
    #endif
    	
    	retVal = sl_Start(0, 0, 0);	
        if (retVal == (ROLE_AP))
        {// if the device is in AP mode, we need to wait 
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: device was AP mode...\n");
    #endif
    		timer = getRTC2();
    		while(!IS_IP_AQUIRED(g_Status))									
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
        else
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: device was STA mode...\n");
    #endif
            sl_WlanSetMode(ROLE_AP);										// configure CC3100 to start in AP mode
            sl_Stop(0xFF);													// stop CC3100 device
            mode = sl_Start(0, 0, 0);										// start the CC3100 and check the mode
            
    		timer = getRTC2();											// If the device is in AP mode, we need to wait 
    		while(!IS_IP_AQUIRED(g_Status))									// for this event before doing anything 
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device started in AP mode\n");
    #endif	
    	
    	sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID,
                strlen(ssid), (unsigned char *)ssid);						// set AP SSID for the CC3100 in AP mode
    	
    	sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, 1,			// configure the Security parameter to open for the AP mode
                (unsigned char *)&enc);
    
        sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, strlen(passwd),	// set AP password
                (unsigned char *)passwd);
    
        
        
        ipV4.ipV4 = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_AP);		// set AP address
        getStr4AddrMISC(g_wifi_local_ip_str,ipV4.ipV4); 
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: configuring TCP/IP server ADDR[%s] PORT[%d]...\n",g_wifi_local_ip_str,portNum);
    #endif	    
        ipV4.ipV4Mask = (WIFI_NETWORK_MASK);								// set Network Mask
        ipV4.ipV4Gateway = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_GW);	// set AP Gateway address
        ipV4.ipV4DnsServer = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_DNS);// set AP DNS address
    
        
        sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE,1,sizeof(_NetCfgIpV4Args_t),
                (unsigned char *)&ipV4);									// Configure the Static IP 
    	
    	addr_offset = (WIFI_NETWORK_IP_OFFSET);
        dhcpParams.lease_time      = WIFI_IP_LEASE_TIME;					// set IP address lease time
        dhcpParams.ipv4_addr_start =  addr_offset + (WIFI_NETWORK_IP_DHCP_BEG);	// set the start address of the DHCP server
        dhcpParams.ipv4_addr_last  =  addr_offset + (WIFI_NETWORK_IP_DHCP_END);	// set the end address of the DHCP server
    
        // Configure DHCP address range. This step is necessary if the subnet of the IP is changed 
        sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID);							// apply DHCP IP address parameters							
        sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT,
                sizeof(SlNetAppDhcpServerBasicOpt_t), (unsigned char*)&dhcpParams);
        sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID);
    
    	sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);							// stop the HTTP web server
        g_Status = 0;
    
    
        sl_Stop(0x00FF);													// stop CC3100
        mode = sl_Start(0, 0, 0);											// start CC3100
        if (ROLE_AP == mode)
        {      																// If the device is in AP mode, we need to wait 
    		
    		timer = getRTC2();											// If the device is in AP mode, we need to wait 
    		while(!IS_IP_AQUIRED(g_Status))									// for this event before doing anything 
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
        else
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: unable to start device in AP mode...\n");
    #endif
            return (WIFI_ERROR_CANNOT_RUN_AP);
        }
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device started in AP mode...\n");
    #endif	 
        
    	socket = openSocketWIFI();
        if(socket >= 0)
        {
    		g_wifi_ser_socket = socket;
    #ifdef SYSTEM_DEBUG
    		utmp32 = socket;
    		printUART("-> WIFI: Socket [%d] created\n",utmp32);
    #endif
    	}
    	else
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to open socket\n");
    #endif
    		return (WIFI_ERROR_SERVER_FAILED);
    	}
    	
    	//socket = openSocketWIFI();
    	return (WIFI_OK);
    }
    
    uint8_t setSTAmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc)
    {/// power up and setup the wifi module
    	char str[16];
    	INT32 retVal = -1;
    	int16_t socket;
    	uint32_t utmp32;
    	g_wifi_port = portNum;
    	
    #ifdef SYSTEM_DEBUG
    	printUART("\n-> WIFI: STA mode setup initiated....\n");
    #endif
    	
    	
    	CC3100_disable();
    	CC3100_enable();													// wakeup CC3100
    	retVal = initializeAppVariables();									// init CC3100 variables
    	rstWIFI();															// reset CC3100 just to clear any problems
    	retVal = configureSimpleLinkToDefaultState();						// set default state to STA mode, clear all settings
        if(retVal != ROLE_STA)
        {
    #ifdef SYSTEM_DEBUG
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
            {
    			printUART("-> WIFI: Failed to configure the device to default state\n");
    		}
    		else
    		{
    			printUART("-> WIFI: Failed!\n");
    		}
    #endif			
            return (WIFI_ERROR_SET_DEF);
        }
        
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device is configured in default state\n");
    #endif
    	
    	retVal = sl_Start(0, 0, 0);	
        if ((retVal < 0)||(ROLE_STA != retVal))
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to start the device in STA mode\n");
    #endif
            return (WIFI_ERROR_START_DEV);
        }
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Device started in STA mode\n");
    #endif
        
        
        retVal = establishConnectionWithAP(ssid, passwd, enc);				// connect to remote AP
        if(retVal == (WIFI_ERROR_LAN_CONNECTION_TIMEOUT))
        {
    #ifdef SYSTEM_DEBUG
            printUART("-> WIFI: Failed to establish connection with an AP\n");
    #endif
            return retVal;
        }
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Connection established with an AP and IP is acquired\n");
    #endif	
        
        unsigned char len = sizeof(_NetCfgIpV4Args_t);
    	unsigned char dhcpIsOn = 0;
    	_NetCfgIpV4Args_t ipV4 = {0};
    	sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&dhcpIsOn,&len,(unsigned char *)&ipV4);
    	 
      
        getStr4AddrMISC(g_wifi_local_ip_str, ipV4.ipV4);
    #ifdef SYSTEM_DEBUG  
    	printUART("-> WIFI: Client IP: [%s]\n",g_wifi_local_ip_str);
    #endif	
    
        socket = openSocketWIFI();
        if(socket >= 0)
        {
    		g_wifi_ser_socket = socket;
    #ifdef SYSTEM_DEBUG
    		utmp32 = socket;
    		printUART("-> WIFI: Socket [%d] created\n",utmp32);
    #endif
    	}
    	else
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to open socket\n");
    #endif
    		return (WIFI_ERROR_SERVER_FAILED);
    	}
     
    	//openSocketWIFI();
    	return (WIFI_OK);
    }
    
    uint8_t connect2ServerCC3100(void)
    {// connect to remote server on Internet
    	//if(chk4TimeoutRTC2(g_wifi_rc_conn_timer, 1) == (RTC_KEEP_ALIVE))
    	int32_t r_val;
    	int32_t nonBlocking = 1;
    	int16_t status;
    	
    
    	if(chk4TimeoutRTC2(g_wifi_rc_conn_timer, WIFI_REMOTE_SERVER_CONNECTION_RETRY_PERIOD) == (RTC_KEEP_ALIVE))
    		return (WIFI_ERROR_WAITING4RETRY_TIMEOUT);
    		
    	g_wifi_rc_conn_timer = getRTC2();
    	
    
    	
    	
    	Rem_Addr.sin_family = SL_AF_INET;
    	Rem_Addr.sin_port = sl_Htons(g_wifi_port);
    	//Rem_Addr.sin_addr.s_addr = sl_Ntohl(g_wifi_remote_server_ip);		
    	Rem_Addr.sin_addr.s_addr = sl_Htonl(g_wifi_remote_server_ip);
    	
    	
    	Rem_AddrSize = sizeof(SlSockAddrIn_t);
    	
    #ifdef SYSTEM_DEBUG	
    	uint8_t ip_str[8];
    	getStr4AddrMISC(ip_str, g_wifi_remote_server_ip);
    	printUART("-> WIFI: Creating socket for remote server IP: %s PORT: %d\n",ip_str,g_wifi_port);
    #endif		
    	g_wifi_remote_cli_socket = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); // create socket
    	if(g_wifi_remote_cli_socket < 0)
    	{
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: Error creating socket for remote server %x\n",ip_str);
    #endif		
    		
    		return (WIFI_ERROR_REMOTE_SERVER_SOCKET_FAILED);
    	}
    	
        r_val = sl_Connect(g_wifi_remote_cli_socket, ( SlSockAddr_t *)&Rem_Addr, Rem_AddrSize);			// connect to remote server
        if(r_val < 0)
        {
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: Error connecting to remote server SoID %d RVAL[%d]\n",g_wifi_remote_cli_socket,r_val);
    #endif
    		sl_Close(g_wifi_remote_cli_socket);
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: socket closed %d\n",g_wifi_remote_cli_socket);
    #endif
    		g_wifi_remote_cli_socket = -1;
    		return (WIFI_ERROR_REMOTE_SERVER_DISCONNECTED);
        }
        
        	r_val = sl_SetSockOpt(g_wifi_remote_cli_socket, (SL_SOL_SOCKET), (SL_SO_NONBLOCKING),&nonBlocking, sizeof(nonBlocking));
    	
        
    #ifdef SYSTEM_DEBUG	
        printUART("-> WIFI: Connected to remote server with SID %d\n",g_wifi_remote_cli_socket);
    #endif		
        
        // tx ID info
        //txPktWIFI(g_wifi_remote_cli_socket, WIFI_PKT_REGISTER_DEVICE);
        
        return (WIFI_OK);
    }
    
    int16_t openSocketWIFI(void)
    {/// open new TCP socket
    	int16_t status;
    	int32_t nonBlocking = 1;
    	int16_t sid;
    	uint32_t utmp32;
    	
    	
        LocalAddr.sin_family = SL_AF_INET;									// setup local address and port
        LocalAddr.sin_port = sl_Htons(g_wifi_port);
        LocalAddr.sin_addr.s_addr = 0;
    
        sid = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);						// create socket with unique ID (sid)
        if(sid < 0)
    		return (WIFI_ERROR_CREATE_SOCKET);
    
        // set socket as non-blocking
    	status = sl_SetSockOpt(sid, (SL_SOL_SOCKET), (SL_SO_NONBLOCKING),&nonBlocking, sizeof(nonBlocking));
    	if(status < 0)
        {
            sl_Close(sid);
            return (WIFI_ERROR_SOCKET_NONBLOCKING);							// error: can not set non-blocking mode for socket
        }
    
    	AddrSize = sizeof(SlSockAddrIn_t);
        status = sl_Bind(sid, (SlSockAddr_t *)&LocalAddr, AddrSize);
        if(status<0)
        {
    		sl_Close(sid);
            return (WIFI_ERROR_SOCKET_BINDING);								// error: binding socket
        }
        
        status = sl_Listen(sid, 0);
        if(status<0)
        {
            sl_Close(sid);
            return (WIFI_ERROR_SOCKET_BINDING);								// error: binding socket
        }
    
    
    #ifdef SYSTEM_DEBUG    
    	utmp32 = g_wifi_port;
    	printUART("-> WIFI: Server listening at port [%d]\n",utmp32);
    #endif
    	
        return sid;
    }
    
    static _i32 establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    /*
    static int32_t establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        /*
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    */
    
    uint8_t chkLocalSocketWIFI(void)
    {/// check socket for incomming connections	
    	uint8_t str[32];
    	
    	if(g_wifi_local_cli_socket < 0)											// test if client socket slot is open
    	{
    																	// test if there is pending connection
    		AddrSize = sizeof(SlSockAddrIn_t); 
    		g_wifi_local_cli_socket = sl_Accept(g_wifi_ser_socket, ( struct SlSockAddr_t *)&(Addr), (SlSocklen_t*)&AddrSize);
    	
    		if(g_wifi_local_cli_socket >= 0)
    		{	
    				
    			
    #ifdef SYSTEM_DEBUG
    			getStr4AddrMISC(str, sl_Htonl(Addr.sin_addr.s_addr));
    			printUART("-> WIFI: client SID[%d] --- IP [%s]\n",g_wifi_local_cli_socket, str);
    #endif
    		}
    	}
    		
    	if(g_wifi_local_cli_socket >= 0)
    	{
    		return (WIFI_SOCKET_CONNECTED);
    	}
    	else
    	{
    		return (WIFI_SOCKET_DISCONNECTED);
    	}
    }
    
    uint16_t txMessageWIFI(int16_t socket, uint8_t * dataPtr, uint16_t numBytes)
    {/// send predefined number of bytes if the connection is open, default size by CC3100 internals is 1400 B
    	uint16_t status;
    	
    	if((g_wifi_ser_socket < 0) || (socket < 0))
    		return (WIFI_ERROR_SOCKET_CLOSED);
    	
    	status = sl_Send(socket, dataPtr, numBytes, 0);						// now we send message to remote device
    
    	if(status == 0xFFFF)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Client with SoID[%d] disconnected", socket);
    #endif
    		if(socket == g_wifi_local_cli_socket)
    		{
    			g_wifi_local_cli_socket = -1;
    		}
    		else
    		{
    			g_wifi_remote_cli_socket = -1;
    		}
    		
    		sl_Close(socket);
    		return (WIFI_ERROR_SOCKET_CLOSED);								// close the socket
    	}
    			
    	return (WIFI_OK);
    }
    
    uint16_t rxLocalSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen)
    {/// receive byte, up to buffLen, if connection is open, default size by CC3100 internals is 1400 B
    	uint16_t rxbytes;
    	
    	if((g_wifi_ser_socket < 0) || (g_wifi_local_cli_socket < 0))
    		return 0;
    	
    	
    	rxbytes = sl_Recv(g_wifi_local_cli_socket, dataPtr, buffLen, 0);
    	
    	if(rxbytes == 0)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Local WLAN client with SoID[%d] disconnected...\n", g_wifi_local_cli_socket);
    #endif	
    		sl_Close(g_wifi_local_cli_socket);
    		g_wifi_local_cli_socket = -1;
    				
    		return 0;
    	}
    	
    	if(rxbytes >= buffLen)
    	{
    		rxbytes = 0;
    	}
    				
    	return rxbytes;
    }
    
    uint16_t rxRemoteSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen)
    {/// receive byte, up to buffLen, if connection is open, default size by CC3100 internals is 1400 B
    	uint16_t rxbytes;
    	
    	if((g_wifi_ser_socket < 0) || (g_wifi_remote_cli_socket < 0))
    		return 0;
    	
    	rxbytes = sl_Recv(g_wifi_remote_cli_socket, dataPtr, buffLen, 0);
    	
    	if(rxbytes == 0)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Remote client with SoID[%d] disconnected...\n",g_wifi_remote_cli_socket);
    #endif	
    		sl_Close(g_wifi_remote_cli_socket);
    		g_wifi_remote_cli_socket = -1;	
    		
    		return 0;
    	}
    	
    	if(rxbytes >= buffLen)
    	{
    		rxbytes = 0;
    	}
    				
    	return rxbytes;
    }
    
    
    /*
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
    #ifdef SYSTEM_DEBUG			
    			printUART("-> WIFI: connected to AP...\n");
    #endif			
    			g_wifi_remote_cli_socket = -1;
    			g_wifi_local_cli_socket = -1;
    			
                /*
                 * Information about the connected AP (like name, MAC etc) will be
                 * available in 'sl_protocol_wlanConnectAsyncResponse_t' - Applications
                 * can use it if required
                 *
                 * sl_protocol_wlanConnectAsyncResponse_t *pEventData = NULL;
                 * pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
                 *
                 */
    /*             break;
            }
            case SL_WLAN_DISCONNECT_EVENT:
            {
                sl_protocol_wlanConnectAsyncResponse_t*  pEventData = NULL;
                CLR_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;
    
                /* If the user has initiated 'Disconnect' request, 'reason_code' is SL_USER_INITIATED_DISCONNECTION */
    /*            if(SL_USER_INITIATED_DISCONNECTION == pEventData->reason_code)
                {
                    ////CLI_Write((unsigned char *)" Device disconnected from the AP on application's request \n\r");
                }
                else
                {
                    ////CLI_Write((unsigned char *)" Device disconnected from the AP on an ERROR..!! \n\r");
                }
                
    			g_wifi_remote_cli_socket = -1;
    			g_wifi_local_cli_socket = -1;
    #ifdef SYSTEM_DEBUG			
    			printUART("-> WIFI: disconnected from AP...\n");
    #endif         
                break;
            }
            
    
            case SL_WLAN_STA_CONNECTED_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
    #ifdef SYSTEM_DEBUG			
                printUART("-> WIFI: new STA device connected\n");
    #endif         
            }
            break;
    
            case SL_WLAN_STA_DISCONNECTED_EVENT:
            {
                CLR_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
    #ifdef SYSTEM_DEBUG			
                printUART("-> WIFI: STA device disconnected\n");
    #endif         
    
            }
    		break;
    
            default:
            {
                ////CLI_Write((unsigned char *)" [WLAN EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    */
    /*
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
    	//printUART("SimpleLinkNetAppEventHandler");
        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;
    
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_GatewayIP = pEventData->gateway;
            }
            break;
    
            case SL_NETAPP_IP_LEASED_EVENT :
            {
                g_StationIP = pNetAppEvent->EventData.ipLeased.ip_address;
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
            }
            break;
    
            default:
            {
                ////CLI_Write((unsigned char *)" [NETAPP EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    */
    void SimpleLinkPingReport(SlPingReport_t *pPingReport)
    {
        SET_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = pPingReport->PacketsReceived;
    }
    
    /*
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
    {
    }
    */
    
    /*
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
    }
    */
    /*
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pEvent, SlHttpServerResponse_t *pResponse)
    {
    }
    
    uint16_t getRxBuffCountWIFI(void)
    {
    	if(g_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    	{
    		return 0;
    	}
    	else if(g_wifi_rx_buff_ridx < g_wifi_rx_buff_widx)
    	{
    		return (g_wifi_rx_buff_widx - g_wifi_rx_buff_ridx - 1);
    	}
    	else
    	{
    		return (g_wifi_rx_buff_widx + (WIFI_RX_BUFF_SIZE) - g_wifi_rx_buff_ridx - 1);
    	}
    }
    
    */
    void chkWIFI(void)
    {
    	if(g_wifi_mode == (WIFI_MODE_STA))
    	{
    		if(g_wifi_remote_cli_socket == -1)
    		{// create connection with remote server
    			connect2ServerCC3100();
    		}
    		
    		chkLocalSocketWIFI();
    		
    		if((g_wifi_local_cli_socket < 0)&&(g_wifi_remote_cli_socket < 0))
    			return;
    	}
    	else 
    	{
    		if(chkLocalSocketWIFI() == (WIFI_SOCKET_DISCONNECTED))	
    			return;
    	}
    	
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// check if there is data pending in CC31xx Rx buffer
    	//------------------------------------------------------------------
    	uint16_t rxcnt = rxLocalSocketDataWIFI((uint8_t *)g_wifi_data, WIFI_BUFF_SIZE);							
    	if(rxcnt > 0)
    	{
    		if(rxcnt > (WIFI_BUFF_SIZE))
    			rxcnt = (WIFI_BUFF_SIZE);
    		
    #ifdef SYSTEM_DEBUG		
    		printUART("-> WIFI: Local WLAN socket Rx-ed [%d]B's\n",rxcnt);
    #endif
    		uint16_t k;
    		for(k=0;k<rxcnt;k++)
    		{
    			g_wifi_rx_buff[g_wifi_rx_buff_widx] = g_wifi_data[k];
    			g_wifi_rx_buff_widx++;
    			g_wifi_rx_buff_widx &= (WIFI_RX_BUFF_MASK);
    			
    			//printUART("%xb ",g_wifi_data[k]);
    		}
    		//printUART("\n");
    	}
    	
    	rxcnt = rxRemoteSocketDataWIFI((uint8_t *)g_wifi_data, WIFI_BUFF_SIZE);							
    	if(rxcnt > 0)
    	{
    		if(rxcnt > (WIFI_BUFF_SIZE))
    			rxcnt = (WIFI_BUFF_SIZE);
    		
    #ifdef SYSTEM_DEBUG		
    		printUART("-> WIFI: Remote server socket Rx-ed [%d]B's\n",rxcnt);
    #endif
    		uint16_t k;
    		for(k=0;k<rxcnt;k++)
    		{
    			g_wifi_rx_buff[g_wifi_rx_buff_widx] = g_wifi_data[k];
    			g_wifi_rx_buff_widx++;
    			g_wifi_rx_buff_widx &= (WIFI_RX_BUFF_MASK);
    			
    			//printUART("%xb ",g_wifi_data[k]);
    		}
    		//printUART("\n");
    	}
    		
    	// check if there is data in Rx buffer
    	g_wifi_rx_buff_byte_cnt = getRxBuffCountWIFI();
    	if(g_wifi_rx_buff_byte_cnt < 8)
    		return;
    		
    	// check if there is at least one packet in rx buffer, if there is
    	// get packet start and stop index in 
    	uint8_t res = getNextPktWIFI();
    	if(res != (WIFI_PACKET_FOUND))
    		return;
    		
    	switch(g_wifi_pkt_type)
    	{
    		case(WIFI_PKT_SET_STA_CONFIG):
    		{// extract STA configuration information and reboot device to start in STA mode
    #ifdef SYSTEM_DEBUG
    			printUART("-> WIFI: setting new STA info...\n");
    #endif				
    			//writeDataFLASH(FLASH_WRITE_NEW_STA_INFO, (uint8_t *)g_wifi_pkt);
    			g_flash_update = (FLASH_UPDATE_STA_INFO);
    			
    			break;
    		}
    		case(WIFI_PKT_FORCE_AP_MODE):
    		{//
    #ifdef SYSTEM_DEBUG
    			printUART("-> WIFI: forcing AP mode...\n");
    #endif
    			setDefaultFLASH();
    			NVIC_SystemReset();
    			break;
    		}
    		default:
    		{
    #ifdef SYSTEM_DEBUG		
    			printUART("-> WIFI: unknown packet TYPE[%xb]B\n",g_wifi_pkt[WIFI_PKT_TYPE_IDX]);
    #endif			
    			break;
    		}
    	}
    }
    
    uint8_t getNextPktWIFI(void)
    {
    	uint8_t csum[2] = {0x00,0x00};
    	uint16_t csum_idx = 0;
    	uint8_t flag = 1;
    	uint16_t t_wifi_rx_buff_ridx = g_wifi_rx_buff_ridx;
    	uint16_t tg_wifi_rx_buff_ridx = g_wifi_rx_buff_ridx;
    	
    	
    	g_wifi_pkt_len = 0;
    	
    	// find first byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[0])
    	{
    		g_wifi_rx_buff_ridx = t_wifi_rx_buff_ridx;
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	// find second byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[1])
    	{
    		g_wifi_rx_buff_ridx++;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	// find third byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[2])
    	{
    		g_wifi_rx_buff_ridx += 2;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	// check if there is enough bytes in buffer to check the packet type 
    	// payload length
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    		return (WIFI_PACKET_MISSING_DATA);
    	
    	g_wifi_pkt_type = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    		return (WIFI_PACKET_MISSING_DATA);
    	
    	g_wifi_pkt_len = ((uint16_t)g_wifi_rx_buff[t_wifi_rx_buff_ridx])<<8;
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    				
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    	{
    		g_wifi_pkt_len = 0;
    		return (WIFI_PACKET_MISSING_DATA);
    	}
    	
    	
    	//printUART("-> type %xb\n",g_wifi_pkt_type);
    	
    	g_wifi_pkt_len |= ((uint16_t)g_wifi_rx_buff[t_wifi_rx_buff_ridx]);		
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	g_wifi_rx_buff_ridx = t_wifi_rx_buff_ridx;
    	//printUART("P5 len %d\n",getRxBuffCountWIFI());
    	
    	if(getRxBuffCountWIFI() < g_wifi_pkt_len)							// add 2 more for checksum
    	{
    		g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx;						// restore ridx
    		return (WIFI_PACKET_NOT_ENOUGHT_DATA);
    	}
    	
    	
    	//printUART("P6\n");
    	// check the csum now
    	uint16_t k;
    	for(k=0;k<g_wifi_pkt_len;k++)
    	{
    		t_wifi_rx_buff_ridx++;
    		t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		g_wifi_pkt[k] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    		csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    		printUART("%xb ",g_wifi_rx_buff[t_wifi_rx_buff_ridx]);
    		csum_idx ^= 0x01;
    	}
    	printUART("\n");
    	
    	uint8_t rxcsum[2];
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	rxcsum[0] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	rxcsum[1] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	
    	printUART("Rx-ed %xb%xb  calc %xb%xb\n",rxcsum[0],rxcsum[1],csum[0],csum[1]);
    	
    	if((rxcsum[0] != csum[0])||(rxcsum[1] != csum[1]))
    	{
    		g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx + 3;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		
    		return (WIFI_PACKET_CSUM_ERROR);
    	}
    	
    	g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx + 8 + g_wifi_pkt_len;
    	g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	
    	
    	//printUART("BEFORE EXIT\n");
    	//for(k=0;k<71;k++)
    		//printUART("%xb ",g_wifi_pkt[k]);
    	
    	//printUART("\n\n");
    	
    	
    	return (WIFI_PACKET_FOUND);
    }
    
    uint16_t txPktWIFI(int16_t socket, uint8_t pkt_type)
    {
    	if(g_wifi_remote_cli_socket < 0)
    		return (WIFI_ERROR_SOCKET_CLOSED);
    	
    	uint16_t pkt_len = 0;
    	uint16_t k;
    	uint16_t n;
    	uint16_t offset;
    	
    	for(k=0;k<(WIFI_BUFF_SIZE);k++)
    		g_wifi_tx_buff[k] = 0x00;
    		
    	g_wifi_tx_buff[0] = c_wifi_preambule[0];
    	g_wifi_tx_buff[1] = c_wifi_preambule[1];
    	g_wifi_tx_buff[2] = c_wifi_preambule[2];
    	g_wifi_tx_buff[3] = pkt_type;
    	offset = 4;
    	
    	switch(pkt_type)
    	{
    		case(WIFI_PKT_BLE_BEACONS):
    		{
    			// packet will hold up to 1400B which means max of 1400-8 of beacon data, 
    			// there will always be integer number of BLE beacon packets
    			
    			uint16_t m = 0;
    			for(n=4;n<12;n++)
    			{
    				g_wifi_tx_buff[n] = g_device_id[m++];
    			}
    			
    			
    			g_wifi_tx_buff[12] = (g_blef_tx_count>>8)&0x00FF;
    			g_wifi_tx_buff[13] = g_blef_tx_count&0x00FF;
    			
    			offset = 14;
    			
    			n = 0;
    			for(k=offset;k<(g_blef_tx_count + offset);k++)
    			{
    				g_wifi_tx_buff[k] = g_ble_tx_buff[n];
    				n++;
    			}
    			pkt_len = k;
    			
    			break;
    		}
    		default:
    		{
    #ifdef SYSTEM_DEBUG		
    			printUART("-> WIFI: tx-ing unknown packet...\n");
    #endif			
    			return;
    		}
    	}
    	
    	
    	// generate checksum
    	uint8_t csum[2] = {0x00,0x00};
    	uint8_t cflag = 0x00;
    	for(k=0;k<pkt_len;k++)
    	{
    		printUART("%xb",g_wifi_tx_buff[k]);
    		g_wifi_tx_buff[pkt_len + cflag] += g_wifi_tx_buff[k]; 
    		cflag ^= 0x01;
    	}
    	pkt_len += 2;
    	
    #ifdef SYSTEM_DEBUG		
    	printUART("\n-> WIFI: tx-ing on SoID[%d] pkt type [0x%xb] of size [%d]\n", socket, pkt_type, pkt_len);
    #endif		
    	return txMessageWIFI(socket, (uint8_t *)g_wifi_tx_buff, pkt_len);
    }
    
    /////////////////////////////////////////////////////////////////////////////////
    void initClk()
    {
    }
    
    void stopWDT()
    {
    }
    
    int registerInterruptHandler(P_EVENT_HANDLER InterruptHdl , void* pValue)
    {
    	pIrqEventHandler = InterruptHdl;
    
        return 0;
    }
    
    
    
    void deinitSPI1(void)
    {
    	NRF_SPI1->ENABLE = 0x00000000;										// disable SPI1 
    	NRF_P0->PIN_CNF[CC_SCK_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_P0->PIN_CNF[CC_MISO_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_P0->PIN_CNF[CC_MOSI_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_SPI1->PSEL.SCK  = 0xFFFFFFFF;										
    	NRF_SPI1->PSEL.MOSI = 0xFFFFFFFF;										
    	NRF_SPI1->PSEL.MISO = 0xFFFFFFFF;
    }
    
    uint8_t rxByteSPI1(void)
    {///
        uint32_t counter = 0;
        uint32_t TIMEOUT_COUNTER = 50000;
    
    	NRF_SPI1->TXD = 0x00000000;
    
    	counter = 0;														// wait for the transaction complete or timeout (about 10ms - 20 ms)
    	while ((NRF_SPI1->EVENTS_READY == 0) && (counter < TIMEOUT_COUNTER))
    	{
    		counter++;
    	}
    
    	if (counter == TIMEOUT_COUNTER)
    	{
    		return 0;
    	}
    	else
    	{   
    		NRF_SPI1->EVENTS_READY = 0U;									// clear the event to be ready to receive next messages
    	}
    
        return (uint8_t)NRF_SPI1->RXD;
    }
    
    uint8_t txByteSPI1(uint8_t tx_data)
    {///
        uint32_t counter = 0;
        uint32_t TIMEOUT_COUNTER = 50000;
    
    
    	NRF_SPI1->TXD = (uint32_t)tx_data;
    
    	counter = 0;														// wait for the transaction complete or timeout (about 10ms - 20 ms)
    	while ((NRF_SPI1->EVENTS_READY == 0) && (counter < TIMEOUT_COUNTER))
    	{
    		counter++;
    	}
    
    	if (counter == TIMEOUT_COUNTER)
    	{
    		return 0;
    	}
    	else
    	{   
    		NRF_SPI1->EVENTS_READY = 0U;									// clear the event to be ready to receive next messages
    	}
    
    	return NRF_SPI1->RXD;
    }
    
    void txSPI1(uint8_t * txdata, uint16_t size)
    {
    	uint16_t k;
    	
    	for(k=0;k<size;k++)
    	{
    		txByteSPI1(txdata[k]);
    	}
    }
    
    void rxSPI1(uint8_t * data, uint16_t size)
    {
    	uint16_t k;
    	for(k=0;k<size;k++)
    	{
    		data[k] = rxByteSPI1();
    	}
    }
    
    void initLED(void)
    {
    	g_led_blink_pin = 0x00;
    	deinitLED(); 
    }
    
    void setLED(uint8_t led, uint8_t mode, uint32_t period)
    {	
    	
    	NRF_P0->PIN_CNF[LED_RED] = 0x00000002;
    	NRF_P0->PIN_CNF[LED_GREEN] = 0x00000002;
    	NRF_P0->PIN_CNF[LED_BLUE] = 0x00000002;
    	switch(mode)
    	{
    		case(LED_MODE_OFF):
    		{
    			NRF_P0->OUTCLR = (1<<led);
    			NRF_P0->PIN_CNF[led] = 0x00000002;							// set as input, disconnect input
    			g_led_flag = (LED_DISABLED);
    			break;
    		}
    		case(LED_MODE_STATIC):
    		{
    			NRF_P0->PIN_CNF[led] = 0x00000001;							
    			NRF_P0->OUTCLR = (1<<led);
    			g_led_flag = (LED_DISABLED);
    			break;
    		}
    		case(LED_MODE_BLINK):
    		{
    			
    			g_led_blink_pin = led;
    			NRF_P0->PIN_CNF[led] = 0x00000001;							
    			NRF_P0->OUTCLR = (1<<led);
    			g_led_blink_period = period;
    			g_led_blink_timer = 0;
    			g_led_flag = (LED_ENABLED);
    			break;
    		}
    		default:
    		{
    			break;
    		}
    	}
    }
    	
    void deinitLED(void)
    {
    	NRF_P0->PIN_CNF[LEDR_PIN] = 0x00000002;								// set as input, disconnect input
    	NRF_P0->PIN_CNF[LEDG_PIN] = 0x00000002;								// set as input, disconnect input
    	NRF_P0->PIN_CNF[LEDB_PIN] = 0x00000002;								// set as input, disconnect input
    	g_led_flag = (LED_DISABLED);
    }	
    	
    void chkLED(void)
    {
    	
    }
    
    void initFLASH(void)
    {/// check the user flash integrity
    	g_flash_update = (FLASH_UPDATE_DISABLED);
    	g_flash_sms = (FLASH_SMS_INIT_ERASE_MEMORY);
    	
    	chkUserSpaceFLASH();
    		
    	loadUserDataFLASH();
    }
    
    void loadUserDataFLASH(void)
    {
    	uint16_t k;
    	uint32_t * dwptr = (uint32_t *)(FLASH_UDATA_WIFI_MODE_ADDR);
    	uint8_t * bptr = (uint8_t *)(dwptr);
    	
    	g_wifi_mode = (uint8_t)dwptr[0];
    	
    	if(g_wifi_mode == (WIFI_MODE_AP))
    	{
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_SSID_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_SSID_SIZE);k++)
    		{
    			g_wifi_ssid[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_SSID_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_PASSWD_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_PASSWD_SIZE);k++)
    		{
    			g_wifi_passwd[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_PASSWD_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_PORT_ADDR);
    		g_wifi_port = dwptr[0];
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_ENC_ADDR);
    		g_wifi_enc = dwptr[0];
    	}
    	else
    	{
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_SSID_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_SSID_SIZE);k++)
    		{
    			g_wifi_ssid[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_SSID_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_PASSWD_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_PASSWD_SIZE);k++)
    		{
    			g_wifi_passwd[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_PASSWD_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_PORT_ADDR);
    		g_wifi_port = ((uint32_t)dwptr[0]);
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_ENC_ADDR);
    		g_wifi_enc = (uint32_t)dwptr[0];
    		
    	}
    	
    	dwptr = (uint32_t *)(FLASH_UDATA_REMOTE_SERVER_ADDR);
    	g_wifi_remote_server_ip = (uint32_t)dwptr[0];
    	
    	dwptr = (uint32_t *)(FLASH_UDATA_DEVICE_NAME_ADDR);
    	bptr = (uint8_t *)(dwptr);
    	for(k=0;k<(DEVICE_NAME_SIZE);k++)
    	{
    		g_device_name[k] = 0;
    	}
    	
    	for(k=0;k<(DEVICE_NAME_SIZE);k++)
    	{
    		g_device_name[k] = bptr[k];
    		if(g_device_name[k] == 0)
    			break;
    	}
    	g_device_name[(DEVICE_NAME_SIZE) - 1] = '\0';
    	
    	
    	
    	
    #ifdef SYSTEM_DEBUG	
    	printUART("-> FLASH: WMODE    [%d]\n",g_wifi_mode);
    	printUART("-> FLASH: SSID     [%s]\n",g_wifi_ssid);
    	printUART("-> FLASH: PASSWD   [%s]\n",g_wifi_passwd);
    	printUART("-> FLASH: PORT     [%d]\n",g_wifi_port);
    	printUART("-> FLASH: ENC      [%d]\n",g_wifi_enc);
    	
    	uint8_t addr[4];
    	addr[0] = (uint8_t)((g_wifi_remote_server_ip>>24)&0x000000FF);
    	addr[1] = (uint8_t)((g_wifi_remote_server_ip>>16)&0x000000FF);
    	addr[2] = (uint8_t)((g_wifi_remote_server_ip>>8)&0x000000FF);
    	addr[3] = (uint8_t)((g_wifi_remote_server_ip)&0x000000FF);
    	printUART("-> FLASH: RSERVER  [%d.%d.%d.%d]\n",addr[0],addr[1],addr[2],addr[3]);
    	printUART("-> FLASH: NAME     [%s]\n",g_device_name);
    #endif
    }
    
    void updateUserDataFLASH(void)
    {
    	//uint32_t cdata[9];
    	//uint8_t k;
    	//uint32_t addr = (FLASH_USER_VOLUME_ADDR);
    	
    	//cdata[0] = g_menu_audio_volume;
    	//cdata[1] = g_buzzer_tone;
    	//cdata[2] = g_menu_light_style;
    	//cdata[3] = g_menu_light_intensity;
    	//cdata[4] = g_menu_light_color;
    	//cdata[5] = g_menu_oled_light_brightness;
    	//cdata[6] = g_menu_oled_light_timeout;
    	//cdata[7] = g_menu_bobber_initial_depth;
    	//cdata[8] = g_menu_sonar_rate;
    	
    	//for(k=0;k<9;k++)
    	//{
    		//uint32_t odata = readWordFLASH(addr);
    		//if(cdata[k] != odata)
    		//{
    //#ifdef SYSTEM_DEBUG
    			//printUART("-> FLASH: update, diff at[%d] N[%x]O[%x]...\n",k,cdata[k],odata);
    //#endif			
    			//g_ble_flash_update = (FLASH_UPDATE_ENABLED);
    			//return;
    		//}
    		//addr += 4;
    	//}
    	
    //#ifdef SYSTEM_DEBUG
    	//printUART("-> FLASH: skip update...\n");
    //#endif
    	
    }
    
    void chkUserSpaceFLASH(void)
    {/// check user space data in internal flash memory
    	uint16_t m;
    	uint8_t flag = 0;
    	uint32_t * taddr = (uint32_t *)(FLASH_UDATA_ADDR);
    	uint32_t utmp32;
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> FLASH: Checking user data integrity\n");
    #endif	
    		
    	for(m=0;m<(FLASH_USER_SIGN_WSIZE);m++)
    	{
    		if(taddr[m] != FLASH_USER_SIGN[m])
    		{// flash page sign is different from expected
    			flag = 1;
    			break;
    		}
    	}
    	
    	if(flag == 1)
    	{// erase the page and set default values
    #ifdef SYSTEM_DEBUG
    		printUART("-> FLASH: Restoring default values, user sign error\n");
    #endif
    		setDefaultFLASH();
    	}
    	else
    	{// user sign detected, check checksum  		
    		utmp32 = 0;
    		for(m=0;m<((FLASH_PAGE_SIZE_IN_WORDS)-1);m++)
    		{
    			utmp32 ^= taddr[m];
    		}
    		
    		if(utmp32 != taddr[m])
    		{
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: Restoring default values checksum error\n");
    #endif
    			setDefaultFLASH();					
    		}
    		else
    		{// checksum OK, check firmware version
    			if(taddr[4] != (FLASH_UDATA_VER_VAL))
    			{// restore default values for all FLASH memory entries
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: Restoring default values, flash user data version differs\n");
    #endif
    				setDefaultFLASH();	
    			}
    			else
    			{
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: User data integrity OK\n");
    #endif	
    			}
    		}
    	}
    }
    
    void setDefaultFLASH(void)
    {
    	uint32_t k;
    	uint32_t * pflash = (uint32_t *)(FLASH_UDATA_ADDR);
    	uint32_t * pdata;
    	uint32_t utmp32;
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> FLASH: Writing default user data...\n");
    #endif
    	
    	erasePageFLASH(FLASH_UDATA_ADDR);									// erase user data flash page
    	//delay_ms(FLASH_ERASE_PAGE_DELAY);									// delay required for erase to take place			
    	
    	// 1. write user data preamble - sign
    	for(k=0;k<(FLASH_USER_SIGN_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_USER_SIGN_ADDR) + 4*k, FLASH_USER_SIGN[k]);
    	}
    	
    	// 2. write user data 	
    	writeWordFLASH(FLASH_UDATA_VER_ADDR, FLASH_UDATA_VER_VAL);
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_SSID_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_SSID_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_SSID_ADDR) + 4*k, pdata[k]);
    	}
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    	
    	writeWordFLASH(FLASH_UDATA_AP_PORT_ADDR, FLASH_UDATA_AP_PORT_VAL);
    	writeWordFLASH(FLASH_UDATA_AP_ENC_ADDR, FLASH_UDATA_AP_ENC_VAL);
    
    	pdata = (uint32_t *)(FLASH_UDATA_STA_SSID_VAL);
    	for(k=0;k<(FLASH_UDATA_STA_SSID_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_STA_SSID_ADDR) + 4*k, pdata[k]);
    	}
    
    	pdata = (uint32_t *)(FLASH_UDATA_STA_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_STA_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_STA_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    
    	writeWordFLASH(FLASH_UDATA_STA_PORT_ADDR, FLASH_UDATA_STA_PORT_VAL);
    	writeWordFLASH(FLASH_UDATA_STA_ENC_ADDR, FLASH_UDATA_STA_ENC_VAL);
    
    	writeWordFLASH(FLASH_UDATA_REMOTE_SERVER_ADDR, FLASH_UDATA_REMOTE_SERVER_VAL);
    
    	writeWordFLASH(FLASH_UDATA_WIFI_MODE_ADDR, FLASH_UDATA_WIFI_MODE_VAL);
    
    	pdata = (uint32_t *)(FLASH_UDATA_DEVICE_NAME_VAL);
    	for(k=0;k<(FLASH_UDATA_DEVICE_NAME_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_DEVICE_NAME_ADDR) + 4*k, pdata[k]);
    	}
    
    			
    	// 3. calculate the checksum
    	utmp32 = 0;	
    	for(k=0;k<((FLASH_PAGE_SIZE_IN_WORDS)-1);k++)
    	{
    		utmp32 ^= pflash[k];
    	}
    	
    	// 4. write the user data checksum
    	writeWordFLASH(FLASH_UDATA_CHKSUM_ADDR, utmp32);
    }
    
    void erasePageFLASH(uint32_t addr)
    {///
        NRF_NVMC->CONFIG = 0x00000002;   									// enable flash erase and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
        
        NRF_NVMC->ERASEPAGE = addr;											// erase given page 
        while (NRF_NVMC->READY == 0x00000000);
          
        NRF_NVMC->CONFIG = 0x00000000;	  									// disable flash erase and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    }
    
    void writeWordFLASH(uint32_t addr, uint32_t data)
    {///
    	uint32_t * fm_addr = (uint32_t *)addr;
        NRF_NVMC->CONFIG = 0x00000001;										// enable flash write and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    	
        *fm_addr = data;
        while (NRF_NVMC->READY == 0x00000000);
      
        NRF_NVMC->CONFIG = 0x00000000;										// disable flash write and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    }
    
    uint32_t readWordFLASH(uint32_t addr)
    {///
    	uint32_t * fm_addr = (uint32_t *)addr;
    	return (*fm_addr);
    }
    
    void chkFLASH(void)
    {
    	if(g_flash_update == (FLASH_UPDATE_DISABLED))
    		return;
    		
    	// state machine for writting new data into flash memory		
    	switch(g_flash_sms)
    	{
    		case(FLASH_SMS_INIT_ERASE_MEMORY):
    		{
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: erasing user data...\n");
    #endif
    			uint32_t k;
    			uint32_t * ptr = (uint32_t *)(FLASH_UDATA_ADDR);
    			for(k=0;k<(FLASH_PAGE_SIZE_IN_WORDS);k++)
    			{
    				g_flash_page[k] = ptr[k];
    			}
    			
    			for(k=0;k<(FLASH_WRITE_DATA_SIZE);k++)
    			{
    				g_flash_write_data[k] = g_wifi_pkt[k];
    				//printUART("-> FLASH: data [%d] [%xb]...\n",k,g_flash_write_data[k]);
    			}
    			
    			//erasePageFLASH(FLASH_UDATA_ADDR);							// erase user data flash page
    			NRF_NVMC->CONFIG = 0x00000002;   							// enable flash erase and wait until the NVMC is ready
    			g_flash_timer = getRTC2();
    			g_flash_sms = (FLASH_SMS_WAIT_PHASE1);			
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE1):
    		{	
    			if(NRF_NVMC->READY == 0x00000001)
    			{
    				NRF_NVMC->ERASEPAGE = (FLASH_UDATA_ADDR);				// erase given page 
    				g_flash_timer = getRTC2();
    				g_flash_sms = (FLASH_SMS_WAIT_PHASE2);	
    			}	
        
    			if(chk4TimeoutRTC2(g_flash_timer, 2*(FLASH_ERASE_PAGE_DELAY)) == (RTC_TIMEOUT))
    			{
    				g_flash_update = (FLASH_UPDATE_DISABLED);
    			}		
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE2):
    		{	
    			if(NRF_NVMC->READY == 0x00000001)
    			{
    				NRF_NVMC->CONFIG = 0x00000000;							// disable flash erase and wait until the NVMC is ready
    				g_flash_timer = getRTC2();
    				g_flash_sms = (FLASH_SMS_WAIT_PHASE3);	
    			}	
        
    			if(chk4TimeoutRTC2(g_flash_timer, 2*(FLASH_ERASE_PAGE_DELAY)) == (RTC_TIMEOUT))
    			{
    				g_flash_update = (FLASH_UPDATE_DISABLED);
    			}		
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE3):
    		{			
    			uint32_t k, utmp32;
    			uint32_t * pflash = (uint32_t *)(FLASH_UDATA_ADDR);
    			uint32_t n, kmax;
    			uint32_t * pdata = (uint32_t *)g_flash_write_data;
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: writing new user data...\n");
    #endif		
    			// 1. write user data preamble - sign
    			for(k=0;k<(FLASH_USER_SIGN_WSIZE);k++)
    			{
    				writeWordFLASH((FLASH_USER_SIGN_ADDR) + 4*k, FLASH_USER_SIGN[k]);
    			}
    			
    			// 2. write user data 	
    			writeWordFLASH(FLASH_UDATA_VER_ADDR, FLASH_UDATA_VER_VAL);
    	
    			
    			if(g_flash_update == (FLASH_UPDATE_AP_INFO))
    			{		
    				n = ((FLASH_UDATA_AP_SSID_ADDR) - (FLASH_UDATA_ADDR))/4;
    				for(k=0;k<16;k++)
    				{
    					g_flash_page[n] = pdata[k];
    					n++;
    				}
    				
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x0000FF00)>>8;
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<8;
    				g_flash_page[((FLASH_UDATA_STA_ENC_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0xFF000000)>>24;
    				
    				g_flash_page[((FLASH_UDATA_WIFI_MODE_ADDR) - (FLASH_UDATA_ADDR))/4] = (WIFI_MODE_AP);
    				
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: new AP info [%d]...\n",n);
    #endif			
    			}
    			else
    			{					
    				n = ((FLASH_UDATA_STA_SSID_ADDR) - (FLASH_UDATA_ADDR))/4;
    				for(k=0;k<16;k++)
    				{
    					g_flash_page[n] = pdata[k];
    					n++;
    				}
    				
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x0000FF00)>>8;
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<8;
    				g_flash_page[((FLASH_UDATA_STA_ENC_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x00FF0000)>>16;
    				
    				
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0xFF000000);
    				k++;
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x00FF0000)>>16;
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x0000FF00);
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<16;
    				g_flash_page[((FLASH_UDATA_WIFI_MODE_ADDR) - (FLASH_UDATA_ADDR))/4] = (WIFI_MODE_STA);
    				
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: new STA info  [%d]...\n",n);
    #endif
    			}
    			
    			
    			// 9. calculate the checksum
    			utmp32 = 0;	
    			for(k=0;k<((FLASH_PAGE_SIZE_IN_WORDS)-1);k++)
    			{
    				writeWordFLASH((FLASH_UDATA_ADDR) + k*4, g_flash_page[k]);
    				utmp32 ^= pflash[k];
    				//if(k<50)
    				//{
    					//printUART("-> FLASH: [%d] [%x]\n",k, pflash[k]);
    				//}
    			}
    
    			// 10. write the user data checksum
    			writeWordFLASH(FLASH_UDATA_CHKSUM_ADDR, utmp32);
    
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: write completed\n");
    #endif
    
    			g_flash_sms = (FLASH_SMS_INIT_ERASE_MEMORY);
    			g_flash_update = (FLASH_UPDATE_DISABLED);
    			
    			
    			loadUserDataFLASH();
    			
    			NVIC_SystemReset();
    			break;
    		}
    		default:
    		{
    			break;
    		}
    	}
    
    }
    
    /*
    void GPIOTE_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    
    */
    
    /////////////////////////////////////////////////////////////////////////////////
    
    /*
    #include "gpioint.h"
    
    volatile uint32_t g_btn_sense;
    
    void initGPIOINT(void)
    {
    	g_btn_state = (BTN_STATE_IDLE);
    
    	NRF_GPIOTE->EVENTS_IN[0] = 0;
    	NRF_GPIOTE->EVENTS_IN[1] = 0;
    	
    	NRF_P0->PIN_CNF[PBTN_PIN] = 0x0000000C;								// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00020001|((PBTN_PIN)<<8);					// event mode, high to low transition
    	
    	
    	NRF_GPIOTE->INTENCLR = 0x00000002;	
    	NRF_GPIOTE->INTENSET = 0x00000001;									
        NVIC_EnableIRQ(GPIOTE_IRQn);										
    
    #ifdef SYSTEM_DEBUG
    	printUART0("-> GPIOINT: init [DONE]\n",0);
    #endif
    
    }
    
    void GPIOTE_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    
    //void chkBTN(void)
    //{	
    	//if(g_btn_state == (BTN_STATE_IDLE))
    		//return;
    		
    //#i
    //}
    
    */

    And header file 

    #ifndef __MEDSENSE_H_
    #define __MEDSENSE_H_
    #include "boards.h"
    #include "nrf52.h"
    #include "clock.h"
    #include "uart.h"
    
    #include "nrf_delay.h"
    #include "sl_common.h"
    
    #include "spi.h"
    #include "flash.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    
    
    #define delay_ms nrf_delay_ms          
    
    #define	FLASH_MEMORY_PAGE_SIZE				0x00001000
    
    #define	FLASH_PAGE_SIZE_IN_WORDS			1024
    #define	FLASH_PAGE_SIZE						4096
    
    #define	FLASH_UDATA_ADDR					0x0007F000
    #define FLASH_UDATA_SIZE					(FLASH_MEMORY_PAGE_SIZE)	
    	
    #define	FLASH_USER_SIGN_ADDR				(FLASH_UDATA_ADDR)
    #define FLASH_USER_SIGN_BSIZE				16
    #define	FLASH_USER_SIGN_WSIZE				4
    
    #define	FLASH_UDATA_VER_ADDR				((FLASH_USER_SIGN_ADDR) + (FLASH_USER_SIGN_BSIZE))
    #define	FLASH_UDATA_VER_VAL					0x00000000
    #define	FLASH_UDATA_VER_BSIZE				4
    #define	FLASH_UDATA_VER_WSIZE				1
    
    #define FLASH_UDATA_AP_SSID_ADDR			((FLASH_UDATA_VER_ADDR) + (FLASH_UDATA_VER_BSIZE))
    #define FLASH_UDATA_AP_SSID_VAL				"BLE2WiFi"
    #define FLASH_UDATA_AP_SSID_BSIZE			32
    #define FLASH_UDATA_AP_SSID_WSIZE			8
    
    #define FLASH_UDATA_AP_PASSWD_ADDR			((FLASH_UDATA_AP_SSID_ADDR) + (FLASH_UDATA_AP_SSID_BSIZE))
    #define FLASH_UDATA_AP_PASSWD_VAL			"wifi1234"
    #define FLASH_UDATA_AP_PASSWD_BSIZE			32
    #define FLASH_UDATA_AP_PASSWD_WSIZE			8
    
    #define FLASH_UDATA_AP_PORT_ADDR			((FLASH_UDATA_AP_PASSWD_ADDR) + (FLASH_UDATA_AP_PASSWD_BSIZE))
    #define FLASH_UDATA_AP_PORT_VAL				(WIFI_DEFAULT_AP_PORT)
    #define FLASH_UDATA_AP_PORT_BSIZE			4
    #define FLASH_UDATA_AP_PORT_WSIZE			1
    
    #define FLASH_UDATA_AP_ENC_ADDR				((FLASH_UDATA_AP_PORT_ADDR) + (FLASH_UDATA_AP_PORT_BSIZE))
    #define FLASH_UDATA_AP_ENC_VAL				(WIFI_DEFAULT_AP_ENC)
    #define FLASH_UDATA_AP_ENC_BSIZE			4
    #define FLASH_UDATA_AP_ENC_WSIZE			1
    
    
    #define FLASH_UDATA_STA_SSID_ADDR			((FLASH_UDATA_AP_ENC_ADDR) + (FLASH_UDATA_AP_ENC_BSIZE))
    #define FLASH_UDATA_STA_SSID_VAL			"unknown"
    #define FLASH_UDATA_STA_SSID_BSIZE			32
    #define FLASH_UDATA_STA_SSID_WSIZE			8
    
    #define FLASH_UDATA_STA_PASSWD_ADDR			((FLASH_UDATA_STA_SSID_ADDR) + (FLASH_UDATA_STA_SSID_BSIZE))
    #define FLASH_UDATA_STA_PASSWD_VAL			"none1234"
    #define FLASH_UDATA_STA_PASSWD_BSIZE		32
    #define FLASH_UDATA_STA_PASSWD_WSIZE		8
    
    #define FLASH_UDATA_STA_PORT_ADDR			((FLASH_UDATA_STA_PASSWD_ADDR) + (FLASH_UDATA_STA_PASSWD_BSIZE))
    #define FLASH_UDATA_STA_PORT_VAL			(WIFI_DEFAULT_AP_PORT)
    #define FLASH_UDATA_STA_PORT_BSIZE			4
    #define FLASH_UDATA_STA_PORT_WSIZE			1
    
    #define FLASH_UDATA_STA_ENC_ADDR			((FLASH_UDATA_STA_PORT_ADDR) + (FLASH_UDATA_STA_PORT_BSIZE))
    #define FLASH_UDATA_STA_ENC_VAL				(WIFI_DEFAULT_STA_ENC)
    #define FLASH_UDATA_STA_ENC_BSIZE			4
    #define FLASH_UDATA_STA_ENC_WSIZE			1
    
    #define FLASH_UDATA_REMOTE_SERVER_ADDR		((FLASH_UDATA_STA_ENC_ADDR) + (FLASH_UDATA_STA_ENC_BSIZE))
    #define FLASH_UDATA_REMOTE_SERVER_VAL		(WIFI_REMOTE_SERVER_IP_ADDR)
    #define FLASH_UDATA_REMOTE_SERVER_BSIZE		4
    #define FLASH_UDATA_REMOTE_SERVER_WSIZE		1
    
    #define FLASH_UDATA_WIFI_MODE_ADDR			((FLASH_UDATA_REMOTE_SERVER_ADDR) + (FLASH_UDATA_REMOTE_SERVER_BSIZE))
    #define FLASH_UDATA_WIFI_MODE_VAL			(WIFI_MODE_AP)
    #define FLASH_UDATA_WIFI_MODE_BSIZE			4
    #define FLASH_UDATA_WIFI_MODE_WSIZE			1
    
    #define FLASH_UDATA_DEVICE_NAME_ADDR		((FLASH_UDATA_WIFI_MODE_ADDR) + (FLASH_UDATA_WIFI_MODE_BSIZE))
    #define FLASH_UDATA_DEVICE_NAME_VAL			"BLE2WiFi-Gateway"
    #define FLASH_UDATA_DEVICE_NAME_BSIZE		32
    #define FLASH_UDATA_DEVICE_NAME_WSIZE		8
    
    
    #define	FLASH_UDATA_CHKSUM_ADDR				((FLASH_UDATA_ADDR) + (FLASH_UDATA_SIZE) - 4)
    #define FLASH_UDATA_CHKSUM_SIZE				4
    	
    #define FLASH_CSUM_OK						0x00
    #define FLASH_CSUM_FAIL						0x01
    
    #define FLASH_ERASE_PAGE_DELAY				200							// [x1ms]
    
    #define FLASH_SMS_INIT_ERASE_MEMORY			0x00
    #define FLASH_SMS_WAIT_PHASE1				0x01
    #define FLASH_SMS_WAIT_PHASE2				0x02
    #define FLASH_SMS_WAIT_PHASE3				0x03
    #define FLASH_SMS_WAIT_PHASE4				0x04                                                     
    	
    //#define SYSTEM_DEBUG
    #define Buttons_Number 1
    
    #define UART_BAUDRATE							UART0_BAUDRATE_921600
    
    #define UINT8   uint8_t
    #define UINT32  uint32_t
    #define INT32 int32_t
    #define _i32 int32_t
    
    /*  moved to custom_board
    #define CC_IRQ_PIN								0
    #define CC_NRST_PIN								1
    #define CC_CS_PIN								2
    #define CC_MISO_PIN								3
    #define CC_MOSI_PIN								4
    #define CC_SCK_PIN								5
    #define CC_NHIB_PIN								6
    
    */
    #define initUART								initUART0
    #define printUART								printUART0
    #define deinitUART								deinitUART0
    
    //#define SL_MAX_SOCKETS                                                          8
    #define SL_STOP_TIMEOUT        0xFF
    
    #define BLEF_CHANNEL_SCAN_SWITCHING_PERIOD		20						// [x1ms]
    #define UART_TX_PIN								11						
    #define UART_RX_PIN								12	
    
    #define LED_MODE_OFF							0x00
    #define LED_MODE_STATIC							0x01
    #define LED_MODE_BLINK							0x02
    #define LED_DISABLED							0x00
    #define LED_ENABLED								0x01
    #define LED_STATE_FLAG							0x80
    
    
    	
    
    #define BLE_RX_BUFF_SIZE						512
    #define BLE_RX_DATA_BUFF_SIZE					4096					// must be in a form of 2^n
    #define BLE_RX_DATA_BUFF_MASK					((BLE_RX_DATA_BUFF_SIZE) - 1)
    
    
    #define BTN_STATE_RESTORE_AP_MODE				0x01
    #define BTN_STATE_IDLE							0x00
    
    #define WIFI_NETWORK_IP_OFFSET					0xC0A82A01				// 192.168.42.1
    #define WIFI_NETWORK_MASK						0xFFFFFF00				// 255.255.255.0
    #define WIFI_NETWORK_IP_GW						1						// x.y.z.1
    #define WIFI_NETWORK_IP_DNS						2						// x.y.z.2
    #define WIFI_NETWORK_IP_AP						3						// x.y.z.3
    #define WIFI_NETWORK_IP_DHCP_BEG				100
    #define WIFI_NETWORK_IP_DHCP_END				200
    #define WIFI_SERVER_PORT						5000					// TCP server port 
    #define WIFI_SECURITY_OPEN						(SL_SEC_TYPE_OPEN)
    #define WIFI_SECURITY_WPA						(SL_SEC_TYPE_WPA)
    #define WIFI_MAC_ADDR_LEN						(SL_MAC_ADDR_LEN)
    #define WIFI_AP_LIST_LEN						20						// number of AP which can be stored during the scan of medium
    
    
    #define WIFI_BUFF_SIZE							1400
    #define WIFI_RX_BUFF_SIZE						2048					// must be a power of two!
    #define WIFI_RX_BUFF_MASK						((WIFI_RX_BUFF_SIZE) - 1)
    
    #define WIFI_MODE_AP							0x00
    #define WIFI_MODE_STA							0x01
    #define WIFI_SSID_SIZE							33
    #define WIFI_PASSWD_SIZE						33
    #define WIFI_DEFAULT_AP_PORT					50000
    #define WIFI_DEFAULT_STA_PORT					50000
    #define WIFI_DEFAULT_AP_ENC					2
    #define WIFI_DEFAULT_STA_ENC					2
    #define WIFI_REMOTE_SERVER_IP_ADDR				0xFFFFFFFF
    
    #define WIFI_PKT_SET_STA_CONFIG					0x1A
    #define WIFI_PKT_FORCE_AP_MODE					0x21
    #define WIFI_PKT_BLE_BEACONS					0x6A
    
    #define WIFI_PKT_PREAMBULE_IDX					0
    #define WIFI_PKT_TYPE_IDX						3
    #define WIFI_PKT_PAYLOAD_SIZE_IDX				4
    
    #define WIFI_PACKET_FOUND						0x00
    #define WIFI_PACKET_NOT_FOUND					0x01
    #define WIFI_PACKET_CSUM_ERROR					0x02
    #define WIFI_PACKET_MISSING_PREAMBULE			0x04
    #define WIFI_PACKET_MISSING_DATA				0x08
    #define WIFI_PACKET_NOT_ENOUGHT_DATA			0x10
    
    #define FLASH_UPDATE_DISABLED					0x00
    #define FLASH_UPDATE_AP_INFO					0x01
    #define FLASH_UPDATE_STA_INFO					0x02
    
    #define FLASH_WRITE_DATA_SIZE					256
    
    #define DEVICE_NAME_SIZE						32
    #define DEVICE_ID_SIZE							8
    
    #define WIFI_AP_INFO_LEN						32
    #define WIFI_SCAN_INTERVAL						10								// in seconds
    
    #define WIFI_CONNECTED							1
    #define WIFI_DISCONNECTED						0
    
    #define WIFI_IP_LEASE_TIME   					3600					// IP address lease time [s]
    #define SUCCESS        							0
    
    #define WIFI_SETUP_RETRIES						0x03					// number of retries executed to set certian mode
    #define WIFI_RESET_DELAY						500						// [ms] reset delay 
    #define WIFI_LOOP_DELAY							10000					// [ms] while loop delay - wait response
    #define WIFI_REMOTE_SERVER_CONNECTION_RETRY_PERIOD	5000				// [x1ms] check for connection establishment  
    
    #define WIFI_OK									0x00
    #define WIFI_ERROR_SET_DEF						0x01
    #define WIFI_ERROR_START_DEV					0x02
    #define WIFI_ERROR_STA_DEVICE					0x03
    #define WIFI_ERROR_MISSING_AP					0x04
    #define WIFI_EEROR_NO_IP						0x05
    #define WIFI_EEROR_CANNOT_RUN_AP				0x06
    #define WIFI_ERROR_CANNOT_CONN2AP				0x07
    #define WIFI_ERROR_CANNOT_CONN2INT				0x08
    #define WIFI_ERROR_SERVER_FAILED				0x09
    #define WIFI_ERROR_CONNECTION_POLICY			0x0A
    #define WIFI_ERROR_DIS_SCAN_POLICY				0x0B
    #define WIFI_ERROR_CREATE_SOCKET				0x0C
    #define WIFI_ERROR_SOCKET_NONBLOCKING			0x0D
    #define WIFI_ERROR_SOCKET_BINDING				0x0E	
    #define WIFI_ERROR_LAN_CONNECTION_TIMEOUT		0x10	
    #define WIFI_ERROR_REMOTE_SERVER_DISCONNECTED	0x11
    #define WIFI_ERROR_REMOTE_SERVER_SOCKET_FAILED	0x12
    #define WIFI_ERROR_FAIL2SEND_DATA				0x13
    #define WIFI_ERROR_AP_NO_IP						0x14
    #define WIFI_ERROR_CANNOT_RUN_AP				0x15
    #define WIFI_ERROR_WAITING4RETRY_TIMEOUT		0x16	
    #define WIFI_ERROR_SOCKET_CLOSED				0x17
    
    #define WIFI_DISABLED							0x00
    #define WIFI_ENABLED							0x01	
    #define WIFI_WAIT4IP_PERIOD						10000					// [x1ms]
    		
    #define WIFI_AP_DISCONNECTED					0x00
    #define WIFI_AP_CONNECTED						0x01
    
    #define WIFI_SOCKET_DISCONNECTED				0x00
    #define WIFI_SOCKET_CONNECTED					0x01
    
    #define STATUS_BIT_PING_DONE  31
    
    /* Status bits - These are used to set/reset the corresponding bits in a 'status_variable' */
    
    /* Application specific status/error codes */
    typedef enum{
        LAN_CONNECTION_FAILED = -0x7D0,        /* Choosing this number to avoid overlap with host-driver's error codes */
        LAN_CONNECTION_TIMEOUT = LAN_CONNECTION_FAILED -1,       
        INTERNET_CONNECTION_FAILED = LAN_CONNECTION_TIMEOUT - 1,
        DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,
    
        STATUS_CODE_MAX = -0xBB8
    }e_AppStatusCodes;
    
    typedef struct
    {
        unsigned long  ipV4;
        unsigned long  ipV4Mask;
        unsigned long  ipV4Gateway;
        unsigned long  ipV4DnsServer;
    }_NetCfgIpV4Args_t;
    
                                                       
    
    extern const uint8_t g_firmware_version[6];
    
    extern volatile uint8_t g_led_blink_pin;
    extern volatile uint32_t g_led_blink_period;
    extern volatile uint32_t g_led_blink_timer;
    extern volatile uint8_t g_led_flag;
    
    
    extern volatile uint8_t g_btn_state;
    
    extern volatile uint8_t g_ble_rx_buff[BLE_RX_BUFF_SIZE];
    extern volatile uint16_t g_ble_rx_buff_len;
    extern volatile uint8_t g_ble_rx_data[BLE_RX_DATA_BUFF_SIZE];
    extern volatile uint16_t g_ble_rx_data_widx;
    extern volatile uint16_t g_ble_rx_data_ridx;
    extern volatile uint8_t g_ble_tx_buff[WIFI_BUFF_SIZE];
    extern volatile uint16_t g_blef_tx_count;
    
    
    extern volatile uint8_t g_flash_update;
    
    extern volatile uint8_t g_wifi_status;
    extern volatile uint8_t g_wifi_error;
    extern volatile uint8_t g_wifi_mode;
    extern volatile uint8_t g_wifi_ssid[WIFI_SSID_SIZE];
    extern volatile uint8_t g_wifi_passwd[WIFI_PASSWD_SIZE];
    extern volatile uint32_t g_wifi_port;
    extern volatile uint32_t g_wifi_enc;
    extern volatile uint32_t g_wifi_remote_server_ip;
    extern volatile uint8_t g_wifi_tx_buff[WIFI_BUFF_SIZE];
    extern volatile uint8_t g_wifi_rx_buff[WIFI_RX_BUFF_SIZE];
    extern volatile uint8_t g_wifi_pkt[WIFI_BUFF_SIZE];
    extern volatile uint16_t g_wifi_rx_buff_widx;
    extern volatile uint16_t g_wifi_rx_buff_ridx;
    extern volatile uint8_t g_wifi_local_ip_str[20];
    extern volatile uint8_t g_wifi_remote_server_ip_str[20];
    extern volatile int16_t g_wifi_remote_cli_socket;
    
    extern volatile uint8_t g_device_name[DEVICE_NAME_SIZE];
    extern volatile uint8_t g_device_id[DEVICE_ID_SIZE];
    extern volatile uint8_t g_flash_write_data[FLASH_WRITE_DATA_SIZE];
    
    
    static volatile uint16_t AddrSize;
    static volatile uint16_t Rem_AddrSize;
    typedef unsigned int Fd_t;
    Fd_t spi_Open(char *ifName, unsigned long flags);
    int spi_Close(Fd_t fd);
    int spi_Write(Fd_t fd, unsigned char *pBuff, int len);
    int spi_Read(Fd_t fd, unsigned char *pBuff, int len);
    
    void output(int pin);
    void CC3100_IRQHandler(void);
    void	 	initFLASH(void);
    void 		loadUserDataFLASH(void);
    void 		updateUserDataFLASH(void);
    void		chkUserSpaceFLASH(void);
    void 		erasePageFLASH(uint32_t addr);
    void 		writeWordFLASH(uint32_t addr, uint32_t data);
    uint32_t 	readWordFLASH(uint32_t addr);
    void 		setDefaultFLASH(void);
    void 		chkFLASH(void);
    
    void 		initWIFI(void);
    void 		rstWIFI(void);
    void 		powerDownWIFI(void);
    uint8_t 	setAPmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc);
    uint8_t 	setSTAmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc);
    void 		chkWIFI(void);
    uint16_t 	getRxBuffCountWIFI(void);
    uint8_t 	getNextPktWIFI(void);
    uint16_t  	txPktWIFI(int16_t socket, uint8_t pkt_type);
    
    int16_t 	openSocketWIFI(void);
    uint8_t 	chkLocalSocketWIFI(void);
    uint16_t 	txMessageWIFI(int16_t socket, uint8_t * dataPtr, uint16_t numBytes);
    uint16_t 	rxLocalSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen);
    uint16_t 	rxRemoteSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen);
    void 		getStrAddr(char * str, uint32_t addr);
    uint8_t 	scanMediumCC3100(void);
    uint8_t 	connect2ServerCC3100(void);
    void chkCC3100IRQ(void);
    
    void initLED(void);
    void deinitLED(void);
    void setLED(uint8_t led, uint8_t mode, uint32_t period);
    void chkLED(void);
    
    
     
    ///wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    /// AP mode CC3100 generic functions
    ///---------------------------------------------------------------------
    //int32_t	 	initializeAppVariables(void);
    int32_t 	configureSimpleLinkToDefaultState(void);
    //static int32_t	establishConnectionWithAP(uint8_t * ssid, uint8_t * passwd, uint8_t enc);
    static _i32 establishConnectionWithAP();
    
    volatile  uint32_t  g_Status = 0;
    volatile uint32_t  g_PingPacketsRecv = 0;
    volatile uint32_t  g_GatewayIP = 0;
    static volatile uint32_t  g_StationIP = 0;
    
    void ASSERT_ON_ERROR(int);
    
    
    #endif
    
    

    Here is sdk_config , don't know if there is negative interactions from trying so many approaches.

    Not sure what needs to be removed or added.

    Will attach since there were errors on including as code.3364.sdk_config.h

Reply
  • The spi functions are being called by main.c and are not interrupt based.

    But they commands/data they send over spi to a CC3100 SoC generate an interrupt when the CC3100 needs a reply.

    The functions are actually in another set of files, one the .c and the other a supporting header file.

    Those functions are used in the main body of main.c.

    I will include what I can from the main.c file below :

    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    #include "nordic_common.h"
    #include "nrf_sdm.h"
    
    #include "ble.h"
    #include "ble_hci.h"
    #include "ble_srv_common.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "nrf_sdh_soc.h"
    #include "nrf_drv_gpiote.h"
    #include "app_util.h"
    #include "app_error.h"
    #include "app_util.h"
    #include "app_timer.h"
    #include "app_gpiote.h"
    #include "bsp_btn_ble.h"
    #include "peer_manager.h"
    #include "peer_manager_handler.h"
    #include "fds.h"
    #include "nrf_fstorage.h"
    #include "ble_conn_state.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_ble_scan.h"
    #include "nrf_pwr_mgmt.h"
    
    
    #include "simplelink.h"
    #include "sl_common.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "SEGGER_RTT.h"
    //#include "SEGGER_RTT_printf.h"
    #include "medsense.h"
    #include "host_programming_1.0.1.13-2.11.0.1_ucf.h"
    #include "host_programming_1.0.1.13-2.11.0.1_ucf-signed.h"
    
    
    
    
    
    
    
    
    #define NRF_LOG_INFO(...)  SEGGER_RTT_printf(0 , __VA_ARGS__)
    
    
    #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 APP_SOC_OBSERVER_PRIO     1                                /**< Applications' SoC observer priority. You shouldn't need to modify this value. */
    
    #define SEC_PARAM_BOND            1                                /**< Perform bonding. */
    #define SEC_PARAM_MITM            0                                /**< Man In The Middle protection not required. */
    #define SEC_PARAM_LESC            0                                /**< LE Secure Connections not enabled. */
    #define SEC_PARAM_KEYPRESS        0                                /**< Keypress notifications not enabled. */
    #define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE             /**< No I/O capabilities. */
    #define SEC_PARAM_OOB             0                                /**< Out Of Band data not available. */
    #define SEC_PARAM_MIN_KEY_SIZE    7                                /**< Minimum encryption key size. */
    #define SEC_PARAM_MAX_KEY_SIZE    16                               /**< Maximum encryption key size. */
    
    #define SCAN_DURATION_WITELIST    3000                             /**< Duration of the scanning in units of 10 milliseconds. */
    
    #define TARGET_UUID               BLE_UUID_GATT                    /**< Target device name that application is looking for. */
    
    
    /**@brief Variable length data encapsulation in terms of length and pointer to data */
    typedef struct
    {
        uint8_t * p_data;   /**< Pointer to data. */
        uint16_t  data_len; /**< Length of data. */
    }data_t;
    
    NRF_BLE_GATT_DEF(m_gatt);                                 /**< GATT module instance. */
    NRF_BLE_SCAN_DEF(m_scan);                                 /**< Scanning Module instance. */
    
    static uint16_t              m_conn_handle;               /**< Current connection handle. */
    static bool                  m_whitelist_disabled;        /**< True if whitelist has been temporarily disabled. */
    static bool                  m_memory_access_in_progress; /**< Flag to keep track of ongoing operations on persistent memory. */
    static bool                  m_erase_bonds;               /**< Bool to determine if bonds should be erased before scanning starts. Based on button push upon startup. */
    
    /**< Scan parameters requested for scanning and connection. */
    static ble_gap_scan_params_t const m_scan_param =
    {
        .active        = 0x01,
        .interval      = NRF_BLE_SCAN_SCAN_INTERVAL,
        .window        = NRF_BLE_SCAN_SCAN_WINDOW,
        .filter_policy = BLE_GAP_SCAN_FP_WHITELIST,
        .timeout       = SCAN_DURATION_WITELIST,
        .scan_phys     = BLE_GAP_PHY_1MBPS,
    };
    
    bool startup = true;
    
    static void scan_start(void);
    
    static char const m_target_periph_name[] = "Nordic_GATTS"; /**< If you want to connect to a peripheral using a given advertising name, type its name here. */
    static bool       is_connect_per_addr    = false;          /**< If you want to connect to a peripheral with a given address, set this to true and put the correct address in the variable below. */
    
    static ble_gap_addr_t const m_target_periph_addr =
    {
        /* Possible values for addr_type:
           BLE_GAP_ADDR_TYPE_PUBLIC,
           BLE_GAP_ADDR_TYPE_RANDOM_STATIC,
           BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE,
           BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */
          .addr_type = BLE_GAP_ADDR_TYPE_RANDOM_STATIC,
          .addr      = {0x8D, 0xFE, 0x23, 0x86, 0x77, 0xD9}
    };
    
    
    //**********Simplelink items
    #define _u32 uint32_t
    #define _i32 int32_t
    #define i32 int32_t
    
    #define VERSION_OFFSET      	(8)
    #define UCF_OFFSET      		(20)
    #define CHUNK_LEN			(1024)
    #define LEN_128KB			(131072)
    
    #define find_min(a,b) (((a) < (b)) ? (a) : (b))
    
    char		  printBuffer[1024];
    
    typedef enum
    {
      size512KB = 0,
      size1MB,
      size2MB,
      size4MB,
      size8MB,
      size16MB
    }sflashSize_e;
    
    sflashSize_e	flashSize = size1MB;;
    
    #define APPLICATION_VERSION "1.3.0"
    
    
    
    /* Use bit 32:
     *      1 in a 'status_variable', the device has completed the ping operation
     *      0 in a 'status_variable', the device has not completed the ping operation
     */
    #define STATUS_BIT_PING_DONE  31
    
    #define HOST_NAME       "www.ti.com"
    
    /*
     * Values for below macros shall be modified for setting the 'Ping' properties
     */
    #define PING_INTERVAL   1000    /* In msecs */
    #define PING_TIMEOUT    3000    /* In msecs */
    #define PING_PKT_SIZE   20      /* In bytes */
    #define NO_OF_ATTEMPTS  3
    
    #define IS_PING_DONE(status_variable)           GET_STATUS_BIT(status_variable, \
                                                                   STATUS_BIT_PING_DONE)
    
    /*
     * GLOBAL VARIABLES -- Start
     */
    extern volatile  uint32_t g_Status;
    extern volatile uint32_t g_PingPacketsRecv;
    extern volatile uint32_t g_GatewayIP;
    /*
     * GLOBAL VARIABLES -- End
     */
    
    
    /*
     * STATIC FUNCTION DEFINITIONS -- Start
     */
    extern int32_t	 configureSimpleLinkToDefaultState();
    static int32_t	 establishConnectionWithAP();
    static int32_t	 checkLanConnection();
    static int32_t	 checkInternetConnection();
    static int32_t	 initializeAppVariables();
    static void displayBanner();
    
    // End if Simplelink items
    
    static app_gpiote_user_id_t   m_example_user_id;
    static void example_gpiote_event_handler(uint32_t event_pins_low_to_high, uint32_t event_pins_high_to_low);
    
    
    
    /**@brief 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] 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 for handling Peer Manager events.
     *
     * @param[in] p_evt  Peer Manager event.
     */
    static void pm_evt_handler(pm_evt_t const * p_evt)
    {
        pm_handler_on_pm_evt(p_evt);
        pm_handler_disconnect_on_sec_failure(p_evt);
        pm_handler_flash_clean(p_evt);
    
        switch (p_evt->evt_id)
        {
            case PM_EVT_PEERS_DELETE_SUCCEEDED:
                scan_start();
                break;
    
            default:
                break;
        }
    }
    
    
    /**
     * @brief Function for 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 SoftDevice SoC event handler.
     *
     * @param[in] evt_id    SoC event.
     * @param[in] p_context Context.
     */
    static void soc_evt_handler(uint32_t evt_id, void * p_context)
    {
        switch (evt_id)
        {
            case NRF_EVT_FLASH_OPERATION_SUCCESS:
            /* fall through */
            case NRF_EVT_FLASH_OPERATION_ERROR:
    
                if (m_memory_access_in_progress)
                {
                    m_memory_access_in_progress = false;
                    scan_start();
                }
                break;
    
            default:
                // No implementation needed.
                break;
        }
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupt.
      */
    
    
    /**@brief Function for disabling the use of whitelist for scanning.
     */
    static void whitelist_disable(void)
    {
        if (!m_whitelist_disabled)
        {
            NRF_LOG_INFO("Whitelist temporarily disabled.");
            m_whitelist_disabled = true;
            nrf_ble_scan_stop();
            scan_start();
        }
    }
    
    
    /**@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)
    {
        ret_code_t err_code;
    
        switch (event)
        {
            case BSP_EVENT_SLEEP:
                nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
                break;
    
            case BSP_EVENT_DISCONNECT:
                err_code = sd_ble_gap_disconnect(m_conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
                break;
    
            case BSP_EVENT_WHITELIST_OFF:
                whitelist_disable();
                break;
    
            case BSP_EVENT_KEY_2:
                // Note that to simplify this example, we are not actually making any changes to our
                // database (Which is normally when you would want to send this indication).
                // Acting upon this indication (doing a rediscovery) is pointless for the peer.
                pm_local_database_has_changed();
                break;
            default:
                break;
        }
    }
    
    
    /**@brief Function for the Peer Manager initialization.
     *
     * @param[in] erase_bonds  Indicates whether bonding information should be cleared from
     *                         persistent storage during initialization of the Peer Manager.
     */
    static void peer_manager_init()
    {
        ble_gap_sec_params_t sec_param;
        ret_code_t           err_code;
    
        err_code = pm_init();
        APP_ERROR_CHECK(err_code);
    
        memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
    
        // Security parameters to be used for all security procedures.
        sec_param.bond           = SEC_PARAM_BOND;
        sec_param.mitm           = SEC_PARAM_MITM;
        sec_param.lesc           = SEC_PARAM_LESC;
        sec_param.keypress       = SEC_PARAM_KEYPRESS;
        sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
        sec_param.oob            = SEC_PARAM_OOB;
        sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
        sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
        sec_param.kdist_own.enc  = 1;
        sec_param.kdist_own.id   = 1;
        sec_param.kdist_peer.enc = 1;
        sec_param.kdist_peer.id  = 1;
    
        err_code = pm_sec_params_set(&sec_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = pm_register(pm_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Clear bond information from persistent storage.
     */
    static void delete_bonds(void)
    {
        ret_code_t err_code;
    
        NRF_LOG_INFO("Erase bonds.");
        err_code = pm_peers_delete();
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Retrive a list of peer manager peer IDs.
     *
     * @param[inout] p_peers   The buffer where to store the list of peer IDs.
     * @param[inout] p_size    In: The size of the @p p_peers buffer.
     *                         Out: The number of peers copied in the buffer.
     */
    static void peer_list_get(pm_peer_id_t * p_peers, uint32_t * p_size)
    {
        pm_peer_id_t peer_id;
        uint32_t     peers_to_copy;
    
        peers_to_copy = (*p_size < BLE_GAP_WHITELIST_ADDR_MAX_COUNT) ?
                         *p_size : BLE_GAP_WHITELIST_ADDR_MAX_COUNT;
    
        peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID);
        *p_size = 0;
    
        while ((peer_id != PM_PEER_ID_INVALID) && (peers_to_copy--))
        {
            p_peers[(*p_size)++] = peer_id;
            peer_id              = pm_next_peer_id_get(peer_id);
        }
    }
    
    
    static void whitelist_load()
    {
        ret_code_t   ret;
        pm_peer_id_t peers[8];
        uint32_t     peer_cnt;
    
        memset(peers, PM_PEER_ID_INVALID, sizeof(peers));
        peer_cnt = (sizeof(peers) / sizeof(pm_peer_id_t));
    
        // Load all peers from flash and whitelist them.
        peer_list_get(peers, &peer_cnt);
    
        ret = pm_whitelist_set(peers, peer_cnt);
        APP_ERROR_CHECK(ret);
    
        // Setup the device identities list.
        // Some SoftDevices do not support this feature.
        ret = pm_device_identities_list_set(peers, peer_cnt);
        if (ret != NRF_ERROR_NOT_SUPPORTED)
        {
            APP_ERROR_CHECK(ret);
        }
    }
    
    
    static void on_whitelist_req(void)
    {
        // Whitelist buffers.
        ble_gap_addr_t whitelist_addrs[8];
        ble_gap_irk_t  whitelist_irks[8];
    
        memset(whitelist_addrs, 0x00, sizeof(whitelist_addrs));
        memset(whitelist_irks, 0x00, sizeof(whitelist_irks));
    
        uint32_t addr_cnt = (sizeof(whitelist_addrs) / sizeof(ble_gap_addr_t));
        uint32_t irk_cnt  = (sizeof(whitelist_irks) / sizeof(ble_gap_irk_t));
    
        // Reload the whitelist and whitelist all peers.
        whitelist_load();
    
        ret_code_t err_code;
    
        // Get the whitelist previously set using pm_whitelist_set().
        err_code = pm_whitelist_get(whitelist_addrs, &addr_cnt,
                                    whitelist_irks, &irk_cnt);
    
        if (((addr_cnt == 0) && (irk_cnt == 0)) ||
            (m_whitelist_disabled))
        {
            // Don't use whitelist.
            err_code = nrf_ble_scan_params_set(&m_scan, NULL);
            APP_ERROR_CHECK(err_code);
        }
    
        NRF_LOG_INFO("Starting scan.");
    
        err_code = bsp_indication_set(BSP_INDICATE_SCANNING);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function to start scanning.
     */
    static void scan_start(void)
    {
        ret_code_t err_code;
    
        // If there is any pending write to flash, defer scanning until it completes.
        if (nrf_fstorage_is_busy(NULL))
        {
            m_memory_access_in_progress = true;
            return;
        }
    
        err_code = nrf_ble_scan_params_set(&m_scan, &m_scan_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_start(&m_scan);
        APP_ERROR_CHECK(err_code);
    
    }
    
    
    /**@brief Function for initializing buttons and LEDs.
     *
     * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
     */
    static void buttons_leds_init(bool * p_erase_bonds)
    {
        ret_code_t  err_code;
        bsp_event_t startup_event;
    
        err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
        APP_ERROR_CHECK(err_code);
    
        err_code = bsp_btn_ble_init(NULL, &startup_event);
        APP_ERROR_CHECK(err_code);
    
        *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
    }
    
    
    /**@brief Function for initializing logging. */
    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 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 initializing the power management.
     */
    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_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_WHITELIST_REQUEST:
            {
                on_whitelist_req();
                m_whitelist_disabled = false;
            } break;
    
            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_SCAN_TIMEOUT:
            {
                NRF_LOG_INFO("Scan timed out.");
                scan_start();
            } break;
    
            case NRF_BLE_SCAN_EVT_FILTER_MATCH:
                break;
            case NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT:
                break;
    
            default:
              break;
        }
    }
    
    
    /**@brief Function for initializing scanning.
     */
    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.p_scan_param     = &m_scan_param;
        init_scan.connect_if_match = 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);
    }
    
    
    /**@ Function for settings scan filters.
     */
    static void scan_filters_set(void)
    {
        ret_code_t err_code;
        ble_uuid_t target_uuid = {.uuid = TARGET_UUID, .type = BLE_UUID_TYPE_BLE};
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &target_uuid);
        APP_ERROR_CHECK(err_code);
    
        if (is_connect_per_addr)
        {
            err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, m_target_periph_addr.addr);
            APP_ERROR_CHECK(err_code);
            err_code = nrf_ble_scan_filters_enable(&m_scan,
                           NRF_BLE_SCAN_NAME_FILTER | NRF_BLE_SCAN_UUID_FILTER | NRF_BLE_SCAN_ADDR_FILTER,
                           false);
            APP_ERROR_CHECK(err_code);
        }
        else
        {
            err_code = nrf_ble_scan_filters_enable(&m_scan,
                           NRF_BLE_SCAN_NAME_FILTER | NRF_BLE_SCAN_UUID_FILTER,
                           false);
            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)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            nrf_pwr_mgmt_run();
        }
    }
    
    
    /**@brief Function for starting a scan, or instead trigger it from peer manager (after
              deleting bonds).
    
       @param[in] p_erase_bonds Pointer to a bool to determine if bonds will be deleted before scanning.
    */
    void scanning_start(bool * p_erase_bonds)
    {
        // Start scanning for peripherals and initiate connection
        // with devices that advertise GATT Service UUID.
        if (*p_erase_bonds == true)
        {
            // Scan is started by the PM_EVT_PEERS_DELETE_SUCCEEDED event.
            delete_bonds();
        }
        else
        {
            scan_start();
        }
    }
    
    
    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;
    
        pm_handler_secure_on_connection(p_ble_evt);
    
        switch (p_ble_evt->header.evt_id)
        {
            case BLE_GAP_EVT_CONNECTED:
            {
                m_conn_handle = p_gap_evt->conn_handle;
                err_code      = bsp_indication_set(BSP_INDICATE_CONNECTED);
                APP_ERROR_CHECK(err_code);
    
                if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    scan_start();
                }
            } break;
    
            case BLE_GAP_EVT_TIMEOUT:
            {
                if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
                {
                    NRF_LOG_DEBUG("Connection Request timed out.");
                }
            } 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_DISCONNECTED:
            {
                NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
                             p_gap_evt->conn_handle,
                             p_gap_evt->params.disconnected.reason);
    
                if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    scan_start();
                }
            } 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;
        }
    }
    
    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 handlers for BLE and SoC events.
        NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
        NRF_SDH_SOC_OBSERVER(m_soc_observer, APP_SOC_OBSERVER_PRIO, soc_evt_handler, NULL);
    }
    
    /**@brief Function for initializing all the modules used in this example application.
     */
    static void modules_init(void)
    {
     int status = 0;
     int x;
        // Initialize.
        SEGGER_RTT_Init();
        log_init();
    
        output(CC_NHIB_PIN);
    output(LED_RED);
    output(LED_GREEN);
    output(LED_BLUE);
    
    NRF_GPIO->OUTSET = (1<<CC_NHIB_PIN);
    NRF_GPIO->OUTSET = (1<<LED_RED);
    NRF_GPIO->OUTSET = (1<<LED_GREEN);
    NRF_GPIO->OUTSET = (1<<LED_BLUE);
    
    NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;		// set as input with pullup
    
    /*
        NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000001;		// set as output
        NRF_P0->PIN_CNF[LED_RED] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_GREEN] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_BLUE] = 0x00000001;	// set as output
    
    */
    
    
        for (x = 0; x < 5 ; x++)
        {
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        delay_ms(200);
        NRF_P0->OUTSET = (1<<(LED_GREEN));
         delay_ms(200);
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        }
        NRF_P0->OUTSET = (1<<(LED_GREEN));
        CC3100_disable();
    
     //   NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[0] = 0x00010001;	
     
         NRF_P0->PIN_CNF[BUTTON_2] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[1] = 0x00020001|((BUTTON_2)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001;	
    
            
    
         gpio_init();
        // APP_GPIOTE_INIT(1);
       
       // initGPIOINT();
     // gpio_init();
     //  initGPIOINT();
        NRF_LOG_INFO("GPIO Init completed.\r\n");
      //  timer_init();
         NRF_LOG_INFO("lOGGING started.\r\n");
    status = SEGGER_RTT_WriteString(0, "writing to channel 0");
       // buttons_leds_init(&m_erase_bonds);
      //  power_management_init();
      //  ble_stack_init();
      //  gatt_init();
      //  peer_manager_init();
      //  scan_init();
       // scan_filters_set();
    }
    
    
    // Simplelink handlers and functions
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        if(pWlanEvent == NULL)
        {
            CLI_Write((_u8 *)" [WLAN EVENT] NULL Pointer Error \n\r");
            return;
        }
        
        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
    
                /*
                 * Information about the connected AP (like name, MAC etc) will be
                 * available in 'slWlanConnectAsyncResponse_t' - Applications
                 * can use it if required
                 *
                 * slWlanConnectAsyncResponse_t *pEventData = NULL;
                 * pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
                 *
                 */
                   CLI_Write((_u8 *)" WLAN connect event. \n\r");
            }
            break;
    
            case SL_WLAN_DISCONNECT_EVENT:
            {
                slWlanConnectAsyncResponse_t*  pEventData = NULL;
    
                CLR_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;
    
                /* If the user has initiated 'Disconnect' request, 'reason_code' is SL_USER_INITIATED_DISCONNECTION */
                if(SL_WLAN_DISCONNECT_USER_INITIATED_DISCONNECTION == pEventData->reason_code)
                {
                    CLI_Write((_u8 *)" Device disconnected from the AP on application's request \n\r");
                }
                else
                {
                    CLI_Write((_u8 *)" Device disconnected from the AP on an ERROR..!! \n\r");
                }
            }
            break;
    
            default:
            {
                CLI_Write((_u8 *)" [WLAN EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    /*!
        \brief This function handles events for IP address acquisition via DHCP
               indication
    
        \param[in]      pNetAppEvent is the event passed to the handler
    
        \return         None
    
        \note
    
        \warning
    */
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if(pNetAppEvent == NULL)
        {
            CLI_Write((_u8 *)" [NETAPP EVENT] NULL Pointer Error \n\r");
            return;
        }
     
        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;
    
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_GatewayIP = pEventData->gateway;
            }
            break;
    
            default:
            {
                CLI_Write((_u8 *)" [NETAPP EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    /*!
        \brief This function handles callback for the HTTP server events
    
        \param[in]      pHttpEvent - Contains the relevant event information
        \param[in]      pHttpResponse - Should be filled by the user with the
                        relevant response information
    
        \return         None
    
        \note
    
        \warning
    */
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent,
                                      SlHttpServerResponse_t *pHttpResponse)
    {
        /*
         * This application doesn't work with HTTP server - Hence these
         * events are not handled here
         */
        CLI_Write((_u8 *)" [HTTP EVENT] Unexpected event \n\r");
    }
    
    
    /*!
        \brief This function handles ping report events
    
        \param[in]      pPingReport holds the ping report statistics
    
        \return         None
    
        \note
    
        \warning
    */
    static void SimpleLinkPingReport(SlPingReport_t *pPingReport)
    {
        SET_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
    
        if(pPingReport == NULL)
        {
            CLI_Write((_u8 *)" [PING REPORT] NULL Pointer Error\r\n");
            return;
        }
    
        g_PingPacketsRecv = pPingReport->PacketsReceived;
    }
    
    /*!
        \brief This function handles general error events indication
    
        \param[in]      pDevEvent is the event passed to the handler
    
        \return         None
    */
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
    {
        /*
         * Most of the general errors are not FATAL are are to be handled
         * appropriately by the application
         */
        CLI_Write((_u8 *)" [GENERAL EVENT] handler \n\r");
    
        if(pDevEvent == NULL)
        {
            CLI_Write((_u8 *)" [General EVENT] NULL Pointer Error \n\r");
            return;
        }
     
    
    /*
    
     SL_DEVICE_GENERAL_ERROR_EVENT = 1,
        SL_DEVICE_ABORT_ERROR_EVENT,
        SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT,
        SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE,
        SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN,
        SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT,
        SL_DEVICE_ERROR_MAX
    
        */
    
        switch(pDevEvent->Event)
        {
    
        case SL_DEVICE_GENERAL_ERROR_EVENT :
    
         CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_GENERAL_ERROR_EVENT \n\r");
    break;
        case SL_DEVICE_ABORT_ERROR_EVENT :
        CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_ABORT_ERROR_EVENT\n\r");
        break;
    
        case SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_ASSERT_ERROR_EVENT\n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_CMD_COMPLETE\n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_SYNC_PATTERN \n\r");
    break;
        case SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_DRIVER_TIMEOUT_ASYNC_EVENT\n\r");
    break;
        case SL_DEVICE_ERROR_MAX :
    CLI_Write((_u8 *)" [GENERAL EVENT] handler SL_DEVICE_ERROR_MAX\n\r");
    break;
    
      default :
      CLI_Write((_u8 *)" [GENERAL EVENT] handler number %d \n\r", pDevEvent->Event );
    
        }
    }
    
    /*!
        \brief This function handles socket events indication
    
        \param[in]      pSock is the event passed to the handler
    
        \return         None
    */
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
        /*
         * This application doesn't work w/ socket - Hence not handling these events
         */
        CLI_Write((_u8 *)" [SOCK EVENT] Unexpected event \n\r");
    }
    /*
     * ASYNCHRONOUS EVENT HANDLERS -- End
     */
    
     //****End of Simplelink handlers and functions
    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    void ReadVersion(void)
    {
    	SlVersionFull 		ver;
        	_u8 				pConfigOpt, pConfigLen;
    	_i32         		retVal = 0;
    	
    	/* read the version and print it on terminal */
    	pConfigOpt = SL_DEVICE_GENERAL_VERSION;
    	pConfigLen = sizeof(SlVersionFull);
    	retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&pConfigOpt,&pConfigLen,(_u8 *)(&ver));
    
    	if(retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nReading version failed. Error code: %d\r\n", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    	}
    
    	if (ver.ChipFwAndPhyVersion.ChipId & 0x10)
    		CLI_Write((_u8 *)"\r\nThis is a CC3200");
    	else
    		CLI_Write((_u8 *)"\r\nThis is a CC3100");
    
    	if (ver.ChipFwAndPhyVersion.ChipId & 0x2)
    		CLI_Write((_u8 *)"Z device\r\n");
    	else
    		CLI_Write((_u8 *)"R device\r\n");
    
    	sprintf(printBuffer, "NWP %d.%d.%d.%d\n\rMAC 31.%d.%d.%d.%d\n\rPHY %d.%d.%d.%d\n\r\n\r", \
    			(_u8)ver.NwpVersion[0],(_u8)ver.NwpVersion[1],(_u8)ver.NwpVersion[2],(_u8)ver.NwpVersion[3], \
    				 (_u8)ver.ChipFwAndPhyVersion.FwVersion[0],(_u8)ver.ChipFwAndPhyVersion.FwVersion[1], \
    				 (_u8)ver.ChipFwAndPhyVersion.FwVersion[2],(_u8)ver.ChipFwAndPhyVersion.FwVersion[3], \
    				 ver.ChipFwAndPhyVersion.PhyVersion[0],(_u8)ver.ChipFwAndPhyVersion.PhyVersion[1], \
    				 ver.ChipFwAndPhyVersion.PhyVersion[2],(_u8)ver.ChipFwAndPhyVersion.PhyVersion[3]);
    
    	CLI_Write((_u8 *)printBuffer);
    }
     cc3100_fw()
     {
     i32         fileHandle = -1;
    
     _u32        Token = 0;
      _i32       retVal = 0;
        _u32     remainingLen, movingOffset, chunkLen;
    #define FORMAT_ENABLE = 1
    
      /* Initializing the CC3100 device */
    
      
        sl_Start(0, 0, 0);
    
     
    
        /* create/open the servicepack file for 128KB with rollback, secured and public write */
    	CLI_Write((_u8 *)"\r\nOpenning ServicePack file");
    	retVal = sl_FsOpen("/sys/servicepack.ucf" ,
    					   FS_MODE_OPEN_CREATE(LEN_128KB, _FS_FILE_OPEN_FLAG_SECURE | _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
    					   &Token, &fileHandle);
    	if(retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nCannot open ServicePack file. Error code: %d", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    		return -1;
    	}
    
    	/* program the servicepack */
    	CLI_Write((_u8 *)"\r\nProgramming ServicePack file");
    
    	remainingLen = sizeof(ota_1_0_1_13_2_11_0_1_ucf);
    	movingOffset = 0;
    	chunkLen = (_u32)find_min(CHUNK_LEN, remainingLen);
    
    	/* Flashing must be done in 1024 bytes chunks */
    	do
    	{
    		retVal = sl_FsWrite(fileHandle, movingOffset, (_u8 *)&ota_1_0_1_13_2_11_0_1_ucf[movingOffset], chunkLen);
    		if (retVal < 0)
    		{
    			sprintf(printBuffer, "\r\nCannot program ServicePack file. Error code: %d", (int)retVal);
    			CLI_Write((_u8 *)printBuffer);
    
    			//turnLedOn(LED1);
    			return -1;
    		}
    
    		remainingLen -= chunkLen;
    		movingOffset += chunkLen;
    		chunkLen = (_u32)find_min(CHUNK_LEN, remainingLen);
    	}while (chunkLen > 0);
    
    	/* close the servicepack file */
    	CLI_Write((_u8 *)"\r\nClosing ServicePack file");
    	retVal = sl_FsClose(fileHandle, 0, (_u8 *)ota_1_0_1_13_2_11_0_1_ucf, sizeof(ota_1_0_1_13_2_11_0_1_ucf));
    
    	if (retVal < 0)
    	{
    		sprintf(printBuffer, "\r\nCannot close ServicePack file. Error code: %d", (int)retVal);
    		CLI_Write((_u8 *)printBuffer);
    
    		//turnLedOn(LED1);
    		return -1;
    	}
    
    	CLI_Write((_u8 *)"\r\nServicePack successfuly programmed\r\n\r\n");
    
    	/* Turn On the Green LED */
    	//turnLedOn(LED2);
    
    	CLI_Write((_u8 *)"Restarting CC3100... ");
    	/* Stop the CC3100 device */
    	sl_Stop(0xFF);
    
    	/* Initializing the CC3100 device */
    	sl_Start(0, 0, 0);
    
    	ReadVersion();
    
    	return 0;
    
    
     }
    
    void initGPIOINT(void)
    {
        ret_code_t err_code;
    	g_btn_state = (BTN_STATE_IDLE);
    
    	NRF_GPIOTE->EVENTS_IN[0] = 0;
    	NRF_GPIOTE->EVENTS_IN[1] = 0;
     
    	
    	NRF_P0->PIN_CNF[PBTN_PIN] = 0x0000000C;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00020001|((PBTN_PIN)<<8);	// event mode, high to low transition
    	
    	
    	NRF_GPIOTE->INTENCLR = 0x00000002;	
    	NRF_GPIOTE->INTENSET = 0x00000001;									
        NVIC_EnableIRQ(GPIOTE_IRQn);										
    
    #ifdef SYSTEM_DEBUG
    	printUART0("-> GPIOINT: init [DONE]\n",0);
    #endif
    
    }
    void Button_IRQHandler(void)
    {/// GPIOTE IRQ service routine
      
      nrf_drv_gpiote_out_toggle(LED_RED);
    
       if (startup) return;
    	
    	NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		//NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	
    	
    	
    }
    
    void CC3100_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	
    	chkCC3100IRQ();
          //  NRF_GPIOTE->EVENTS_IN[0] = 0;
    }
    
    
    
    void gpio_init(void)
    {
        ret_code_t err_code;
    
         // APP_GPIOTE_INIT(1);
    
         if (!nrf_drv_gpiote_is_init())
            {
                    err_code = nrf_drv_gpiote_init();
                    APP_ERROR_CHECK(err_code);
            }
            
    
        nrf_drv_gpiote_out_config_t out_config = GPIOTE_CONFIG_OUT_SIMPLE(true);
    
            err_code = nrf_drv_gpiote_out_init(CC_NRST_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
          err_code = nrf_drv_gpiote_out_init(LED_RED, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
            err_code = nrf_drv_gpiote_out_init(CC_NHIB_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
         // Make a configuration for input pins. This is suitable for both pins in this example.
        nrf_drv_gpiote_in_config_t in_config = {// = GPIOTE_CONFIG_IN_SENSE_LOTOHI(true);
          .is_watcher = false,                        \
           .hi_accuracy = true,                     \
            .pull = NRF_GPIO_PIN_PULLUP,                \
            .sense = NRF_GPIOTE_POLARITY_LOTOHI
            };
    
         err_code = nrf_drv_gpiote_in_init(CC_IRQ_PIN, &in_config, CC3100_IRQHandler);
        APP_ERROR_CHECK(err_code);
       
        in_config.hi_accuracy = true;
        in_config.pull = NRF_GPIO_PIN_PULLUP;
        in_config.sense = NRF_GPIOTE_POLARITY_HITOLO;
        
         err_code = nrf_drv_gpiote_in_init(BUTTON_2, &in_config, Button_IRQHandler);
        APP_ERROR_CHECK(err_code);
    
        //    nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
          nrf_drv_gpiote_in_event_enable(BUTTON_2, true);
        
      
     
    }
    
    static void example_gpiote_event_handler(uint32_t event_pins_low_to_high, uint32_t event_pins_high_to_low)
    {
      nrf_drv_gpiote_out_toggle(LED_RED);
    
    }
    
    void newint(void)
    {
    
    uint32_t  low_to_high_bitmask = (0x00000000 | (3<<26)); // Bitmask to be notified of transition from low to high for GPIO 0-3
    uint32_t  high_to_low_bitmask = (0x00000000 | (3<<26)); // Bitmask to be notified of transition from high to low for GPIO 0-2
    uint32_t retval;
    retval = app_gpiote_user_register(&m_example_user_id,
                                      low_to_high_bitmask,
                                      high_to_low_bitmask,
                                      example_gpiote_event_handler);
    if (retval != NRF_SUCCESS)
    {
        // Failed to register with user with GPIO module!
    }
    
    }
    
    int main(void)
    {
    
        // Initialize.
    
       // P_EVENT_HANDLER = &SimpleLinkGeneralEventHandler;
        
        modules_init();
      //  whitelist_load();
    
        // Start execution.
        NRF_LOG_INFO("GATT Service server started.\r\n");
      //  scanning_start(&m_erase_bonds);
    
      // GPIOTE user identifier for the example module.
    
    // GPIOTE event handler.
    
    
    
      //cc3100_fw();
      //newint();
     
     CC3100_InterruptEnable();
    
        // Enter main loop.
        for (;;)
        {
           __NOP();
    
        
        
        //    idle_state_handle();
             int32_t retVal = -1;
    
        retVal = initializeAppVariables();
        ASSERT_ON_ERROR(retVal);
    
        /* Stop WDT and initialize the system-clock of the MCU */
      //  stopWDT();
      //  initClk();
    
        /* Configure command line interface */
       // CLI_Configure();
    
        displayBanner();
    
        /*
         * Following function configures the device to default state by cleaning
         * the persistent settings stored in NVMEM (viz. connection profiles &
         * policies, power policy etc)
         *
         * Applications may choose to skip this step if the developer is sure
         * that the device is in its default state at start of application
         *
         * Note that all profiles and persistent settings that were done on the
         * device will be lost
         */
        retVal = configureSimpleLinkToDefaultState();
        if(retVal < 0)
        {
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
                CLI_Write((_u8 *)" Failed to configure the device in its default state \n\r");
    
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device is configured in default state \n\r");
    
        /*
         * Assumption is that the device is configured in station mode already
         * and it is in its default state
         */
        retVal = sl_Stop(SL_STOP_TIMEOUT);
        retVal = sl_Start(0, 0, 0);
        if ((retVal < 0) ||
            (ROLE_STA != retVal) )
        {
            CLI_Write((_u8 *)" Failed to start the device \n\r");
            LOOP_FOREVER();
        }
    
         ReadVersion();
    
        CLI_Write((_u8 *)" Device started as STATION \n\r");
    
        /* Connecting to WLAN AP */
        retVal = establishConnectionWithAP();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Failed to establish connection w/ an AP \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Connection established w/ AP and IP is acquired \n\r");
        CLI_Write((_u8 *)" Pinging...! \n\r");
    
        retVal = checkLanConnection();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Device couldn't connect to LAN \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device successfully connected to the LAN\r\n");
    
        retVal = checkInternetConnection();
        if(retVal < 0)
        {
            CLI_Write((_u8 *)" Device couldn't connect to the internet \n\r");
            LOOP_FOREVER();
        }
    
        CLI_Write((_u8 *)" Device successfully connected to the internet \n\r");
        return 0;
        }
    }
    
    static int32_t establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    
    /*!
        \brief This function checks the LAN connection by pinging the AP's gateway
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 checkLanConnection()
    {
        SlPingStartCommand_t pingParams = {0};
        SlPingReport_t pingReport = {0};
    
        _i32 retVal = -1;
    
        CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    
        /* Set the ping parameters */
        pingParams.PingIntervalTime = PING_INTERVAL;
        pingParams.PingSize = PING_PKT_SIZE;
        pingParams.PingRequestTimeout = PING_TIMEOUT;
        pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
        pingParams.Flags = 0;
        pingParams.Ip = g_GatewayIP;
    
        /* Check for LAN connection */
        retVal = sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                                     (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while(!IS_PING_DONE(g_Status)) { _SlNonOsMainLoopTask(); }
    
        if(0 == g_PingPacketsRecv)
        {
            /* Problem with LAN connection */
            ASSERT_ON_ERROR(LAN_CONNECTION_FAILED);
        }
    
        /* LAN connection is successful */
        return SUCCESS;
    }
    
    /*!
        \brief This function checks the internet connection by pinging
               the external-host (HOST_NAME)
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 checkInternetConnection()
    {
        SlPingStartCommand_t pingParams = {0};
        SlPingReport_t pingReport = {0};
    
        _u32 ipAddr = 0;
    
        _i32 retVal = -1;
    
        CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    
        /* Set the ping parameters */
        pingParams.PingIntervalTime = PING_INTERVAL;
        pingParams.PingSize = PING_PKT_SIZE;
        pingParams.PingRequestTimeout = PING_TIMEOUT;
        pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
        pingParams.Flags = 0;
        pingParams.Ip = g_GatewayIP;
    
        /* Check for Internet connection */
        retVal = sl_NetAppDnsGetHostByName((_i8 *)HOST_NAME, pal_Strlen(HOST_NAME), &ipAddr, SL_AF_INET);
        ASSERT_ON_ERROR(retVal);
    
        /* Replace the ping address to match HOST_NAME's IP address */
        pingParams.Ip = ipAddr;
    
        /* Try to ping HOST_NAME */
        retVal = sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                                     (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while(!IS_PING_DONE(g_Status)) { _SlNonOsMainLoopTask(); }
    
        if (0 == g_PingPacketsRecv)
        {
            /* Problem with internet connection*/
            ASSERT_ON_ERROR(INTERNET_CONNECTION_FAILED);
        }
    
        /* Internet connection is successful */
        return SUCCESS;
    }
    
    /*!
        \brief This function initializes the application variables
    
        \param[in]  None
    
        \return     0 on success, negative error-code on error
    */
    static _i32 initializeAppVariables()
    {
        g_Status = 0;
        g_PingPacketsRecv = 0;
        g_GatewayIP = 0;
    
        return SUCCESS;
    }
    
    /*!
        \brief This function displays the application's banner
    
        \param      None
    
        \return     None
    */
    static void displayBanner()
    {
        CLI_Write((_u8 *)"\n\r\n\r");
        CLI_Write((_u8 *)" Getting started with station application - Version ");
        CLI_Write((_u8 *) APPLICATION_VERSION);
        CLI_Write((_u8 *)"\n\r*******************************************************************************\n\r");
    }
    

    Here is the supporting .c file for the spi functions :
    #include "stdint.h"
    #include "sl_common.h"
    
    #include "medsense.h"
    #include "simplelink.h"
    #include "nrf_drv_gpiote.h"
    #include "nrf_delay.h"
    
    //#include "user.h"
    
    
    
    
    
    const uint8_t g_firmware_version[6] = "1.0.3";
    
    volatile uint8_t g_led_blink_pin;
    volatile uint32_t g_led_blink_period;
    volatile uint32_t g_led_blink_timer;
    volatile uint8_t g_led_flag;
    
    volatile uint8_t g_flash_sms;
    volatile uint32_t g_flash_timer;
    const uint32_t FLASH_USER_SIGN[FLASH_USER_SIGN_WSIZE] = {0x474F4749, 0x4341534D, 0x49523230, 0x31360000};
    volatile uint32_t g_flash_page[FLASH_PAGE_SIZE_IN_WORDS];
    
    static volatile SlSockAddrIn_t  Addr;
    static volatile SlSockAddrIn_t  LocalAddr;
    static volatile SlSockAddrIn_t  Rem_Addr;
    
    //void 		SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent);
    //void 		SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent);
    //void 		SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent, SlHttpServerResponse_t *pHttpResponse);
    void 		SimpleLinkPingReport(SlPingReport_t *pPingReport);
    void 		SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent);
    //void 		SimpleLinkSockEventHandler(SlSockEvent_t *pSock);
    
    volatile uint8_t g_btn_state;
    
    volatile uint8_t g_ble_rx_buff[BLE_RX_BUFF_SIZE];
    volatile uint16_t g_ble_rx_buff_len;
    volatile uint8_t g_ble_rx_data[BLE_RX_DATA_BUFF_SIZE];
    volatile uint16_t g_ble_rx_data_widx;
    volatile uint16_t g_ble_rx_data_ridx;
    volatile uint8_t g_ble_tx_buff[WIFI_BUFF_SIZE];
    volatile uint16_t g_blef_tx_count;
    
    volatile uint8_t g_flash_update;
    
    
    volatile uint8_t g_wifi_tx_buff[WIFI_BUFF_SIZE];
    volatile uint8_t g_wifi_rx_buff[WIFI_RX_BUFF_SIZE];
    volatile uint8_t g_wifi_pkt[WIFI_BUFF_SIZE];
    volatile uint16_t g_wifi_rx_buff_widx;
    volatile uint16_t g_wifi_rx_buff_ridx;
    volatile uint8_t g_wifi_status;
    volatile uint8_t g_wifi_error;
    volatile uint8_t g_wifi_mode;
    volatile uint8_t g_wifi_ssid[WIFI_SSID_SIZE];
    volatile uint8_t g_wifi_passwd[WIFI_PASSWD_SIZE];
    volatile uint32_t g_wifi_port;
    volatile uint32_t g_wifi_enc;
    volatile uint32_t g_wifi_remote_server_ip;
    volatile uint8_t g_device_name[DEVICE_NAME_SIZE];
    volatile uint8_t g_device_id[DEVICE_ID_SIZE];
    volatile uint8_t g_flash_write_data[FLASH_WRITE_DATA_SIZE];
    volatile uint8_t g_wifi_local_ip_str[20];
    volatile uint8_t g_wifi_remote_server_ip_str[20];
    volatile int16_t g_wifi_remote_cli_socket = -1;
    
    //#include "wifi.h"
    
    volatile int16_t g_wifi_ser_socket = -1;
    volatile int16_t g_wifi_local_cli_socket = -1;
    volatile uint8_t g_wifi_data[WIFI_BUFF_SIZE];
    volatile uint16_t g_wifi_rx_buff_byte_cnt;
    volatile uint16_t g_wifi_pkt_len;
    volatile uint8_t g_wifi_pkt_type;
    volatile uint32_t g_wifi_rc_conn_timer;
    
    typedef struct
    {
      unsigned char     connection_type;/* 0-STA,3-P2P_CL */
      unsigned char     ssid_len;
      unsigned char     ssid_name[32];
      unsigned char     go_peer_device_name_len;
      unsigned char     go_peer_device_name[32];
      unsigned char     bssid[6];
      unsigned char     reason_code;
      unsigned char     padding[2];
    } sl_protocol_wlanConnectAsyncResponse_t;
    
    
    volatile P_EVENT_HANDLER        pIrqEventHandler = 0;
    
    volatile bool IntIsMasked;
    
    
    
    const uint8_t c_wifi_preambule[3] = {0xA5, 0xAA, 0x5A};
    
    /*
    void CC3100_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    */
    void ASSERT_ON_ERROR(retVal)
    {
        NRF_LOG_INFO("Assert from simplelink function : %d", retVal);
        
       
    }
    void CC3100_disable()
    {
    	CC3100_NHIB_LOW;
          //  nrf_drv_gpiote_out_clear(CC_NHIB_PIN);
    	delay_ms(100);
    }
    
    
    void do_CC3100_NRST_HIGH(void)
    {
        CC3100_NRST_HIGH;
        // nrf_drv_gpiote_set(CC_NHIB_PIN);
    }
    
    void output(int pin)
    {
    	  NRF_GPIO->PIN_CNF[pin] = (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) |
                                       (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) |
                                       (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos) |
                                       (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) |
                                       (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
    }
    void CC3100_enable()
    {
    	CC3100_NHIB_HIGH;
           // nrf_drv_gpiote_out_set(CC_NHIB_PIN);
    	delay_ms(500);
    }
    
    void CC3100_InterruptEnable()
    {	
    	//NVIC_DisableIRQ(GPIOTE_IRQn);
            //NRF_GPIOTE->INTENSET = 0x00000002;	
    	//NRF_GPIOTE->EVENTS_IN[1] = 0;									
        //NVIC_EnableIRQ(GPIOTE_IRQn);
    
         nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
         
    }
    
    void CC3100_InterruptDisable()
    {
    	//NVIC_DisableIRQ(GPIOTE_IRQn);
    	//NRF_GPIOTE->INTENCLR = 0x00000002;	
    	//NRF_GPIOTE->EVENTS_IN[1] = 0;								
        NVIC_EnableIRQ(GPIOTE_IRQn);	
    
        nrf_drv_gpiote_in_event_disable(CC_IRQ_PIN);
    }
    
    void MaskIntHdlr()
    {
    	IntIsMasked = TRUE;
    }
    
    void UnMaskIntHdlr()
    {
    	IntIsMasked = FALSE;
    }
    
    void Delay(unsigned long interval)
    {/// system delay func
    	delay_ms(interval);
    }
    
    void chkCC3100IRQ(void)
    {
    	if(pIrqEventHandler)
    	{
    		pIrqEventHandler(0);
    	}
    }
    
    
    
    int spi_Close(Fd_t fd)
    {
        CC3100_InterruptDisable();
    
        return 0;
    }
    
    Fd_t spi_Open(char *ifName, unsigned long flags)
    {
    	NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000301;
    	CC3100_NHIB_LOW;
           // nrf_drv_gpiote_out_clear(CC_NHIB_PIN);
    	
    	NRF_P0->PIN_CNF[CC_CS_PIN] = 0x00000301;
    	SPI1_CS_HIGH;
    	
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// init SPI
    	//------------------------------------------------------------------
    	NRF_P0->PIN_CNF[CC_SCK_PIN] = 0x00000001;							// set as output
    	NRF_P0->PIN_CNF[CC_MISO_PIN] = 0x00000000;							// set as input
    	NRF_P0->PIN_CNF[CC_MOSI_PIN] = 0x00000001;							// set as output
    
    	NRF_SPI1->PSEL.SCK  = (CC_SCK_PIN);										
    	NRF_SPI1->PSEL.MISO = (CC_MISO_PIN);										
    	NRF_SPI1->PSEL.MOSI = (CC_MOSI_PIN);
    	
        NRF_SPI1->FREQUENCY = (SPI_DATARATE_1Mbps);							// set SPI clock rate
    	NRF_SPI1->CONFIG  = 0x00;											// Tx MSB first, CPHA_Leading, CPOL_ActiveHigh
        NRF_SPI1->EVENTS_READY = 0x00;										// clear the status flags
        NRF_SPI1->ENABLE = 0x00000001;										// enable SPI0
    
    
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// setup IRQ on falling edge
    	//------------------------------------------------------------------
    	NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;							// set as input with pullup
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	NRF_GPIOTE->CONFIG[1] = 0x00010001; // event mode, low to high transition
    	
    	delay_ms(100);
    	CC3100_InterruptEnable();
    
        return NONOS_RET_OK;
    }
    
    
    int spi_Write(Fd_t fd, unsigned char *pBuff, int len)
    {
        uint16_t k;
    
    	SPI1_CS_LOW;
    	//delay_us(5);
    	
    	for(k=0;k<len;k++)
    	{
    		txByteSPI1(pBuff[k]); 											// write data SPI data register
    		//delay_us(2);													// must be here as seen by spi test routine
    	}
    	
        SPI1_CS_HIGH;
    	//delay_us(5);
    	
        return len;
    }
    
    int spi_Read(Fd_t fd, unsigned char *pBuff, int len)
    {
        uint16_t k;
    
        SPI1_CS_LOW;
    	//delay_us(5);
        
        for(k=0;k<len;k++)
    	{
    		pBuff[k] = rxByteSPI1();
    		nrf_delay_us(1);													// must be here as seen by spi test routine
    	}
    	
        SPI1_CS_HIGH;
    	//delay_us(5);
    	
        return len;
    }
    
    int32_t initializeAppVariables(void)
    {
        g_Status = 0;
        g_PingPacketsRecv = 0;
        g_StationIP = 0;
        g_GatewayIP = 0;
    
        return SUCCESS;
    }
    
    int32_t  configureSimpleLinkToDefaultState()
    {
        SlVersionFull   ver = {0};
        _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};
    
        _u8           val = 1;
        _u8           configOpt = 0;
        _u8           configLen = 0;
        _u8           power = 0;
    
        _i32          retVal = -1;
        _i32          mode = -1;
    
        mode = sl_Start(0, 0, 0);
        ASSERT_ON_ERROR(mode);
    
        /* If the device is not in station-mode, try configuring it in station-mode */
        if (ROLE_STA != mode)
        {
            if (ROLE_AP == mode)
            {
                /* If the device is in AP mode, we need to wait for this event before doing anything */
                while(!IS_IP_ACQUIRED(g_Status)) { _SlNonOsMainLoopTask(); }
            }
    
            /* Switch to STA role and restart */
            retVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(retVal);
    
            retVal = sl_Stop(SL_STOP_TIMEOUT);
            ASSERT_ON_ERROR(retVal);
    
            retVal = sl_Start(0, 0, 0);
            ASSERT_ON_ERROR(retVal);
    
            /* Check if the device is in station again */
            if (ROLE_STA != retVal)
            {
                /* We don't want to proceed if the device is not coming up in station-mode */
                ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE);
            }
        }
    
        /* Get the device's version-information */
        configOpt = SL_DEVICE_GENERAL_VERSION;
        configLen = sizeof(ver);
        retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (_u8 *)(&ver));
        ASSERT_ON_ERROR(retVal);
    
        /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */
        retVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Remove all profiles */
        retVal = sl_WlanProfileDel(0xFF);
        ASSERT_ON_ERROR(retVal);
    
        /*
         * Device in station-mode. Disconnect previous connection if any
         * The function returns 0 if 'Disconnected done', negative number if already disconnected
         * Wait for 'disconnection' event if 0 is returned, Ignore other return-codes
         */
        retVal = sl_WlanDisconnect();
        if(0 == retVal)
        {
            /* Wait */
            while(IS_CONNECTED(g_Status)) { _SlNonOsMainLoopTask(); }
        }
    
        /* Enable DHCP client*/
        retVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);
        ASSERT_ON_ERROR(retVal);
    
        /* Disable scan */
        configOpt = SL_SCAN_POLICY(0);
        retVal = sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Set Tx power level for station mode
           Number between 0-15, as dB offset from max power - 0 will set maximum power */
        power = 0;
        retVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (_u8 *)&power);
        ASSERT_ON_ERROR(retVal);
    
        /* Set PM policy to normal */
        retVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Unregister mDNS services */
        retVal = sl_NetAppMDNSUnRegisterService(0, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Remove  all 64 filters (8*8) */
        pal_Memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
        retVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
                           sizeof(_WlanRxFilterOperationCommandBuff_t));
        ASSERT_ON_ERROR(retVal);
    
        retVal = sl_Stop(SL_STOP_TIMEOUT);
        ASSERT_ON_ERROR(retVal);
    
        retVal = initializeAppVariables();
        ASSERT_ON_ERROR(retVal);
    
        return retVal; /* Success */
    }
    /*
    void bsp_board_led_on(uint32_t led_idx)
    {
     // NRF_LOG_INFO("Turn on LED idx here .");
    }
    void bsp_board_leds_on(void)
    {
      //NRF_LOG_INFO("Turn on LEDs idx here .");
    }
    void bsp_board_leds_off(void)
    {
      //NRF_LOG_INFO("Turn off LEDs idx here .");
    }
    void bsp_board_led_off(uint32_t led_idx)
    {
     // NRF_LOG_INFO("Turn off LED idx here .");
    }
    void bsp_board_led_invert(uint32_t led_idx)
    {
    //  NRF_LOG_INFO("Turn invert LED idx here .");
    }
    bool bsp_board_led_state_get(uint32_t led_idx)
    {
    //  NRF_LOG_INFO("Get LED board state here .");
      return true;
    }
    void bsp_board_init(uint32_t led_idx)
    {
      //NRF_LOG_INFO("Get LED board init state here .");
    }
    
    uint32_t bsp_board_pin_to_button_idx(uint32_t pin_number)
    {
     //NRF_LOG_INFO("bsp_board_pin_to_button_idx function  .");
    }
    
    uint32_t bsp_board_button_idx_to_pin(uint32_t pin_number)
    {
     // NRF_LOG_INFO("bsp_board_button_idx_to_pin function  .");
    }
    */
    void initWIFI(void)
    {/// init CC3100 reset pin and socket id
    	g_wifi_rx_buff_widx = 0;
    	g_wifi_rx_buff_ridx = (WIFI_RX_BUFF_MASK);
    	g_wifi_status = (WIFI_ENABLED);
    	getStr4AddrMISC((uint8_t *)g_wifi_remote_server_ip_str, g_wifi_remote_server_ip);
    	g_wifi_rc_conn_timer = getRTC2();
    	
    	NRF_P0->PIN_CNF[CC_NRST_PIN] = 0x00000301;
    	CC3100_NRST_HIGH;
    	//g_wifi_mode = (WIFI_MODE_STA);
    	//g_wifi_enc = (SL_SEC_TYPE_WPA);
    	//cpyStrMISC(g_wifi_ssid, "Dune2");
    	//cpyStrMISC(g_wifi_passwd, "palas512");
    	//g_wifi_remote_server_ip = 0xC0A80168;
    	//g_wifi_remote_server_ip = 0xC0A80167;
    	
    	if(g_wifi_mode == (WIFI_MODE_AP))
    	{// configure CC31xx in AP mode
    		g_wifi_error = setAPmodeWIFI((uint8_t *)g_wifi_ssid, (uint8_t *)g_wifi_passwd, g_wifi_port, g_wifi_enc);	
    	}
    	else
    	{// configure CC31xx in STA mode
    		g_wifi_error = setSTAmodeWIFI((uint8_t *)g_wifi_ssid, (uint8_t *)g_wifi_passwd, g_wifi_port, g_wifi_enc);
    	}
    		
    	if(g_wifi_error != (WIFI_OK))
    	{
    		g_wifi_status = (WIFI_DISABLED);
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: failed, rebooting [%x]...\n",g_wifi_mode);
    #endif		
    		if(g_wifi_mode == (WIFI_MODE_STA))
    		{// restore default AP mode
    			setDefaultFLASH();
    		}
    		
    		NVIC_SystemReset();
    	}
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: init completed\n");
    #endif	
    
    }
    
    void rstWIFI(void)
    {/// reset CC3100 chip
    	CC3100_NRST_LOW;
    	delay_ms(5);
    	CC3100_NRST_HIGH;
    }
    
    void powerDownWIFI(void)
    {/// put the wifi module into sleep mode
    	g_wifi_ser_socket = -1;
    	g_wifi_local_cli_socket = -1;
    	g_wifi_remote_cli_socket = -1;
    	CC3100_disable();													// put CC3100 in sleep mode
    }
    
    uint8_t setAPmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc)
    {/// set AP mode for CC3100
    	uint32_t timer;
    	
    	uint32_t utmp32;
    	int16_t socket;
    	uint32_t addr_offset;
    	uint8_t str[4];
    	
    	SlPingStartCommand_t PingParams = {0};
        SlPingReport_t Report = {0};
        _NetCfgIpV4Args_t ipV4 = {0};
        SlNetAppDhcpServerBasicOpt_t dhcpParams = {0};
    
        unsigned char SecType = 0;
        uint32_t mode = ROLE_STA;
        uint32_t retVal = -1;
    
    #ifdef SYSTEM_DEBUG
    	printUART("\n-> WIFI: AP mode setup initiated....\n");
    #endif
    
    
        retVal = initializeAppVariables();									// init CC3100 variables
    	
    	rstWIFI();															
    	
    	
    	CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = 0;
    	
        retVal = configureSimpleLinkToDefaultState();						// set default state to STA mode, clear all settings
       
        if(retVal != ROLE_STA)
        {
    #ifdef SYSTEM_DEBUG
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
            {
    			printUART("-> WIFI: Failed to configure the device to default state\n");
    		}
    		else
    		{
    			printUART("-> WIFI: Failed!\n");
    		}
    #endif			
            return (WIFI_ERROR_SET_DEF);
        }
    	    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device is configured in default state\n");
    #endif
    	
    	retVal = sl_Start(0, 0, 0);	
        if (retVal == (ROLE_AP))
        {// if the device is in AP mode, we need to wait 
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: device was AP mode...\n");
    #endif
    		timer = getRTC2();
    		while(!IS_IP_AQUIRED(g_Status))									
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
        else
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: device was STA mode...\n");
    #endif
            sl_WlanSetMode(ROLE_AP);										// configure CC3100 to start in AP mode
            sl_Stop(0xFF);													// stop CC3100 device
            mode = sl_Start(0, 0, 0);										// start the CC3100 and check the mode
            
    		timer = getRTC2();											// If the device is in AP mode, we need to wait 
    		while(!IS_IP_AQUIRED(g_Status))									// for this event before doing anything 
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device started in AP mode\n");
    #endif	
    	
    	sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID,
                strlen(ssid), (unsigned char *)ssid);						// set AP SSID for the CC3100 in AP mode
    	
    	sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, 1,			// configure the Security parameter to open for the AP mode
                (unsigned char *)&enc);
    
        sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, strlen(passwd),	// set AP password
                (unsigned char *)passwd);
    
        
        
        ipV4.ipV4 = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_AP);		// set AP address
        getStr4AddrMISC(g_wifi_local_ip_str,ipV4.ipV4); 
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: configuring TCP/IP server ADDR[%s] PORT[%d]...\n",g_wifi_local_ip_str,portNum);
    #endif	    
        ipV4.ipV4Mask = (WIFI_NETWORK_MASK);								// set Network Mask
        ipV4.ipV4Gateway = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_GW);	// set AP Gateway address
        ipV4.ipV4DnsServer = (WIFI_NETWORK_IP_OFFSET) + (WIFI_NETWORK_IP_DNS);// set AP DNS address
    
        
        sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE,1,sizeof(_NetCfgIpV4Args_t),
                (unsigned char *)&ipV4);									// Configure the Static IP 
    	
    	addr_offset = (WIFI_NETWORK_IP_OFFSET);
        dhcpParams.lease_time      = WIFI_IP_LEASE_TIME;					// set IP address lease time
        dhcpParams.ipv4_addr_start =  addr_offset + (WIFI_NETWORK_IP_DHCP_BEG);	// set the start address of the DHCP server
        dhcpParams.ipv4_addr_last  =  addr_offset + (WIFI_NETWORK_IP_DHCP_END);	// set the end address of the DHCP server
    
        // Configure DHCP address range. This step is necessary if the subnet of the IP is changed 
        sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID);							// apply DHCP IP address parameters							
        sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT,
                sizeof(SlNetAppDhcpServerBasicOpt_t), (unsigned char*)&dhcpParams);
        sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID);
    
    	sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);							// stop the HTTP web server
        g_Status = 0;
    
    
        sl_Stop(0x00FF);													// stop CC3100
        mode = sl_Start(0, 0, 0);											// start CC3100
        if (ROLE_AP == mode)
        {      																// If the device is in AP mode, we need to wait 
    		
    		timer = getRTC2();											// If the device is in AP mode, we need to wait 
    		while(!IS_IP_AQUIRED(g_Status))									// for this event before doing anything 
    		{
    			_SlNonOsMainLoopTask();
    			if(chk4TimeoutRTC2(timer, WIFI_WAIT4IP_PERIOD) == (RTC_TIMEOUT))
    			{
    				return (WIFI_ERROR_AP_NO_IP);
    			}
    		}
        }
        else
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: unable to start device in AP mode...\n");
    #endif
            return (WIFI_ERROR_CANNOT_RUN_AP);
        }
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device started in AP mode...\n");
    #endif	 
        
    	socket = openSocketWIFI();
        if(socket >= 0)
        {
    		g_wifi_ser_socket = socket;
    #ifdef SYSTEM_DEBUG
    		utmp32 = socket;
    		printUART("-> WIFI: Socket [%d] created\n",utmp32);
    #endif
    	}
    	else
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to open socket\n");
    #endif
    		return (WIFI_ERROR_SERVER_FAILED);
    	}
    	
    	//socket = openSocketWIFI();
    	return (WIFI_OK);
    }
    
    uint8_t setSTAmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc)
    {/// power up and setup the wifi module
    	char str[16];
    	INT32 retVal = -1;
    	int16_t socket;
    	uint32_t utmp32;
    	g_wifi_port = portNum;
    	
    #ifdef SYSTEM_DEBUG
    	printUART("\n-> WIFI: STA mode setup initiated....\n");
    #endif
    	
    	
    	CC3100_disable();
    	CC3100_enable();													// wakeup CC3100
    	retVal = initializeAppVariables();									// init CC3100 variables
    	rstWIFI();															// reset CC3100 just to clear any problems
    	retVal = configureSimpleLinkToDefaultState();						// set default state to STA mode, clear all settings
        if(retVal != ROLE_STA)
        {
    #ifdef SYSTEM_DEBUG
            if (DEVICE_NOT_IN_STATION_MODE == retVal)
            {
    			printUART("-> WIFI: Failed to configure the device to default state\n");
    		}
    		else
    		{
    			printUART("-> WIFI: Failed!\n");
    		}
    #endif			
            return (WIFI_ERROR_SET_DEF);
        }
        
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Device is configured in default state\n");
    #endif
    	
    	retVal = sl_Start(0, 0, 0);	
        if ((retVal < 0)||(ROLE_STA != retVal))
        {
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to start the device in STA mode\n");
    #endif
            return (WIFI_ERROR_START_DEV);
        }
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Device started in STA mode\n");
    #endif
        
        
        retVal = establishConnectionWithAP(ssid, passwd, enc);				// connect to remote AP
        if(retVal == (WIFI_ERROR_LAN_CONNECTION_TIMEOUT))
        {
    #ifdef SYSTEM_DEBUG
            printUART("-> WIFI: Failed to establish connection with an AP\n");
    #endif
            return retVal;
        }
    #ifdef SYSTEM_DEBUG
    	printUART("-> WIFI: Connection established with an AP and IP is acquired\n");
    #endif	
        
        unsigned char len = sizeof(_NetCfgIpV4Args_t);
    	unsigned char dhcpIsOn = 0;
    	_NetCfgIpV4Args_t ipV4 = {0};
    	sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&dhcpIsOn,&len,(unsigned char *)&ipV4);
    	 
      
        getStr4AddrMISC(g_wifi_local_ip_str, ipV4.ipV4);
    #ifdef SYSTEM_DEBUG  
    	printUART("-> WIFI: Client IP: [%s]\n",g_wifi_local_ip_str);
    #endif	
    
        socket = openSocketWIFI();
        if(socket >= 0)
        {
    		g_wifi_ser_socket = socket;
    #ifdef SYSTEM_DEBUG
    		utmp32 = socket;
    		printUART("-> WIFI: Socket [%d] created\n",utmp32);
    #endif
    	}
    	else
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Failed to open socket\n");
    #endif
    		return (WIFI_ERROR_SERVER_FAILED);
    	}
     
    	//openSocketWIFI();
    	return (WIFI_OK);
    }
    
    uint8_t connect2ServerCC3100(void)
    {// connect to remote server on Internet
    	//if(chk4TimeoutRTC2(g_wifi_rc_conn_timer, 1) == (RTC_KEEP_ALIVE))
    	int32_t r_val;
    	int32_t nonBlocking = 1;
    	int16_t status;
    	
    
    	if(chk4TimeoutRTC2(g_wifi_rc_conn_timer, WIFI_REMOTE_SERVER_CONNECTION_RETRY_PERIOD) == (RTC_KEEP_ALIVE))
    		return (WIFI_ERROR_WAITING4RETRY_TIMEOUT);
    		
    	g_wifi_rc_conn_timer = getRTC2();
    	
    
    	
    	
    	Rem_Addr.sin_family = SL_AF_INET;
    	Rem_Addr.sin_port = sl_Htons(g_wifi_port);
    	//Rem_Addr.sin_addr.s_addr = sl_Ntohl(g_wifi_remote_server_ip);		
    	Rem_Addr.sin_addr.s_addr = sl_Htonl(g_wifi_remote_server_ip);
    	
    	
    	Rem_AddrSize = sizeof(SlSockAddrIn_t);
    	
    #ifdef SYSTEM_DEBUG	
    	uint8_t ip_str[8];
    	getStr4AddrMISC(ip_str, g_wifi_remote_server_ip);
    	printUART("-> WIFI: Creating socket for remote server IP: %s PORT: %d\n",ip_str,g_wifi_port);
    #endif		
    	g_wifi_remote_cli_socket = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0); // create socket
    	if(g_wifi_remote_cli_socket < 0)
    	{
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: Error creating socket for remote server %x\n",ip_str);
    #endif		
    		
    		return (WIFI_ERROR_REMOTE_SERVER_SOCKET_FAILED);
    	}
    	
        r_val = sl_Connect(g_wifi_remote_cli_socket, ( SlSockAddr_t *)&Rem_Addr, Rem_AddrSize);			// connect to remote server
        if(r_val < 0)
        {
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: Error connecting to remote server SoID %d RVAL[%d]\n",g_wifi_remote_cli_socket,r_val);
    #endif
    		sl_Close(g_wifi_remote_cli_socket);
    #ifdef SYSTEM_DEBUG	
    		printUART("-> WIFI: socket closed %d\n",g_wifi_remote_cli_socket);
    #endif
    		g_wifi_remote_cli_socket = -1;
    		return (WIFI_ERROR_REMOTE_SERVER_DISCONNECTED);
        }
        
        	r_val = sl_SetSockOpt(g_wifi_remote_cli_socket, (SL_SOL_SOCKET), (SL_SO_NONBLOCKING),&nonBlocking, sizeof(nonBlocking));
    	
        
    #ifdef SYSTEM_DEBUG	
        printUART("-> WIFI: Connected to remote server with SID %d\n",g_wifi_remote_cli_socket);
    #endif		
        
        // tx ID info
        //txPktWIFI(g_wifi_remote_cli_socket, WIFI_PKT_REGISTER_DEVICE);
        
        return (WIFI_OK);
    }
    
    int16_t openSocketWIFI(void)
    {/// open new TCP socket
    	int16_t status;
    	int32_t nonBlocking = 1;
    	int16_t sid;
    	uint32_t utmp32;
    	
    	
        LocalAddr.sin_family = SL_AF_INET;									// setup local address and port
        LocalAddr.sin_port = sl_Htons(g_wifi_port);
        LocalAddr.sin_addr.s_addr = 0;
    
        sid = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);						// create socket with unique ID (sid)
        if(sid < 0)
    		return (WIFI_ERROR_CREATE_SOCKET);
    
        // set socket as non-blocking
    	status = sl_SetSockOpt(sid, (SL_SOL_SOCKET), (SL_SO_NONBLOCKING),&nonBlocking, sizeof(nonBlocking));
    	if(status < 0)
        {
            sl_Close(sid);
            return (WIFI_ERROR_SOCKET_NONBLOCKING);							// error: can not set non-blocking mode for socket
        }
    
    	AddrSize = sizeof(SlSockAddrIn_t);
        status = sl_Bind(sid, (SlSockAddr_t *)&LocalAddr, AddrSize);
        if(status<0)
        {
    		sl_Close(sid);
            return (WIFI_ERROR_SOCKET_BINDING);								// error: binding socket
        }
        
        status = sl_Listen(sid, 0);
        if(status<0)
        {
            sl_Close(sid);
            return (WIFI_ERROR_SOCKET_BINDING);								// error: binding socket
        }
    
    
    #ifdef SYSTEM_DEBUG    
    	utmp32 = g_wifi_port;
    	printUART("-> WIFI: Server listening at port [%d]\n",utmp32);
    #endif
    	
        return sid;
    }
    
    static _i32 establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    /*
    static int32_t establishConnectionWithAP()
    {
        SlSecParams_t secParams = {0};
        _i32 retVal = 0;
    
        secParams.Key = (_i8 *)PASSKEY;
        secParams.KeyLen = pal_Strlen(PASSKEY);
        secParams.Type = SEC_TYPE;
    
        retVal = sl_WlanConnect((_i8 *)SSID_NAME, pal_Strlen(SSID_NAME), 0, &secParams, 0);
        ASSERT_ON_ERROR(retVal);
    
        /* Wait */
        /*
        while((!IS_CONNECTED(g_Status)) || (!IS_IP_ACQUIRED(g_Status))) { _SlNonOsMainLoopTask(); }
    
        return SUCCESS;
    }
    */
    
    uint8_t chkLocalSocketWIFI(void)
    {/// check socket for incomming connections	
    	uint8_t str[32];
    	
    	if(g_wifi_local_cli_socket < 0)											// test if client socket slot is open
    	{
    																	// test if there is pending connection
    		AddrSize = sizeof(SlSockAddrIn_t); 
    		g_wifi_local_cli_socket = sl_Accept(g_wifi_ser_socket, ( struct SlSockAddr_t *)&(Addr), (SlSocklen_t*)&AddrSize);
    	
    		if(g_wifi_local_cli_socket >= 0)
    		{	
    				
    			
    #ifdef SYSTEM_DEBUG
    			getStr4AddrMISC(str, sl_Htonl(Addr.sin_addr.s_addr));
    			printUART("-> WIFI: client SID[%d] --- IP [%s]\n",g_wifi_local_cli_socket, str);
    #endif
    		}
    	}
    		
    	if(g_wifi_local_cli_socket >= 0)
    	{
    		return (WIFI_SOCKET_CONNECTED);
    	}
    	else
    	{
    		return (WIFI_SOCKET_DISCONNECTED);
    	}
    }
    
    uint16_t txMessageWIFI(int16_t socket, uint8_t * dataPtr, uint16_t numBytes)
    {/// send predefined number of bytes if the connection is open, default size by CC3100 internals is 1400 B
    	uint16_t status;
    	
    	if((g_wifi_ser_socket < 0) || (socket < 0))
    		return (WIFI_ERROR_SOCKET_CLOSED);
    	
    	status = sl_Send(socket, dataPtr, numBytes, 0);						// now we send message to remote device
    
    	if(status == 0xFFFF)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Client with SoID[%d] disconnected", socket);
    #endif
    		if(socket == g_wifi_local_cli_socket)
    		{
    			g_wifi_local_cli_socket = -1;
    		}
    		else
    		{
    			g_wifi_remote_cli_socket = -1;
    		}
    		
    		sl_Close(socket);
    		return (WIFI_ERROR_SOCKET_CLOSED);								// close the socket
    	}
    			
    	return (WIFI_OK);
    }
    
    uint16_t rxLocalSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen)
    {/// receive byte, up to buffLen, if connection is open, default size by CC3100 internals is 1400 B
    	uint16_t rxbytes;
    	
    	if((g_wifi_ser_socket < 0) || (g_wifi_local_cli_socket < 0))
    		return 0;
    	
    	
    	rxbytes = sl_Recv(g_wifi_local_cli_socket, dataPtr, buffLen, 0);
    	
    	if(rxbytes == 0)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Local WLAN client with SoID[%d] disconnected...\n", g_wifi_local_cli_socket);
    #endif	
    		sl_Close(g_wifi_local_cli_socket);
    		g_wifi_local_cli_socket = -1;
    				
    		return 0;
    	}
    	
    	if(rxbytes >= buffLen)
    	{
    		rxbytes = 0;
    	}
    				
    	return rxbytes;
    }
    
    uint16_t rxRemoteSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen)
    {/// receive byte, up to buffLen, if connection is open, default size by CC3100 internals is 1400 B
    	uint16_t rxbytes;
    	
    	if((g_wifi_ser_socket < 0) || (g_wifi_remote_cli_socket < 0))
    		return 0;
    	
    	rxbytes = sl_Recv(g_wifi_remote_cli_socket, dataPtr, buffLen, 0);
    	
    	if(rxbytes == 0)
    	{
    #ifdef SYSTEM_DEBUG
    		printUART("-> WIFI: Remote client with SoID[%d] disconnected...\n",g_wifi_remote_cli_socket);
    #endif	
    		sl_Close(g_wifi_remote_cli_socket);
    		g_wifi_remote_cli_socket = -1;	
    		
    		return 0;
    	}
    	
    	if(rxbytes >= buffLen)
    	{
    		rxbytes = 0;
    	}
    				
    	return rxbytes;
    }
    
    
    /*
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
    #ifdef SYSTEM_DEBUG			
    			printUART("-> WIFI: connected to AP...\n");
    #endif			
    			g_wifi_remote_cli_socket = -1;
    			g_wifi_local_cli_socket = -1;
    			
                /*
                 * Information about the connected AP (like name, MAC etc) will be
                 * available in 'sl_protocol_wlanConnectAsyncResponse_t' - Applications
                 * can use it if required
                 *
                 * sl_protocol_wlanConnectAsyncResponse_t *pEventData = NULL;
                 * pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
                 *
                 */
    /*             break;
            }
            case SL_WLAN_DISCONNECT_EVENT:
            {
                sl_protocol_wlanConnectAsyncResponse_t*  pEventData = NULL;
                CLR_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;
    
                /* If the user has initiated 'Disconnect' request, 'reason_code' is SL_USER_INITIATED_DISCONNECTION */
    /*            if(SL_USER_INITIATED_DISCONNECTION == pEventData->reason_code)
                {
                    ////CLI_Write((unsigned char *)" Device disconnected from the AP on application's request \n\r");
                }
                else
                {
                    ////CLI_Write((unsigned char *)" Device disconnected from the AP on an ERROR..!! \n\r");
                }
                
    			g_wifi_remote_cli_socket = -1;
    			g_wifi_local_cli_socket = -1;
    #ifdef SYSTEM_DEBUG			
    			printUART("-> WIFI: disconnected from AP...\n");
    #endif         
                break;
            }
            
    
            case SL_WLAN_STA_CONNECTED_EVENT:
            {
                SET_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
    #ifdef SYSTEM_DEBUG			
                printUART("-> WIFI: new STA device connected\n");
    #endif         
            }
            break;
    
            case SL_WLAN_STA_DISCONNECTED_EVENT:
            {
                CLR_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
                CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
    #ifdef SYSTEM_DEBUG			
                printUART("-> WIFI: STA device disconnected\n");
    #endif         
    
            }
    		break;
    
            default:
            {
                ////CLI_Write((unsigned char *)" [WLAN EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    */
    /*
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
    	//printUART("SimpleLinkNetAppEventHandler");
        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;
    
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
    
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_GatewayIP = pEventData->gateway;
            }
            break;
    
            case SL_NETAPP_IP_LEASED_EVENT :
            {
                g_StationIP = pNetAppEvent->EventData.ipLeased.ip_address;
                SET_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
            }
            break;
    
            default:
            {
                ////CLI_Write((unsigned char *)" [NETAPP EVENT] Unexpected event \n\r");
            }
            break;
        }
    }
    
    */
    void SimpleLinkPingReport(SlPingReport_t *pPingReport)
    {
        SET_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
        g_PingPacketsRecv = pPingReport->PacketsReceived;
    }
    
    /*
    void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
    {
    }
    */
    
    /*
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
    }
    */
    /*
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pEvent, SlHttpServerResponse_t *pResponse)
    {
    }
    
    uint16_t getRxBuffCountWIFI(void)
    {
    	if(g_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    	{
    		return 0;
    	}
    	else if(g_wifi_rx_buff_ridx < g_wifi_rx_buff_widx)
    	{
    		return (g_wifi_rx_buff_widx - g_wifi_rx_buff_ridx - 1);
    	}
    	else
    	{
    		return (g_wifi_rx_buff_widx + (WIFI_RX_BUFF_SIZE) - g_wifi_rx_buff_ridx - 1);
    	}
    }
    
    */
    void chkWIFI(void)
    {
    	if(g_wifi_mode == (WIFI_MODE_STA))
    	{
    		if(g_wifi_remote_cli_socket == -1)
    		{// create connection with remote server
    			connect2ServerCC3100();
    		}
    		
    		chkLocalSocketWIFI();
    		
    		if((g_wifi_local_cli_socket < 0)&&(g_wifi_remote_cli_socket < 0))
    			return;
    	}
    	else 
    	{
    		if(chkLocalSocketWIFI() == (WIFI_SOCKET_DISCONNECTED))	
    			return;
    	}
    	
    	//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    	// check if there is data pending in CC31xx Rx buffer
    	//------------------------------------------------------------------
    	uint16_t rxcnt = rxLocalSocketDataWIFI((uint8_t *)g_wifi_data, WIFI_BUFF_SIZE);							
    	if(rxcnt > 0)
    	{
    		if(rxcnt > (WIFI_BUFF_SIZE))
    			rxcnt = (WIFI_BUFF_SIZE);
    		
    #ifdef SYSTEM_DEBUG		
    		printUART("-> WIFI: Local WLAN socket Rx-ed [%d]B's\n",rxcnt);
    #endif
    		uint16_t k;
    		for(k=0;k<rxcnt;k++)
    		{
    			g_wifi_rx_buff[g_wifi_rx_buff_widx] = g_wifi_data[k];
    			g_wifi_rx_buff_widx++;
    			g_wifi_rx_buff_widx &= (WIFI_RX_BUFF_MASK);
    			
    			//printUART("%xb ",g_wifi_data[k]);
    		}
    		//printUART("\n");
    	}
    	
    	rxcnt = rxRemoteSocketDataWIFI((uint8_t *)g_wifi_data, WIFI_BUFF_SIZE);							
    	if(rxcnt > 0)
    	{
    		if(rxcnt > (WIFI_BUFF_SIZE))
    			rxcnt = (WIFI_BUFF_SIZE);
    		
    #ifdef SYSTEM_DEBUG		
    		printUART("-> WIFI: Remote server socket Rx-ed [%d]B's\n",rxcnt);
    #endif
    		uint16_t k;
    		for(k=0;k<rxcnt;k++)
    		{
    			g_wifi_rx_buff[g_wifi_rx_buff_widx] = g_wifi_data[k];
    			g_wifi_rx_buff_widx++;
    			g_wifi_rx_buff_widx &= (WIFI_RX_BUFF_MASK);
    			
    			//printUART("%xb ",g_wifi_data[k]);
    		}
    		//printUART("\n");
    	}
    		
    	// check if there is data in Rx buffer
    	g_wifi_rx_buff_byte_cnt = getRxBuffCountWIFI();
    	if(g_wifi_rx_buff_byte_cnt < 8)
    		return;
    		
    	// check if there is at least one packet in rx buffer, if there is
    	// get packet start and stop index in 
    	uint8_t res = getNextPktWIFI();
    	if(res != (WIFI_PACKET_FOUND))
    		return;
    		
    	switch(g_wifi_pkt_type)
    	{
    		case(WIFI_PKT_SET_STA_CONFIG):
    		{// extract STA configuration information and reboot device to start in STA mode
    #ifdef SYSTEM_DEBUG
    			printUART("-> WIFI: setting new STA info...\n");
    #endif				
    			//writeDataFLASH(FLASH_WRITE_NEW_STA_INFO, (uint8_t *)g_wifi_pkt);
    			g_flash_update = (FLASH_UPDATE_STA_INFO);
    			
    			break;
    		}
    		case(WIFI_PKT_FORCE_AP_MODE):
    		{//
    #ifdef SYSTEM_DEBUG
    			printUART("-> WIFI: forcing AP mode...\n");
    #endif
    			setDefaultFLASH();
    			NVIC_SystemReset();
    			break;
    		}
    		default:
    		{
    #ifdef SYSTEM_DEBUG		
    			printUART("-> WIFI: unknown packet TYPE[%xb]B\n",g_wifi_pkt[WIFI_PKT_TYPE_IDX]);
    #endif			
    			break;
    		}
    	}
    }
    
    uint8_t getNextPktWIFI(void)
    {
    	uint8_t csum[2] = {0x00,0x00};
    	uint16_t csum_idx = 0;
    	uint8_t flag = 1;
    	uint16_t t_wifi_rx_buff_ridx = g_wifi_rx_buff_ridx;
    	uint16_t tg_wifi_rx_buff_ridx = g_wifi_rx_buff_ridx;
    	
    	
    	g_wifi_pkt_len = 0;
    	
    	// find first byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[0])
    	{
    		g_wifi_rx_buff_ridx = t_wifi_rx_buff_ridx;
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	// find second byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[1])
    	{
    		g_wifi_rx_buff_ridx++;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	// find third byte
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(g_wifi_rx_buff[t_wifi_rx_buff_ridx] != c_wifi_preambule[2])
    	{
    		g_wifi_rx_buff_ridx += 2;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		return (WIFI_PACKET_MISSING_PREAMBULE);
    	}
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	// check if there is enough bytes in buffer to check the packet type 
    	// payload length
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    		return (WIFI_PACKET_MISSING_DATA);
    	
    	g_wifi_pkt_type = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    		return (WIFI_PACKET_MISSING_DATA);
    	
    	g_wifi_pkt_len = ((uint16_t)g_wifi_rx_buff[t_wifi_rx_buff_ridx])<<8;
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    				
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	if(t_wifi_rx_buff_ridx == g_wifi_rx_buff_widx)
    	{
    		g_wifi_pkt_len = 0;
    		return (WIFI_PACKET_MISSING_DATA);
    	}
    	
    	
    	//printUART("-> type %xb\n",g_wifi_pkt_type);
    	
    	g_wifi_pkt_len |= ((uint16_t)g_wifi_rx_buff[t_wifi_rx_buff_ridx]);		
    	csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	csum_idx ^= 0x01;
    	
    	
    	g_wifi_rx_buff_ridx = t_wifi_rx_buff_ridx;
    	//printUART("P5 len %d\n",getRxBuffCountWIFI());
    	
    	if(getRxBuffCountWIFI() < g_wifi_pkt_len)							// add 2 more for checksum
    	{
    		g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx;						// restore ridx
    		return (WIFI_PACKET_NOT_ENOUGHT_DATA);
    	}
    	
    	
    	//printUART("P6\n");
    	// check the csum now
    	uint16_t k;
    	for(k=0;k<g_wifi_pkt_len;k++)
    	{
    		t_wifi_rx_buff_ridx++;
    		t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		g_wifi_pkt[k] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    		csum[csum_idx] += g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    		printUART("%xb ",g_wifi_rx_buff[t_wifi_rx_buff_ridx]);
    		csum_idx ^= 0x01;
    	}
    	printUART("\n");
    	
    	uint8_t rxcsum[2];
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	rxcsum[0] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	
    	t_wifi_rx_buff_ridx++;
    	t_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	rxcsum[1] = g_wifi_rx_buff[t_wifi_rx_buff_ridx];
    	
    	printUART("Rx-ed %xb%xb  calc %xb%xb\n",rxcsum[0],rxcsum[1],csum[0],csum[1]);
    	
    	if((rxcsum[0] != csum[0])||(rxcsum[1] != csum[1]))
    	{
    		g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx + 3;
    		g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    		
    		return (WIFI_PACKET_CSUM_ERROR);
    	}
    	
    	g_wifi_rx_buff_ridx = tg_wifi_rx_buff_ridx + 8 + g_wifi_pkt_len;
    	g_wifi_rx_buff_ridx &= (WIFI_RX_BUFF_MASK);
    	
    	
    	//printUART("BEFORE EXIT\n");
    	//for(k=0;k<71;k++)
    		//printUART("%xb ",g_wifi_pkt[k]);
    	
    	//printUART("\n\n");
    	
    	
    	return (WIFI_PACKET_FOUND);
    }
    
    uint16_t txPktWIFI(int16_t socket, uint8_t pkt_type)
    {
    	if(g_wifi_remote_cli_socket < 0)
    		return (WIFI_ERROR_SOCKET_CLOSED);
    	
    	uint16_t pkt_len = 0;
    	uint16_t k;
    	uint16_t n;
    	uint16_t offset;
    	
    	for(k=0;k<(WIFI_BUFF_SIZE);k++)
    		g_wifi_tx_buff[k] = 0x00;
    		
    	g_wifi_tx_buff[0] = c_wifi_preambule[0];
    	g_wifi_tx_buff[1] = c_wifi_preambule[1];
    	g_wifi_tx_buff[2] = c_wifi_preambule[2];
    	g_wifi_tx_buff[3] = pkt_type;
    	offset = 4;
    	
    	switch(pkt_type)
    	{
    		case(WIFI_PKT_BLE_BEACONS):
    		{
    			// packet will hold up to 1400B which means max of 1400-8 of beacon data, 
    			// there will always be integer number of BLE beacon packets
    			
    			uint16_t m = 0;
    			for(n=4;n<12;n++)
    			{
    				g_wifi_tx_buff[n] = g_device_id[m++];
    			}
    			
    			
    			g_wifi_tx_buff[12] = (g_blef_tx_count>>8)&0x00FF;
    			g_wifi_tx_buff[13] = g_blef_tx_count&0x00FF;
    			
    			offset = 14;
    			
    			n = 0;
    			for(k=offset;k<(g_blef_tx_count + offset);k++)
    			{
    				g_wifi_tx_buff[k] = g_ble_tx_buff[n];
    				n++;
    			}
    			pkt_len = k;
    			
    			break;
    		}
    		default:
    		{
    #ifdef SYSTEM_DEBUG		
    			printUART("-> WIFI: tx-ing unknown packet...\n");
    #endif			
    			return;
    		}
    	}
    	
    	
    	// generate checksum
    	uint8_t csum[2] = {0x00,0x00};
    	uint8_t cflag = 0x00;
    	for(k=0;k<pkt_len;k++)
    	{
    		printUART("%xb",g_wifi_tx_buff[k]);
    		g_wifi_tx_buff[pkt_len + cflag] += g_wifi_tx_buff[k]; 
    		cflag ^= 0x01;
    	}
    	pkt_len += 2;
    	
    #ifdef SYSTEM_DEBUG		
    	printUART("\n-> WIFI: tx-ing on SoID[%d] pkt type [0x%xb] of size [%d]\n", socket, pkt_type, pkt_len);
    #endif		
    	return txMessageWIFI(socket, (uint8_t *)g_wifi_tx_buff, pkt_len);
    }
    
    /////////////////////////////////////////////////////////////////////////////////
    void initClk()
    {
    }
    
    void stopWDT()
    {
    }
    
    int registerInterruptHandler(P_EVENT_HANDLER InterruptHdl , void* pValue)
    {
    	pIrqEventHandler = InterruptHdl;
    
        return 0;
    }
    
    
    
    void deinitSPI1(void)
    {
    	NRF_SPI1->ENABLE = 0x00000000;										// disable SPI1 
    	NRF_P0->PIN_CNF[CC_SCK_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_P0->PIN_CNF[CC_MISO_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_P0->PIN_CNF[CC_MOSI_PIN] = 0x00000002;							// set as input, disconnect input
    	NRF_SPI1->PSEL.SCK  = 0xFFFFFFFF;										
    	NRF_SPI1->PSEL.MOSI = 0xFFFFFFFF;										
    	NRF_SPI1->PSEL.MISO = 0xFFFFFFFF;
    }
    
    uint8_t rxByteSPI1(void)
    {///
        uint32_t counter = 0;
        uint32_t TIMEOUT_COUNTER = 50000;
    
    	NRF_SPI1->TXD = 0x00000000;
    
    	counter = 0;														// wait for the transaction complete or timeout (about 10ms - 20 ms)
    	while ((NRF_SPI1->EVENTS_READY == 0) && (counter < TIMEOUT_COUNTER))
    	{
    		counter++;
    	}
    
    	if (counter == TIMEOUT_COUNTER)
    	{
    		return 0;
    	}
    	else
    	{   
    		NRF_SPI1->EVENTS_READY = 0U;									// clear the event to be ready to receive next messages
    	}
    
        return (uint8_t)NRF_SPI1->RXD;
    }
    
    uint8_t txByteSPI1(uint8_t tx_data)
    {///
        uint32_t counter = 0;
        uint32_t TIMEOUT_COUNTER = 50000;
    
    
    	NRF_SPI1->TXD = (uint32_t)tx_data;
    
    	counter = 0;														// wait for the transaction complete or timeout (about 10ms - 20 ms)
    	while ((NRF_SPI1->EVENTS_READY == 0) && (counter < TIMEOUT_COUNTER))
    	{
    		counter++;
    	}
    
    	if (counter == TIMEOUT_COUNTER)
    	{
    		return 0;
    	}
    	else
    	{   
    		NRF_SPI1->EVENTS_READY = 0U;									// clear the event to be ready to receive next messages
    	}
    
    	return NRF_SPI1->RXD;
    }
    
    void txSPI1(uint8_t * txdata, uint16_t size)
    {
    	uint16_t k;
    	
    	for(k=0;k<size;k++)
    	{
    		txByteSPI1(txdata[k]);
    	}
    }
    
    void rxSPI1(uint8_t * data, uint16_t size)
    {
    	uint16_t k;
    	for(k=0;k<size;k++)
    	{
    		data[k] = rxByteSPI1();
    	}
    }
    
    void initLED(void)
    {
    	g_led_blink_pin = 0x00;
    	deinitLED(); 
    }
    
    void setLED(uint8_t led, uint8_t mode, uint32_t period)
    {	
    	
    	NRF_P0->PIN_CNF[LED_RED] = 0x00000002;
    	NRF_P0->PIN_CNF[LED_GREEN] = 0x00000002;
    	NRF_P0->PIN_CNF[LED_BLUE] = 0x00000002;
    	switch(mode)
    	{
    		case(LED_MODE_OFF):
    		{
    			NRF_P0->OUTCLR = (1<<led);
    			NRF_P0->PIN_CNF[led] = 0x00000002;							// set as input, disconnect input
    			g_led_flag = (LED_DISABLED);
    			break;
    		}
    		case(LED_MODE_STATIC):
    		{
    			NRF_P0->PIN_CNF[led] = 0x00000001;							
    			NRF_P0->OUTCLR = (1<<led);
    			g_led_flag = (LED_DISABLED);
    			break;
    		}
    		case(LED_MODE_BLINK):
    		{
    			
    			g_led_blink_pin = led;
    			NRF_P0->PIN_CNF[led] = 0x00000001;							
    			NRF_P0->OUTCLR = (1<<led);
    			g_led_blink_period = period;
    			g_led_blink_timer = 0;
    			g_led_flag = (LED_ENABLED);
    			break;
    		}
    		default:
    		{
    			break;
    		}
    	}
    }
    	
    void deinitLED(void)
    {
    	NRF_P0->PIN_CNF[LEDR_PIN] = 0x00000002;								// set as input, disconnect input
    	NRF_P0->PIN_CNF[LEDG_PIN] = 0x00000002;								// set as input, disconnect input
    	NRF_P0->PIN_CNF[LEDB_PIN] = 0x00000002;								// set as input, disconnect input
    	g_led_flag = (LED_DISABLED);
    }	
    	
    void chkLED(void)
    {
    	
    }
    
    void initFLASH(void)
    {/// check the user flash integrity
    	g_flash_update = (FLASH_UPDATE_DISABLED);
    	g_flash_sms = (FLASH_SMS_INIT_ERASE_MEMORY);
    	
    	chkUserSpaceFLASH();
    		
    	loadUserDataFLASH();
    }
    
    void loadUserDataFLASH(void)
    {
    	uint16_t k;
    	uint32_t * dwptr = (uint32_t *)(FLASH_UDATA_WIFI_MODE_ADDR);
    	uint8_t * bptr = (uint8_t *)(dwptr);
    	
    	g_wifi_mode = (uint8_t)dwptr[0];
    	
    	if(g_wifi_mode == (WIFI_MODE_AP))
    	{
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_SSID_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_SSID_SIZE);k++)
    		{
    			g_wifi_ssid[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_SSID_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_PASSWD_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_PASSWD_SIZE);k++)
    		{
    			g_wifi_passwd[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_PASSWD_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_PORT_ADDR);
    		g_wifi_port = dwptr[0];
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_AP_ENC_ADDR);
    		g_wifi_enc = dwptr[0];
    	}
    	else
    	{
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_SSID_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_SSID_SIZE);k++)
    		{
    			g_wifi_ssid[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_SSID_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_PASSWD_ADDR);
    		bptr = (uint8_t *)(dwptr);
    		for(k=0;k<(WIFI_PASSWD_SIZE);k++)
    		{
    			g_wifi_passwd[k] = bptr[k];
    		}
    		g_wifi_ssid[(WIFI_PASSWD_SIZE) - 1] = '\0';
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_PORT_ADDR);
    		g_wifi_port = ((uint32_t)dwptr[0]);
    		
    		dwptr = (uint32_t *)(FLASH_UDATA_STA_ENC_ADDR);
    		g_wifi_enc = (uint32_t)dwptr[0];
    		
    	}
    	
    	dwptr = (uint32_t *)(FLASH_UDATA_REMOTE_SERVER_ADDR);
    	g_wifi_remote_server_ip = (uint32_t)dwptr[0];
    	
    	dwptr = (uint32_t *)(FLASH_UDATA_DEVICE_NAME_ADDR);
    	bptr = (uint8_t *)(dwptr);
    	for(k=0;k<(DEVICE_NAME_SIZE);k++)
    	{
    		g_device_name[k] = 0;
    	}
    	
    	for(k=0;k<(DEVICE_NAME_SIZE);k++)
    	{
    		g_device_name[k] = bptr[k];
    		if(g_device_name[k] == 0)
    			break;
    	}
    	g_device_name[(DEVICE_NAME_SIZE) - 1] = '\0';
    	
    	
    	
    	
    #ifdef SYSTEM_DEBUG	
    	printUART("-> FLASH: WMODE    [%d]\n",g_wifi_mode);
    	printUART("-> FLASH: SSID     [%s]\n",g_wifi_ssid);
    	printUART("-> FLASH: PASSWD   [%s]\n",g_wifi_passwd);
    	printUART("-> FLASH: PORT     [%d]\n",g_wifi_port);
    	printUART("-> FLASH: ENC      [%d]\n",g_wifi_enc);
    	
    	uint8_t addr[4];
    	addr[0] = (uint8_t)((g_wifi_remote_server_ip>>24)&0x000000FF);
    	addr[1] = (uint8_t)((g_wifi_remote_server_ip>>16)&0x000000FF);
    	addr[2] = (uint8_t)((g_wifi_remote_server_ip>>8)&0x000000FF);
    	addr[3] = (uint8_t)((g_wifi_remote_server_ip)&0x000000FF);
    	printUART("-> FLASH: RSERVER  [%d.%d.%d.%d]\n",addr[0],addr[1],addr[2],addr[3]);
    	printUART("-> FLASH: NAME     [%s]\n",g_device_name);
    #endif
    }
    
    void updateUserDataFLASH(void)
    {
    	//uint32_t cdata[9];
    	//uint8_t k;
    	//uint32_t addr = (FLASH_USER_VOLUME_ADDR);
    	
    	//cdata[0] = g_menu_audio_volume;
    	//cdata[1] = g_buzzer_tone;
    	//cdata[2] = g_menu_light_style;
    	//cdata[3] = g_menu_light_intensity;
    	//cdata[4] = g_menu_light_color;
    	//cdata[5] = g_menu_oled_light_brightness;
    	//cdata[6] = g_menu_oled_light_timeout;
    	//cdata[7] = g_menu_bobber_initial_depth;
    	//cdata[8] = g_menu_sonar_rate;
    	
    	//for(k=0;k<9;k++)
    	//{
    		//uint32_t odata = readWordFLASH(addr);
    		//if(cdata[k] != odata)
    		//{
    //#ifdef SYSTEM_DEBUG
    			//printUART("-> FLASH: update, diff at[%d] N[%x]O[%x]...\n",k,cdata[k],odata);
    //#endif			
    			//g_ble_flash_update = (FLASH_UPDATE_ENABLED);
    			//return;
    		//}
    		//addr += 4;
    	//}
    	
    //#ifdef SYSTEM_DEBUG
    	//printUART("-> FLASH: skip update...\n");
    //#endif
    	
    }
    
    void chkUserSpaceFLASH(void)
    {/// check user space data in internal flash memory
    	uint16_t m;
    	uint8_t flag = 0;
    	uint32_t * taddr = (uint32_t *)(FLASH_UDATA_ADDR);
    	uint32_t utmp32;
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> FLASH: Checking user data integrity\n");
    #endif	
    		
    	for(m=0;m<(FLASH_USER_SIGN_WSIZE);m++)
    	{
    		if(taddr[m] != FLASH_USER_SIGN[m])
    		{// flash page sign is different from expected
    			flag = 1;
    			break;
    		}
    	}
    	
    	if(flag == 1)
    	{// erase the page and set default values
    #ifdef SYSTEM_DEBUG
    		printUART("-> FLASH: Restoring default values, user sign error\n");
    #endif
    		setDefaultFLASH();
    	}
    	else
    	{// user sign detected, check checksum  		
    		utmp32 = 0;
    		for(m=0;m<((FLASH_PAGE_SIZE_IN_WORDS)-1);m++)
    		{
    			utmp32 ^= taddr[m];
    		}
    		
    		if(utmp32 != taddr[m])
    		{
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: Restoring default values checksum error\n");
    #endif
    			setDefaultFLASH();					
    		}
    		else
    		{// checksum OK, check firmware version
    			if(taddr[4] != (FLASH_UDATA_VER_VAL))
    			{// restore default values for all FLASH memory entries
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: Restoring default values, flash user data version differs\n");
    #endif
    				setDefaultFLASH();	
    			}
    			else
    			{
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: User data integrity OK\n");
    #endif	
    			}
    		}
    	}
    }
    
    void setDefaultFLASH(void)
    {
    	uint32_t k;
    	uint32_t * pflash = (uint32_t *)(FLASH_UDATA_ADDR);
    	uint32_t * pdata;
    	uint32_t utmp32;
    
    #ifdef SYSTEM_DEBUG
    	printUART("-> FLASH: Writing default user data...\n");
    #endif
    	
    	erasePageFLASH(FLASH_UDATA_ADDR);									// erase user data flash page
    	//delay_ms(FLASH_ERASE_PAGE_DELAY);									// delay required for erase to take place			
    	
    	// 1. write user data preamble - sign
    	for(k=0;k<(FLASH_USER_SIGN_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_USER_SIGN_ADDR) + 4*k, FLASH_USER_SIGN[k]);
    	}
    	
    	// 2. write user data 	
    	writeWordFLASH(FLASH_UDATA_VER_ADDR, FLASH_UDATA_VER_VAL);
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_SSID_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_SSID_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_SSID_ADDR) + 4*k, pdata[k]);
    	}
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    	
    	pdata = (uint32_t *)(FLASH_UDATA_AP_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_AP_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_AP_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    	
    	writeWordFLASH(FLASH_UDATA_AP_PORT_ADDR, FLASH_UDATA_AP_PORT_VAL);
    	writeWordFLASH(FLASH_UDATA_AP_ENC_ADDR, FLASH_UDATA_AP_ENC_VAL);
    
    	pdata = (uint32_t *)(FLASH_UDATA_STA_SSID_VAL);
    	for(k=0;k<(FLASH_UDATA_STA_SSID_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_STA_SSID_ADDR) + 4*k, pdata[k]);
    	}
    
    	pdata = (uint32_t *)(FLASH_UDATA_STA_PASSWD_VAL);
    	for(k=0;k<(FLASH_UDATA_STA_PASSWD_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_STA_PASSWD_ADDR) + 4*k, pdata[k]);
    	}
    
    	writeWordFLASH(FLASH_UDATA_STA_PORT_ADDR, FLASH_UDATA_STA_PORT_VAL);
    	writeWordFLASH(FLASH_UDATA_STA_ENC_ADDR, FLASH_UDATA_STA_ENC_VAL);
    
    	writeWordFLASH(FLASH_UDATA_REMOTE_SERVER_ADDR, FLASH_UDATA_REMOTE_SERVER_VAL);
    
    	writeWordFLASH(FLASH_UDATA_WIFI_MODE_ADDR, FLASH_UDATA_WIFI_MODE_VAL);
    
    	pdata = (uint32_t *)(FLASH_UDATA_DEVICE_NAME_VAL);
    	for(k=0;k<(FLASH_UDATA_DEVICE_NAME_WSIZE);k++)
    	{
    		writeWordFLASH((FLASH_UDATA_DEVICE_NAME_ADDR) + 4*k, pdata[k]);
    	}
    
    			
    	// 3. calculate the checksum
    	utmp32 = 0;	
    	for(k=0;k<((FLASH_PAGE_SIZE_IN_WORDS)-1);k++)
    	{
    		utmp32 ^= pflash[k];
    	}
    	
    	// 4. write the user data checksum
    	writeWordFLASH(FLASH_UDATA_CHKSUM_ADDR, utmp32);
    }
    
    void erasePageFLASH(uint32_t addr)
    {///
        NRF_NVMC->CONFIG = 0x00000002;   									// enable flash erase and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
        
        NRF_NVMC->ERASEPAGE = addr;											// erase given page 
        while (NRF_NVMC->READY == 0x00000000);
          
        NRF_NVMC->CONFIG = 0x00000000;	  									// disable flash erase and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    }
    
    void writeWordFLASH(uint32_t addr, uint32_t data)
    {///
    	uint32_t * fm_addr = (uint32_t *)addr;
        NRF_NVMC->CONFIG = 0x00000001;										// enable flash write and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    	
        *fm_addr = data;
        while (NRF_NVMC->READY == 0x00000000);
      
        NRF_NVMC->CONFIG = 0x00000000;										// disable flash write and wait until the NVMC is ready
        while (NRF_NVMC->READY == 0x00000000);
    }
    
    uint32_t readWordFLASH(uint32_t addr)
    {///
    	uint32_t * fm_addr = (uint32_t *)addr;
    	return (*fm_addr);
    }
    
    void chkFLASH(void)
    {
    	if(g_flash_update == (FLASH_UPDATE_DISABLED))
    		return;
    		
    	// state machine for writting new data into flash memory		
    	switch(g_flash_sms)
    	{
    		case(FLASH_SMS_INIT_ERASE_MEMORY):
    		{
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: erasing user data...\n");
    #endif
    			uint32_t k;
    			uint32_t * ptr = (uint32_t *)(FLASH_UDATA_ADDR);
    			for(k=0;k<(FLASH_PAGE_SIZE_IN_WORDS);k++)
    			{
    				g_flash_page[k] = ptr[k];
    			}
    			
    			for(k=0;k<(FLASH_WRITE_DATA_SIZE);k++)
    			{
    				g_flash_write_data[k] = g_wifi_pkt[k];
    				//printUART("-> FLASH: data [%d] [%xb]...\n",k,g_flash_write_data[k]);
    			}
    			
    			//erasePageFLASH(FLASH_UDATA_ADDR);							// erase user data flash page
    			NRF_NVMC->CONFIG = 0x00000002;   							// enable flash erase and wait until the NVMC is ready
    			g_flash_timer = getRTC2();
    			g_flash_sms = (FLASH_SMS_WAIT_PHASE1);			
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE1):
    		{	
    			if(NRF_NVMC->READY == 0x00000001)
    			{
    				NRF_NVMC->ERASEPAGE = (FLASH_UDATA_ADDR);				// erase given page 
    				g_flash_timer = getRTC2();
    				g_flash_sms = (FLASH_SMS_WAIT_PHASE2);	
    			}	
        
    			if(chk4TimeoutRTC2(g_flash_timer, 2*(FLASH_ERASE_PAGE_DELAY)) == (RTC_TIMEOUT))
    			{
    				g_flash_update = (FLASH_UPDATE_DISABLED);
    			}		
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE2):
    		{	
    			if(NRF_NVMC->READY == 0x00000001)
    			{
    				NRF_NVMC->CONFIG = 0x00000000;							// disable flash erase and wait until the NVMC is ready
    				g_flash_timer = getRTC2();
    				g_flash_sms = (FLASH_SMS_WAIT_PHASE3);	
    			}	
        
    			if(chk4TimeoutRTC2(g_flash_timer, 2*(FLASH_ERASE_PAGE_DELAY)) == (RTC_TIMEOUT))
    			{
    				g_flash_update = (FLASH_UPDATE_DISABLED);
    			}		
    			break;	
    		}
    		case(FLASH_SMS_WAIT_PHASE3):
    		{			
    			uint32_t k, utmp32;
    			uint32_t * pflash = (uint32_t *)(FLASH_UDATA_ADDR);
    			uint32_t n, kmax;
    			uint32_t * pdata = (uint32_t *)g_flash_write_data;
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: writing new user data...\n");
    #endif		
    			// 1. write user data preamble - sign
    			for(k=0;k<(FLASH_USER_SIGN_WSIZE);k++)
    			{
    				writeWordFLASH((FLASH_USER_SIGN_ADDR) + 4*k, FLASH_USER_SIGN[k]);
    			}
    			
    			// 2. write user data 	
    			writeWordFLASH(FLASH_UDATA_VER_ADDR, FLASH_UDATA_VER_VAL);
    	
    			
    			if(g_flash_update == (FLASH_UPDATE_AP_INFO))
    			{		
    				n = ((FLASH_UDATA_AP_SSID_ADDR) - (FLASH_UDATA_ADDR))/4;
    				for(k=0;k<16;k++)
    				{
    					g_flash_page[n] = pdata[k];
    					n++;
    				}
    				
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x0000FF00)>>8;
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<8;
    				g_flash_page[((FLASH_UDATA_STA_ENC_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0xFF000000)>>24;
    				
    				g_flash_page[((FLASH_UDATA_WIFI_MODE_ADDR) - (FLASH_UDATA_ADDR))/4] = (WIFI_MODE_AP);
    				
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: new AP info [%d]...\n",n);
    #endif			
    			}
    			else
    			{					
    				n = ((FLASH_UDATA_STA_SSID_ADDR) - (FLASH_UDATA_ADDR))/4;
    				for(k=0;k<16;k++)
    				{
    					g_flash_page[n] = pdata[k];
    					n++;
    				}
    				
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x0000FF00)>>8;
    				g_flash_page[((FLASH_UDATA_STA_PORT_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<8;
    				g_flash_page[((FLASH_UDATA_STA_ENC_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0x00FF0000)>>16;
    				
    				
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] = (pdata[k]&0xFF000000);
    				k++;
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x00FF0000)>>16;
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x0000FF00);
    				g_flash_page[((FLASH_UDATA_REMOTE_SERVER_ADDR) - (FLASH_UDATA_ADDR))/4] |= (pdata[k]&0x000000FF)<<16;
    				g_flash_page[((FLASH_UDATA_WIFI_MODE_ADDR) - (FLASH_UDATA_ADDR))/4] = (WIFI_MODE_STA);
    				
    #ifdef SYSTEM_DEBUG
    				printUART("-> FLASH: new STA info  [%d]...\n",n);
    #endif
    			}
    			
    			
    			// 9. calculate the checksum
    			utmp32 = 0;	
    			for(k=0;k<((FLASH_PAGE_SIZE_IN_WORDS)-1);k++)
    			{
    				writeWordFLASH((FLASH_UDATA_ADDR) + k*4, g_flash_page[k]);
    				utmp32 ^= pflash[k];
    				//if(k<50)
    				//{
    					//printUART("-> FLASH: [%d] [%x]\n",k, pflash[k]);
    				//}
    			}
    
    			// 10. write the user data checksum
    			writeWordFLASH(FLASH_UDATA_CHKSUM_ADDR, utmp32);
    
    #ifdef SYSTEM_DEBUG
    			printUART("-> FLASH: write completed\n");
    #endif
    
    			g_flash_sms = (FLASH_SMS_INIT_ERASE_MEMORY);
    			g_flash_update = (FLASH_UPDATE_DISABLED);
    			
    			
    			loadUserDataFLASH();
    			
    			NVIC_SystemReset();
    			break;
    		}
    		default:
    		{
    			break;
    		}
    	}
    
    }
    
    /*
    void GPIOTE_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    
    */
    
    /////////////////////////////////////////////////////////////////////////////////
    
    /*
    #include "gpioint.h"
    
    volatile uint32_t g_btn_sense;
    
    void initGPIOINT(void)
    {
    	g_btn_state = (BTN_STATE_IDLE);
    
    	NRF_GPIOTE->EVENTS_IN[0] = 0;
    	NRF_GPIOTE->EVENTS_IN[1] = 0;
    	
    	NRF_P0->PIN_CNF[PBTN_PIN] = 0x0000000C;								// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00020001|((PBTN_PIN)<<8);					// event mode, high to low transition
    	
    	
    	NRF_GPIOTE->INTENCLR = 0x00000002;	
    	NRF_GPIOTE->INTENSET = 0x00000001;									
        NVIC_EnableIRQ(GPIOTE_IRQn);										
    
    #ifdef SYSTEM_DEBUG
    	printUART0("-> GPIOINT: init [DONE]\n",0);
    #endif
    
    }
    
    void GPIOTE_IRQHandler(void)
    {/// GPIOTE IRQ service routine
    	
    	if(NRF_GPIOTE->EVENTS_IN[0] == 1)
    	{
    		NVIC_DisableIRQ(GPIOTE_IRQn);
    		g_btn_state = (BTN_STATE_RESTORE_AP_MODE);
    		NRF_GPIOTE->EVENTS_IN[0] = 0;
    		setLED(LED_RED, LED_MODE_STATIC, 0);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Restoring WIFI AP mode ...\n");
    #endif
    		setDefaultFLASH();
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    #ifdef SYSTEM_DEBUG
    		printUART("-> SYS: Rebooting...\n\n\n");
    #endif	
    		delay_ms(200);
    		while((NRF_P0->IN & (1<<(PBTN_PIN))) == 0x00000000);
    		
    		NVIC_SystemReset();
    	}
    	
    	if(NRF_GPIOTE->EVENTS_IN[1] == 1)
    	{
    		NRF_GPIOTE->EVENTS_IN[1] = 0;
    		chkCC3100IRQ();
    	}
    }
    
    //void chkBTN(void)
    //{	
    	//if(g_btn_state == (BTN_STATE_IDLE))
    		//return;
    		
    //#i
    //}
    
    */

    And header file 

    #ifndef __MEDSENSE_H_
    #define __MEDSENSE_H_
    #include "boards.h"
    #include "nrf52.h"
    #include "clock.h"
    #include "uart.h"
    
    #include "nrf_delay.h"
    #include "sl_common.h"
    
    #include "spi.h"
    #include "flash.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    
    
    #define delay_ms nrf_delay_ms          
    
    #define	FLASH_MEMORY_PAGE_SIZE				0x00001000
    
    #define	FLASH_PAGE_SIZE_IN_WORDS			1024
    #define	FLASH_PAGE_SIZE						4096
    
    #define	FLASH_UDATA_ADDR					0x0007F000
    #define FLASH_UDATA_SIZE					(FLASH_MEMORY_PAGE_SIZE)	
    	
    #define	FLASH_USER_SIGN_ADDR				(FLASH_UDATA_ADDR)
    #define FLASH_USER_SIGN_BSIZE				16
    #define	FLASH_USER_SIGN_WSIZE				4
    
    #define	FLASH_UDATA_VER_ADDR				((FLASH_USER_SIGN_ADDR) + (FLASH_USER_SIGN_BSIZE))
    #define	FLASH_UDATA_VER_VAL					0x00000000
    #define	FLASH_UDATA_VER_BSIZE				4
    #define	FLASH_UDATA_VER_WSIZE				1
    
    #define FLASH_UDATA_AP_SSID_ADDR			((FLASH_UDATA_VER_ADDR) + (FLASH_UDATA_VER_BSIZE))
    #define FLASH_UDATA_AP_SSID_VAL				"BLE2WiFi"
    #define FLASH_UDATA_AP_SSID_BSIZE			32
    #define FLASH_UDATA_AP_SSID_WSIZE			8
    
    #define FLASH_UDATA_AP_PASSWD_ADDR			((FLASH_UDATA_AP_SSID_ADDR) + (FLASH_UDATA_AP_SSID_BSIZE))
    #define FLASH_UDATA_AP_PASSWD_VAL			"wifi1234"
    #define FLASH_UDATA_AP_PASSWD_BSIZE			32
    #define FLASH_UDATA_AP_PASSWD_WSIZE			8
    
    #define FLASH_UDATA_AP_PORT_ADDR			((FLASH_UDATA_AP_PASSWD_ADDR) + (FLASH_UDATA_AP_PASSWD_BSIZE))
    #define FLASH_UDATA_AP_PORT_VAL				(WIFI_DEFAULT_AP_PORT)
    #define FLASH_UDATA_AP_PORT_BSIZE			4
    #define FLASH_UDATA_AP_PORT_WSIZE			1
    
    #define FLASH_UDATA_AP_ENC_ADDR				((FLASH_UDATA_AP_PORT_ADDR) + (FLASH_UDATA_AP_PORT_BSIZE))
    #define FLASH_UDATA_AP_ENC_VAL				(WIFI_DEFAULT_AP_ENC)
    #define FLASH_UDATA_AP_ENC_BSIZE			4
    #define FLASH_UDATA_AP_ENC_WSIZE			1
    
    
    #define FLASH_UDATA_STA_SSID_ADDR			((FLASH_UDATA_AP_ENC_ADDR) + (FLASH_UDATA_AP_ENC_BSIZE))
    #define FLASH_UDATA_STA_SSID_VAL			"unknown"
    #define FLASH_UDATA_STA_SSID_BSIZE			32
    #define FLASH_UDATA_STA_SSID_WSIZE			8
    
    #define FLASH_UDATA_STA_PASSWD_ADDR			((FLASH_UDATA_STA_SSID_ADDR) + (FLASH_UDATA_STA_SSID_BSIZE))
    #define FLASH_UDATA_STA_PASSWD_VAL			"none1234"
    #define FLASH_UDATA_STA_PASSWD_BSIZE		32
    #define FLASH_UDATA_STA_PASSWD_WSIZE		8
    
    #define FLASH_UDATA_STA_PORT_ADDR			((FLASH_UDATA_STA_PASSWD_ADDR) + (FLASH_UDATA_STA_PASSWD_BSIZE))
    #define FLASH_UDATA_STA_PORT_VAL			(WIFI_DEFAULT_AP_PORT)
    #define FLASH_UDATA_STA_PORT_BSIZE			4
    #define FLASH_UDATA_STA_PORT_WSIZE			1
    
    #define FLASH_UDATA_STA_ENC_ADDR			((FLASH_UDATA_STA_PORT_ADDR) + (FLASH_UDATA_STA_PORT_BSIZE))
    #define FLASH_UDATA_STA_ENC_VAL				(WIFI_DEFAULT_STA_ENC)
    #define FLASH_UDATA_STA_ENC_BSIZE			4
    #define FLASH_UDATA_STA_ENC_WSIZE			1
    
    #define FLASH_UDATA_REMOTE_SERVER_ADDR		((FLASH_UDATA_STA_ENC_ADDR) + (FLASH_UDATA_STA_ENC_BSIZE))
    #define FLASH_UDATA_REMOTE_SERVER_VAL		(WIFI_REMOTE_SERVER_IP_ADDR)
    #define FLASH_UDATA_REMOTE_SERVER_BSIZE		4
    #define FLASH_UDATA_REMOTE_SERVER_WSIZE		1
    
    #define FLASH_UDATA_WIFI_MODE_ADDR			((FLASH_UDATA_REMOTE_SERVER_ADDR) + (FLASH_UDATA_REMOTE_SERVER_BSIZE))
    #define FLASH_UDATA_WIFI_MODE_VAL			(WIFI_MODE_AP)
    #define FLASH_UDATA_WIFI_MODE_BSIZE			4
    #define FLASH_UDATA_WIFI_MODE_WSIZE			1
    
    #define FLASH_UDATA_DEVICE_NAME_ADDR		((FLASH_UDATA_WIFI_MODE_ADDR) + (FLASH_UDATA_WIFI_MODE_BSIZE))
    #define FLASH_UDATA_DEVICE_NAME_VAL			"BLE2WiFi-Gateway"
    #define FLASH_UDATA_DEVICE_NAME_BSIZE		32
    #define FLASH_UDATA_DEVICE_NAME_WSIZE		8
    
    
    #define	FLASH_UDATA_CHKSUM_ADDR				((FLASH_UDATA_ADDR) + (FLASH_UDATA_SIZE) - 4)
    #define FLASH_UDATA_CHKSUM_SIZE				4
    	
    #define FLASH_CSUM_OK						0x00
    #define FLASH_CSUM_FAIL						0x01
    
    #define FLASH_ERASE_PAGE_DELAY				200							// [x1ms]
    
    #define FLASH_SMS_INIT_ERASE_MEMORY			0x00
    #define FLASH_SMS_WAIT_PHASE1				0x01
    #define FLASH_SMS_WAIT_PHASE2				0x02
    #define FLASH_SMS_WAIT_PHASE3				0x03
    #define FLASH_SMS_WAIT_PHASE4				0x04                                                     
    	
    //#define SYSTEM_DEBUG
    #define Buttons_Number 1
    
    #define UART_BAUDRATE							UART0_BAUDRATE_921600
    
    #define UINT8   uint8_t
    #define UINT32  uint32_t
    #define INT32 int32_t
    #define _i32 int32_t
    
    /*  moved to custom_board
    #define CC_IRQ_PIN								0
    #define CC_NRST_PIN								1
    #define CC_CS_PIN								2
    #define CC_MISO_PIN								3
    #define CC_MOSI_PIN								4
    #define CC_SCK_PIN								5
    #define CC_NHIB_PIN								6
    
    */
    #define initUART								initUART0
    #define printUART								printUART0
    #define deinitUART								deinitUART0
    
    //#define SL_MAX_SOCKETS                                                          8
    #define SL_STOP_TIMEOUT        0xFF
    
    #define BLEF_CHANNEL_SCAN_SWITCHING_PERIOD		20						// [x1ms]
    #define UART_TX_PIN								11						
    #define UART_RX_PIN								12	
    
    #define LED_MODE_OFF							0x00
    #define LED_MODE_STATIC							0x01
    #define LED_MODE_BLINK							0x02
    #define LED_DISABLED							0x00
    #define LED_ENABLED								0x01
    #define LED_STATE_FLAG							0x80
    
    
    	
    
    #define BLE_RX_BUFF_SIZE						512
    #define BLE_RX_DATA_BUFF_SIZE					4096					// must be in a form of 2^n
    #define BLE_RX_DATA_BUFF_MASK					((BLE_RX_DATA_BUFF_SIZE) - 1)
    
    
    #define BTN_STATE_RESTORE_AP_MODE				0x01
    #define BTN_STATE_IDLE							0x00
    
    #define WIFI_NETWORK_IP_OFFSET					0xC0A82A01				// 192.168.42.1
    #define WIFI_NETWORK_MASK						0xFFFFFF00				// 255.255.255.0
    #define WIFI_NETWORK_IP_GW						1						// x.y.z.1
    #define WIFI_NETWORK_IP_DNS						2						// x.y.z.2
    #define WIFI_NETWORK_IP_AP						3						// x.y.z.3
    #define WIFI_NETWORK_IP_DHCP_BEG				100
    #define WIFI_NETWORK_IP_DHCP_END				200
    #define WIFI_SERVER_PORT						5000					// TCP server port 
    #define WIFI_SECURITY_OPEN						(SL_SEC_TYPE_OPEN)
    #define WIFI_SECURITY_WPA						(SL_SEC_TYPE_WPA)
    #define WIFI_MAC_ADDR_LEN						(SL_MAC_ADDR_LEN)
    #define WIFI_AP_LIST_LEN						20						// number of AP which can be stored during the scan of medium
    
    
    #define WIFI_BUFF_SIZE							1400
    #define WIFI_RX_BUFF_SIZE						2048					// must be a power of two!
    #define WIFI_RX_BUFF_MASK						((WIFI_RX_BUFF_SIZE) - 1)
    
    #define WIFI_MODE_AP							0x00
    #define WIFI_MODE_STA							0x01
    #define WIFI_SSID_SIZE							33
    #define WIFI_PASSWD_SIZE						33
    #define WIFI_DEFAULT_AP_PORT					50000
    #define WIFI_DEFAULT_STA_PORT					50000
    #define WIFI_DEFAULT_AP_ENC					2
    #define WIFI_DEFAULT_STA_ENC					2
    #define WIFI_REMOTE_SERVER_IP_ADDR				0xFFFFFFFF
    
    #define WIFI_PKT_SET_STA_CONFIG					0x1A
    #define WIFI_PKT_FORCE_AP_MODE					0x21
    #define WIFI_PKT_BLE_BEACONS					0x6A
    
    #define WIFI_PKT_PREAMBULE_IDX					0
    #define WIFI_PKT_TYPE_IDX						3
    #define WIFI_PKT_PAYLOAD_SIZE_IDX				4
    
    #define WIFI_PACKET_FOUND						0x00
    #define WIFI_PACKET_NOT_FOUND					0x01
    #define WIFI_PACKET_CSUM_ERROR					0x02
    #define WIFI_PACKET_MISSING_PREAMBULE			0x04
    #define WIFI_PACKET_MISSING_DATA				0x08
    #define WIFI_PACKET_NOT_ENOUGHT_DATA			0x10
    
    #define FLASH_UPDATE_DISABLED					0x00
    #define FLASH_UPDATE_AP_INFO					0x01
    #define FLASH_UPDATE_STA_INFO					0x02
    
    #define FLASH_WRITE_DATA_SIZE					256
    
    #define DEVICE_NAME_SIZE						32
    #define DEVICE_ID_SIZE							8
    
    #define WIFI_AP_INFO_LEN						32
    #define WIFI_SCAN_INTERVAL						10								// in seconds
    
    #define WIFI_CONNECTED							1
    #define WIFI_DISCONNECTED						0
    
    #define WIFI_IP_LEASE_TIME   					3600					// IP address lease time [s]
    #define SUCCESS        							0
    
    #define WIFI_SETUP_RETRIES						0x03					// number of retries executed to set certian mode
    #define WIFI_RESET_DELAY						500						// [ms] reset delay 
    #define WIFI_LOOP_DELAY							10000					// [ms] while loop delay - wait response
    #define WIFI_REMOTE_SERVER_CONNECTION_RETRY_PERIOD	5000				// [x1ms] check for connection establishment  
    
    #define WIFI_OK									0x00
    #define WIFI_ERROR_SET_DEF						0x01
    #define WIFI_ERROR_START_DEV					0x02
    #define WIFI_ERROR_STA_DEVICE					0x03
    #define WIFI_ERROR_MISSING_AP					0x04
    #define WIFI_EEROR_NO_IP						0x05
    #define WIFI_EEROR_CANNOT_RUN_AP				0x06
    #define WIFI_ERROR_CANNOT_CONN2AP				0x07
    #define WIFI_ERROR_CANNOT_CONN2INT				0x08
    #define WIFI_ERROR_SERVER_FAILED				0x09
    #define WIFI_ERROR_CONNECTION_POLICY			0x0A
    #define WIFI_ERROR_DIS_SCAN_POLICY				0x0B
    #define WIFI_ERROR_CREATE_SOCKET				0x0C
    #define WIFI_ERROR_SOCKET_NONBLOCKING			0x0D
    #define WIFI_ERROR_SOCKET_BINDING				0x0E	
    #define WIFI_ERROR_LAN_CONNECTION_TIMEOUT		0x10	
    #define WIFI_ERROR_REMOTE_SERVER_DISCONNECTED	0x11
    #define WIFI_ERROR_REMOTE_SERVER_SOCKET_FAILED	0x12
    #define WIFI_ERROR_FAIL2SEND_DATA				0x13
    #define WIFI_ERROR_AP_NO_IP						0x14
    #define WIFI_ERROR_CANNOT_RUN_AP				0x15
    #define WIFI_ERROR_WAITING4RETRY_TIMEOUT		0x16	
    #define WIFI_ERROR_SOCKET_CLOSED				0x17
    
    #define WIFI_DISABLED							0x00
    #define WIFI_ENABLED							0x01	
    #define WIFI_WAIT4IP_PERIOD						10000					// [x1ms]
    		
    #define WIFI_AP_DISCONNECTED					0x00
    #define WIFI_AP_CONNECTED						0x01
    
    #define WIFI_SOCKET_DISCONNECTED				0x00
    #define WIFI_SOCKET_CONNECTED					0x01
    
    #define STATUS_BIT_PING_DONE  31
    
    /* Status bits - These are used to set/reset the corresponding bits in a 'status_variable' */
    
    /* Application specific status/error codes */
    typedef enum{
        LAN_CONNECTION_FAILED = -0x7D0,        /* Choosing this number to avoid overlap with host-driver's error codes */
        LAN_CONNECTION_TIMEOUT = LAN_CONNECTION_FAILED -1,       
        INTERNET_CONNECTION_FAILED = LAN_CONNECTION_TIMEOUT - 1,
        DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,
    
        STATUS_CODE_MAX = -0xBB8
    }e_AppStatusCodes;
    
    typedef struct
    {
        unsigned long  ipV4;
        unsigned long  ipV4Mask;
        unsigned long  ipV4Gateway;
        unsigned long  ipV4DnsServer;
    }_NetCfgIpV4Args_t;
    
                                                       
    
    extern const uint8_t g_firmware_version[6];
    
    extern volatile uint8_t g_led_blink_pin;
    extern volatile uint32_t g_led_blink_period;
    extern volatile uint32_t g_led_blink_timer;
    extern volatile uint8_t g_led_flag;
    
    
    extern volatile uint8_t g_btn_state;
    
    extern volatile uint8_t g_ble_rx_buff[BLE_RX_BUFF_SIZE];
    extern volatile uint16_t g_ble_rx_buff_len;
    extern volatile uint8_t g_ble_rx_data[BLE_RX_DATA_BUFF_SIZE];
    extern volatile uint16_t g_ble_rx_data_widx;
    extern volatile uint16_t g_ble_rx_data_ridx;
    extern volatile uint8_t g_ble_tx_buff[WIFI_BUFF_SIZE];
    extern volatile uint16_t g_blef_tx_count;
    
    
    extern volatile uint8_t g_flash_update;
    
    extern volatile uint8_t g_wifi_status;
    extern volatile uint8_t g_wifi_error;
    extern volatile uint8_t g_wifi_mode;
    extern volatile uint8_t g_wifi_ssid[WIFI_SSID_SIZE];
    extern volatile uint8_t g_wifi_passwd[WIFI_PASSWD_SIZE];
    extern volatile uint32_t g_wifi_port;
    extern volatile uint32_t g_wifi_enc;
    extern volatile uint32_t g_wifi_remote_server_ip;
    extern volatile uint8_t g_wifi_tx_buff[WIFI_BUFF_SIZE];
    extern volatile uint8_t g_wifi_rx_buff[WIFI_RX_BUFF_SIZE];
    extern volatile uint8_t g_wifi_pkt[WIFI_BUFF_SIZE];
    extern volatile uint16_t g_wifi_rx_buff_widx;
    extern volatile uint16_t g_wifi_rx_buff_ridx;
    extern volatile uint8_t g_wifi_local_ip_str[20];
    extern volatile uint8_t g_wifi_remote_server_ip_str[20];
    extern volatile int16_t g_wifi_remote_cli_socket;
    
    extern volatile uint8_t g_device_name[DEVICE_NAME_SIZE];
    extern volatile uint8_t g_device_id[DEVICE_ID_SIZE];
    extern volatile uint8_t g_flash_write_data[FLASH_WRITE_DATA_SIZE];
    
    
    static volatile uint16_t AddrSize;
    static volatile uint16_t Rem_AddrSize;
    typedef unsigned int Fd_t;
    Fd_t spi_Open(char *ifName, unsigned long flags);
    int spi_Close(Fd_t fd);
    int spi_Write(Fd_t fd, unsigned char *pBuff, int len);
    int spi_Read(Fd_t fd, unsigned char *pBuff, int len);
    
    void output(int pin);
    void CC3100_IRQHandler(void);
    void	 	initFLASH(void);
    void 		loadUserDataFLASH(void);
    void 		updateUserDataFLASH(void);
    void		chkUserSpaceFLASH(void);
    void 		erasePageFLASH(uint32_t addr);
    void 		writeWordFLASH(uint32_t addr, uint32_t data);
    uint32_t 	readWordFLASH(uint32_t addr);
    void 		setDefaultFLASH(void);
    void 		chkFLASH(void);
    
    void 		initWIFI(void);
    void 		rstWIFI(void);
    void 		powerDownWIFI(void);
    uint8_t 	setAPmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc);
    uint8_t 	setSTAmodeWIFI(uint8_t * ssid, uint8_t * passwd, uint16_t portNum, uint8_t enc);
    void 		chkWIFI(void);
    uint16_t 	getRxBuffCountWIFI(void);
    uint8_t 	getNextPktWIFI(void);
    uint16_t  	txPktWIFI(int16_t socket, uint8_t pkt_type);
    
    int16_t 	openSocketWIFI(void);
    uint8_t 	chkLocalSocketWIFI(void);
    uint16_t 	txMessageWIFI(int16_t socket, uint8_t * dataPtr, uint16_t numBytes);
    uint16_t 	rxLocalSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen);
    uint16_t 	rxRemoteSocketDataWIFI(uint8_t * dataPtr, uint16_t buffLen);
    void 		getStrAddr(char * str, uint32_t addr);
    uint8_t 	scanMediumCC3100(void);
    uint8_t 	connect2ServerCC3100(void);
    void chkCC3100IRQ(void);
    
    void initLED(void);
    void deinitLED(void);
    void setLED(uint8_t led, uint8_t mode, uint32_t period);
    void chkLED(void);
    
    
     
    ///wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    /// AP mode CC3100 generic functions
    ///---------------------------------------------------------------------
    //int32_t	 	initializeAppVariables(void);
    int32_t 	configureSimpleLinkToDefaultState(void);
    //static int32_t	establishConnectionWithAP(uint8_t * ssid, uint8_t * passwd, uint8_t enc);
    static _i32 establishConnectionWithAP();
    
    volatile  uint32_t  g_Status = 0;
    volatile uint32_t  g_PingPacketsRecv = 0;
    volatile uint32_t  g_GatewayIP = 0;
    static volatile uint32_t  g_StationIP = 0;
    
    void ASSERT_ON_ERROR(int);
    
    
    #endif
    
    

    Here is sdk_config , don't know if there is negative interactions from trying so many approaches.

    Not sure what needs to be removed or added.

    Will attach since there were errors on including as code.3364.sdk_config.h

Children
  • I don't see how to execute my application code at different interrupt prioritizes. I see ref to running at app high, low med as if we all know how/where it is set. I have gone through the docs and examples and I don't see how to do this.  I do think that main runs at the lowest priority but how do I provide functions that run at anything other than the same priority as main ?  I know I must be missing more than one piece of key info. I have not seen any examples yet that show how to do this. Appreciate any help.

  • If you were using a timer to and then calling functions from its timeout handler, which in turn waits for interrupts, then you will have application code running at main's context and two interrupt contexts as the functions called in the timeout handler must be waiting for a higher priority interrupt than the handler they are being called from. 

    I have taken a look at your code and you are mixing register-level programming of the GPIOTE peripheral with the GPIOTE driver ( nrf_drv_gpiote.c) which can lead to conflicts, especially when you're configuring the registers manually first and then enabling the driver and calling its API to configure the registers. 

    In main() you're calling modules_init()  and CC3100_InterruptEnable(), which contains this code

    static void modules_init(void)
    {
    
    output(CC_NHIB_PIN);
    output(LED_RED);
    output(LED_GREEN);
    output(LED_BLUE);
    
    NRF_GPIO->OUTSET = (1<<CC_NHIB_PIN);
    NRF_GPIO->OUTSET = (1<<LED_RED);
    NRF_GPIO->OUTSET = (1<<LED_GREEN);
    NRF_GPIO->OUTSET = (1<<LED_BLUE);
    
    NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;		// set as input with pullup
    
    /*
        NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000001;		// set as output
        NRF_P0->PIN_CNF[LED_RED] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_GREEN] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_BLUE] = 0x00000001;	// set as output
    
    */
    
    
        for (x = 0; x < 5 ; x++)
        {
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        delay_ms(200);
        NRF_P0->OUTSET = (1<<(LED_GREEN));
         delay_ms(200);
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        }
        NRF_P0->OUTSET = (1<<(LED_GREEN));
        CC3100_disable();
    
     //   NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[0] = 0x00010001;	
     
         NRF_P0->PIN_CNF[BUTTON_2] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[1] = 0x00020001|((BUTTON_2)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001;	
    
         gpio_init();
           .
           .
           .
    }   
    void CC3100_InterruptEnable()
    {	
    	//NVIC_DisableIRQ(GPIOTE_IRQn);
        //NRF_GPIOTE->INTENSET = 0x00000002;	
    	//NRF_GPIOTE->EVENTS_IN[1] = 0;									
        //NVIC_EnableIRQ(GPIOTE_IRQn);
    
         nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
         
    }

    At the end you calling gpio_init() which contains this code

    void gpio_init(void)
    {
        ret_code_t err_code;
    
         // APP_GPIOTE_INIT(1);
    
         if (!nrf_drv_gpiote_is_init())
            {
                    err_code = nrf_drv_gpiote_init();
                    APP_ERROR_CHECK(err_code);
            }
            
    
        nrf_drv_gpiote_out_config_t out_config = GPIOTE_CONFIG_OUT_SIMPLE(true);
    
            err_code = nrf_drv_gpiote_out_init(CC_NRST_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
          err_code = nrf_drv_gpiote_out_init(LED_RED, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
            err_code = nrf_drv_gpiote_out_init(CC_NHIB_PIN, &out_config);
            APP_ERROR_CHECK(err_code);
    
    
         // Make a configuration for input pins. This is suitable for both pins in this example.
        nrf_drv_gpiote_in_config_t in_config = {// = GPIOTE_CONFIG_IN_SENSE_LOTOHI(true);
          .is_watcher = false,                        \
           .hi_accuracy = true,                     \
            .pull = NRF_GPIO_PIN_PULLUP,                \
            .sense = NRF_GPIOTE_POLARITY_LOTOHI
            };
    
         err_code = nrf_drv_gpiote_in_init(CC_IRQ_PIN, &in_config, CC3100_IRQHandler);
        APP_ERROR_CHECK(err_code);
       
        in_config.hi_accuracy = true;
        in_config.pull = NRF_GPIO_PIN_PULLUP;
        in_config.sense = NRF_GPIOTE_POLARITY_HITOLO;
        
         err_code = nrf_drv_gpiote_in_init(BUTTON_2, &in_config, Button_IRQHandler);
        APP_ERROR_CHECK(err_code);
    
        //    nrf_drv_gpiote_in_event_enable(CC_IRQ_PIN, true);
          nrf_drv_gpiote_in_event_enable(BUTTON_2, true);
    
    }

    There are also references/calls to 

    NVIC_EnableIRQ(GPIOTE_IRQn) and NVIC_DisableIRQ(GPIOTE_IRQn)in the Button_IRQHandler as well as initGPIOINT, CC3100_InterruptDisable and CC3100_InterruptEnable.

    So I would recommend that you only use the nrf_gpiote_drv and its API instead of the register-level programming.

    Here is what I would like you to try:

    Can you comment out the following code in modules init()

        output(CC_NHIB_PIN);
    output(LED_RED);
    output(LED_GREEN);
    output(LED_BLUE);
    
    NRF_GPIO->OUTSET = (1<<CC_NHIB_PIN);
    NRF_GPIO->OUTSET = (1<<LED_RED);
    NRF_GPIO->OUTSET = (1<<LED_GREEN);
    NRF_GPIO->OUTSET = (1<<LED_BLUE);
    
    NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;		// set as input with pullup
    
    /*
        NRF_P0->PIN_CNF[CC_NHIB_PIN] = 0x00000001;		// set as output
        NRF_P0->PIN_CNF[LED_RED] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_GREEN] = 0x00000001;	// set as output
        NRF_P0->PIN_CNF[LED_BLUE] = 0x00000001;	// set as output
    
    */
    
    
        for (x = 0; x < 5 ; x++)
        {
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        delay_ms(200);
        NRF_P0->OUTSET = (1<<(LED_GREEN));
         delay_ms(200);
        NRF_P0->OUTCLR = (1<<(LED_GREEN));	
        }
        NRF_P0->OUTSET = (1<<(LED_GREEN));
        CC3100_disable();
    
     //   NRF_P0->PIN_CNF[CC_IRQ_PIN] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[0] = 0x00010001|((CC_IRQ_PIN)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[0] = 0x00010001;	
     
         NRF_P0->PIN_CNF[BUTTON_2] = 0x00000000;			// set as input with pullup
    	NRF_GPIOTE->CONFIG[1] = 0x00020001|((BUTTON_2)<<8);	// event mode, high to low transition
    	//NRF_GPIOTE->CONFIG[1] = 0x00010001;	

    and then run the code in a debug session and provide a screenshot of  the GPIOTE registers after you have run gpio_init() and CC3100_InterruptEnable()? You should see that the INTENSET register has IN0 and IN1 enabled in addition to PORT.  INTCLR should be identical to INTENSET. 

    CONFIG[0] and CONFIG[1] should also reflect the in_config passed to nrf_drv_gpiote_in_init().

    Bjørn

  • Thank you for the help. I will update the code to use driver versus register level.

    Assume that includes the spi code I am using.

    I also changed to using sd_nvic_ interrupt enable/disable versus NVIC.

    I understand your timer explanation but don't see how to apply it to getting an interrupt from a CC3100 SoC that needs to be serviced by spi functions. Are you saying that if I clean up per your suggestions that the GPIOTE driver will work. If the GPIOTE interrupt priority in the sdk_config is set to 2 then the CC3100 interrupt handler defined in the gpio_init in main will execute from that interrupt. Or is that wrong since main itself if a much lower priority ? 

  • Is is screenshot after breaking in middle of program.

  • Looking into the spi code I was using, is using the legacy SPI driver an option or  is there another solution that would integrate better with this application ?

Related