Files

52 lines
1.8 KiB
C++
Raw Permalink Normal View History

#pragma once
#include <Arduino.h>
// Will parse serial messages using the serial interface supplied by the dev board
2025-12-14 18:57:28 +01:00
// Expects packets must be 5 bytes.
// Singleton-class
class UartHandler
{
public:
static UartHandler& getInstance() noexcept;
// Will attempt to initialize the serial port, returns status.
// May block up to 1000ms.
bool init(const uint32_t baudRate);
void close();
void poll() noexcept;
// 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) noexcept;
size_t send(const char* buf, size_t nbytes);
size_t send(const String& str);
// Returns how many packets are ready for reading
uint8_t getNumAvailablePackets() const noexcept;
bool isOpen() const noexcept;
2025-12-14 18:57:28 +01:00
static constexpr uint8_t PACKET_SIZE = 5;
2025-12-14 12:43:31 +01:00
static constexpr uint8_t PACKET_RINGBUF_SIZE = 16;
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;
};