Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/modbus.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);

Expand Down
15 changes: 15 additions & 0 deletions tests/unit-test-client.c
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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:
Expand Down