why the second request always return -1
env: windows 10 x64 visual studio 2019 libmodbus 3.1.6
code

result

why?
i have the same problesm. libmodbus3.1.6 , windows10
for starters, it sets errno, so you need to call modbus_strerror(errno) that will at least give you the correct error description, which might then be more useful. Beyond that, it's possible that your device simply can't accept back to back requests?
@karlp the problem i met seems a little different, when i connect to the modbus server, it works well ,but if i idled for sometimes, for example , about 5 minutes with no activity. The libmodbus function return -1, and my program use modbus_strerror(errno) to check the error , but i say no error。I use wireshark to check the connection, it seems the client doesn't send query again, just like died. So what's wrong?
below is how i establish the connection.
temp.robot = modbus_new_tcp(config.arm_ip.toLatin1(), 502);
if (modbus_connect(temp.robot) == -1)
{
qWarning()<<"Can't connect to" << machinecode<<" ARM"<<" ErrorInfo:"<< modbus_strerror(errno) <<"\n";
modbus_close(temp.robot);
modbus_free(temp.robot);
return false;
}
and below is how i read the data
if(modbus_read_input_bits(client, static_cast<int>(addr), 1, &buf) == 1) //
{
status = (buf==1? true:false);
UA_Variant_setScalarCopy(&data->value, &status, &UA_TYPES[UA_TYPES_BOOLEAN]);
}
else
{
qWarning()<<"Can't read ARM" << browser_name <<" ErrorInfo:"<< modbus_strerror(errno) <<"\n";
data->hasValue = false;
return UA_STATUSCODE_BADDATALOST;
}
@karlp I use the modbus slave as server.
well that'sjust completley different. if you're using tcp and idle for a long time and then it fails, you might just have networking problems between your endpoints. things might be getting closed underneath you.
@karlp thank you for your reply. could you please give me some suggestion? now my modbus client and server run on the loopback network, should i set a timer to keep the tcp connection?
@karlp I find being idled for some minutes the tcp status become CLOSE_WAIT. And the read function return -1 but set no error. Some people have the same problem , CLOSE_WAIT
welcome to networking. there's nothing you can do about this in libmodbus. You can try setting socket options on the fd you get back with modbus_get_socket(3) but you're on your own. If you really only want to read every few minutes, just open the connection from scratch when you're about to read and close it again afterwards. Alternatively, read more frequently.
@karlp Thank you very much, i will try. Have a nice day. : )