JunMo Hong / Mbed 2 deprecated cubebite_rnd_SPSGRFC433

Dependencies:   mbed

Fork of HelloWorld_IDS01A4 by ST

main.cpp

Committer:
jmhong
Date:
2018-01-17
Revision:
13:d802c6ed2e75
Parent:
12:5e20115bd13b
Child:
14:1a6faeda6579

File content as of revision 13:d802c6ed2e75:

/**
 ******************************************************************************
 * @file    main.cpp
 * @author  JMHong, Cubebite
 * @version V1.0.0
 * @date    June 19th, 2018
 * @brief   mbed test application for the STMicroelectronics X-NUCLEO-IDB01A4/5
 *          Spirit1 Module(SPSGRFC-433)
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; COPYRIGHT(c) 2018 Cubebite</center></h2>
 *
 ******************************************************************************
 */

//*************************************************************************************
//Include
//*************************************************************************************
#include "mbed.h"
#include "SimpleSpirit1.h"

#include <fstream>  // library that contains file input/output functions
//*************************************************************************************


//*************************************************************************************
//Define : Debug
//*************************************************************************************
/* 180108 cubebite HJM : SimpleSpirit1 Debug define */
#define NDEBUG
#define HEAVY_DEBUG


/* 180108 cubebite HJM : cubebite Debug define */
//#define CUBEBITE_DEBUG
//*************************************************************************************


//*************************************************************************************
//Define : Test, Compile 
//*************************************************************************************
/* 180108 cubebite HJM : cubebite Testing define, 1개씩만 켜야 함. */
//#define CUBEBITE_RF_USER_BUTTON_SEND_TEST
//#define CUBEBITE_RF_DEVICE_PARTNUMBER_TEST
//#define CUBEBITE_RF_GPIO_0_TEST
#define CUBEBITE_RF_SPEED_TEST_SEND_ON
//#define CUBEBITE_RF_SPEED_TEST_RECV_ON


/* 180109 cubebite HJM : cubebite Compile define, 1개씩만 켜야 함. */
//#define CUBEBITE_BOARD_F746ZG
#define CUBEBITE_BOARD_F401RE
//*************************************************************************************


//*************************************************************************************
//Global variable : Create an instance by board
//*************************************************************************************
/* 180108 cubebite HJM : orignal code, backup */          
//static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance(D11, D12, D3, D9, D10, D2); /* (SPI_CLK) = (D13:PA5:resistorR7 --> D3:PB3:resistorR4)*/

#ifdef  CUBEBITE_BOARD_F401RE
/* 180108 cubebite HJM : F401re borad, AnalogIn PIN Info, A0(PA_0) A1(PA_1) A2(PA_4) A3(PB_0) A4(PC_1) A5(PC_0) */
/* RF Module 과 상관 관계 => A0(PA_0)[SPI GPIO 3] A1(PA_1)[CSN] A2(PA_4)[SPI1 GPIO 2] A3(PB_0)[SPI1 GPIO 1] A4(PC_1)[SPI1_GPIO 0] */
/* 180108 cubebite HJM : F401re borad Init code */
//static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance(PA_7, PA_6, PA_5, PC_7, PB_6, PA_10);    //F401re borad
static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance(PA_7, PA_6, PA_5, PA_0, PB_6, PA_10);    //F401re borad, IRQ Testing, GPIO 3 -> IRQ
//static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance2(PA_7, PA_6, PA_5, PA_0, PB_6, PA_10);    //F401re borad, IRQ Testing, GPIO 3 -> IRQ
#endif



#ifdef  CUBEBITE_BOARD_F746ZG
/* 180108 cubebite HJM : F746zg borad, AnalogIn PIN Info, A0(PA_3) A1(PC_0) A2(PC_3) A3(PF_3) A4(PF_5) A5(PF_10)  */
/* RF Module 과 상관 관계 => A0(PA_3)[SPI GPIO 3] A1(PC_0)[CSN] A2(PC_3)[SPI1 GPIO 2] A3(PF_3)[SPI1 GPIO 1] A4(PF_5)[SPI1_GPIO 0] */
/* 180108 cubebite HJM : F746zg borad Init code */
//static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance(PB_5, PB_4, PB_3, PD_14, PD_5, PD_6);    //F746zg borad
static SimpleSpirit1 &myspirit = SimpleSpirit1::CreateInstance(PB_5, PB_4, PB_3, PA_3, PD_5, PD_6);    //F746zg borad, IRQ Testing, GPIO 3 -> IRQ
//static SimpleSpirit1 &myspirit2 = SimpleSpirit1::CreateInstance2(PB_5, PB_4, PB_3, PA_3, PD_5, PD_6);    //F746zg borad, IRQ Testing, GPIO 3 -> IRQ
#endif
//*************************************************************************************


