Skip to content

Commit 195777f

Browse files
BootloaderTest: Refactor CRC calculation
This introduces a Crc helper class to make it easier to mix single bytes and buffers in a CRC calculation. It should not change any behaviour yet.
1 parent 5b60aee commit 195777f

2 files changed

Lines changed: 30 additions & 8 deletions

File tree

BootloaderTest/BootloaderTest.ino

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ bool write_command(uint8_t cmd, uint8_t *dataout, uint8_t len, uint8_t crc_xor =
7070
for (uint8_t i = 0; i < len; ++i)
7171
assertAck(bus.write(dataout[i]));
7272

73-
uint8_t crc = calcCrc(cmd, dataout, len);
73+
uint8_t crc = Crc().update(cmd).update(dataout, len).get();
7474
assertAck(bus.write(crc ^ crc_xor));
7575

7676
if (!cfg.repStartAfterWrite)
@@ -105,7 +105,8 @@ bool read_status(uint8_t *status, uint8_t *datain, uint8_t okLen, uint8_t failLe
105105
else
106106
assertAck(bus.readThenNack(crc));
107107

108-
assertEqual(crc, calcCrc(*status, datain, expectedLen));
108+
uint8_t expectedCrc = Crc().update(*status).update(datain, expectedLen).get();
109+
assertEqual(crc, expectedCrc);
109110
if (!cfg.repStartAfterRead)
110111
bus.stop();
111112
return true;

BootloaderTest/Util.h

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,30 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3838
#define assertAck(result) assertEqual(result, SoftWire::ack)
3939
#define assertOk(status) assertEqual(status, Status::COMMAND_OK)
4040

41-
inline uint8_t calcCrc(uint8_t first, uint8_t *rest, uint8_t len) {
42-
uint8_t crc = _crc8_ccitt_update(0xff, first);
43-
for (uint8_t i = 0; i < len; ++i)
44-
crc = _crc8_ccitt_update(crc, rest[i]);
45-
return crc;
46-
}
41+
/**
42+
* Helper class to calculate crcs for transfers. To use it, create an
43+
* instance, call update() for each byte and/or buffer of bytes to
44+
* calculate the CRC over, and then call get() to get the result.
45+
* update() is chainable, so you can do e.g.:
46+
*
47+
* uint8_t crc = Crc().update(first_byte).update(rest_of_bytes, len).get();
48+
*/
49+
class Crc {
50+
public:
51+
Crc& update(uint8_t b) {
52+
this->crc = _crc8_ccitt_update(this->crc, b);
53+
return *this;
54+
}
55+
56+
Crc& update(uint8_t *buf, uint8_t len) {
57+
for (uint8_t i = 0; i < len; ++i)
58+
this->update(buf[i]);
59+
return *this;
60+
}
61+
uint8_t get() {
62+
return this->crc;
63+
}
64+
65+
private:
66+
uint8_t crc = 0xff;
67+
};

0 commit comments

Comments
 (0)