准备阶段
ESP模块+云服务器
1.需要一个连接正常的ESP8266模块,ESP引脚说明及连接参见https://blog.csdn.net/jidudong0673/article/details/105219900
2.能正常ping通的服务器,本人使用的是腾讯云服务器(学生版,10块/月,最低配,能满足学习的基本需要),使用Tomcat搭建服务器,然后自己还注册了域名(已备案),可以通过域名任意访问,然后配置MySQL数据库。其实也可以用电脑在本地使用搭建服务器,使用穿网工具,同样可以实现(免费穿网工具,域名有时限性,使用也有不少坑,这也是自己选择买个云服务器的原因)服务器搭建这块后面可以给大家分享下作为萌新踩过的坑
服务器端配置
本人使用Eclipse生成服务器端,新建Dynamic Web Project,如图新建如下包:
这里考虑到服务器可以管理和响应多个客户端,所以采用设备ID和密匙PW管理,实例层使用DeviceMessage类,代码如下
package com.entity;
public class DeviceMessage {
public DeviceMessage(String id) {
this.ID = id;
this.PW = "888888";
}
public DeviceMessage(String id,String pw) {
this.ID = id;
this.PW = pw;
}
public DeviceMessage(String id,String pw,String note) {
this.ID = id;
this.PW = pw;
this.Note = note;
}
private String ID;
private String PW="888888";
private String Note="device";
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getPW() {
return PW;
}
public void setPW(String pW) {
PW = pW;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
}
应用层添加数据库增删改查等基本操作,方便管理设备,及管理用户登录
package com.dao;
import com.entity.DeviceMessage;
public interface DeviceMet {
public boolean IsContain(String id);
public boolean InsertDevice(DeviceMessage deviceMessage);
public boolean DeleteDevice(DeviceMessage deviceMessage);
public boolean VerificationDevice(DeviceMessage deviceMessage);
public boolean VerificationDevice(String id,String pw);
public boolean VerificationDevice(int hashCode);
}
ESPServlet用于响应ESP模块的请求,这里简单的讲模块发过来的数据,首先检查是否是已注册过的设备(检查ID和PW的hashCode在数据库中是否存在)若存在则回传数据,否则回传"Error",仅用于测试连接,源码如下:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.DeviceMet;
import com.dao.DeviceMetImpl;
public class ESPServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void init() {
System.out.print("test");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Message = "";
Message = request.getParameter("Message");
DeviceMet deviceMet = new DeviceMetImpl();
PrintWriter out = response.getWriter();
if(deviceMet.VerificationDevice(Integer.parseInt(Message))) {
out.println(Message);
}
else {
out.println("Error");
}
out.flush();
out.close();
}
}
不要忘记在web.xml文件中注册刚才的servlet类
然后讲工程导出war包,复制到云服务器的Tomcat安装目录下的webapps文件夹下,服务器端就配置完成,可以使用Postman测试服务器响应状态(这里就不做演示了,直接上ESP模块测试)
Lua脚本实现ESP8266连接云服务器
如果已经烧录了Node固件库的,就可以使用Lua脚本语言快速实现对应功能,烧录方法参见https://blog.csdn.net/jidudong0673/article/details/105222924
打开Esplore编译器,首先需要连接wifi,这里使用电脑创建的猎豹wifi,依据自己的网络环境设置合适wifi即可
wifi.setmode(wifi.STATIONAP)
station_cfg={}
station_cfg.ssid = "LieBaoWiFi103"
station_cfg.pwd = "1234567890"
station_cfg.save=false
wifi.sta.config(station_cfg)
wifi.sta.connect()
--tmr.ALARM_SINGLE
local mytimer = tmr.create()
mytimer:register(3000,1 , function (t)
if wifi.sta.getip()== nil then
print("Connecting...")
else
print("Connected,IP is "..wifi.sta.getip())
t:unregister()
end
end)
mytimer:start()
然后连接服务器,这里我使用80端口和自己的域名连接服务器,(Tomcat默认端口80,没有域名的可以使用ip连接)注意发送的数据需要结束符好。
local socket = require("websocket")
TCPClient = net.createConnection(net.TCP,0)
TCPClient:connect(80,"littlefoxes.cn")
TCPClient:on("receive",function(sck,data)
print("receive"..data)
end
)
TCPClient:on('connection',function(sck)
print("connection")
url = "http://littlefoxes.cn/ESP8266Service/ESPServlet"
message = "?Message="..device.."&status="..status
request = "GET "..url..message.."\r\n"
TCPClient:send(request,function()
print("send OK...")
end
)
end
)
TCPClient:on("receive",function(sck,data)
print("receive "..data)
end
)
TCPClient:on("disconnection",function(sck,c)
print("disconnection")
end
)
为了提高安全性,使用hashCode加密ID和密匙,这里自己写了个hashCode帮助类,最终生成6位(暂时不会有如此多设备导致哈希冲突,哈哈)
helper = {}
function helper.hashCode(a)
h = 0
for i = 1, string.len(a) do
h = h*31+string.byte(string.sub(a,i,i))
if h>999999 then
h = h %1000000
end
end
if h<100000 then
h = h+87654
end
return h
end
return helper
注意程序的入口文件为init.lua文件,可以将所以代码放在该文件中,也可以使用模块来管理代码,代码完成后下载在ESP模块中,重启后即可实现连接服务器,并收到服务器的返回
TCP连接超时后会自动断开连接,下次发送数据需要重连,如果需要需要持续发送大量数据,可以使用TCP长连接,这个后面再说。
AT指令连接云服务器
使用模块自带的AT固件库或者自己烧录AT固件库,烧录方法:https://blog.csdn.net/jidudong0673/article/details/105222924
AT指令集可以去查阅官方文档
这里我们需要用到的指令是:
指令 | 说明 |
---|---|
AT+CWMODE = 3 | 设置工作模式:1为Station模式,2为AP模式,3为AP+Station模式,作为客户端使用Station模式,选择1或3均可 |
AT+CWJAP = “wifi名称”,“wifi密码” | 设置连接的wifi账号及密码 |
AT+CIPSTART=“TCP”,“服务器IP或域名”,端口号 | 设置使用TCP连接,并设置IP和端口 |
AT+CIPSEND = 发送数据长度 | 开始发送数据,并给出数据长度,ESP会返回”>“等待数据 |
这里有完整的演示示例,同时再次测试了下前面的服务器,一切工作正常
到这里我们就实现了ESP模块连接云服务器,即使没有自己的服务器想要构建物联网项目,也可以使用腾讯云,阿里云,百度云等等他们的物联网平台,实现思路是类似的(当然他们的服务器性能和安全性会好些)