//*************************************************************************************
//Global variable : LEDs and user buttons by board
//*************************************************************************************
#ifdef  CUBEBITE_BOARD_F401RE
//180116 HJM : 그 전날 뻗어서 혹시 이쪽 LED 병렬회선을 사용하다가 오류가 났을 수도 있을 것 같다는 의심을 하게 됨. 주석처리하고 다시 테스트 하기로 함.
//static DigitalOut TestLED(D5);         /* LED of IDS01A4/5 */
#endif

#ifdef  CUBEBITE_BOARD_F746ZG
static DigitalOut TestLED(PB_0);         /* LED of IDS01A4/5 */
#endif

#ifdef  CUBEBITE_RF_USER_BUTTON_SEND_TEST
static InterruptIn event(USER_BUTTON); /* Interrupt event to give userinterface to send pkt. */
#endif
//*************************************************************************************


//*************************************************************************************
//Global variable : Rf Send, read Buffer
//*************************************************************************************
/* 180108 cubebite HJM : send testing, orignal code  */
#define TEST_STR_LEN (32)
static uint8_t send_buf[TEST_STR_LEN] ={'S','P','I','R','I','T','1',' ','H','E','L','L','O',' ','W','O','R','L','D',' ','P','2','P',' ','D','E','M','O'};
static uint8_t read_buf[TEST_STR_LEN] ={'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
//*************************************************************************************


//*************************************************************************************
//Global variable : tx, rx Flag
//*************************************************************************************
static volatile bool rx_done_flag = false; 
static volatile bool tx_done_flag = false; 
static volatile bool send_data_flag = false;
//*************************************************************************************


//*************************************************************************************
//Global variable : Testing
//*************************************************************************************
/* Test : GPIO 0 */
#ifdef  CUBEBITE_RF_GPIO_0_TEST
    #ifdef  CUBEBITE_BOARD_F401RE
/* 180108 cubebite HJM : F401re borad, PC_1 == RF_MODULE_GPIO 0, Testing code */
static DigitalIn RF_GPIO_0_INPUT(PC_1);   //F401re borad
//static DigitalIn RF_GPIO_3_INPUT(PA_0);   //F401re borad, 사용시, send 정상 동작 안함, Spirit1 IRQ 핀이랑 같이 물려있기 때문
    #endif
#endif

#ifdef  CUBEBITE_RF_GPIO_0_TEST
    #ifdef  CUBEBITE_BOARD_F746ZG
/* 180108 cubebite HJM : F746zg borad, PC_1 == RF_MODULE_GPIO 0, Testing code */
static DigitalIn RF_GPIO_0_INPUT(PF_5); //F746zg borad
//static DigitalIn RF_GPIO_3_INPUT(PA_3); //F746zg borad, 사용시, send 정상 동작 안함, Spirit1 IRQ 핀이랑 같이 물려있기 때문
    #endif
#endif


/* Test : RF Speed Test */
#ifdef  CUBEBITE_RF_SPEED_TEST_SEND_ON
static clock_t clockRfSpeedTestStart, clockRfSpeedTestEnd;
static float fRfSpeedTestResultTime;

static bool bIsSendFirstClockFunctionStarted = false;
static bool bIsSetSendFlag = false;

#endif

#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON
#define TEST_ACK_STR_LEN (6)
static uint8_t send_ack_buf[TEST_ACK_STR_LEN] ={'O','K'};
size_t curr_ack_len = strlen((const char*)send_ack_buf) + 1;

static bool bIsAckSended = false;
#endif
//*************************************************************************************
















/**
 * @brief  callback_func
 * @param  callback event
 * @retval None.
 */
static void callback_func(int event) 
{
#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] callback_func(int event) \n");
#endif
  
  
  
    if(event == SimpleSpirit1::RX_DONE) 
    {         
        rx_done_flag = 1;
    }
    else if (event == SimpleSpirit1::TX_DONE) 
    {  
        tx_done_flag = 1;
    }
}




/**
 * @brief  set_send_data_flag
 * @param  None
 * @retval None
 */
static void set_send_data_flag(void)
{  
    send_data_flag = 1 ;
}


static void set_ack_send_data_flag(void)
{  
#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON
    bIsAckSended = 1;
#endif
}




/**
 * @brief  send_data
 * @param  None
 * @retval None
 */
static void send_data(void)
{
#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] send_data() 호출 됨.\n");
    printf("[CUBEBITE] myspirit, is_receiving()\t......");
#endif
    while(myspirit.is_receiving()); /* wait for ongoing RX ends 180110 HJM 아마 이 전에 보내던 거 마저 다 보내려고 하는 거 같다. */
#ifdef  CUBEBITE_DEBUG
    printf("OK\n");
#endif


    size_t curr_len = strlen((const char*)send_buf) + 1;
    int iRet = 0;


#ifdef  CUBEBITE_DEBUG  
    printf("[CUBEBITE] myspirit, send()\t......");
#endif
    iRet = myspirit.send(send_buf, curr_len);
    if (iRet == RADIO_TX_OK)
    {
#ifdef  CUBEBITE_DEBUG        
        printf("[RADIO_TX_OK]\n");
#endif

#ifdef  CUBEBITE_RF_SPEED_TEST_SEND_ON 
    #ifdef CUBEBITE_BOARD_F401RE
        if (false == bIsSendFirstClockFunctionStarted)
        {
            clockRfSpeedTestStart = clock();    
            bIsSendFirstClockFunctionStarted = true;
        }
    #endif
#endif
    }
    else if (iRet == RADIO_TX_ERR)
    {
#ifdef  CUBEBITE_DEBUG
        printf("[RADIO_TX_ERR]\n");
#endif
    }
    else if (iRet == RADIO_TX_COLLISION)
    {
#ifdef  CUBEBITE_DEBUG
        printf("[RADIO_TX_COLLISION]\n");
#endif
    }
    else if (iRet == RADIO_TX_NOACK)
    {
#ifdef  CUBEBITE_DEBUG
        printf("[RADIO_TX_NOACK]\n");
#endif
    }
    
#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] send_data() 호출 끝.\n");
#endif
}










/**
 * @brief  read_rcvd_data
 * @param  None
 * @retval None
 */
static void read_rcvd_data(void)
{  
#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] read_rcvd_data() 호출 됨. \n");  
#endif
 
    for(unsigned int flush_count = 0; flush_count < TEST_STR_LEN; flush_count++) read_buf[flush_count] = 0 ;/* clear the read buffer */

    int ret = myspirit.read(read_buf, sizeof(read_buf));
    if (ret == 0) 
    {
        printf("[CUBEBITE] Read() Error : Nothing to read\n");
        return;
    }
#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON
    ret = strcmp((const char *)read_buf, (const char *)send_buf);
    if (0 == ret)
    {        
        set_ack_send_data_flag();
//        printf("read, send buf collect!!\n");
        TestLED = !TestLED;     /* Toggle LED at the receiver */
//        bIsAckSended = true;
        
        //746zg 보드
        /*
        int iRet = myspirit.send(send_ack_buf, curr_ack_len);
        if (iRet == RADIO_TX_OK)
        {
        #ifdef  CUBEBITE_DEBUG
            printf("ACK : [RADIO_TX_OK]\n");
        #endif
        }
        else if (iRet == RADIO_TX_ERR)
        {
        #ifdef  CUBEBITE_DEBUG            
            printf("ACK : [RADIO_TX_ERR]\n");
        #endif
        }
        else if (iRet == RADIO_TX_COLLISION)
        {
        #ifdef  CUBEBITE_DEBUG            
            printf("ACK : [RADIO_TX_COLLISION]\n");
        #endif            
        }
        else if (iRet == RADIO_TX_NOACK)
        {
        #ifdef  CUBEBITE_DEBUG            
            printf("ACK : [RADIO_TX_NOACK]\n");
        #endif
        }    
        */              
    }
#endif

#ifdef  CUBEBITE_RF_SPEED_TEST_SEND_ON 
    //401re 보드
    if (true == bIsSendFirstClockFunctionStarted)
    {
        clockRfSpeedTestEnd = clock();
    } 
//    printf("[DEBUG]recv -> %s\n", read_buf);
#endif    


#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] read_rcvd_data() 호출 끝. \n");  
#endif
}

static void ack_send_data(void)
{  
#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON
    //746zg 보드
    int iRet = myspirit.send(send_ack_buf, curr_ack_len);
    if (iRet == RADIO_TX_OK)
    {
    #ifdef  CUBEBITE_DEBUG
        printf("ACK : [RADIO_TX_OK]\n");
    #endif
    }
    else if (iRet == RADIO_TX_ERR)
    {
    #ifdef  CUBEBITE_DEBUG            
        printf("ACK : [RADIO_TX_ERR]\n");
    #endif
    }
    else if (iRet == RADIO_TX_COLLISION)
    {
    #ifdef  CUBEBITE_DEBUG            
        printf("ACK : [RADIO_TX_COLLISION]\n");
    #endif            
    }
    else if (iRet == RADIO_TX_NOACK)
    {
    #ifdef  CUBEBITE_DEBUG            
        printf("ACK : [RADIO_TX_NOACK]\n");
    #endif
    }    
#endif
}



/**
 * @brief  main routine
 * @param  None
 * @retval int
 */
int main() 
{  
#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON
    /* LED off */
    TestLED = 0;                
#endif  
    /* 180108 cubebite HJM : function return value print */
    int iRet = 0;

#ifdef  CUBEBITE_RF_GPIO_0_TEST
    /* 180108 cubebite HJM : GPIO 0, init code */
    SGpioInit gpioIRQ={
        SPIRIT_GPIO_0,
        SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_LP,
        SPIRIT_GPIO_DIG_OUT_IRQ
    };
    SpiritGpioInit(&gpioIRQ);
    
    /* 180108 cubebite HJM : GPIO 0, For spiritFunctionalState(), Testing code */
    SpiritFunctionalState spiritFunctionalState={
          S_DISABLE
    };
#endif    
    
    /* 180108 cubebite HJM : spirit module, init code  */
    printf("[CUBEBITE] myspirit, attach_irq_callback()\t......");
    myspirit.attach_irq_callback(callback_func);
    printf("OK\n");    
      
    printf("[CUBEBITE] myspirit, on()\t......");
    iRet = myspirit.on();
    if ( 0 == iRet )
    {
        printf("OK\n");    
    }
    else
    {
        printf("ERROR\n");
    }
#ifdef  CUBEBITE_DEBUG
    printf("[CUBEBITE] CUBEBITE_DEBUG ON. \n");
#endif

      
#ifdef  CUBEBITE_RF_USER_BUTTON_SEND_TEST
    event.rise(&set_send_data_flag); /*User button interrupt trigger to set send data flag */
#endif


#ifdef  CUBEBITE_RF_DEVICE_PARTNUMBER_TEST  
  uint16_t int16SpiritPartNum = 0;
#endif
    while(1) 
    {
#ifdef  CUBEBITE_RF_DEVICE_PARTNUMBER_TEST
        printf("[CUBEBITE][devicePartNumber] SpiritGeneralGetDevicePartNumber()\t......");
    
        int16SpiritPartNum = SpiritGeneralGetDevicePartNumber();
        printf("OK => ");
        printf("int16SpiritPartNum value : [0x%04X]\n", int16SpiritPartNum);
        int16SpiritPartNum = 0;
#endif    




        /* low power in idle condition., waiting for an event */
        __WFE(); 
    
    
    
    
    
#ifdef  CUBEBITE_RF_GPIO_0_TEST    
        //180108 HJM : For spiritFunctionalState(), testing code
        
        if (S_ENABLE == spiritFunctionalState)
        {
            spiritFunctionalState = S_DISABLE;    
        }
        else
        {
            spiritFunctionalState = S_ENABLE;    
        }
        
        /* 180108 cubebite HJM : GPIO 0, For, spiritFunctionalState() => Enables or Disables the output of temperature sensor on SPIRIT GPIO_0. */
        SpiritGpioTemperatureSensor(spiritFunctionalState);
        
        /* 180108 cubebite HJM : RF_GPIO_0_INPUT pin value print */
        printf("****** RF GPIO_0 Status Testing => [%d] ******\n", (int)RF_GPIO_0_INPUT);
        wait(1);
#endif
    
#ifdef  CUBEBITE_RF_SPEED_TEST_SEND_ON 
    //180112 HJM : Ack 응답 올 때 까지의 Timeout.
//            wait(0.5);  //100ms, 정상 동작, .       ( 테스트)
            wait(0.1);  //100ms, 정상 동작, 송신 쪽 오류 O.       (1일 테스트)
//            wait(0.08);  //100ms, 정상 동작, 오류 X.    (5분 테스트)
//            wait(0.07);  //70ms, 
//            wait(0.06); //60ms, 정상 동작, 송신 쪽 오류 O, (1시간 테스트)
//            wait(0.05);  // 50ms, 정상 동작, 오류 X.   (13분 테스트)
//            wait(0.03);  // 30ms, 정상 동작, ??? 오류 O.      (1시간 테스트)
//            wait(0.02);  // 20ms, 정상 동작, 수신 쪽 오류 O.   (2분 테스트)
//            wait(0.01);  // 10ms, 정상 동작, 수신 쪽 오류 O.   (1분 테스트)
//            wait(0.008);    // 8ms, 정상 동작, 하지만 0.01 이 최대 속도값으로 보임.
//            wait(0.005);  // 5ms, 정상 동작, 하지만 0.01 이 최대 속도값으로 보임, 하지만 Nothing to read 오류가 많이 뜸.    (20분 테스트)
//            wait(0.00001);  // 0.01ms, 비 정상 동작.   (30분 테스트)
            set_send_data_flag();    
#endif
    
        if(rx_done_flag) 
        {
            rx_done_flag = false; 
            read_rcvd_data();
//            printf("recvedd.\n");            
#ifdef  CUBEBITE_RF_SPEED_TEST_SEND_ON                
            if (true == bIsSendFirstClockFunctionStarted)
            {
                fRfSpeedTestResultTime = (float)(clockRfSpeedTestEnd - clockRfSpeedTestStart)/CLOCKS_PER_SEC;
                //180115 HJM : .csv 형식으로 출력하여 데이터를 도식화 하기위해 log 수정,
                //((putty출력中)시,분,초,)송신위치,수신위치,대략거리(m),송신딜레이(sec),송신데이터양(byte),속도(sec)
//                printf("Clock Rf Speed Test : [%.9f(sec)] \n", fRfSpeedTestResultTime);
//                printf(",hjm(keyboard-right),hjm(keyboard-left),1,0.1,28,%.9f\n", fRfSpeedTestResultTime);    //1차, 2시간 테스트
                printf(",hjm(keyboard-left),mars(tv-desk),10,0.1,28,%.9f\n", fRfSpeedTestResultTime);                                                    //2차
                
                
                bIsSendFirstClockFunctionStarted = false;                
            }
#endif
        }
        
        else if (send_data_flag)
        { 

            send_data_flag = false;
            send_data();
//            printf("sended.\n");

        }
    
        else if (tx_done_flag)
        {
          tx_done_flag = false;
    //      printf("\n***Packet sent ***\nSent string ='%s' (len=%d)\n", send_buf, strlen((const char*)send_buf) + 1);      
        }
    
#ifdef  CUBEBITE_RF_SPEED_TEST_RECV_ON 
//180112 HJM 오후 1시, 현재 사용 안하는 중, recv 쪽에서 strcmp로 보낸 데이터와 받은 데이터 비교 후, send 를 바로 하는 코드로 바꿨음.
//180116 HJM 오전 9시, 그 전날도 뻗고, OK 신호를 제대로 받지를 않아서 recv 쪽 ok send 보내는 쪽을 의심, 다시 바꾸기로함.
        else if (true == bIsAckSended)
        {
            bIsAckSended = false;
            ack_send_data();
//            printf("recv sended.\n"); 
        }
#endif
    }
  /* unreachable */
  // myspirit.off();
  // return 0;
}