Listening for packets¶
-
typedef PacketListener_
packetio::
PacketListener
¶ Convenience typedef for a PacketListener with a sensible buffer size.
-
template <size_t BufferSize = 256>
classpacketio::
PacketListener_
¶ Class for listening for packets on a PacketStream.
- Template Parameters
BufferSize
: The size of the buffer to allocate for incoming packets
Public Types
-
enum
Error
¶ Types of error that can occur when receiving a packet.
Values:
-
Overflow
¶ The end of the message could not be recieved because the buffer overflowed.
-
Framing
¶ The message was framed incorrectly.
-
-
typedef LambdaPointer<void(uint8_t *, size_t)>
MessageHandler
¶
Public Functions
-
PacketListener_
(PacketStream &base)¶ Construct a listener for the given packet stream.
-
void
update
()¶ Read as much as possible from the underlying stream. If new packets are completed or errors occur, invoke the appropriate handler.
-
void
onMessage
(MessageHandler handler)¶ Set the handler to invoke when a message is recieved.
Note that because this is a LambdaPointer, the lambda function must have been allocated on the stack, such that its lifetime exceeds that of this object.
- Parameters
handler
: The handler to invoke. This will be called with the pointer to the start of the message, and its length.
-
void
onError
(ErrorHandler handler)¶ Set the handler to invoke when an error occurs.
Note that because this is a LambdaPointer, the lambda function must have been allocated on the stack, such that its lifetime exceeds that of this object.
- Parameters
handler
: The handler to invoke. This will be called with the pointer to the start of the message, and its length.
Example usage:
#include <packet_interface.h>
#include <PacketListener.h>
#include <cobs/Stream.h>
using namespace packetio;
void setup () {
COBSStream cobs_serial_in(Serial);
PacketListener handler(cobs_serial_in);
int message_count = 0;
auto message_handler = [&](const uint8_t* buffer, size_t len) {
message_count++;
};
handler.onMessage(&message_handler);
while(true) {
handler.update();
Serial.print("Message recieved: ");
Serial.print(message_count);
Serial.println();
}
}