我制作了一个自定义固件来连接到 TCP 套接字服务器,一切正常,直到 WIFI 失去连接并再次重新连接。我将尝试解释:
1. ESP8266EX启动,当它连接到我的 AP 时(我在 wifi_sta
tion_get_connect_status() == STATION_GOT_IP时签入计时器,因为没有 WIFI CONNECTION CALLBACK),然后我通过调用我的自定义函数创建一个 TCP 连接,如下所示:
结构体 espconn *ctrlConn;全局变量保持连接
创建 TCP 连接并开始连接
静态空隙ICACHE_FLASH_ATTR tcp_connection_create(void)
{
enum espconn_type linkType = ESPCONN_TCP;
ctrlConn = (struct espconn *)os_zalloc(sizeof(struct espconn));
ctrlConn->type = linkType;
ctrlConn->state = ESPCONN_NONE;
ctrlConn->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
ctrlConn->proto.tcp->local_port = espconn_port();
ctrlConn->proto.tcp->remote_port = ctrlSetup.serverPort;
os_memcpy(ctrlConn->proto.tcp->remote_ip, ctrlSetup.serverIp, 4);
ctrlConn->reverse = NULL; // I don't need this, right?
espconn_regist_connectcb(ctrlConn, tcpclient_connect_cb);
espconn_regist_reconcb(ctrlConn, tcpclient_recon_cb);
espconn_connect(ctrlConn);
uart0_sendStr("TCP connection created.rn");
}
当回调函数 tcpclient_connect_cb() 执行时,我开始与服务器
通信,一切正常,没有问题。
2. Now, when I turn my AP off, the ESP8266EX detects the connection break and calls a callback function tcpclient_recon_cb(). That function gets parameters: sint8 errType which has value -11 (ESPCONN_CONN), and the state of espconn (arg->State is 6 ... ESPCONN_CLOSE). In that function I call my other function to destroy the connection because I will create it again when AP gets connected again:
关闭并破坏当前连接
静态空隙ICACHE_FLASH_ATTR tcp_connection_destroy(void)
{
uart0_sendStr("tcp_connection_destroy()rn");
ctrlState &= ~CTRL_STATE_AUTHENTICATED; // my custom variables
connState = CTRL_TCP_DISCONNECTED; // my custom variables
espconn_disconnect(ctrlconn); // this will os_free() my ctrlConn so I can create it again by calling tcp_connection_create(); when WIFI gets IP again
}
3. 当我重新打开我的 AP 时,几秒钟后,ESP8266EX会自动连接并获得 IP。我的计时器将检测到它再次获得 IP,并开始连接 TCP 客户端的过程。
现在它成功连接到 TCP,并且通信工作正常,但在 ~30 秒后,我意外地遇到 TCP 连接中断并调用我的 tcpclient_recon_cb() 函数。 Again, it gets parameters sint8 errType which has value -11 (ESPCONN_CONN), and the state of espconn (arg->State is 6 ... ESPCONN_CLOSE). After that I destroy the current connection and recreate it again but from then it just hangs and doesn't work.
发生了什么,为什么ESP8266EX再次从 WIFI AP 获取 IP 时,它会在几秒钟后断开 TCP 客户端连接?
My TCP Client code is in "user/ctrl_platform.c".
我使用 lubuntu 和 SDK v0.9.2 来编译所有内容。