遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

arduino 与 android 通过TCP进行字节收发

arduino

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


#define FPIN 13

SoftwareSerial mySerial(10, 11); // RX, TX
unsigned long lastSendTime=0;
unsigned long lastReceiveTime=0;
unsigned long SafeKey=987654321UL; // Max 4,294,967,295
String RecCache="";

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



  //========Wifi Config=============
  initWifi();
 

}

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(){
    //handle user input cmd
  while (Serial.available()){
    mySerial.write(Serial.read()); 
  }
  
  while(mySerial.available()){
    char c= mySerial.read();
    RecCache=RecCache +(String)c;
  }
  
    int bIndex= RecCache.indexOf("$F");
  if(bIndex>=0){
    int eIndex=RecCache.indexOf("$E",bIndex);
    if(eIndex>=0){
       //Extra Data
       String data=RecCache.substring(bIndex+2,eIndex);
       RecCache=RecCache.substring(eIndex);
       lastReceiveTime=millis();
       
       handleCmd(data);
    }
  }else{
    RecCache=""; 
  }
  
  if(RecCache.length()>=512)RecCache="";
  
}

void handleCmd(String cmd){
 Serial.println("cmd->" + cmd +"."); 
 if(cmd.startsWith("HB:")){
    byte bs[4];
    long2byte(millis(),bs);
    String msg=bytes2String(bs,0,4);// (String)((char)bs[0]) +(String)((char)bs[1]) +(String)((char)bs[2]) +(String)((char)bs[3]) ;

   reply(true,"HB",msg);
 }else if(cmd.startsWith("F:")){
    fireCmd(cmd);
 }
}

void fireCmd(String cmd){
   byte safeBytes[4]={0,0,0,0};
   for(int i=0;i<4;i++){
     safeBytes[i]=(byte)cmd.charAt(2+i);
     //Serial.print(safeBytes[i],HEX);
     //Serial.print(",");
    
   }
  unsigned long sk= bytes2long(safeBytes);
  byte duration=cmd.charAt(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 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);
 } 
  
}

String bytes2String(byte bs[],int offset,int len){
  
   String t="";
   for(int i=offset;i<len;i++){
    t +=(String)((char)bs[i]); 
     
   }
   return t;
  
}

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

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

 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

android

package cn.fstudio.wificracker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;

import org.apache.http.util.EncodingUtils;

import junit.framework.Protectable;
import android.R.integer;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class TCPClient {
    private Handler mHandler=null;
    private volatile boolean isConnecting = false;
    
    private Thread mThreadClient = null;
    private Socket mSocketClient = null;

    private BufferedReader mBufferedReaderClient    = null;

    public OutputStream os=null;
    public InputStream is=null;
    private String ip;
    private int port;
    
    private boolean Enabled=false;
    
    public boolean isEnabled(){
        return Enabled;
    }
    public boolean isConnecting() {
        return isConnecting;
    }

    

    
    public TCPClient(Handler handler,String ip,int port) {
        this.mHandler=handler;
        this.ip=ip;
        this.port=port;
    }
    

    public void Start(){
        if(Enabled)return;
        Enabled=true;
        _Start();
    }
    public void Stop(){
        Enabled=false;
        _Stop();
        
    }
    private void _Start(){
        mThreadClient = new Thread(mRunnable);
        mThreadClient.start();    
    }
    private void _Stop(){
        isConnecting=false;
        try {
            if(mSocketClient!=null)
            {
                mSocketClient.close();
                mSocketClient = null;
                
                os.close();
                os=null;

                is.close();
                is=null;
                
                mBufferedReaderClient.close();
                mBufferedReaderClient=null;
                
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try{
            Thread.sleep(3000);
           if(mThreadClient!=null)    mThreadClient.interrupt();
        }catch(Exception e){
            e.printStackTrace();
        }
        
    
                
    }
    

    public void sendMsg(String msg){
        try 
        {    
            
            byte[] cs=msg.getBytes("UTF-8");
            os.write(cs, 0, cs.length);

            os.flush();
        }
        catch(Exception e) 
        {
        }
    }
    
    
    private Runnable    mRunnable    = new Runnable() 
    {
        public void run()
        {

            String sIP = ip;
                    
            
            Log.d("T", "IP:"+ sIP + ":" + port);    
            
            try{
               ConnectAndReceive(sIP); 
               
            }catch(Exception e){
                SendMsgToUI("运行异常:" + e.getMessage() + "\n", MainActivity.MESSAGE_ERROR);
       
            }finally{
                try{
                if(Enabled){    
                _Stop();
                }
                }catch(Exception e){}
      
                
                 if(Enabled){
                    _Start();    
                   }
            }
            
        }

        private void ConnectAndReceive(String sIP) {
            try 
            {                
                
                mSocketClient = new Socket(sIP, port);    //portnum
                mSocketClient.setSoTimeout(1000 * 30);
                mSocketClient.setKeepAlive(true);
            
                //mBufferedReaderClient = new BufferedReader(new InputStreamReader(mSocketClient.getInputStream()));
                is=mSocketClient.getInputStream();
                os= mSocketClient.getOutputStream();
    
                
                isConnecting=true;
                sendMsg("$FHB:$E");
              
                //break;
            }
            catch (Exception e) 
            {

                
                throw new RuntimeException("无法链接->" + ip +":" + String.valueOf(port));
            }            

            //char[] buffer = new char[256];
            int count = 0;
            int errCount=0;
            byte[] Cache=new byte[1024];
            while (Enabled)
            {
                try
                {
                    byte[] buffer=new byte[1024];
                   
                    if((count=is.read(buffer, 0, buffer.length))>0){
                        String revMsg= new String(buffer,0,count, "UTF-8");
                    
                        int bIndex=revMsg.indexOf("$F");
                        if(bIndex>=0){
                            int eIndex =revMsg.indexOf("$E", bIndex);
                            if(eIndex>0){
                                handMsg(revMsg.substring(bIndex +2, eIndex) ,buffer);
                            }
                            
                        }
                            
                            
        
                    }else {
                        SendMsgToUI("空数据",  MainActivity.MESSAGE_ERROR);    
                        throw new RuntimeException("链接异常");
                    }
                    
                }catch(SocketTimeoutException e){
                    errCount++;
                    if(errCount<=3){
    
                        continue;
                    }
                    if(errCount>3){
                        isConnecting=false;
                        throw new RuntimeException("链接异常");
                    }
                }
                catch (Exception e)
                {
                    
                    throw new RuntimeException("网络断开");
                    
                }
            
            }//end while
        }

        private void handMsg(String cmdReply,byte[] rawBytes) {
            
            //处理心跳回复
            if(cmdReply.startsWith("OK-HB:")){
                
                
                try {
                     byte[] hbReplyBytes = cmdReply.getBytes("UTF-8");
                    
                     long millis=    BitConvert.unsigned4BytesToInt(rawBytes, 8);
                        Message msg = new Message();
                        msg.obj ="HB:" + millis;
                        
                        msg.what = MainActivity.MESSAGE_ERROR;
                       
                        mHandler.sendMessage(msg);
                     return;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               
                
            }
            Message msg = new Message();
            msg.obj = cmdReply;
            
            msg.what = MainActivity.MESSAGE_ERROR;
           
            mHandler.sendMessage(msg);
            Log.d("T", cmdReply);
        }
    };
    
    
    private void SendMsgToUI(String txt,int what){
        Message msg= mHandler.obtainMessage();
        msg.what=what;
        msg.obj=txt;
        msg.sendToTarget();
    }
    private String getInfoBuff(char[] buff, int count)
    {
        char[] temp = new char[count];
        for(int i=0; i<count; i++)
        {
            temp[i] = buff[i];
        }
    
        return new String(temp);
    }
    
}
View Code
package cn.fstudio.wificracker;


public class BitConvert {  
    /** 
     * 灏嗕竴涓崟瀛楄妭鐨刡yte杞崲鎴�32浣嶇殑int 
     *  
     * @param b 
     *            byte 
     * @return convert result 
     */  
    public static int unsignedByteToInt(byte b) {  
        return (int) b & 0xFF;  
    }  
  
    /** 
     * 灏嗕竴涓崟瀛楄妭鐨凚yte杞崲鎴愬崄鍏繘鍒剁殑鏁� 
     *  
     * @param b 
     *            byte 
     * @return convert result 
     */  
    public static String byteToHex(byte b) {  
        int i = b & 0xFF;  
        return Integer.toHexString(i);  
    }  
  
    /** 
     * 灏嗕竴涓�4byte鐨勬暟缁勮浆鎹㈡垚32浣嶇殑int 
     *  
     * @param buf 
     *            bytes buffer 
     * @param byte[]涓紑濮嬭浆鎹㈢殑浣嶇疆 
     * @return convert result 
     */  
    public static long unsigned4BytesToInt(byte[] buf, int pos) {  
        int firstByte = 0;  
        int secondByte = 0;  
        int thirdByte = 0;  
        int fourthByte = 0;  
        int index = pos;  
        firstByte = (0x000000FF & ((int) buf[index+3]));  
        secondByte = (0x000000FF & ((int) buf[index + 2]));  
        thirdByte = (0x000000FF & ((int) buf[index + 1]));  
        fourthByte = (0x000000FF & ((int) buf[index ]));  
        index = index + 4;  
        return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;  
    }  
  
    /** 
     * 灏�16浣嶇殑short杞崲鎴恇yte鏁扮粍 
     *  
     * @param s 
     *            short 
     * @return byte[] 闀垮害涓�2 
     * */  
    public static byte[] shortToByteArray(short s) {  
        byte[] targets = new byte[2];  
        for (int i = 0; i < 2; i++) {  
            int offset = (targets.length - 1 - i) * 8;  
            targets[i] = (byte) ((s >>> offset) & 0xff);  
        }  
        return targets;  
    }  
  
    /** 
     * 灏�32浣嶆暣鏁拌浆鎹㈡垚闀垮害涓�4鐨刡yte鏁扮粍 
     *  
     * @param s 
     *            int 
     * @return byte[] 
     * */  
    public static byte[] intToByteArray(int s) {  
        byte[] targets = new byte[2];  
        for (int i = 0; i < 4; i++) {  
            int offset = (targets.length - 1 - i) * 8;  
            targets[i] = (byte) ((s >>> offset) & 0xff);  
        }  
        return targets;  
    }  
  
    /** 
     * long to byte[] 
     *  
     * @param s 
     *            long 
     * @return byte[] 
     * */  
    public static byte[] longToByteArray(long s) {  
        byte[] targets = new byte[2];  
        for (int i = 0; i < 8; i++) {  
            int offset = (targets.length - 1 - i) * 8;  
            targets[i] = (byte) ((s >>> offset) & 0xff);  
        }  
        return targets;  
    }  
  
    /**32浣峣nt杞琤yte[]*/  
    public static byte[] int2byte(int res) {  
        byte[] targets = new byte[4];  
        targets[0] = (byte) (res & 0xff);// 鏈�浣庝綅  
        targets[1] = (byte) ((res >> 8) & 0xff);// 娆′綆浣�  
        targets[2] = (byte) ((res >> 16) & 0xff);// 娆¢珮浣�  
        targets[3] = (byte) (res >> 24);// 鏈�楂樹綅,鏃犵鍙峰彸绉汇��  
        return targets;  
    }  
  
    /** 
     * 灏嗛暱搴︿负2鐨刡yte鏁扮粍杞崲涓�16浣峣nt 
     *  
     * @param res 
     *            byte[] 
     * @return int 
     * */  
    public static int byte2int(byte[] res) {  
        // res = InversionByte(res);  
        // 涓�涓猙yte鏁版嵁宸︾Щ24浣嶅彉鎴�0x??000000锛屽啀鍙崇Щ8浣嶅彉鎴�0x00??0000  
        int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 琛ㄧず瀹変綅鎴�  
        return targets;  
    }  
}  
View Code

注意:

 char c= mySerial.read();
    RecCache=RecCache +(String)c;
遇到byte=0 时会发生错误

如果需要按byte接收数据,请采用
http://www.cnblogs.com/wdfrog/p/4988244.html
的方式

posted on 2015-11-17 16:50  遗忘海岸  阅读(5014)  评论(0编辑  收藏  举报