Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 1 | #include "frc971/wpilib/spi_rx_clearer.h" |
| 2 | |
| 3 | #include <fcntl.h> |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 4 | #include <sys/mman.h> |
| 5 | #include <unistd.h> |
| 6 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 7 | #include <cinttypes> |
| 8 | |
John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 9 | #include "aos/logging/logging.h" |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 10 | |
| 11 | namespace frc971 { |
| 12 | namespace wpilib { |
| 13 | |
| 14 | SpiRxClearer::SpiRxClearer() { |
Austin Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 15 | const int fd = AOS_PCHECK(open("/dev/mem", O_RDWR)); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 16 | 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 Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 19 | AOS_PLOG(FATAL, "mmap the SPI peripheral from /dev/mem failed\n"); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 20 | } |
Austin Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 21 | AOS_PCHECK(close(fd)); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 22 | mapping_ = static_cast<volatile uint32_t *>(mmap_result); |
| 23 | } |
| 24 | |
| 25 | SpiRxClearer::~SpiRxClearer() { |
Austin Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 26 | AOS_PCHECK(munmap(const_cast<uint32_t *>(mapping_), kMappingSize)); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | void 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 Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 38 | AOS_LOG(DEBUG, "Read from RX FIFO: %" PRIx32 "\n", ReadRegister(0x20)); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 39 | } |
Austin Schuh | f257f3c | 2019-10-27 21:00:43 -0700 | [diff] [blame] | 40 | AOS_LOG(FATAL, "Failed to clear the RX FIFO\n"); |
Brian Silverman | 003a473 | 2018-03-11 14:02:15 -0700 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | } // namespace wpilib |
| 44 | } // namespace frc971 |