arduino 与 android 通过TCP进行字节收发
arduino
#include <avr/wdt.h>
#include <SoftwareSerial.h> #define FPIN 13 SoftwareSerial mySerial(, ); // RX, TX
unsigned long lastSendTime=;
unsigned long lastReceiveTime=;
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();
delay();
Serial.println("Ready!"); //========Wifi Config=============
initWifi(); } void loop() {
// put your main code here, to run repeatedly:
handleTXR();
} void initWifi(){
mySerial.begin();
delay();
mySerial.println("AT+RST");
delayAndRead(); mySerial.println("AT+CIPMUX=1");
delayAndRead();
mySerial.println("AT+CIPSERVER=1");
delayAndRead();
} 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>=){
int eIndex=RecCache.indexOf("$E",bIndex);
if(eIndex>=){
//Extra Data
String data=RecCache.substring(bIndex+,eIndex);
RecCache=RecCache.substring(eIndex);
lastReceiveTime=millis(); handleCmd(data);
}
}else{
RecCache="";
} if(RecCache.length()>=)RecCache=""; } void handleCmd(String cmd){
Serial.println("cmd->" + cmd +".");
if(cmd.startsWith("HB:")){
byte bs[];
long2byte(millis(),bs);
String msg=bytes2String(bs,,);// (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[]={,,,};
for(int i=;i<;i++){
safeBytes[i]=(byte)cmd.charAt(+i);
//Serial.print(safeBytes[i],HEX);
//Serial.print(","); }
unsigned long sk= bytes2long(safeBytes);
byte duration=cmd.charAt();
if(duration>) duration=;
if(duration<=)duration=; if(sk!=SafeKey){
reply(false,"F","Safe Key not match!");
return;
}
reply(true,"F","");
digitalWrite(FPIN,HIGH);
delay(duration * );
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();
mySerial.println(rStr);
}else{
rStr="$FEE-" + cmd +":" +msg +"$E";
mySerial.println("AT+CIPSEND=0," + (String)rStr.length());
delay();
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[] = (byte) (res & 0xff);// 鏈�浣庝綅
targets[] = (byte) ((res >> ) & 0xff);// 娆′綆浣�
targets[] = (byte) ((res >> ) & 0xff);// 娆¢珮浣�
targets[] = (byte) (res >> );// 鏈�楂樹綅,鏃犵鍙峰彸绉汇�� } unsigned long bytes2long(byte buf[]) {
unsigned long firstByte = ;
unsigned long secondByte = ;
unsigned long thirdByte = ;
unsigned long fourthByte = ;
int index = ;
firstByte = (0x000000FFU & ( buf[index+]));
secondByte = (0x000000FFU & ( buf[index + ]));
thirdByte = (0x000000FFU & ( buf[index + ]));
fourthByte = (0x000000FFU & ( buf[index ]));
index = index + ;
return ((unsigned long) (firstByte << | secondByte << | thirdByte << | fourthByte)) & 0xFFFFFFFFUL;
}
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();
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, , 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( * );
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 = ;
int errCount=;
byte[] Cache=new byte[];
while (Enabled)
{
try
{
byte[] buffer=new byte[]; if((count=is.read(buffer, , buffer.length))>){
String revMsg= new String(buffer,,count, "UTF-8"); int bIndex=revMsg.indexOf("$F");
if(bIndex>=){
int eIndex =revMsg.indexOf("$E", bIndex);
if(eIndex>){
handMsg(revMsg.substring(bIndex +, eIndex) ,buffer);
} } }else {
SendMsgToUI("空数据", MainActivity.MESSAGE_ERROR);
throw new RuntimeException("链接异常");
} }catch(SocketTimeoutException e){
errCount++;
if(errCount<=){ continue;
}
if(errCount>){
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, );
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=; i<count; i++)
{
temp[i] = buff[i];
} return new String(temp);
} }
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 = ;
int secondByte = ;
int thirdByte = ;
int fourthByte = ;
int index = pos;
firstByte = (0x000000FF & ((int) buf[index+]));
secondByte = (0x000000FF & ((int) buf[index + ]));
thirdByte = (0x000000FF & ((int) buf[index + ]));
fourthByte = (0x000000FF & ((int) buf[index ]));
index = index + ;
return ((long) (firstByte << | secondByte << | thirdByte << | fourthByte)) & 0xFFFFFFFFL;
} /**
* 灏�16浣嶇殑short杞崲鎴恇yte鏁扮粍
*
* @param s
* short
* @return byte[] 闀垮害涓�2
* */
public static byte[] shortToByteArray(short s) {
byte[] targets = new byte[];
for (int i = ; i < ; i++) {
int offset = (targets.length - - i) * ;
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[];
for (int i = ; i < ; i++) {
int offset = (targets.length - - i) * ;
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[];
for (int i = ; i < ; i++) {
int offset = (targets.length - - i) * ;
targets[i] = (byte) ((s >>> offset) & 0xff);
}
return targets;
} /**32浣峣nt杞琤yte[]*/
public static byte[] int2byte(int res) {
byte[] targets = new byte[];
targets[] = (byte) (res & 0xff);// 鏈�浣庝綅
targets[] = (byte) ((res >> ) & 0xff);// 娆′綆浣�
targets[] = (byte) ((res >> ) & 0xff);// 娆¢珮浣�
targets[] = (byte) (res >> );// 鏈�楂樹綅,鏃犵鍙峰彸绉汇��
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[] & 0xff) | ((res[] << ) & 0xff00); // | 琛ㄧず瀹変綅鎴�
return targets;
}
}
注意:
char c= mySerial.read();
RecCache=RecCache +(String)c;
遇到byte=0 时会发生错误 如果需要按byte接收数据,请采用
http://www.cnblogs.com/wdfrog/p/4988244.html
的方式
arduino 与 android 通过TCP进行字节收发的更多相关文章
- NFC:Arduino、Android与PhoneGap近场通信
NFC:Arduino.Android与PhoneGap近场通信(第一本全面讲解NFC应用开发的技术著作移动智能设备近距离通信编程实战入门) [美]Tom Igoe(汤姆.伊戈),Don Colema ...
- Annikken Andee–Arduino与Android间的简易连接
一个Arduino的兼容板,允许你显示并控制来自Android设备的Arduino应用.无需Anroid APP开发. 点击:观看视频 什么是Annikken Andee? Annikken Ande ...
- Android之TCP服务器编程
推荐一个学java或C++的网站http://www.weixueyuan.net/,本来想自己学了总结出来再写博客,现在没时间,打字太慢!!!!,又想让这好东西让许多人知道. 关于网络通信:每一台电 ...
- Android动态加载字节码
概述 面对App业务逻辑的频繁变更,如果每一次改变都对App进行一次升级,会降低App的用户体验,那么App进行模块化升级(这里与增量升级是不同的)是很好的解决方案,让用户在完全无感觉的情况下改变Ap ...
- 免杀手法-tcp套字节传递shellcode学习
免杀手法-tcp套字节传递shellcode学习
- Android实现TCP断点上传,后台C#服务实现接收
终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现,因为大多实现过断点下载.但稳定性不能保证, ...
- 5年Android程序员面试字节跳动两轮后被完虐,请查收给你的面试指南
大家应该看过很多分享面试成功的经验,但根据幸存者偏差的理论,也许多看看别人面试失败在哪里,对自己才更有帮助. 最近跟一个朋友聊天,他准备了几个月,刚刚参加完字节跳动面试,第二面结束后,嗯,挂了- 所以 ...
- Android笔记:Socket客户端收发数据
client.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" and ...
- Android 开发TCP协议时,报错NetworkOnMainThreadException
设想是通过Android应用连接PC的TCP服务器,通过点击按钮连接服务器, 最终在点击按钮后报错:networkonmainthreadexception 解决办法: 在MainActivity文件 ...
随机推荐
- delphi c++builder JSON 生成与解析 例子
json,System.JSON,REST.JSON JSON有两种数据结构,对象和数组. 对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,...} 数组 ...
- python模块说明
1.模块(变量,函数,类,实现一个功能) 包:用来从逻辑上组织模块,本质是一个目录(必须带有__init__.py) 2.导入方法 import module_alex from module_ale ...
- Mongodb 安装 和 启动
教程:http://www.mongodb.org.cn/tutorial/59.html 下载 >wget https://fastdl.mongodb.org/linux/mongodb-l ...
- 下载gradle缓慢的解决方法
用AndroidStudio或者Qt编译apk,下载gradle缓慢时,可以用迅雷等下载工具在https://services.gradle.org/distributions/下载对应的版本. 中断 ...
- dstat 性能监测工具
dstat 是一个可以取代vmstat,iostat,netstat和ifstat这些命令的多功能产品.dstat克服了这些命令的局限并增加了一些另外的功能,增加了监控项,也变得更灵活了.dstat可 ...
- unity VideoPlayer
Events(事件) started:在调用play()后立刻调用 prepareCompleted:播放器准备完成时 seekCompleted:缓冲完成时
- Jquery detect page refresh
first thing there are 3 functions we will use: function setCookie(c_name, value, exdays) { ...
- NodeJS框架express的路径映射(路由)功能及控制
我 们知道Express是一个基于NodeJS的非常优秀的服务端开发框架,本篇CSSer将提供express框架的route和route control章节,route实现了客户端请求的URL的路径映 ...
- jenkins 自动构建gitlab项目
安装的plugin: - kubernetes:1.7.1 - workflow-aggregator:2.5 - workflow-job:2.21 - credentials-b ...
- Containerpilot 配置文件 之 Jobs
ContainerPilot job是用户定义的进程和规则,用于何时执行它,如何进行健康检查,以及如何向Consul做广告. 这些规则旨在允许灵活性覆盖几乎可能要运行的任何类型的进程. 一些可能的jo ...