From f525628ef13bb6fefd52485c6cdaa3303ea7fb4d Mon Sep 17 00:00:00 2001 From: Sara Damiano Date: Fri, 22 Sep 2023 12:42:28 -0400 Subject: [PATCH] Function to verify CRC, #75 Signed-off-by: Sara Damiano --- src/SDI12.cpp | 23 +++++++++++++++++++++++ src/SDI12.h | 10 ++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/SDI12.cpp b/src/SDI12.cpp index 35abc20..5c73dc6 100644 --- a/src/SDI12.cpp +++ b/src/SDI12.cpp @@ -632,6 +632,29 @@ String SDI12::crcToString(uint16_t crc) { return (String(crcStr[0]) + String(crcStr[1]) + String(crcStr[2])); } +bool SDI12::verifyCRC(String& respWithCRC) { + uint16_t nChar = respWithCRC.length() - + 2; // number of characters without and (readable string composed of + // sensor address, values separated by + and -) and the 3 characters + String recCRC = ""; // the CRC portion of the response + String recString = ""; // the data portion of the response + + // extract the data portion of the string + for (int i = 0; i < (nChar - 3); i++) recString += respWithCRC[i]; + + // extract the last 3 characters that are the CRC from the full response string + for (int i = (nChar - 3); i < nChar; i++) recCRC += respWithCRC[i]; + + // calculate the CRC for the data portion + String calcCRC = crcToString(calculateCRC(recString)); + + if (recCRC == calcCRC) { + return false; + } else { + return true; + } +} + /* ================ Interrupt Service Routine =======================================*/ // 7.1 - Passes off responsibility for the interrupt to the active object. diff --git a/src/SDI12.h b/src/SDI12.h index bbb8ab2..a376031 100644 --- a/src/SDI12.h +++ b/src/SDI12.h @@ -934,6 +934,16 @@ class SDI12 : public Stream { */ String crcToString(uint16_t crc); + /** + * @brief Verifies that the CRC returned at the end of an SDI-12 message matches that + * of the content of the message. + * + * @param respWithCRC The full SDI-12 message, including the CRC at the end. + * @return *true* The CRC matches and the message is valid + * @return *false* The CRC doesn't match; the conversation should be retried. + */ + bool verifyCRC(String& respWithCRC); + /** * @brief Send a response out on the data line (for slave use) *