/* The check_crc16 function shall return the message length if the CRC is valid. Otherwise it shall return -1 and set errno to EMBADCRC. */ int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length) { uint16_t crc_calculated; uint16_t crc_received; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; ctx->last_crc_expected = crc_calculated; ctx->last_crc_received = crc_received; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { if (ctx->debug) { fprintf(stderr, "ERROR CRC received %0X != CRC calculated %0X\n", crc_received, crc_calculated); } if (ctx->error_recovery) { _modbus_rtu_flush(ctx); } errno = EMBBADCRC; return -1; } }
/* The check_crc16 function shall return 0 is the message is ignored and the message length if the CRC is valid. Otherwise it shall return -1 and set errno to EMBADCRC. */ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length) { uint16_t crc_calculated; uint16_t crc_received; int slave = msg[0]; /* Filter on the Modbus unit identifier (slave) in RTU mode to avoid useless * CRC computing. */ if (slave != ctx->slave && slave != MODBUS_BROADCAST_ADDRESS) { if (ctx->debug) { printf("Request for slave %d ignored (not %d)\n", slave, ctx->slave); } /* Following call to check_confirmation handles this error */ return 0; } crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; ctx->last_crc_expected = crc_calculated; ctx->last_crc_received = crc_received; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { if (ctx->debug) { fprintf(stderr, "ERROR CRC received %0X != CRC calculated %0X\n", crc_received, crc_calculated); } if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _modbus_rtu_flush(ctx); } errno = EMBBADCRC; return -1; } }
/* The check_crc16 function shall return 0 is the message is ignored and the message length if the CRC is valid. Otherwise it shall return -1 and set errno to EMBADCRC. */ int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length) { uint16_t crc_calculated; uint16_t crc_received; int slave = msg[0]; /* Filter on the Modbus unit identifier (slave) in RTU mode */ if (slave != ctx->slave && slave != MODBUS_BROADCAST_ADDRESS) { /* Ignores the request (not for me) */ if (ctx->debug) { printf("Request for slave %d ignored (not %d)\n", slave, ctx->slave); } return 0; } crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { if (ctx->debug) { fprintf(stderr, "ERROR CRC received %0X != CRC calculated %0X\n", crc_received, crc_calculated); } if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _modbus_rtu_flush(ctx); } errno = EMBBADCRC; return -1; } }