1.完成上次station初始化后,wifi已经连接,并且能获取到ip地址
2.连上wifi的目的:无非就是进行网络通信
3.进行tcp连接,建立socket,然后发送和接受数据
4.查看了例程tcp_client,不过例程里面的wifi回调事件被封装好了,所以想移植到这个station例程里,所以说干就干(上班搬砖太累了,下班懒惰了几天才淦)
代码思路:
1.创建一个专门服务tcp连接的线程(api查看freertos库吧,我倒是用开RTT)
2.在wifi回调中断函数中判断获取ip事件,成功获取ip后启动这个标志位
3.tcp线程首先使用等待标志位的api函数阻塞线程,等获取到标志位置位时再启动,代码如下:
等待标志位,等到后建立socket,建立成功后,发送 接受
static void tcp_client_task(void *pvParameters)
{
char rx_buffer[128];
char host_ip[] = "192.168.0.109";
int addr_family = 0;
int ip_protocol = 0;
//生成事件标志位
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
while (1)
{
struct sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(host_ip);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
addr_family = AF_INET;
ip_protocol = IPPROTO_IP;
int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
if (sock < 0)
{
ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
break;
}
ESP_LOGI(TAG, "Socket created, connecting to %s:%d", host_ip, PORT);
int err = connect(sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in6));
if (err != 0)
{
ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno);
break;
}
ESP_LOGI(TAG, "Successfully connected");
while (1)
{
int err = send(sock, payload, strlen(payload), 0);
if (err < 0)
{
ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
break;
}
int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
// Error occurred during receiving
if (len < 0)
{
ESP_LOGE(TAG, "recv failed: errno %d", errno);
break;
}
// Data received
else
{
rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
ESP_LOGI(TAG, "Received %d bytes from %s:", len, host_ip);
ESP_LOGI(TAG, "%s", rx_buffer);
}
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
if (sock != -1)
{
ESP_LOGE(TAG, "Shutting down socket and restarting...");
shutdown(sock, 0);
close(sock);
}
}
}
}
4.使用网络调试助手验证
5.工程打包上传了有需要的自己下载。
esp32初始化wifi后建立tcp连接-嵌入式文档类资源-CSDN下载