nrf51822 AT SIM868

/* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */


/** @file
 * @defgroup uart_example_pca10000_main main.c
 * @{
 * @ingroup uart_example_pca10000
 *
 * @brief UART Example Application main file.
 *
 * This file contains the source code for a sample application using UART.
 *
 */


#include <stdbool.h>
#include <stdint.h>
#include "nrf_delay.h"
#include "nrf.h"
#include "simple_uart.h"
#include "nrf_gpio.h"
#include "boards.h"
#include "app_fifo.h"
#include "app_uart.h"
#include "compiler_abstraction.h"
#include "app_error.h"


//BLE
#include "softdevice_handler.h"
#include "ble.h"
#include "ble_bas.h"
#include "ble_hrs.h"
#include "ble_dis.h"
#include "ble_advdata.h"
#include "ble_srv_common.h"
//#include "device_manager.h"


#define IS_SRVC_CHANGED_CHARACT_PRESENT      0                                          /**< Include or not the service_changed characteristic. if not enabled, the server's database cannot be changed for the lifetime of the device*/
                                                                             
#define HR_INC_BUTTON_PIN_NO                 BUTTON_0                                   /**< Button used to increment heart rate. */
#define HR_DEC_BUTTON_PIN_NO                 BUTTON_1                                   /**< Button used to decrement heart rate. */
#define BOND_DELETE_ALL_BUTTON_ID            HR_DEC_BUTTON_PIN_NO                       /**< Button used for deleting all bonded centrals during startup. */


#define DEVICE_NAME                          "Nordic_HRM"                               /**< Name of device. Will be included in the advertising data. */
#define MANUFACTURER_NAME                    "NordicSemiconductor"                      /**< Manufacturer. Will be passed to Device Information Service. */
#define APP_ADV_INTERVAL                     40                                         /**< The advertising interval (in units of 0.625 ms. This value corresponds to 25 ms). */
#define APP_ADV_TIMEOUT_IN_SECONDS           180                                        /**< The advertising timeout in units of seconds. */


#define APP_TIMER_PRESCALER                  0                                          /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_MAX_TIMERS                 5                                          /**< Maximum number of simultaneously created timers. */
#define APP_TIMER_OP_QUEUE_SIZE              5                                          /**< Size of timer operation queues. */


#define BATTERY_LEVEL_MEAS_INTERVAL          APP_TIMER_TICKS(2000, APP_TIMER_PRESCALER) /**< Battery level measurement interval (ticks). */


#define HEART_RATE_MEAS_INTERVAL             APP_TIMER_TICKS(1000, APP_TIMER_PRESCALER) /**< Heart rate measurement interval (ticks). */
#define MIN_HEART_RATE                       60                                         /**< Minimum heart rate as returned by the simulated measurement function. */
#define MAX_HEART_RATE                       300                                        /**< Maximum heart rate as returned by the simulated measurement function. */
#define HEART_RATE_CHANGE                    2                                          /**< Value by which the heart rate is incremented/decremented during button press. */


#define APP_GPIOTE_MAX_USERS                 1                                          /**< Maximum number of users of the GPIOTE handler. */


#define BUTTON_DETECTION_DELAY               APP_TIMER_TICKS(50, APP_TIMER_PRESCALER)   /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */


#define MIN_CONN_INTERVAL                    MSEC_TO_UNITS(500, UNIT_1_25_MS)           /**< Minimum acceptable connection interval (0.5 seconds). */
#define MAX_CONN_INTERVAL                    MSEC_TO_UNITS(1000, UNIT_1_25_MS)          /**< Maximum acceptable connection interval (1 second). */
#define SLAVE_LATENCY                        0                                          /**< Slave latency. */
#define CONN_SUP_TIMEOUT                     MSEC_TO_UNITS(4000, UNIT_10_MS)            /**< Connection supervisory timeout (4 seconds). */


#define FIRST_CONN_PARAMS_UPDATE_DELAY       APP_TIMER_TICKS(5000, APP_TIMER_PRESCALER) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY        APP_TIMER_TICKS(30000, APP_TIMER_PRESCALER)/**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT         3                                          /**< Number of attempts before giving up the connection parameter negotiation. */


#define SEC_PARAM_TIMEOUT                    30                                         /**< Timeout for Pairing Request or Security Request (in seconds). */
#define SEC_PARAM_BOND                       1                                          /**< Perform bonding. */
#define SEC_PARAM_MITM                       0                                          /**< Man In The Middle protection not required. */
#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 encrypt*/




 
static ble_gap_adv_params_t                  m_adv_params;                              /**< Parameters to be passed to the stack when starting advertising. */
ble_bas_t                                    bas;                                       /**< Structure used to identify the battery service. */
static ble_hrs_t                             m_hrs;                                     /**< Structure used to identify the heart rate service. */
static volatile uint16_t                     m_cur_heart_rate;                          /**< Current heart rate value. */
                                                                                       
//static app_timer_id_t                        m_battery_timer_id;                        /**< Battery timer. */
//static app_timer_id_t                        m_heart_rate_timer_id;                     /**< Heart rate measurement timer. */
static bool                                  m_memory_access_in_progress = false;       /**< Flag to keep track of ongoing operations on persistent memory. */
//static dm_application_instance_t             m_app_handle;                              /**< Application identifier allocated by device manager */
static void ble_evt_dispatch(ble_evt_t * p_ble_evt);


static void sys_evt_dispatch(uint32_t sys_evt);












#define UART_TX_BUF_SIZE                256                                         /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE                256                                         /**< UART RX buffer size. */
#define LOG_RX_PIN_NUMBER               23
#define LOG_TX_PIN_NUMBER               24
#define MAX_DATA_LEN 500


static uint8_t uart_rx_data_array[MAX_DATA_LEN];
static uint8_t m_uart_rx_data_array[MAX_DATA_LEN];
static uint16_t m_uart_data_array_index;
static uint16_t mm_uart_data_array_index;


#define UNUSED_VARIABLE(X)  ((void)(X))
#define UNUSED_PARAMETER(X) UNUSED_VARIABLE(X)
#define UNUSED_RETURN_VALUE(X) UNUSED_VARIABLE(X)
uint8_t rx_cmd_data = 0;
volatile uint8_t  start_test_flag = 0;
void uart_event_handle(app_uart_evt_t * p_event)
{
    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
            UNUSED_VARIABLE(app_uart_get(&rx_cmd_data));
   m_uart_rx_data_array[mm_uart_data_array_index++] = rx_cmd_data;
if(m_uart_rx_data_array[mm_uart_data_array_index-8]=='A'&&m_uart_rx_data_array[mm_uart_data_array_index-7]=='T'&&m_uart_rx_data_array[mm_uart_data_array_index-2]=='T')
{
start_test_flag = m_uart_rx_data_array[mm_uart_data_array_index-1];
}
if(MAX_DATA_LEN==m_uart_data_array_index)
                    mm_uart_data_array_index = 0;
            break;
        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;


        default:
            break;
    }
}






static void m_uart_init(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        LOG_RX_PIN_NUMBER,
        LOG_TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };


app_uart_close(0);

app_uart_flush();
nrf_delay_ms(2);
    APP_UART_FIFO_INIT( &comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);
    APP_ERROR_CHECK(err_code);
}


#define PCCTL_PIN                29
#define UART_TX_BUF_SIZE                256                                         /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE                256                                         /**< UART RX buffer size. */
#define GPRS_TX_PIN  4
#define GPRS_RX_PIN               5
#define GPRS_POWER_ON     nrf_gpio_cfg_output(PCCTL_PIN);nrf_gpio_pin_set(PCCTL_PIN)
#define GPRS_POWER_OFF nrf_gpio_pin_clear(PCCTL_PIN)
static uint8_t server[]       = "AT+CIPSTART=\"TCP\",\"14.215.177.38\",80\r\n";
uint8_t M_imsi[20]={0};
uint8_t M_imei[20]={0};
uint8_t M_csq[4]={0};
uint8_t TCP_CONNECT[20] = {0};




void gprs_event_handle(app_uart_evt_t * p_event)
{
uint8_t temp = 0;
    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
             app_uart_get(&temp);
             uart_rx_data_array[m_uart_data_array_index++] = temp;
             //m_data_array_index++
NRF_LOG_PRINTF("%c",temp);
             if(MAX_DATA_LEN==m_uart_data_array_index)
                    m_uart_data_array_index = 0;
            break;
        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;


        default:
            break;
    }
}


static void m_gprs_init(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        GPRS_RX_PIN,
        GPRS_TX_PIN,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };


app_uart_close(0);


app_uart_flush();
nrf_delay_ms(2);
    APP_UART_FIFO_INIT( &comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       gprs_event_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);
    APP_ERROR_CHECK(err_code);
}


typedef uint32_t ret_code_t;
//typedef struct
//{
//    uint16_t        line_num;    /**< The line number where the error occurred. */
//    uint8_t const * p_file_name; /**< The file in which the error occurred. */
//    uint32_t        err_code;    /**< The error code representing the error that occurred. */
//} error_info_t;




  __weak void app_error_fault_handler(uint32_t id, uint32_t pc, uint32_t info);


void app_error_handler(ret_code_t error_code, uint32_t line_num, const uint8_t * p_file_name)
{
    error_info_t error_info =
    {
        .line_num    = line_num,
        .p_file_name = p_file_name,
        .err_code    = error_code,
    };
    app_error_fault_handler(0x00004000+1, 0, (uint32_t)(&error_info));


    UNUSED_VARIABLE(error_info);
}






void nrf_delay_ms(uint32_t volatile number_of_ms)
{
    while(number_of_ms != 0)
    {
        number_of_ms--;
        nrf_delay_us(999);
    }
}


void print_log(const uint8_t *pstring)
{
      while(*pstring)
      {
          while(app_uart_put(*pstring++) != NRF_SUCCESS);
            
      }
}


void clear_rx_buffer(uint8_t *buf,uint16_t *index)
{
      memset(buf,0,MAX_DATA_LEN);
      *index = 0;
}


void send_at_cmd(const uint8_t *pstring)
{
      while(*pstring)
      {
          while(app_uart_put(*pstring++) != NRF_SUCCESS);
            
      }


}


void get_IMSI()
{
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);   
send_at_cmd("AT+CIMI\r\n");
nrf_delay_ms(2000);
memset(M_imsi,0,20);
memcpy(M_imsi,&uart_rx_data_array[10],15);
nrf_delay_ms(1000);
}




void get_IMEI()
{
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);   
send_at_cmd("AT+GSN\r\n");
nrf_delay_ms(2000);
memset(M_imei,0,20);
memcpy(M_imei,&uart_rx_data_array[9],17);
nrf_delay_ms(1000);
}


void Wait_CREG(void)
{
uint8_t i = 0;
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
while(i == 0)        
{
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);       
send_at_cmd("AT+CGREG?\r\n");
nrf_delay_ms(2000);  


for(uint8_t k=0;k<m_uart_data_array_index;k++)      
{
 if(uart_rx_data_array[k] == ':')
 {
 if((uart_rx_data_array[k+4] == '1')||(uart_rx_data_array[k+4] == '5'))
 {
 i = 1;
 //UART1_SendLR();
 break;
 }
 }
}
     }
}


void check_csq()
{
uint8_t i = 0;
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
while(i == 0)        
{
clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
nrf_delay_ms(2000); 
send_at_cmd("AT+CSQ\r\n");
nrf_delay_ms(2000);  


for(uint8_t k=0;k<m_uart_data_array_index;k++)      
{
 if(uart_rx_data_array[k] == ':')
 {
memcpy(M_csq,&uart_rx_data_array[k+2],2);
// M_csq[0]=uart_rx_data_array[k+2];
// M_csq[1]=uart_rx_data_array[k+3];
// M_csq[2]='\0';
if(M_csq[1]==',')M_csq[1]='\0';
if(atoi((char*)M_csq)>=16)
//  if(((uart_rx_data_array[k+2] == '1')&&(uart_rx_data_array[k+3] >= '6'))||(uart_rx_data_array[k+2] >= '2'))
 {
 i = 1;
 //UART1_SendLR();
 break;
 }
 }
}
     }
}


bool find(uint8_t *s)
{

if(strstr((char*)uart_rx_data_array,(char*)s)!=NULL)
return true;


else
return false;
}


void AT_CMD_Handler(uint8_t *p_atcmd,uint8_t *s,uint32_t wait_time)
{
int i = 0;
      bool pass = false;
      clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
      while(!pass)
      {
          if(!find(s))
          {
                clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
                send_at_cmd(p_atcmd);
                nrf_delay_ms(wait_time);
for(int k = 0;k < 50 ; k++){
if(uart_rx_data_array[k] == 'E' && uart_rx_data_array[k+1] == 'R' ){
goto error;
}
if(uart_rx_data_array[k] == 'e' && uart_rx_data_array[k+1] == 'r'){
goto error;
}
}
if(i > 20){
goto error;
}
          }
          else
          {
                pass = true;
          }

i++;
          
      }


if(!pass){
error:
m_uart_init();
print_log("error");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();
return ;
}
     // clear_rx_buffer();
}




