-
Notifications
You must be signed in to change notification settings - Fork 25
/
SoftwareSerial52.cpp
419 lines (373 loc) · 12.9 KB
/
SoftwareSerial52.cpp
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
SoftwareSerial52.cpp - Implementation of the Arduino software serial for ESP8266/ESP32.
Copyright (c) 2015-2016 Peter Lerup. All rights reserved.
Copyright (c) 2018-2019 Dirk O. Kaar. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SoftwareSerial52.h"
#include <Arduino.h>
#ifdef ESP32
#define xt_rsil(a) (a)
#define xt_wsr_ps(a)
#endif
constexpr uint8_t BYTE_ALL_BITS_SET = ~static_cast<uint8_t>(0);
SoftwareSerial52::SoftwareSerial52() {
m_isrOverflow = false;
}
SoftwareSerial52::SoftwareSerial52(int8_t rxPin, int8_t txPin)
{
m_isrOverflow = false;
m_rxPin = rxPin;
m_txPin = txPin;
}
SoftwareSerial52::~SoftwareSerial52() {
end();
}
bool SoftwareSerial52::isValidGPIOpin(int8_t pin) {
#if defined(ESP8266)
return (pin >= 0 && pin <= 5) || (pin >= 12 && pin <= 15);
#elif defined(ESP32)
return pin == 0 || pin == 2 || (pin >= 4 && pin <= 5) || (pin >= 12 && pin <= 19) ||
(pin >= 21 && pin <= 23) || (pin >= 25 && pin <= 27) || (pin >= 32 && pin <= 35);
#else
return true;
#endif
}
void SoftwareSerial52::begin(uint32_t baud, SoftwareSerial52Config config,
int8_t rxPin, int8_t txPin,
bool invert, int bufCapacity, int isrBufCapacity) {
if (-1 != rxPin) m_rxPin = rxPin;
if (-1 != txPin) m_txPin = txPin;
m_oneWire = (m_rxPin == m_txPin);
m_invert = invert;
if (isValidGPIOpin(m_rxPin)) {
std::unique_ptr<circular_queue<uint8_t> > buffer(new circular_queue<uint8_t>((bufCapacity > 0) ? bufCapacity : 64));
m_buffer = move(buffer);
std::unique_ptr<circular_queue<uint32_t> > isrBuffer(new circular_queue<uint32_t>((isrBufCapacity > 0) ? isrBufCapacity : (sizeof(uint8_t) * 8 + 2) * bufCapacity));
m_isrBuffer = move(isrBuffer);
if (m_buffer != 0 && m_isrBuffer != 0) {
m_rxValid = true;
pinMode(m_rxPin, INPUT_PULLUP);
}
}
if (isValidGPIOpin(m_txPin)
#ifdef ESP8266
|| ((m_txPin == 16) && !m_oneWire)) {
#else
) {
#endif
m_txValid = true;
if (!m_oneWire) {
pinMode(m_txPin, OUTPUT);
digitalWrite(m_txPin, !m_invert);
}
}
m_dataBits = 5 + config;
m_bit_us = (1000000 + baud / 2) / baud;
m_bitCycles = (ESP.getCpuFreqMHz() * 1000000 + baud / 2) / baud;
m_intTxEnabled = true;
if (!m_rxEnabled) { enableRx(true); }
}
void SoftwareSerial52::end()
{
enableRx(false);
m_txValid = false;
if (m_buffer) {
m_buffer.reset();
}
if (m_isrBuffer) {
m_isrBuffer.reset();
}
}
uint32_t SoftwareSerial52::baudRate() {
return ESP.getCpuFreqMHz() * 1000000 / m_bitCycles;
}
void SoftwareSerial52::setTransmitEnablePin(int8_t txEnablePin) {
if (isValidGPIOpin(txEnablePin)) {
m_txEnableValid = true;
m_txEnablePin = txEnablePin;
pinMode(m_txEnablePin, OUTPUT);
digitalWrite(m_txEnablePin, LOW);
}
else {
m_txEnableValid = false;
}
}
void SoftwareSerial52::enableIntTx(bool on) {
m_intTxEnabled = on;
}
void SoftwareSerial52::enableTx(bool on) {
if (m_txValid && m_oneWire) {
if (on) {
enableRx(false);
pinMode(m_txPin, OUTPUT);
digitalWrite(m_txPin, !m_invert);
}
else {
pinMode(m_rxPin, INPUT_PULLUP);
enableRx(true);
}
}
}
void SoftwareSerial52::enableRx(bool on) {
if (m_rxValid) {
if (on) {
m_rxCurBit = m_dataBits;
// Init to stop bit level and current cycle
m_isrLastCycle = (ESP.getCycleCount() | 1) ^ m_invert;
if (m_bitCycles >= (ESP.getCpuFreqMHz() * 1000000U) / 74880U)
attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast<void (*)(void*)>(rxBitISR), this, CHANGE);
else
attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast<void (*)(void*)>(rxBitSyncISR), this, m_invert ? RISING : FALLING);
}
else {
detachInterrupt(digitalPinToInterrupt(m_rxPin));
}
m_rxEnabled = on;
}
}
int SoftwareSerial52::read() {
if (!m_rxValid) { return -1; }
if (!m_buffer->available()) {
rxBits();
if (!m_buffer->available()) { return -1; }
}
return m_buffer->pop();
}
size_t SoftwareSerial52::readBytes(uint8_t * buffer, size_t size) {
if (!m_rxValid) { return -1; }
if (0 != (size = m_buffer->pop_n(buffer, size))) return size;
rxBits();
size = m_buffer->pop_n(buffer, size);
return (size == 0) ? -1 : size;
}
int SoftwareSerial52::available() {
if (!m_rxValid) { return 0; }
rxBits();
int avail = m_buffer->available();
if (!avail) {
optimistic_yield(10000);
}
return avail;
}
void ICACHE_RAM_ATTR SoftwareSerial52::preciseDelay(bool asyn, uint32_t savedPS) {
if (asyn)
{
if (!m_intTxEnabled) { xt_wsr_ps(savedPS); }
auto expired = ESP.getCycleCount() - m_periodStart;
auto micro_s = expired < m_periodDuration ? (m_periodDuration - expired) / ESP.getCpuFreqMHz() : 0;
delay(micro_s / 1000);
}
while ((ESP.getCycleCount() - m_periodStart) < m_periodDuration) { if (asyn) optimistic_yield(10000); }
if (asyn)
{
resetPeriodStart();
if (!m_intTxEnabled) { savedPS = xt_rsil(15); }
}
}
void ICACHE_RAM_ATTR SoftwareSerial52::writePeriod(
uint32_t dutyCycle, uint32_t offCycle, bool withStopBit, uint32_t savedPS) {
preciseDelay(false, savedPS);
if (dutyCycle) {
digitalWrite(m_txPin, HIGH);
m_periodDuration += dutyCycle;
bool asyn = withStopBit && !m_invert;
// Reenable interrupts while delaying to avoid other tasks piling up
if (asyn || offCycle) preciseDelay(asyn, savedPS);
// Disable interrupts again
}
if (offCycle) {
digitalWrite(m_txPin, LOW);
m_periodDuration += offCycle;
bool asyn = withStopBit && m_invert;
// Reenable interrupts while delaying to avoid other tasks piling up
if (asyn) preciseDelay(asyn, savedPS);
// Disable interrupts again
}
}
size_t SoftwareSerial52::write(uint8_t b) {
return write(&b, 1);
}
size_t ICACHE_RAM_ATTR SoftwareSerial52::write(const uint8_t * buffer, size_t size) {
if (m_rxValid) { rxBits(); }
if (!m_txValid) { return -1; }
if (m_txEnableValid) {
digitalWrite(m_txEnablePin, HIGH);
}
// Stop bit : LOW if inverted logic, otherwise HIGH
bool b = !m_invert;
// Force line level on entry
uint32_t dutyCycle = b;
uint32_t offCycle = m_invert;
uint32_t savedPS = 0;
if (!m_intTxEnabled) {
// Disable interrupts in order to get a clean transmit timing
savedPS = xt_rsil(15);
}
resetPeriodStart();
const uint32_t dataMask = ((1UL << m_dataBits) - 1);
for (size_t cnt = 0; cnt < size; ++cnt, ++buffer) {
bool withStopBit = true;
// push LSB start-data-stop bit pattern into uint32_t
// Stop bit : LOW if inverted logic, otherwise HIGH
uint32_t word = (!m_invert) << m_dataBits;
word |= (m_invert ? ~*buffer : *buffer) & dataMask;
// Start bit : HIGH if inverted logic, otherwise LOW
word <<= 1;
word |= m_invert;
for (int i = 0; i < m_dataBits + 2; ++i) {
bool pb = b;
b = (word >> i) & 1;
if (!pb && b) {
writePeriod(dutyCycle, offCycle, withStopBit, savedPS);
withStopBit = false;
dutyCycle = offCycle = 0;
}
if (b) {
dutyCycle += m_bitCycles;
}
else {
offCycle += m_bitCycles;
}
}
}
writePeriod(dutyCycle, offCycle, true, savedPS);
if (!m_intTxEnabled) {
// restore the interrupt state
xt_wsr_ps(savedPS);
}
if (m_txEnableValid) {
digitalWrite(m_txEnablePin, LOW);
}
return size;
}
void SoftwareSerial52::flush() {
if (!m_rxValid) { return; }
m_buffer->flush();
}
bool SoftwareSerial52::overflow() {
bool res = m_overflow;
m_overflow = false;
return res;
}
int SoftwareSerial52::peek() {
if (!m_rxValid) { return -1; }
if (!m_buffer->available()) {
rxBits();
if (!m_buffer->available()) return -1;
}
return m_buffer->peek();
}
void SoftwareSerial52::rxBits() {
int isrAvail = m_isrBuffer->available();
#ifdef ESP8266
if (m_isrOverflow.load()) {
m_overflow = true;
m_isrOverflow.store(false);
}
#else
if (m_isrOverflow.exchange(false)) {
m_overflow = true;
}
#endif
// stop bit can go undetected if leading data bits are at same level
// and there was also no next start bit yet, so one byte may be pending.
// low-cost check first
if (!isrAvail && m_rxCurBit >= -1 && m_rxCurBit < m_dataBits) {
uint32_t detectionCycles = (m_dataBits - m_rxCurBit) * m_bitCycles;
if (ESP.getCycleCount() - m_isrLastCycle > detectionCycles) {
// Produce faux stop bit level, prevents start bit maldetection
// cycle's LSB is repurposed for the level bit
rxBits(((m_isrLastCycle + detectionCycles) | 1) ^ m_invert);
}
}
m_isrBuffer->for_each([this](const uint32_t& isrCycle) { rxBits(isrCycle); });
}
void SoftwareSerial52::rxBits(const uint32_t & isrCycle) {
bool level = (m_isrLastCycle & 1) ^ m_invert;
// error introduced by edge value in LSB of isrCycle is negligible
int32_t cycles = isrCycle - m_isrLastCycle;
m_isrLastCycle = isrCycle;
uint8_t bits = cycles / m_bitCycles;
if (cycles % m_bitCycles > (m_bitCycles >> 1)) ++bits;
while (bits > 0) {
// start bit detection
if (m_rxCurBit >= m_dataBits) {
// leading edge of start bit
if (level) break;
m_rxCurBit = -1;
--bits;
continue;
}
// data bits
if (m_rxCurBit >= -1 && m_rxCurBit < (m_dataBits - 1)) {
int8_t dataBits = min(bits, static_cast<uint8_t>(m_dataBits - m_rxCurBit - 1));
m_rxCurBit += dataBits;
bits -= dataBits;
m_rxCurByte >>= dataBits;
if (level) { m_rxCurByte |= (BYTE_ALL_BITS_SET << (8 - dataBits)); }
continue;
}
// stop bit
if (m_rxCurBit == (m_dataBits - 1)) {
// Store the received value in the buffer unless we have an overflow
// if not high stop bit level, discard word
if (level)
{
m_buffer->push(m_rxCurByte >> (sizeof(uint8_t) * 8 - m_dataBits));
}
++m_rxCurBit;
// reset to 0 is important for masked bit logic
m_rxCurByte = 0;
break;
}
break;
}
}
void ICACHE_RAM_ATTR SoftwareSerial52::rxBitISR(SoftwareSerial52 * self) {
uint32_t curCycle = ESP.getCycleCount();
bool level = digitalRead(self->m_rxPin);
// Store level and cycle in the buffer unless we have an overflow
// cycle's LSB is repurposed for the level bit
if (!self->m_isrBuffer->push((curCycle | 1U) ^ !level)) self->m_isrOverflow.store(true);
}
void ICACHE_RAM_ATTR SoftwareSerial52::rxBitSyncISR(SoftwareSerial52 * self) {
uint32_t start = ESP.getCycleCount();
uint32_t wait = self->m_bitCycles - 172U;
bool level = self->m_invert;
// Store level and cycle in the buffer unless we have an overflow
// cycle's LSB is repurposed for the level bit
if (!self->m_isrBuffer->push(((start + wait) | 1U) ^ !level)) self->m_isrOverflow.store(true);
for (uint32_t i = 0; i < self->m_dataBits + 1U; ++i) {
while (ESP.getCycleCount() - start < wait) {};
wait += self->m_bitCycles;
// Store level and cycle in the buffer unless we have an overflow
// cycle's LSB is repurposed for the level bit
if (digitalRead(self->m_rxPin) != level)
{
if (!self->m_isrBuffer->push(((start + wait) | 1U) ^ level)) self->m_isrOverflow.store(true);
level = !level;
}
}
}
void SoftwareSerial52::onReceive(std::function<void(int available)> handler) {
receiveHandler = handler;
}
void SoftwareSerial52::perform_work() {
if (!m_rxValid) { return; }
rxBits();
if (receiveHandler) {
int avail = m_buffer->available();
if (avail) { receiveHandler(avail); }
}
}