From d0ebeee0aad15e6f66e33f7ed4d06cbce29e06d0 Mon Sep 17 00:00:00 2001 From: Carles Cufi Date: Thu, 3 Feb 2022 16:51:46 +0100 Subject: [PATCH] modbus: Get rid of custom CRC16 function In previous commits the crc16_ansi() function has been made compliant with the CRC-16-ANSI aka CRC-16-MODBUS standard. Use that standard function instead of a custom one. Signed-off-by: Carles Cufi --- subsys/modbus/modbus_serial.c | 39 ++++------------------------------- 1 file changed, 4 insertions(+), 35 deletions(-) diff --git a/subsys/modbus/modbus_serial.c b/subsys/modbus/modbus_serial.c index 06e44bd2414..32aa525ad8d 100644 --- a/subsys/modbus/modbus_serial.c +++ b/subsys/modbus/modbus_serial.c @@ -26,6 +26,7 @@ LOG_MODULE_REGISTER(modbus_serial, CONFIG_MODBUS_LOG_LEVEL); #include #include #include +#include #include static void modbus_serial_tx_on(struct modbus_context *ctx) @@ -238,37 +239,6 @@ static void modbus_ascii_tx_adu(struct modbus_context *ctx) } #endif -static uint16_t modbus_rtu_crc16(uint8_t *src, size_t length) -{ - uint16_t crc = 0xFFFF; - uint8_t shiftctr; - bool flag; - uint8_t *pblock = src; - - while (length > 0) { - length--; - crc ^= (uint16_t)*pblock++; - shiftctr = 8; - do { - /* Determine if the shift out of rightmost bit is 1 */ - flag = (crc & 0x0001) ? true : false; - /* Shift CRC to the right one bit. */ - crc >>= 1; - /* - * If bit shifted out of rightmost bit was a 1 - * exclusive OR the CRC with the generating polynomial. - */ - if (flag == true) { - crc ^= MODBUS_CRC16_POLY; - } - - shiftctr--; - } while (shiftctr > 0); - } - - return crc; -} - /* Copy Modbus RTU frame and check if the CRC is valid. */ static int modbus_rtu_rx_adu(struct modbus_context *ctx) { @@ -296,8 +266,8 @@ static int modbus_rtu_rx_adu(struct modbus_context *ctx) ctx->rx_adu.crc = sys_get_le16(&cfg->uart_buf[crc_idx]); /* Calculate CRC over address, function code, and payload */ - calc_crc = modbus_rtu_crc16(&cfg->uart_buf[0], - cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc)); + calc_crc = crc16_ansi(&cfg->uart_buf[0], + cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc)); if (ctx->rx_adu.crc != calc_crc) { LOG_WRN("Calculated CRC does not match received CRC"); @@ -320,8 +290,7 @@ static void rtu_tx_adu(struct modbus_context *ctx) memcpy(data_ptr, ctx->tx_adu.data, ctx->tx_adu.length); - ctx->tx_adu.crc = modbus_rtu_crc16(&cfg->uart_buf[0], - ctx->tx_adu.length + 2); + ctx->tx_adu.crc = crc16_ansi(&cfg->uart_buf[0], ctx->tx_adu.length + 2); sys_put_le16(ctx->tx_adu.crc, &cfg->uart_buf[ctx->tx_adu.length + 2]); tx_bytes += 2;