blob: 1faa3f62468538a49f9b9c47b2edf70836c28b7b [file] [log] [blame]
Brian Silverman003a4732018-03-11 14:02:15 -07001#include "frc971/wpilib/spi_rx_clearer.h"
2
3#include <fcntl.h>
Brian Silverman003a4732018-03-11 14:02:15 -07004#include <sys/mman.h>
5#include <unistd.h>
6
Tyler Chatowbf0609c2021-07-31 16:13:27 -07007#include <cinttypes>
8
John Park33858a32018-09-28 23:05:48 -07009#include "aos/logging/logging.h"
Brian Silverman003a4732018-03-11 14:02:15 -070010
11namespace frc971 {
12namespace wpilib {
13
14SpiRxClearer::SpiRxClearer() {
Austin Schuhf257f3c2019-10-27 21:00:43 -070015 const int fd = AOS_PCHECK(open("/dev/mem", O_RDWR));
Brian Silverman003a4732018-03-11 14:02:15 -070016 void *const mmap_result = mmap(nullptr, kMappingSize, PROT_READ | PROT_WRITE,
17 MAP_SHARED, fd, spi_peripheral_base_);
18 if (mmap_result == MAP_FAILED) {
Austin Schuhf257f3c2019-10-27 21:00:43 -070019 AOS_PLOG(FATAL, "mmap the SPI peripheral from /dev/mem failed\n");
Brian Silverman003a4732018-03-11 14:02:15 -070020 }
Austin Schuhf257f3c2019-10-27 21:00:43 -070021 AOS_PCHECK(close(fd));
Brian Silverman003a4732018-03-11 14:02:15 -070022 mapping_ = static_cast<volatile uint32_t *>(mmap_result);
23}
24
25SpiRxClearer::~SpiRxClearer() {
Austin Schuhf257f3c2019-10-27 21:00:43 -070026 AOS_PCHECK(munmap(const_cast<uint32_t *>(mapping_), kMappingSize));
Brian Silverman003a4732018-03-11 14:02:15 -070027}
28
29void SpiRxClearer::ClearRxFifo() {
30 // The FIFO has 128 entries, so if we do that many reads and don't get it all,
31 // something weird is going on.
32 for (int i = 0; i < 128; ++i) {
33 if (RxFifoIsEmpty()) {
34 // If there's nothing more, we're done.
35 return;
36 }
37 // Read the next byte.
Austin Schuhf257f3c2019-10-27 21:00:43 -070038 AOS_LOG(DEBUG, "Read from RX FIFO: %" PRIx32 "\n", ReadRegister(0x20));
Brian Silverman003a4732018-03-11 14:02:15 -070039 }
Austin Schuhf257f3c2019-10-27 21:00:43 -070040 AOS_LOG(FATAL, "Failed to clear the RX FIFO\n");
Brian Silverman003a4732018-03-11 14:02:15 -070041}
42
43} // namespace wpilib
44} // namespace frc971