Fix modbus CRC calculation (#789)

* Fix modbus CRC calculation

Fixes https://github.com/esphome/feature-requests/issues/49#issuecomment-545045776

* Fix
This commit is contained in:
Otto Winter 2019-10-22 22:56:34 +02:00
parent dcb4a0a81e
commit c27fd0f01a
No known key found for this signature in database
GPG Key ID: DB66C0BE6013F97E

View File

@ -24,7 +24,7 @@ void Modbus::loop() {
} }
} }
uint16_t crc16(uint8_t *data, uint8_t len) { uint16_t crc16(const uint8_t *data, uint8_t len) {
uint16_t crc = 0xFFFF; uint16_t crc = 0xFFFF;
while (len--) { while (len--) {
crc ^= *data++; crc ^= *data++;
@ -43,7 +43,7 @@ uint16_t crc16(uint8_t *data, uint8_t len) {
bool Modbus::parse_modbus_byte_(uint8_t byte) { bool Modbus::parse_modbus_byte_(uint8_t byte) {
size_t at = this->rx_buffer_.size(); size_t at = this->rx_buffer_.size();
this->rx_buffer_.push_back(byte); this->rx_buffer_.push_back(byte);
uint8_t *raw = &this->rx_buffer_[0]; const uint8_t *raw = &this->rx_buffer_[0];
// Byte 0: modbus address (match all) // Byte 0: modbus address (match all)
if (at == 0) if (at == 0)
@ -69,7 +69,7 @@ bool Modbus::parse_modbus_byte_(uint8_t byte) {
return true; return true;
// Byte 3+len+1: CRC_HI (over all bytes) // Byte 3+len+1: CRC_HI (over all bytes)
uint16_t computed_crc = crc16(raw, 3 + data_len); uint16_t computed_crc = crc16(raw, 3 + data_len);
uint16_t remote_crc = uint16_t(raw[3 + data_len]) | (uint16_t(raw[3 + data_len]) << 8); uint16_t remote_crc = uint16_t(raw[3 + data_len]) | (uint16_t(raw[3 + data_len + 1]) << 8);
if (computed_crc != remote_crc) { if (computed_crc != remote_crc) {
ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc); ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc);
return false; return false;