#include "lwip.
h"
#include "lwip/tcp.h"
#include "string.h"
#include "stdio.h"
static err_t tcp_server_accept(void *arg, struct tcp_pcb *newpcb, err_t err) {
tcp_setprio(newpcb, TCP_PRIO_MIN);
printf("New connection established.\n");
// Set the receive callback for incoming data
tcp_recv(newpcb, tcp_server_recv);
return ERR_OK;
}
static err_t tcp_server_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t
err) {
if (p != NULL) {
// Acknowledge that we've received the data
tcp_recved(tpcb, p->tot_len);
// Print the received message to UART or debug console
printf("Received %d bytes from client.\n", p->len);
char received_message[256];
if (p->len < sizeof(received_message)) {
memcpy(received_message, p->payload, p->len);
received_message[p->len] = '\0'; // Null-terminate the string
printf("Message: %s\n", received_message);
}
// Prepare a response
const char *response = "Hello from STM32 TCP server!";
tcp_write(tpcb, response, strlen(response), TCP_WRITE_FLAG_COPY);
// Free the pbuf
pbuf_free(p);
} else if (p == NULL) {
// Connection closed by the client
printf("Connection closed by client.\n");
tcp_close(tpcb);
}
return ERR_OK;
}
static void tcp_server_error(void *arg, err_t err) {
printf("TCP connection error: %d\n", err);
}
#define TCP_SERVER_PORT 1234 // Server's port number
void tcp_server_init(void) {
struct tcp_pcb *pcb;
// Create a new TCP control block
pcb = tcp_new();
if (pcb != NULL) {
err_t err;
// Bind to the TCP port
err = tcp_bind(pcb, IP_ADDR_ANY, TCP_SERVER_PORT);
if (err == ERR_OK) {
// Start listening for incoming connections
pcb = tcp_listen(pcb);
// Set the accept callback to handle incoming connections
tcp_accept(pcb, tcp_server_accept);
printf("TCP server listening on port %d\n", TCP_SERVER_PORT);
} else {
// Binding failed
printf("Failed to bind TCP server on port %d\n", TCP_SERVER_PORT);
tcp_close(pcb);
}
}
}
int main(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_LWIP_Init();
// Initialize the TCP server
tcp_server_init();
// Wait for DHCP to assign IP (if using DHCP)
struct netif *netif = &gnetif;
while (netif->ip_addr.addr == 0) {
MX_LWIP_Process();
HAL_Delay(100);
}
// Process LwIP tasks in the main loop
while (1) {
MX_LWIP_Process(); // Continue processing network tasks
HAL_Delay(100); // Add delay to avoid overwhelming the CPU
}
}