arduino 串口数据啊按字节分析

#include <avr/wdt.h>  
#include <SoftwareSerial.h>
#include <EEPROM.h>

#define FPIN 13
#define E2PROM_OFFSET 16


SoftwareSerial mySerial(10, 11); // RX, TX
unsigned long lastSendTime=0;
unsigned long lastReceiveTime=0;
unsigned long SafeKey=987654321UL; // Max 4,294,967,295
byte RecCache[512];
volatile int CacheIndex=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(FPIN,OUTPUT);
  digitalWrite(FPIN,LOW);
  
  Serial.begin(9600);
  delay(100);
  Serial.println("Ready!");

   //========Start==========

   //=========End=============
  unsigned long sk=123456789UL;
  if(_ReadSafeKey(sk)){
    SafeKey=sk;
  }

  //========Wifi Config=============
  initWifi();
  setCache(0,512);

}

void loop() {
  // put your main code here, to run repeatedly:
  handleTXR();
}

void  initWifi(){
  mySerial.begin(9600);
  delay(100);
    mySerial.println("AT+RST");
    delayAndRead(3000);
  
   mySerial.println("AT+CIPMUX=1");
   delayAndRead(500);
   mySerial.println("AT+CIPSERVER=1");
   delayAndRead(500); 
}

void handleTXR(){

  
  while(mySerial.available()){
    byte c=(byte) mySerial.read();
    RecCache[CacheIndex++]=c;

  }
   if(CacheIndex>512){
      CacheIndex=0;
      setCache(0,512); 
    }
    
  int bIndex=bIndexOf("$F",0);
  if(bIndex>=0){
    int eIndex=bIndexOf("$E",bIndex);
    if(eIndex>bIndex){
       //Extra Data
       int dataLen= eIndex - (bIndex +2);
       byte data[dataLen];
       for(int i=0;i<dataLen;i++){
         data[i]= RecCache[bIndex+2 +i] ;

       }

       for(int w=(eIndex +2);w<CacheIndex && w<512;w++){
          RecCache[w-(eIndex + 2)]=RecCache[w]; 
       }
       CacheIndex = CacheIndex - (eIndex +2);
       setCache(CacheIndex,512);
       
       lastReceiveTime=millis();
       handleCmd(data,dataLen);

    }
  }
  
    if(CacheIndex>512){
      CacheIndex=0;
      setCache(0,512); 
    }
  
}

void setCache(int start,int endIndex){
  for(int i=start;i<endIndex;i++){
     RecCache[i]=0;
  }  
}
boolean bStartsWith(byte data[],int len, String fStr){
    int fLen=fStr.length() ;
   byte fBytes[fLen + 1];
   fStr.getBytes(fBytes,fLen+1);

   if(len<=0)return false;
   if(len<fLen)return false;
   byte flag=1;
   for(int j=0;j<fLen;j++){
       if(fBytes[j]!=data[j])
       {
                flag=0;
                break; 
        }
              
    }
   if(flag) return true; 
  
   return false;
}

int bIndexOf(String fStr,int start){
    int fLen=fStr.length() ;
   byte fBytes[fLen + 1];
   fStr.getBytes(fBytes,fLen+1);

   for(int i=start;i<(CacheIndex + 1 -fLen);i++){
  
       if(RecCache[i]==fBytes[0])
       {
         byte flag=1;
          for(int j=1;j<fLen;j++){
              if(fBytes[j]!=RecCache[i+j])
              {
                flag=0;
                break; 
              }
          }
          if(flag)return i;
       }
   }
   return -1;
}

void handleCmd(byte data[], int len){

//    Serial.println("\n=============");
//  for(int i=0;i<len;i++){
//    Serial.print(data[i],DEC); 
//    Serial.print(",");
//  }
  
 if(bStartsWith(data,len,"HB:")){
     hbCmd();
 }else if(bStartsWith(data,len,"F:")){
  
    fireCmd(data,len);
 }else if(bStartsWith(data,len,"SetSK:")){
    setSKCmd(data,len);
 }else if(bStartsWith(data,len,"ClsSK:")){
    clsSKCmd(data,len);
 }
}

void hbCmd(){
    byte bs[4];
    unsigned long mlis=millis();
    long2byte(mlis,bs);
    byte msg[]={0,1,2,3,127,128,200,255,0,1,0};
    Serial.println(mlis);
    replyBytes(true,"HB",bs,4); 
}

void fireCmd(byte data[], int len){
   byte safeBytes[4]={0,0,0,0};

   for(int i=0;i<4;i++){
     safeBytes[i]=(byte)data[2+i];

   }
  unsigned long sk= bytes2long(safeBytes);
  byte duration=data[6];
  if(duration>15) duration=15;
  if(duration<=0)duration=1;
  
  if(sk!=SafeKey){
    reply(false,"F","Safe Key not match!");
    return;
  }
  reply(true,"F","");
  digitalWrite(FPIN,HIGH);
  delay(duration * 1000);
  digitalWrite(FPIN,LOW);
}