void AT_CMD_Handler2(uint8_t *p_atcmd,uint8_t *s,uint32_t wait_time)
{

int i = 0;
      bool pass = false;
      clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
      while(!pass)
      {

          if(!find(s))
          {
                clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
                send_at_cmd(p_atcmd);
                nrf_delay_ms(wait_time);




//
// if(uart_rx_data_array[k] == 'E' && uart_rx_data_array[k+1] == 'R' ){
//
// goto error;
// }
//
if(uart_rx_data_array[16] == 'O' && uart_rx_data_array[17] == 'K' ){

return ;
}


if(i > 20){

goto error;

}

          }
          else
          {
                pass = true;
          }

i++;
          
      }


if(!pass){
error:
m_uart_init();
print_log("error");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();
return ;
}
     // clear_rx_buffer();
}




void AT_CMD_Handler1(uint8_t *p_atcmd,uint8_t *s,uint32_t wait_time)
{

int i = 0;
      bool pass = false;
      clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);


      while(!pass)
      {
          if(!find(s))
          {
                clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);
                send_at_cmd(p_atcmd);
                nrf_delay_ms(wait_time);


for(int k = 0;k < 50 ; k++){

if(uart_rx_data_array[k] == 'E' && uart_rx_data_array[k+1] == 'R' ){

goto error;
}

}

if(i > 20){

goto error;

}




          }
          else
          {
if(uart_rx_data_array[23] == '1'){

m_uart_init();
print_log("GNSS Link OK");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();

}else{

m_uart_init();
print_log("GNSS Link error");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();


}
if(uart_rx_data_array[25] == '1'){

m_uart_init();
print_log("Location OK");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();

}else{

m_uart_init();
print_log("Location error");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();


}


                pass = true;
          }

i++;
          
      }


if(!pass){
error:
m_uart_init();
print_log("error");
nrf_delay_ms(100);
print_log("\r\n");
m_gprs_init();
return ;
}
     // clear_rx_buffer();
}








void Get_LocalIP()
{
        //uint8_t i = 0;
        clear_rx_buffer(uart_rx_data_array,&m_uart_data_array_index);      
        send_at_cmd("AT+CIFSR\r\n");
        nrf_delay_ms(2000);  
}


//void connect_server(void)
//{  
AT_CMD_Handler("ATE1\r\n","OK",1000);

AT_CMD_Handler("AT+CIPSHUT\r\n","SHUT OK",1000);
AT_CMD_Handler("AT+CGATT=1\r\n","OK",1000);
// AT_CMD_Handler("AT+CGATT?\r\n","+CGATT: 1",1000);
// AT_CMD_Handler("AT+CSTT = \"CMNET\"\r\n","OK",2000);
// AT_CMD_Handler("AT+CIICR\r\n","OK",2000);
// Get_LocalIP();
//
// //AT_CMD_Handler("AT+CIPCSGP=1,\"CMNET\"","OK",2);
// AT_CMD_Handler("AT+CSTT\r\n","OK",2000);
// AT_CMD_Handler("AT+CIICR\r\n","OK",2000);
// //AT_CMD_Handler("AT+CGATT?\r\n","OK",2);
//    Get_LocalIP();
// AT_CMD_Handler("AT+CIPHEAD=1\r\n","OK",1000);
// AT_CMD_Handler(server,"CONNECT OK",4000);
// AT_CMD_Handler("AT+CIPSHUT\r\n","SHUT OK",1000);
AT_CMD_Handler("AT+CIPSEND\r\n",">",2000);
//}




