2022-07-20 03:07:00 -04:00
|
|
|
// Copyright 2020 Mobilinkd LLC.
|
2022-06-06 21:22:18 -04:00
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cstdint>
|
|
|
|
#include <array>
|
|
|
|
#include <cstddef>
|
|
|
|
|
2022-07-04 17:03:07 -04:00
|
|
|
namespace modemm17
|
2022-06-06 21:22:18 -04:00
|
|
|
{
|
|
|
|
|
|
|
|
struct CRC16
|
|
|
|
{
|
2022-07-27 12:15:47 -04:00
|
|
|
static const uint16_t MASK = 0xFFFF;
|
|
|
|
static const uint16_t LSB = 0x0001;
|
|
|
|
static const uint16_t MSB = 0x8000;
|
2022-06-06 21:22:18 -04:00
|
|
|
|
2022-07-27 12:15:47 -04:00
|
|
|
|
|
|
|
CRC16(uint16_t poly = 0x5935, uint16_t init = 0xFFFF) :
|
|
|
|
poly_(poly),
|
|
|
|
init_(init)
|
|
|
|
{
|
|
|
|
reg_ = init_;
|
|
|
|
}
|
2022-06-06 21:22:18 -04:00
|
|
|
|
|
|
|
void reset()
|
|
|
|
{
|
2022-07-27 12:15:47 -04:00
|
|
|
reg_ = init_;
|
2022-06-06 21:22:18 -04:00
|
|
|
|
|
|
|
for (size_t i = 0; i != 16; ++i)
|
|
|
|
{
|
|
|
|
auto bit = reg_ & LSB;
|
2022-07-27 12:15:47 -04:00
|
|
|
if (bit) reg_ ^= poly_;
|
2022-06-06 21:22:18 -04:00
|
|
|
reg_ >>= 1;
|
|
|
|
if (bit) reg_ |= MSB;
|
|
|
|
}
|
|
|
|
|
|
|
|
reg_ &= MASK;
|
|
|
|
}
|
|
|
|
|
|
|
|
void operator()(uint8_t byte)
|
|
|
|
{
|
|
|
|
reg_ = crc(byte, reg_);
|
|
|
|
}
|
|
|
|
|
|
|
|
uint16_t crc(uint8_t byte, uint16_t reg)
|
|
|
|
{
|
|
|
|
for (size_t i = 0; i != 8; ++i)
|
|
|
|
{
|
|
|
|
auto msb = reg & MSB;
|
|
|
|
reg = ((reg << 1) & MASK) | ((byte >> (7 - i)) & LSB);
|
2022-07-27 12:15:47 -04:00
|
|
|
if (msb) reg ^= poly_;
|
2022-06-06 21:22:18 -04:00
|
|
|
}
|
|
|
|
return reg & MASK;
|
|
|
|
}
|
2022-07-04 17:03:07 -04:00
|
|
|
|
2022-06-06 21:22:18 -04:00
|
|
|
uint16_t get()
|
|
|
|
{
|
|
|
|
auto reg = reg_;
|
|
|
|
for (size_t i = 0; i != 16; ++i)
|
|
|
|
{
|
|
|
|
auto msb = reg & MSB;
|
|
|
|
reg = ((reg << 1) & MASK);
|
2022-07-27 12:15:47 -04:00
|
|
|
if (msb) reg ^= poly_;
|
2022-06-06 21:22:18 -04:00
|
|
|
}
|
|
|
|
return reg;
|
|
|
|
}
|
2022-07-04 17:03:07 -04:00
|
|
|
|
2022-06-06 21:22:18 -04:00
|
|
|
std::array<uint8_t, 2> get_bytes()
|
|
|
|
{
|
|
|
|
auto crc = get();
|
|
|
|
std::array<uint8_t, 2> result{uint8_t((crc >> 8) & 0xFF), uint8_t(crc & 0xFF)};
|
|
|
|
return result;
|
|
|
|
}
|
2022-07-27 12:15:47 -04:00
|
|
|
|
|
|
|
private:
|
|
|
|
uint16_t poly_;
|
|
|
|
uint16_t init_;
|
|
|
|
uint16_t reg_;
|
2022-06-06 21:22:18 -04:00
|
|
|
};
|
|
|
|
|
2022-07-04 17:03:07 -04:00
|
|
|
} // modemm17
|