本博文全部代码下载地址:https://download.csdn.net/download/zq666888/13119921
本博文实现功能截图:
ESP8266要想实现TCP Service功能要经过一下步骤:
1、配置ESP8266工作在AP模式,设置AP模式相关参数,比如wifi名字、密码、加密方式、最大连接数量、Wifi信道、信标间隔时槽等。
void ICACHE_FLASH_ATTR
Wifi_Init(void)
{
struct softap_config MySoftAp;
wifi_set_opmode(0x02);//设置wifi工作模式为SoftAP模式
os_strcpy(MySoftAp.ssid,"ESP8266"); //Wifi名字
os_strcpy(MySoftAp.password,"12345678");//Wifi密码
MySoftAp.ssid_len = strlen("ESP8266");//Wifi名字长度
MySoftAp.channel = 1;//Wifi通道
MySoftAp.authmode = AUTH_WPA2_PSK;//加密模式
MySoftAp.max_connection = 4;//最大连接数量
MySoftAp.beacon_interval = 100;//信标间隔时槽100 ~ 60000 ms
MySoftAp.ssid_hidden = 0;//不隐藏SSID
wifi_softap_set_config(&MySoftAp);
}
2、初始化espconn参数,注册连接成功和断开连接的回调函数,建立监听。
void ICACHE_FLASH_ATTR
TcpServiceInit(uint32_t LocalPort)
{
MyTcpEspconn.proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));//分配空间
MyTcpEspconn.type = ESPCONN_TCP;
MyTcpEspconn.proto.tcp->local_port = LocalPort;//本地端口
espconn_regist_connectcb(&MyTcpEspconn,ServiceListen);//注册TCP连接成功回调函数
espconn_regist_reconcb(&MyTcpEspconn,MyTcpReconcb);//注册 TCP 连接发生异常断开时的回调函数,可以在回调函数中进行重连。
espconn_accept(&MyTcpEspconn);//建立监听
espconn_regist_time(&MyTcpEspconn,180,0);//设置注册ESP8266 TCP server超时时间,时间值仅作参考 并不精确。
}
3、建立监听后注册TCP发送和接收回调函数以及断开连接回调函数。
void server_recv(void *arg,char *pdata,unsigned short len)
{
os_printf("Receive Data:%s\r\n",pdata);
os_printf("Receive Length:%d\r\n",len);
}
void server_sent()
{
os_printf("Send OK!\r\n");
}
void server_discon()
{
os_printf("Tcp break!\r\n");
}
/*
注册TCP连接成功的回调函数
* */
void ServiceListen(void *arg)
{
struct espconn *Myespconn = arg;
os_printf("Tcp connect Success!\r\n");
espconn_regist_recvcb(Myespconn, server_recv); //接收回调函数
espconn_regist_sentcb(Myespconn, server_sent); //发送回调函数
espconn_regist_disconcb(Myespconn, server_discon); //断开回调函数
}