ESP8266 AP 模式下或渤,建立TCP服務(wù)器朋魔,開啟通信函荣,使用小程序或者APP 進(jìn)行配網(wǎng)
-
1.AP 模式,固定IP地址是 192.168.4.1浸踩,也可以自己設(shè)定IP
WiFi.mode(WIFI_AP); //設(shè)置為AP模式 WiFi.softAP(ssid, password); //配置AP信息叔汁,并開啟AP IPAddress softLocal(192,168,128,1); //IP地址,用以設(shè)置IP第4字段 IPAddress softGateway(192,168,128,1); //IP網(wǎng)關(guān)检碗,用以設(shè)置IP第3字段 IPAddress softSubnet(255,255,255,0); WiFi.softAPConfig(softLocal, softGateway, softSubnet); int gotoAP=WiFi.softAPgetStationNum(); //獲取當(dāng)前連接到AP的設(shè)備數(shù)量
-
2.建立TCP客戶端
server.begin(port); //服務(wù)器啟動監(jiān)聽端口號 serverClients[i].connected()//檢查端口 i 是否連接 serverClients[i].read()//從端口號獲取數(shù)據(jù)据块,返回類型char serverClients[i].print("OK! Got your request."); //回復(fù)消息
具體代碼如下:
//檢測服務(wù)器端是否有活動的客戶端連接
if (server.hasClient())
{
for (i = 0; i < MAX_SRV_CLIENTS; i++)
//查找空閑或者斷開連接的客戶端,并置為可用
{
if (!serverClients[i] || !serverClients[i].connected())
{
if (serverClients[i]) serverClients[i].stop(); //未連接,就釋放
serverClients[i] = server.available(); //分配新的
// Serial.print("New client: "); Serial.println(i);
continue;
}
}
//若沒有可用客戶端后裸,則停止連接
WiFiClient serverClient = server.available();
serverClient.stop();
}
//查詢客戶端是否有數(shù)據(jù)發(fā)出瑰钮,并打印出來
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
if (serverClients[i] && serverClients[i].connected())
{
if (serverClients[i].available())
{
Serial.println("Connected to client !!! ");
//從Telnet客戶端獲取數(shù)據(jù)
while (serverClients[i].available()) {
data[ind] = serverClients[i].read(); //讀取client端發(fā)送的字符
ind++
}
for(int j=0;j < ind; j++)
{
Serial.print(data[j]);
}
// Serial.println();
ind = 0;
serverClients[i].print("OK! Got your request."); //在client端回復(fù)
}
}
}
- 完成TCP通信冒滩,解析Json數(shù)據(jù)微驶,可以進(jìn)行配網(wǎng)\
- client 發(fā)送數(shù)據(jù)
serializeJson(doc, json_send);//將json格式數(shù)據(jù),放入發(fā)送區(qū)
serverClients[i].write(json_send, strlen(json_send));