void connect_server(void)
{  
AT_CMD_Handler("ATE1\r\n","OK",1000);

AT_CMD_Handler("AT+CIPSHUT\r\n","SHUT OK",1000);
AT_CMD_Handler("AT+CGATT=1\r\n","OK",1000);
AT_CMD_Handler("AT+CGATT?\r\n","+CGATT: 1",1000);
//AT_CMD_Handler("AT+CIPCSGP=1,\"CMNET\"","OK",2);
AT_CMD_Handler("AT+CSTT\r\n","OK",2000);
AT_CMD_Handler("AT+CIICR\r\n","OK",2000);
//AT_CMD_Handler("AT+CGATT?\r\n","OK",2);
    Get_LocalIP();
AT_CMD_Handler("AT+CIPHEAD=1\r\n","OK",1000);
AT_CMD_Handler(server,"CONNECT OK",4000);
memcpy(TCP_CONNECT,&uart_rx_data_array[45],15);
nrf_delay_ms(10);
AT_CMD_Handler("AT+CIPSHUT\r\n","SHUT OK",1000);
// AT_CMD_Handler("AT+CIPSEND\r\n",">",2000);
}






void GPS_server(void)
{  
// AT_CMD_Handler("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n","OK",1000);
// AT_CMD_Handler("AT+SAPBR=3,1,\"APN\",\"3GNET\"\r\n","OK",1000);
// AT_CMD_Handler("AT+SAPBR=1,1\r\n","OK",1000);
// AT_CMD_Handler("AT+SAPBR=2,1\r\n","OK",1000);
//
// AT_CMD_Handler("AT+CNTPCID=1\r\n","OK",1000);
// AT_CMD_Handler("AT+CNTP?\r\n","OK",1000);


// AT_CMD_Handler("AT+CNTP\r\n","OK",1000);
// AT_CMD_Handler("AT+CCLK?\r\n","OK",1000);
// AT_CMD_Handler("AT+CLBS=1,1\r\n","OK",1000);
//
// AT_CMD_Handler("AT+FTPSERV=\"116.247.119.165\"\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPUN=\"customer\"\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPPW=\"111111\"\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPGETNAME=\"MTK3.EPO\"\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPGETPATH=\"/\"\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPEXTGET=1\r\n","OK",1000);
// AT_CMD_Handler("AT+FTPEXTGET=4,\"epo\"\r\n","OK",3000);
// AT_CMD_Handler("AT+FSLS=C:\\User\\\r\n","OK",1000);
// AT_CMD_Handler("AT+CGNSCHK=3,1\r\n","OK",1000);
// AT_CMD_Handler("AT+CGNSPWR=1\r\n","OK",1000);
//
// AT_CMD_Handler("AT+CGNSAID=31,1,1\r\n","+CGNSAID: OK",1000);
// AT_CMD_Handler("AT+CGNSINF\r\n","1,1,20",2000);

AT_CMD_Handler2("AT+CGNSPWR=1\r\n","OK",1000);
AT_CMD_Handler1("AT+CGNSINF\r\n","+CGNSINF: 1,",1000);
}








void gprs_test()
{
uint32_t err_code;
GPRS_POWER_ON;
nrf_delay_ms(2000);

m_gprs_init();
nrf_delay_ms(1000);
// Wait_CREG();
get_IMEI();
m_uart_init();
nrf_delay_ms(100);
print_log("IMEI = ");
print_log(M_imei);
print_log("\r\n");
nrf_delay_ms(100);

m_gprs_init();
get_IMSI();
m_uart_init();
nrf_delay_ms(100);
print_log("IMSI = ");
print_log(M_imsi);
print_log("\r\n");
nrf_delay_ms(50);


m_gprs_init();
check_csq();
m_uart_init();
nrf_delay_ms(100);
print_log("CSQ = ");
print_log(M_csq);
print_log("\r\n");
nrf_delay_ms(100);

  m_gprs_init();
connect_server();
m_uart_init();
nrf_delay_ms(100);
print_log(TCP_CONNECT);
// print_log("\r\n");
nrf_delay_ms(100);

m_gprs_init();
nrf_delay_ms(1000);
GPS_server();
// gps_flag = true;

}




void uart_disable (void)
{
    NRF_UART0->ENABLE = (UART_ENABLE_ENABLE_Disabled << UART_ENABLE_ENABLE_Pos);
    NRF_UART0->TASKS_STOPTX = 1;
    NRF_UART0->TASKS_STOPRX = 1;
    NRF_UART0->POWER = 0;
}




static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
//    dm_ble_evt_handler(p_ble_evt);
    ble_hrs_on_ble_evt(&m_hrs, p_ble_evt);
    ble_bas_on_ble_evt(&bas, p_ble_evt);
    ble_conn_params_on_ble_evt(p_ble_evt);
