diff --git a/firmware/util/math/crc8hondak.cpp b/firmware/util/math/crc8hondak.cpp new file mode 100644 index 0000000000..f0bf577ac3 --- /dev/null +++ b/firmware/util/math/crc8hondak.cpp @@ -0,0 +1,41 @@ +#include +#include + +#include "crc8hondak.h" + +static inline uint8_t crc_init(void) +{ + return 0xff; +} + +static inline uint8_t crc_next(uint8_t crc, uint8_t data) +{ + uint8_t eor; + unsigned int i = 8; + + crc ^= data; + do { + /* This might produce branchless code */ + eor = crc & 1 ? 0xb8 : 0; + crc >>= 1; + crc ^= eor; + } while (--i); + + return crc; +} + +static inline uint8_t crc_final(uint8_t crc) +{ + return ~crc; +} + +uint8_t crc_hondak_calc(const uint8_t *data, size_t len) +{ + uint8_t crc = crc_init(); + + if (len) do { + crc = crc_next(crc, *data++); + } while (--len); + + return crc_final(crc); +} diff --git a/firmware/util/math/crc8hondak.h b/firmware/util/math/crc8hondak.h new file mode 100644 index 0000000000..fe427dc90e --- /dev/null +++ b/firmware/util/math/crc8hondak.h @@ -0,0 +1,19 @@ +/* + * crc8hondak.h + * + * Code generated by universal_crc by Danjel McGougan + * + * matches CRC8_EBU with 0xFF OutXor + * + * CRC parameters used: + * bits: 8 + * poly: 0x1d + * init: 0xff + * xor: 0xff + * reverse: true + * non-direct: false + * + * CRC of the string "123456789" is 0x68 + */ + +uint8_t crc_hondak_calc(const uint8_t *data, size_t len); diff --git a/firmware/util/util.mk b/firmware/util/util.mk index a1563bb225..c71723a71c 100644 --- a/firmware/util/util.mk +++ b/firmware/util/util.mk @@ -12,6 +12,7 @@ UTILSRC_CPP = \ $(UTIL_DIR)/math/error_accumulator.cpp \ $(UTIL_DIR)/math/efi_pid.cpp \ $(UTIL_DIR)/math/interpolation.cpp \ + $(UTIL_DIR)/math/crc8hondak.cpp \ $(PROJECT_DIR)/util/datalogging.cpp \ $(PROJECT_DIR)/util/loggingcentral.cpp \ $(PROJECT_DIR)/util/cli_registry.cpp \ diff --git a/unit_tests/tests/util/test_honda_crc.cpp b/unit_tests/tests/util/test_honda_crc.cpp new file mode 100644 index 0000000000..8611f85861 --- /dev/null +++ b/unit_tests/tests/util/test_honda_crc.cpp @@ -0,0 +1,15 @@ +#include "pch.h" +#include "crc8hondak.h" + + +TEST(util, crc8hondak) { + const uint8_t data[] = {0x1, 0, 0}; + + ASSERT_EQ(140, crc_hondak_calc(data, 3)); +} + +// https://rusefi.com/forum/viewtopic.php?p=47283#p47283 +TEST(util, crc8hondak_2) { + const uint8_t data[] = {0, 0xD0, 0x06, 0}; + ASSERT_EQ(0x62, crc_hondak_calc(data, 4)); +} diff --git a/unit_tests/tests/util/test_util.mk b/unit_tests/tests/util/test_util.mk index e54a9337e3..b5e0e3651b 100644 --- a/unit_tests/tests/util/test_util.mk +++ b/unit_tests/tests/util/test_util.mk @@ -3,6 +3,7 @@ CPPSRC += $(PROJECT_DIR)/../unit_tests/tests/util/test_buffered_writer.cpp \ $(PROJECT_DIR)/../unit_tests/tests/util/test_error_accumulator.cpp \ $(PROJECT_DIR)/../unit_tests/tests/util/test_exp_average.cpp \ + $(PROJECT_DIR)/../unit_tests/tests/util/test_honda_crc.cpp \ $(PROJECT_DIR)/../unit_tests/tests/util/test_hash.cpp \ INCDIR += $(PROJECT_DIR)/controllers/system