Skip to content

Commit

Permalink
Function to verify CRC, #75
Browse files Browse the repository at this point in the history
Signed-off-by: Sara Damiano <sdamiano@stroudcenter.org>
  • Loading branch information
SRGDamia1 committed Sep 22, 2023
1 parent 9389a7b commit f525628
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/SDI12.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <CR> and <LF> (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.
Expand Down
10 changes: 10 additions & 0 deletions src/SDI12.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
*
Expand Down

0 comments on commit f525628

Please sign in to comment.