Skip to content

Conversation

@grantramsay
Copy link

Hi, I'm using a protocol that runs on top of modbus.
It has requirements like: "If attempting to write a register to an invalid value, modbus Illegal-Data-Value exception must be returned".
This was not possible to do from the read/write callbacks, so I've made a minor change to allow it.

This is a great libmodbus fork btw


send_response:
/* Check if a user read/write callback returned a negated error code within the
* range of modbus protocol exceptions, if so respond with that exception */
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively could get the user to set errno in the callback, instead of returning the negated error number if you think that's better

@grantramsay
Copy link
Author

I found a workaround to this.
For anyone interested, you can pass the request data via callback context (or static buffer if not multi-instance) and use modbus_reply_exception:

struct callback_context {
    modbus_t *modbus;
    const uint8_t *req;
};

static int write_callback(void *user_ctx, int slave, int function, uint16_t address, int nb, const uint8_t *req)
{
    struct callback_context *cb_ctx = (struct callback_context *)user_ctx;
    modbus_reply_exception(cb_ctx->modbus, cb_ctx->req, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE);
    return -1; // No additional reply will be sent if negative
}

int main() {
    modbus_t *modbus = modbus_new_...
    struct callback_context cb_ctx = {
        .modbus = modbus
    };
    int rc = modbus_set_reply_callbacks(modbus, &callbacks, &cb_ctx);
    uint8_t req[260];
    int rx_length = modbus_receive(modbus, req);
    cb_ctx.req = req; // Pass the request data to callbacks
    rc = modbus_reply_callback(modbus, query, rx_length);
    ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant