rssi test for 915

Dependencies:   libmDot915 mbed-rtos mbed

Fork of rssi_test by wireless sensor

Revision:
16:847c028f4130
Parent:
15:04b37f329c84
Child:
17:b60549bc8626
--- a/main.cpp	Thu Aug 25 12:58:12 2016 +0000
+++ b/main.cpp	Thu Feb 16 14:43:17 2017 +0000
@@ -1,56 +1,108 @@
+#include "mbed.h"
+//#include "DataLoggerRS232.h"
 #include "mbed.h"
 #include "mDot.h"
 #include "MTSLog.h"
 #include <string>
 #include <vector>
 #include <algorithm>
+#include <math.h>
 
+#define RETURN_OK              0
+#define RETURN_ERR            -1
+//define baudrate
+#define PC_BAUDRATE            115200
+#define CARD_MACHINE_BAUDRATE  19200
 
-const char TURNON[]  = "ON";
-const char TURNOFF[] = "OFF";
+#define COMMAND_LENGTH         7
+#define RESPONSE_LENGTH        16
+#define RINGBUFFER_SIZE        100
+
+#define READ_PERIOD            1
+#define SEND_PERIOD            5
+
+const char readCmd[COMMAND_LENGTH] = {0x09,0x41,0x31,0x46,0x33,0x46,0x0d};
+
+char readBuf[RESPONSE_LENGTH] = {0};
+char ringBuffer[RINGBUFFER_SIZE][RESPONSE_LENGTH] = {0};
 
-bool cmpStr(char* str1, const char* str2, int len)
-{
-     int k;
-     for (k=0; k<len; k++){
-         if (str1[k] != str2[k]) return false;
-     }
-     return true;    
-}
+unsigned int inIndex  = 0;
+unsigned int outIndex = 0;
+
+/* functions prototype */
+void readCardID(void);
+void sendCardID(void);
+
+void my_strcpy(char *dst, char *src);
+void my_strclear(char *str, unsigned int len);
 
-DigitalOut Alarm(PB_0);
+int configNetwork(void);
+int joinNetwork(void);
+int send_data(char *str);
 
-//defined for mDot SVB debug, comment it if applying for whole system
-//#define NO_MULTITECH_GATEWAY
+/* Global variables */
+Serial pc       (USBTX, USBRX);  // tx, rx
+Serial cm_rs485 (PA_2,PA_3);     // tx, rx
 
-// these options must match the settings on your Conduit
-// uncomment the following lines and edit their values to match your configuration
+mDot* dot;
+
 static std::string config_network_name = "chinaiot";
 static std::string config_network_pass = "password";
 static uint8_t config_frequency_sub_band = 2; 
 
