stephane / libmodbus

A Modbus library for Linux, Mac OS, FreeBSD and Windows
http://libmodbus.org
GNU Lesser General Public License v2.1
3.29k stars 1.71k forks source link

How to actively stop the “modbus_receive”? #661

Closed singlebear closed 1 year ago

singlebear commented 1 year ago

My program creates a Modbus RTU slave,and i created a thread to deal “modbus_receive” . But I found that the “modbus_receive” was blocking the thread when there was no master site to interact with it. So I can't stop this process on the main thread. Is there any way to stop it? Thanks!

void ModbusBase::SlaveDealThread()
{
    int rc = 0;
    uint8_t query[MODBUS_RTU_MAX_ADU_LENGTH];
    base_parameter->is_func_thread_run = true;
    while (base_parameter->is_slave_running)
    {
        std::cout << "\n MODBUS begin \n" << std::endl;
        memset(query, 0, sizeof(query));
        rc = modbus_receive(base_parameter->link_object, query);
        if (rc > 0) {
            modbus_reply(base_parameter->link_object, query, rc, base_parameter->data_ptr);
        }
        else if (rc == -1) {
            std::cout << "\n MODBUS error \n" << std::endl;
            break;
        }
        std::cout << "\n MODBUS loop \n" << std::endl;

    }
    std::cout << "\n MODBUS end \n" << std::endl;
    base_parameter->is_func_thread_run = false;
}
singlebear commented 1 year ago

I find the "modbus_set_indication_timeout" can slove it