Skip to content

Commit

Permalink
Swap CRC bytes in request data but not at CRC computing (stephane#397)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephane committed Mar 30, 2022
1 parent 6af09ce commit 0b4020c
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/modbus-rtu.c
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)

/* pass through message buffer */
while (buffer_length--) {
i = crc_hi ^ *buffer++; /* calculate the CRC */
crc_hi = crc_lo ^ table_crc_hi[i];
crc_lo = table_crc_lo[i];
i = crc_lo ^ *buffer++; /* calculate the CRC */
crc_lo = crc_hi ^ table_crc_hi[i];
crc_hi = table_crc_lo[i];
}

return (crc_hi << 8 | crc_lo);
Expand All @@ -155,8 +155,11 @@ static int _modbus_rtu_prepare_response_tid(const uint8_t *req, int *req_length)
static int _modbus_rtu_send_msg_pre(uint8_t *req, int req_length)
{
uint16_t crc = crc16(req, req_length);
req[req_length++] = crc >> 8;

/* According to the MODBUS specs (p. 14), the low order byte of the CRC comes
* first in the RTU message */
req[req_length++] = crc & 0x00FF;
req[req_length++] = crc >> 8;

return req_length;
}
Expand Down Expand Up @@ -374,7 +377,7 @@ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg,
}

crc_calculated = crc16(msg, msg_length - 2);
crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
crc_received = (msg[msg_length - 1] << 8) | msg[msg_length - 2];

/* Check CRC of msg */
if (crc_calculated == crc_received) {
Expand Down

0 comments on commit 0b4020c

Please sign in to comment.