Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow read/write callbacks to respond with modbus exception codes #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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

@@ -410,6 +410,21 @@ int modbus_reply_callback(modbus_t *ctx, const uint8_t *req, int req_length)
}

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