From ddae10c5de591e984dcd8e2f8b9d7faf793785f8 Mon Sep 17 00:00:00 2001 From: Carlo Perassi Date: Fri, 30 Oct 2026 18:51:32 +0100 Subject: [PATCH] modbus: set the exception bit with | 0x80, not + 0x80 A request whose function code is 0x80 to 0xFF (reserved for exception responses) got an exception whose function byte wrapped around: 0x81 was answered 0x01 0x01, which reads as a Read Coils response with a byte count of 1 and no data. The client then waits for that data byte. Building the byte with | 0x80 keeps the exception bit set and changes nothing for valid function codes. --- src/modbus.c | 4 ++-- tests/unit-test-client.c | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/modbus.c b/src/modbus.c index abdd718c4..fcd07bfc8 100644 --- a/src/modbus.c +++ b/src/modbus.c @@ -786,7 +786,7 @@ static int response_exception(modbus_t *ctx, } /* Build exception response */ - sft->function = sft->function + 0x80; + sft->function = sft->function | 0x80; rsp_length = ctx->backend->build_response_basis(sft, rsp); rsp[rsp_length++] = exception_code; @@ -1283,7 +1283,7 @@ int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int excep function = req[offset]; sft.slave = slave; - sft.function = function + 0x80; + sft.function = function | 0x80; sft.t_id = ctx->backend->get_response_tid(req); rsp_length = ctx->backend->build_response_basis(&sft, rsp); diff --git a/tests/unit-test-client.c b/tests/unit-test-client.c index c1542e971..b103ef070 100644 --- a/tests/unit-test-client.c +++ b/tests/unit-test-client.c @@ -868,6 +868,10 @@ int test_server(modbus_t *ctx, int use_backend) const int INVALID_FC = 0x42; const int INVALID_FC_REQ_LEN = 6; uint8_t invalid_fc_raw_req[] = {slave, 0x42, 0x00, 0x00, 0x00, 0x00}; + /* 0x80 to 0xFF are reserved for exception responses */ + const int RESERVED_FC = 0x81; + const int RESERVED_FC_REQ_LEN = 6; + uint8_t reserved_fc_raw_req[] = {slave, 0x81, 0x00, 0x00, 0x00, 0x00}; int req_length; uint8_t rsp[MODBUS_TCP_MAX_ADU_LENGTH]; @@ -999,6 +1003,17 @@ int test_server(modbus_t *ctx, int use_backend) rsp[backend_offset] == (0x80 + INVALID_FC), "") + /* Test a function code reserved for exception responses: the answer + must still have the exception bit set */ + modbus_send_raw_request( + ctx, reserved_fc_raw_req, RESERVED_FC_REQ_LEN * sizeof(uint8_t)); + rc = modbus_receive_confirmation(ctx, rsp); + printf("Return an exception on reserved function code: "); + ASSERT_TRUE(rc == (backend_length + EXCEPTION_RC) && + rsp[backend_offset] == RESERVED_FC && + rsp[backend_offset + 1] == MODBUS_EXCEPTION_ILLEGAL_FUNCTION, + "") + modbus_set_response_timeout(ctx, old_response_to_sec, old_response_to_usec); return 0; close: