通过ardunio向esp8266模块发送at指令,连接上wifi,然后向服务器发送tcp连接请求,之后是与服务器进行sockt通信,实现通过web服务器,更改设备的led开关。
esp8266连接,ardunio使用软串口RX=2,TX=3,
RX—–ardunio的TX
TX—–ardunio的RX
IO15–GND
CHP_EK—3.3V
RST—-3.3V
IO0—3.3V
IO2 —3.3V
#include
#include
SoftwareSerial mySerial(2, 3); // RX, TX
//发送的数据
String json="";
//发送数据长度
int sendlength;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
}
Serial.println("Goodnight moon!");
mySerial.begin(115200);
delay(2000);
mySerial.print("AT+RST\r\n");
delay(8000);
clearCash();
Serial.println("rst finish");
mySerial.print("AT+CWMODE=3\r\n");
delay(5000);
clearCash();
Serial.println("mode finish");
mySerial.print("AT+CWJAP=\"wifiname\",\"wifipassword\"\r\n");
delay(8000);
clearCash();
Serial.println("CWJAP finish");
mySerial.print("AT+CIPSTART=\"TCP\",\"192.168.1.144 \",8888\r\n" );
delay(8000);
clearCash();
json ="{\"id\":1,\"name\":\"szh\"}";
delay(300);
String text1 ="AT+CIPSEND=";
sendlength =json.length()+2;
text1.concat(String(sendlength));
Serial.println(text1);
delay(300);
mySerial.println(text1);
delay(1000);
clearCash();
Serial.print("Send String:");
Serial.println(json);
mySerial.println(json);
delay(1000);
clearCash();
Serial.println("setup end");
}
void loop() { // run over and over
String inString="";
boolean start =false;
mySerial.listen();
while(mySerial.available()){
char inChar = (char)mySerial.read();
Serial.write(inChar);
if(start){
if(inChar == '}'){
start =false;
Serial.println("start false");
}
if(start){
inString +=(char)inChar;
}
Serial.println(inString);
}
if(inChar == '{'){
start =true;
Serial.println("start true");
delay(10);
}
delay(10);
}
if(inString != ""){
Serial.print("InputString:");
Serial.println(inString);
if(inString == "off"){
digitalWrite(7, LOW);
json ="{\"state\":\"off\"}";
delay(300);
sendResult();
}else if(inString == "on"){
digitalWrite(7, HIGH);
json ="{\"state\":\"on\"}";
delay(300);
sendResult();
}else{
json ="{\"state\":\"error\"}";
delay(300);
sendResult();
}
inString="";
}
}
//清空缓存
void clearCash(){
while(mySerial.available()){
mySerial.read();
}
}
//发送结果数据
void sendResult(){
String text1 ="AT+CIPSEND=";
sendlength =json.length()+2;
text1.concat(String(sendlength));
mySerial.println(text1);
delay(1000);
clearCash();
mySerial.println(json);
delay(1000);
clearCash();
}
注:每一次发送软串口会返回结果,所以需要将这些信息读取掉。通过at指令,会不太稳定,延迟时间可以长一点。与java的通信协议为json数据,往java发数据,可以完整读取,但java发往设备会出现乱码,所以可以将数据长度简单或者重发。
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>sendservlet-name>
<servlet-class>com.test.example.SendServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>sendservlet-name>
<url-pattern>/send.jspurl-pattern>
servlet-mapping>
<listener>
<listener-class>com.test.example.SocketListenerlistener-class>
listener>
web-app>
服务器启动运行代码
public class SocketListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
new Thread(new Runnable() {
@Override
public void run() {
new SocketServer();
}
}).start();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
public class SocketServer {
/**端口号*/
private static final int port = 8888;
/** 线程池*/
private ExecutorService mExecutorService;
/**ServerSocket对象*/
private ServerSocket mServerSocket;
/**存储socket*/
public static Map socketMap =new HashMap<>();
private String ip;
public SocketServer() {
try {
System.out.println("socket启动");
//设置socket端口
mServerSocket = new ServerSocket(port);
//创建线程池
mExecutorService = Executors.newCachedThreadPool();
// 用来临时保存客户端连接的Socket对象
Socket client = null;
while(true){
client = mServerSocket.accept();
ip = client.getInetAddress().getHostAddress();
System.out.println("ip="+ip);
socketMap.put("1",client);
System.out.println(client+"------");
mExecutorService.execute(convertData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**处理数据*/
public Runnable convertData = new Runnable(){
@Override
public void run() {
System.out.println("convertData");
int result;
try {
Socket client = socketMap.get("1");
while (true) {
InputStream inputStream = client.getInputStream();
OutputStream outputStream =client.getOutputStream();
while(inputStream.available()>0) {
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
String resultData = new String(data);
resultData = replaceBlank(resultData);
System.out.println("resultData=" + resultData);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
/***
*去除空格,水平制表符,换行,回车
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
}
发送信息代码
public class SendServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Socket client = SocketServer.socketMap.get("1");
System.out.println("client="+client);
String send ="{off}";
OutputStream out = client.getOutputStream();
out.write(send.getBytes());
out.flush();
System.out.println("send finish");
}
}