forked from iphong/lib-esp-rc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProtocol.h
129 lines (114 loc) · 2.67 KB
/
Protocol.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "Arduino.h"
#include "Stream.h"
typedef void (*TransportReceiveCallback)(uint8_t *data, uint8_t size);
class Transport
{
public:
virtual void begin();
virtual void end();
virtual void send(uint8_t *data, uint8_t size);
virtual void receive(TransportReceiveCallback *fn);
protected:
TransportReceiveCallback *_onReceive;
};
class SerialTransport: public Transport {
void send(uint8_t *data, uint8_t size) {
}
};
class LoraTransport : public Transport
{
void send(uint8_t *data, uint8_t size)
{
}
};
Transport *transport = new SerialTransport;
class RcProtocol;
class RcTransport
{
protected:
RcProtocol *_protocol;
public:
RcTransport(RcProtocol *p) : _protocol(p)
{
}
virtual void begin();
virtual void send();
virtual void receive();
};
class RcProtocol : public Print
{
protected:
uint8_t syncWord = 0x81;
uint8_t _buffer[250];
size_t _length = 0;
bool synced = false;
RcTransport *_transport;
public:
RcProtocol()
{
memset(_buffer, 0xff, 250);
}
void begin()
{
_transport = new RcTransport(this);
}
size_t write(uint8_t c)
{
_buffer[_length++] = c;
return 1;
}
void decode()
{
if (!_length)
return;
Serial.println("decode");
Serial.printf(" %u %u \n", _length, _buffer[0]);
if (!synced && syncWord != _buffer[0])
return;
Serial.println("synced");
if (_length >= 2)
{
uint8_t size = _buffer[1];
Serial.printf("has size %u \n", size);
if (_length >= size + 3)
{
uint8_t crc = _buffer[size + 3];
uint8_t sum = checksum(&_buffer[2], size - 1);
Serial.printf("has size %02X %02X \n", crc, sum);
if (sum == crc)
{
_length = 0;
}
}
}
}
void encode(uint8_t *data, uint8_t size)
{
uint8_t sum = 0xff;
uint8_t payload[size + 3];
payload[0] = syncWord;
payload[1] = size + 1;
for (auto i = 0; i < size; i++)
{
sum += data[i];
payload[i + 2] = data[i];
}
payload[size + 2] = sum;
for (auto i = 0; i < size + 3; i++)
{
Serial.printf("%02X\t", payload[i]);
write(payload[i]);
}
Serial.println();
decode();
}
uint8_t checksum(uint8_t *data, uint8_t size)
{
uint8_t sum = 0xff;
for (int i = 0; i < size; i++)
{
sum += data[i];
}
return sum;
}
};