Modbus C++ error ctx->slave != -1 failed

311 views
Skip to first unread message

sepei

unread,
May 1, 2014, 5:12:31 AM5/1/14
to libm...@googlegroups.com
Hello,

first of all I'm new to programming C++ and also programming on linux. But I dont get it whats wrong with my source.
I'm getting the error: "test1: modbus-rtu.c:119: _modbus_rtu_build_request_basis: Assertion `ctx->slave != -1' failed."

My Code is:

modbus_t *ctx;
uint16_t tab_reg[64];
int rc;
int i;
ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);
if (ctx == NULL) {
    fprintf(stderr, "Unable to create the libmodbus context\n");
    return -1;
}

if (modbus_connect(ctx) == -1) {
    fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}
rc = modbus_read_registers(ctx, 14, 2, tab_reg);
if (rc == -1) {
    fprintf(stderr, "%s\n", modbus_strerror(errno));
    return -1;
}
for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
}
modbus_close(ctx);
modbus_free(ctx);

I was debugging the programm and till "rc = modbus_read_registers(ctx, 14, 2, tab_reg);" it works fine but there I just get the above error.
Please help

Thank you

sepei

unread,
May 1, 2014, 5:14:41 AM5/1/14
to libm...@googlegroups.com
I'm on ubuntu 14.04 on arm, I installed the libary via apt-get (V. 3.05)

Bodo

unread,
May 1, 2014, 5:55:03 AM5/1/14
to libm...@googlegroups.com
Am 01.05.2014 11:12, schrieb sepei:

> But I dont get it whats wrong with my source.
> I'm getting the error: "test1: modbus-rtu.c:119:
> _modbus_rtu_build_request_basis: Assertion `ctx->slave != -1' failed."

[...]

> I was debugging the programm and till "rc = modbus_read_registers(ctx,
> 14, 2, tab_reg);" it works fine but there I just get the above error.

I think you have to call modbus_set_slave() before any read or write
function.

An assertion failure is not a good error handling in this case. IMHO
assertions should only be used for programming errors in internal to the
library not for errors caused by the calling program. A better reaction
would be to return an error code (rc < 0) from modbus_read_registers()
and set errno to specify the details.

Bodo
Reply all
Reply to author
Forward
0 new messages