TCP modbus server
下面程序 只能接收一个客户端数据,同时有几个客户端要怎么处理呢?
static void test_thread(void *param)
{
while(1){
rt_thread_mdelay(5000);
int s = -1;
modbus_t *ctx = NULL;
modbus_mapping_t *mb_mapping = NULL;
int rc;
ctx = modbus_new_tcp(RT_NULL, 1502);
s = modbus_tcp_listen(ctx, 10);
modbus_tcp_accept(ctx, &s);
mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
MODBUS_MAX_READ_REGISTERS, 0);
while(1)
{
uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
uint16_t data[]={1,2,3,4,5,6,7,8};
// modbus_write_registers(ctx,0x12,4,data);
rc = modbus_receive(ctx, query);
if (rc > 0) {
modbus_reply(ctx, query, rc, mb_mapping);
for(int i=0;i<20;i++)
printf("%2x ",query
);
} else if (rc == -1) {
/* Connection closed by the client or error */
break;
}
rt_thread_mdelay(50);
}
modbus_mapping_free(mb_mapping);
if (s != -1) {
close(s);
}
/* For RTU, skipped by TCP (no TCP connect) */
modbus_close(ctx);
modbus_free(ctx);
}
}
查看更多