2025-12-13 20:23:28 +01:00
|
|
|
#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.
|
2025-12-13 20:23:28 +01:00
|
|
|
// Singleton-class
|
|
|
|
|
class UartHandler
|
|
|
|
|
{
|
|
|
|
|
public:
|
2025-12-15 20:22:28 +01:00
|
|
|
static UartHandler& getInstance() noexcept;
|
2025-12-13 20:23:28 +01:00
|
|
|
|
|
|
|
|
// Will attempt to initialize the serial port, returns status.
|
|
|
|
|
// May block up to 1000ms.
|
|
|
|
|
bool init(const uint32_t baudRate);
|
|
|
|
|
|
|
|
|
|
void close();
|
|
|
|
|
|
2025-12-15 20:22:28 +01:00
|
|
|
void poll() noexcept;
|
2025-12-13 20:23:28 +01:00
|
|
|
// 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.
|
2025-12-15 20:22:28 +01:00
|
|
|
bool getNextPacket(char* dest) noexcept;
|
|
|
|
|
|
|
|
|
|
size_t send(const char* buf, size_t nbytes);
|
|
|
|
|
size_t send(const String& str);
|
2025-12-13 20:23:28 +01:00
|
|
|
|
|
|
|
|
// Returns how many packets are ready for reading
|
2025-12-15 20:22:28 +01:00
|
|
|
uint8_t getNumAvailablePackets() const noexcept;
|
2025-12-13 20:23:28 +01:00
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
2025-12-13 20:23:28 +01:00
|
|
|
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;
|
|
|
|
|
};
|