Skip to content

Commit 70d0aca

Browse files
committed
RTU - Check CRC before filtering on slave ID
1 parent ae6f327 commit 70d0aca

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

src/modbus-rtu.c

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -351,23 +351,11 @@ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, const int ms
351351
uint16_t crc_received;
352352
int slave = msg[0];
353353

354-
/* Filter on the Modbus unit identifier (slave) in RTU mode to avoid useless
355-
* CRC computing. */
356-
if (slave != ctx->slave && slave != MODBUS_BROADCAST_ADDRESS) {
357-
if (ctx->debug) {
358-
printf("Request for slave %d ignored (not %d)\n", slave, ctx->slave);
359-
}
360-
/* Following call to check_confirmation handles this error */
361-
return 0;
362-
}
363-
364354
crc_calculated = crc16(msg, msg_length - 2);
365355
crc_received = (msg[msg_length - 1] << 8) | msg[msg_length - 2];
366356

367357
/* Check CRC of msg */
368-
if (crc_calculated == crc_received) {
369-
return msg_length;
370-
} else {
358+
if (crc_calculated != crc_received) {
371359
if (ctx->debug) {
372360
fprintf(stderr,
373361
"ERROR CRC received 0x%0X != CRC calculated 0x%0X\n",
@@ -381,6 +369,18 @@ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, const int ms
381369
errno = EMBBADCRC;
382370
return -1;
383371
}
372+
373+
/* Filter on the Modbus unit identifier (slave) in RTU mode to avoid useless
374+
* CRC computing. */
375+
if (slave != ctx->slave && slave != MODBUS_BROADCAST_ADDRESS) {
376+
if (ctx->debug) {
377+
printf("Request for slave %d ignored (not %d)\n", slave, ctx->slave);
378+
}
379+
/* Following call to check_confirmation handles this error */
380+
return 0;
381+
}
382+
383+
return msg_length;
384384
}
385385

386386
/* Sets up a serial port for RTU communications */

0 commit comments

Comments
 (0)