#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/pbuf.h"
#include "lwip/tcp.h"
#include "lwip/dns.h"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define TCP_SERVER "tcpbin.com"
#define TCP_PORT 4242
static struct tcp_pcb *tcp_client_pcb;
// Callback for when data is received
err_t tcp_recv_callback(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) {
if (p == NULL) {
printf("Connection closed by server.\n");
tcp_close(tpcb);
return ERR_OK;
}
char buffer[128];
pbuf_copy_partial(p, buffer, p->len, 0);
buffer[p->len] = '\0';
printf("Received: %s\n", buffer);
pbuf_free(p);
return ERR_OK;
}
// Callback for when the connection is established
err_t tcp_connect_callback(void *arg, struct tcp_pcb *tpcb, err_t err) {
if (err != ERR_OK) {
printf("Failed to connect to server.\n");
return err;
}
printf("Connected to server.\n");
const char *message = "camisa confortavel de tamanho adequado\n";
tcp_write(tpcb, message, strlen(message), TCP_WRITE_FLAG_COPY);
tcp_recv(tpcb, tcp_recv_callback);
return ERR_OK;
}
// DNS callback function
static void dns_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) {
if (ipaddr == NULL) {
printf("Failed to resolve DNS for %s\n", name);
return;
}
printf("Resolved %s to %s\n", name, ipaddr_ntoa(ipaddr));
tcp_connect(tcp_client_pcb, ipaddr, TCP_PORT, tcp_connect_callback);
}
void wifi_setup() {
if (cyw43_arch_init()) {
printf("Failed to initialize Wi-Fi module.\n");
return;
}
cyw43_arch_enable_sta_mode();
if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 10000)) {
printf("Cannot find SSID.\n");
cyw43_arch_poll();
cyw43_arch_deinit();
sleep_ms(1000);
wifi_setup();
}
printf("WiFi connected successfully.\n");
}
void print_network_info() {
struct netif *netif = netif_list;
printf("Network interface: %c%c\n", netif->name[0], netif->name[1]);
printf("IP Address: %s\n", ip4addr_ntoa(netif_ip4_addr(netif)));
printf("Netmask: %s\n", ip4addr_ntoa(netif_ip4_netmask(netif)));
printf("Gateway: %s\n", ip4addr_ntoa(netif_ip4_gw(netif)));
}
void connect_to_server() {
tcp_client_pcb = tcp_new();
if (!tcp_client_pcb) {
printf("Failed to create TCP PCB.\n");
return;
}
printf("Resolving %s...\n", TCP_SERVER);
ip_addr_t server_ip;
err_t err = dns_gethostbyname(TCP_SERVER, &server_ip, dns_callback, NULL);
if (err == ERR_OK) {
printf("DNS resolved immediately: %s\n", ipaddr_ntoa(&server_ip));
tcp_connect(tcp_client_pcb, &server_ip, TCP_PORT, tcp_connect_callback);
} else if (err != ERR_INPROGRESS) {
printf("DNS resolution failed: %d\n", err);
tcp_close(tcp_client_pcb);
}
}
int main() {
stdio_init_all();
wifi_setup();
print_network_info();
while (1) {
connect_to_server();
sleep_ms(10000); // Wait before reconnecting
}
}