Arduino KVComm  master
Key-Value pair communication library for Arduino
SLIPParser.ipp
Go to the documentation of this file.
1 #include "SLIPParser.hpp"
2 
3 template <class Callback>
4 size_t SLIPParser::parse(uint8_t c, Callback callback) {
5  using namespace SLIP_Constants;
6  /*
7  * handle bytestuffing if necessary
8  */
9  switch (c) {
10  /*
11  * if it's an END character then we're done with
12  * the packet
13  */
14  case END: {
15  /*
16  * a minor optimization: if there is no
17  * data in the packet, ignore it. This is
18  * meant to avoid bothering IP with all
19  * the empty packets generated by the
20  * duplicate END characters which are in
21  * turn sent to try to detect line noise.
22  */
23  auto packetLen = write - buffer;
24  escape = false;
25  reset();
26  if (packetLen)
27  return packetLen;
28  } break;
29 
30  /*
31  * if it's the same code as an ESC character, wait
32  * and get another character and then figure out
33  * what to store in the packet based on that.
34  */
35  case ESC: {
36  escape = true;
37  } break;
38 
39  /*
40  * here we fall into the default handler and let
41  * it store the character for us
42  */
43  default: {
44  if (escape) {
45  /*
46  * if "c" is not one of these two, then we
47  * have a protocol violation. The best bet
48  * seems to be to leave the byte alone and
49  * just stuff it into the packet
50  */
51  switch (c) {
52  case ESC_END: c = END; break;
53  case ESC_ESC: c = ESC; break;
54  default: break; // LCOV_EXCL_LINE (protocol violation)
55  }
56  escape = false;
57  }
58  auto writeSize = reinterpret_cast<uintptr_t>(write) -
59  reinterpret_cast<uintptr_t>(buffer);
60  callback(c, writeSize + truncated);
61  if (writeSize == 0) // first byte of packet
62  truncated = 0;
63  if (writeSize < bufferSize) {
64  *write++ = c;
65  } else {
66  truncated++;
67  }
68  }
69  }
70  return 0;
71 }
SLIPParser::buffer
uint8_t * buffer
Definition: SLIPParser.hpp:118
SLIPParser::bufferSize
size_t bufferSize
Definition: SLIPParser.hpp:120
SLIPParser::truncated
size_t truncated
Definition: SLIPParser.hpp:121
SLIP_Constants
SLIP special character codes.
Definition: SLIP.hpp:9
SLIP_Constants::ESC_END
const static uint8_t ESC_END
ESC ESC_END means END data byte.
Definition: SLIP.hpp:12
SLIPParser::parse
size_t parse(uint8_t c, Callback callback)
Parse the given byte, and call the callback for each data byte.
Definition: SLIPParser.ipp:4
SLIP_Constants::ESC_ESC
const static uint8_t ESC_ESC
ESC ESC_ESC means ESC data byte.
Definition: SLIP.hpp:13
SLIP_Constants::ESC
const static uint8_t ESC
indicates byte stuffing
Definition: SLIP.hpp:11
SLIPParser::escape
bool escape
Definition: SLIPParser.hpp:122
SLIPParser.hpp
SLIPParser::reset
void reset()
Definition: SLIPParser.hpp:115
SLIP_Constants::END
const static uint8_t END
indicates end of packet
Definition: SLIP.hpp:10
SLIPParser::write
uint8_t * write
Definition: SLIPParser.hpp:119