尝试使用LwIP 2.0.3和FreeRTOS 9.0.0通过STM32H743BI开发MODBUS Slave应用程序
我的应用程序应该能够同时处理多个客户端。我想为每个接受的连接创建单独的线程,并在不再需要时自行杀死,如下所示:
void modbus_server_netconn_thread(void *arg)
{
struct netconn *conn = NULL, *newconn = NULL;
err_t err, accept_err;
osThreadDef(MBParticular, modbus_handler, osPriorityNormal, 8, configMINIMAL_STACK_SIZE *4);
/* Create a new TCP connection handle */
conn = netconn_new(NETCONN_TCP);
if (conn!= NULL)
{
/* Bind to port 502 with default IP address */
err = netconn_bind(conn, NULL, 502);
if (err == ERR_OK)
{
/* Put the connection into LISTEN state */
netconn_listen(conn);
while(1)
{
/* accept any incoming connection */
accept_err = netconn_accept(conn, &newconn);
if(accept_err == ERR_OK)
{
osThreadCreate (osThread(MBParticular), (void *)newconn);
// /* delete connection */
// netconn_delete(newconn); //if I put this here, no data can be rcved
newconn = NULL;
}
else netconn_delete(newconn);
}
}
}
}
static void modbus_handler(void const *arg)
{
struct netconn *conn = (struct netconn *)arg;
err_t recv_err;
u16_t buflen;
char* buf;
struct pbuf *p = NULL;
struct netbuf *inbuf;
while(TRUE){
/* Read the data from the port, blocking if nothing yet there.
We assume the request (the part we care about) is in one netbuf */
recv_err = netconn_recv(conn, &inbuf);
if (recv_err == ERR_OK)
{
if (netconn_err(conn) == ERR_OK)
{
netbuf_data(inbuf, (void**)&buf, &buflen);
// HANDLE PACKET
}
}
/* Delete the buffer (netconn_recv gives us ownership, so we have to make sure to deallocate the buffer) */
netbuf_delete(inbuf);
}
/* Close the connection */
netconn_delete(conn);
osThreadTerminate(NULL);
}
但是最多只能连接1个。另一方面,如果MODBUS Master程序已断开连接,则无法再次连接。在两种情况下,netconn_accept都会返回ERR_ABRT。
这是我的lwipopts.h的一部分:
#define MEMP_NUM_NETCONN 30
#define MEMP_NUM_NETBUF 30
#define MEMP_NUM_PBUF 60
#define MEMP_NUM_UDP_PCB 6
#define MEMP_NUM_TCP_PCB 10
#define MEMP_NUM_TCP_PCB_LISTEN 8
#define MEMP_NUM_TCP_SEG 8
#define MEMP_NUM_SYS_TIMEOUT 10
我可能犯了一个基本错误。如果这浪费您的时间,请原谅我。谢谢!