Files
MinumelArmMCU/UartHandler.hpp
T

50 lines
1.6 KiB
C++
Raw Normal View History

#pragma once
#include <Arduino.h>
constexpr uint8_t PACKET_SIZE = 16;
constexpr uint8_t PACKET_RINGBUF_SIZE = 16;
// Will parse serial messages using the serial interface supplied by the dev board
// Expects packets of at max 16 bytes.
// Terminating byte must be 0x0A.
// Singleton-class
class UartHandler
{
public:
static UartHandler& getInstance();
// Will attempt to initialize the serial port, returns status.
// May block up to 1000ms.
bool init(const uint32_t baudRate);
void close();
void poll();
// Will write the next available whole line into char* (provide at least 16 bytes!)
// Returns whether any data was written.
// If data available is longer than 16 bytes, an error will be raised.
bool getNextPacket(char* dest);
// Returns how many packets are ready for reading
uint8_t getNumAvailablePackets() const;
bool isOpen() const noexcept;
private:
// Will move the current contents of inBuf into packetRingBuf. Does NOT reset inBufPos!
void pushPacket();
UartHandler() noexcept;
UartHandler(const UartHandler&) = delete;
UartHandler(UartHandler&&) = delete;
~UartHandler();
// By spec, packets will not exceed 16 bytes
uint8_t inBuf[PACKET_SIZE];
uint8_t inBufPos = 0;
uint8_t packetRingBuf[PACKET_RINGBUF_SIZE * PACKET_SIZE];
uint8_t packetRingBufReadPos = 0; // 0 to PACKET_RINGBUF_SIZE
uint8_t packetRingBufWritePos = 0; // 0 to PACKET_RINGBUF_SIZE
uint8_t numPacketsAvailable = 0;
};