-int main() {
+int main() 
+{    
+    int32_t ret;
+
+    pc.baud(PC_BAUDRATE);
+    pc.printf("\n\r\n\r\n\r");
+    pc.printf("============================================\n\r");
+    pc.printf("SiFOX remote card read system!\n\r");
+    pc.printf("============================================\n\r");
+    pc.printf("PC COM RS232 baudrate: %d \n\r", PC_BAUDRATE);
+    cm_rs485.baud(CARD_MACHINE_BAUDRATE);
+    cm_rs485.format(9,SerialBase::Even,1);
+    pc.printf("Card Machine RS485 baudrate: %d!\n\r", CARD_MACHINE_BAUDRATE);
+
+    //*******************************************
+    // Configurate Network
+    //*******************************************
+    ret = configNetwork();
+    if(ret != RETURN_OK)         
+        dot->sleep(5, mDot::RTC_ALARM); //sleep a while and restart
+    
+    //*******************************************
+    // Join Network
+    //*******************************************
+    ret = joinNetwork();
+    if(ret != RETURN_OK)         
+        dot->sleep(5, mDot::RTC_ALARM); //sleep a while and restart
+   
+    pc.printf("Wait 15S or card machine booting...\n\r");
+    wait(15); 
+    
+    while(1) {
+        /* Read Card ID */
+        readCardID();
+        
+        /* Send Card ID to gateway */
+        sendCardID();
+        
+        /* wait a while */
+        wait(2);          
+    }
+}
+
+    
+int configNetwork(void)
+{
     int32_t ret; 
-    mDot* dot;
-    std::vector<uint8_t> sendData, recvData;
-    std::vector<uint8_t> sendData1,sendData2, sendData3, sendData4;
-    char recvBuf[11];
-    int send_failed;
-    int  i;
-    //bool alarm_on;
-    std::string data_str1 = "REQ1";
-    std::string data_str2 = "REQ2";
-    std::string data_str3 = "REQ3";
-    std::string data_str4 = "REQ4";
-    bool a1, a2, a3, a4;
+    
+    dot = mDot::getInstance();
     
- 
-    // get a mDot handle
-    dot = mDot::getInstance();
-
     // print library version information
-    logInfo("version: %s", dot->getId().c_str());
-
+    pc.printf("version: %s\n\r", dot->getId().c_str());
+    
     //*******************************************
     // configuration
     //*******************************************
@@ -65,214 +117,219 @@
     // frequency sub band is only applicable in the 915 (US) frequency band
     // if using a MultiTech Conduit gateway, use the same sub band as your Conduit (1-8) - the mDot will use the 8 channels in that sub band
     // if using a gateway that supports all 64 channels, use sub band 0 - the mDot will use all 64 channels
-    logInfo("setting frequency sub band");
+    pc.printf("Setting frequency sub band\n\r");
     if ((ret = dot->setFrequencySubBand(config_frequency_sub_band)) != mDot::MDOT_OK) {
-        logError("failed to set frequency sub band %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
+        pc.printf("Error:failed to set frequency sub band %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
     }
 
-    logInfo("setting network name");
+    pc.printf("Setting network name\n\r");
     if ((ret = dot->setNetworkName(config_network_name)) != mDot::MDOT_OK) {
-        logError("failed to set network name %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
+        pc.printf("Error:failed to set network name %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
     }
 
-    logInfo("setting network password");
+    pc.printf("Setting network password\n\r");
     if ((ret = dot->setNetworkPassphrase(config_network_pass)) != mDot::MDOT_OK) {
-        logError("failed to set network password %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
+        pc.printf("Error:failed to set network password %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
     }
-
+    
     // a higher spreading factor allows for longer range but lower throughput
     // in the 915 (US) frequency band, spreading factors 7 - 10 are available
     // in the 868 (EU) frequency band, spreading factors 7 - 12 are available
-    logInfo("setting TX spreading factor");
+    pc.printf("Setting TX spreading factor\n\r");
     if ((ret = dot->setTxDataRate(mDot::SF_10)) != mDot::MDOT_OK) {
-        logError("failed to set TX datarate %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
+        pc.printf("Error:failed to set TX datarate %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
     }
 
     // request receive confirmation of packets from the gateway
-    logInfo("enabling ACKs");
+    pc.printf("Enabling ACKs\n\r");
     if ((ret = dot->setAck(1)) != mDot::MDOT_OK) {
-        logError("failed to enable ACKs %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
+        pc.printf("Error:failed to enable ACKs %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_OK;
     }
 
     // save this configuration to the mDot's NVM
-    logInfo("saving config");
+    pc.printf("Saving config\n\r");
     if (! dot->saveConfig()) {
-        logError("failed to save configuration");
+        pc.printf("Error:failed to save configuration\n\r");
     }
-    //*******************************************
-    // end of configuration
-    //*******************************************
-
-    // attempt to join the network
-    logInfo("joining network");
-    while ((ret = dot->joinNetwork()) != mDot::MDOT_OK) {
-        logError("failed to join network %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
-        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
-        osDelay(std::max((uint32_t)1000, (uint32_t)dot->getNextTxMs()));
-    }
-   
-    // format data for sending to the gateway
-    for (std::string::iterator it = data_str1.begin(); it != data_str1.end(); it++)
-        sendData1.push_back((uint8_t) *it);
     
-    // format data for sending to the gateway
-    for (std::string::iterator it = data_str2.begin(); it != data_str2.end(); it++)
-        sendData2.push_back((uint8_t) *it);
-        
-    // format data for sending to the gateway
-    for (std::string::iterator it = data_str3.begin(); it != data_str3.end(); it++)
-        sendData3.push_back((uint8_t) *it);
+    return RETURN_OK;
+}   // end of configuration
 
-    // format data for sending to the gateway
-    for (std::string::iterator it = data_str4.begin(); it != data_str4.end(); it++)
-        sendData4.push_back((uint8_t) *it);
-        
-    send_failed = 0;              
-    while (true) {         
-            // send the data to the gateway
-            if ((ret = dot->send(sendData1)) != mDot::MDOT_OK) {
-               send_failed++; 
-               logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
-               osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            } else { 
-                send_failed=0;            
-                logInfo("successfully sent data to gateway");  
-                for(i=0;i<11;i++)recvBuf[i]=0; //clear recv buffer
-                recvData.clear(); //clear recv data
-                if ((ret = dot->recv(recvData)) != mDot::MDOT_OK) {
-                   logError("failed to recv: [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str());
-                } else {
-                   //logInfo("datasize = %d", recvData.size());
-                   for(i=0; i< recvData.size(); i++ )
-                     recvBuf[i] = recvData[i];
-                   //logInfo("RECV:%s", recvBuf);
-                   if(cmpStr(recvBuf, TURNON, 2)){
-                      a1 = true;
-                      logInfo("A1 is on!"); 
-                    } 
-                    if(cmpStr(recvBuf, TURNOFF, 3)){
-                      a1 = false;
-                      logInfo("A1 is off!"); 
-                    }    
-                } 
-            }
-            
-            osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
 
-            // send the data to the gateway
-            if ((ret = dot->send(sendData2)) != mDot::MDOT_OK) {
-               send_failed++; 
-               logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
-               osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            } else { 
-                send_failed=0;            
-                logInfo("successfully sent data to gateway");  
-                for(i=0;i<11;i++)recvBuf[i]=0; //clear recv buffer
-                recvData.clear(); //clear recv data
-                if ((ret = dot->recv(recvData)) != mDot::MDOT_OK) {
-                   logError("failed to recv: [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str());
-                } else {
-                   //logInfo("datasize = %d", recvData.size());
-                   for(i=0; i< recvData.size(); i++ )
-                     recvBuf[i] = recvData[i];
-                   //logInfo("RECV:%s", recvBuf);
-                   if(cmpStr(recvBuf, TURNON, 2)){
-                      a2 = true;
-                      logInfo("A2 is on!"); 
-                    } 
-                    if(cmpStr(recvBuf, TURNOFF, 3)){
-                      a2 = false;
-                      logInfo("A2 is off!"); 
-                    }    
-                } 
-            }
-            
-            osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-
-            // send the data to the gateway
-            if ((ret = dot->send(sendData3)) != mDot::MDOT_OK) {
-               send_failed++; 
-               logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
-               osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            } else { 
-                send_failed=0;            
-                logInfo("successfully sent data to gateway");  
-                for(i=0;i<11;i++)recvBuf[i]=0; //clear recv buffer
-                recvData.clear(); //clear recv data
-                if ((ret = dot->recv(recvData)) != mDot::MDOT_OK) {
-                   logError("failed to recv: [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str());
-                } else {
-                   //logInfo("datasize = %d", recvData.size());
-                   for(i=0; i< recvData.size(); i++ )
-                     recvBuf[i] = recvData[i];
-                   //logInfo("RECV:%s", recvBuf);
-                   if(cmpStr(recvBuf, TURNON, 2)){
-                      a3 = true;
-                      logInfo("A3 is on!"); 
-                    } 
-                    if(cmpStr(recvBuf, TURNOFF, 3)){
-                      a3 = false;
-                      logInfo("A3 is off!"); 
-                    }    
-                } 
-            }
-            
-            osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            
-            // send the data to the gateway
-            if ((ret = dot->send(sendData4)) != mDot::MDOT_OK) {
-               send_failed++; 
-               logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
-               osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            } else { 
-                send_failed=0;            
-                logInfo("successfully sent data to gateway");  
-                for(i=0;i<11;i++)recvBuf[i]=0; //clear recv buffer
-                recvData.clear(); //clear recv data
-                if ((ret = dot->recv(recvData)) != mDot::MDOT_OK) {
-                   logError("failed to recv: [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str());
-                } else {
-                   //logInfo("datasize = %d", recvData.size());
-                   for(i=0; i< recvData.size(); i++ )
-                     recvBuf[i] = recvData[i];
-                   //logInfo("RECV:%s", recvBuf);
-                   if(cmpStr(recvBuf, TURNON, 2)){
-                      a4 = true;
-                      logInfo("A4 is on!"); 
-                    } 
-                    if(cmpStr(recvBuf, TURNOFF, 3)){
-                      a4 = false;
-                      logInfo("A4 is off!"); 
-                    }    
-                } 
-            }
-            osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-            
-            if(a1 || a2 || a3 || a4){
-                logInfo("============================");
-                logInfo("Alarm is ON");
-                Alarm = 1;
-            }else{
-                logInfo("============================");
-                logInfo("Alarm is OFF");
-                Alarm = 0;
-            }
-            
-            osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-                         
-        
-        if(send_failed>=3){
-           send_failed=0;           
-           // attempt to rejoin the network
-           logInfo("Attemp to rejoin network....");
-           if ((ret = dot->joinNetworkOnce()) != mDot::MDOT_OK) {
-                logError("Failed to rejoin network!"); // %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
-           }else{
-                logInfo("Rejoin network successfully!");   
-           } 
-           osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
-        }
-        
+int joinNetwork(void)
+{    
+    int32_t ret,i; 
+    std::vector<uint8_t> sendData;
+    char _header[] = "ChongQi!";
+    
+    // attempt to join the network
+    pc.printf("Joining network...\n\r");
+    
+    while ((ret = dot->joinNetwork()) != mDot::MDOT_OK) {
+        pc.printf("Error: failed to join network %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
+        return RETURN_ERR;
     }
 
+    sendData.clear(); 
+    // format data for sending to the gateway
+    for( i=0; i< strlen(_header); i++ )
+               sendData.push_back( _header[i] );
+               
+    // send the data to the gateway
+    pc.printf("Send header to the gateway\n\r");
+
+    if ((ret = dot->send(sendData)) != mDot::MDOT_OK) {
+        pc.printf("Error: failed to send %d:%s\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
+    } else {
+        pc.printf("Successfully sent data to gateway\n\r");
+    } 
+    
+    return RETURN_OK;
 }
+
+int send_data(char *str)
+{
+    int32_t i, ret;
+    std::vector<uint8_t> sendData;
+    
+    //Send the data to Gateway
+    sendData.clear();   
+    // probably not the most efficent way to do this
+    for(i=0; i< strlen(str); i++ )
+        sendData.push_back(str[i] );
+        
+    // send the data to the gateway
+    pc.printf("Send %s to Gateway \n\r", str); 
+    
+    if ((ret = dot->send(sendData)) != mDot::MDOT_OK) {
+        pc.printf("Error:failed to send\n\r", ret, mDot::getReturnCodeString(ret).c_str());
+        return RETURN_ERR;
+    } else {            
+        pc.printf("Sent data to gateway successfully!\n\r");
+    }
+    return RETURN_OK;
+}
+
+
+void my_strcpy(char *dst, char *src)
+{
+    int j=0;
+    
+    while(src[j] != 0)
+    {
+        dst[j] = src[j];
+        j++;
+    }       
+}
+
+
+void my_strclear(char *str, unsigned int len)
+{
+    unsigned int j;
+    for(j=0; j<len; j++)str[j]=0;  
+}
+
+
+void readCardID(void)
+{
+      unsigned int i;
+      char chr;
+      
+      //pc.printf("Read Tick!\n\r");
+      
+      /* clear the read buffer */
+      my_strclear(readBuf, RESPONSE_LENGTH);
+        
+      pc.printf("Send the READ command!\n\r");//, &readCmd[1]);
+      if(cm_rs485.writeable()){
+            for(i=0; i<COMMAND_LENGTH; i++){
+               cm_rs485.putc(readCmd[i]);
+            }            
+      }
+      
+      /* read the response */
+      chr = cm_rs485.getc();
+      i = 0;
+      while(chr != 0x0d)
+      {
+            readBuf[i] = chr;
+            i++;
+            chr = cm_rs485.getc();
+      }  
+        
+      /* print the response for debug */
+      pc.printf("Response[ASCII]:");
+        
+      for(i=0; i< RESPONSE_LENGTH; i++){
+           pc.printf("%0X ", readBuf[i]);
+           if (readBuf[i] == 0) break;
+      } 
+      pc.printf("Response[Text]:%s\n\r", &readBuf[3]);
+      
+      /* add to ringBuffer if valid */
+    if((readBuf[3] != 0) && (readBuf[4] != 0)){ 
+      if((readBuf[3]!= '3') && (readBuf[4] !='C')) //valid response
+      {
+          my_strcpy(ringBuffer[inIndex], &readBuf[3]); //strim the 3 bytes prehead
+          //pc.printf("addr = 0x%0X, inIndex = %d\n\r", &ringBuffer[inIndex],inIndex);
+          inIndex++;
+          if(inIndex >= RINGBUFFER_SIZE) inIndex = 0;
+          if(ringBuffer[inIndex][0] != 0)  //is not empty
+          {
+              pc.printf("Warning! Ringbuffer overflow at [%d]!\n\r", inIndex);
+              pc.printf("Please have a check of the network!\n\r");
+              pc.printf("Data in ring buffer:\n\r");
+              for(i=0; i<RINGBUFFER_SIZE; i++)
+              {
+                  pc.printf("Data[%d]: %s \n\r", i, ringBuffer[i]);
+              }
+              
+              wait(10); //in seconds
+          }
+      }
+    }
+}
+
+void sendCardID(void)
+{
+    int32_t ret;
+    
+    //pc.printf("Send Tick!\n\r");
+    /*send the data */
+    if(ringBuffer[outIndex][0] != 0) //not empty
+    {
+        pc.printf("Send dada[%s] to Gateway!\n\r", ringBuffer[outIndex]);
+      #ifndef NO_MULTITECH_GATEWAY  
+        /* t.b.d : send data though LoRA */
+        if(send_data(ringBuffer[outIndex]) != RETURN_OK)
+        {
+           pc.printf("Failed to send data to netwotk!\n\r");
+           pc.printf("Rejoin network and try one more time!\n\r");
+                       // attempt to rejoin the network
+           pc.printf("Attemp to rejoin network....\n\r");
+           if ((ret = dot->joinNetworkOnce()) != mDot::MDOT_OK) {
+                pc.printf("Failed to rejoin network! %d:%s \n\r", ret, mDot::getReturnCodeString(ret).c_str());
+                return;
+           }else{
+                pc.printf("Rejoin network successfully!");
+                if(send_data(ringBuffer[outIndex]) != RETURN_OK) return;  //abort to send       
+           } 
+        }
+       #endif 
+        //clear the buffer
+        my_strclear(ringBuffer[outIndex], RESPONSE_LENGTH);
+        outIndex++;
+        if(outIndex >= RINGBUFFER_SIZE)outIndex = 0;
+    }else{ //empty
+        pc.printf("Nothing to send!\n\r");
+        //wait(10);
+    }
+    
+}
\ No newline at end of file