openEmbroider  0.1
an open source embroidery software
uart.hpp
1 #pragma once
2 
3 #include <inttypes.h>
4 #include "crc16.hpp"
5 
6 template<unsigned packetSize>
7 class UartBlock
8 {
9 public:
10  static const unsigned kPacketSize=packetSize;
11  UartBlock() : qosMsg(0), qosSync(0), qosFullSync(0), pos(0) { }
12  virtual void onMsg(uint8_t* buffer) = 0;
13  virtual void send(const uint8_t* buffer, unsigned len) = 0;
14  void onChar(uint8_t c)
15  {
16  if (!(pos || (c==kMarker)))
17  return;
18  buffer[pos++] = c;
19  if (pos != kPacketSize)
20  return;
21  uint16_t packetCrc = (buffer[kPacketSize-2]<<8)+buffer[kPacketSize-1];
22  if (packetCrc == CRC16::compute(buffer+1, kPacketSize-3)) {
23  qosMsg++;
24  onMsg(buffer+1);
25  pos = 0;
26  } else {
27  unsigned i = 1;
28  while ((i<kPacketSize) && (buffer[i]!=kMarker))
29  i++;
30  for (unsigned j=0; j<kPacketSize-i; j++)
31  buffer[j] = buffer[j+i];
32  pos = kPacketSize - i;
33  if (pos)
34  qosSync++;
35  else
36  qosFullSync++;
37  }
38  }
39 
40  void sendMsg(const uint8_t* buffer)
41  {
42  uint8_t b = kMarker;
43  send(&b, 1);
44  send(buffer, kPacketSize-3);
45  uint16_t packetCrc = CRC16::compute(buffer, kPacketSize-3);
46  b = packetCrc >> 8;
47  send(&b, 1);
48  b = packetCrc & 0xff;
49  send(&b, 1);
50  }
51 
52  unsigned long qosMsg;
53  unsigned long qosSync;
54  unsigned long qosFullSync;
55 
56 private:
57  static const uint8_t kMarker = 0x3A;
58 
59  uint8_t buffer[kPacketSize];
60  uint8_t pos;
61 };
Definition: uart.hpp:7