From 1e127de5173e3b8fb62efc79f97651ca22694441 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 19 Feb 2019 22:09:04 +0000 Subject: Validate CRC of incoming data The data sent with Set_Report requests contains a CRC which we so far ignored. This patch adds a Crc struct that uses the CRC peripheral to calculate the CRC for some data and uses it to validate the CRC of the received data. --- src/crc.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/crc.rs (limited to 'src/crc.rs') diff --git a/src/crc.rs b/src/crc.rs new file mode 100644 index 0000000..cfcf982 --- /dev/null +++ b/src/crc.rs @@ -0,0 +1,40 @@ +// Copyright 2019 Robin Krahl +// SPDX-License-Identifier: GPL-3.0-or-later + +use hal::stm32::CRC; + +pub struct Crc { + crc: CRC, +} + +impl Crc { + pub fn new(crc: CRC) -> Self { + Crc { crc } + } + + pub fn get(&self, data: &[u8]) -> u32 { + self.reset(); + data.chunks(4) + .map(slice_to_u32) + .for_each(|val| self.write(val)); + self.read() + } + + fn write(&self, val: u32) { + self.crc.dr.write(|w| w.dr().bits(val)); + } + + fn read(&self) -> u32 { + self.crc.dr.read().dr().bits() + } + + fn reset(&self) { + self.crc.cr.write(|w| w.reset().reset()); + } +} + +fn slice_to_u32(data: &[u8]) -> u32 { + data.iter() + .enumerate() + .fold(0, |acc, (idx, val)| acc + (u32::from(*val) << (idx * 8))) +} -- cgit v1.2.1