通过微信小程序配置未入网的安信可Wi-Fi模组连接家庭2.4G路由器,实现连接云端服务器;
{
"port":61691 , //微信小程序本地端口,代码获取
"password":"12345678" , //要连接的家庭网络路由器的密码
"ssid":"xuhong@aithinker" //要连接的家庭网络路由器的SSID
}
{
"result": 0 , //错误码
}
{
"code": 1 , // 错误码
}
错误码 | 含义 |
---|---|
0 | 设备成功收到信息 |
1 | 设备成功解析到小程序发来的SSID和PWD信息 |
2 | 设备成功连接到路由器 |
3 | 设备失败连接到路由器 |
命令顺序:
AT顺序 | 说明 |
---|---|
AT+CWMODE=3 | STAT+AP模式 |
AT+CIPMUX=1 | 设置多连接 |
AT+CWSAP=“ESP32”,“123456789”,1,3 | 设置软热点 |
AT+CIPSTART=0,“UDP”,“192.168.4.1”,8888,1000,0 | 开启UDP服务(等待小程序发来SSID和PWD) |
AT+CIPSENDEX=0,10,“192.168.4.2”,63665 | 解析OK,回复给小程序 |
{“code”:0} | 协议,见上章 |
AT+CWJAP=“iot@xuhongv”,“xh12345678” | 根据小程序发来的SSID和PWD连接路由器 |
AT+CIPSENDEX=0,10,“192.168.4.2”,63665 | 解析OK,回复给小程序 |
{“code”:2} | 协议,见上章 |
详细的交互抓取:
Ai-Thinker Technology Co. Ltd.
ready
WIFI CONNECTED
WIFI GOT IP
AT+CWMODE=3
OK
AT+CIPMUX=1
OK
AT+CWSAP="ESP32","123456789",1,3
OK
AT+CIPSTART=0,"UDP","192.168.4.1",8888,1000,0
0,CONNECT
OK
+STA_CONNECTED:"f8:87:f1:0f:35:3b"
+DIST_STA_IP:"f8:87:f1:0f:35:3b","192.168.4.2"
+DIST_STA_IP:"f8:87:f1:0f:35:3b","192.168.4.2"
+IPD,0,63:{"port":63665,"password":"xh12345678","ssid":"iot@xuhongv"}
AT+CIPSENDEX=0,10,"192.168.4.2",63665
收:OK
>busy p...
Recv 10 bytes
SEND OK
AT+CWJAP="iot@xuhongv","xh12345678"
WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP
OK
小程序的核心代码:
//是否第一次UDP建立
if (this.data.isFirst) {
let udp = wx.createUDPSocket();
this.setData({
isFirst: false,
udp,
port: udp.bind(),
});
}
const password = this.data.password;
const ssid = this.data.ssid;
const port = this.data.port;
let message = JSON.stringify({
port,
password,
ssid
})
//双方约好为
this.data.udp.send({
address: '192.168.4.1',
port: 1000,
message
});
this.data.udp.onMessage((res) => {
//字符串转换,很重要
let unit8Arr = new Uint8Array(res.message);
let encodedString = String.fromCharCode.apply(null, unit8Arr);
let data = decodeURIComponent(escape((encodedString)));
console.log("data:", data);
let str = JSON.parse(data);
switch (str.code) {
//成功收到信息
case 0:
wx.showToast({
title: '接收成功',
})
break;
//成功解析到信息
case 1:
wx.showToast({
title: '准备连接路由器',
})
break;
//成功连接到路由器
case 2:
wx.showToast({
title: '成功连接',
})
break;
//连接失败路由器
case 3:
wx.showToast({
title: '连接失败',
})
break;
}
})
},
微信小程序源码:https://github.com/xuhongv/WeChatMiniAP2Net
共勉!有疑问请留言,或邮箱:[email protected]