void setSKCmd(byte data[], int len){
   byte safeBytes[4]={0,0,0,0};
   for(int i=0;i<4;i++){
     safeBytes[i]=(byte)data[6+i];
     //Serial.println(safeBytes[i],DEC);
   }
  unsigned long sk= bytes2long(safeBytes);
  if(sk!=SafeKey){
    reply(false,"SetSK","Safe Key not match!");
    return;
  }
  
   byte newSafeBytes[4]={0,0,0,0};
   for(int i=0;i<4;i++){
     newSafeBytes[i]=(byte)data[10+i];

   }
  unsigned long newSK= bytes2long(newSafeBytes);
  _StorageSafeKey(newSafeBytes);
  SafeKey=newSK;
  
  reply(true,"SetSK","");
}

void clsSKCmd(byte data[],int len){
  if(bStartsWith(data,len,"ClsSK:pwdashitdingke")){
    _ClsSafeKey();
    reply(true,"ClsSK","");
    
  }else{
    reply(false,"ClsSK","-_!"); 
  }
}

void reply(bool isOk,String cmd,String msg){
 String rStr="";
 if(isOk){
  rStr="$FOK-" + cmd +":" +msg +"$E";
  mySerial.println("AT+CIPSEND=0," + (String)rStr.length());  
  delay(10);
  mySerial.println(rStr);
 }else{
    rStr="$FEE-" + cmd +":" +msg +"$E";
    mySerial.println("AT+CIPSEND=0," + (String)rStr.length());  
    delay(10);
    mySerial.println(rStr);
 } 
  
}

void replyBytes(bool isOk,String cmd,byte msg[],int msgLen){
 String rStr="";
 int  sendLen=0;
 if(isOk){
  rStr="$FOK-" + cmd +":" ;
    sendLen= rStr.length() + msgLen +2; //2 is "$E"
  mySerial.println("AT+CIPSEND=0," + (String)sendLen);  
  delay(10);
  mySerial.print(rStr);
  for(int i=0;i<msgLen;i++){
    mySerial.write(msg[i]);
  }
  mySerial.println("$E");
 }else{
  rStr="$FEE-" + cmd +":" ;
  sendLen= rStr.length() + msgLen +2; //2 is "$E"
  mySerial.println("AT+CIPSEND=0," + (String)sendLen);  
  delay(10);
  mySerial.print(rStr);
  for(int i=0;i<msgLen;i++){
    mySerial.write(msg[i]);
  }
  mySerial.println("$E");
 } 
  
}



void cls(){
   while(mySerial.available()){
     mySerial.read();
  }
}

void delayAndRead(int waitTime){
   delay(waitTime);
   while(mySerial.available()){
     Serial.write(mySerial.read()); 
   }
}

void _StorageSafeKey(byte skBytes[]){
    String flag="SK-OK";
    int i=0;
    for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + 5);address++){
     EEPROM.write(address,flag.charAt(i++));
     //Serial.print((char)EEPROM.read(address));
   }
   
   i=0;
   for(int address=(E2PROM_OFFSET + 5);address< (E2PROM_OFFSET + 5 +4);address++){
       EEPROM.write(address,skBytes[i++]);
   }
}

void _ClsSafeKey(){
    for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + 5);address++){
     EEPROM.write(address,(byte)0xFF);
     //Serial.print((char)EEPROM.read(address));
   }
}

boolean _ReadSafeKey(unsigned long &b){
    b=0;
    int address=0;
    String tmp="";
    char readChar=' ';
   for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + 5);address++){
     readChar=(char)EEPROM.read(address);
     tmp +=readChar;
  }
 
  if(tmp!="SK-OK"){
    return false;
  }
  
   byte skBytes[]={0,0,0,0};
   int i=0;
   for(int address=(E2PROM_OFFSET + 5);address< (E2PROM_OFFSET + 5 +4);address++){
     skBytes[i]=(byte)EEPROM.read(address);
  
     i++;
  }
  //Serial.println(tmp);
  b= bytes2long(skBytes);
  return true;
}

 void long2byte(unsigned long res,byte targets[] ) {  
        targets[0] = (byte) (res & 0xff);// 鏈�浣庝綅  
        targets[1] = (byte) ((res >> 8) & 0xff);// 娆′綆浣�  
        targets[2] = (byte) ((res >> 16) & 0xff);// 娆¢珮浣�  
        targets[3] = (byte) (res >> 24);// 鏈�楂樹綅,鏃犵鍙峰彸绉汇��  
              
    }  
    
unsigned long bytes2long(byte buf[]) {  
        unsigned long firstByte = 0;  
        unsigned long secondByte = 0;  
        unsigned long thirdByte = 0;  
        unsigned long fourthByte = 0;  
        int index = 0;  
        firstByte = (0x000000FFU & ( buf[index+3]));  
        secondByte = (0x000000FFU & ( buf[index + 2]));  
        thirdByte = (0x000000FFU & ( buf[index + 1]));  
        fourthByte = (0x000000FFU & ( buf[index ]));  
        index = index + 4;  
        return ((unsigned long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFUL;  
    }  
View Code

 

 

注意,unsigned int 跟int 最好只用一种,混合使用是有些莫名其妙的问题

你可能感兴趣的:(arduino 串口数据啊按字节分析)