//    on_ble_evt(p_ble_evt);
}


static void sys_evt_dispatch(uint32_t sys_evt)
{
    pstorage_sys_event_handler(sys_evt);
//    on_sys_evt(sys_evt);
}


static void ble_stack_init(void)
{
    uint32_t err_code;
    
    // Initialize the SoftDevice handler module.
    SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, false);


    // Enable BLE stack 
    ble_enable_params_t ble_enable_params;
    memset(&ble_enable_params, 0, sizeof(ble_enable_params));
    ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT;
    err_code = sd_ble_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);


    // Register with the SoftDevice handler module for BLE events.
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);
    
    // Register with the SoftDevice handler module for BLE events.
    err_code = softdevice_sys_evt_handler_set(sys_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}




static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);


    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *)DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);


    err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_HEART_RATE_SENSOR_HEART_RATE_BELT);
    APP_ERROR_CHECK(err_code);


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


    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;


    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}




static void advertising_init(void)
{
    uint32_t      err_code;
    ble_advdata_t advdata;
    uint8_t       flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;


    ble_uuid_t adv_uuids[] =
    {
        {BLE_UUID_HEART_RATE_SERVICE,         BLE_UUID_TYPE_BLE},
        {BLE_UUID_BATTERY_SERVICE,            BLE_UUID_TYPE_BLE},
        {BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
    };


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


    advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance      = true;
    advdata.flags.size              = sizeof(flags);
    advdata.flags.p_data            = &flags;
    advdata.uuids_complete.uuid_cnt = sizeof(adv_uuids) / sizeof(adv_uuids[0]);
    advdata.uuids_complete.p_uuids  = adv_uuids;


    err_code = ble_advdata_set(&advdata, NULL);
    APP_ERROR_CHECK(err_code);


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


    m_adv_params.type        = BLE_GAP_ADV_TYPE_ADV_IND;
    m_adv_params.p_peer_addr = NULL;                           // Undirected advertisement.
    m_adv_params.fp          = BLE_GAP_ADV_FP_ANY;
    m_adv_params.interval    = APP_ADV_INTERVAL;
    m_adv_params.timeout     = APP_ADV_TIMEOUT_IN_SECONDS;
}


static void services_init(void)
{
    uint32_t       err_code;
    ble_hrs_init_t hrs_init;
    ble_bas_init_t bas_init;
    ble_dis_init_t dis_init;
    uint8_t        body_sensor_location;


    // Initialize Heart Rate Service.
    body_sensor_location = BLE_HRS_BODY_SENSOR_LOCATION_FINGER;


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


    hrs_init.is_sensor_contact_supported = false;
    hrs_init.p_body_sensor_location      = &body_sensor_location;


    // Here the sec level for the Heart Rate Service can be changed/increased.
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&hrs_init.hrs_hrm_attr_md.cccd_write_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&hrs_init.hrs_hrm_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&hrs_init.hrs_hrm_attr_md.write_perm);


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&hrs_init.hrs_bsl_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&hrs_init.hrs_bsl_attr_md.write_perm);


    err_code = ble_hrs_init(&m_hrs, &hrs_init);
    APP_ERROR_CHECK(err_code);


    // Initialize Battery Service.
    memset(&bas_init, 0, sizeof(bas_init));


    // Here the sec level for the Battery Service can be changed/increased.
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&bas_init.battery_level_char_attr_md.cccd_write_perm);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&bas_init.battery_level_char_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&bas_init.battery_level_char_attr_md.write_perm);


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&bas_init.battery_level_report_read_perm);


    bas_init.evt_handler          = NULL;
    bas_init.support_notification = true;
    bas_init.p_report_ref         = NULL;
    bas_init.initial_batt_level   = 100;


    err_code = ble_bas_init(&bas, &bas_init);
    APP_ERROR_CHECK(err_code);


    // Initialize Device Information Service
    memset(&dis_init, 0, sizeof(dis_init));


    ble_srv_ascii_to_utf8(&dis_init.manufact_name_str, MANUFACTURER_NAME);


    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&dis_init.dis_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&dis_init.dis_attr_md.write_perm);


    err_code = ble_dis_init(&dis_init);
    APP_ERROR_CHECK(err_code);
}




static void advertising_start(void)
{
    uint32_t err_code;


    err_code = sd_ble_gap_adv_start(&m_adv_params);
    APP_ERROR_CHECK(err_code);


//    led_start();
}






