Repository navigation
Expand file tree
/
Copy pathConsole.cpp
More file actions
645 lines (570 loc) · 15 KB
/
Copy pathConsole.cpp
File metadata and controls
645 lines (570 loc) · 15 KB
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
Console code - Scott Penrose <[email protected]>
Map console to multiple outputs. Use Printf and a buffer. Automatically
support PROGMEM (Flash memory), String object and char pointers.
* XXX This should be callbacks
* NMEA Strings updated - do This
* Etc
* XXX Binary is almost certainly out by one start/end or both
* XXX Write test code that sends streams:
* NMEA - obvious one
* @CSV
* !Binary
Console console();
void setup() {
SerialConsole.begin(115200);
console.begin();
console.add(&SerialConsole);
console.printf(F("Hello world"));
* Rename to something better than console
* Release open source on github Sh3d
* Add print from SD card - ability to get and print data form a SD card out
* Add print from PROGMEM arrays
* Add print from SPIFlash
NOTE on NMEA devices
* NMEA is always processed from incoming data on the consoles
* If a second "TinyGPS++" is required, you can addNmea stream instead
* OR even better, just add a stream as add(&HWSerial, CONSOLE_DIRECTION_INPUT);
Restructure to simpler methods:
* BEFORE
= Sketch size 15378
* AFTER
= Sketch size 15046 (saved 340 bytes)
Restructure to error numbers:
* Sh3dNodeErrors
* console.error(n)
* console.safeError(n)
* uint16_t - 01..65 modules split, 1000 message per module
* Could we add an optional long?
*/
#include "Arduino.h"
#include <WII5Sh3dConsole.h>
#include <TimeLib.h>
#include <MemoryFree.h>
// printf support
// Just a string
void WII5Sh3dConsole::print(char *out) {
for(byte i = 0; i < CONSOLE_STREAMS; i++) {
if (
streams[i]
&& (
(streamsDirection[i] == CONSOLE_DIRECTION_BOTH)
|| (streamsDirection[i] == CONSOLE_DIRECTION_OUTPUT)
)
) {
streams[i]->print(out);
#ifdef CONSOLE_DEBUG_FLUSH
streams[i]->flush();
#endif
}
}
}
// sprintf - STREAM printf
void WII5Sh3dConsole::sprintf(Stream *s, const __FlashStringHelper *out, ... ) {
if (!check()) return;
va_list argptr;
va_start(argptr, out);
VSNPRINTF(printBuffer, bufferMax, (const char *)out, argptr);
va_end(argptr);
s->print(printBuffer);
}
// printf support
void WII5Sh3dConsole::printf(char* out, ...) {
if (!check()) return;
va_list argptr;
va_start(argptr, out);
vsnprintf(printBuffer, bufferMax, out, argptr);
va_end(argptr);
print(printBuffer);
}
// Convert FLASH String to String
void WII5Sh3dConsole::printf(const __FlashStringHelper *out, ... ){
if (!check()) return;
va_list argptr;
va_start(argptr, out);
VSNPRINTF(printBuffer, bufferMax, (const char *)out, argptr);
va_end(argptr);
print(printBuffer);
}
// TODO Move to Sh3dNodeErrors
void WII5Sh3dConsole::printPrefix(uint8_t level) {
switch(level) {
case LOG_INFO:
printf(F(CONSOLE_PRE_INFO));
break;
case LOG_WARN:
printf(F(CONSOLE_PRE_WARN));
break;
case LOG_ERROR:
printf(F(CONSOLE_PRE_ERROR));
break;
case LOG_DEBUG:
printf(F(CONSOLE_PRE_DEBUG));
break;
case LOG_FATAL:
printf(F(CONSOLE_PRE_FATAL));
break;
default:
// Do we need unknown?
break;
}
printDateTime();
printf(F(CONSOLE_POST_TIME));
}
// printf support
void WII5Sh3dConsole::log(uint8_t l, char* out, ...) {
if (level < l) return;
if (!check()) return;
printPrefix(l);
va_list argptr;
va_start(argptr, out);
vsnprintf(printBuffer, bufferMax, out, argptr);
va_end(argptr);
print(printBuffer);
printNewLine();
}
// Convert FLASH String to String
void WII5Sh3dConsole::log(uint8_t l, const __FlashStringHelper *out, ... ){
if (level < l) return;
if (!check()) return;
printPrefix(l);
va_list argptr;
va_start(argptr, out);
VSNPRINTF(printBuffer, bufferMax, (const char *)out, argptr);
va_end(argptr);
print(printBuffer);
printNewLine();
}
// TODO - Compile time option to remove unused entries - e.g We may not support String
void WII5Sh3dConsole::safeLog(uint8_t l, char* out, ...) {
if (!check()) return;
printPrefix(l);
va_list argptr;
va_start(argptr, out);
vsnprintf(printBuffer, bufferMax, out, argptr);
va_end(argptr);
print(printBuffer);
printNewLine();
flush();
}
void WII5Sh3dConsole::safeLog(uint8_t l, const __FlashStringHelper *out, ... ){
if (!check()) return;
printPrefix(l);
va_list argptr;
va_start(argptr, out);
VSNPRINTF(printBuffer, bufferMax, (const char *)out, argptr);
va_end(argptr);
print(printBuffer);
printNewLine();
flush();
}
void WII5Sh3dConsole::printDateTime(uint32_t t) {
if (t == 0) {
if (!displayDateTime) return; // Automatic mode
#ifdef _Time_h
t = now();
#endif
}
// uint16_t - date.year,
// uint8_t - date.month, date.day,
// uint8_t - time.hour, time.minute, time.second
sprintf_P(printBuffer, PSTR("%04d-%02d-%02dT%02d:%02d:%02d"),
year(t),
int(month(t)),
int(day(t)),
int(hour(t)),
int(minute(t)),
int(second(t))
);
print(printBuffer);
}
void WII5Sh3dConsole::loop() {
// Reset cmd
if (cmd) {
cmdCount = 0;
csv_count = 0;
csv_last = 0;
cmdType = 0;
cmd = '\0';
}
// Reset Binary
if (binAvailable) {
binAvailable = false;
binReceiveCount = 0;
}
for(byte i = 0; i < CONSOLE_STREAMS; i++) {
// NOTE - while important, but can be too much - limit?
if (
(streamsDirection[i] == CONSOLE_DIRECTION_BOTH)
|| (streamsDirection[i] == CONSOLE_DIRECTION_INPUT)
) {
while (streams[i] && streams[i]->available())
processCmd(streams[i]->read());
}
}
}
void WII5Sh3dConsole::processCsv() {
// XXX check for csv_count max and cmdCount max Etc
// Point to the start of the last strinb before the comma
csv_str[csv_count] = &cmdBuffer[csv_last];
// Null the ','
cmdBuffer[cmdCount] = '\0';
// Parse to ingeger
csv_uint32[csv_count] = atol(csv_str[csv_count]);
// Next character
csv_last = cmdCount + 1;
// console.log(LOG_DEBUG, F("CSV found comma last=%d, count=%d, str=%s, lu=%lu"), int(csv_last), int(csv_count), csv_str[csv_count], csv_uint32[csv_count]);
csv_count++;
}
// processCmd
void WII5Sh3dConsole::processCmd(char in) {
// DO Timeout
if ( (cmdCount > 0) && (waitInput > CONSOLE_TIMEOUT) ) {
printf(F("# CONSOLE: Timeout for new Serial Command. Max time = %d seconds"), int(CONSOLE_TIMEOUT / 1000));
printNewLine();
cmdCount = 0;
binAvailable = false;
binReceiveCount = 0;
}
// BINARY Data mode - keep here
if (binEnable && (cmdType == CONSOLE_TYPE_BINDATA_ID)) {
if (cmdCount == 0) {
printf(F("# FATAL ERROR - Must not be in BINDATA mode with no count, Invalid mode")); printNewLine();
cmdCount = 0;
cmdType = 0;
}
binBuffer[binReceiveCount] = in;
binReceiveCount++;
if (binReceiveCount >= binReceiveExpect) {
// COMPLETE !
cmdType = 0;
cmdCount = 0;
binAvailable = true;
return;
}
if (binReceiveCount >= binMax) {
// XXX This should NOT be allowed to happen - since we check below
safeLog(LOG_FATAL, F("CONSOLE: Binary incoming data too large"));
cmdCount = 0;
cmd = '\0';
val = 0;
csv_last = 0;
csv_count = 0;
binReceiveCount = 0;
}
// Rest of function is TEXT processing - leave now
return;
}
// TEXT Mode - NOT a new line, keep data
if ( (in != '\n') && (in != '\r') ) {
// First character - see if it is $
if ( (cmdCount == 0) ) {
// Reset timeout
waitInput = 0;
// $ = NMEA = 1
if (in == CONSOLE_TYPE_NMEA_C0) {
cmdType = CONSOLE_TYPE_NMEA_ID;
}
// CSV
else if (in == CONSOLE_TYPE_CSV_C0) {
csv_last = 1; // Skip the "@"
// Start all at Zero
for (csv_count = 0; csv_count < CONSOLE_TYPE_CSV_LEN; csv_count++) {
csv_uint32[csv_count] = 0;
}
csv_count = 0;
cmdType = CONSOLE_TYPE_CSV_ID;
// console.log(LOG_DEBUG, F("CSV START last=%d, count=%d"), int(csv_last), int(csv_count));
}
// BINARY
else if (binEnable && (in == CONSOLE_TYPE_BIN_C0)) {
cmdType = CONSOLE_TYPE_BIN_ID;
binReceiveCount = 0;
binReceiveExpect = 0;
binReceiveCRC = 0; // Optional?
}
// Else assume standard ending in ";"
else {
cmdType = CONSOLE_TYPE_OTHER_ID;
}
}
// Keep cmdBuffer if not NMEA
if (
// Keep Other
cmdType == CONSOLE_TYPE_OTHER_ID // Keep for external use
|| cmdType == CONSOLE_TYPE_CSV_ID // Keep and process on the fly
|| cmdType == CONSOLE_TYPE_NMEA_ID // NMEA
|| cmdType == CONSOLE_TYPE_BIN_ID
) {
// TODO test out by one
if (cmdCount < (consoleMax - 1)) {
cmdBuffer[cmdCount] = in;
// XXX ',' should be #define in case we use : or tab or something
if (cmdType == CONSOLE_TYPE_CSV_ID && in == ',') {
processCsv();
}
cmdCount++;
cmdBuffer[cmdCount] = '\0';
}
}
}
// TEXT MODE - New Line - process - NOTE: This may get called twice (\r then \n)
// - Once leaving this, the only way for a new command to start
// is to set cmdCount = 0
else {
// Do nothing with this
if (cmdType == CONSOLE_TYPE_IGNORE_ID) {
}
// Blank everything
else if (cmdType == CONSOLE_TYPE_DESTROY_ID) {
cmdCount = 0;
cmd = '\0';
val = 0;
csv_last = 0;
csv_count = 0;
}
// Binary
else if (binEnable && (cmdType == CONSOLE_TYPE_BIN_ID)) {
if (cmdCount < 2) {
printf(F("# CONSOLE: Error, no size requests for binary data")); printNewLine();
printf(F("BINARY ERROR: No size")); printNewLine();
cmdCount = 0;
cmdType = 0;
}
else {
val = atol(&cmdBuffer[1]);
if (val >= binMax) {
printf(F("# CONSOLE: Request Binary larger than buffer")); printNewLine();
printf(F("BINARY ERROR: Too large")); printNewLine();
cmd = '\0';
cmdType = 0;
cmdCount = 0;
}
else {
printf(F("# CONSOLE: Request Binary size=%d"), binReceiveExpect); printNewLine();
printf(F("BINARY OK: Ready to send")); printNewLine();
binReceiveExpect = val;
binReceiveCount = 0;
cmdType = CONSOLE_TYPE_BINDATA_ID;
}
}
}
// Add optional ending, or even CRC
else if (cmdType == CONSOLE_TYPE_OTHER_ID) {
if (echo)
log(LOG_DEBUG, F("CONSOLE Receved: %s"), cmdBuffer);
// Check we have a buffe?
if (cmdCount >= (consoleMax - 1)) {
// printf(F("# CONSOLE overflow: cmd size - c=%d of %d\r\n"), cmdCount, consoleMax);
printf(F("# CONSOLE cmd overflow"));
printNewLine();
cmdCount = 0;
cmdType = CONSOLE_TYPE_IGNORE_ID;
}
else if (cmdBuffer[cmdCount - 1] != ';') {
printf(F("# CONSOLE: standard input must end in ; count=%d, last=%d"), cmdCount, (uint8_t)cmdBuffer[cmdCount =- 1]);
printNewLine();
cmdCount = 0;
cmdType = CONSOLE_TYPE_IGNORE_ID;
}
else {
cmd = cmdBuffer[0];
val = atol(&cmdBuffer[1]);
cmdType = CONSOLE_TYPE_IGNORE_ID;
}
}
else if ( cmdType == CONSOLE_TYPE_NMEA_ID ) {
// Ignore the NMEA - already processed
// TODO: Maybe mark the buffer as now a copy of the NMEA for passthrough?
}
else if ( cmdType == CONSOLE_TYPE_CSV_ID ) {
cmdCount++; // Spin on, so this will be like the "," where we add the null
processCsv();
cmd = CONSOLE_TYPE_CSV_C0;
cmdType = CONSOLE_TYPE_IGNORE_ID;
if (echo) {
printPrefix(LOG_DEBUG);
printf(F("CONSOLE Received (@): "));
for (i = 0; i < console.getCsvCount(); i++) {
printf(console.getCsvBuffer(i));
printf(",");
}
printNewLine();
}
}
}
}
bool WII5Sh3dConsole::available(){
return cmd != '\0';
}
// begin - using External Buffers
void WII5Sh3dConsole::begin(char* buf, uint16_t bufLen, char* cmdBuf, uint16_t cmdLen) {
// XXX XXX XXX
echo = true;
printBuffer = buf;
bufferMax = bufLen;
cmdBuffer = cmdBuf;
consoleMax = cmdLen;
cmdType = 0;
setDateTime();
}
// begin - Allocate the buffers and get things going
void WII5Sh3dConsole::begin(uint16_t bufLen, uint16_t cmdLen) {
if ( (bufLen + cmdLen) >= freeMemory() )
internalErrorNotEnoughMemory();
else {
printBuffer = (char*)malloc(bufLen);
if (printBuffer == NULL)
internalErrorNotEnoughMemory();
else
bufferMax = bufLen;
cmdBuffer = (char*)malloc(cmdLen);
if (cmdBuffer == NULL)
internalErrorNotEnoughMemory();
else
consoleMax = cmdLen;
cmdType = 0;
setDateTime();
}
}
void WII5Sh3dConsole::internalErrorNotEnoughMemory() {
SerialConsole.println(F("CONSOLE IntErr: failbuf"));
}
void WII5Sh3dConsole::internalErrorNoBufferStream() {
SerialConsole.println(F("CONSOLE IntErr: buf, stream"));
}
bool WII5Sh3dConsole::check() {
if (streamCount == 0) {
internalErrorNoBufferStream();
return false;
}
if (bufferMax == 0) {
internalErrorNoBufferStream();
return false;
}
return true;
}
void WII5Sh3dConsole::clearCommand() {
cmdCount = 0;
csv_count = 0;
csv_last = 0;
cmdType = 0;
cmd = '\0';
}
void WII5Sh3dConsole::clearCallback() {
callback_default = false;
callback = NULL;
}
void WII5Sh3dConsole::setCallbackFunction(CallbackFunction f) {
callback_default = false;
callback = f;
}
void WII5Sh3dConsole::setCallbackLevel(uint8_t l) {
callback_level = l;
}
uint8_t WII5Sh3dConsole::getCallbackLevel() {
return callback_level;
}
// Add a stream - currently very limited (0 NEITHER, 1 INPUT, 2 OUTPUT, 3 BOTH)
bool WII5Sh3dConsole::add(Stream *s, uint8_t direction) {
for(byte i = 0; i < CONSOLE_STREAMS; i++) {
if (streams[i] == s) {
return true;
}
else if (! streams[i]) {
streams[i] = s;
streamsDirection[i] = direction;
streamCount++;
return true;
}
}
// Internal Error !
return false;
}
bool WII5Sh3dConsole::remove(Stream *s) {
for(byte i = 0; i < CONSOLE_STREAMS; i++) {
if (streams[i] == s) {
streams[i] = NULL;
streamsDirection[i] = 0;
streamCount--;
return true;
}
}
return false;
}
void WII5Sh3dConsole::setLevel(byte l) {
level = l;
}
// Flush sending....no longer doing inputs
void WII5Sh3dConsole::flush() {
for(byte i = 0; i < CONSOLE_STREAMS; i++) {
if (streams[i]) {
streams[i]->flush();
}
}
}
void WII5Sh3dConsole::printNewLine() {
printf(F("\r\n"));
}
bool WII5Sh3dConsole::enableBinary() {
binEnable = true;
}
bool WII5Sh3dConsole::disableBinary() {
binEnable = false;
}
void WII5Sh3dConsole::setBinaryBuffer(char *buf, uint16_t len) {
binBuffer = buf;
binMax = len;
binEnable = true;
}
// Pretty Print Binary
#define PERLINE 10
void WII5Sh3dConsole::printBinary(char* buf, uint16_t len) {
printf(F("LEN = %d\r\n"), len);
uint16_t i = 0;
while (i < len) {
for (uint16_t x = 0; x < PERLINE; x++) {
if ( (i+x) < len) {
printf(F("0x%.2X "), (uint8_t)buf[i+x]);
}
else {
printf(F(" "), (int16_t)buf[i+x]);
}
}
printf(F(" |"));
for (uint16_t x = 0; x < PERLINE; x++) {
if (
((i+x) < len)
&& ((uint8_t)buf[i+x] >= 32)
&& ((uint8_t)buf[i+x] < 127)
) {
printBuffer[x] = buf[i+x];
}
else {
printBuffer[x] = ' ';
}
}
printBuffer[PERLINE] = '\0';
print(printBuffer);
printf(F("|\r\n"));
i = i + PERLINE;
}
printNewLine();
}
void WII5Sh3dConsole::printBits(void* buf, uint16_t len) {
for (uint16_t x = 0; x < len; x++) {
void* n = buf + (x/8);
printf(bitRead(*(uint8_t*)n, x % 8) ? "1" : "0");
}
printNewLine();
SerialConsole.print(F("BIN: "));
SerialConsole.print(*(uint16_t*)buf, BIN);
SerialConsole.println();
}
void WII5Sh3dConsole::setEcho(bool in) {
echo = in;
}
bool WII5Sh3dConsole::getEcho() {
return echo;
}
WII5Sh3dConsole console;