From f22b06082ebe716635652ffc76ba4566e8423fbd Mon Sep 17 00:00:00 2001 From: "jonath.re@gmail.com" Date: Sat, 25 Jun 2022 17:17:34 +0200 Subject: [PATCH] Expose the function that calculates CRC Having access to this function is useful in a variety of cases: - hand-crafting PDUs for unit tests - implementing extensions of the protocol - reusing the code for other purposes (e.g. firmware integrity check) --- nanomodbus.c | 6 +++--- nanomodbus.h | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/nanomodbus.c b/nanomodbus.c index 5421ad1..cc0aef0 100644 --- a/nanomodbus.c +++ b/nanomodbus.c @@ -175,7 +175,7 @@ void nmbs_set_platform_arg(nmbs_t* nmbs, void* arg) { } -static uint16_t crc_calc(const uint8_t* data, uint32_t length) { +uint16_t nmbs_crc_calc(const uint8_t* data, uint32_t length) { uint16_t crc = 0xFFFF; for (uint32_t i = 0; i < length; i++) { crc ^= (uint16_t) data[i]; @@ -232,7 +232,7 @@ static nmbs_error recv_msg_footer(nmbs_t* nmbs) { DEBUG("\n"); if (nmbs->platform.transport == NMBS_TRANSPORT_RTU) { - uint16_t crc = crc_calc(nmbs->msg.buf, nmbs->msg.buf_idx); + uint16_t crc = nmbs_crc_calc(nmbs->msg.buf, nmbs->msg.buf_idx); nmbs_error err = recv(nmbs, 2); if (err != NMBS_ERROR_NONE) @@ -402,7 +402,7 @@ static nmbs_error send_msg(nmbs_t* nmbs) { DEBUG("\n"); if (nmbs->platform.transport == NMBS_TRANSPORT_RTU) { - uint16_t crc = crc_calc(nmbs->msg.buf, nmbs->msg.buf_idx); + uint16_t crc = nmbs_crc_calc(nmbs->msg.buf, nmbs->msg.buf_idx); put_2(nmbs, crc); } diff --git a/nanomodbus.h b/nanomodbus.h index 56e9bb0..ed9a042 100644 --- a/nanomodbus.h +++ b/nanomodbus.h @@ -226,6 +226,12 @@ void nmbs_set_byte_timeout(nmbs_t* nmbs, int32_t timeout_ms); */ void nmbs_set_platform_arg(nmbs_t* nmbs, void* arg); +/** Calculate the Modbus CRC of some data. + * @param data Data + * @param length Length of the data + */ +uint16_t nmbs_crc_calc(const uint8_t* data, uint32_t length); + #ifndef NMBS_CLIENT_DISABLED /** Set the recipient server address of the next request on RTU transport. * @param nmbs pointer to the nmbs_t instance