int main(void)
{


ble_stack_init();
  gap_params_init();
  advertising_init();
  services_init();

advertising_start();


// nrf_gpio_cfg_output(27);
// nrf_gpio_cfg_input(28, NRF_GPIO_PIN_PULLDOWN);
// nrf_gpio_cfg_sense_input(28, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW );
//
// gprs_test();
//
// m_uart_init();
// print_log("\r\n");
// print_log("GPS test STOP!\r\n");
// nrf_delay_ms(100);
//
//
// GPRS_POWER_OFF;
// uart_disable();
//
// nrf_gpio_cfg_output(2);
nrf_gpio_pin_set(2);
nrf_gpio_pin_write(2, 1);
//
// nrf_gpio_pin_clear(23);
// nrf_gpio_pin_clear(24);
// nrf_gpio_pin_clear(4);
// nrf_gpio_pin_clear(5);
//
nrf_gpio_pin_clear(2);
//




// nrf_gpio_cfg_input(2,  NRF_GPIO_PIN_PULLUP );
//
// nrf_gpio_cfg_input(23, NRF_GPIO_PIN_PULLDOWN);
// nrf_gpio_cfg_input(24, NRF_GPIO_PIN_PULLDOWN);
// nrf_gpio_cfg_input(4, NRF_GPIO_PIN_PULLDOWN);
// nrf_gpio_cfg_input(5, NRF_GPIO_PIN_PULLDOWN);
//
// nrf_gpio_cfg_input(29, NRF_GPIO_PIN_PULLDOWN);
//
//
//
// NRF_POWER->RAMON = POWER_RAMON_ONRAM0_RAM0On << POWER_RAMON_ONRAM0_Pos


//| POWER_RAMON_ONRAM1_RAM1On << POWER_RAMON_ONRAM1_Pos


//| POWER_RAMON_OFFRAM0_RAM0Off << POWER_RAMON_OFFRAM0_Pos


//| POWER_RAMON_OFFRAM1_RAM1Off << POWER_RAMON_OFFRAM1_Pos;




//while(1){


//NRF_POWER->SYSTEMOFF = 1;




//}




while(1){


}



}


bool find(uint8_t *s)
{

if(strstr((char*)uart_rx_data_array,(char*)s)!=NULL)
return true;


else
return false;
}




/**
 *@}
 **/
nrf51822中文参考手册,nRF51822 是一款集成nRF51x系列无线收发器的超低功耗的片上系统 (Soc) , 包含一个32位ARM Cortex-M0 CPU , flash 存储器和模拟、数字外设。NORDIC SEMICONDUCTOR nRF51822 Product Specification v1.3 Liability disclaimer Nordic Semiconductor ASa reserves the right to make changes without further notice to the product to improve reliability, function or design. Nordic Semiconductor asa does not assume any liability arising out of the application or use of any product or circuits described herein ife support applications Nordic Semiconductor's products are not designed for use in life support appliances, devices, or systems where malfunction of these products can reasonably be expected to result in personal injury. Nordic Semiconductor ASa customers using or selling these products for use in such applications do so at their own risk and agree to fully indemnify Nordic Semiconductor ASA for any damages resulting from such improper use or sale Contact details Foryournearestdistributorpleasevisitwww.nordicsemi.com Information regarding product updates, downloads, and technical support can be accessed through your My Page account on our home page Main office: Otto Nielsens veg 12 Mailing address: Nordic Semiconductor 7052 Trondheim P.O. Box 2336 Norway 7004 Trondhe Phone:+4772898900 Norway 4772898989 画N远 NS-EN ISO 9001 CERTIFICATEDFIRM RoHS and reach statement Nordic semiconductor's products meet the requirements of Directive 2002/95/EC of the European Parliament and of the Council on the restriction of Hazardous Substances(roHS)and the requirements of the reach regulation(EC 1907/2006)on Registration, Evaluation, Authorization and Restriction of Chemicals. The SvHC(Substances of Very High Concern) candidate list is continually being updated Complete hazardous substance reports material composition reports and latest version of nordics reach statementcanbefoundonourwebsitewww.nordicsemicom Page 2 of 67 NORDIC SEMICONDUCTOR nRF51822 Product Specification v1.3 Datasheet status Status Description Objective Pro
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值